auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>SqlArrayArgument(SqlArrayType<T> arrayType, Object newArray) { this.typeName = arrayType.getTypeName(); List<Object> elements = new ArrayList<>(newArray.getClass().isArray() ? Array.getLength(newArray) : 10); <START> IterableLike.of(newArray).forEachRemaining(e -> { <END> @SuppressWarnings("unchecked") T cast = (T) e; elements.add(arrayType.convertArrayElement(cast)); }); array = elements.toArray(); }</code><technical_language>in this refactoring? wordier now. This improvement missing something. duplicated some code previously factored out (the lookup function)</technical_language>

Target:
SqlArrayArgument(SqlArrayType<T> arrayType, Object newArray) { this.typeName = arrayType.getTypeName(); @SuppressWarnings("unchecked") Stream<T> stream = (Stream<T>) IterableLike.stream(newArray); array = stream.map(arrayType::convertArrayElement).toArray(); }
Source:
<code>private static TestingHttpServer createServer(final TestResource resource) { try { return new Bootstrap( new TestingNodeModule(), new JaxrsModule(true), new JsonModule(), new TestingHttpServerModule(), binder -> jaxrsBinder(binder).bindInstance(resource)) .strictConfig() .doNotInitializeLogging() .quiet() .initialize() .getInstance(TestingHttpServer.class); } catch (Exception e) { <START> throw new RuntimeException(e); <END> } }</code><technical_language>This wrapping strange. add a variable for Bootstrap</technical_language>

Target:
private static TestingHttpServer createServer(final TestResource resource) { try { List<Module> modules = ImmutableList.<Module>builder() .add(new TestingNodeModule()) .add(new JaxrsModule(true)) .add(new JsonModule()) .add(new TestingHttpServerModule()) .add(binder -> jaxrsBinder(binder).bindInstance(resource)) .build(); return new Bootstrap(modules) .strictConfig() .doNotInitializeLogging() .quiet() .initialize() .getInstance(TestingHttpServer.class); } catch (Exception e) { throwIfUnchecked(e); throw new RuntimeException(e); } }
Source:
<code>public T getAndRemove(Predicate<T> preCondition) { Iterator<T> iterator = deque.iterator(); T found = null; for (int i = 0; i < deque.size(); i++) { T next = iterator.next(); if (preCondition.test(next)) { if (i < numPriorityElements) { numPriorityElements--; } found = next; checkState(deque.remove(found)); } } <START> return checkNotNull(found); <END> }</code><technical_language>return Nullable check call-site for non-null? function a bit more versatily more in line Collection methods</technical_language>

Target:
public T getAndRemove(Predicate<T> preCondition) { Iterator<T> iterator = deque.iterator(); for (int i = 0; i < deque.size(); i++) { T next = iterator.next(); if (preCondition.test(next)) { if (i < numPriorityElements) { numPriorityElements--; } iterator.remove(); return next; } } throw new NoSuchElementException(); }
Source:
<code><START> public AbstractSegmentBaseStateSystemAnalysis() { <END> registerListener(); }</code><technical_language>call super()</technical_language>

Target:
public AbstractSegmentBaseStateSystemAnalysis() { super(); registerListener(); }
Source:
<code>private void doTaskFailed(Throwable exception) { if(started) { this.taskExecution.setEndTime(new Date()); this.taskExecution.setExitCode(1); this.taskExecution.setExitMessage(stackTraceToString(exception)); taskRepository.update(taskExecution); } else { <START> logger.warn("An event to fail a task has been received for a task that has " + <END> "not yet started."); } }</code><technical_language>log error possibly. Thoughts</technical_language>

Target:
private void doTaskFailed(Throwable exception) { if(started) { this.taskExecution.setEndTime(new Date()); this.taskExecution.setExitCode(1); this.taskExecution.setExitMessage(stackTraceToString(exception)); taskRepository.update(taskExecution); } else { logger.error("An event to fail a task has been received for a task that has " + "not yet started."); } }
Source:
<code><START> private Boolean isHeartBeating() throws Exception { <END> Stat stat = this.clClient.checkExists().forPath(clConfig.getWorkerNodePath()); return (null != stat); }</code><technical_language>this boolean (with a small b)</technical_language>

Target:
private boolean isHeartBeating() throws Exception { Stat stat = this.clClient.checkExists().forPath(clConfig.getWorkerNodePath()); return (null != stat); }
Source:
<code>public PinotFilterExpressionConverter(TypeManager typeManager, FunctionMetadataManager functionMetadataManager, StandardFunctionResolution standardFunctionResolution) { this.typeManager = typeManager; this.functionMetadataManager = functionMetadataManager; this.standardFunctionResolution = standardFunctionResolution; <START> } <END></code><technical_language>need put requireNonNull here: requireNonNull(typeManger, "typeManager is null"); ..</technical_language>

Target:
public PinotFilterExpressionConverter( TypeManager typeManager, FunctionMetadataManager functionMetadataManager, StandardFunctionResolution standardFunctionResolution) { this.typeManager = requireNonNull(typeManager, "type manager is null"); this.functionMetadataManager = requireNonNull(functionMetadataManager, "function metadata manager is null"); this.standardFunctionResolution = requireNonNull(standardFunctionResolution, "standardFunctionResolution is null"); }
Source:
<code>private boolean initCheckTypeModifiers() { <START> if (Reflections.isClassLoadable(CLASSINFO_CLASS_NAME, new ClassLoaderResourceLoader(classFileServices.getClass().getClassLoader()))) { <END> try { Class<?> classInfoclass = Reflections.loadClass(CLASSINFO_CLASS_NAME, new ClassLoaderResourceLoader(classFileServices.getClass().getClassLoader())); Method setFlags = AccessController.doPrivileged(GetDeclaredMethodAction.of(classInfoclass, "setFlags", short.class)); return setFlags != null; } catch (Exception exceptionIgnored) { return false; } } else { return true; } }</code><technical_language>I try load class if null try find method - right now, ClassLoaderResourceLoader is created ResourceLoader.classForName(String)}} is invoked twice</technical_language>

Target:
private boolean initCheckTypeModifiers() { Class<?> classInfoclass = Reflections.loadClass(CLASSINFO_CLASS_NAME, new ClassLoaderResourceLoader(classFileServices.getClass().getClassLoader())); if (classInfoclass != null) { try { Method setFlags = AccessController.doPrivileged(GetDeclaredMethodAction.of(classInfoclass, "setFlags", short.class)); return setFlags != null; } catch (Exception exceptionIgnored) { BootstrapLogger.LOG.usingOldJandexVersion(); return false; } } else { return true; } }
Source:
<code>private String overrideSiteId(HttpServletRequest request, String siteId) { if (siteId.equals("!error")) { <START> siteId = request.getContextPath().split("/portal")[1]; <END> } return siteId; }</code><technical_language>Array access check based request a NullPointerException waiting happen</technical_language>

Target:
private String overrideSiteId(HttpServletRequest request, String siteId) { if (siteId.equals("!error")) { return request.getContextPath(); } return siteId; }
Source:
<code>private boolean updateVms() { for (VmStatic vm : vmsLockedForUpdate) { VmManagementParametersBase updateParams = new VmManagementParametersBase(vm); updateParams.setLockProperties(LockProperties.create(LockProperties.Scope.None)); updateParams.setClusterLevelChangeFromVersion(oldCluster.getCompatibilityVersion()); upgradeGraphicsDevices(vm, updateParams); updateRngDeviceIfNecessary(vm.getId(), vm.getCustomCompatibilityVersion(), updateParams); VdcReturnValueBase result = runInternalAction( VdcActionType.UpdateVm, updateParams, cloneContextAndDetachFromParent()); if (!result.getSucceeded()) { List<String> params = new ArrayList<>(); params.add("$action Update"); params.add("$type VM"); params.add(parseErrorMessage(result.getValidationMessages())); List<String> messages = Backend.getInstance().getErrorsTranslator().translateErrorText(params); failedUpgradeVms.put(vm.getName(), <START> messages.get(0)); <END> } } return true; }</code><technical_language>hmmm, is messages empty</technical_language>

Target:
private boolean updateVms() { for (VmStatic vm : vmsLockedForUpdate) { VmManagementParametersBase updateParams = new VmManagementParametersBase(vm); updateParams.setLockProperties(LockProperties.create(LockProperties.Scope.None)); updateParams.setClusterLevelChangeFromVersion(oldCluster.getCompatibilityVersion()); upgradeGraphicsDevices(vm, updateParams); updateRngDeviceIfNecessary(vm.getId(), vm.getCustomCompatibilityVersion(), updateParams); VdcReturnValueBase result = runInternalAction( VdcActionType.UpdateVm, updateParams, cloneContextAndDetachFromParent()); if (!result.getSucceeded()) { List<String> params = new ArrayList<>(); params.add("$action Update"); params.add("$type VM"); params.add(parseErrorMessage(result.getValidationMessages())); List<String> messages = Backend.getInstance().getErrorsTranslator().translateErrorText(params); failedUpgradeEntities.put(vm.getName(), getFailedMessage(messages)); } } return true; }
Source:
<code>public SimplePatientCorrelationResponseType addPatientCorrelationPLQ(AddPatientCorrelationPLQRequestType request) { SimplePatientCorrelationResponseType response = new SimplePatientCorrelationResponseType(); PatientCorrelationPLQHelper.addPatientCorrelationPLQRecords(request.getPatientLocationQueryResponse()); <START> response.setMessage("It is done."); <END> return response; }</code><technical_language>Remove this message set more appropriate</technical_language>

Target:
public SimplePatientCorrelationResponseType addPatientCorrelationPLQ(AddPatientCorrelationPLQRequestType request) { SimplePatientCorrelationResponseType response = new SimplePatientCorrelationResponseType(); PatientCorrelationPLQHelper.addPatientCorrelationPLQRecords(request.getPatientLocationQueryResponse()); response.setMessage("Response has been received and processed."); return response; }
Source:
<code>public static Map<Integer, Integer> getCategoricalFeatureInfo(Schema inputSchema, @Nullable String featuresToInclude, @Nullable String featuresToExclude, String labelField, @Nullable String cardinalityMapping) { List<String> featureList = getFeatureList(inputSchema, featuresToInclude, featuresToExclude, labelField); Map<Integer, Integer> outputFieldMappings = new HashMap<>(); if (!Strings.isNullOrEmpty(cardinalityMapping)) { return outputFieldMappings; } try { Map<String, String> map = Splitter.on(',').trimResults().withKeyValueSeparator(":").split(cardinalityMapping); for (String field : map.keySet()) { <START> String value = map.get(field); <END> try { outputFieldMappings.put(featureList.indexOf(field), Integer.parseInt(value)); } catch (NumberFormatException e) { throw new IllegalArgumentException( String.format("Invalid cardinality %s. Please specify valid integer for cardinality", value)); } } } catch (IllegalArgumentException e) { throw new IllegalArgumentException( String.format("Invalid categorical feature mapping. %s. Please make sure it is in the format " + "'feature':'cardinality'.", e.getMessage()), e); } return outputFieldMappings; }</code><technical_language>Instead of looping key set call get, iterate entry set. java for (Map.Entry<String, String> entry : map.entrySet()) { ... }</technical_language>

Target:
static Map<Integer, Integer> getCategoricalFeatureInfo(Schema inputSchema, @Nullable String featuresToInclude, @Nullable String featuresToExclude, String labelField, @Nullable String cardinalityMapping) { Map<String, Integer> featureList = getFeatureList(inputSchema, featuresToInclude, featuresToExclude, labelField); Map<Integer, Integer> outputFieldMappings = new HashMap<>(); if (Strings.isNullOrEmpty(cardinalityMapping)) { return outputFieldMappings; } try { Map<String, String> map = Splitter.on(',').trimResults().withKeyValueSeparator(":").split(cardinalityMapping); for (Map.Entry<String, String> field : map.entrySet()) { String value = field.getValue(); try { outputFieldMappings.put(featureList.get(field.getKey()), Integer.parseInt(value)); } catch (NumberFormatException e) { throw new IllegalArgumentException( String.format("Invalid cardinality %s. Please specify valid integer for cardinality.", value)); } } } catch (IllegalArgumentException e) { throw new IllegalArgumentException( String.format("Invalid categorical feature mapping. %s. Please make sure it is in the format " + "'feature':'cardinality'.", e.getMessage()), e); } return outputFieldMappings; }
Source:
<code>protected synchronized void removeHandler(ThingHandler thingHandler) { if (thingHandler instanceof OwserverBridgeHandler) { ServiceRegistration<?> serviceReg = this.discoveryServiceRegs.get(thingHandler.getThing().getUID()); if (serviceReg != null) { OwDiscoveryService service = (OwDiscoveryService) bundleContext.getService(serviceReg.getReference()); <START> service.deactivate(); <END> serviceReg.unregister(); discoveryServiceRegs.remove(thingHandler.getThing().getUID()); } } }</code><technical_language>is service is null</technical_language>

Target:
protected synchronized void removeHandler(ThingHandler thingHandler) { if (thingHandler instanceof OwserverBridgeHandler) { ServiceRegistration<?> serviceReg = this.discoveryServiceRegs.get(thingHandler.getThing().getUID()); OwDiscoveryService service = (OwDiscoveryService) bundleContext.getService(serviceReg.getReference()); service.deactivate(); serviceReg.unregister(); discoveryServiceRegs.remove(thingHandler.getThing().getUID()); } }
Source:
<code>public void testCreateSecureS3Bucket() throws IOException { long currentTime = Time.now(); String userName = "ozone/localhost@EXAMPLE.COM"; String bucketName = UUID.randomUUID().toString(); <START> String md5Hash = DigestUtils.md5Hex(userName); <END> store.createS3Bucket(md5Hash, bucketName); String volumeName = store.getOzoneVolumeName(bucketName); assertEquals(volumeName,"s3" + md5Hash); OzoneVolume volume = store.getVolume(volumeName); OzoneBucket bucket = volume.getBucket(bucketName); Assert.assertEquals(bucketName, bucket.getName()); Assert.assertTrue(bucket.getCreationTime() >= currentTime); Assert.assertTrue(volume.getCreationTime() >= currentTime); }</code><technical_language>call OzoneS3Util.getVolumeName()</technical_language>

Target:
public void testCreateSecureS3Bucket() throws IOException { long currentTime = Time.now(); String userName = "ozone/localhost@EXAMPLE.COM"; String bucketName = UUID.randomUUID().toString(); String s3VolumeName = OzoneS3Util.getVolumeName(userName); store.createS3Bucket(s3VolumeName, bucketName); String volumeName = store.getOzoneVolumeName(bucketName); assertEquals(volumeName, "s3" + s3VolumeName); OzoneVolume volume = store.getVolume(volumeName); OzoneBucket bucket = volume.getBucket(bucketName); Assert.assertEquals(bucketName, bucket.getName()); Assert.assertTrue(bucket.getCreationTime() >= currentTime); Assert.assertTrue(volume.getCreationTime() >= currentTime); }
Source:
<code>public static int get(final String key) { <START> return map.containsKey(key)? map.get(key) : -1; <END> }</code><technical_language>1 is invalid - default R.string.na that. Shortened error below: android.content.res.Resources$NotFoundException: String resource ID #0xffffffff</technical_language>

Target:
public static int get(final String key) { return map.containsKey(key)? map.get(key) : R.string.unknown; }
Source:
<code>protected void onPostExecute(List<ApplicationInfoEx> listApp) { super.onPostExecute(listApp); mAppAdapter = new AppListAdapter(ActivityMain.this, R.layout.mainentry, listApp, mRestrictionName); ListView lvApp = (ListView) findViewById(R.id.lvApp); lvApp.setAdapter(mAppAdapter); <START> applyFilter(); <END> mProgressDialog.setMessage(getString(R.string.msg_filtering)); ActivityMain.this.selectRestriction(spRestriction.getSelectedItemPosition()); }</code><technical_language>_applyFilter_ is called _selectRestriction_</technical_language>

Target:
protected void onPostExecute(List<ApplicationInfoEx> listApp) { super.onPostExecute(listApp); mAppAdapter = new AppListAdapter(ActivityMain.this, R.layout.mainentry, listApp, mRestrictionName); ListView lvApp = (ListView) findViewById(R.id.lvApp); lvApp.setAdapter(mAppAdapter); try { mProgressDialog.dismiss(); } catch (Throwable ex) { Util.bug(null, ex); } ActivityMain.this.selectRestriction(spRestriction.getSelectedItemPosition()); }
Source:
<code>static List<Job> getTopologyJobs(NomadApiClient apiClient, String topologyName) { List<JobListStub> jobs = getJobList(apiClient); List<Job> ret = new LinkedList<>(); for (JobListStub job : jobs) { Job jobActual; try { jobActual = apiClient.getJobsApi().info(job.getId()).getValue(); } catch (IOException | NomadException e) { String msg = "Failed to retrieve job info for job " + job.getId() + " part of topology " + topologyName; LOG.log(Level.SEVERE, msg, e); throw new RuntimeException(msg, e); } Map<String, String> metaData = jobActual.getMeta(); if (metaData != null) { <START> if (metaData.get(NomadConstants.NOMAD_TOPOLOGY_NAME).equals(topologyName)) { <END> ret.add(jobActual); } } } return ret; }</code><technical_language>metaData.get return null</technical_language>

Target:
static List<Job> getTopologyJobs(NomadApiClient apiClient, String topologyName) { List<JobListStub> jobs = getJobList(apiClient); List<Job> ret = new LinkedList<>(); for (JobListStub job : jobs) { Job jobActual; try { jobActual = apiClient.getJobsApi().info(job.getId()).getValue(); } catch (IOException | NomadException e) { String msg = "Failed to retrieve job info for job " + job.getId() + " part of topology " + topologyName; LOG.log(Level.SEVERE, msg, e); throw new RuntimeException(msg, e); } Map<String, String> metaData = jobActual.getMeta(); if (metaData != null && metaData.containsKey(NomadConstants.NOMAD_TOPOLOGY_NAME)) { if (metaData.get(NomadConstants.NOMAD_TOPOLOGY_NAME).equals(topologyName)) { ret.add(jobActual); } } } return ret; }
Source:
<code>public Stream<QueryTerminationResult> killQuery( @Name( "id" ) String idText ) throws InvalidArgumentsException, IOException { securityContext.assertCredentialsNotExpired(); try { long queryId = fromExternalString( idText ).kernelQueryId(); Set<Pair<KernelTransactionHandle,ExecutingQuery>> querys = getActiveTransactions( tx -> executingQueriesWithId( queryId, tx ) ).collect( toSet() ); <START> Config configs = resolver.resolveDependency( Config.class ); <END> if ( configs.get( GraphDatabaseSettings.kill_query_verbose ) && querys.isEmpty() ) { return Stream.<QueryTerminationResult>builder().add( new QueryFailedTerminationResult( fromExternalString( idText ) ) ).build(); } return querys.stream().map( catchThrown( InvalidArgumentsException.class, this::killQueryTransaction ) ); } catch ( UncaughtCheckedException uncaught ) { throwIfPresent( uncaught.getCauseIfOfType( InvalidArgumentsException.class ) ); throw uncaught; } }</code><technical_language>need find setting once, right? Do need do for call killQuery</technical_language>

Target:
public Stream<QueryTerminationResult> killQuery( @Name( "id" ) String idText ) throws InvalidArgumentsException, IOException { securityContext.assertCredentialsNotExpired(); try { long queryId = fromExternalString( idText ).kernelQueryId(); Set<Pair<KernelTransactionHandle,ExecutingQuery>> querys = getActiveTransactions( tx -> executingQueriesWithId( queryId, tx ) ).collect( toSet() ); boolean killQueryVerbose = resolver.resolveDependency( Config.class ).get( GraphDatabaseSettings.kill_query_verbose ); if ( killQueryVerbose && querys.isEmpty() ) { return Stream.<QueryTerminationResult>builder().add( new QueryFailedTerminationResult( fromExternalString( idText ) ) ).build(); } return querys.stream().map( catchThrown( InvalidArgumentsException.class, this::killQueryTransaction ) ); } catch ( UncaughtCheckedException uncaught ) { throwIfPresent( uncaught.getCauseIfOfType( InvalidArgumentsException.class ) ); throw uncaught; } }
Source:
<code>public void shouldGet404WhenRetrievingNonExistentNode() throws Exception { gen.get() .expectedStatus( 404 ) <START> .get( nodeUri + "600000" ); <END> }</code><technical_language>This out of nowhere</technical_language>

Target:
public void shouldGet404WhenRetrievingNonExistentNode() throws Exception { gen.get() .expectedStatus( 404 ) .get( nodeUri + "123456" ); }
Source:
<code><START> public void skipCreateInitialFilter(String filterName) {logInfo("016","skip create initial filter, filter with this name already exists: {}", filterName); } <END></code><technical_language>Please format code properly: 1. logInfo call a new line, closing curly brace. 2. repfrase log message following: * Skip initial filter creation, Filter this name exists: suggestion public void skipCreateInitialFilter(String filterName) { logInfo("016", "Skip initial filter creation, Filter this name exists: {}", filterName); }</technical_language>

Target:
public void skipCreateInitialFilter(String filterName) { logInfo("016", "Skip initial filter creation, the filter with this name already exists: {}", filterName); }
Source:
<code>private static List<String> innerInitRange(int stopAfter, long startNum, long endNum) { if (startNum > endNum) { return Collections.emptyList(); } <START> List<String> macAddresses = new ArrayList<>(Math.min(stopAfter, (int)(endNum - startNum))); <END> for (long i = startNum; i <= endNum; i++) { if ((MAC_ADDRESS_MULTICAST_BIT & i) != 0) { continue; } macAddresses.add(macAddressToString(i)); if (stopAfter-- <= 0) { return macAddresses; } } return new ArrayList<>(macAddresses); }</code><technical_language>LinkedList is more here</technical_language>

Target:
private static List<String> innerInitRange(int stopAfter, long startNum, long endNum) { if (startNum > endNum) { return Collections.emptyList(); } List<String> macAddresses = new LinkedList<>(); for (long i = startNum; i <= endNum; i++) { if ((MAC_ADDRESS_MULTICAST_BIT & i) != 0) { continue; } macAddresses.add(macAddressToString(i)); if (stopAfter-- <= 0) { return macAddresses; } } return macAddresses; }
Source:
<code>public void callService(VM vm, String vdc, ProductRelease product, String action, String token) throws InstallatorException, NodeExecutionException { try { generateFilesinPuppetMaster (vm, vdc, product, action, token); } catch (InstallatorException e) { log.warn ("It is not possible to generate the manifests in the puppet master " + e.getMessage()); throw new InstallatorException(e.getMessage()); } try { isRecipeExecuted(vm,product.getProduct().getName(),token); } catch (NodeExecutionException e) { log.debug(e.getMessage()); throw new NodeExecutionException(e.getMessage()); } try { isRecipeExecuted(vm,product.getProduct().getName(),token); } catch (NodeExecutionException e) { <START> log.warn ("It is not possible execute the recipe " + product.getProduct().getName() + " in node " + vm.getHostname() ); <END> } }</code><technical_language>In puppet related logs, talk manifests instead of recipes</technical_language>

Target:
public void callService(VM vm, String vdc, ProductRelease product, String action, String token) throws InstallatorException, NodeExecutionException { try { generateFilesinPuppetMaster (vm, vdc, product, action, token); } catch (InstallatorException e) { log.warn ("It is not possible to generate the manifests in the puppet master " + e.getMessage()); throw new InstallatorException(e.getMessage()); } try { isRecipeExecuted(vm,product.getProduct().getName(),token); } catch (NodeExecutionException e) { log.debug(e.getMessage()); throw new NodeExecutionException(e.getMessage()); } try { isRecipeExecuted(vm,product.getProduct().getName(),token); } catch (NodeExecutionException e) { log.warn ("It is not possible execute the module " + product.getProduct().getName() + " in node " + vm.getHostname() ); } }
Source:
<code>private void readResourceServerConfig(OperationContext context, ModelNode operation) { <START> final PathAddress address = PathAddress.pathAddress(operation.require(OP_ADDR)); <END> final String hostName = address.getElement(0).getValue(); final PathElement element = address.getLastElement(); final String serverName = element.getValue(); final ModelNode addr = new ModelNode(); addr.add(HOST, hostName); addr.add(SERVER_CONFIG, serverName); context.readResourceFromRoot(PathAddress.pathAddress(addr), false); }</code><technical_language>This context.getCurrentAddress(). a minor thing, I want eliminate handlers parsing of address op code base</technical_language>

Target:
private void readResourceServerConfig(OperationContext context, ModelNode operation) { final PathAddress address = context.getCurrentAddress(); final String hostName = address.getElement(0).getValue(); final PathElement element = address.getLastElement(); final String serverName = element.getValue(); final ModelNode addr = new ModelNode(); addr.add(HOST, hostName); addr.add(SERVER_CONFIG, serverName); context.readResourceFromRoot(PathAddress.pathAddress(addr), false); }
Source:
<code><START> private void deleteFeatureFolders(IFolder sourceFolder, ArrayList<String> removedFeatures) { <END> final ArrayList<IResource> featureFolders = new ArrayList<IResource>(); try { Collections.addAll(featureFolders, sourceFolder.members()); } catch (final CoreException e) { e.printStackTrace(); } final ArrayList<IResource> foldersToDelete = new ArrayList<IResource>(); for (final String feature : removedFeatures) { for (final IResource folder : featureFolders) { if (folder.getName().equals(feature)) { foldersToDelete.add(folder); } } } for (final IResource folder : foldersToDelete) { try { folder.delete(true, null); } catch (final CoreException e) { e.printStackTrace(); } } }</code><technical_language>complicated. Is necessary create intermediate lists</technical_language>

Target:
private void deleteFeatureFolders(IFolder sourceFolder, ArrayList<String> removedFeatures) { final ArrayList<IResource> featureFolders = new ArrayList<IResource>(); try { Collections.addAll(featureFolders, sourceFolder.members()); } catch (final CoreException e) { e.printStackTrace(); } for (final String feature : removedFeatures) { for (final IResource folder : featureFolders) { if (folder.getName().equals(feature)) { try { folder.delete(true, null); } catch (final CoreException e) { e.printStackTrace(); } } } } }
Source:
<code>protected void afterTest() { sharedBuilder = null; final int pending = messagesPending.get(); final int pendingDeferred = messagesDeferredPending.get().size(); if (pending < 1 && pendingDeferred < 1) { dispose(receiver, sender, receiveAndDeleteReceiver); return; } try { if (pending > 0) { receiveAndDeleteReceiver.receive() .map(message -> { logger.info("Message received: {}", message.getMessage().getSequenceNumber()); return message; }) .timeout(Duration.ofSeconds(15), Mono.empty()) .blockLast(); } <START> if (pendingDeferred > 0) { <END> for(Long sequenceNumber: messagesDeferredPending.get()) { receiveAndDeleteReceiver.receiveDeferredMessage(sequenceNumber) .map(message -> { logger.info("Message received: {}", message.getSequenceNumber()); return message; }) .timeout(Duration.ofSeconds(15), Mono.empty()) .block(); } } } catch (Exception e) { logger.warning("Error occurred when draining queue.", e); } finally { dispose(receiver, sender, receiveAndDeleteReceiver); } }</code><technical_language>a try-catch finally block. if pending > 0 portion throws exception, I want messagesDeferrenedPending run</technical_language>

Target:
protected void afterTest() { sharedBuilder = null; final int pending = messagesPending.get(); final int pendingDeferred = messagesDeferredPending.size(); if (pending < 1 && pendingDeferred < 1) { dispose(receiver, sender, receiveAndDeleteReceiver); return; } try { if (pending > 0) { receiveAndDeleteReceiver.receive() .map(message -> { logger.info("Message received: {}", message.getMessage().getSequenceNumber()); return message; }) .timeout(Duration.ofSeconds(15), Mono.empty()) .blockLast(); } } catch (Exception e) { logger.warning("Error occurred when draining queue.", e); } try { if (pendingDeferred > 0) { for (Long sequenceNumber : messagesDeferredPending) { receiveAndDeleteReceiver.receiveDeferredMessage(sequenceNumber) .map(message -> { logger.info("Message received: {}", message.getSequenceNumber()); return message; }) .timeout(Duration.ofSeconds(15), Mono.empty()) .block(); } } } catch (Exception e) { logger.warning("Error occurred when draining for deferred messages.", e); } finally { dispose(receiver, sender, receiveAndDeleteReceiver); } }
Source:
<code>public void missingConfigThrowsException() { ModuleDefinition moduleDefinition = ModuleDefinitions.simple("missing", ModuleType.processor, "classpath:/ModuleFactoryTests/modules/processor/missing"); <START> ModuleDescriptor moduleDescriptor = new ModuleDescriptor.Builder() <END> .setModuleDefinition(moduleDefinition) .setModuleName("missing") .setGroup("group") .setModuleDefinition(moduleDefinition) .build(); createResourceConfiguredModule("missing",ModuleType.processor); }</code><technical_language>browsing web interface moment, I moduleDescriptor in test</technical_language>

Target:
public void missingConfigThrowsException() { ModuleDefinition moduleDefinition = ModuleDefinitions.simple("missing", ModuleType.processor, "classpath:/ModuleFactoryTests/modules/processor/missing"); createResourceConfiguredModule("missing",ModuleType.processor); }
Source:
<code>public List<DocumentRevision> deleteDocument(String id) throws ConflictException { ArrayList<DocumentRevision> deleted = new ArrayList<DocumentRevision>(); Cursor cursor = null; try { this.getSQLDatabase().beginTransaction(); final String sql = "SELECT revs.revid FROM docs,revs " + "WHERE revs.doc_id = docs.doc_id " + "AND docs.docid = ? " + "AND deleted = 0 AND revs.sequence NOT IN " + <START> "(SELECT DISTINCT parent FROM revs WHERE parent NOT NULL) "; <END> cursor = this.sqlDb.rawQuery(sql, new String[]{id}); while (cursor.moveToNext()) { String revId = cursor.getString(0); deleted.add(deleteDocument(id, revId)); } this.getSQLDatabase().setTransactionSuccessful(); return deleted; } catch (SQLException sqe) { throw new SQLRuntimeException("SQLException in deleteDocument, not deleting revisions", sqe); } finally { this.getSQLDatabase().endTransaction(); DatabaseUtils.closeCursorQuietly(cursor); } }</code><technical_language>share this SQL query conflicts getConflictsForDocId call</technical_language>

Target:
public List<BasicDocumentRevision> deleteDocument(String id) throws ConflictException { Preconditions.checkNotNull(id, "id can not be null"); ArrayList<BasicDocumentRevision> deleted = new ArrayList<BasicDocumentRevision>(); Cursor cursor = null; try { this.getSQLDatabase().beginTransaction(); final String sql = "SELECT revs.revid FROM docs,revs " + "WHERE revs.doc_id = docs.doc_id " + "AND docs.docid = ? " + "AND deleted = 0 AND revs.sequence NOT IN " + "(SELECT DISTINCT parent FROM revs WHERE parent NOT NULL) "; cursor = this.sqlDb.rawQuery(sql, new String[]{id}); while (cursor.moveToNext()) { String revId = cursor.getString(0); deleted.add(deleteDocument(id, revId)); } this.getSQLDatabase().setTransactionSuccessful(); return deleted; } catch (SQLException sqe) { throw new SQLRuntimeException("SQLException in deleteDocument, not deleting revisions", sqe); } finally { this.getSQLDatabase().endTransaction(); DatabaseUtils.closeCursorQuietly(cursor); } }
Source:
<code>private void makeRequest(URI uri) throws IOException { <START> try(CloseableHttpClient httpclient = HttpClients.createDefault()) { <END> HttpGet request = new HttpGet(uri); HttpResponse response = httpclient.execute(request); assertEquals(200, response.getStatusLine().getStatusCode()); } }</code><technical_language>jerseyclient here</technical_language>

Target:
private void makeRequest(URI uri) throws IOException { Client client = ClientBuilder.newClient(); WebTarget target = client.target(uri); Response response = target.request(MediaType.APPLICATION_JSON_TYPE).get(); assertEquals(200, response.getStatus()); }
Source:
<code>protected boolean checkPostConditions( final ResourceStoreRequest request, final StorageItem item ) throws IllegalOperationException, ItemNotFoundException, AccessDeniedException { if ( getRequestProcessors().size() > 0 ) { for ( RequestProcessor processor : getRequestProcessors().values() ) { if ( !processor.shouldRetrieve( this, request, item ) ) { request.addItemNotFoundReason( reasonFor( request, this, "Retrieval of request %s in repository %s prevented.", request.getRequestPath(), <START> RepositoryStringUtils.getHumanizedNameString( this ) ) ); <END> return false; } } } return true; }</code><technical_language>additional information message provide? add info processor, if is relevant user, provide additional info</technical_language>

Target:
protected void checkPostConditions( final ResourceStoreRequest request, final StorageItem item ) throws IllegalOperationException, ItemNotFoundException { final Map<String, RequestStrategy> effectiveRequestStrategies = getRegisteredStrategies(); for ( RequestStrategy strategy : effectiveRequestStrategies.values() ) { strategy.onServing( this, request, item ); } }
Source:
<code>void sendSelection (long id, long sel, long arg) { panel.validateVisibleColumns(); <START> if (filterExtensions.length > 0){ <END> setAllowedFileType(filterExtensions[(int) popup.indexOfSelectedItem()]); } }</code><technical_language>add single space '{'</technical_language>

Target:
void sendSelection (long id, long sel, long arg) { panel.validateVisibleColumns(); if (filterExtensions != null && filterExtensions.length > 0) { setAllowedFileType(filterExtensions[(int) popup.indexOfSelectedItem()]); } }
Source:
<code>public void paperTag(ReplaceableTagEvent event) { if (!event.matches("paper") || event.replaced()) { return; } Attribute attribute = event.getAttributes().fulfill(1); if (attribute.startsWith("tick_times")) { ListTag list = new ListTag(); for (long time : Bukkit.getServer().getTickTimes()) { <START> list.add(String.valueOf(time / 1000000D)); <END> } event.setReplacedObject(list.getObjectAttribute(attribute.fulfill(1))); return; } }</code><technical_language>If this is a representation of a time duration, this a DurationTag</technical_language>

Target:
public void paperTag(ReplaceableTagEvent event) { if (!event.matches("paper") || event.replaced()) { return; } Attribute attribute = event.getAttributes().fulfill(1); if (attribute.startsWith("tick_times")) { ListTag list = new ListTag(); for (long time : Bukkit.getServer().getTickTimes()) { list.addObject(new DurationTag(time / 1000000000D)); } event.setReplacedObject(list.getObjectAttribute(attribute.fulfill(1))); return; } }
Source:
<code>public void verifyAccessibleForCurrentUserAsInstructorOrTeamMember(AccountAttributes account, String courseId, <START> String section, String email) { <END> if (!isValidInstructor(section, courseId, account) && !isValidStudent(email, courseId, account)) { throw new UnauthorizedAccessException("User is not in the course that student belongs to"); } }</code><technical_language>Unnecessary indentation change. revert 8-space indentation before</technical_language>

Target:
public void verifyAccessibleForCurrentUserAsInstructorOrTeamMember(AccountAttributes account, String courseId, String section, String email) { InstructorAttributes instructor = instructorsLogic.getInstructorForGoogleId(courseId, account.googleId); if (instructor != null) { verifyInstructorCanViewPhoto(instructor, section); return; } StudentAttributes student = studentsLogic.getStudentForCourseIdAndGoogleId(courseId, account.googleId); if (student != null) { verifyStudentCanViewPhoto(student, courseId, email); return; } throw new UnauthorizedAccessException("User is not in the course that student belongs to"); }
Source:
<code>private void prepareInsertExistingTable(HdfsContext context, TableAndMore tableAndMore) { deleteOnly = false; Table table = tableAndMore.getTable(); <START> Table tableOld = delegate.getTable(table.getDatabaseName(), table.getTableName()) <END> .orElseThrow(() -> new TableNotFoundException(new SchemaTableName(table.getDatabaseName(), table.getTableName()))); Path targetPath = new Path(table.getStorage().getLocation()); Path currentPath = tableAndMore.getCurrentLocation().get(); cleanUpTasksForAbort.add(new DirectoryCleanUpTask(context, targetPath, false)); if (!targetPath.equals(currentPath)) { asyncRename(hdfsEnvironment, renameExecutor, fileRenameCancelled, fileRenameFutures, context, currentPath, targetPath, tableAndMore.getFileNames().get()); } if (tableAndMore.getStatisticsUpdate().isPresent()) { StatisticsUpdate statisticsUpdate = tableAndMore.getStatisticsUpdate().get(); updateStatisticsOperations.add( new UpdateStatisticsOperation( new SchemaTableName(table.getDatabaseName(), table.getTableName()), Optional.empty(), statisticsUpdate.getStatistics(), statisticsUpdate.getOperator())); } }</code><technical_language>This variable is unused. Remove</technical_language>

Target:
private void prepareInsertExistingTable(HdfsContext context, TableAndMore tableAndMore) { deleteOnly = false; Table table = tableAndMore.getTable(); Path targetPath = new Path(table.getStorage().getLocation()); Path currentPath = tableAndMore.getCurrentLocation().get(); cleanUpTasksForAbort.add(new DirectoryCleanUpTask(context, targetPath, false)); if (!targetPath.equals(currentPath)) { asyncRename(hdfsEnvironment, renameExecutor, fileRenameCancelled, fileRenameFutures, context, currentPath, targetPath, tableAndMore.getFileNames().get()); } if (tableAndMore.getStatisticsUpdate().isPresent()) { updateStatisticsOperations.add( new UpdateStatisticsOperation( new SchemaTableName(table.getDatabaseName(), table.getTableName()), Optional.empty(), tableAndMore.getStatisticsUpdate().get())); } }
Source:
<code>public static Optional<BlockState> addTraits(BlockState state, Map<BlockTrait<?>, Object> traits) { Optional<BlockState> newState = Optional.of(state); for (Map.Entry<BlockTrait<?>, Object> traitEntry : traits.entrySet()) { newState = newState.get().withTrait(traitEntry.getKey(), traitEntry.getValue()); if (!newState.isPresent()) { <START> return newState; <END> } } return newState; }</code><technical_language>check if trait applied if didn't, continue adding remainder of traits</technical_language>

Target:
public static BlockState addTraits(BlockState state, Map<BlockTrait<?>, Object> traits) { Optional<BlockState> nextState; for (Map.Entry<BlockTrait<?>, Object> traitEntry : traits.entrySet()) { nextState = state.withTrait(traitEntry.getKey(), traitEntry.getValue()); if (nextState.isPresent()) { state = nextState.get(); } } return state; }
Source:
<code>public MysqlDaoProvider(DbResourceGroupConfig config) { requireNonNull(config, "DbResourceGroupConfig is null"); MysqlDataSource dataSource = new MysqlDataSource(); dataSource.setURL(requireNonNull(config.getConfigDbUrl(), "resource-groups.config-db-url is null")); this.dao = Jdbi.create(dataSource) .installPlugin(new SqlObjectPlugin()) <START> .open() <END> .attach(ResourceGroupsDao.class); }</code><technical_language>Handle need closed</technical_language>

Target:
public MysqlDaoProvider(DbResourceGroupConfig config) { requireNonNull(config, "DbResourceGroupConfig is null"); MysqlDataSource dataSource = new MysqlDataSource(); dataSource.setURL(requireNonNull(config.getConfigDbUrl(), "resource-groups.config-db-url is null")); this.dao = Jdbi.create(dataSource) .installPlugin(new SqlObjectPlugin()) .onDemand(ResourceGroupsDao.class); }
Source:
<code><START> @Override public <END> EngineBackupLogId getId() { EngineBackupLogId key = new EngineBackupLogId(); key.setDbName(dbName); key.setDoneAt(doneAt); return key; }</code><technical_language>please put @Override a separate line</technical_language>

Target:
public EngineBackupLogId getId() { EngineBackupLogId key = new EngineBackupLogId(); key.setDbName(dbName); key.setDoneAt(doneAt); return key; }
Source:
<code><START> public void setStatus(Status newStatus) { <END> this.status = newStatus; }</code><technical_language>this public. Package visible</technical_language>

Target:
void setStatus(Status newStatus) { this.status = newStatus; }
Source:
<code>private void uploadPatientPhoto(final Patient patient) { RestApi apiService = RestServiceBuilder.createService(RestApi.class); PatientPhoto patientPhoto = new PatientPhoto(); patientPhoto.setPhoto(patient.getPerson().getPhoto()); patientPhoto.setPerson(patient.getPerson()); Call<PatientPhoto> personPhotoCall = apiService.uploadPatientPhoto(patient.getUuid(), patientPhoto); personPhotoCall.enqueue(new Callback<PatientPhoto>() { @Override public void onResponse(Call<PatientPhoto> call, Response<PatientPhoto> response) { if (!response.isSuccessful()) { ToastUtil.error("Patient[" + patient.getId() + "] photo cannot be synced due to server error"+ response.message()); } } @Override public void onFailure(Call<PatientPhoto> call, Throwable t) { <START> ToastUtil.notify("Patient[" + patient.getId() + "] photo cannot be synced due to request error: " + t.toString()); <END> } }); }</code><technical_language>if long messages displayed in toasts. patient id end user</technical_language>

Target:
private void uploadPatientPhoto(final Patient patient) { RestApi apiService = RestServiceBuilder.createService(RestApi.class); PatientPhoto patientPhoto = new PatientPhoto(); patientPhoto.setPhoto(patient.getPerson().getPhoto()); patientPhoto.setPerson(patient.getPerson()); Call<PatientPhoto> personPhotoCall = apiService.uploadPatientPhoto(patient.getUuid(), patientPhoto); personPhotoCall.enqueue(new Callback<PatientPhoto>() { @Override public void onResponse(Call<PatientPhoto> call, Response<PatientPhoto> response) { logger.i(response.message()); if (!response.isSuccessful()) { ToastUtil.error("Patient photo cannot be synced due to server error: "+ response.message()); } } @Override public void onFailure(Call<PatientPhoto> call, Throwable t) { ToastUtil.notify("Patient photo cannot be synced due to error: " + t.toString() ); } }); }
Source:
<code>private boolean hasReviewsIncoming(ITask task) { <START> Set<String> reviewUrls = Collections.emptySet(); END> for (String reviewUrl : reviewUrls) { AbstractRepositoryConnector connector = TasksUiPlugin.getRepositoryManager() .getConnectorForRepositoryTaskUrl(reviewUrl); String taskId = connector.getTaskIdFromTaskUrl(reviewUrl); String repositoryUrl = connector.getRepositoryUrlFromTaskUrl(reviewUrl); ITask reviewTask = taskList.getTask(repositoryUrl, taskId); boolean anyIncomingReviews = (reviewTask.getSynchronizationState().isIncoming()); if (anyIncomingReviews) { return true; } } return false; }</code><technical_language>mapping</technical_language>

Target:
private boolean hasReviewsIncoming(ITask task) { Set<String> reviewUrls = ImmutableSet.copyOf(taskReviewStore.getReviewUrls(task.getUrl())); for (String reviewUrl : reviewUrls) { AbstractRepositoryConnector connector = TasksUiPlugin.getRepositoryManager() .getConnectorForRepositoryTaskUrl(reviewUrl); String taskId = connector.getTaskIdFromTaskUrl(reviewUrl); String repositoryUrl = connector.getRepositoryUrlFromTaskUrl(reviewUrl); ITask reviewTask = taskList.getTask(repositoryUrl, taskId); if ((reviewTask.getSynchronizationState().isIncoming())) { return true; } } return false; }
Source:
<code>private EntityId getMapEntityId(long id) { if (id < (1 << 41)) { if ((id % 2) == 0) { return new EntityId(EntityType.WAY, id >> (BinaryInspector.SHIFT_ID + 1)); } else { return new EntityId(EntityType.NODE, id >> (BinaryInspector.SHIFT_ID + 1)); } } <START> return new EntityId(EntityType.RELATION, id >> (BinaryInspector.SHIFT_ID + 1)); <END> }</code><technical_language>return null is impossible detect</technical_language>

Target:
private EntityId getMapEntityId(long id) { if (id < ID_MULTIPOLYGON_LIMIT) { if ((id % 2) == 0) { return new EntityId(EntityType.NODE, id >> (BinaryInspector.SHIFT_ID + 1)); } else { return new EntityId(EntityType.WAY, id >> (BinaryInspector.SHIFT_ID + 1)); } } return null; }
Source:
<code>public void dispose() { <START> if (diagram.eResource() != null) { <END> diagram.eAdapters().remove(this); } diagram = null; session = null; }</code><technical_language>diagram != null && diagram.eResource != null if dispose is called for example, proposition leads a NPE before</technical_language>

Target:
public void dispose() { if (diagram != null && diagram.eResource() != null) { diagram.eAdapters().remove(this); } diagram = null; session = null; }
Source:
<code>private static String normalizeMd5(String data) throws CorrelationAttributeNormalizationException { final String errorMessage = "Data purporting to be an MD5 was found not to comform to expected format: %s"; if(data == null){ throw new CorrelationAttributeNormalizationException(String.format(errorMessage, data)); } <START> final String validMd5Regex = "^[a-fA-F0-9]{32}$"; <END> final String dataLowered = data.toLowerCase(); if(dataLowered.matches(validMd5Regex)){ return dataLowered; } else { throw new CorrelationAttributeNormalizationException(String.format(errorMessage, data)); } }</code><technical_language>point in matching upper case hex digits convert string case applying regex</technical_language>

Target:
private static String normalizeMd5(String data) throws CorrelationAttributeNormalizationException { final String validMd5Regex = "^[a-f0-9]{32}$"; final String dataLowered = data.toLowerCase(); if(dataLowered.matches(validMd5Regex)){ return dataLowered; } else { throw new CorrelationAttributeNormalizationException(String.format("Data purporting to be an MD5 was found not to comform to expected format: %s", data)); } }
Source:
<code>public void testJobFailure() { String errorMsg = "error_msg"; doThrow(new InstallationException(errorMsg)).when(componentInstaller).install(any(), any()); ComponentInstallationJob job = service.install(new DigitalExchange(), "test"); assertThat(job).isNotNull(); try { Thread.sleep(500); <START> } catch (InterruptedException ex) { <END> } assertThat(job.getStatus()).isEqualTo(InstallationStatus.ERROR); assertThat(job.getErrorMessage()).isEqualTo(errorMsg); }</code><technical_language>rename "ex" "ignored"</technical_language>

Target:
public void testJobFailure() { String errorMsg = "error_msg"; doThrow(new InstallationException(errorMsg)).when(componentInstaller).install(any(), any()); ComponentInstallationJob job = service.install(new DigitalExchange(), "test"); assertThat(job).isNotNull(); try { Thread.sleep(500); } catch (InterruptedException ignored) { } assertThat(job.getStatus()).isEqualTo(InstallationStatus.ERROR); assertThat(job.getErrorMessage()).isEqualTo(errorMsg); }
Source:
<code><START> public void initialize() throws ParseException, RuntimeException { <END> return; }</code><technical_language>I added RuntimeException instead of IdGenerationException. code compile if method signature explicitly throw a RuntimeException</technical_language>

Target:
public void initialize() throws ParseException { return; }
Source:
<code>public void activate(final BundleContext bundleContext, final Map<String, Object> configuration) { this.bundleContext = bundleContext; String refreshIntervalString = (String) configuration.get("refresh"); if (StringUtils.isNotBlank(refreshIntervalString)) { refreshInterval = Long.parseLong(refreshIntervalString); } <START> cmiAddress = (String) configuration.get("cmiAddress"); <END> try { clientSocket = new DatagramSocket(cmiPort); } catch (SocketException e) { e.printStackTrace(); } setProperlyConfigured(true); }</code><technical_language>i assume binding work cmiAddress, right? If yes, please check validity of configuration write some WARN logs if configuration is invalid</technical_language>

Target:
public void activate(final BundleContext bundleContext, final Map<String, Object> configuration) { this.bundleContext = bundleContext; String refreshIntervalString = (String) configuration.get("refresh"); if (StringUtils.isNotBlank(refreshIntervalString)) { refreshInterval = Long.parseLong(refreshIntervalString); } try { cmiAddress = InetAddress .getByName((String) configuration.get("cmiAddress")); } catch (UnknownHostException e1) { logger.error("Failed to get IP of CMI from configuration"); setProperlyConfigured(false); return; } try { clientSocket = new DatagramSocket(cmiPort); } catch (SocketException e) { logger.error("Failed to create Socket for receiving UDP packts from CMI"); setProperlyConfigured(true); return; } setProperlyConfigured(true); }