auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void doTest(StreamDefinition routerDefinition) throws InterruptedException { assertEquals(0, streamRepository.count()); streamDeployer.save(routerDefinition); deploy(routerDefinition); Thread.sleep(1000); assertEquals(1, streamRepository.count()); assertModuleRequest("router", false); final Module module = getModule("router", 0); MessageBus bus = module.getComponent(MessageBus.class); QueueChannel fooChannel = new QueueChannel(); QueueChannel barChannel = new QueueChannel(); queues.add(queueRoute); queues.add(queueFoo); bus.bindConsumer(queueFoo, fooChannel, Collections.singletonList(MediaType.ALL), true); queues.add(queueBar); bus.bindConsumer(queueBar, barChannel, Collections.singletonList(MediaType.ALL), true); DirectChannel testChannel = new DirectChannel(); bus.bindProducer(queueRoute, testChannel, true); testChannel.send(MessageBuilder.withPayload("a").build()); testChannel.send(MessageBuilder.withPayload("b").build()); final Message<?> fooMessage = fooChannel.receive(10000); final Message<?> barMessage = barChannel.receive(10000); assertEquals("a", fooMessage.getPayload()); assertEquals("b", barMessage.getPayload()); bus.unbindProducer(queueRoute, testChannel); bus.unbindConsumer(queueFoo, fooChannel); bus.unbindConsumer(queueBar, barChannel); }

Target:
private void doTest(StreamDefinition routerDefinition) throws InterruptedException { assertEquals(0, streamRepository.count()); streamDeployer.save(routerDefinition); deploy(routerDefinition); Thread.sleep(1000); assertEquals(1, streamRepository.count()); assertModuleRequest("router", false); final Module module = getModule("router", 0); MessageBus bus = module.getComponent(MessageBus.class); QueueChannel fooChannel = new QueueChannel(); QueueChannel barChannel = new QueueChannel(); bus.bindConsumer(queueFoo, fooChannel, Collections.singletonList(MediaType.ALL), true); bus.bindConsumer(queueBar, barChannel, Collections.singletonList(MediaType.ALL), true); DirectChannel testChannel = new DirectChannel(); bus.bindProducer(queueRoute, testChannel, true); testChannel.send(MessageBuilder.withPayload("a").build()); testChannel.send(MessageBuilder.withPayload("b").build()); final Message<?> fooMessage = fooChannel.receive(10000); final Message<?> barMessage = barChannel.receive(10000); assertEquals("a", fooMessage.getPayload()); assertEquals("b", barMessage.getPayload()); bus.unbindProducer(queueRoute, testChannel); bus.unbindConsumer(queueFoo, fooChannel); bus.unbindConsumer(queueBar, barChannel); }
Source:
private void optimizeConsecutiveExitWhen(ImExitwhen lookback, ImExitwhen element) { lookback.getCondition().replaceBy(JassIm.ImOperatorCall(WurstOperator.OR, JassIm.ImExprs(lookback.getCondition().copy(), element.getCondition().copy()))); element.replaceBy(JassIm.ImNull()); }

Target:
private void optimizeConsecutiveExitWhen(ImExitwhen lookback, ImExitwhen element) { element.getCondition().setParent(null); lookback.setCondition(JassIm.ImOperatorCall(WurstOperator.OR, JassIm.ImExprs(lookback.getCondition().copy(), element.getCondition()))); element.replaceBy(JassIm.ImNull()); totalRewrites++; }
Source:
private void postConstruct() { classToMapperMap.put(EventMessageDataResponseDto.class, this.managementMapper); classToMapperMap.put(MeterReadsResponseDto.class, this.monitoringMapper); classToMapperMap.put(MeterReadsGasResponseDto.class, this.monitoringMapper); classToMapperMap.put(ActionResponseDto.class, this.commonMapper); classToMapperMap.put(FaultResponseDto.class, this.commonMapper); classToMapperMap.put(AlarmRegisterResponseDto.class, this.commonMapper); classToMapperMap.put(AdministrativeStatusTypeResponseDto.class, this.configurationMapper); classToMapperMap.put(PeriodicMeterReadsResponseDto.class, this.monitoringMapper); classToMapperMap.put(PeriodicMeterReadGasResponseDto.class, this.monitoringMapper); classToMapperMap.put(GetAttributeValuesResponseDto.class, this.configurationMapper); classToMapperMap.put(FirmwareVersionResponseDto.class, this.configurationMapper); classToMapperMap.put(UpdateFirmwareResponseDto.class, this.configurationMapper); classToMapperMap.put(AssociationLnObjectsResponseDto.class, this.commonMapper); classToMapperMap.put(GetConfigurationObjectResponseDto.class, this.configurationMapper); classToMapperMap.put(ProfileGenericDataResponseDto.class, this.monitoringMapper); }

Target:
private void postConstruct() { classToMapperMap.put(EventMessageDataResponseDto.class, this.managementMapper); classToMapperMap.put(MeterReadsResponseDto.class, this.monitoringMapper); classToMapperMap.put(MeterReadsGasResponseDto.class, this.monitoringMapper); classToMapperMap.put(ActionResponseDto.class, this.commonMapper); classToMapperMap.put(FaultResponseDto.class, this.commonMapper); classToMapperMap.put(AlarmRegisterResponseDto.class, this.commonMapper); classToMapperMap.put(AdministrativeStatusTypeResponseDto.class, this.configurationMapper); classToMapperMap.put(PeriodicMeterReadsResponseDto.class, this.monitoringMapper); classToMapperMap.put(PeriodicMeterReadGasResponseDto.class, this.monitoringMapper); classToMapperMap.put(GetAttributeValuesResponseDto.class, this.configurationMapper); classToMapperMap.put(FirmwareVersionResponseDto.class, this.configurationMapper); classToMapperMap.put(UpdateFirmwareResponseDto.class, this.configurationMapper); classToMapperMap.put(AssociationLnObjectsResponseDto.class, this.commonMapper); classToMapperMap.put(ProfileGenericDataResponseDto.class, this.monitoringMapper); }
Source:
private void putValuesToQuestion(final Question question, final QuestionViewHolder holder) { holder.question.setText(question.getName()); holder.value.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { mOnInteractionListener.onQuestionAnswered(question, holder.value.getText().toString()); } @Override public void afterTextChanged(Editable editable) { } }); mOnInteractionListener.onQuestionAnswered(question, holder.value.getText().toString().isEmpty() ? holder.value.getHint().toString() : holder.value.getText().toString()); }

Target:
private void putValuesToQuestion(final Question question, final QuestionViewHolder holder) { holder.question.setText(question.getName()); holder.value.setHint(mDefValue); holder.value.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { mOnInteractionListener.onQuestionAnswered(question, holder.value.getText().toString()); } @Override public void afterTextChanged(Editable editable) { } }); mOnInteractionListener.onQuestionAnswered(question, holder.value.getText().toString()); }
Source:
private void serialize(final String taskUrl) { new Job(LABEL_SERIALIZE_JOB_NAME) { @Override protected IStatus run(IProgressMonitor monitor) { try { String repositoryUrl = TasksUiPlugin.getRepositoryManager() .getConnectorForRepositoryTaskUrl(taskUrl) .getRepositoryUrlFromTaskUrl(taskUrl); repositoryUrl = URLEncoder.encode(repositoryUrl); File file = new File(getSaveFileName(), repositoryUrl); file.mkdirs(); file = new File(file, URLEncoder.encode(taskUrl) + ".json"); OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file)); gson.toJson(new TempMapping(taskUrl, taskReviewsMap.get(taskUrl)), writer); writer.close(); } catch (IOException e) { e.printStackTrace(); } return Status.OK_STATUS; } }.schedule(); }

Target:
private void serialize(final String taskUrl) { new Job(LABEL_SERIALIZE_JOB_NAME) { @Override protected IStatus run(IProgressMonitor monitor) { String repositoryUrl = repositoryManager.getConnectorForRepositoryTaskUrl(taskUrl) .getRepositoryUrlFromTaskUrl(taskUrl); repositoryUrl = URLEncoder.encode(repositoryUrl); File file = new File(getSaveFileName(), repositoryUrl); file.mkdirs(); file = new File(file, URLEncoder.encode(taskUrl) + ".json"); try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file))) { gson.toJson(new SerializationMapping(taskUrl, taskReviewsMap.get(taskUrl)), writer); } catch (IOException e) { e.printStackTrace(); } return Status.OK_STATUS; } }.schedule(); }
Source:
public File getUploadedImage() { waitForElementByElement(thumbnailImage); File uploadedImageFile = new File(PageContent.resourcesPath + "shouldBeDeleted.png"); try { URL url = new URL(thumbnailImage.getAttribute("src")); BufferedImage bufImgOne = ImageIO.read(url); ImageIO.write(bufImgOne, "png", uploadedImageFile); } catch (IOException e) { e.printStackTrace(); } return uploadedImageFile; }

Target:
public File getUploadedImage() { waitForElementByElement(thumbnailImage); File uploadedImageFile = new File(PageContent.resourcesPath + "shouldBeDeleted.png"); try { URL url = new URL(thumbnailImage.getAttribute("src")); BufferedImage bufImgOne = ImageIO.read(url); ImageIO.write(bufImgOne, "png", uploadedImageFile); } catch (IOException e) { throw new RuntimeException(); } return uploadedImageFile; }
Source:
private List<Key> optionsOfQuestion(DatastoreService ds, Long qId) { final Query optq = new Query("QuestionOptions").setFilter(new Query.FilterPredicate("questionId", FilterOperator.EQUAL, qId)); final PreparedQuery pqopt = ds.prepare(optq); List<Key> result = new ArrayList<>(); for (Entity qa : pqopt.asIterable(FetchOptions.Builder.withChunkSize(500))) { result.add(qa.getKey()); } return result; }

Target:
private List<Key> optionsOfQuestion(DatastoreService ds, Long qId) { final Query optq = new Query("QuestionOptions") .setFilter(new Query.FilterPredicate("questionId", FilterOperator.EQUAL, qId)) .setKeysOnly(); final PreparedQuery pqopt = ds.prepare(optq); List<Key> result = new ArrayList<>(); for (Entity qa : pqopt.asIterable(FetchOptions.Builder.withChunkSize(500))) { result.add(qa.getKey()); } return result; }
Source:
private String getUpToDateRuleElement() { final String template = "<rule name=\"%s\"\n" + " language=\"%s\"\n" + " message=\"%s\"\n" + " class=\"net.sourceforge.pmd.lang.rule.XPathRule\"\n" + " <!-- externalInfoUrl=\"%s\"--> >\n" + " <description>\n" + "%s\n" + " </description>\n" + " <priority>%d</priority>\n" + " <properties>\n" + " <property name=\"xpath\">\n" + " <value>\n" + "<![CDATA[\n" + "%s" + "]]>\n" + " </value>\n" + " </property>\n" + " </properties>\n" + " <!--<example><![CDATA[]]></example>-->\n" + "</rule>"; return String.format(template, nameField.getText(), languageChoiceBox.getSelectionModel().getSelectedItem().getTerseName(), messageField.getText(), "TODO", descriptionField.getText(), (int) prioritySlider.getValue(), xpathExpression.getValue() ); }

Target:
private String getUpToDateRuleElement() { final String template = "<rule name=\"%s\"\n" + " language=\"%s\"\n" + " message=\"%s\"\n" + " class=\"net.sourceforge.pmd.lang.rule.XPathRule\"\n" + " <!-- externalInfoUrl=\"%s\"--> >\n" + " <description>\n" + "%s\n" + " </description>\n" + " <priority>%d</priority>\n" + " <properties>\n" + " <property name=\"xpath\">\n" + " <value>\n" + "<![CDATA[\n" + "%s\n" + "]]>\n" + " </value>\n" + " </property>\n" + " </properties>\n" + " <!--<example><![CDATA[]]></example>-->\n" + "</rule>"; return String.format(template, nameField.getText(), languageChoiceBox.getSelectionModel().getSelectedItem().getTerseName(), messageField.getText(), "TODO", descriptionField.getText(), (int) prioritySlider.getValue(), xpathExpression.getValue() ); }
Source:
public void start(Map<String, String> props) { try { HdfsSinkConnectorConfig connectorConfig = new HdfsSinkConnectorConfig(props); boolean hiveIntegration = connectorConfig.getBoolean(HdfsSinkConnectorConfig.HIVE_INTEGRATION_CONFIG); if (hiveIntegration) { Compatibility compatibility = SchemaUtils.getCompatibility( connectorConfig.getString(HdfsSinkConnectorConfig.SCHEMA_COMPATIBILITY_CONFIG)); if (compatibility == Compatibility.NONE) { throw new ConfigException("Hive Integration requires schema compatibility to be BACKWARD, FORWARD or FULL"); } } int schemaCacheSize = connectorConfig.getInt(HdfsSinkConnectorConfig.SCHEMA_CACHE_SIZE_CONFIG); avroData = new AvroData(schemaCacheSize); hdfsWriter = new DataWriter(connectorConfig, context, avroData); Set<TopicPartition> assignment = context.assignment(); recover(assignment); if (hiveIntegration) { syncWithHive(); } } catch (ConfigException e) { throw new ConnectException("Couldn't start HdfsSinkConnector due to configuration error.", e); } catch (ConnectException e) { log.info("Couldn't start HdfsSinkConnector due to {}", e.getMessage()); log.info("Shutting down HdfsSinkConnector."); if (hdfsWriter != null) { hdfsWriter.close(); } } }

Target:
public void start(Map<String, String> props) { try { HdfsSinkConnectorConfig connectorConfig = new HdfsSinkConnectorConfig(props); boolean hiveIntegration = connectorConfig.getBoolean(HdfsSinkConnectorConfig.HIVE_INTEGRATION_CONFIG); if (hiveIntegration) { Compatibility compatibility = SchemaUtils.getCompatibility( connectorConfig.getString(HdfsSinkConnectorConfig.SCHEMA_COMPATIBILITY_CONFIG)); if (compatibility == Compatibility.NONE) { throw new ConfigException("Hive Integration requires schema compatibility to be BACKWARD, FORWARD or FULL"); } } int schemaCacheSize = connectorConfig.getInt(HdfsSinkConnectorConfig.SCHEMA_CACHE_SIZE_CONFIG); avroData = new AvroData(schemaCacheSize); hdfsWriter = new DataWriter(connectorConfig, context, avroData); Set<TopicPartition> assignment = context.assignment(); recover(assignment); if (hiveIntegration) { syncWithHive(); } } catch (ConfigException e) { throw new ConnectException("Couldn't start HdfsSinkConnector due to configuration error.", e); } catch (ConnectException e) { log.info("Couldn't start HdfsSinkConnector:", e); log.info("Shutting down HdfsSinkConnector."); if (hdfsWriter != null) { hdfsWriter.close(); } } }
Source:
private JiraSession createSession() { if (StringUtils.isEmpty(credentialsId)) { LOGGER.warning("Jira session could not be created. No credentials supplied."); return null; } final URI uri; try { uri = url.toURI(); } catch (URISyntaxException e) { LOGGER.warning("convert URL to URI error: " + e.getMessage()); throw new RuntimeException("failed to create JiraSession due to convert URI error"); } LOGGER.fine("creating Jira Session: " + uri); StandardUsernamePasswordCredentials credentials = CredentialsHelper.lookupSystemCredentials(credentialsId, url); String userName = credentials.getUsername(); Secret password = credentials.getPassword(); final ExtendedJiraRestClient jiraRestClient = new ExtendedAsynchronousJiraRestClientFactory() .create(uri, new BasicHttpAuthenticationHandler( userName, password.getPlainText()),getHttpClientOptions()); return new JiraSession(this, new JiraRestService(uri, jiraRestClient, userName, password.getPlainText(), readTimeout, sendAssigneeAsName)); }

Target:
private JiraSession createSession() { if (StringUtils.isEmpty(credentialsId)) { LOGGER.warning("Jira session could not be created. No credentials supplied."); return null; } final URI uri; try { uri = url.toURI(); } catch (URISyntaxException e) { LOGGER.warning("convert URL to URI error: " + e.getMessage()); throw new RuntimeException("failed to create JiraSession due to convert URI error"); } LOGGER.fine("creating Jira Session: " + uri); StandardUsernamePasswordCredentials credentials = CredentialsHelper.lookupSystemCredentials(credentialsId, url); String userName = credentials.getUsername(); Secret password = credentials.getPassword(); final ExtendedJiraRestClient jiraRestClient = new ExtendedAsynchronousJiraRestClientFactory() .create(uri, new BasicHttpAuthenticationHandler( userName, password.getPlainText()),getHttpClientOptions()); return new JiraSession(this, new JiraRestService(uri, jiraRestClient, userName, password.getPlainText(), readTimeout)); }
Source:
public void afterPropertiesSet() { InvalidationListener modDirectoryChangedListener = observable -> { modsDirectory = preferencesService.getPreferences().getForgedAlliance().getModsDirectory(); if (modsDirectory != null) { installedModVersions.clear(); onModDirectoryReady(); } }; taskService.submitTask(new CompletableTask<Void>(Priority.LOW) { @Override protected Void call() throws Exception { updateTitle(i18n.get("modVault.loadingMaps")); modDirectoryChangedListener.invalidated(preferencesService.getPreferences().getForgedAlliance().modsDirectoryProperty()); return null; } }); JavaFxUtil.addListener(preferencesService.getPreferences().getForgedAlliance().modsDirectoryProperty(), modDirectoryChangedListener); }

Target:
public void afterPropertiesSet() { InvalidationListener modDirectoryChangedListener = observable -> { modsDirectory = preferencesService.getPreferences().getForgedAlliance().getModsDirectory(); if (modsDirectory != null) { installedModVersions.clear(); onModDirectoryReady(); } }; taskService.submitTask(new CompletableTask<Void>(Priority.LOW) { @Override protected Void call() throws Exception { updateTitle(i18n.get("modVault.loadingMods")); modDirectoryChangedListener.invalidated(preferencesService.getPreferences().getForgedAlliance().modsDirectoryProperty()); return null; } }); JavaFxUtil.addListener(preferencesService.getPreferences().getForgedAlliance().modsDirectoryProperty(), modDirectoryChangedListener); }
Source:
private void fillInBases(final SAMRecord rec) { final int length = getReadLengthFromCigar(rec); final byte[] bases = SequenceUtil.getRandomBases(random, length); rec.setReadBases(bases); }

Target:
private void fillInBases(final SAMRecord rec) { rec.setReadBases(SequenceUtil.getRandomBases(random, getReadLengthFromCigar(rec))); }
Source:
private static boolean canConvert(ParameterDefinition def, ParameterValue v) { return def instanceof SimpleParameterDefinition && !(def instanceof StringParameterDefinition) && v instanceof StringParameterValue; }

Target:
private static boolean canConvert(ParameterDefinition def, ParameterValue v) { return def instanceof SimpleParameterDefinition && !(def instanceof StringParameterDefinition) && v.getClass().equals(StringParameterValue.class); }
Source:
public static CharSequence getFormattedString(@NonNull String pattern, @NonNull Map<String, ? extends CharSequence> keyValMap) { Phrase resourceString = Phrase.from(pattern); Set<String> keys = keyValMap.keySet(); for (String key : keys) { final CharSequence val = keyValMap.get(key); if (val == null) { logger.warn(String.format("Value for key %s is null", key)); resourceString.putOptional(key, ""); } else { resourceString.putOptional(key, val); } } return resourceString.format(); }

Target:
public static CharSequence getFormattedString(@NonNull String pattern, @NonNull Map<String, ? extends CharSequence> keyValMap) { Phrase resourceString = Phrase.from(pattern); Set<String> keys = keyValMap.keySet(); for (String key : keys) { final CharSequence val = keyValMap.get(key); if (val == null) { logger.warn(String.format("Value for key %s is null", key)); resourceString.put(key, ""); } else { resourceString.put(key, val); } } return resourceString.format(); }
Source:
public PartitionMetadata withColumnStatistics(Map<String, HiveColumnStatistics> columnStatistics) { requireNonNull(columnStatistics, "columnStatistics is null"); return new PartitionMetadata(columns, parameters, storageFormat, bucketProperty, serdeParameters, externalLocation, columnStatistics); }

Target:
public PartitionMetadata withColumnStatistics(Map<String, HiveColumnStatistics> columnStatistics) { return new PartitionMetadata(columns, parameters, storageFormat, bucketProperty, serdeParameters, externalLocation, columnStatistics); }
Source:
protected Iterable<String> getChoices(CommandSource source) { return Arrays.stream(this.type.getEnumConstants()) .map(input -> input == null ? null : input.name()) .collect(Collectors.toList()); }

Target:
protected Iterable<String> getChoices(CommandSource source) { return this.values.keySet(); }
Source:
public void InteractiveMaps_033_PalantirSetHugeZoomVerifyError() { InteractiveMapPageObject selectedMap = new InteractiveMapPageObject(driver); selectedMap.openMap(wikiURL, 3); selectedMap.verifyMapOpened(); PalantirComponentObject poi = new PalantirComponentObject(driver); PalantirContent handle = new PalantirContent(); handle = poi.setAndVerifyPlayerPosition(-40, -10, 3000, true); poi.verifyWrongZoomLevel(handle.success, handle.responseCode, handle.message); poi.verifyPoiNotAppearOnMap(); }

Target:
public void InteractiveMaps_033_PalantirSetHugeZoomVerifyError() { InteractiveMapsPageObject specialMap = new InteractiveMapsPageObject(driver); InteractiveMapPageObject selectedMap = specialMap.openMap(wikiURL, PalantirContent.PALANTIR_MAP); selectedMap.verifyMapOpened(); PalantirComponentObject poi = new PalantirComponentObject(driver); PalantirContent handle = poi.setAndVerifyPlayerPosition(-40, -10, 3000, true); poi.verifyWrongZoomLevel(handle); poi.verifyPoiNotAppearOnMap(); }
Source:
public void removePlayer(ProxiedPlayer player) { Preconditions.checkNotNull( player, "player" ); players.remove( player ); if ( player.isConnected() && visible ) { player.unsafe().sendPacket( removePacket() ); } }

Target:
public void removePlayer(ProxiedPlayer player) { Preconditions.checkNotNull( player, "player" ); players.remove( player ); if ( player.isConnected() && visible ) { sendPacket( player, removePacket ); } }
Source:
public static Set<GeneNumber> getGeneNumberListWithLevels(Set<Gene> genes, Set<LevelOfEvidence> levels) { if (levels == null) { return getGeneNumberList(genes); } Map<Gene, Set<Evidence>> evidences = EvidenceUtils.getEvidenceByGenes(genes); Set<GeneNumber> geneNumbers = new HashSet<>(); Iterator it = evidences.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Gene, Set<Evidence>> pair = (Map.Entry) it.next(); GeneNumber geneNumber = new GeneNumber(); geneNumber.setGene(pair.getKey()); LevelOfEvidence highestSensitiveLevel = LevelUtils.getHighestLevelFromEvidenceByLevels(pair.getValue(), new HashSet<>(CollectionUtils.intersection(levels, LevelUtils.getPublicSensitiveLevels()))); LevelOfEvidence highestResistanceLevel = LevelUtils.getHighestLevelFromEvidenceByLevels(pair.getValue(), new HashSet<>(CollectionUtils.intersection(levels, LevelUtils.getPublicResistanceLevels()))); geneNumber.setHighestSensitiveLevel(highestSensitiveLevel != null ? highestSensitiveLevel.name() : null); geneNumber.setHighestResistenceLevel(highestResistanceLevel != null ? highestSensitiveLevel.name() : null); Set<Alteration> alterations = AlterationUtils.getAllAlterations(pair.getKey()); List<Alteration> excludeVUS = AlterationUtils.excludeVUS(pair.getKey(), new ArrayList<>(alterations)); geneNumber.setAlteration(excludeVUS.size()); geneNumbers.add(geneNumber); } return geneNumbers; }

Target:
public static Set<GeneNumber> getGeneNumberListWithLevels(Set<Gene> genes, Set<LevelOfEvidence> levels) { if (levels == null) { return getGeneNumberList(genes); } Map<Gene, Set<Evidence>> evidences = EvidenceUtils.getEvidenceByGenes(genes); Set<GeneNumber> geneNumbers = new HashSet<>(); Iterator it = evidences.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Gene, Set<Evidence>> pair = (Map.Entry) it.next(); GeneNumber geneNumber = new GeneNumber(); geneNumber.setGene(pair.getKey()); LevelOfEvidence highestSensitiveLevel = LevelUtils.getHighestLevelFromEvidenceByLevels(pair.getValue(), new HashSet<>(CollectionUtils.intersection(levels, LevelUtils.getPublicSensitiveLevels()))); LevelOfEvidence highestResistanceLevel = LevelUtils.getHighestLevelFromEvidenceByLevels(pair.getValue(), new HashSet<>(CollectionUtils.intersection(levels, LevelUtils.getPublicResistanceLevels()))); geneNumber.setHighestSensitiveLevel(highestSensitiveLevel != null ? highestSensitiveLevel.name() : null); geneNumber.setHighestResistenceLevel(highestResistanceLevel != null ? highestResistanceLevel.name() : null); Set<Alteration> alterations = AlterationUtils.getAllAlterations(pair.getKey()); List<Alteration> excludeVUS = AlterationUtils.excludeVUS(pair.getKey(), new ArrayList<>(alterations)); geneNumber.setAlteration(excludeVUS.size()); geneNumbers.add(geneNumber); } return geneNumbers; }
Source:
private boolean isVisibilitySetToAnonymousToRecipientVisibleToInstructors(FeedbackQuestionAttributes question) { boolean responsesVisibleOnlyToRecipientAndInstructors; if (question.questionType.equals(FeedbackQuestionType.CONTRIB)) { responsesVisibleOnlyToRecipientAndInstructors = question.showResponsesTo.size() == 4 && question.showResponsesTo.contains(FeedbackParticipantType.RECEIVER) && question.showResponsesTo.contains(FeedbackParticipantType.OWN_TEAM_MEMBERS) && question.showResponsesTo.contains(FeedbackParticipantType.RECEIVER_TEAM_MEMBERS) && question.showResponsesTo.contains(FeedbackParticipantType.INSTRUCTORS); } else { responsesVisibleOnlyToRecipientAndInstructors = question.showResponsesTo.size() == 2 && question.showResponsesTo.contains(FeedbackParticipantType.RECEIVER) && question.showResponsesTo.contains(FeedbackParticipantType.INSTRUCTORS); } boolean giverNameVisibleOnlyToInstructors = question.showGiverNameTo.size() == 1 && question.showGiverNameTo.contains(FeedbackParticipantType.INSTRUCTORS); return responsesVisibleOnlyToRecipientAndInstructors && giverNameVisibleOnlyToInstructors; }

Target:
private boolean isVisibilitySetToAnonymousToRecipientVisibleToInstructors(FeedbackQuestionAttributes question) { boolean responsesVisibleOnlyToRecipientAndInstructors = question.showResponsesTo.size() == 2 && question.showResponsesTo.contains(FeedbackParticipantType.INSTRUCTORS) && question.showResponsesTo.contains(FeedbackParticipantType.RECEIVER); boolean giverNameVisibleOnlyToInstructors = question.showGiverNameTo.size() == 1 && question.showGiverNameTo.contains(FeedbackParticipantType.INSTRUCTORS); return responsesVisibleOnlyToRecipientAndInstructors && giverNameVisibleOnlyToInstructors; }
Source:
public boolean shouldBeAnEclipseProject(IContainer container, IProgressMonitor monitor) { return container.getFile(new Path("feature.xml")).exists(); }

Target:
public boolean shouldBeAnEclipseProject(IContainer container, IProgressMonitor monitor) { return container.getFile(new Path(ICoreConstants.FEATURE_FILENAME_DESCRIPTOR)).exists(); }
Source:
public RemoteReplicaInfo(ReplicaId replicaId, Store localStore, FindToken token, long tokenPersistIntervalInMs) { this.replicaId = replicaId; this.currentToken = token; if (tokenToPersist == null) { this.tokenToPersist = token; timeTokenSetInMs = SystemTime.getInstance().milliseconds(); } this.tokenPersistIntervalInMs = tokenPersistIntervalInMs; this.totalBytesReadFromLocalStore = new Long(0); this.localStore = localStore; }

Target:
public RemoteReplicaInfo(ReplicaId replicaId, Store localStore, FindToken token, long tokenPersistIntervalInMs) { this.replicaId = replicaId; this.currentToken = token; if (tokenToPersist == null) { this.tokenToPersist = token; timeTokenSetInMs = SystemTime.getInstance().milliseconds(); } this.tokenPersistIntervalInMs = tokenPersistIntervalInMs; this.totalBytesReadFromLocalStore = 0; this.localStore = localStore; }
Source:
protected List<Edge> getEdgeList(DDiagram representation) { List<Edge> edges = new ArrayList<Edge>(); TreeIterator<EObject> eAllContents = representation.eAllContents(); while (eAllContents.hasNext()) { EObject element = eAllContents.next(); if (element instanceof Edge) { edges.add((Edge) element); eAllContents.prune(); } } return edges; }

Target:
protected List<Edge> getEdgeList(DDiagram representation) { List<Edge> edges = new ArrayList<Edge>(); DiagramCreationUtil diagramCreationUtil = new DiagramCreationUtil(representation); if (diagramCreationUtil.findAssociatedGMFDiagram()) { Diagram gmfDiagram = diagramCreationUtil.getAssociatedGMFDiagram(); edges = gmfDiagram.getEdges(); } return edges; }
Source:
public RuleClass build(RuleClass.Builder builder, RuleDefinitionEnvironment env) { return builder .requiresConfigurationFragments(CppConfiguration.class) .add(attr("compile_only_deps", LABEL_LIST) .allowedRuleClasses(BazelCppRuleClasses.DEPS_ALLOWED_RULES) .allowedFileTypes(CppFileTypes.LINKER_SCRIPT) .skipAnalysisTimeFileTypeCheck()) .add(attr("alwayslink", BOOLEAN)) .override(attr("linkstatic", BOOLEAN).value(false)) .build(); }

Target:
public RuleClass build(RuleClass.Builder builder, RuleDefinitionEnvironment env) { return builder .requiresConfigurationFragments(CppConfiguration.class) .add(attr("compile_only_deps", LABEL_LIST) .allowedFileTypes() .allowedRuleClasses(BazelCppRuleClasses.DEPS_ALLOWED_RULES) .skipAnalysisTimeFileTypeCheck() .mandatoryProviders(SkylarkProviderIdentifier.forKey(CcInfo.PROVIDER.getKey()))) .add(attr("alwayslink", BOOLEAN)) .override(attr("linkstatic", BOOLEAN).value(false)) .build(); }
Source:
private AsyncTaskManager() { _tasks = new ConcurrentHashMap<Guid, SPMAsyncTask>(); SchedulerUtil scheduler = SchedulerUtilQuartzImpl.getInstance(); scheduler.scheduleAFixedDelayJob(this, "_timer_Elapsed", new Class[] {}, new Object[] {}, Config.<Integer> GetValue(ConfigValues.AsyncTaskPollingRate), Config.<Integer> GetValue(ConfigValues.AsyncTaskPollingRate), TimeUnit.SECONDS); scheduler.scheduleAFixedDelayJob(this, "_cacheTimer_Elapsed", new Class[] {}, new Object[] {}, Config.<Integer> GetValue(ConfigValues.AsyncTaskStatusCacheRefreshRateInSeconds), Config.<Integer> GetValue(ConfigValues.AsyncTaskStatusCacheRefreshRateInSeconds), TimeUnit.SECONDS); _cacheTimeInMinutes = Config.<Integer> GetValue(ConfigValues.AsyncTaskStatusCachingTimeInMinutes); tasksInDbAfterRestart = new ConcurrentHashMap<Guid, List<AsyncTasks>>(); for (AsyncTasks task: DbFacade.getInstance().getAsyncTaskDao().getAll()) { if (task.getVdsmTaskId().equals(NGuid.Empty)) { failTaskWithoutVdsmId(task); continue; } tasksInDbAfterRestart.putIfAbsent(task.getStoragePoolId(), new ArrayList<AsyncTasks>()); List<AsyncTasks> tasksPerStoragePool = tasksInDbAfterRestart.get(task.getStoragePoolId()); tasksInDbAfterRestart.put(task.getStoragePoolId(), tasksPerStoragePool); tasksPerStoragePool.add(task); } }

Target:
private AsyncTaskManager() { _tasks = new ConcurrentHashMap<Guid, SPMAsyncTask>(); SchedulerUtil scheduler = SchedulerUtilQuartzImpl.getInstance(); scheduler.scheduleAFixedDelayJob(this, "_timer_Elapsed", new Class[] {}, new Object[] {}, Config.<Integer> GetValue(ConfigValues.AsyncTaskPollingRate), Config.<Integer> GetValue(ConfigValues.AsyncTaskPollingRate), TimeUnit.SECONDS); scheduler.scheduleAFixedDelayJob(this, "_cacheTimer_Elapsed", new Class[] {}, new Object[] {}, Config.<Integer> GetValue(ConfigValues.AsyncTaskStatusCacheRefreshRateInSeconds), Config.<Integer> GetValue(ConfigValues.AsyncTaskStatusCacheRefreshRateInSeconds), TimeUnit.SECONDS); _cacheTimeInMinutes = Config.<Integer> GetValue(ConfigValues.AsyncTaskStatusCachingTimeInMinutes); tasksInDbAfterRestart = new ConcurrentHashMap<Guid, List<AsyncTasks>>(); for (AsyncTasks task: DbFacade.getInstance().getAsyncTaskDao().getAll()) { if (NGuid.Empty.equals(task.getVdsmTaskId())) { log.infoFormat("Failing task {0} as it does not have a vdsm id.", task.getTaskId()); failTaskWithoutVdsmId(task); continue; } tasksInDbAfterRestart.putIfAbsent(task.getStoragePoolId(), new ArrayList<AsyncTasks>()); List<AsyncTasks> tasksPerStoragePool = tasksInDbAfterRestart.get(task.getStoragePoolId()); tasksInDbAfterRestart.put(task.getStoragePoolId(), tasksPerStoragePool); tasksPerStoragePool.add(task); } }
Source:
public static boolean isSchedulable(JobCurator jobCurator, JobStatus status) { Class<? extends KingpinJob> jobClass; try { jobClass = (Class<? extends KingpinJob>) Class.forName(status.getJobClass()); } catch (ClassNotFoundException cnfe) { log.warn("Could not schedule job of class {}. The class was not found.", status.getJobClass()); return false; } JobStatus nextJob = jobCurator.getNextByClassAndTarget(status.getTargetId(), HypervisorUpdateJob.class); return nextJob != null && nextJob.getId().equals(status.getId()); }

Target:
public static boolean isSchedulable(JobCurator jobCurator, JobStatus status) { Class<? extends KingpinJob> jobClass; try { jobClass = (Class<? extends KingpinJob>) Class.forName(status.getJobClass()); } catch (ClassNotFoundException cnfe) { log.warn("Could not schedule job of class {}. The class was not found.", status.getJobClass()); return false; } long running = jobCurator.findNumRunningByClassAndTarget( status.getTargetId(), jobClass); return running == 0; }
Source:
public void enableVersioning(EnableVersioningArgs args) throws ErrorResponseException, IllegalArgumentException, InsufficientDataException, InternalException, InvalidBucketNameException, InvalidKeyException, InvalidResponseException, IOException, NoSuchAlgorithmException, XmlParserException { Map<String, String> queryParamMap = new HashMap<>(); queryParamMap.put("versioning", ""); String config = "<VersioningConfiguration xmlns=\"<LINK_0>\">" + "<Status>Enabled</Status></VersioningConfiguration>"; Response response = executePut(args.bucket(), null, null, queryParamMap, config, 0); response.body().close(); }

Target:
public void enableVersioning(EnableVersioningArgs args) throws ErrorResponseException, IllegalArgumentException, InsufficientDataException, InternalException, InvalidBucketNameException, InvalidKeyException, InvalidResponseException, IOException, NoSuchAlgorithmException, XmlParserException { if (args == null) { throw new IllegalArgumentException("null arguments"); } Map<String, String> queryParamMap = new HashMap<>(); queryParamMap.put("versioning", ""); String config = "<VersioningConfiguration xmlns=\"<LINK_0>\">" + "<Status>Enabled</Status></VersioningConfiguration>"; Response response = executePut(args.bucket(), null, null, queryParamMap, config, 0); response.body().close(); }
Source:
private AutoIngestCaseManager() throws AutoIngestCaseManagerException { try { init(); } catch (AutoIngestCaseManager.AutoIngestCaseManagerException ex) { Logger.getLogger(AutoIngestCaseManager.class.getName()).log(Level.SEVERE, null, ex); throw ex; } }

Target:
private AutoIngestCaseManager() throws AutoIngestCaseManagerException { try { coordinationService = CoordinationService.getInstance(); } catch (CoordinationServiceException ex) { throw new AutoIngestCaseManager.AutoIngestCaseManagerException("Failed to get the coordination service.", ex); } }
Source:
private void setPartitionResult(int partition, Object result) { assert result != null : "null result"; boolean success = partitionResults.compareAndSet(partition, null, result); assert success : "two results for same partition: old=" + partitionResults.get(partition) + ", new=" + result; }

Target:
private void setPartitionResult(int partition, Object result) { if (result == null) { result = NULL_RESULT; } boolean success = partitionResults.compareAndSet(partition, null, result); assert success : "two results for same partition: old=" + partitionResults.get(partition) + ", new=" + result; }
Source:
public void onEventMainThread(DiscussionThreadPostedEvent event) { if (!isFollowingTopics() && !isAllTopics() && event.getDiscussionThread().getTopicId().equalsIgnoreCase(discussionTopic.getIdentifier())) { int i = 0; for (; i < discussionPostsAdapter.getCount(); ++i) { if (!discussionPostsAdapter.getItem(i).isPinned()) { break; } } discussionPostsAdapter.insert(event.getDiscussionThread(), i); } }

Target:
public void onEventMainThread(DiscussionThreadPostedEvent event) { if (!isFollowingTopics() && !isAllTopics() && discussionTopic.containsThread(event.getDiscussionThread())) { int i = 0; for (; i < discussionPostsAdapter.getCount(); ++i) { if (!discussionPostsAdapter.getItem(i).isPinned()) { break; } } discussionPostsAdapter.insert(event.getDiscussionThread(), i); } }
Source:
public void setCancelIdleInterval(long cancelIdleInterval) { this.cancelIdleInterval = cancelIdleInterval; }

Target:
public void setCancelIdleInterval(long cancelIdleInterval) { this.cancelIdleInterval = cancelIdleInterval * 1000; }
Source:
protected void populateColumnSchema(ArrayList<ColumnInfo> columns) { super.populateColumnSchema(columns); columns.add(new VoltTable.ColumnInfo("RSS", VoltType.INTEGER)); columns.add(new VoltTable.ColumnInfo("JAVAUSED", VoltType.INTEGER)); columns.add(new VoltTable.ColumnInfo("JAVAUNUSED", VoltType.INTEGER)); columns.add(new VoltTable.ColumnInfo("TUPLEDATA", VoltType.BIGINT)); columns.add(new VoltTable.ColumnInfo("TUPLEALLOCATED", VoltType.BIGINT)); columns.add(new VoltTable.ColumnInfo("INDEXMEMORY", VoltType.INTEGER)); columns.add(new VoltTable.ColumnInfo("STRINGMEMORY", VoltType.BIGINT)); columns.add(new VoltTable.ColumnInfo("TUPLECOUNT", VoltType.BIGINT)); columns.add(new VoltTable.ColumnInfo("POOLEDMEMORY", VoltType.BIGINT)); columns.add(new VoltTable.ColumnInfo("PHYSICALMEMORY", VoltType.BIGINT)); columns.add(new VoltTable.ColumnInfo("JAVAMAXHEAP", VoltType.INTEGER)); }

Target:
protected void populateColumnSchema(ArrayList<ColumnInfo> columns) { super.populateColumnSchema(columns); columns.add(new VoltTable.ColumnInfo("RSS", VoltType.INTEGER)); columns.add(new VoltTable.ColumnInfo("JAVAUSED", VoltType.INTEGER)); columns.add(new VoltTable.ColumnInfo("JAVAUNUSED", VoltType.INTEGER)); columns.add(new VoltTable.ColumnInfo("TUPLEDATA", VoltType.BIGINT)); columns.add(new VoltTable.ColumnInfo("TUPLEALLOCATED", VoltType.BIGINT)); columns.add(new VoltTable.ColumnInfo("INDEXMEMORY", VoltType.BIGINT)); columns.add(new VoltTable.ColumnInfo("STRINGMEMORY", VoltType.BIGINT)); columns.add(new VoltTable.ColumnInfo("TUPLECOUNT", VoltType.BIGINT)); columns.add(new VoltTable.ColumnInfo("POOLEDMEMORY", VoltType.BIGINT)); columns.add(new VoltTable.ColumnInfo("PHYSICALMEMORY", VoltType.BIGINT)); columns.add(new VoltTable.ColumnInfo("JAVAMAXHEAP", VoltType.INTEGER)); }
Source:
public HpccRemoteFileReader(DataPartition dp, FieldDef originalRD, IRecordBuilder recBuilder, int connectTimeout, int limit) throws Exception { this(dp, originalRD, recBuilder, connectTimeout, limit, true, -1); }

Target:
public HpccRemoteFileReader(DataPartition dp, FieldDef originalRD, IRecordBuilder recBuilder, int connectTimeout, int limit) throws Exception { this(dp, originalRD, recBuilder, connectTimeout, limit, true, DEFAULT_READ_SIZE_OPTION); }
Source:
void populate(final int row, final PluginInfo plugin) { table.setWidget(row, 1, new Anchor(plugin.name(), "/plugins/" + plugin.name() + "/")); table.setText(row, 2, plugin.version()); final FlexCellFormatter fmt = table.getFlexCellFormatter(); fmt.addStyleName(row, 1, Gerrit.RESOURCES.css().dataCell()); fmt.addStyleName(row, 2, Gerrit.RESOURCES.css().dataCell()); setRowItem(row, plugin); }

Target:
void populate(final int row, final PluginInfo plugin) { table.setWidget( row, 1, new Anchor(plugin.name(), Gerrit.selfRedirect("/plugins/" + plugin.name() + "/"))); table.setText(row, 2, plugin.version()); final FlexCellFormatter fmt = table.getFlexCellFormatter(); fmt.addStyleName(row, 1, Gerrit.RESOURCES.css().dataCell()); fmt.addStyleName(row, 2, Gerrit.RESOURCES.css().dataCell()); setRowItem(row, plugin); }
Source:
private String sanitizedCacheName() { String cacheFileName = ctx.getCache().getName().replaceAll("[^a-zA-Z0-9-_\\.]", "_"); return cacheFileName; }

Target:
private String sanitizedCacheName() { return ctx.getCache().getName().replaceAll("[^a-zA-Z0-9-_\\.]", "_"); }
Source:
protected static CommandLine parseOptions(String[] args) throws ParseException { CommandLineParser parser = new DefaultParser(); CommandLine cmdLine; cmdLine = parser.parse(options, args); if (cmdLine.hasOption(OPTION_HELP)) { cmdLine.getArgList().add(OPTION_HELP); setQuiet(); } else if (cmdLine.getArgList().isEmpty()) { throw new ParseException("Missing command."); } if (cmdLine.hasOption(OPTION_QUIET) || cmdLine.hasOption(OPTION_XML) || cmdLine.hasOption(OPTION_JSON)) { setQuiet(); } if (cmdLine.hasOption(OPTION_DEBUG)) { setDebug(cmdLine.getOptionValues(OPTION_DEBUG), "org.nuxeo.launcher"); } if (cmdLine.hasOption(OPTION_DEBUG_CATEGORY)) { setDebug(cmdLine.getOptionValues(OPTION_DEBUG_CATEGORY), "org.nuxeo.launcher"); } if (cmdLine.hasOption(OPTION_FORCE) || cmdLine.hasOption(OPTION_STRICT)) { setStrict(true); } return cmdLine; }

Target:
protected static CommandLine parseOptions(String[] args) throws ParseException { CommandLineParser parser = new DefaultParser(); CommandLine cmdLine = parser.parse(options, args); if (cmdLine.hasOption(OPTION_HELP)) { cmdLine.getArgList().add(OPTION_HELP); setQuiet(); } else if (cmdLine.getArgList().isEmpty()) { throw new ParseException("Missing command."); } if (cmdLine.hasOption(OPTION_QUIET) || cmdLine.hasOption(OPTION_XML) || cmdLine.hasOption(OPTION_JSON)) { setQuiet(); } if (cmdLine.hasOption(OPTION_DEBUG)) { setDebug(cmdLine.getOptionValues(OPTION_DEBUG), "org.nuxeo.launcher"); } if (cmdLine.hasOption(OPTION_DEBUG_CATEGORY)) { setDebug(cmdLine.getOptionValues(OPTION_DEBUG_CATEGORY), "org.nuxeo.launcher"); } if (cmdLine.hasOption(OPTION_FORCE) || cmdLine.hasOption(OPTION_STRICT)) { setStrict(true); } return cmdLine; }
Source:
public Void invoke(File f, VirtualChannel channel) throws IOException, InterruptedException { f.deleteOnExit(); return null; }

Target:
@Override public Void invoke(File f, VirtualChannel channel) throws IOException, InterruptedException { f.deleteOnExit(); return null; }
Source:
public long appendObjectState(Stream<Map.Entry> entryStream) { ImmutableMap<CheckpointEntry.CheckpointDictKey, String> mdkv = ImmutableMap.copyOf(this.mdkv); final Iterable<List<Map.Entry>> partitions = Iterables.partition(entryStream::iterator, batchSize); ExecutorService executor = Executors.newFixedThreadPool(MAX_WRITER); int i = 0; for (List<Map.Entry> partition : partitions) { int finalI = i; executor.submit(()-> {writeCKJob(partition, finalI);}); i++; } executor.shutdown(); return entryCount.get(); }

Target:
public long appendObjectState(Stream<Map.Entry> entryStream ) { ImmutableMap<CheckpointEntry.CheckpointDictKey, String> mdkv = ImmutableMap.copyOf(this.mdkv); List<Future<String>> taskList = new ArrayList<>(); ExecutorService executor = Executors.newFixedThreadPool(MAX_WRITER); Iterator streamIter = entryStream.iterator (); int i = 0; List<Map.Entry> partition = new ArrayList(); while (streamIter.hasNext()) { partition.add((Map.Entry)streamIter.next()); if (partition.size () == batchSize || !streamIter.hasNext()) { int finalI = i++; List<Map.Entry> current = partition; Future<String> future = executor.submit (new Callable () { public Object call() { writeCKJob (current, finalI); return "Done" + finalI; } }); taskList.add (future); partition = new ArrayList<Map.Entry> (); } } try { for (Future<String> task : taskList) { log.debug ("task done: ", task.get()); } } catch (ExecutionException | InterruptedException e) { log.error ("Checkpoint failure with exception ", e); } log.info("Checkpoint total batches entries.", i, entryCount.get()); executor.shutdown(); return entryCount.get(); }
Source:
public void should_not_propagate_unchecked_exceptions() { Level previous = TestUtils.setLogLevel(HostConnectionPool.class, Level.WARN); MemoryAppender logs = new MemoryAppender().enableFor(HostConnectionPool.class); try { Session session = cluster.connect(); Session.State state = session.getState(); Host host1 = scassandra.host(cluster, 1, 1); Host host2 = scassandra.host(cluster, 1, 2); assertThat(state.getOpenConnections(host1)).isEqualTo(0); assertThat(state.getOpenConnections(host2)).isEqualTo(0); assertThat(logs.get()) .contains( "Unexpected error during transport initialization", "not really", NullPointerException.class.getSimpleName(), "com.datastax.driver.core.Connection$4.apply"); } finally { TestUtils.setLogLevel(HostConnectionPool.class, previous); logs.disableFor(HostConnectionPool.class); } }

Target:
public void should_not_propagate_unchecked_exceptions() { Level previous = TestUtils.setLogLevel(HostConnectionPool.class, Level.WARN); MemoryAppender logs = new MemoryAppender().enableFor(HostConnectionPool.class); try { Session session = cluster.connect(); Host host1 = scassandra.host(cluster, 1, 1); Host host2 = scassandra.host(cluster, 1, 2); TestUtils.waitForDown(TestUtils.ipOfNode(2), cluster); Session.State state = session.getState(); assertThat(state.getOpenConnections(host1)).isEqualTo(0); assertThat(state.getOpenConnections(host2)).isEqualTo(0); assertThat(logs.get()) .contains( "Unexpected error during transport initialization", "not really", NullPointerException.class.getSimpleName(), "com.datastax.driver.core.Connection$4.apply"); HostConnectionPool pool1 = ((SessionManager)session).pools.get(host1); HostConnectionPool pool2 = ((SessionManager)session).pools.get(host2); assertThat(pool1).isNotNull(); assertThat(pool1.isClosed()).isFalse(); assertThat(pool2).isNull(); } finally { TestUtils.setLogLevel(HostConnectionPool.class, previous); logs.disableFor(HostConnectionPool.class); } }
Source:
private static Waypoint createWaypointFromDatabaseContent(final Cursor cursor) { JSONObject json; final String name = cursor.getString(cursor.getColumnIndex("name")); final WaypointType type = WaypointType.findById(cursor.getString(cursor.getColumnIndex("type"))); final boolean own = cursor.getInt(cursor.getColumnIndex("own")) != 0; final Waypoint waypoint = new Waypoint(name, type, own); waypoint.setVisited(cursor.getInt(cursor.getColumnIndex("visited")) != 0); waypoint.setId(cursor.getInt(cursor.getColumnIndex("_id"))); waypoint.setGeocode(cursor.getString(cursor.getColumnIndex("geocode"))); waypoint.setPrefix(cursor.getString(cursor.getColumnIndex("prefix"))); waypoint.setLookup(cursor.getString(cursor.getColumnIndex("lookup"))); waypoint.setCoords(getCoords(cursor, cursor.getColumnIndex("latitude"), cursor.getColumnIndex("longitude"))); waypoint.setNote(cursor.getString(cursor.getColumnIndex("note"))); waypoint.setUserNote(cursor.getString(cursor.getColumnIndex("user_note"))); waypoint.setOriginalCoordsEmpty(cursor.getInt(cursor.getColumnIndex("org_coords_empty")) != 0); try { waypoint.setCalculatorStoredState(CalcState.fromJSON(cursor.getString(cursor.getColumnIndex("calc_state")))); } catch (JSONException e) { waypoint.setCalculatorStoredState(null); } return waypoint; }

Target:
private static Waypoint createWaypointFromDatabaseContent(final Cursor cursor) { final String name = cursor.getString(cursor.getColumnIndex("name")); final WaypointType type = WaypointType.findById(cursor.getString(cursor.getColumnIndex("type"))); final boolean own = cursor.getInt(cursor.getColumnIndex("own")) != 0; final Waypoint waypoint = new Waypoint(name, type, own); waypoint.setVisited(cursor.getInt(cursor.getColumnIndex("visited")) != 0); waypoint.setId(cursor.getInt(cursor.getColumnIndex("_id"))); waypoint.setGeocode(cursor.getString(cursor.getColumnIndex("geocode"))); waypoint.setPrefix(cursor.getString(cursor.getColumnIndex("prefix"))); waypoint.setLookup(cursor.getString(cursor.getColumnIndex("lookup"))); waypoint.setCoords(getCoords(cursor, cursor.getColumnIndex("latitude"), cursor.getColumnIndex("longitude"))); waypoint.setNote(cursor.getString(cursor.getColumnIndex("note"))); waypoint.setUserNote(cursor.getString(cursor.getColumnIndex("user_note"))); waypoint.setOriginalCoordsEmpty(cursor.getInt(cursor.getColumnIndex("org_coords_empty")) != 0); try { waypoint.setCalculatorStoredState(CalcState.fromJSON(cursor.getString(cursor.getColumnIndex("calc_state")))); } catch (final JSONException e) { Log.e("Unable to read calculator state information", e); } return waypoint; }
Source:
private static <T extends Metric> void saveMetricTaskIdMapping(Integer taskId, MetricNames names, T metric, Map<Integer, Map<String, T>> taskIdMetrics) { Map<String, T> metrics = taskIdMetrics.computeIfAbsent(taskId, (tid) -> new HashMap<>()); if (metrics.get(names.getShortName()) != null) { LOG.warn("Adding duplicate short metric for with long name {}, only the last metric " + "will be reported during the V2 metrics tick.", names.getShortName(), names.longName); } metrics.put(names.getShortName(), metric); }

Target:
private static <T extends Metric> void saveMetricTaskIdMapping(Integer taskId, MetricNames names, T metric, Map<Integer, Map<String, T>> taskIdMetrics) { Map<String, T> metrics = taskIdMetrics.computeIfAbsent(taskId, (tid) -> new HashMap<>()); metrics.put(names.getShortName(), metric); }