auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> FixedDoubleHistogram(FixedDoubleHistogram other) <END> { this(other.bucketCount, other.min, other.max); for (int i = 0; i < bucketCount; ++i) { weights[i] = other.weights[i]; } }</code><technical_language>I feel do this in Presto explicitly create a new object parameters</technical_language>

Target:
protected FixedDoubleHistogram(FixedDoubleHistogram other) { this(other.bucketCount, other.min, other.max); for (int i = 0; i < bucketCount; ++i) { weights[i] = other.weights[i]; } }
Source:
<code>public ValidationResult validate(Object value) { Long longValue = null; ValidationResult res = new ValidationResult(); <START> if (value instanceof Long) { longValue = (Long) value; } else if (value instanceof String && !((String) value).trim().isEmpty()) { try { longValue = Long.valueOf((String) value); } catch (NumberFormatException e) { } } <END> if (longValue != null && longValue == 0) { return ValidationResult.ok(); } if (getMaximum() <= 0) { String msg = ConstantsManager.getInstance().getConstants().diskMaxSizeReached(); res.setSuccess(false); res.setReasons(Collections.singletonList(msg)); } return super.validate(value); }</code><technical_language>If reason needed "value" is of "Long" type a "String" type, update "LongValidation.tryParseLong()" method able receive "Object" & transform "Long" "String" "Long". "static" & "public" 3 classes (and more). is a code duplication in "LongValidation" & "NonNegativeLongNumberValidation" classes. Also, is some inconsistency strings spaces: "NonNegativeLongNumberValidation" trims check string is empty, "LongValidation" not</technical_language>

Target:
public ValidationResult validate(Object value) { Long longValue = LongValidation.tryParseLong(value); if (longValue != null && longValue == 0) { return ValidationResult.ok(); } if (getMaximum() <= 0) { String msg = ConstantsManager.getInstance().getConstants().diskMaxSizeReached(); return ValidationResult.fail(msg); } return super.validate(value); }
Source:
<code>public void testShowHindiNumberFormatAsEngNumberFormat() throws Exception { createProject(AR_ONE_TO_ZERO); baseActivityTestRule.launchActivity(null); <START> onView(withId(R.id.button_play)) <END> .perform(click()); onView(isRoot()) .perform(CustomActions.wait(500)); Bitmap bitmap = Screenshot.capture().getBitmap(); TessOCR tessocr = new TessOCR("eng"); final String srcText = tessocr.getOCRResult(bitmap); assertFalse("stage screenshot contains a text which is :" + srcText, srcText.isEmpty()); assertEquals(String.valueOf(ONE_TO_ZERO), srcText); tessocr.onDestroy(); }</code><technical_language>StageActivity in test rule, skip wait if possible. (if fails wait, please a eg. SayBubbleBrickStageTest, ive wrote a "ScriptEvaluationGateBrick" helps ensure brick test executed in stage test continues</technical_language>

Target:
public void testShowHindiNumberFormatAsEngNumberFormat() throws Exception { createProject(AR_ONE_TO_ZERO); baseActivityTestRule.launchActivity(null); lastBrickInScript.waitUntilEvaluated(3000); onView(isRoot()) .perform(CustomActions.wait(1000)); Bitmap bitmap = Screenshot.capture().getBitmap(); TessOCR tessocr = new TessOCR("eng"); final String srcText = tessocr.getOCRResult(bitmap); assertFalse("stage screenshot contains a text which is :" + srcText, srcText.isEmpty()); assertEquals(String.valueOf(ONE_TO_ZERO), srcText); tessocr.onDestroy(); }
Source:
<code>public PayloadValidatingInterceptor payloadValidatingInterceptor() { final PayloadValidatingInterceptor payloadValidatingInterceptor = new PayloadValidatingInterceptor(); <START> final Resource[] resources = new Resource[] { new ClassPathResource("schemas/common.xsd"), <END> new ClassPathResource("schemas/devicemonitoring.xsd"), new ClassPathResource("schemas/pl-adhocmanagement.xsd"), new ClassPathResource("schemas/pl-schedulemanagement.xsd") }; payloadValidatingInterceptor.setSchemas(resources); return payloadValidatingInterceptor; }</code><technical_language>Move String values more a constant</technical_language>

Target:
public PayloadValidatingInterceptor payloadValidatingInterceptor() { final PayloadValidatingInterceptor payloadValidatingInterceptor = new PayloadValidatingInterceptor(); final Resource[] resources = new Resource[] { new ClassPathResource(COMMON_XSD_PATH), new ClassPathResource(DEVICE_MONITORING_XSD_PATH), new ClassPathResource(PL_ADHOCMANAGEMENT_XSD_PATH), new ClassPathResource(PL_SCHEDULEMANAGEMENT_XSD_PATH) }; payloadValidatingInterceptor.setSchemas(resources); return payloadValidatingInterceptor; }
Source:
<code>public void delete(final Integer formulaId) { final BindingResult bindingResult = new MapBindingResult(new HashMap<String, String>(), FormulaDto.class.getName()); final Optional<FormulaDto> formula = this.formulaService.getById(formulaId); if (!formula.isPresent()) { bindingResult.reject("variable.formula.not.exist", new Integer[] {formulaId}, ""); throw new ApiRequestValidationException(bindingResult.getAllErrors()); } this.formulaValidator.validateDelete(formula.get(), bindingResult); if (bindingResult.hasErrors()) { throw new ApiRequestValidationException(bindingResult.getAllErrors()); } <START> VariableCache.removeFromCache(formula.get().getTarget().getTargetTermId()); <END> this.formulaService.delete(formulaId); }</code><technical_language>I this getTarget().getId() in save, right? for update</technical_language>

Target:
public void delete(final Integer formulaId) { final BindingResult bindingResult = new MapBindingResult(new HashMap<String, String>(), FormulaDto.class.getName()); final Optional<FormulaDto> formula = this.formulaService.getById(formulaId); if (!formula.isPresent()) { bindingResult.reject("variable.formula.not.exist", new Integer[] {formulaId}, ""); throw new ApiRequestValidationException(bindingResult.getAllErrors()); } this.formulaValidator.validateDelete(formula.get(), bindingResult); if (bindingResult.hasErrors()) { throw new ApiRequestValidationException(bindingResult.getAllErrors()); } VariableCache.removeFromCache(formula.get().getTarget().getId()); this.formulaService.delete(formulaId); }
Source:
<code>public void testGetContent_whenAllTestsPassedShouldGiveMeaningfulMessage() throws Exception { AbstractTestResultAction testResults = mock( AbstractTestResultAction.class ); <START> <END> when( build.getAction(AbstractTestResultAction.class) ).thenReturn( testResults ); String content = failedTestContent.evaluate( build, listener, FailedTestsContent.MACRO_NAME ); assertEquals( "All tests passed", content ); }</code><technical_language>is this test modified</technical_language>

Target:
public void testGetContent_whenAllTestsPassedShouldGiveMeaningfulMessage() throws Exception { AbstractTestResultAction testResults = mock( AbstractTestResultAction.class ); when( testResults.getFailCount() ).thenReturn( 0 ); when( build.getAction(AbstractTestResultAction.class) ).thenReturn( testResults ); String content = failedTestContent.evaluate( build, listener, FailedTestsContent.MACRO_NAME ); assertEquals( "All tests passed", content ); }
Source:
<code>public static VmNetworkInterface map(NIC model, VmNetworkInterface template) { VmNetworkInterface entity = template != null ? template : new VmNetworkInterface(); if (model.isSetVm() && model.getVm().isSetId()) { entity.setVmId(new Guid(model.getVm().getId())); } if (model.isSetId()) { entity.setId(new Guid(model.getId())); } if (model.isSetName()) { entity.setName(model.getName()); } if (model.isSetMac() && model.getMac().isSetAddress()) { entity.setMacAddress(model.getMac().getAddress()); } if (model.isSetNetwork() && model.getNetwork().isSetName()) { entity.setNetworkName(model.getNetwork().getName()); } if (model.isSetInterface()) { NicInterface nicType = NicInterface.fromValue(model.getInterface()); if (nicType != null) { entity.setType(map(nicType)); } } if (model.isSetActive()) { entity.setActive(model.isActive()); <START> } <END> return entity; }</code><technical_language>This is a status field. mapped REST-API Backend. user changes this status is running activate/deactivate action. please remove this mapping. mapping in other direction is ok (REST-API show status, status mapped Backend --> REST)</technical_language>

Target:
public static VmNetworkInterface map(NIC model, VmNetworkInterface template) { VmNetworkInterface entity = template != null ? template : new VmNetworkInterface(); if (model.isSetVm() && model.getVm().isSetId()) { entity.setVmId(new Guid(model.getVm().getId())); } if (model.isSetId()) { entity.setId(new Guid(model.getId())); } if (model.isSetName()) { entity.setName(model.getName()); } if (model.isSetMac() && model.getMac().isSetAddress()) { entity.setMacAddress(model.getMac().getAddress()); } if (model.isSetNetwork() && model.getNetwork().isSetName()) { entity.setNetworkName(model.getNetwork().getName()); } if (model.isSetInterface()) { NicInterface nicType = NicInterface.fromValue(model.getInterface()); if (nicType != null) { entity.setType(map(nicType)); } } return entity; }
Source:
<code>public GetBlobPropertiesOperation(String datacenterName, ConnectionPool connectionPool, ExecutorService requesterPool, OperationContext oc, BlobId blobId, long operationTimeoutMs, ClusterMap clusterMap) throws CoordinatorException { super(datacenterName, connectionPool, requesterPool, oc, blobId, operationTimeoutMs, clusterMap, MessageFormatFlags.BlobProperties); logger.trace( <START> "DatacenterNAme " + datacenterName + " Connection pool " + connectionPool + ", requestorPool " + requesterPool <END> + ", Operation context " + oc + ", blobId " + blobId + ", timeout " + operationTimeoutMs + ", clustermap " + clusterMap); this.blobProperties = null; }</code><technical_language>typo in "DatacenterNAme" printing requestorPool print</technical_language>

Target:
public GetBlobPropertiesOperation(String datacenterName, ConnectionPool connectionPool, ExecutorService requesterPool, OperationContext oc, BlobId blobId, long operationTimeoutMs, ClusterMap clusterMap) throws CoordinatorException { super(datacenterName, connectionPool, requesterPool, oc, blobId, operationTimeoutMs, clusterMap, MessageFormatFlags.BlobProperties); logger.trace("GetBlobProperties: Datacenter name " + datacenterName + " Connection pool " + (connectionPool != null) + ", requester pool " + (requesterPool != null) + ", Operation context " + oc + ", blobId " + blobId + ", timeout " + operationTimeoutMs + ", clustermap " + (clusterMap != null)); this.blobProperties = null; }
Source:
<code>public void testDefaultParam() { assertEarlyReferenceError("function f(x=a) { let a; }"); assertEarlyReferenceError(LINE_JOINER.join( "function f(x=a) { let a; }", "function g(x=1) { var a; }")); assertEarlyReferenceError("function f(x=a) { var a; }"); assertEarlyReferenceError("function f(x=a()) { function a() }"); assertEarlyReferenceError("function f(x=[a]) { var a; }"); assertEarlyReferenceError("function f(x=y, y=2) {}"); <START> assertNoWarning("function f(x=a) {}"); <END> assertNoWarning("function f(x=a) var a;"); assertNoWarning("let b; function f(x=b) { var b; }"); assertNoWarning("function f(y = () => x, x = 5) { return y(); }"); }</code><technical_language>VarCheck pass give a warning right? Es6VariableReferenceCheck pass</technical_language>

Target:
public void testDefaultParam() { assertEarlyReferenceError("function f(x=a) { let a; }"); assertEarlyReferenceError(LINE_JOINER.join( "function f(x=a) { let a; }", "function g(x=1) { var a; }")); assertEarlyReferenceError("function f(x=a) { var a; }"); assertEarlyReferenceError("function f(x=a()) { function a() }"); assertEarlyReferenceError("function f(x=[a]) { var a; }"); assertEarlyReferenceError("function f(x=y, y=2) {}"); assertNoWarning("function f(x=a) {}"); assertNoWarning("function f(x=a) var a;"); assertNoWarning("let b; function f(x=b) { var b; }"); assertNoWarning("function f(y = () => x, x = 5) { return y(); }"); assertNoWarning("function f(x = new foo.bar()) {}"); assertNoWarning("var foo = {}; foo.bar = class {}; function f(x = new foo.bar()) {}"); }
Source:
<code>private static Date parseDate(List<String> parameters) { <START> DateFormat df = new SimpleDateFormat("dd-MMM-yyyy"); <END> try { Date d = df.parse(parameters.get(0)); LOGGER.debug("Using date '{}'.", d); return d; } catch (ParseException e) { throw new RuntimeException(e); } }</code><technical_language>I need locale Locale.ENGLISH for SimpleDateFormat, avoid a default system locale. Example failing parse (simulating a German system locale): new SimpleDateFormat("dd-MMM-yyyy", Locale.GERMANY).parse("1-May-1994");</technical_language>

Target:
private static Date parseDate(List<String> parameters) { DateFormat df = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH); String date = parameters.get(0); try { Date d = df.parse(date); LOGGER.debug("Using date '{}'.", d); return d; } catch (ParseException e) { throw new IllegalArgumentException("Unable to parse date '" + date+"'",e); } }
Source:
<code>public static TimeZone getTimezone(long userId) { String timezone = Context.getPermissionsManager().getUser(userId).getTimezone(); <START> if (timezone == null) { <END> timezone = Context.getPermissionsManager().getServer().getTimezone(); } return timezone != null ? TimeZone.getTimeZone(timezone) : TimeZone.getDefault(); }</code><technical_language>Yes, should. a helper method automatically do this</technical_language>

Target:
public static TimeZone getTimezone(long userId) { String timezone = (String) Context.getPermissionsManager().lookupPreference(userId, "timezone", null); return timezone != null ? TimeZone.getTimeZone(timezone) : TimeZone.getDefault(); }
Source:
<code>private static void updateMemoryFuture(ListenableFuture<?> memoryPoolFuture, AtomicReference<SettableFuture<?>> targetFutureReference) { if (!memoryPoolFuture.isDone()) { SettableFuture<?> currentMemoryFuture = targetFutureReference.get(); while (currentMemoryFuture.isDone()) { SettableFuture<?> settableFuture = SettableFuture.create(); if (targetFutureReference.compareAndSet(currentMemoryFuture, settableFuture)) { currentMemoryFuture = settableFuture; } else { currentMemoryFuture = targetFutureReference.get(); } } SettableFuture<?> finalMemoryFuture = currentMemoryFuture; Futures.addCallback(memoryPoolFuture, new FutureCallback<Object>() { @Override public void onSuccess(Object result) { finalMemoryFuture.set(null); } @Override public void onFailure(Throwable t) { finalMemoryFuture.set(null); } <START> }, directExecutor()); <END> } }</code><technical_language>Replace memoryPoolFuture.addListener() methods same</technical_language>

Target:
private static void updateMemoryFuture(ListenableFuture<?> memoryPoolFuture, AtomicReference<SettableFuture<?>> targetFutureReference) { if (!memoryPoolFuture.isDone()) { SettableFuture<?> currentMemoryFuture = targetFutureReference.get(); while (currentMemoryFuture.isDone()) { SettableFuture<?> settableFuture = SettableFuture.create(); if (targetFutureReference.compareAndSet(currentMemoryFuture, settableFuture)) { currentMemoryFuture = settableFuture; } else { currentMemoryFuture = targetFutureReference.get(); } } SettableFuture<?> finalMemoryFuture = currentMemoryFuture; memoryPoolFuture.addListener(() -> finalMemoryFuture.set(null), directExecutor()); } }
Source:
<code>public static void exportToStream(FileOutputStream outFileStream, Context context) throws IOException { FileChannel src = null; FileChannel dst = null; try { File currentDB = context.getDatabasePath(PodDBAdapter.DATABASE_NAME); if (currentDB.exists()) { src = new FileInputStream(currentDB).getChannel(); dst = outFileStream.getChannel(); long srcSize = src.size(); long oldDstSize = dst.size(); dst.transferFrom(src, 0, srcSize); long newDstSize = dst.size(); <START> long expected = srcSize + oldDstSize; <END> if (newDstSize < expected) { throw new IOException(String.format( "Unable to write entire database. Expected to write %s, but wrote %s.", Formatter.formatShortFileSize(context, expected), Formatter.formatShortFileSize(context, newDstSize - oldDstSize))); } } else { throw new IOException("Can not access current database"); } } catch (IOException e) { Log.e(TAG, Log.getStackTraceString(e)); throw e; } finally { IOUtils.closeQuietly(src); IOUtils.closeQuietly(dst); } }</code><technical_language>file fully overwritten. Is size needed</technical_language>

Target:
public static void exportToStream(FileOutputStream outFileStream, Context context) throws IOException { FileChannel src = null; FileChannel dst = null; try { File currentDB = context.getDatabasePath(PodDBAdapter.DATABASE_NAME); if (currentDB.exists()) { src = new FileInputStream(currentDB).getChannel(); dst = outFileStream.getChannel(); long srcSize = src.size(); dst.transferFrom(src, 0, srcSize); long newDstSize = dst.size(); if (newDstSize != srcSize) { throw new IOException(String.format( "Unable to write entire database. Expected to write %s, but wrote %s.", Formatter.formatShortFileSize(context, srcSize), Formatter.formatShortFileSize(context, newDstSize))); } } else { throw new IOException("Can not access current database"); } } catch (IOException e) { Log.e(TAG, Log.getStackTraceString(e)); throw e; } finally { IOUtils.closeQuietly(src); IOUtils.closeQuietly(dst); } }
Source:
<code>public final Response toResponse(T exception) { String message = Objects.toString(exception.getMessage()); <START> String errorString = message; <END> StatusType status = this.getStatus(exception); ResponseBuilder builder = Response.status(status); try { final SerializableError error; if (includeStackTrace) { StackTraceElement[] stackTrace = exception.getStackTrace(); error = SerializableError.of(message, exception.getClass(), Arrays.asList(stackTrace)); } else { String errorId = UUID.randomUUID().toString(); errorString = String.format("Error %s: %s", errorId, message); error = SerializableError.of(errorId, exception.getClass()); } builder.type(MediaType.APPLICATION_JSON); String json = MAPPER.writeValueAsString(error); builder.entity(json); } catch (RuntimeException | JsonProcessingException e) { log.warn("Unable to translate exception to json: {}", e.getMessage(), e); builder = Response.status(status); builder.type(MediaType.TEXT_PLAIN); builder.entity(message); } finally { log.error(errorString, exception); } return builder.build(); }</code><technical_language>name errorMessage logMessage</technical_language>

Target:
public final Response toResponse(T exception) { String exceptionMessage = Objects.toString(exception.getMessage()); String logMessage = exceptionMessage; StatusType status = this.getStatus(exception); ResponseBuilder builder = Response.status(status); try { final SerializableError error; if (includeStackTrace) { StackTraceElement[] stackTrace = exception.getStackTrace(); error = SerializableError.of(exceptionMessage, exception.getClass(), Arrays.asList(stackTrace)); } else { String errorId = UUID.randomUUID().toString(); logMessage = String.format("Error %s: %s", errorId, exceptionMessage); error = SerializableError.of(errorId, exception.getClass()); } builder.type(MediaType.APPLICATION_JSON); String json = MAPPER.writeValueAsString(error); builder.entity(json); } catch (RuntimeException | JsonProcessingException e) { log.warn("Unable to translate exception to json: {}", e.getMessage(), e); builder = Response.status(status); builder.type(MediaType.TEXT_PLAIN); builder.entity(exceptionMessage); } finally { log.error(logMessage, exception); } return builder.build(); }
Source:
<code>public void iteratesUserOrganizations() throws Exception { final String login = "orgTestIterate"; final MkOrganizations orgs = new MkOrganizations( new MkStorage.InFile(), login ); <START> orgs.get(login); <END> MatcherAssert.assertThat( orgs.iterate(login), Matchers.not(Matchers.emptyIterable()) ); }</code><technical_language>get is here? I this call needed</technical_language>

Target:
public void iteratesUserOrganizations() throws Exception { final String login = "orgTestIterate"; final MkOrganizations orgs = new MkOrganizations( new MkStorage.InFile(), login ); final Organization org = orgs.get(login); MatcherAssert.assertThat( orgs.iterate(org.login()), Matchers.not(Matchers.emptyIterable()) ); }
Source:
<code>public ColumnSortList reloadColumnSortList() { ColumnSortList columnSortList = getListGrid().getColumnSortList(); GridPreferencesStore gridPreferencesStore = getListGrid().getGridPreferencesStore(); if (gridPreferencesStore != null) { GridSortedColumnPreference gridSortedColumnPreference = gridPreferencesStore.getGridSortedColumnPreference(); if (gridSortedColumnPreference != null && columnSortList.size() <= 1) { Optional<ColumnMeta<T>> optional = getListGrid().getColumnMetaList().stream().filter( tColumnMeta -> tColumnMeta.getColumn().getDataStoreName().equals(gridSortedColumnPreference.getDataStoreName())) .findFirst(); if (optional.isPresent()) { Column col = optional.get().getColumn(); String dataStoreName = gridSortedColumnPreference.getDataStoreName(); <START> col.setDataStoreName(dataStoreName); <END> Scheduler.get().scheduleDeferred(new Command() { public void execute () { columnSortList.push(new ColumnSortList.ColumnSortInfo(col, gridSortedColumnPreference.isAscending())); } }); } } } return columnSortList; }</code><technical_language>@bxf12315 in case avoid adding columnSortList if column is there</technical_language>

Target:
public ColumnSortList reloadColumnSortList() { ColumnSortList columnSortList = getListGrid().getColumnSortList(); GridPreferencesStore gridPreferencesStore = getListGrid().getGridPreferencesStore(); if (gridPreferencesStore != null) { GridSortedColumnPreference gridSortedColumnPreference = gridPreferencesStore.getGridSortedColumnPreference(); if (gridSortedColumnPreference != null && columnSortList.size() <= 1) { Optional<ColumnMeta<T>> optional = getListGrid().getColumnMetaList().stream().filter( tColumnMeta -> tColumnMeta.getColumn().getDataStoreName().equals(gridSortedColumnPreference.getDataStoreName())) .findFirst(); if (optional.isPresent()) { if (columnSortList.get(0).getColumn().getDataStoreName().equals(gridSortedColumnPreference.getDataStoreName())) { columnSortList.push(getSecondSortColumn()); } Column col = optional.get().getColumn(); col.setDataStoreName(gridSortedColumnPreference.getDataStoreName()); columnSortList.push(new ColumnSortList.ColumnSortInfo(col, gridSortedColumnPreference.isAscending())); } } } return columnSortList; }
Source:
<code>public void execute(TupleWindow inputWindow) { I reducedValue = null; for (Tuple tuple : inputWindow.get()) { I tup = (I) tuple.getValue(0); if (reducedValue == null) { reducedValue = tup; } else { reducedValue = reduceFn.apply(reducedValue, tup); } } long startWindow; long endWindow; if (inputWindow.getStartTimestamp() == null) { startWindow = 0; } else { startWindow = inputWindow.getStartTimestamp(); } if (inputWindow.getEndTimestamp() == null) { endWindow = 0; } else { endWindow = inputWindow.getEndTimestamp(); } <START> Window window = new Window(startWindow, endWindow); <END> collector.emit(new Values(new KeyValue<>(window, reducedValue))); }</code><technical_language>This ReduceByWindowOperator supports time based window. other types of window</technical_language>

Target:
public void execute(TupleWindow inputWindow) { I reducedValue = null; for (Tuple tuple : inputWindow.get()) { I tup = (I) tuple.getValue(0); if (reducedValue == null) { reducedValue = tup; } else { reducedValue = reduceFn.apply(reducedValue, tup); } } long startWindow; long endWindow; if (inputWindow.getStartTimestamp() == null) { startWindow = 0; } else { startWindow = inputWindow.getStartTimestamp(); } if (inputWindow.getEndTimestamp() == null) { endWindow = 0; } else { endWindow = inputWindow.getEndTimestamp(); } Window window = new Window(startWindow, endWindow, inputWindow.get().size()); collector.emit(new Values(new KeyValue<>(window, reducedValue))); }
Source:
<code>void startConsumer() { if (topicPartitionsToOffset.size() <= 0) { LOG.error ("{}: Consumer is not subscribed to any SSPs", this); } topicPartitionToStartpointMap.forEach((topicPartition, startpoint) -> { Partition partition = new Partition(topicPartition.partition()); SystemStreamPartition systemStreamPartition = new SystemStreamPartition(systemName, topicPartition.topic(), partition); startpoint.apply(systemStreamPartition, kafkaStartpointRegistrationHandler); <START> proxy.addTopicPartition(topicPartitionsToSSP.get(topicPartition), kafkaConsumer.position(topicPartition)); <END> }); topicPartitionsToOffset.forEach((topicPartition, startingOffsetString) -> { if (!topicPartitionToStartpointMap.containsKey(topicPartition)) { long startingOffset = Long.valueOf(startingOffsetString); try { synchronized (kafkaConsumer) { kafkaConsumer.seek(topicPartition, startingOffset); } LOG.info("{}: Changing consumer's starting offset for topicPartition = to {}", this, topicPartition, startingOffsetString); } catch (Exception e) { String msg = String.format("%s: Got Exception while seeking to %s for partition %s", this, startingOffsetString, topicPartition); LOG.error(msg, e); throw new SamzaException(msg, e); } proxy.addTopicPartition(topicPartitionsToSSP.get(topicPartition), kafkaConsumer.position(topicPartition)); } }); if (proxy != null && !proxy.isRunning()) { LOG.info("{}: Starting proxy {}", this, proxy); proxy.start(); } }</code><technical_language>this moved registration handler? this functionality fall responsibility of object</technical_language>

Target:
void startConsumer() { if (topicPartitionToStartpointMap.size() <= 0) { LOG.error ("{}: Consumer is not subscribed to any SSPs", this); } topicPartitionToStartpointMap.forEach((topicPartition, startpoint) -> { Partition partition = new Partition(topicPartition.partition()); SystemStreamPartition systemStreamPartition = new SystemStreamPartition(systemName, topicPartition.topic(), partition); startpoint.apply(systemStreamPartition, kafkaStartpointRegistrationHandler); }); if (proxy != null && !proxy.isRunning()) { LOG.info("{}: Starting proxy {}", this, proxy); proxy.start(); } }
Source:
<code>public void addDataPoints(String auth, List<SignalFxProtocolBuffers.DataPoint> dataPoints) throws SignalFxMetricsException { if (dataPoints.isEmpty()) { return; } try { CloseableHttpResponse resp = null; try { resp = postToEndpoint(auth, getEntityForVersion(dataPoints), getEndpointForAddDatapoints(), <START> !Boolean.getBoolean(DISABLE_COMPRESSION_PROPERTY)); <END> int code = resp.getStatusLine().getStatusCode(); if (code != HttpStatus.SC_OK) { throw new SignalFxMetricsException("Invalid status code " + code); } } finally { if (resp != null) { resp.close(); } } } catch (IOException e) { throw new SignalFxMetricsException("Exception posting to addDataPoints", e); } }</code><technical_language>figure out boolean once</technical_language>

Target:
public void addDataPoints(String auth, List<SignalFxProtocolBuffers.DataPoint> dataPoints) throws SignalFxMetricsException { if (dataPoints.isEmpty()) { return; } try { CloseableHttpResponse resp = null; try { resp = postToEndpoint(auth, getEntityForVersion(dataPoints), getEndpointForAddDatapoints(), compress); int code = resp.getStatusLine().getStatusCode(); if (code != HttpStatus.SC_OK) { throw new SignalFxMetricsException("Invalid status code " + code); } } finally { if (resp != null) { resp.close(); } } } catch (IOException e) { throw new SignalFxMetricsException("Exception posting to addDataPoints", e); } }
Source:
<code>public void updateDominantLocks( String path, UnlockStatus unlockStatus ) { <START> assert true; <END> }</code><technical_language>I this is us, some sort of overhead cost. leave method empty</technical_language>

Target:
public void updateDominantLocks( String path, UnlockStatus unlockStatus ) { }
Source:
<code>public void fieldMissing(Object object, String fieldName, Object value) { if (!DeserializeDeletedFieldHandler.class.isAssignableFrom(object.getClass())) { return; } Object deserialized = value; if (value instanceof JsonObject) { deserialized = new com.cedarsoftware.util.io.JsonReader().jsonObjectsToJava((JsonObject) value); if (deserialized instanceof JsonObject) { deserialized = null; } } Boolean migrated = ((DeserializeDeletedFieldHandler) object).deletedField(fieldName, deserialized); if (migrated) { <START> migratedDeleted[0] = true; <END> } }</code><technical_language>This is realy due this PR, I difficulties understand migratedDeleted is a table of 1 element. change a simple boolean</technical_language>

Target:
public void fieldMissing(Object object, String fieldName, Object value) { if (!DeserializeDeletedFieldHandler.class.isAssignableFrom(object.getClass())) { return; } Object deserialized = value; if (value instanceof JsonObject) { deserialized = new com.cedarsoftware.util.io.JsonReader().jsonObjectsToJava((JsonObject) value); if (deserialized instanceof JsonObject) { deserialized = null; } } Boolean migrated = ((DeserializeDeletedFieldHandler) object).deletedField(fieldName, deserialized); if (migrated) { migratedDeleted.set(true); } }
Source:
<code>private String startUserDialog() throws IOException { log.debug("starting user dialog."); String user; while (true) { System.out.println("Please enter user:"); user = System.console().readLine(); if (StringUtils.isNotEmpty(user)) { break; } <START> } <END> return user; }</code><technical_language>while condition shorter while(StringUtils.isBlank(user)) { StringUtils is org.apache.commons.lang</technical_language>

Target:
private String startUserDialog() throws IOException { log.debug("starting user dialog."); String user = null; while(StringUtils.isBlank(user)) { System.out.println("Please enter user:"); user = System.console().readLine(); } return user; }
Source:
<code>public Object execute(ExecutionEvent event) throws ExecutionException { IReplicationController rc = getSelectedElement(event, IReplicationController.class); <START> if(rc == null) { <END> rc = getSelectedElement(event, IDeploymentConfig.class); } if(rc != null) { scaleUsing(event, rc, rc.getName()); return null; } Deployment deployment = getSelectedElement(event, Deployment.class); if(deployment != null) { Collection<IResourceUIModel> rcs = deployment.getReplicationControllers(); if(!rcs.isEmpty()) { rc = (IReplicationController) rcs.iterator().next().getResource(); scaleUsing(event, rc, deployment.getResource().getName()); } } return null; }</code><technical_language>if a deployment config is selected, a IReplicationController returned in 1st place? In other words, return selected element a more precise type if rc == null</technical_language>

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { IReplicationController rc = getSelectedElement(event, IReplicationController.class); if(rc != null) { scaleUsing(event, rc, rc.getName()); return null; } Deployment deployment = getSelectedElement(event, Deployment.class); if(deployment != null) { Collection<IResourceUIModel> rcs = deployment.getReplicationControllers(); if(!rcs.isEmpty()) { rc = (IReplicationController) rcs.iterator().next().getResource(); scaleUsing(event, rc, deployment.getResource().getName()); } } return null; }
Source:
<code>public boolean getSwipeArticles() { <START> return getBoolean(R.string.pref_key_ui_swipeArticles, true); <END> }</code><technical_language>false</technical_language>

Target:
public boolean getSwipeArticles() { return getBoolean(R.string.pref_key_ui_swipeArticles, false); }
Source:
<code><START> public String getConfigFile() <END> { return configFile; }</code><technical_language>this file File</technical_language>

Target:
public File getConfigFile() { return configFile; }
Source:
<code><START> String getQualifier(Date timestamp) throws MojoFailureException { <END> String qualifier = format.format(timestamp); try { Version.parseVersion(Version.emptyVersion + "." + qualifier); } catch (IllegalArgumentException e) { throw new MojoFailureException("Invalid build qualifier format '" + format.toPattern() + "', it does not match the OSGi qualifier constraint ([0..9]|[a..zA..Z]|'_'|'-')"); } return qualifier; }</code><technical_language>in calculateQualifiedVersion(), other ways set qualifier validated. pull this out a dedicated validateQualifer method call qualifier determined</technical_language>

Target:
String getQualifier(Date timestamp) { return format.format(timestamp); }
Source:
<code>public void sendToAll(String str) throws IOException { for (NanoWebSocketConnection connection : connectionsList) { <START> if (connection != null) { <END> try { connection.send(str); } catch (IOException e) { try { connection.close(WebSocketFrame.CloseCode.InvalidFramePayloadData,"reqrement",false); } catch (IOException e1) { connectionsList.remove(connection); } } } } }</code><technical_language>Needed? expect connections in list null</technical_language>

Target:
public void sendToAll(String str){ for (NanoWebSocketConnection connection : connectionsList) { try { connection.send(str); }catch (IOException e) { try { connection.close(WebSocketFrame.CloseCode.InvalidFramePayloadData, CLOSE_REASON_CANT_SENT,false); } catch (IOException e1) { e1.printStackTrace(); } connectionsList.remove(connection); } } }
Source:
<code>private final PGPEncryptedDataGenerator cpk() throws NoSuchProviderException, PGPException { final PGPEncryptedDataGenerator cpk = new PGPEncryptedDataGenerator(PGPEncryptedData.CAST5, true, prng, "BC"); <START> cpk.addMethod(dest); <END> return cpk; }</code><technical_language>I underestimate fast change. :-( more remove PGP support Gerrit. Yay</technical_language>

Target:
private final PGPEncryptedDataGenerator cpk() throws NoSuchProviderException, PGPException { PGPEncryptedDataGenerator cpk = new PGPEncryptedDataGenerator(PGPEncryptedData.CAST5, true, prng, "BC"); cpk.addMethod(dest); return cpk; }
Source:
<code>CompactionDetails getCompactionDetails(BlobStore blobStore) throws StoreException { ReplicaId replicaId = blobStore.getReplicaId(); <START> if (compactionPolicyFactory != null && compactionPolicyFactory instanceof HybridCompactionPolicyFactory) { CompactionPolicyCounter compactionPolicyCounter = replicaToCounterMap.getOrDefault(replicaId, new CompactionPolicyCounter(storeConfig)); compactionPolicyCounter.increment(); replicaToCounterMap.put(replicaId, compactionPolicyCounter); } <END> return blobStore.getCompactionDetails(compactionPolicy, replicaToCounterMap.get(replicaId)); }</code><technical_language>differentiate compaction policy factory creating incrementing couter. increment for policy</technical_language>

Target:
CompactionDetails getCompactionDetails(BlobStore blobStore) throws StoreException { return blobStore.getCompactionDetails(compactionPolicy); }
Source:
<code>public ActionResult execute() { String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); String teamName = getRequestParamValue(Const.ParamsNames.TEAM_NAME); if (teamName == null) { List<StudentAttributes> studentsForCourse = logic.getStudentsForCourse(courseId); StudentsData studentsData = new StudentsData(studentsForCourse); studentsData.getStudents().forEach(StudentData::hideInformationForInstructor); return new JsonResult(studentsData); } else { <START> List<StudentAttributes> studentsForTeam = logic.getStudentsForTeam(teamName, courseId); <END> StudentsData studentsData = new StudentsData(studentsForTeam); studentsData.getStudents().forEach(StudentData::hideInformationForStudent); return new JsonResult(studentsData); } }</code><technical_language>This is insufficient googleId leaks</technical_language>

Target:
public ActionResult execute() { String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); String teamName = getRequestParamValue(Const.ParamsNames.TEAM_NAME); if (teamName == null) { List<StudentAttributes> studentsForCourse = logic.getStudentsForCourse(courseId); return new JsonResult(new StudentsData(studentsForCourse)); } else { List<StudentAttributes> studentsForTeam = logic.getStudentsForTeam(teamName, courseId); StudentsData studentsData = new StudentsData(studentsForTeam); studentsData.getStudents().forEach(StudentData::hideInformationForStudent); return new JsonResult(studentsData); } }
Source:
<code>private Object parseDateType(Object obj) { try { <START> return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse((String) obj); <END> } catch (ParseException e) { } return obj; }</code><technical_language>This date format is in multiple places. Consider making this a string constant</technical_language>

Target:
private Object parseDateType(Object obj) { try { return new SimpleDateFormat(ISO8601_FORMAT).parse((String) obj); } catch (ParseException e) { return obj; } }
Source:
<code>private void setTicker(String cryptoCurrency, String fiatCurrency) { String crypto = cryptoCurrency.toUpperCase(); String fiat = fiatCurrency.toUpperCase(); <START> this.rateInfo = api.getTicker(crypto, fiat).get(fiat + '_' + crypto); <END> }</code><technical_language>is recommended a network calls in getter. Server handle errors calling getters</technical_language>

Target:
private void setTicker(String cryptoCurrency, String fiatCurrency) { String crypto = cryptoCurrency.toUpperCase(); String fiat = fiatCurrency.toUpperCase(); this.bitKubRateInfo = api.getTicker(crypto, fiat).get(fiat + '_' + crypto); }
Source:
<code>public KMSConfig(VerifiableProperties verifiableProperties) { kmsKeyGenAlgo = verifiableProperties.getString("kms.key.gen.algo", "AES"); kmsDefaultKey = <START> verifiableProperties.getString("kms.default.key", "feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308"); <END> }</code><technical_language>I if set a default key. want require user generate unique service</technical_language>

Target:
public KMSConfig(VerifiableProperties verifiableProperties) { kmsKeyGenAlgo = verifiableProperties.getString("kms.key.gen.algo", "AES"); kmsRandomKeySizeInBits = verifiableProperties.getInt("kms.random.key.size.in.bits", 256); }
Source:
<code>public Client get() throws OseeCoreException { Client client = new Client(); String[] supportedVersions = serverManager.getSupportedVersions(); for (String ver : supportedVersions) { <START> client.getSupportedVersions().add(ver); <END> } return client; }</code><technical_language>add a method class Client add a supported version</technical_language>

Target:
public Client get() throws OseeCoreException { Client client = new Client(); String[] supportedVersions = serverManager.getSupportedVersions(); for (String ver : supportedVersions) { client.addSupportedVersion(ver); } return client; }
Source:
<code>private boolean isWikibaseRedirection(MwRevision mwRevision) { <START> return redirectionsPattern.matcher(mwRevision.getText()).matches(); <END> }</code><technical_language>of main goals of this code is fast possible, I this a regular expression a startsWith similar</technical_language>

Target:
private boolean isWikibaseRedirection(MwRevision mwRevision) { return mwRevision.getText().contains("\"redirect\":"); }
Source:
<code>private void sendVolumeCommand(String itemName, String command, DataOutputStream outToServer, BufferedReader i) throws IOException { char[] cbuf = new char[50]; outToServer.write(hexStringToByteArray(command)); i.read(cbuf, 0, 50); <START> Pattern p = Pattern.compile(".*Vol=(-?\\d{1,2}).*"); <END> Matcher m = p.matcher(new String(cbuf)); if (m.find()) eventPublisher.postUpdate(itemName, new DecimalType(m.group(1))); else logger.error("Error sending command, received this: " + new String(cbuf)); }</code><technical_language>compile pattern statically</technical_language>

Target:
private void sendVolumeCommand(String itemName, String command, DataOutputStream outToServer, BufferedReader i) throws IOException { char[] cbuf = new char[50]; logger.debug("Sending volume command {}", command); outToServer.write(hexStringToByteArray(command)); i.read(cbuf, 0, 50); Matcher m = volumePattern.matcher(new String(cbuf)); if (m.find()) { String volume = m.group(1); eventPublisher.postUpdate(itemName, new DecimalType(volume)); logger.debug("Setting volume for item on {}", itemName, volume); } else { logger.error( "Error sending regular volume command {}, received this: {}", command, new String(cbuf)); } }
Source:
<code>public OpaqueValue<ITuple> fromValues(List<Values> valuesList) { if (valuesList == null || valuesList.size() == 0) { return null; } Values values = valuesList.get(0); int index = 0; SimpleTuple curr = new SimpleTuple(tupleFields); for (String valueField : tupleFields) { curr.put(valueField, values.get(index++)); } if (isAllNull(curr)) { curr = null; } SimpleTuple prev = new SimpleTuple(tupleFields); for (String valueField : tupleFields) { prev.put(valueField, values.get(index++)); } if (isAllNull(prev)) { prev = null; } <START> Long currTx = (Long) values.get(index++); <END> return new OpaqueValue<ITuple>(currTx, curr, prev); }</code><technical_language>I this introduces a bug. index is supposed 0 here, for loops increment it. initialize index 1 above, do get(0) here</technical_language>

Target:
public OpaqueValue<ITuple> fromValues(List<Values> valuesList) { if (valuesList == null || valuesList.size() == 0) { return null; } Values values = valuesList.get(0); int index = 0; @SuppressWarnings("checkstyle:VariableDeclarationUsageDistance") Long currTx = (Long) values.get(index++); SimpleTuple curr = new SimpleTuple(tupleFields); for (String valueField : tupleFields) { curr.put(valueField, values.get(index++)); } if (isAllNull(curr)) { curr = null; } SimpleTuple prev = new SimpleTuple(tupleFields); for (String valueField : tupleFields) { prev.put(valueField, values.get(index++)); } if (isAllNull(prev)) { prev = null; } return new OpaqueValue<ITuple>(currTx, curr, prev); }
Source:
<code>public Component getComponent(int number) { SideEffect effect = getSideEffects().get(number); SideEffect.State state = this.sideEffectSet.getState(effect); TextComponent.Builder builder = TextComponent.builder(); builder = builder.append(TranslatableComponent.of(effect.getDisplayName(), TextColor.YELLOW) .hoverEvent(HoverEvent.of(HoverEvent.Action.SHOW_TEXT, TranslatableComponent.of(effect.getDescription())))); for (SideEffect.State uiState : SideEffect.State.values()) { builder = builder.append(TextComponent.space()); builder = builder.append(TranslatableComponent.of(uiState.getDisplayName(), uiState == state ? TextColor.WHITE : TextColor.GRAY) .clickEvent(ClickEvent.runCommand(" .hoverEvent(HoverEvent.showText(uiState == state ? <START> TextComponent.of("Current") : TextComponent.of("Click to set to ").append(TranslatableComponent.of(uiState.getDisplayName())))) <END> ); } return builder.build(); }</code><technical_language>i18n</technical_language>

Target:
public Component getComponent(int number) { SideEffect effect = getSideEffects().get(number); SideEffect.State state = this.sideEffectSet.getState(effect); TextComponent.Builder builder = TextComponent.builder(); builder = builder.append(TranslatableComponent.of(effect.getDisplayName(), TextColor.YELLOW) .hoverEvent(HoverEvent.of(HoverEvent.Action.SHOW_TEXT, TranslatableComponent.of(effect.getDescription())))); for (SideEffect.State uiState : SHOWN_VALUES) { builder = builder.append(TextComponent.space()); builder = builder.append(TranslatableComponent.of(uiState.getDisplayName(), uiState == state ? TextColor.WHITE : TextColor.GRAY) .clickEvent(ClickEvent.runCommand(" .hoverEvent(HoverEvent.showText(uiState == state ? TranslatableComponent.of("worldedit.sideeffect.box.current") : TranslatableComponent.of("worldedit.sideeffect.box.change-to", TranslatableComponent.of(uiState.getDisplayName())) )) ); } return builder.build(); }
Source:
<code>public static void main(String[] args) { ConsoleAppender console = new ConsoleAppender(); console.setLayout(new PatternLayout("%d{ISO8601} [%t] %-5p %c - %m%n")); console.setThreshold(Level.DEBUG); console.activateOptions(); Logger.getRootLogger().addAppender(console); GraphicalSurveySummaryExporter exporter = new GraphicalSurveySummaryExporter(); Map<String, String> criteria = new HashMap<String, String>(); Map<String, String> options = new HashMap<String, String>(); options.put(LOCALE_OPT, "en"); options.put(LAST_COLLECTION_OPT, "false"); <START> options.put("useQuestionId", "true"); END> options.put("email", "email@example.com"); options.put("from", null); options.put("to", null); options.put("maxDataReportRows", null); criteria.put(SurveyRestRequest.SURVEY_ID_PARAM, args[2]); criteria.put("apiKey", args[3]); exporter.export(criteria, new File(args[0]), args[1], options); }</code><technical_language>Some left overs..? :)</technical_language>

Target:
public static void main(String[] args) { ConsoleAppender console = new ConsoleAppender(); console.setLayout(new PatternLayout("%d{ISO8601} [%t] %-5p %c - %m%n")); console.setThreshold(Level.DEBUG); console.activateOptions(); Logger.getRootLogger().addAppender(console); GraphicalSurveySummaryExporter exporter = new GraphicalSurveySummaryExporter(); Map<String, String> criteria = new HashMap<String, String>(); Map<String, String> options = new HashMap<String, String>(); options.put(LOCALE_OPT, "en"); options.put(LAST_COLLECTION_OPT, "false"); options.put("useQuestionId", "false"); options.put("email", "email@example.com"); options.put("from", null); options.put("to", null); options.put("maxDataReportRows", null); criteria.put(SurveyRestRequest.SURVEY_ID_PARAM, args[2]); criteria.put("apiKey", args[3]); exporter.export(criteria, new File(args[0]), args[1], options); }
Source:
<code>public void testIncludedProtocols() throws Exception { URL url = new URL(baseUrl, SERVLET_PATH_ECHO + "?a=b&c=d"); String includedProtocols; <START> String version = System.getProperty("java.version"); if (version.startsWith("1.")) { includedProtocols = INCLUDED_PROTOCOLS; } else { includedProtocols = INCLUDED_PROTOCOLS_JDK11; } <END> HttpsURLConnection conn = getConnectionWithPreferredProtocolSSLSocketFactory(url, includedProtocols); assertFalse("included protocol list is empty", includedProtocols.isEmpty()); readFromConnection(conn); PreferredProtocolSSLSocketFactory factory = (PreferredProtocolSSLSocketFactory)conn.getSSLSocketFactory(); if (version.startsWith("1.")) { assertEquals("TLSv1.2", factory.getSocket().getSession().getProtocol()); } else { assertEquals("TLSv1.3", factory.getSocket().getSession().getProtocol()); } }</code><technical_language>utility method parse java.version string. This change avoid test failure in Java 9 10 (corner case). suggestion if (Shell.isJavaVersionAtLeast(11) { includedProtocols = INCLUDED_PROTOCOLS_JDK11; } else { includedProtocols = INCLUDED_PROTOCOLS; }</technical_language>

Target:
public void testIncludedProtocols() throws Exception { URL url = new URL(baseUrl, SERVLET_PATH_ECHO + "?a=b&c=d"); String includedProtocols = INCLUDED_PROTOCOLS; if (Shell.isJavaVersionAtLeast(11)) { includedProtocols = INCLUDED_PROTOCOLS_JDK11; } HttpsURLConnection conn = getConnectionWithPreferredProtocolSSLSocketFactory(url, includedProtocols); assertFalse("included protocol list is empty", includedProtocols.isEmpty()); readFromConnection(conn); PreferredProtocolSSLSocketFactory factory = (PreferredProtocolSSLSocketFactory)conn.getSSLSocketFactory(); if (Shell.isJavaVersionAtLeast(11)) { assertEquals("TLSv1.3", factory.getSocket().getSession().getProtocol()); } else { assertEquals("TLSv1.2", factory.getSocket().getSession().getProtocol()); } }