auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public <T> Pair<Long, T> remove(final String dataType, final Long id) { <END> final String operationId = Long.toString(operationIdCounter.getAndIncrement()); final LongKeyOperation<T> operation = new LongKeyOperation<>(Optional.<String>empty(), operationId, DataOpType.REMOVE, dataType, id, Optional.<T>empty()); executeOperation(operation); final T outputData = operation.getOutputData().get(id); return outputData == null ? null : new Pair<>(id, outputData); }</code><technical_language>change T V</technical_language>

Target:
public <V> Pair<Long, V> remove(final String dataType, final Long id) { final String operationId = Long.toString(operationIdCounter.getAndIncrement()); final LongKeyOperation<V> operation = new LongKeyOperation<>(Optional.<String>empty(), operationId, DataOpType.REMOVE, dataType, id, Optional.<V>empty()); executeOperation(operation); final V outputData = operation.getOutputData().get(id); return outputData == null ? null : new Pair<>(id, outputData); }
Source:
<code>public static void query( AsyncCallback<JsArray<ChangeList>> callback, EnumSet<ListChangesOption> options, String... queries) { assert queries.length >= 2; RestApi call = new RestApi(URI); for (String q : queries) { call.addParameterRaw("q", KeyUtil.encode(q)); } <START> EnumSet<ListChangesOption> o = EnumSet.of(ListChangesOption.LABELS); o.add(ListChangesOption.DETAILED_ACCOUNTS); <END> o.addAll(options); addOptions(call, o); call.get(callback); }</code><technical_language>do in statement (here below): EnumSet<ListChangesOption> o = EnumSet.of(ListChangesOption.LABELS, ListChangesOption.DETAILED_ACCOUNTS);</technical_language>

Target:
public static void query( AsyncCallback<JsArray<ChangeList>> callback, EnumSet<ListChangesOption> options, String... queries) { assert queries.length >= 2; RestApi call = new RestApi(URI); for (String q : queries) { call.addParameterRaw("q", KeyUtil.encode(q)); } OPTIONS.addAll(options); addOptions(call, OPTIONS); call.get(callback); }
Source:
<code>private boolean isUsedByOwner(HypervisorIdDTO hypervisor, Owner owner) { if (hypervisor == null) { return false; } return consumerCurator.getHypervisorsBulk( Collections.singletonList(hypervisor.getHypervisorId()), owner.getOwnerId()) .list() <START> .size() > 0; <END> }</code><technical_language>is a curator interface for querying a single hypervisorId, a singleton list. work: return this.consumerCurator.getHypervisor(hypervisor.getHypervisorId(), owner.getOwnerId()) != null</technical_language>

Target:
private boolean isUsedByOwner(HypervisorIdDTO hypervisor, Owner owner) { if (hypervisor == null) { return false; } return consumerCurator.getHypervisor(hypervisor.getHypervisorId(), owner) != null; }
Source:
<code>private String connectorCancelChargePathFor(String paymentId, String accountId) { <START> return CONNECTOR_CANCEL_CHARGE_PATH.replace("{accountId}", accountId).replace("{chargeId}", paymentId); <END> }</code><technical_language>this String.replace String.format(blah, blah)</technical_language>

Target:
private String connectorCancelChargePathFor(String paymentId, String accountId) { return String.format(CONNECTOR_CANCEL_CHARGE_PATH, accountId, paymentId); }
Source:
<code>protected void postSaveAction(Guid networkGuid, boolean succeeded) { if (succeeded) { if ((Boolean) getIsVmNetwork().getEntity()) { performProfilesActions(networkGuid); } else { <START> stopProgress(); <END> cancel(); } } stopProgress(); }</code><technical_language>call stopProgress now..</technical_language>

Target:
protected void postSaveAction(Guid networkGuid, boolean succeeded) { if (succeeded) { if ((Boolean) getIsVmNetwork().getEntity()) { performProfilesActions(networkGuid); stopProgress(); } else { stopProgress(); cancel(); } } }
Source:
<code>public void validate_shouldPassValidationIfAllFieldsAreCorrect() throws Exception { Order order = new Order(); Encounter encounter = new Encounter(); order.setConcept(Context.getConceptService().getConcept(88)); order.setOrderer(Context.getProviderService().getProvider(1)); Patient patient = Context.getPatientService().getPatient(2); encounter.setPatient(patient); order.setPatient(patient); Calendar cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH) - 1); order.setStartDate(cal.getTime()); order.setDateStopped(new Date()); order.setAutoExpireDate(new Date()); order.setCareSetting(new CareSetting()); order.setEncounter(encounter); order.setUrgency(Order.Urgency.ROUTINE); order.setAction(Order.Action.NEW); <START> order.setOrderType(Context.getOrderService().getOrderTypeByName("Test order")); <END> Errors errors = new BindException(order, "order"); new OrderValidator().validate(order, errors); Assert.assertFalse(errors.hasErrors()); }</code><technical_language>concept id 88 in test dataset is a drug a test, this Drug Order type</technical_language>

Target:
public void validate_shouldPassValidationIfAllFieldsAreCorrect() throws Exception { Order order = new Order(); Encounter encounter = new Encounter(); order.setConcept(Context.getConceptService().getConcept(88)); order.setOrderer(Context.getProviderService().getProvider(1)); Patient patient = Context.getPatientService().getPatient(2); encounter.setPatient(patient); order.setPatient(patient); Calendar cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH) - 1); order.setStartDate(cal.getTime()); order.setDateStopped(new Date()); order.setAutoExpireDate(new Date()); order.setCareSetting(new CareSetting()); order.setEncounter(encounter); order.setUrgency(Order.Urgency.ROUTINE); order.setAction(Order.Action.NEW); order.setOrderType(Context.getOrderService().getOrderTypeByName("Drug order")); Errors errors = new BindException(order, "order"); new OrderValidator().validate(order, errors); Assert.assertFalse(errors.hasErrors()); }
Source:
<code>protected boolean writeFilesToDisk( Bundle bundle, String bundleSource, File to ) { InputStream in = null; OutputStream out = null; try { Enumeration<URL> fileUrls = bundle.findEntries( bundleSource, null, true ); if ( fileUrls == null || !fileUrls.hasMoreElements() ) { return false; } while ( fileUrls.hasMoreElements() ) { URL url = fileUrls.nextElement(); String endPath = url.getFile(); File outFile = new File( to.getAbsolutePath() + endPath.replace( ManagedResourceProvider.MANAGED_RESOURCES_DIR, "" ) ); String fileName = endPath.replaceAll( ".+\\/", "" ); if ( !outFile.exists() ) { if ( !fileName.isEmpty() ) { copyStream( url, outFile.getAbsolutePath() ); } else { outFile.mkdir(); } } } } catch ( FileNotFoundException e ) { e.printStackTrace(); return false; } catch ( IOException e ) { <START> e.printStackTrace(); <END> return false; } finally { try { if ( in != null ) { in.close(); } } catch ( IOException e ) { e.printStackTrace(); } try { if ( out != null ) { out.close(); } } catch ( IOException e ) { e.printStackTrace(); } } return true; }</code><technical_language>log</technical_language>

Target:
protected boolean writeFilesToDisk( Bundle bundle, String bundleSource, File to ) { InputStream in = null; OutputStream out = null; try { Enumeration<URL> fileUrls = bundle.findEntries( bundleSource, null, true ); if ( fileUrls == null || !fileUrls.hasMoreElements() ) { return false; } while ( fileUrls.hasMoreElements() ) { URL url = fileUrls.nextElement(); Path outPath = Paths .get( to.getPath(), url.getFile().replace( ManagedResourceProvider.MANAGED_RESOURCES_DIR, "" ) ); File outFile = outPath.toFile(); String fileName = outPath.getFileName().toString(); if ( !outFile.exists() ) { if ( fileName.matches( ".+\\..+" ) ) { copyStream( url, outFile.getAbsolutePath() ); } else { outFile.mkdir(); } } } } catch ( FileNotFoundException e ) { logger.error( e.getMessage() ); return false; } catch ( IOException e ) { logger.error( e.getMessage() ); return false; } finally { try { if ( in != null ) { in.close(); } } catch ( IOException e ) { logger.error( e.getMessage() ); } try { if ( out != null ) { out.close(); } } catch ( IOException e ) { logger.error( e.getMessage() ); } } return true; }
Source:
<code>static <T> List<T> tabulate(int n, Function<? super Integer, ? extends T> f) { Objects.requireNonNull(f, "f is null"); int nOrZero = java.lang.Math.max(n, 0); @SuppressWarnings("unchecked") T[] elements = (T[]) new Object[nOrZero]; for (int i = 0; i < n; i++) { elements[i] = f.apply(i); } <START> return List.of(elements); <END> }</code><technical_language>optimize this: java Objects.requireNonNull(f, "f is null"); n = n < 0 ? 0 : n; List<T> list = List.empty(); for (int i = n - 1; i >= 0; i--) { list = list.prepend(f.apply(i)); } return list;</technical_language>

Target:
static <T> List<T> tabulate(int n, Function<? super Integer, ? extends T> f) { Objects.requireNonNull(f, "f is null"); n = n < 0 ? 0 : n; @SuppressWarnings("unchecked") T[] elements = (T[]) new Object[n]; for (int i = 0; i < n; i++) { elements[i] = f.apply(i); } return List.of(elements); }
Source:
<code>private void writeOutUsersDotPropertiesFile(File userPropertiesFile) { try { Properties usersDotProperties = new Properties(userPropertiesFile); if (!usersDotProperties.isEmpty()) { String oldHostValue = usersDotProperties.getProperty(oldHostName); if (oldHostValue != null) { String newInternalHost = System.getProperty(SystemBaseUrl.INTERNAL_HOST); String newDataManager = newInternalHost + "-" + DATA_MANAGER; <START> String newHostValue = oldHostValue.replaceAll(LOCALHOST_DATA_MANAGER, newDataManager); <END> usersDotProperties.remove(oldHostName); usersDotProperties.setProperty(newInternalHost, newHostValue); usersDotProperties.save(); } } } catch (IOException e) { LOGGER.warn("Exception while writing to users.properties file.", e); } }</code><technical_language>recommend rid of newDataManager inlining (and String.format instead of concatenation): String newHostValue = oldHostValue.replaceAll(LOCALHOST_DATA_MANAGER, String.format("%s-%s", newInternalHost, DATA_MANAGER));</technical_language>

Target:
private void writeOutUsersDotPropertiesFile(File userPropertiesFile) { try { Properties usersDotProperties = new Properties(userPropertiesFile); if (!usersDotProperties.isEmpty()) { String oldHostValue = usersDotProperties.getProperty(oldHostName); if (oldHostValue != null) { String newInternalHost = System.getProperty(SystemBaseUrl.INTERNAL_HOST); String newHostValue = oldHostValue.replaceAll( LOCALHOST_DATA_MANAGER, String.format("%s-%s", newInternalHost, DATA_MANAGER)); usersDotProperties.remove(oldHostName); usersDotProperties.setProperty(newInternalHost, newHostValue); usersDotProperties.save(); } } } catch (IOException e) { LOGGER.warn("Exception while writing to users.properties file.", e); } }
Source:
<code>public RecordReader<NullWritable, StructuredRecord> createRecordReader(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException { if (!(split instanceof FileSplit)) { throw new IllegalStateException("Input split is not a FileSplit."); } FileSplit fileSplit = (FileSplit) split; String pathField = context.getConfiguration().get(PATH_FIELD); boolean filenameOnly = context.getConfiguration().getBoolean(FILENAME_ONLY, false); String format = context.getConfiguration().get(FORMAT); String path = filenameOnly ? fileSplit.getPath().getName() : fileSplit.getPath().toUri().toString(); String schema = context.getConfiguration().get(SCHEMA); if ("avro".equalsIgnoreCase(format)) { RecordReader<AvroKey<GenericRecord>, NullWritable> delegate = (new AvroKeyInputFormat<GenericRecord>()) .createRecordReader(split, context); return new TrackingAvroRecordReader(delegate, pathField, path, Schema.parseJson(schema)); } else if ("parquet".equalsIgnoreCase(format)) { RecordReader<Void, GenericRecord> delegate = (new AvroParquetInputFormat<GenericRecord>()) .createRecordReader(split, context); return new TrackingParquetRecordReader(delegate, pathField, path, Schema.parseJson(schema)); } else { RecordReader<LongWritable, Text> delegate = (new TextInputFormat()).createRecordReader(split, context); <START> return new TrackingTextRecordReader(delegate, pathField, path, getTextOutputSchema(pathField)); <END> } }</code><technical_language>Do Schema.parseJson() this if else section pass schema record reader. mentioned before, getTextOutputSchema() here, easier accidentally break code evolves</technical_language>

Target:
public RecordReader<NullWritable, StructuredRecord> createRecordReader(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException { if (!(split instanceof FileSplit)) { throw new IllegalStateException("Input split is not a FileSplit."); } FileSplit fileSplit = (FileSplit) split; String pathField = context.getConfiguration().get(PATH_FIELD); boolean filenameOnly = context.getConfiguration().getBoolean(FILENAME_ONLY, false); String format = context.getConfiguration().get(FORMAT); String path = filenameOnly ? fileSplit.getPath().getName() : fileSplit.getPath().toUri().toString(); String schema = context.getConfiguration().get(SCHEMA); Schema parsedSchema = Schema.parseJson(schema); if ("avro".equalsIgnoreCase(format)) { RecordReader<AvroKey<GenericRecord>, NullWritable> delegate = (new AvroKeyInputFormat<GenericRecord>()) .createRecordReader(split, context); return new TrackingAvroRecordReader(delegate, pathField, path, parsedSchema); } else if ("parquet".equalsIgnoreCase(format)) { RecordReader<Void, GenericRecord> delegate = (new AvroParquetInputFormat<GenericRecord>()) .createRecordReader(split, context); return new TrackingParquetRecordReader(delegate, pathField, path, parsedSchema); } else { RecordReader<LongWritable, Text> delegate = (new TextInputFormat()).createRecordReader(split, context); return new TrackingTextRecordReader(delegate, pathField, path, parsedSchema); } }
Source:
<code>public void onMessage(Message message) { MessageProperties messageProperties = message.getMessageProperties(); if (messageProperties != null) { byte[] correlationId = messageProperties.getCorrelationId(); if (correlationId != null) { if (logger.isDebugEnabled()) { logger.debug("onMessage: " + message); } RabbitFuture<?> future = this.pending.remove(new String(correlationId, this.charset)); if (future != null) { if (future instanceof AsyncRabbitTemplate.RabbitConverterFuture) { Object converted = this.template.getMessageConverter().fromMessage(message); ((RabbitConverterFuture<Object>) future).set(converted); } else { ((RabbitMessageFuture) future).set(message); } } else { if (logger.isDebugEnabled()) { <START> logger.debug("No pending reply - perhaps timed out"); <END> } } } } }</code><technical_language>warn() instead? message, of course, able diagnose logs. similar in TemporaryReplyChannel: if (errorDescription != null) { if (logger.isWarnEnabled()) { logger.warn(errorDescription + ":" + message); } if (GenericMessagingTemplate.this.throwExceptionOnLateReply) { throw new MessageDeliveryException(message, errorDescription); } }</technical_language>

Target:
public void onMessage(Message message) { MessageProperties messageProperties = message.getMessageProperties(); if (messageProperties != null) { byte[] correlationId = messageProperties.getCorrelationId(); if (correlationId != null) { if (logger.isDebugEnabled()) { logger.debug("onMessage: " + message); } RabbitFuture<?> future = this.pending.remove(new String(correlationId, this.charset)); if (future != null) { if (future instanceof AsyncRabbitTemplate.RabbitConverterFuture) { Object converted = this.template.getMessageConverter().fromMessage(message); ((RabbitConverterFuture<Object>) future).set(converted); } else { ((RabbitMessageFuture) future).set(message); } } else { if (logger.isWarnEnabled()) { logger.warn("No pending reply - perhaps timed out: " + message); } } } } }
Source:
<code><START> protected boolean canRunActions(ArrayList<VdcReturnValueBase> returnValues) { <END> if (getCommands().size() == 1) { CorrelationIdTracker.setCorrelationId(getCommands().get(0).getCorrelationId()); returnValues.add(getCommands().get(0).canDoActionOnly()); } else { checkCanDoActionsAsynchronously(returnValues); } if (isRunOnlyIfAllCanDoPass) { for (VdcReturnValueBase value : returnValues) { if (!value.getCanDoAction()) { return false; } } } return true; }</code><technical_language>please this method private</technical_language>

Target:
private boolean canRunActions(ArrayList<VdcReturnValueBase> returnValues) { if (getCommands().size() == 1) { CorrelationIdTracker.setCorrelationId(getCommands().get(0).getCorrelationId()); returnValues.add(getCommands().get(0).canDoActionOnly()); } else { checkCanDoActionsAsynchronously(returnValues); } if (isRunOnlyIfAllCanDoPass) { for (VdcReturnValueBase value : returnValues) { if (!value.getCanDoAction()) { return false; } } } return true; }
Source:
<code>public static JSONArray getJsonArrayDuplicateDataNodes(int dataNodeCount, String hostname, int basePort, HardwareState hardwareState, JSONArray disks) throws JSONException { JSONArray jsonArray = new JSONArray(); for (int i = 0; i < dataNodeCount; ++i) { <START> jsonArray.put(getJsonDataNode(hostname, basePort + i, hardwareState, disks)); <END> } return jsonArray; }</code><technical_language>change basePort + i here</technical_language>

Target:
public static JSONArray getJsonArrayDuplicateDataNodes(int dataNodeCount, String hostname, int basePort, HardwareState hardwareState, JSONArray disks) throws JSONException { JSONArray jsonArray = new JSONArray(); for (int i = 0; i < dataNodeCount; ++i) { jsonArray.put(getJsonDataNode(hostname, basePort, hardwareState, disks)); } return jsonArray; }
Source:
<code>public void checkChunksForPlayback() { try { int chunkCount = this.packetizerCupertino.getChunkCount(); <START> logger.info("Stream: [" + this.streamName + "] contains [" + chunkCount + "] chunks"); <END> if (chunkCount >= readyForPlaybackMinimumChunkCount) { logger.info("Raising STREAM_READY_FOR_PLAYBACK event"); raiseReadyForPlaybackEvent(); } } catch (Exception err) { logger.error(err); } }</code><technical_language>this file relevant for this specific pull request</technical_language>

Target:
public void checkChunksForPlayback() { try { int chunkCount = this.packetizerCupertino.getChunkCount(); logger.info("Stream contains [" + chunkCount + "] chuncks"); if (chunkCount >= readyForPlaybackMinimumChunkCount) { logger.info("Raising STREAM_READY_FOR_PLAYBACK event"); raiseReadyForPlaybackEvent(); } } catch (Exception err) { logger.error(err); } }
Source:
<code>public void component2(Span span) { try (Span component2Span = getTracer().buildSpan("Component2") .addReference(References.FOLLOWS_FROM, span.context()) .withTag("sql", "INSERT order INTO Orders") .withTag("component", "database") .start()) { try { synchronized (this) { wait(500); } <START> } catch (Exception e) { <END> e.printStackTrace(); } callService(component2Span); delay(500); } }</code><technical_language>delay(500)</technical_language>

Target:
public void component2(Span span) { try (Span component2Span = getTracer().buildSpan("Component2") .addReference(References.FOLLOWS_FROM, span.context()) .withTag("sql", "INSERT order INTO Orders") .withTag("component", "database") .start()) { delay(500); callService(component2Span); delay(500); } }
Source:
<code>public void testAsSet_ignoresPermutations() { <START> assertEquals( <END> asSet(new MetricTarget[]{MANAGEMENT_CENTER}), asSet(new MetricTarget[]{MANAGEMENT_CENTER, MANAGEMENT_CENTER}) ); assertEquals( asSet(new MetricTarget[]{JMX, MANAGEMENT_CENTER}), asSet(new MetricTarget[]{MANAGEMENT_CENTER, JMX}) ); }</code><technical_language>assertSame I think</technical_language>

Target:
public void testAsSet_ignoresPermutations() { assertSame( MetricTarget.asSet(new MetricTarget[]{MANAGEMENT_CENTER}), MetricTarget.asSet(new MetricTarget[]{MANAGEMENT_CENTER, MANAGEMENT_CENTER}) ); assertSame( MetricTarget.asSet(new MetricTarget[]{JMX, MANAGEMENT_CENTER}), MetricTarget.asSet(new MetricTarget[]{MANAGEMENT_CENTER, JMX}) ); }
Source:
<code>private static Set<Object> getSelectionContents( @NonNull IStructuredSelection selection) { Set<Object> result = new HashSet<>(); for (Object o : selection.toList()) { IResource resource = AdapterUtils.adapt(o, IResource.class); if (addResource(resource, result)) { continue; } ResourceMapping mapping = AdapterUtils.adapt(o, ResourceMapping.class); if (mapping != null) { for (IResource r : extractResourcesFromMapping(mapping)) { <START> addResource(r, result); <END> } } else { IPath location = AdapterUtils.adapt(o, IPath.class); if (location != null) { result.add(location); } } } return result; }</code><technical_language>reason for patch. a new warning "unknown nullness" "r"</technical_language>

Target:
private static Set<Object> getSelectionContents( @NonNull IStructuredSelection selection) { Set<Object> result = new HashSet<>(); for (Object o : selection.toList()) { IResource resource = AdapterUtils.adapt(o, IResource.class); if (resource != null) { result.add(resource); continue; } ResourceMapping mapping = AdapterUtils.adapt(o, ResourceMapping.class); if (mapping != null) { result.addAll(extractResourcesFromMapping(mapping)); } else { IPath location = AdapterUtils.adapt(o, IPath.class); if (location != null) { result.add(location); } } } return result; }
Source:
<code>private List<String> findBlockMatches(String searchLowercase) { ResourceUrn curUrn; <START> List<String> l=new ArrayList<String>(); <END> for (ResourceUrn urn : assetManager.getAvailableAssets(BlockFamilyDefinition.class)) { curUrn = urn; try{ Optional<BlockFamilyDefinition> def = assetManager.getAsset(urn, BlockFamilyDefinition.class); if (def.isPresent() && def.get().isLoadable() && matchesSearch(searchLowercase, def.get())) { String s = new BlockUri(def.get().getUrn()).toString(); l.add(s); } } catch(Exception e){ List<String> EmptyList=new ArrayList<String>(); console.addMessage("Note : Search may not return results if invalid assets are present"); console.addMessage("Error parsing : "+curUrn.toString()); console.addMessage(e.toString()); return(EmptyList); } } return l; }</code><technical_language>try variables useful names, if much. suggest matchingBlocks outputList</technical_language>

Target:
private List<String> findBlockMatches(String searchLowercase) { ResourceUrn curUrn; List<String> outputList=new ArrayList<String>(); for (ResourceUrn urn : assetManager.getAvailableAssets(BlockFamilyDefinition.class)) { curUrn = urn; try{ Optional<BlockFamilyDefinition> def = assetManager.getAsset(urn, BlockFamilyDefinition.class); if (def.isPresent() && def.get().isLoadable() && matchesSearch(searchLowercase, def.get())) { outputList.add(new BlockUri(def.get().getUrn()).toString()); } } catch(Exception e){ console.addMessage("Note : Search may not return results if invalid assets are present"); console.addMessage("Error parsing : "+curUrn.toString()); console.addMessage(e.toString()); continue; } } return outputList; }
Source:
<code>public Vector3d getSize(Vector3d dest) { <START> return dest.set(maxX - minX, maxY - minY, maxZ - minZ); <END> }</code><technical_language>here: suggestion return dest.set(lengthX(), lengthY(), lengthZ());</technical_language>

Target:
public Vector3d getSize(Vector3d dest) { return dest.set(lengthX(), lengthY(), lengthZ()); }
Source:
<code>public static boolean isPublishDateInTheFuture(String dateCreated) { <START> Date pubDate = DateTimeUtils.dateFromIso8601(dateCreated); <END> Date now = new Date(); return pubDate != null && pubDate.after(now); }</code><technical_language>want consider calling new method this duplicate code isPublishDateInTheFuture(dateCreated, new Date()) wdyt</technical_language>

Target:
public static boolean isPublishDateInTheFuture(String dateCreated) { return isPublishDateInTheFuture(dateCreated, new Date()); }
Source:
<code>public synchronized void stopStats() { if (statsTask != null) { if (statsTask.cancel(true)) { statsTask = null; } else { log.error("Statistics task was not cancelled"); } Utils.shutdownAndWait(executor); if (!executor.isTerminated()) { log.warn("Failed to terminate statistics executor service."); } <START> this.executor = null; <END> this.statsTask = null; } if (sizeThread != null) { log.debug("Interrupting size thread"); sizeThread.interrupt(); try { sizeThread.join(); } catch (InterruptedException e) { log.error("Interrupted while waiting for stat thread to end."); sizeThread.interrupt(); } sizeThread = null; } }</code><technical_language>If terminate executor, please a new is created in startStats. stats started/stopped times a scenario</technical_language>

Target:
public synchronized void stopStats() { if (statsTask != null) { if (statsTask.cancel(true)) { statsTask = null; } else { log.error("Statistics task was not cancelled"); } Utils.shutdownAndWait(executor); if (!executor.isTerminated()) { log.warn("Failed to terminate statistics executor service."); } this.statsTask = null; this.executor = Executors.newScheduledThreadPool(1); } if (sizeThread != null) { log.debug("Interrupting size thread"); sizeThread.interrupt(); try { sizeThread.join(); } catch (InterruptedException e) { log.error("Interrupted while waiting for stat thread to end."); sizeThread.interrupt(); } sizeThread = null; } }
Source:
<code>private void pullOrganisationCredentials() { Credentials orgUnitCredentials = null; try { OrganisationUnit orgUnit = mOrgUnitDataSource.getUserOrgUnit(insertedCredentials); if (orgUnit == null) { notifyInvalidCredentials(); return; } orgUnitCredentials = new Credentials(insertedCredentials.getServerURL(), orgUnit.getCode(), orgUnit.getPin()); } catch (ApiCallException e) { if(e.getCause() instanceof IOException){ notifyUnexpectedError(); }else { e.printStackTrace(); notifyConfigJsonNotPresent(); } } catch (NetworkException e) { e.printStackTrace(); checkUserCredentialsWithOrgUnit( mCredentialsLocalDataSource.getOrganisationCredentials(), true); } <START> if (orgUnitCredentials != null) { <END> mCredentialsLocalDataSource.saveOrganisationCredentials(orgUnitCredentials); } checkUserCredentialsWithOrgUnit(orgUnitCredentials, false); }</code><technical_language>if orgUnitCredentials null if network fail retrieve credentials server in checkUserCredentialsWithOrgUnit method validate null</technical_language>

Target:
private void pullOrganisationCredentials() { Credentials orgUnitCredentials = null; try { OrganisationUnit orgUnit = mOrgUnitDataSource.getUserOrgUnit(insertedCredentials); if (orgUnit == null) { notifyInvalidCredentials(); return; } orgUnitCredentials = new Credentials(insertedCredentials.getServerURL(), orgUnit.getCode(), orgUnit.getPin()); } catch (ApiCallException e) { if(e.getCause() instanceof IOException){ notifyUnexpectedError(); }else { e.printStackTrace(); notifyConfigJsonNotPresent(); } } catch (NetworkException e) { e.printStackTrace(); checkUserCredentialsWithOrgUnit( mCredentialsLocalDataSource.getOrganisationCredentials(), true); } if (orgUnitCredentials != null) { mCredentialsLocalDataSource.saveOrganisationCredentials(orgUnitCredentials); checkUserCredentialsWithOrgUnit(orgUnitCredentials, false); } else { notifyUnexpectedError(); } }
Source:
<code>private DefaultScoredCandidates.Builder findByCommonAlias( T subject, DefaultScoredCandidates.Builder equivalents, ResultDescription desc ) { desc.startStage("Resolving Barb Aliases:"); subject.getAliasUrls().forEach(alias -> desc.appendText(alias)); desc.finishStage(); Set<Iterable<LookupEntry>> entriesSet = subject.getAliases().stream().map(alias -> { Iterable<LookupEntry> entries = lookupEntryStore.entriesForAliases( Optional.of(alias.getNamespace()), ImmutableSet.of(alias.getValue()) ); <START> return entries; <END> }).collect(Collectors.toSet()); entriesSet.forEach(iterableLookupEntry -> { iterableLookupEntry.forEach(entry -> { Identified identified = resolver.findByCanonicalUris( ImmutableSet.of(entry.uri()) ).getFirstValue().requireValue(); if (identified.getAliasUrls().size() !=0) { boolean match = false; for (String alias : identified.getAliasUrls()) { if (subject.getAliasUrls().contains(alias)) { match = true; } } if (match) { equivalents.addEquivalent((T) identified, Score.ONE); desc.appendText("Resolved %s", identified.getCanonicalUri()); } } }); }); return equivalents; }</code><technical_language>do a straight return assigning intermediate variable (and need curlys)</technical_language>

Target:
private DefaultScoredCandidates.Builder findByCommonAlias( T subject, DefaultScoredCandidates.Builder equivalents, ResultDescription desc ) { desc.startStage("Resolving Barb Aliases:"); subject.getAliasUrls().forEach(alias -> desc.appendText(alias)); desc.finishStage(); Set<Iterable<LookupEntry>> entriesSet = subject.getAliases().stream().map(alias -> lookupEntryStore.entriesForAliases( Optional.of(alias.getNamespace()), ImmutableSet.of(alias.getValue()) )).collect(Collectors.toSet()); entriesSet.forEach(iterableLookupEntry -> { iterableLookupEntry.forEach(entry -> { Identified identified = resolver.findByCanonicalUris( ImmutableSet.of(entry.uri()) ).getFirstValue().requireValue(); if (identified.getAliasUrls().isEmpty()) { boolean match = false; for (String alias : identified.getAliasUrls()) { if (subject.getAliasUrls().contains(alias)) { match = true; break; } } if (match) { equivalents.addEquivalent((T) identified, Score.ONE); desc.appendText("Resolved %s", identified.getCanonicalUri()); } } }); }); return equivalents; }
Source:
<code>private static void checkFile(final ModelRepository modelRepo, final File file, final Kind kind) { if (modelRepo != null && file != null) { try { synchronized (FolderObserver.class) { if ((kind == ENTRY_CREATE || kind == ENTRY_MODIFY)) { if (parsers.contains(getExtension(file.getName()))) { try (FileInputStream inputStream = FileUtils.openInputStream(file)) { modelRepo.addOrRefreshModel(file.getName(), inputStream); } } else { ignoredFiles.add(file); } } else if (kind == ENTRY_DELETE) { modelRepo.removeModel(file.getName()); } } } catch (Exception e) { LoggerFactory.getLogger(FolderObserver.class).error( <START> "Error handling update of file '" + file.getAbsolutePath() + "': {}.", e.getMessage(), e); <END> } } }</code><technical_language>I introduced PR, touched lines, fix string concatenation</technical_language>

Target:
private static void checkFile(final ModelRepository modelRepo, final File file, final Kind kind) { if (modelRepo != null && file != null) { try { synchronized (FolderObserver.class) { if ((kind == ENTRY_CREATE || kind == ENTRY_MODIFY)) { if (parsers.contains(getExtension(file.getName()))) { try (FileInputStream inputStream = FileUtils.openInputStream(file)) { modelRepo.addOrRefreshModel(file.getName(), inputStream); } } else { ignoredFiles.add(file); } } else if (kind == ENTRY_DELETE) { modelRepo.removeModel(file.getName()); } } } catch (Exception e) { LoggerFactory.getLogger(FolderObserver.class).error("Error handling update of file '{}': {}.", file.getAbsolutePath(), e.getMessage(), e); } } }
Source:
<code><START> default <R> ReactiveSeq<R> retry(final Function<? super T, ? extends R> fn, final int retries, final long delay, final TimeUnit timeUnit) { <END> final Function<T, R> retry = t -> { final long[] sleep = { timeUnit.toMillis(delay) }; Throwable exception = null; for (int count = retries; count >=0; count--) { try { return fn.apply(t); } catch (final Throwable e) { exception = e; ExceptionSoftener.softenRunnable(() -> Thread.sleep(sleep[0])) .run(); sleep[0] = sleep[0] * 2; } } ExceptionSoftener.throwSoftenedException(exception); return null; }; return map(retry); }</code><technical_language>@jijisv move this impl Transformable? types retry (& map funcitonality in cyclops-react). Transformable in ReactiveSeq ideally call Transformable.super.retry ( ) . (If super call works, I presume separate implementations is oversight in current code base, a reason for impls)</technical_language>

Target:
default <R> ReactiveSeq<R> retry(final Function<? super T, ? extends R> fn, final int retries, final long delay, final TimeUnit timeUnit) { return (ReactiveSeq) FoldableTraversable.super.retry(fn, retries, delay, timeUnit); }
Source:
<code><START> public ResponseEntity<?> syndicate(HttpServletRequest request, <END> @RequestParam(value = "revision", required = false) Integer revisionNumber) throws IOException { ArticleVersionIdentifier versionId = getArticleVersionIdentifier(request, revisionNumber); SyndicationInputView input = readJsonFromRequest(request, SyndicationInputView.class); Syndication created = syndicationCrudService.syndicate(versionId, input.getTarget()); return reportOk(created.toString()); }</code><technical_language>ResponseEntity<Object> instead of ?</technical_language>

Target:
public ResponseEntity<Object> syndicate(HttpServletRequest request, @RequestParam(value = "revision", required = false) Integer revisionNumber) throws IOException { ArticleVersionIdentifier versionId = getArticleVersionIdentifier(request, revisionNumber); SyndicationInputView input = readJsonFromRequest(request, SyndicationInputView.class); Syndication created = syndicationCrudService.syndicate(versionId, input.getTarget()); return reportOk(created.toString()); }
Source:
<code>public void onDestroyView() { mapView.onDestroy(); mapboxMap = null; unbinder.unbind(); unbinder = null; <START> WikipediaApp.getInstance().getRefWatcher().watch(this); <END> super.onDestroyView(); }</code><technical_language>this in onDestroy</technical_language>

Target:
public void onDestroyView() { mapView.onDestroy(); mapboxMap = null; unbinder.unbind(); unbinder = null; super.onDestroyView(); }
Source:
<code>private boolean isNewerVersion(Version isoClusterVersion) { VDS vds = getVdsByVdsId(getParameters().getVdsId()); Version vdsClusterVersion = vds.getVdsGroupCompatibilityVersion(); log.debugFormat( "cluster major {0} minor {1} iso major {2} minor {3}", vdsClusterVersion.getMajor(), vdsClusterVersion.getMinor(), isoClusterVersion.getMajor(), <START> isoClusterVersion.getMinor() <END> ); return (vdsClusterVersion.getMajor() == isoClusterVersion.getMajor() && vdsClusterVersion.getMinor() <= isoClusterVersion.getMinor()); }</code><technical_language>I want toString() classes, for debug, calling functions time is avoided</technical_language>

Target:
private boolean isNewerVersion(Version isoClusterVersion) { VDS vds = getVdsByVdsId(getParameters().getVdsId()); Version vdsClusterVersion = vds.getVdsGroupCompatibilityVersion(); log.debugFormat( "vdsClusterVersion {0} isoClusterVersion {1}", vdsClusterVersion.toString(), isoClusterVersion.toString() ); return (vdsClusterVersion.getMajor() == isoClusterVersion.getMajor() && vdsClusterVersion.getMinor() <= isoClusterVersion.getMinor()); }
Source:
<code><START> public double overnightIndexRate(OvernightIndex index, LocalDate fixingDate) { <END> ArgChecker.notNull(index, "index"); ArgChecker.notNull(fixingDate, "fixingDate"); if (!fixingDate.isAfter(valuationDate)) { OptionalDouble fixedRate = timeSeries(index).get(fixingDate); if (fixedRate.isPresent()) { return fixedRate.getAsDouble(); } else if (fixingDate.isBefore(valuationDate)) { throw new PricingException(Messages.format("Unable to get fixing for on date {}", index, fixingDate)); } } LocalDate fixingStartDate = index.calculateEffectiveFromFixing(fixingDate); LocalDate fixingEndDate = index.calculateMaturityFromEffective(fixingStartDate); double fixingYearFraction = index.getDayCount().yearFraction(fixingStartDate, fixingEndDate); return multicurve.getSimplyCompoundForwardRate( Legacy.overnightIndex(index), relativeTime(fixingStartDate), relativeTime(fixingEndDate), fixingYearFraction); }</code><technical_language>tests for new methods</technical_language>

Target:
public double overnightIndexRate(OvernightIndex index, LocalDate fixingDate) { ArgChecker.notNull(index, "index"); ArgChecker.notNull(fixingDate, "fixingDate"); LocalDate publicationDate = index.calculatePublicationFromFixing(fixingDate); if (!publicationDate.isAfter(valuationDate)) { OptionalDouble fixedRate = timeSeries(index).get(fixingDate); if (fixedRate.isPresent()) { return fixedRate.getAsDouble(); } else if (publicationDate.isBefore(valuationDate)) { throw new PricingException(Messages.format("Unable to get fixing for on date {}", index, fixingDate)); } } LocalDate fixingStartDate = index.calculateEffectiveFromFixing(fixingDate); LocalDate fixingEndDate = index.calculateMaturityFromEffective(fixingStartDate); double fixingYearFraction = index.getDayCount().yearFraction(fixingStartDate, fixingEndDate); return multicurve.getSimplyCompoundForwardRate( Legacy.overnightIndex(index), relativeTime(fixingStartDate), relativeTime(fixingEndDate), fixingYearFraction); }
Source:
<code>private void switchPortSpeed() { if (fixedPortSettings == null) { logger.debug("No fixed port setting (autodetect ENABLED), switch between specification standard settings"); if (portSettings == DSMRPortSettings.HIGH_SPEED_SETTINGS) { portSettings = DSMRPortSettings.LOW_SPEED_SETTINGS; } else { portSettings = DSMRPortSettings.HIGH_SPEED_SETTINGS; } <START> logger.debug("Switched port settings to:" + portSettings); <END> } else { portSettings = fixedPortSettings; logger.info("Fixed port settings configured (autodetect DISABLED):" + portSettings); } }</code><technical_language>Please parameterized logging instead of string concatenation</technical_language>

Target:
private void switchPortSpeed() { if (fixedPortSettings == null) { logger.debug("No fixed port setting (autodetect ENABLED), switch between specification standard settings"); if (portSettings == DSMRPortSettings.HIGH_SPEED_SETTINGS) { portSettings = DSMRPortSettings.LOW_SPEED_SETTINGS; } else { portSettings = DSMRPortSettings.HIGH_SPEED_SETTINGS; } logger.debug("Switched port settings to: {}", portSettings); } else { portSettings = fixedPortSettings; logger.info("Fixed port settings configured (autodetect DISABLED): {}", portSettings); } }
Source:
<code>public boolean shouldPull(DockerImageName imageName) { Logger logger = DockerLoggerFactory.getLogger(imageName.toString()); <START> ImageData imageData = LOCAL_IMAGES_CACHE.get(imageName); <END> if (imageData != null) { logger.trace("{} is already in image name cache", imageName); } else { logger.debug("{} is not in image name cache, updating...", imageName); imageData = LOCAL_IMAGES_CACHE.refreshCache(imageName).orElse(null); } if (imageData != null && !shouldPullCached(imageName, imageData)) { return false; } log.trace("Should pull image: {}", imageName); return true; }</code><technical_language>tempted suggest additional boolean in line 27, e.g. like: if (isCached && !shouldPullCached(... Alternatively, renaming this cachedImageData equivalently clear</technical_language>

Target:
public boolean shouldPull(DockerImageName imageName) { Logger logger = DockerLoggerFactory.getLogger(imageName.toString()); ImageData cachedImageData = LOCAL_IMAGES_CACHE.get(imageName); if (cachedImageData != null) { logger.trace("{} is already in image name cache", imageName); } else { logger.debug("{} is not in image name cache, updating...", imageName); cachedImageData = LOCAL_IMAGES_CACHE.refreshCache(imageName).orElse(null); if (cachedImageData == null) { log.debug("Not available locally, should pull image: {}", imageName); return true; } } if (shouldPullCached(imageName, cachedImageData)) { log.debug("Should pull locally available image: {}", imageName); return true; } else { log.debug("Using locally available and not pulling image: {}", imageName); return false; } }
Source:
<code><START> public Map<String, Serializable> getResultMap() { <END> return resultMap; }</code><technical_language>this is handled (it return null), I return a UnsupportedOperationException handle (but some time : db, rest mappings)</technical_language>

Target:
public Map<String, Serializable> getResultMap() { throw new UnsupportedOperationException(); }
Source:
<code>public Blob resolveBlobFromDownloadUrl(String url) { String baseUrl = getBaseDownloadUrl(url); <START> if (!baseUrl.equals(Framework.getProperty("nuxeo.url"))) { <END> return null; } String uri = url.substring(baseUrl.length() + 1); Pair<String, String> pair = getDownloadPathAndActionFromUri(uri); if (pair == null) { return null; } String path = pair.getLeft(); Map<String, String> parsedUrl = parseDownloadPath(path); if (parsedUrl == null) { return null; } DocumentModel doc = getDownloadDocument(parsedUrl.get("repository"), parsedUrl.get("docId")); if (doc == null) { return null; } return resolveBlob(doc, parsedUrl.get("xpath")); }</code><technical_language>In getBaseDownloadUrl identify context is. Instead do a url.startsWith(Framework.getProperty("nuxeo.url")) I think, drop getBaseDownloadUrl</technical_language>

Target:
public Blob resolveBlobFromDownloadUrl(String url) { String nuxeoUrl = Framework.getProperty("nuxeo.url"); if (!url.startsWith(nuxeoUrl)) { return null; } String path = url.substring(nuxeoUrl.length() + 1); Pair<String, Action> pair = getDownloadPathAndAction(path); if (pair == null) { return null; } String downloadPath = pair.getLeft(); try { DownloadBlobInfo downloadBlobInfo = new DownloadBlobInfo(downloadPath); DocumentModel doc = getDownloadDocument(downloadBlobInfo.repository, downloadBlobInfo.docId); if (doc == null) { return null; } return resolveBlob(doc, downloadBlobInfo.xpath); } catch (IllegalArgumentException e) { return null; } }
Source:
<code>public synchronized ITmfTimestamp readEnd() { byte[] inputNameBytes = ("<" + fRecordInputElement.getInputName()).getBytes(); try { Long pos = fFile.length() - inputNameBytes.length; while (pos >= 0) { searchloop: <START> while (pos >= 0) { fFile.seek(pos); for (byte c : inputNameBytes) { if (c != fFile.read()) { break searchloop; } } pos--; } <END> ITmfLocation location = new TmfLongLocation(pos); ITmfContext context = seekEvent(location); ITmfEvent event = parseEvent(context); context.dispose(); if (event != null) { return event.getTimestamp(); } pos -= inputNameBytes.length; } } catch (IOException e) { return null; } return null; }</code><technical_language>this a separate function avoid break tag</technical_language>

Target:
public synchronized ITmfTimestamp readEnd() { byte[] inputNameBytes = ("<" + fRecordInputElement.getElementName()).getBytes(); byte[] testBytes = new byte[inputNameBytes.length]; try { Long pos = fFile.length() - inputNameBytes.length; while (pos >= 0) { while (pos >= 0) { fFile.seek(pos); fFile.read(testBytes, 0, testBytes.length); if (Arrays.equals(inputNameBytes, testBytes)) { break; } pos--; } ITmfLocation location = new TmfLongLocation(pos); ITmfContext context = seekEvent(location); ITmfEvent event = parseEvent(context); context.dispose(); if (event != null) { return event.getTimestamp(); } pos -= inputNameBytes.length; } } catch (IOException e) { Activator.logError("Error seeking last event. File: " + getPath(), e); } return null; }
Source:
<code>@Override public void onReadyForRead(ReadableDistributedMetaStorage metastorage) { <START> ClusterIdAndTag idAndTag = readKey(metastorage, CLUSTER_ID_TAG_KEY, "Reading cluster ID and tag from metastorage failed, " + <END> "default values will be generated"); if (log.isInfoEnabled()) log.info("Cluster ID and tag has been read from metastorage: " + idAndTag); if (idAndTag != null) { localClusterId = idAndTag.id(); localClusterTag = idAndTag.tag(); } }</code><technical_language>Line is long considering 120 chars limit</technical_language>

Target:
@Override public void onReadyForRead(ReadableDistributedMetaStorage metastorage) { ClusterIdAndTag idAndTag = readKey(metastorage, CLUSTER_ID_TAG_KEY, "Reading cluster ID and tag " + "from metastorage failed, default values will be generated"); if (log.isInfoEnabled()) log.info("Cluster ID and tag has been read from metastorage: " + idAndTag); if (idAndTag != null) { localClusterId = idAndTag.id(); localClusterTag = idAndTag.tag(); } }
Source:
<code>public void testNormalizeOnDouble() throws Exception { assertNormalize("trunc(29.1947)", isLiteral(29L)); assertNormalize("trunc(-29.1947)", isLiteral(-29L)); <START> assertNormalize("trunc(29.1947, 0)", isFunction(TruncFunction.NAME, List.of(DataTypes.DOUBLE, DataTypes.INTEGER))); <END> assertNormalize("trunc(cast(null as double))", isFunction(TruncFunction.NAME, List.of(DataTypes.DOUBLE))); }</code><technical_language>this result in isLiteral(29L). in general, normalizing literals result in a literal, pls fix normalize tests please</technical_language>

Target:
public void testNormalizeOnDouble() throws Exception { assertNormalize("trunc(29.1947)", isLiteral(29L)); assertNormalize("trunc(-29.1947)", isLiteral(-29L)); assertNormalize("trunc(-29.1947, 0)", isLiteral(-29.0)); assertNormalize("trunc(29.1947, 0)", isLiteral(29.0)); assertNormalize("trunc(29.1947, 1)", isLiteral(29.1d)); assertNormalize("trunc(cast(null as double))", isLiteral(null, DataTypes.LONG)); }
Source:
<code>public static ModelNode addRedeployStep(PathAddress address) { final ModelNode redeployOperation = new ModelNode(); redeployOperation.get(OP).set(REDEPLOY); redeployOperation.get(OP_ADDR).set(address.toModelNode()); <START> return redeployOperation; <END> }</code><technical_language>This method return Util.createEmptyOperation(REDEPLOY, address);</technical_language>

Target:
private static ModelNode addRedeployStep(PathAddress address) { return Operations.createOperation(REDEPLOY, address.toModelNode()); }
Source:
<code>void updateTopologyHandler(String topologyName, Config updateConfig) throws TopologyRuntimeManagementException, PackingException, UpdateDryRunResponse { assert !potentialStaleExecutionData; String newParallelism = updateConfig.getStringValue(RUNTIME_MANAGER_COMPONENT_PARALLELISM_KEY); String userRuntimeConfig = updateConfig.getStringValue(RUNTIME_MANAGER_RUNTIME_CONFIG_KEY); <START> if (newParallelism != null && !newParallelism.isEmpty()) { <END> updateTopologyComponentParallelism(topologyName, newParallelism); } else if (userRuntimeConfig != null && !userRuntimeConfig.isEmpty()) { updateTopologyUserRuntimeConfig(topologyName, userRuntimeConfig); } else { throw new TopologyRuntimeManagementException( String.format("Missing arguments. Not taking action.")); } LOG.fine("Scheduler updated topology successfully."); }</code><technical_language>@nwangtw - if update component parallelism user run time config is provided simultaneously</technical_language>

Target:
void updateTopologyHandler(String topologyName, Config updateConfig) throws TopologyRuntimeManagementException, PackingException, UpdateDryRunResponse { assert !potentialStaleExecutionData; String newParallelism = updateConfig.getStringValue(RUNTIME_MANAGER_COMPONENT_PARALLELISM_KEY); String userRuntimeConfig = updateConfig.getStringValue(RUNTIME_MANAGER_RUNTIME_CONFIG_KEY); if (newParallelism != null && !newParallelism.isEmpty() && userRuntimeConfig != null && !userRuntimeConfig.isEmpty()) { throw new TopologyRuntimeManagementException( "parallelism and runtime config can not be updated at the same time."); } if (newParallelism != null && !newParallelism.isEmpty()) { updateTopologyComponentParallelism(topologyName, newParallelism); } else if (userRuntimeConfig != null && !userRuntimeConfig.isEmpty()) { updateTopologyUserRuntimeConfig(topologyName, userRuntimeConfig); } else { throw new TopologyRuntimeManagementException("Missing arguments. Not taking action."); } LOG.fine("Scheduler updated topology successfully."); }