auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> int getGlobalTermsStringResource(FlowParameters flowParameters) { <END> boolean termsOfServiceUrlProvided = flowParameters.isTermsOfServiceUrlProvided(); boolean privacyPolicyUrlProvided = flowParameters.isPrivacyPolicyUrlProvided(); if (termsOfServiceUrlProvided && privacyPolicyUrlProvided) { return R.string.fui_tos_and_pp; } else if (termsOfServiceUrlProvided) { return R.string.fui_tos_only; } else if (privacyPolicyUrlProvided) { return R.string.fui_pp_only; } return NO_TOS_OR_PP; }</code><technical_language>Formatting (here elsewhere) method declaration arg list line: java private static @StringRes int getGlobalTermsStringResource(FlowParameters flowParameters) { If need line break, do (</technical_language>

Target:
private static int getGlobalTermsStringResource(FlowParameters flowParameters) { boolean termsOfServiceUrlProvided = flowParameters.isTermsOfServiceUrlProvided(); boolean privacyPolicyUrlProvided = flowParameters.isPrivacyPolicyUrlProvided(); if (termsOfServiceUrlProvided && privacyPolicyUrlProvided) { return R.string.fui_tos_and_pp; } else if (termsOfServiceUrlProvided) { return R.string.fui_tos_only; } else if (privacyPolicyUrlProvided) { return R.string.fui_pp_only; } return NO_TOS_OR_PP; }
Source:
<code>public void provision( InternalEnvironment environment, OpenShiftEnvironment osEnv, RuntimeIdentity runtimeIdentity) throws InfrastructureException { if (pvcEnable) { final String workspaceId = runtimeIdentity.getWorkspaceId(); final String pvcUniqueName; switch (pvcStrategy) { case UNIQUE: <START> pvcUniqueName = pvcName + '-' + workspaceId; <END> break; case COMMON: pvcUniqueName = pvcName; break; default: throw new IllegalArgumentException( format("Unsupported PVC strategy '%s' configured", pvcStrategy)); } osEnv .getPersistentVolumeClaims() .put( pvcUniqueName, new PersistentVolumeClaimBuilder() .withNewMetadata() .withName(pvcUniqueName) .endMetadata() .withNewSpec() .withAccessModes(pvcAccessMode) .withNewResources() .withRequests(ImmutableMap.of("storage", new Quantity(pvcQuantity))) .endResources() .endSpec() .build()); final String machineWithSources = WsAgentMachineFinderUtil.getWsAgentServerMachine(environment) .orElseThrow(() -> new InfrastructureException("Machine with wsagent not found")); for (Pod pod : osEnv.getPods().values()) { for (Container container : pod.getSpec().getContainers()) { final String machineName = pod.getMetadata().getName() + "/" + container.getName(); if (machineWithSources.equals(machineName)) { final VolumeMount volumeMount = new VolumeMountBuilder() .withMountPath(projectFolderPath) .withName(pvcUniqueName) .withSubPath(workspaceId + projectFolderPath) .build(); container.getVolumeMounts().add(volumeMount); final PersistentVolumeClaimVolumeSource pvcs = new PersistentVolumeClaimVolumeSourceBuilder().withClaimName(pvcUniqueName).build(); final Volume volume = new VolumeBuilder().withPersistentVolumeClaim(pvcs).withName(pvcUniqueName).build(); pod.getSpec().getVolumes().add(volume); return; } } } } }</code><technical_language>This behavior isolated in some strategy</technical_language>

Target:
public void provision( InternalEnvironment environment, OpenShiftEnvironment osEnv, RuntimeIdentity runtimeIdentity) throws InfrastructureException { if (pvcEnable) { pvcStrategy.prepare(environment, osEnv, runtimeIdentity.getWorkspaceId()); } }
Source:
<code>private void verifySubPolicy(Policy subPolicy) throws InvalidPolicyAttributes { if (subPolicy == null) { <START> return; <END> } if (!(subPolicy instanceof FactorsPolicy) && !(subPolicy instanceof MethodAmountPolicy)) { throw new InvalidPolicyAttributes("Inside or Outside Policy objects must be of type FactorsPolicy or MethodAmountPolicy, or null if no policy", null, null); } if (subPolicy.getDenyEmulatorSimulator() || subPolicy.getDenyRootedJailbroken()) { throw new InvalidPolicyAttributes("Inside or Outside Policy objects must have denyEmulatorSimulator or denyRootedJailbroken set to false", null, null); } if (subPolicy.getFences() != null) { throw new InvalidPolicyAttributes("Fences are not supported on Inside or Outside Policy objects",null,null); } }</code><technical_language>I do a null nested policy</technical_language>

Target:
private void verifySubPolicy(Policy subPolicy) throws InvalidPolicyAttributes { if (subPolicy == null) { throw new InvalidPolicyAttributes("Inside or Outside Policy objects must not be null", null, null); } else if (!(subPolicy instanceof FactorsPolicy) && !(subPolicy instanceof MethodAmountPolicy)) { throw new InvalidPolicyAttributes("Inside or Outside Policy objects must be of type FactorsPolicy or MethodAmountPolicy", null, null); } if (subPolicy.getDenyEmulatorSimulator() || subPolicy.getDenyRootedJailbroken()) { throw new InvalidPolicyAttributes("Inside or Outside Policy objects must have denyEmulatorSimulator or denyRootedJailbroken set to false", null, null); } if (subPolicy.getFences() != null) { throw new InvalidPolicyAttributes("Fences are not supported on Inside or Outside Policy objects",null,null); } }
Source:
<code>private boolean updateRelevantVms() { List<VM> vms = getVmsDiskPluggedTo(); <START> boolean updateAllVmsSucceeded = true; <END> if (vms.isEmpty()) { return extendFloatingDiskSize(); } for (VM vm : vms) { try { VDSReturnValue ret = extendVmDiskSize(vm, getParameters().getNewSize()); if (!ret.getSucceeded()) { updateAuditLogFailedToUpdateVM(vm.getName()); } } catch (EngineException e) { log.warn("Failed to update VM '{}' with the new volume size due to error, " + "VM should be restarted to detect the new size: {}", vm.getName(), e.getMessage()); log.debug("Exception", e); updateAuditLogFailedToUpdateVM(vm.getName()); updateAllVmsSucceeded = false; } } return updateAllVmsSucceeded; }</code><technical_language>readability - move 'updateAllVmsSucceeded' declaration line 118, needed for floating disk flow</technical_language>

Target:
private boolean updateRelevantVms() { List<VM> vms = getVmsDiskPluggedTo(); if (vms.isEmpty()) { return extendFloatingDiskSize(); } boolean updateAllVmsSucceeded = true; for (VM vm : vms) { try { VDSReturnValue ret = extendVmDiskSize(vm, getParameters().getNewSize()); if (!ret.getSucceeded()) { updateAuditLogFailedToUpdateVM(vm.getName()); } } catch (EngineException e) { log.warn("Failed to update VM '{}' with the new volume size due to error, " + "VM should be restarted to detect the new size: {}", vm.getName(), e.getMessage()); log.debug("Exception", e); updateAuditLogFailedToUpdateVM(vm.getName()); updateAllVmsSucceeded = false; } } return updateAllVmsSucceeded; }
Source:
<code>public RunningOperation(SpliceOperation operation, Thread thread, Date submittedTime, DataSetProcessor.Type engine, UUID uuid, String rdbIntTkn) { this.operation = operation; this.thread =thread; <START> this.submittedTime = (Date)submittedTime.clone(); <END> this.engine = engine; this.uuid = uuid; this.rdbIntTkn = rdbIntTkn; }</code><technical_language>I remove this clone, costly for OLTP queries add in hot path</technical_language>

Target:
public RunningOperation(SpliceOperation operation, Thread thread, Date submittedTime, DataSetProcessor.Type engine, UUID uuid, String rdbIntTkn) { this.operation = operation; this.thread =thread; this.submittedTime = submittedTime; this.engine = engine; this.uuid = uuid; this.rdbIntTkn = rdbIntTkn; }
Source:
<code>private void updateStatusOfPushMessageInformation(final PushMessageInformation pushMessageInformation, final String variantID, final int receivers, final Boolean deliveryStatus, final String reason) { final VariantMetricInformation variantMetricInformation = new VariantMetricInformation(); variantMetricInformation.setPushMessageInformation(pushMessageInformation); variantMetricInformation.setVariantID(variantID); variantMetricInformation.setReceivers(receivers); variantMetricInformation.setDeliveryStatus(deliveryStatus); variantMetricInformation.setReason(reason); <START> pushMessageInformation.getVariantInformations().add(variantMetricInformation); <END> dispatchVariantMetricEvent.fire(variantMetricInformation); }</code><technical_language>This is a reason I 2 receivers.. variant information is added PushMessageInformation in MetricCollector#updateExistingMetric: <LINK_0> is added in NotificationDispatcher, re-adds "existing" variant metric. removing this line starts work correctly</technical_language>

Target:
private void updateStatusOfPushMessageInformation(final PushMessageInformation pushMessageInformation, final String variantID, final int receivers, final Boolean deliveryStatus, final String reason) { final VariantMetricInformation variantMetricInformation = new VariantMetricInformation(); variantMetricInformation.setPushMessageInformation(pushMessageInformation); variantMetricInformation.setVariantID(variantID); variantMetricInformation.setReceivers(receivers); variantMetricInformation.setDeliveryStatus(deliveryStatus); variantMetricInformation.setReason(reason); dispatchVariantMetricEvent.fire(variantMetricInformation); }
Source:
<code>public final void afterPropertiesSet() throws Exception { Assert.notNull(this.applicationContext, "The 'applicationContext' property must not be null"); if (this.evaluationContext == null) { this.evaluationContext = ExpressionUtils.createStandardEvaluationContext(getBeanFactory()); } if (this instanceof IntegrationFlowFunctionSupportAware) { <START> ((IntegrationFlowFunctionSupportAware)this).setIntegrationFlowFunctionSupport(integrationFlowFunctionSupport); <END> } onInit(); }</code><technical_language>I this logic belongs AbstractMessageChannelBinder talk IntegrationFlowFunctionSupportAware this feels a responsibility of some BeanPostProcessor... I right mixing a responsibility other non-Channel based Binders depend channel-based logic. Well, big height is IMO polishing approval for this PoC</technical_language>

Target:
public final void afterPropertiesSet() throws Exception { Assert.notNull(this.applicationContext, "The 'applicationContext' property must not be null"); if (this.evaluationContext == null) { this.evaluationContext = ExpressionUtils.createStandardEvaluationContext(getBeanFactory()); } onInit(); }
Source:
<code>public void tapOnPointXY(int pointX, int pointY, int duration, int waitAfter) { pointX = (int)((pointX / 100f) * appNativeWidth); pointY = (int)(((pointY / 100f) * appNativeHeight) + taskbarNativeHeight); <START> if (mobileDriver.getContext() != "NATIVE_APP") { <END> mobileDriver.context("NATIVE_APP"); } try { mobileDriver.tap(1, pointX, pointY, duration); } catch (Exception e) try { Thread.sleep(waitAfter); } catch (Exception e) if (mobileDriver.getContext() != "WEBVIEW_1") { mobileDriver.context("WEBVIEW_1"); } }</code><technical_language>if a String comparison, needs .equals() Right now, this comparison hold true trigger next statement</technical_language>

Target:
public void tapOnPointXY(int pointX, int pointY, int duration, int waitAfter) { String methodName = "tapOnPointXY"; pointX = (int)((pointX / 100f) * appNativeWidth); pointY = (int)(((pointY / 100f) * appNativeHeight) + taskbarNativeHeight); switchToContext(CONTEXT_NATIVE_APP, methodName); mobileDriver.tap(1, pointX, pointY, duration); waitForFinish(waitAfter, methodName); switchToContext(CONTEXT_WEBVIEW_1, methodName); }
Source:
<code>public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GitlabProject that = (GitlabProject) o; <START> return id != null ? id.equals(that.id) : that.id == null; <END> }</code><technical_language>Is right projects null id equal? projects issue create commands for</technical_language>

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GitlabProject that = (GitlabProject) o; if (id != null || that.id != null) { return id != null && id.equals(that.id); } else { if (name != null ? !name.equals(that.name) : that.name != null) return false; return namespace != null ? namespace.equals(that.namespace) : that.namespace == null; } }
Source:
<code><START> public SharedRealm getSharedRealm() { <END> return sharedRealm; }</code><technical_language>This public bleeds public API</technical_language>

Target:
SharedRealm getSharedRealm() { return sharedRealm; }
Source:
<code>public void postGetHeadDeleteTest() throws Exception { for (Container container : refAccount.getAllContainers()) { <START> doPostGetHeadDeleteTest(refAccount, container, refAccount, container); <END> } doPostGetHeadDeleteTest(null, null, refAccount, refDefaultPublicContainer); doPostGetHeadDeleteTest(null, null, refAccount, refDefaultPrivateContainer); }</code><technical_language>chance test accounts, generated logic</technical_language>

Target:
public void postGetHeadDeleteTest() throws Exception { short accountId; String accountName; do { accountId = Utils.getRandomShort(TestUtils.RANDOM); accountName = UtilsTest.getRandomString(10); } while (accountId == refAccount.getId() || accountName.equals(refAccount.getName())); Container randomContainer = getRandomContainer(accountId); Container defaultPublicContainer = getDefaultContainer(accountId, false); Container defaultPrivateContainer = getDefaultContainer(accountId, true); Account account = new AccountBuilder(accountId, accountName, Account.AccountStatus.ACTIVE, Arrays.asList(defaultPublicContainer, defaultPrivateContainer, randomContainer)).build(); accountService.updateAccounts(Collections.singletonList(account)); for (Account testAccount : accountService.getAllAccounts()) { for (Container container : testAccount.getAllContainers()) { doPostGetHeadDeleteTest(testAccount, container, testAccount.getName(), container.isPrivate(), testAccount, container); } } doPostGetHeadDeleteTest(null, null, refAccount.getName(), false, refAccount, refDefaultPublicContainer); doPostGetHeadDeleteTest(null, null, refAccount.getName(), true, refAccount, refDefaultPrivateContainer); doPostGetHeadDeleteTest(null, null, "unknown_service_id", false, Account.UNKNOWN_ACCOUNT, Container.DEFAULT_PUBLIC_CONTAINER); doPostGetHeadDeleteTest(null, null, "unknown_service_id", true, Account.UNKNOWN_ACCOUNT, Container.DEFAULT_PRIVATE_CONTAINER); }
Source:
<code>private DefaultOperatorIdGeneratorImpl(@Parameter(OperatorIdPrefix.class) final String prefix) { this.prefix = prefix; <START> operatorIdSeqNum = new AtomicLong(); <END> }</code><technical_language>this.operatorIdSeqNum</technical_language>

Target:
private DefaultOperatorIdGeneratorImpl(@Parameter(OperatorIdPrefix.class) final String prefix) { this.prefix = prefix; this.operatorIdSeqNum = new AtomicLong(); }
Source:
<code>public static DefaultKfsAccountForAwsResultWrapper generateExpectedDefaultKfsAccountForAwsResultWrapper() { DefaultKfsAccountForAwsResultWrapper defaultKfsAccountForAwsResultWrapper = new DefaultKfsAccountForAwsResultWrapper(); ArrayList<DefaultKfsAccountForAws> defaultKfsAccountForAwsList = new ArrayList<>(); <START> defaultKfsAccountForAwsList.add(buildDefaultKfsAccountForAws("999913976919", "1719999", "2016-04-26 18:43:03")); <END> defaultKfsAccountForAwsList.add(buildDefaultKfsAccountForAws("999970681744", "R999999", "2017-05-26 19:42:23")); defaultKfsAccountForAwsList.add(buildDefaultKfsAccountForAws("999972846379", "R999999", "2016-08-05 04:12:56")); defaultKfsAccountForAwsList.add(buildDefaultKfsAccountForAws("999937185330", "L999999", "2016-04-26 18:43:03")); defaultKfsAccountForAwsResultWrapper.setDefaultKfsAccountsForAws(defaultKfsAccountForAwsList); return defaultKfsAccountForAwsResultWrapper; }</code><technical_language>for mentioning time, move values private static final variables, avoid duplicating strings</technical_language>

Target:
public static DefaultKfsAccountForAwsResultWrapper generateExpectedDefaultKfsAccountForAwsResultWrapper() { DefaultKfsAccountForAwsResultWrapper defaultKfsAccountForAwsResultWrapper = new DefaultKfsAccountForAwsResultWrapper(); ArrayList<DefaultKfsAccountForAws> defaultKfsAccountForAwsList = new ArrayList<>(); defaultKfsAccountForAwsList.add(buildDefaultKfsAccountForAws(EXPECTED_AWS_ACCOUNTS_VALUES[0], EXPECTED_KFS_DEFAULT_ACCOUNT_VALUES[0], EXPECTED_UPDATED_AT_VALUES[0])); defaultKfsAccountForAwsList.add(buildDefaultKfsAccountForAws(EXPECTED_AWS_ACCOUNTS_VALUES[1], EXPECTED_KFS_DEFAULT_ACCOUNT_VALUES[1], EXPECTED_UPDATED_AT_VALUES[1])); defaultKfsAccountForAwsList.add(buildDefaultKfsAccountForAws(EXPECTED_AWS_ACCOUNTS_VALUES[2], EXPECTED_KFS_DEFAULT_ACCOUNT_VALUES[1], EXPECTED_UPDATED_AT_VALUES[2])); defaultKfsAccountForAwsList.add(buildDefaultKfsAccountForAws(EXPECTED_AWS_ACCOUNTS_VALUES[3], EXPECTED_KFS_DEFAULT_ACCOUNT_VALUES[2], EXPECTED_UPDATED_AT_VALUES[3])); defaultKfsAccountForAwsResultWrapper.setDefaultKfsAccountsForAws(defaultKfsAccountForAwsList); return defaultKfsAccountForAwsResultWrapper; }
Source:
<code>public ByteBuffer makeNewBuffer(long offset) { if (sizeAvailable.addAndGet(-1 * chunkSize) > 0) { return delegate.makeNewBuffer(offset); } else { <START> throw new RuntimeException("No more space left for allocating buffers."); <END> } }</code><technical_language>this decrease availableSize throw exception. this possibly availableSize get out of sync actual allocated buffer</technical_language>

Target:
public ByteBuffer makeNewBuffer(long offset) { if (sizeAvailable.addAndGet(-1 * chunkSize) > 0) { return delegate.makeNewBuffer(offset); } else { sizeAvailable.addAndGet(chunkSize); throw new RuntimeException("No more space left for allocating buffers."); } }
Source:
<code>private void startMachine(String name, DockerContainerConfig containerConfig) throws InfrastructureException { InternalMachineConfig machineCfg = getContext().getMachineConfigs().get(name); Map<String, String> labels = new HashMap<>(containerConfig.getLabels()); labels.putAll(Labels.newSerializer() .machineName(name) .runtimeId(identity) .servers(machineCfg.getServers()) .labels()); <START> containerConfig.setLabels(labels); <END> DockerMachine machine = serviceStarter.startService(dockerEnvironment.getNetwork(), name, containerConfig, identity, devMachineName.equals(name)); try { startSynchronizer.addMachine(name, machine); bootstrapperFactory.create(name, identity, machine, machineCfg.getAgents()).bootstrap(); checkServersReadiness(name, machine); } catch (InfrastructureException e) { destroyMachineQuietly(name, machine); throw e; } }</code><technical_language>is tricky case. SourceNotFoundException is thrown fall start origin source. Please, add this workaround</technical_language>

Target:
private void startMachine(String name, DockerContainerConfig containerConfig) throws InfrastructureException { InternalMachineConfig machineCfg = getContext().getMachineConfigs().get(name); Map<String, String> labels = new HashMap<>(containerConfig.getLabels()); labels.putAll(Labels.newSerializer() .machineName(name) .runtimeId(identity) .servers(machineCfg.getServers()) .labels()); containerConfig.setLabels(labels); DockerMachine machine = serviceStarter.startService(dockerEnvironment.getNetwork(), name, containerConfig, identity, devMachineName.equals(name)); try { startSynchronizer.addMachine(name, machine); bootstrapperFactory.create(name, identity, machine, machineCfg.getInstallers()).bootstrap(); checkServersReadiness(name, machine); } catch (InfrastructureException e) { destroyMachineQuietly(name, machine); throw e; } }
Source:
<code><START> private Certificate readCertificateFromPemObject(final PemObject pemObject) throws CertificateException { <END> final ByteArrayInputStream bais = new ByteArrayInputStream(pemObject.getContent()); final CertificateFactory certificateFactory = CertificateFactory.getInstance("X509"); return certificateFactory.generateCertificate(bais); }</code><technical_language>Please consider adding a Preconditions.checkArgument check pemObject is null</technical_language>

Target:
private Certificate readCertificateFromPemObject(final PemObject pemObject) throws CertificateException { Preconditions.checkNotNull(pemObject); final ByteArrayInputStream bais = new ByteArrayInputStream(pemObject.getContent()); final CertificateFactory certificateFactory = CertificateFactory.getInstance("X509"); return certificateFactory.generateCertificate(bais); }
Source:
<code>public T findById(final ID id) { T result = null; if (_cache != null) { final Element element = _cache.get(id); if (element == null) { result = lockRow(id, null); } else { result = (T)element.getObjectValue(); } } else { result = lockRow(id, null); } <START> return result <END> }</code><technical_language>a ';' missing :(</technical_language>

Target:
public T findById(final ID id) { T result = null; if (_cache != null) { final Element element = _cache.get(id); if (element == null) { result = lockRow(id, null); } else { result = (T)element.getObjectValue(); } } else { result = lockRow(id, null); } return result; }
Source:
<code>public Archive<?> generateDeployment(TestDeployment testDeployment, Collection<ProtocolArchiveProcessor> protocolProcessors) { final Archive<?> appArchive = testDeployment.getApplicationArchive(); if (archiveHolder.getArchive() == null) { try { Collection<Archive<?>> auxArchives = testDeployment.getAuxiliaryArchives(); JavaArchive archive = generateArquillianServiceArchive(auxArchives); Processor processor = new Processor(testDeployment, protocolProcessors); <START> processor.process(archive); <END> archiveHolder.setArchive(archive); } catch (Exception ex) { throw new IllegalStateException("Cannot generate arquillian service", ex); } } addModulesManifestDependencies(appArchive); archiveHolder.addPreparedDeployment(testDeployment.getDeploymentName()); return appArchive; }</code><technical_language>Ah okay. I prefer here. need abstract IMO :)</technical_language>

Target:
public Archive<?> generateDeployment(TestDeployment testDeployment, Collection<ProtocolArchiveProcessor> protocolProcessors) { final Archive<?> appArchive = testDeployment.getApplicationArchive(); if (archiveHolder.getArchive() == null) { try { Collection<Archive<?>> auxArchives = testDeployment.getAuxiliaryArchives(); JavaArchive archive = generateArquillianServiceArchive(auxArchives); for(ProtocolArchiveProcessor processor : protocolProcessors) { processor.process(testDeployment, archive); } archiveHolder.setArchive(archive); } catch (Exception ex) { throw new IllegalStateException("Cannot generate arquillian service", ex); } } addModulesManifestDependencies(appArchive); archiveHolder.addPreparedDeployment(testDeployment.getDeploymentName()); return appArchive; }
Source:
<code>private static InsecureAlgorithm algorithm(ExpressionTree invocationArgument) { ExpressionTree expectedAlgorithm = invocationArgument; ExpressionTree defaultPropertyValue = JavaPropertiesHelper.retrievedPropertyDefaultValue(invocationArgument); if (defaultPropertyValue != null) { expectedAlgorithm = defaultPropertyValue; } if (expectedAlgorithm.is(Tree.Kind.STRING_LITERAL)) { String algorithmName = LiteralUtils.trimQuotes(((LiteralTree) expectedAlgorithm).value()); return Arrays.stream(InsecureAlgorithm.values()) .filter(alg -> alg.match(algorithmName)) <START> .findFirst().orElse(null); <END> } return null; }</code><technical_language>change method return Optional<InsecureAlgorithm> mixing null stream api</technical_language>

Target:
private static Optional<InsecureAlgorithm> algorithm(ExpressionTree invocationArgument) { ExpressionTree expectedAlgorithm = invocationArgument; ExpressionTree defaultPropertyValue = JavaPropertiesHelper.retrievedPropertyDefaultValue(invocationArgument); if (defaultPropertyValue != null) { expectedAlgorithm = defaultPropertyValue; } if (expectedAlgorithm.is(Tree.Kind.STRING_LITERAL)) { String algorithmName = LiteralUtils.trimQuotes(((LiteralTree) expectedAlgorithm).value()); return Arrays.stream(InsecureAlgorithm.values()) .filter(alg -> alg.match(algorithmName)) .findFirst(); } return Optional.empty(); }
Source:
<code>public static synchronized void initialize(int myHostId, CatalogContext catalogContext, HostMessenger messenger) throws BundleException, IOException { ImporterStatsCollector statsCollector = new ImporterStatsCollector(myHostId); OperationMode startMode = VoltDB.instance().getMode(); <START> ImportManager em = new ImportManager(myHostId, messenger, statsCollector, catalogContext, startMode); <END> VoltDB.instance().getStatsAgent().registerStatsSource( StatsSelector.IMPORTER, myHostId, statsCollector); try { Map<String, ImportConfiguration> newProcessorConfig = em.loadNewConfigAndBundles(); if (em.m_clusterMode != OperationMode.PAUSED) { em.startImporters(newProcessorConfig); } } catch (final Exception e) { VoltDB.crashLocalVoltDB("Error creating initial import processor", true, e); } m_self = em; }</code><technical_language>pass mode initialize</technical_language>

Target:
public static synchronized void initialize(int myHostId, CatalogContext catalogContext, HostMessenger messenger) throws BundleException, IOException { ImporterStatsCollector statsCollector = new ImporterStatsCollector(myHostId); OperationMode startMode = VoltDB.instance().getMode(); ImportManager em = new ImportManager(myHostId, messenger, statsCollector); VoltDB.instance().getStatsAgent().registerStatsSource( StatsSelector.IMPORTER, myHostId, statsCollector); try { Map<String, ImportConfiguration> newProcessorConfig = em.loadNewConfigAndBundles(catalogContext); if (startMode != OperationMode.PAUSED) { em.startImporters(newProcessorConfig); } } catch (final Exception e) { VoltDB.crashLocalVoltDB("Error creating initial import processor", true, e); } m_self = em; }
Source:
<code><START> public void readGroupList() throws IOException { groupList = GroupList.parse(readUTF8(GroupList.FILE_NAME), this); } <END></code><technical_language>Inline this method private</technical_language>

Target:
private void readGroupList() throws IOException { groupList = GroupList.parse(readUTF8(GroupList.FILE_NAME), this); }
Source:
<code>public void createFromEmptyStoreWithNoProjection() throws Exception { URL storeUrl = TestData.url(this, "rgba"); File testDataFolder = new File(storeUrl.toURI()); File testDirectory = crsMosaicFolder.newFolder("rgba_no_proj"); FileUtils.copyDirectory(testDataFolder, testDirectory); for (File file : testDirectory.listFiles(f -> f.getName().startsWith("rgba"))) { file.delete(); } <START> for (File file : testDirectory.listFiles(f -> f.getName().endsWith("prj"))) { <END> file.delete(); } Properties properties = new Properties(); properties.put(Utils.Prop.STORE_NAME, "test"); try (FileOutputStream fos = new FileOutputStream(new File(testDirectory, "datastore.properties"))) { properties.store(fos, null); } properties = new Properties(); properties.put(Utils.Prop.TYPENAME, "abcd"); try (FileOutputStream fos = new FileOutputStream(new File(testDirectory, "indexer.properties"))) { properties.store(fos, null); } DefaultRepository repository = new DefaultRepository(); final Map<String, Serializable> params = Collections.singletonMap( ShapefileDataStoreFactory.URLP.key, URLs.fileToUrl(testDirectory)); DataStore ds = new ShapefileDataStoreFactory().createDataStore(params); assertNotNull(ds); repository.register("test", ds); Hints hints = new Hints(Hints.REPOSITORY, repository); ImageMosaicReader reader = FORMAT.getReader(testDirectory, hints); final File expectedIndexFile = new File(testDirectory, "abcd.shp"); assertTrue( expectedIndexFile.getAbsolutePath() + " does not exist", expectedIndexFile.exists()); assertNotNull(reader); GridCoverage2D coverage = reader.read(NO_DEFERRED_LOAD); assertNotNull(coverage); coverage.dispose(true); reader.dispose(); ds.dispose(); }</code><technical_language>this removes prj files</technical_language>

Target:
public void createFromEmptyStoreWithNoProjection() throws Exception { URL storeUrl = TestData.url(this, "rgba"); File testDataFolder = new File(storeUrl.toURI()); File testDirectory = crsMosaicFolder.newFolder("rgba_no_proj"); FileUtils.copyDirectory(testDataFolder, testDirectory); for (File file : testDirectory.listFiles(f -> f.getName().startsWith("rgba"))) { file.delete(); } for (File file : testDirectory.listFiles(f -> f.getName().endsWith("prj"))) { file.delete(); } ImageMosaicReader reader = FORMAT.getReader(testDirectory); assertNotNull(reader); GridCoverage2D coverage = reader.read(NO_DEFERRED_LOAD); assertNotNull(coverage); coverage.dispose(true); reader.dispose(); }
Source:
<code>public JavaWriter endType() throws IOException { Scope beginScope = scopes.getFirst(); if (Scope.TYPE_DECLARATION.equals(beginScope)) { <START> popScope(Scope.TYPE_DECLARATION); <END> } else { popScope(Scope.INTERFACE_DECLARATION); } types.pop(); indent(); out.write("}\n"); return this; }</code><technical_language>This line space indent</technical_language>

Target:
public JavaWriter endType() throws IOException { popScope(Scope.TYPE_DECLARATION, Scope.INTERFACE_DECLARATION); types.pop(); indent(); out.write("}\n"); return this; }
Source:
<code>public static void handleIssue(int severity, String message, Throwable throwable, boolean show) { IStatus status = new Status(severity, getPluginId(), message, throwable); int style = StatusManager.LOG; <START> if (show) <END> style |= StatusManager.SHOW; StatusManager.getManager().handle(status, style); }</code><technical_language>missing braces</technical_language>

Target:
public static void handleIssue(int severity, String message, Throwable throwable, boolean show) { IStatus status = new Status(severity, getPluginId(), message, throwable); int style = StatusManager.LOG; if (show) { style |= StatusManager.SHOW; } StatusManager.getManager().handle(status, style); }
Source:
<code>public void shouldSerializeCalendarLikeISO8601() { List<JsonSerializer> adapters = new ArrayList<JsonSerializer>(); <START> adapters.add(new br.com.caelum.vraptor.serialization.iso8601.gson.CalendarISO8601Serializer(new ISO8601Util())); <END> GsonJSONSerialization serialization = new GsonJSONSerialization(response, extractor, initializer, createBuilder(adapters), serializee); Client c = new Client("Rafael"); c.included = new GregorianCalendar(2013, 6, 27, 9, 52, 38); c.included.setTimeZone(TimeZone.getTimeZone("America/Sao_Paulo")); serialization.from(c).serialize(); String result = result(); String expectedResult = "{\"client\":{\"name\":\"Rafael\",\"included\":\"2013-07-27T09:52:38.000-0300\"}}"; assertThat(result, is(equalTo(expectedResult))); }</code><technical_language>I need FQN =/</technical_language>

Target:
public void shouldSerializeCalendarLikeISO8601() { GsonJSONSerialization serialization = serializationWithAdapter(new CalendarISO8601Serializer(new ISO8601Util())); Client c = new Client("Rafael"); c.included = new GregorianCalendar(2013, 6, 27, 9, 52, 38); c.included.setTimeZone(TimeZone.getTimeZone("America/Sao_Paulo")); serialization.from(c).serialize(); String result = result(); String expectedResult = "{\"client\":{\"name\":\"Rafael\",\"included\":\"2013-07-27T09:52:38.000-0300\"}}"; assertThat(result, is(equalTo(expectedResult))); }
Source:
<code>public BlobProperties getBlobProperties(String blobIdString) throws CoordinatorException { try { logger.trace("getBlobProperties. " + blobIdString); long startTimeInMs = System.currentTimeMillis(); BlobId blobId = getBlobIdFromString(blobIdString); GetBlobPropertiesOperation gbpo = new GetBlobPropertiesOperation(datacenterName, connectionPool, requesterPool, getOperationContext(), blobId, operationTimeoutMs, clusterMap); gbpo.execute(); coordinatorMetrics.getBlobPropertiesOperationRate.mark(); coordinatorMetrics.getBlobPropertiesOperationLatencyInMs.update(System.currentTimeMillis() - startTimeInMs); return gbpo.getBlobProperties(); } catch (CoordinatorException e) { <START> logger.error("getBlobProperties re-throwing CoordinatorException" + e); <END> coordinatorMetrics.countError(CoordinatorMetrics.CoordinatorOperationType.GetBlobProperties, e.getErrorCode()); throw e; } }</code><technical_language>question suggestion for error logging</technical_language>

Target:
public BlobProperties getBlobProperties(String blobIdString) throws CoordinatorException { try { logger.trace("getBlobProperties. " + blobIdString); long startTimeInMs = System.currentTimeMillis(); BlobId blobId = getBlobIdFromString(blobIdString); GetBlobPropertiesOperation gbpo = new GetBlobPropertiesOperation(datacenterName, connectionPool, requesterPool, getOperationContext(), blobId, operationTimeoutMs, clusterMap); gbpo.execute(); coordinatorMetrics.getBlobPropertiesOperationRate.mark(); coordinatorMetrics.getBlobPropertiesOperationLatencyInMs.update(System.currentTimeMillis() - startTimeInMs); return gbpo.getBlobProperties(); } catch (CoordinatorException e) { logger.trace("getBlobProperties re-throwing CoordinatorException", e); coordinatorMetrics.countError(CoordinatorMetrics.CoordinatorOperationType.GetBlobProperties, e.getErrorCode()); throw e; } }
Source:
<code>void handleRevocation(final Collection<TopicPartition> revokedPartitions) { final Set<TaskId> revokedTasks = new HashSet<>(); final Set<TopicPartition> remainingPartitions = new HashSet<>(revokedPartitions); for (final Task task : tasks.values()) { <START> for (final TopicPartition topicPartition : task.inputPartitions()) { <END> if (remainingPartitions.contains(topicPartition)) { revokedTasks.add(task.id()); remainingPartitions.remove(topicPartition); } } } if (!remainingPartitions.isEmpty()) { throw new IllegalStateException("Some revoked partitions that do not belong " + "to any tasks remain: " + remainingPartitions); } for (final TaskId taskId : revokedTasks) { final Task task = tasks.get(taskId); task.suspend(); } }</code><technical_language>Hmm.. part of partitions of a task is revoked? do assignment granularity of tasks this check is verify specifically partitions included if a task is removed right</technical_language>

Target:
void handleRevocation(final Collection<TopicPartition> revokedPartitions) { final Set<TaskId> revokedTasks = new HashSet<>(); final Set<TopicPartition> remainingPartitions = new HashSet<>(revokedPartitions); for (final Task task : tasks.values()) { if (remainingPartitions.containsAll(task.inputPartitions())) { revokedTasks.add(task.id()); } remainingPartitions.removeAll(task.inputPartitions()); } if (!remainingPartitions.isEmpty()) { throw new IllegalStateException("Some revoked partitions that do not belong " + "to any tasks remain: " + remainingPartitions); } for (final TaskId taskId : revokedTasks) { final Task task = tasks.get(taskId); task.suspend(); } }
Source:
<code>public void PacketExceptionTest() throws BadPacketException, IOException, BadPcapFileException { PcapTestTrace trace = PcapTestTrace.MOSTLY_TCP; assumeTrue(trace.exists()); <START> PcapFile dummy = trace.getTrace(); <END> ByteBuffer packet = fEthernetPacket; if (packet != null) { new EthernetIIPacket(dummy, null, packet); } fail("PacketExceptionTest has failed!"); }</code><technical_language>I try</technical_language>

Target:
public void PacketExceptionTest() throws BadPacketException, IOException, BadPcapFileException { PcapTestTrace trace = PcapTestTrace.MOSTLY_TCP; assumeTrue(trace.exists()); try (PcapFile dummy = trace.getTrace();) { ByteBuffer packet = fEthernetPacket; if (packet != null) { new EthernetIIPacket(dummy, null, packet); } fail("PacketExceptionTest has failed!"); } }
Source:
<code>public void beforeClass(@Optional Boolean usingEncryption, @Optional String testType) throws IOException { ConfigContext config = new IntegrationTestConfigContext(usingEncryption); String testName = this.getClass().getSimpleName(); mantaClient = new MantaClient(config); <START> if(testType != null && testType.equals("buckets")) { <END> if(IntegrationTestHelper.verifyBucketsSupport(config, mantaClient)) { bucketsEnabled = true; bucketsTestPathPrefix = IntegrationTestHelper.setupBucketsPath(config, testName); testPathPrefix = IntegrationTestHelper.setupBucketObjectBasePath(bucketsTestPathPrefix); } else { throw new SkipException("Buckets operations not supported by the server"); } } else { testPathPrefix = IntegrationTestConfigContext.generateBasePath(config, testName); mantaClient.putDirectory(testPathPrefix, true); } }</code><technical_language>Please put a space if</technical_language>

Target:
public void beforeClass(@Optional Boolean usingEncryption, @Optional String testType) throws IOException { ConfigContext config = new IntegrationTestConfigContext(usingEncryption); String testName = this.getClass().getSimpleName(); mantaClient = new MantaClient(config); testPathPrefix = IntegrationTestHelper.setupTestPath(config, mantaClient, testName, testType); IntegrationTestHelper.createTestBucketOrDirectory(mantaClient, testPathPrefix, testType); }
Source:
<code>private CompletionStage<RestResponse> createScriptTask(RestRequest request) { <START> NettyRestResponse.Builder builder = new NettyRestResponse.Builder(); <END> String taskName = request.variables().get("taskName"); if (taskName == null || taskName.isEmpty() || taskName.startsWith("@@")) { builder.status(HttpResponseStatus.BAD_REQUEST).entity("Task name must be provided and cannot start with '@@'"); } EmbeddedCacheManager cacheManager = invocationHelper.getRestCacheManager().getInstance(); ScriptingManager scriptingManager = SecurityActions.getGlobalComponentRegistry(cacheManager).getComponent(ScriptingManager.class); ContentSource contents = request.contents(); byte[] bytes = contents.rawContent(); MediaType sourceType = request.contentType() == null ? APPLICATION_JAVASCRIPT : request.contentType(); String script = StandardConversions.convertTextToObject(bytes, sourceType); scriptingManager.addScript(taskName, script); return completedFuture(builder.build()); }</code><technical_language>appart REST, is other place create a task name validation added</technical_language>

Target:
private CompletionStage<RestResponse> createScriptTask(RestRequest request) { String taskName = request.variables().get("taskName"); EmbeddedCacheManager cacheManager = invocationHelper.getRestCacheManager().getInstance(); ScriptingManager scriptingManager = SecurityActions.getGlobalComponentRegistry(cacheManager).getComponent(ScriptingManager.class); NettyRestResponse.Builder builder = new NettyRestResponse.Builder(); ContentSource contents = request.contents(); byte[] bytes = contents.rawContent(); MediaType sourceType = request.contentType() == null ? APPLICATION_JAVASCRIPT : request.contentType(); String script = StandardConversions.convertTextToObject(bytes, sourceType); scriptingManager.addScript(taskName, script); return completedFuture(builder.build()); }
Source:
<code>public void testWithDisabledInstancesLimit() throws Exception { MaintenanceSignal maintenanceSignal = _dataAccessor.getProperty(_dataAccessor.keyBuilder().maintenance()); Assert.assertNull(maintenanceSignal); checkForRebalanceError(false); HelixAdmin admin = new ZKHelixAdmin(_gZkClient); int i; for (i = 2; i < 2 + _maxOfflineInstancesAllowed; i++) { String instance = _participants.get(i).getInstanceName(); admin.enableInstance(CLUSTER_NAME, instance, false); } boolean result = TestHelper.verify(() -> { MaintenanceSignal ms = _dataAccessor.getProperty(_dataAccessor.keyBuilder().maintenance()); return ms == null; }, TestHelper.WAIT_DURATION); Assert.assertTrue(result); String instance = _participants.get(i).getInstanceName(); admin.enableInstance(CLUSTER_NAME, instance, false); <START> ZkHelixClusterVerifier clusterVerifier1 = <END> new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient) .build(); Assert.assertTrue(clusterVerifier1.verifyByPolling()); result = TestHelper.verify(() -> { MaintenanceSignal ms =_dataAccessor.getProperty(_dataAccessor.keyBuilder().maintenance()); return ms != null && ms.getReason() != null; }, TestHelper.WAIT_DURATION); checkForRebalanceError(true); for (i = 2; i < 2 + _maxOfflineInstancesAllowed + 1; i++) { instance = _participants.get(i).getInstanceName(); admin.enableInstance(CLUSTER_NAME, instance, true); } admin.enableMaintenanceMode(CLUSTER_NAME, false); }</code><technical_language>Please mind naming of variables. A meaningful name is required in cases</technical_language>

Target:
public void testWithDisabledInstancesLimit() throws Exception { MaintenanceSignal maintenanceSignal = _dataAccessor.getProperty(_dataAccessor.keyBuilder().maintenance()); Assert.assertNull(maintenanceSignal); checkForRebalanceError(false); HelixAdmin admin = new ZKHelixAdmin(_gZkClient); int i; for (i = 2; i < 2 + _maxOfflineInstancesAllowed; i++) { String instance = _participants.get(i).getInstanceName(); admin.enableInstance(CLUSTER_NAME, instance, false); } boolean result = TestHelper.verify(() -> { MaintenanceSignal ms = _dataAccessor.getProperty(_dataAccessor.keyBuilder().maintenance()); return ms == null; }, TestHelper.WAIT_DURATION); Assert.assertTrue(result); String instance = _participants.get(i).getInstanceName(); admin.enableInstance(CLUSTER_NAME, instance, false); ZkHelixClusterVerifier clusterVerifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient) .setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME) .build(); Assert.assertTrue(clusterVerifier.verifyByPolling()); result = TestHelper.verify(() -> { MaintenanceSignal ms =_dataAccessor.getProperty(_dataAccessor.keyBuilder().maintenance()); return ms != null && ms.getReason() != null; }, TestHelper.WAIT_DURATION); Assert.assertTrue(result); checkForRebalanceError(true); for (i = 2; i < 2 + _maxOfflineInstancesAllowed + 1; i++) { instance = _participants.get(i).getInstanceName(); admin.enableInstance(CLUSTER_NAME, instance, true); } admin.enableMaintenanceMode(CLUSTER_NAME, false); Assert.assertTrue(clusterVerifier.verifyByPolling()); }
Source:
<code>public RecordWriter<Long, SinkRecord> getRecordWriter(Configuration conf, String fileName, SinkRecord record) throws IOException{ DatumWriter<Object> datumWriter = new GenericDatumWriter<Object>(); final DataFileWriter<Object> writer = new DataFileWriter<Object>(datumWriter); Path path = new Path(fileName); <START> Object value = AvroData.convertToAvro(record.getValue()); <END> writer.create(((GenericRecord) value).getSchema(), path.getFileSystem(conf).create(path)); return new RecordWriter<Long, SinkRecord>(){ @Override public void write(Long key, SinkRecord record) throws IOException{ Object value = AvroData.convertToAvro(record.getValue()); writer.append(value); } @Override public void close() throws IOException{ writer.close(); } @Override public void flush() throws IOException{ writer.flush(); } }; }</code><technical_language>refactor copycat-core support this. Right now, AvroData is intended internal API. need refactor want serialization pluggable (so moving copycat-avro a big deal), I want if API is want effectively making public API here</technical_language>

Target:
public RecordWriter<Long, SinkRecord> getRecordWriter(Configuration conf, String fileName, SinkRecord record) throws IOException{ DatumWriter<Object> datumWriter = new GenericDatumWriter<Object>(); final DataFileWriter<Object> writer = new DataFileWriter<Object>(datumWriter); Path path = new Path(fileName); Schema schema = ((GenericRecord) record.getValue()).getSchema(); writer.create(AvroData.asAvroSchema(schema), path.getFileSystem(conf).create(path)); return new RecordWriter<Long, SinkRecord>(){ @Override public void write(Long key, SinkRecord record) throws IOException{ Object value = AvroData.convertToAvro(record.getValue()); writer.append(value); } @Override public void close() throws IOException{ writer.close(); } }; }
Source:
<code>public VdcActionParametersBase getParameters(VM incoming, org.ovirt.engine.core.common.businessentities.VM entity) { VmStatic updated = getMapper(modelType, VmStatic.class).map(incoming, entity.getStaticData()); updated.setUsbPolicy(VmMapper.getUsbPolicyOnUpdate(incoming.getUsb(), entity.getUsbPolicy(), lookupCluster(updated.getVdsGroupId()))); VmManagementParametersBase params = new VmManagementParametersBase(updated); if (incoming.isSetPayloads()) { if (incoming.isSetPayloads() && incoming.getPayloads().isSetPayload()) { params.setVmPayload(parent.getPayload(incoming)); } else { params.setClearPayload(true); } } if (incoming.isSetMemoryPolicy() && incoming.getMemoryPolicy().isSetBallooning()) { params.setBalloonEnabled(incoming.getMemoryPolicy().isBallooning()); } <START> if (incoming.isSetConsoleDeviceEnabled()) { <END> params.setConsoleEnabled(incoming.isConsoleDeviceEnabled()); } return params; }</code><technical_language>this in doPopulate() in deprecatedPopulate()</technical_language>

Target:
public VdcActionParametersBase getParameters(VM incoming, org.ovirt.engine.core.common.businessentities.VM entity) { VmStatic updated = getMapper(modelType, VmStatic.class).map(incoming, entity.getStaticData()); updated.setUsbPolicy(VmMapper.getUsbPolicyOnUpdate(incoming.getUsb(), entity.getUsbPolicy(), lookupCluster(updated.getVdsGroupId()))); VmManagementParametersBase params = new VmManagementParametersBase(updated); if (incoming.isSetPayloads()) { if (incoming.isSetPayloads() && incoming.getPayloads().isSetPayload()) { params.setVmPayload(parent.getPayload(incoming)); } else { params.setClearPayload(true); } } if (incoming.isSetMemoryPolicy() && incoming.getMemoryPolicy().isSetBallooning()) { params.setBalloonEnabled(incoming.getMemoryPolicy().isBallooning()); } if (incoming.isSetConsole() && incoming.getConsole().isSetEnabled()) { params.setConsoleEnabled(incoming.getConsole().isEnabled()); } return params; }
Source:
<code>public static ViewerSorter createProjectTreeSorter(final ILabelProvider labelProvider) { final ProjectViewerComparator projectComparator = new ProjectViewerComparator(labelProvider); return new ViewerSorter() { @SuppressWarnings("unchecked") @Override public int compare(Viewer viewer, Object e1, Object e2) { if(e1 instanceof ObservableTreeItem && e2 instanceof ObservableTreeItem) { Object o1 = ((ObservableTreeItem) e1).getModel(); Object o2 = ((ObservableTreeItem) e2).getModel(); if(o1 instanceof IProject && o2 instanceof IProject) { <START> return projectComparator.compare(viewer, e1, e2); <END> } else if(labelProvider != null) { return labelProvider.getText(o1).compareTo(labelProvider.getText(o2)); } else if(o1 instanceof IResource && o2 instanceof IResource) { String name1 = ((IResource) o1).getName(); String name2 = ((IResource) o2).getName(); return getComparator().compare(name1, name2); } } return super.compare(viewer, e1, e2); } }; }</code><technical_language>this branch is covered tests</technical_language>

Target:
public static ViewerComparator createProjectTreeSorter(final ILabelProvider labelProvider) { final ProjectViewerComparator projectComparator = new ProjectViewerComparator(labelProvider); return new ViewerComparator() { @SuppressWarnings("unchecked") @Override public int compare(Viewer viewer, Object e1, Object e2) { if(e1 instanceof ObservableTreeItem && e2 instanceof ObservableTreeItem) { Object o1 = ((ObservableTreeItem) e1).getModel(); Object o2 = ((ObservableTreeItem) e2).getModel(); if(o1 instanceof IProject && o2 instanceof IProject) { return projectComparator.compare(viewer, o1, o2); } else if(labelProvider != null) { return labelProvider.getText(o1).compareTo(labelProvider.getText(o2)); } else if(o1 instanceof IResource && o2 instanceof IResource) { String name1 = ((IResource) o1).getName(); String name2 = ((IResource) o2).getName(); return getComparator().compare(name1, name2); } } return super.compare(viewer, e1, e2); } }; }