auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void deleteOneTemplateTest() throws Exception { context.turnOffAuthorisationSystem(); parentCommunity = CommunityBuilder.createCommunity(context) .withName("Parent Community") .build(); Collection col1 = CollectionBuilder.createCollection(context, parentCommunity).withName("Collection 1").build(); Item templateItem = ItemBuilder.createTemplateItem(context, col1); String token = getAuthToken(admin.getEmail(), password); getClient().perform(get("/api/core/items/" + templateItem.getID())) .andExpect(status().isOk()); <START> getClient(token).perform(delete("/api/core/items/" + templateItem.getID())) <END> .andExpect(status().is(422)); }</code><technical_language>is more useful test item is a failed attempt delete</technical_language>

Target:
public void deleteOneTemplateTest() throws Exception { context.turnOffAuthorisationSystem(); parentCommunity = CommunityBuilder.createCommunity(context) .withName("Parent Community") .build(); Collection col1 = CollectionBuilder.createCollection(context, parentCommunity).withName("Collection 1") .withTemplateItem() .build(); Item templateItem = col1.getTemplateItem(); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(delete("/api/core/items/" + templateItem.getID())) .andExpect(status().is(422)); getClient().perform(get("/api/core/items/" + templateItem.getID())) .andExpect(status().isOk()); }
Source:
<code>public void stop() { Runnable r = new Runnable() { @Override public void run() { stopHawkularAgent(); } }; <START> new Thread(r).start(); <END> }</code><technical_language>Give a name this thread, if hangs blows up, stack trace give a clue called it. i.e: new Thread(r, "Hawkular Java Agent Stop Thread").start(); I need this some more merging making stop() method asynchronous. check kinds of thread safety/concurrency issues this (especially in cases agent is restarted, for example, stop is quickly start. need in start is initiated this stop thread is kicked finishes). In other words, making stop method asynchronous some side affects "bad" some synchronization/locking put in place</technical_language>

Target:
public void stop() { stopHawkularAgent(); }
Source:
<code>protected void delete(Context context, UUID uuid) throws AuthorizeException { Group group = null; try { group = gs.find(context, uuid); if (group == null) { throw new ResourceNotFoundException( GroupRest.CATEGORY + "." + GroupRest.NAME + " with id: " + uuid + " not found" ); } if (isDeleteUnprocessable(context, group)) { <START> throw new UnprocessableEntityException("This group cannot be deleted"); <END> } gs.delete(context, group); } catch (SQLException | IOException e) { throw new RuntimeException(e.getMessage(), e); } }</code><technical_language>Again, prefer more descriptive errors group deleted</technical_language>

Target:
protected void delete(Context context, UUID uuid) throws AuthorizeException { Group group = null; try { group = gs.find(context, uuid); if (group == null) { throw new ResourceNotFoundException( GroupRest.CATEGORY + "." + GroupRest.NAME + " with id: " + uuid + " not found" ); } try { if (group.isPermanent()) { throw new UnprocessableEntityException("A permanent group cannot be deleted"); } final DSpaceObject parentObject = gs.getParentObject(context, group); if (parentObject != null) { throw new UnprocessableEntityException( "This group cannot be deleted" + " as it has a parent " + parentObject.getType() + " with id " + parentObject.getID()); } } catch (SQLException e) { throw new RuntimeException(e); } gs.delete(context, group); } catch (SQLException | IOException e) { throw new RuntimeException(e.getMessage(), e); } }
Source:
<code>void clearExpressionType() { <START> final GridCellTuple gc = new GridCellTuple(0, <END> 0, this); final FunctionDefinition function = expression.get(); sessionCommandManager.execute((AbstractCanvasHandler) sessionManager.getCurrentSession().getCanvasHandler(), new ClearExpressionTypeCommand(gc, function, uiModelMapper, () -> synchroniseViewWhenExpressionEditorChanged(Optional.empty()))); }</code><technical_language>start this expression.ifPresent(function...</technical_language>

Target:
void clearExpressionType() { expression.ifPresent(function -> { final GridCellTuple gc = new GridCellTuple(0, 0, this); sessionCommandManager.execute((AbstractCanvasHandler) sessionManager.getCurrentSession().getCanvasHandler(), new ClearExpressionTypeCommand(gc, function, uiModelMapper, () -> synchroniseViewWhenExpressionEditorChanged(Optional.empty()))); }); }
Source:
<code>private ExecuteResult(InputStream stream, InputStream errorStream, int responseCode, String responseMessage, Throwable cause, JSONHelper jsonHelper) { this.responseCode = responseCode; boolean needsCouchException = false; <START> System.out.println("Response: "+responseMessage); <END> switch(responseCode / 100) { case 1: case 2: this.fatal = false; this.exception = null; this.stream = stream; break; case 3: break; case 4: this.fatal = true; if (responseCode == 404) { this.exception = new NoResourceException(responseMessage, cause); } else if (responseCode == 409) { this.exception = new DocumentConflictException(responseMessage); } else { needsCouchException = true; } break; case 5: this.fatal = false; needsCouchException = true; break; default: this.fatal = false; needsCouchException = true; } if (needsCouchException) { try { Map<String, String> json = jsonHelper.fromJson(new InputStreamReader(errorStream), Map.class); CouchException ce = new CouchException(responseMessage, cause, responseCode); ce.setError(json.get("error")); ce.setReason(json.get("reason")); this.exception = ce; } catch (Exception e) { CouchException ce = new CouchException("Error deserializing server response", cause, responseCode); this.exception = ce; } } }</code><technical_language>Log delete</technical_language>

Target:
private ExecuteResult(InputStream stream, InputStream errorStream, int responseCode, String responseMessage, Throwable cause, JSONHelper jsonHelper) { this.responseCode = responseCode; boolean needsCouchException = false; switch(responseCode / 100) { case 1: case 2: this.fatal = false; this.exception = null; this.stream = stream; break; case 3: throw new CouchException("Unexpected redirection (3xx) code encountered", responseCode); case 4: this.fatal = true; if (responseCode == 404) { this.exception = new NoResourceException(responseMessage, cause); } else if (responseCode == 409) { this.exception = new DocumentConflictException(responseMessage); } else { needsCouchException = true; } break; case 5: this.fatal = false; needsCouchException = true; break; default: this.fatal = false; needsCouchException = true; } if (needsCouchException) { try { Map<String, String> json = jsonHelper.fromJson(new InputStreamReader(errorStream), Map.class); CouchException ce = new CouchException(responseMessage, cause, responseCode); ce.setError(json.get("error")); ce.setReason(json.get("reason")); this.exception = ce; } catch (Exception e) { CouchException ce = new CouchException("Error deserializing server response", cause, responseCode); this.exception = ce; } } }
Source:
<code><START> private static IEclipseContext headlessContext() { <END> if (HEADLESS_CONTEXT == null) { HEADLESS_CONTEXT = EclipseContextFactory.create("headlessContext"); } return HEADLESS_CONTEXT; }</code><technical_language>synchronized? (SIngleton)</technical_language>

Target:
private static synchronized IEclipseContext headlessContext() { if (HEADLESS_CONTEXT == null) { HEADLESS_CONTEXT = EclipseContextFactory.create("headlessContext"); } return HEADLESS_CONTEXT; }
Source:
<code>public void testMaxAge() throws InterruptedException { Summary summary = Summary.build() .quantile(0.99, 0.001) .maxAgeMillis(200) .nBuckets(2) .name("short_attention_span").help("help").register(registry); summary.observe(8.0); double val = registry.getSampleValue("short_attention_span", new String[]{"quantile"}, new String[]{Collector.doubleToGoString(0.99)}).doubleValue(); assertEquals(8.0, val, 0.0); <START> Thread.sleep(100); <END> val = registry.getSampleValue("short_attention_span", new String[]{"quantile"}, new String[]{Collector.doubleToGoString(0.99)}).doubleValue(); assertEquals(8.0, val, 0.0); Thread.sleep(100); val = registry.getSampleValue("short_attention_span", new String[]{"quantile"}, new String[]{Collector.doubleToGoString(0.99)}).doubleValue(); assertEquals(Double.NaN, val, 0.0); }</code><technical_language>tight, give 50ms slack</technical_language>

Target:
public void testMaxAge() throws InterruptedException { Summary summary = Summary.build() .quantile(0.99, 0.001) .maxAgeSeconds(1) .ageBuckets(2) .name("short_attention_span").help("help").register(registry); summary.observe(8.0); double val = registry.getSampleValue("short_attention_span", new String[]{"quantile"}, new String[]{Collector.doubleToGoString(0.99)}).doubleValue(); assertEquals(8.0, val, 0.0); Thread.sleep(600); val = registry.getSampleValue("short_attention_span", new String[]{"quantile"}, new String[]{Collector.doubleToGoString(0.99)}).doubleValue(); assertEquals(8.0, val, 0.0); Thread.sleep(600); val = registry.getSampleValue("short_attention_span", new String[]{"quantile"}, new String[]{Collector.doubleToGoString(0.99)}).doubleValue(); assertEquals(Double.NaN, val, 0.0); }
Source:
<code>public void run() { do { state.accept(this); setPosition(getPosition() + 1); setProgress(); <START> if (supervisor != null && supervisor.isInterrupted()) { <END> return; } } while (!(state.equals(ImageGeneratorStep.GENERATE_IMAGES) && getPosition() == getContentToBeGenerated().size())); logger.info("Completed"); }</code><technical_language>Objects.nonNull</technical_language>

Target:
public void run() { do { state.accept(this); setPosition(getPosition() + 1); setProgress(); if (Objects.nonNull(supervisor) && supervisor.isInterrupted()) { return; } } while (!(state.equals(ImageGeneratorStep.GENERATE_IMAGES) && getPosition() == getContentToBeGenerated().size())); logger.info("Completed"); }
Source:
<code>public void execute(SchemaMigrationOption schemaMigrationOption) throws SQLException { switch (schemaMigrationOption) { case CREATE: create(); break; case MIGRATE: migrate(); break; case INFO: info(); break; <START> case VALIDATE: <END> validate(); break; case DROP: clean(); break; case CHECK_CONNECTION: if(!checkConnection()) { System.exit(1); } break; case REPAIR: repair(); break; default: throw new SchemaMigrationException("SchemaMigrationHelper unable to execute the option : " + schemaMigrationOption.toString()); } }</code><technical_language>exit</technical_language>

Target:
public void execute(SchemaMigrationOption schemaMigrationOption) throws SQLException { switch (schemaMigrationOption) { case CREATE: create(); break; case MIGRATE: migrate(); break; case INFO: info(); break; case VALIDATE: validate(); break; case DROP: clean(); break; case CHECK_CONNECTION: checkConnection(); break; case REPAIR: repair(); break; default: throw new SchemaMigrationException("SchemaMigrationHelper unable to execute the option : " + schemaMigrationOption.toString()); } }
Source:
<code>public Key getKey(int pos) { <START> return new Key(key.getRow(), timeStamps.get(pos)); <END> }</code><technical_language>this following, if I method name Key correct java Key tmpKey = new Key(key); tmpKey.setTimestamp(timeStamps.get(pos)); return tmpKey;</technical_language>

Target:
public Key getKey(int pos) { Key tmpKey = new Key(key); tmpKey.setTimestamp(timeStamps.get(pos)); return tmpKey; }
Source:
<code>public synchronized void close() throws IOException { try { keySerializer.close(); valSerializer.close(); if (out != null) { if (ownOutputStream) { out.close(); } else { out.flush(); } <START> out = null; <END> } } finally { if (fs != null) { try { fs.close(); } catch (Throwable t) { log.error("Could not close FileSystem", t); } } } }</code><technical_language>this in try-finally block? Right now, if out.close() out.flush() throws exception, null out and, if close() is called more (albeit unnecessarily) call close flush another time. simpler ensure null out in finally block</technical_language>

Target:
public synchronized void close() throws IOException { try { keySerializer.close(); valSerializer.close(); if (out != null) { if (ownOutputStream) { out.close(); } else { out.flush(); } } } finally { if (fs != null) { try { fs.close(); } catch (Throwable t) { log.error("Could not close FileSystem", t); } } out = null; } }
Source:
<code>protected void runOneIteration() throws Exception { log.trace("runOneIteration() - Enter"); lock.lock(); try { updateCache(); } finally { lock.unlock(); } <START> log.trace("runOneIteration() - Exit"); <END> }</code><technical_language>this log message moved finally block called if Exception is thrown</technical_language>

Target:
protected void runOneIteration() throws Exception { log.trace("runOneIteration() - Enter"); lock.lock(); try { updateCache(); } finally { lock.unlock(); log.trace("runOneIteration() - Exit"); } }
Source:
<code>public Application createApplication(Application application) { ApplicationCredentials.Builder credentialsBuilder; if (application.getCredentials() != null) { credentialsBuilder = application.getCredentials().copy(); } else { credentialsBuilder = ApplicationCredentials.builder(); } credentialsBuilder = credentialsBuilder.withApiKey(generateApiKey()); ApplicationSources sources = application.getSources(); if (sources == null) { <START> sources = ApplicationSources <END> .builder() .withPrecedence(false) .withReads(ImmutableList.<SourceReadEntry>of()) .withWrites(ImmutableList.<Publisher>of()) .build(); } Id id = Id.valueOf(idGenerator.generateRaw()); Application created = application.copy() .withId(id) .withCreated(clock.now()) .withSlug(generateSlug(id)) .withCredentials(credentialsBuilder.build()) .withSources(sources) .build(); doCreateApplication(created); return created; }</code><technical_language>this extracted a ApplicationSources.defaultSources() method returns a private static final instance is this 'empty' sources</technical_language>

Target:
public Application createApplication(Application application) { ApplicationCredentials.Builder credentialsBuilder; if (application.getCredentials() != null) { credentialsBuilder = application.getCredentials().copy(); } else { credentialsBuilder = ApplicationCredentials.builder(); } credentialsBuilder = credentialsBuilder.withApiKey(generateApiKey()); ApplicationSources sources = application.getSources(); if (sources == null) { sources = ApplicationSources.EMPTY_SOURCES; } Id id = Id.valueOf(idGenerator.generateRaw()); Application created = application.copy() .withId(id) .withCreated(clock.now()) .withSlug(generateSlug(id)) .withCredentials(credentialsBuilder.build()) .withSources(sources) .build(); doCreateApplication(created); return created; }
Source:
<code>private <START> byte getJpegQuality() <END> { if (mCaptureMode == CAPTURE_MODE_MAXIMIZE_QUALITY) { return JPEG_QUALITY_MAXIMIZE_QUALITY_MODE; } else if (mCaptureMode == CAPTURE_MODE_MINIMIZE_LATENCY) { return JPEG_QUALITY_MINIMIZE_LATENCY_MODE; } else { throw new IllegalStateException("CaptureMode " + mCaptureMode + " is insvalid"); } }</code><technical_language>this int? I need extra precision, API guidelines avoid "short" "byte". This allow annotate @IntRange(from=0, to=100) this API future setter APIs</technical_language>

Target:
private byte getJpegQuality() { switch (mCaptureMode) { case CAPTURE_MODE_MAXIMIZE_QUALITY: return JPEG_QUALITY_MAXIMIZE_QUALITY_MODE; case CAPTURE_MODE_MINIMIZE_LATENCY: return JPEG_QUALITY_MINIMIZE_LATENCY_MODE; default: throw new IllegalStateException("CaptureMode " + mCaptureMode + " is invalid"); } }
Source:
<code>public int read(byte[] bytesEntry, int off, int len) throws IOException { try { if (off > 0) { byte[] data = new byte[(len < 10240) ? len : 10240]; <START> int size = recv(fd, data, (len < 10240) ? len : 10240, 0); <END> if (size > 0) { System.arraycopy(data, 0, bytesEntry, off, size); } return size; } else { return recv(fd, bytesEntry, len, 0); } } catch (LastErrorException lee) { throw new IOException("native read() failed : " + formatError(lee)); } }</code><technical_language>loop in case len > 10240, code truncating</technical_language>

Target:
public int read(byte[] bytesEntry, int off, int len) throws IOException { if (!isConnected()) { return -1; } try { if (off > 0) { byte[] data = new byte[(len < 10240) ? len : 10240]; int size = recv(fd, data, data.length, 0); if (size <= 0) { return -1; } System.arraycopy(data, 0, bytesEntry, off, size); return size; } else { int size = recv(fd, bytesEntry, len, 0); if (size <= 0) { return -1; } return size; } } catch (LastErrorException lee) { throw new IOException("native read() failed : " + formatError(lee)); } }
Source:
<code>public static Point getTopLeftCornerOfFBNetwork(List<?> selection) { Assert.isNotNull(selection); Point pt = new Point(0, 0); Object fb = null; for (Object sel : selection) { fb = (sel instanceof EditPart) ? ((EditPart) sel).getModel() : sel; if (fb instanceof <START> FBImpl) { <END> pt.x = (pt.x == 0) ? ((FBNetworkElement) fb).getX() : Math.min(pt.x, ((FBNetworkElement) fb).getX()); pt.y = (pt.y == 0) ? ((FBNetworkElement) fb).getY() : Math.min(pt.y, ((FBNetworkElement) fb).getY()); } } return pt; }</code><technical_language>please impl classes model. FB interface in this case</technical_language>

Target:
public static Point getTopLeftCornerOfFBNetwork(List<?> selection) { Assert.isNotNull(selection); Point pt = new Point(0, 0); Object fb = null; for (Object sel : selection) { fb = (sel instanceof EditPart) ? ((EditPart) sel).getModel() : sel; if (fb instanceof FB) { pt.x = (pt.x == 0) ? ((FBNetworkElement) fb).getX() : Math.min(pt.x, ((FBNetworkElement) fb).getX()); pt.y = (pt.y == 0) ? ((FBNetworkElement) fb).getY() : Math.min(pt.y, ((FBNetworkElement) fb).getY()); } } return pt; }
Source:
<code>public List<PictureView> computeViewsFor(Blob blob, List<PictureConversion> pictureConversions, ImageInfo imageInfo, boolean convert) { String mimeType = blob.getMimeType(); if (mimeType == null) { blob.setMimeType(getImageMimeType(blob)); } if (imageInfo == null) { imageInfo = getImageInfo(blob); } List<PictureView> views = new ArrayList<>(); for (PictureConversion pictureConversion : pictureConversions) { try { views.add(computeView(blob, pictureConversion, imageInfo, convert)); } catch (NuxeoException e) { <START> log.warn("Unable to compute view: {}: {}", pictureConversion::getId, e::getMessage); <END> log.debug(e, e); } } return views; }</code><technical_language>remove :</technical_language>

Target:
public List<PictureView> computeViewsFor(Blob blob, List<PictureConversion> pictureConversions, ImageInfo imageInfo, boolean convert) { String mimeType = blob.getMimeType(); if (mimeType == null) { blob.setMimeType(getImageMimeType(blob)); } if (imageInfo == null) { imageInfo = getImageInfo(blob); } List<PictureView> views = new ArrayList<>(); for (PictureConversion pictureConversion : pictureConversions) { try { views.add(computeView(blob, pictureConversion, imageInfo, convert)); } catch (NuxeoException e) { log.warn("Unable to compute view: exception message: {}", pictureConversion::getId, e::getMessage); log.debug(e, e); } } return views; }
Source:
<code>public Response createPoly(byte[] inputToAutodetectType) { log.debug("Creating app from autodetecting input"); boolean looksLikeLegacy = false; Exception legacyFormatException = null; try { ApplicationSpec appSpec = mapper().readValue(inputToAutodetectType, ApplicationSpec.class); return createFromAppSpec(appSpec); } catch (Exception e) { legacyFormatException = e; <START> log.debug("Input is not legacy ApplicationSpec JSON (will try others): "+e, e); <END> } AssemblyTemplate template = null; boolean looksLikeYaml = false; try { template = camp().pdp().registerDeploymentPlan(new StringReader(new String(inputToAutodetectType))); if (!template.getPlatformComponentTemplates().isEmpty() || !template.getApplicationComponentTemplates().isEmpty()) { looksLikeYaml = true; } else { if (template.getCustomAttributes().containsKey("type")) { looksLikeLegacy = true; } } } catch (Exception e) { log.debug("Input is not valid YAML: "+e); } if (template!=null) { try { return launch(template); } catch (Exception e) { if (looksLikeYaml) throw Throwables.propagate(e); } } if (looksLikeLegacy && legacyFormatException!=null) throw Throwables.propagate(legacyFormatException); return Response.serverError().entity("Unsupported format; not able to autodetect.").build(); }</code><technical_language>do a Exceptions.propagateIfFatal(e) well</technical_language>

Target:
public Response createPoly(byte[] inputToAutodetectType) { log.debug("Creating app from autodetecting input"); boolean looksLikeLegacy = false; Exception legacyFormatException = null; try { ApplicationSpec appSpec = mapper().readValue(inputToAutodetectType, ApplicationSpec.class); return createFromAppSpec(appSpec); } catch (Exception e) { Exceptions.propagateIfFatal(e); legacyFormatException = e; log.debug("Input is not legacy ApplicationSpec JSON (will try others): "+e, e); } AssemblyTemplate template = null; boolean looksLikeYaml = false; try { template = camp().pdp().registerDeploymentPlan(new StringReader(new String(inputToAutodetectType))); if (!template.getPlatformComponentTemplates().isEmpty() || !template.getApplicationComponentTemplates().isEmpty()) { looksLikeYaml = true; } else { if (template.getCustomAttributes().containsKey("type")) { looksLikeLegacy = true; } } } catch (Exception e) { Exceptions.propagateIfFatal(e); log.debug("Input is not valid YAML: "+e); } if (template!=null) { try { return launch(template); } catch (Exception e) { Exceptions.propagateIfFatal(e); if (looksLikeYaml) throw Exceptions.propagate(e); } } if (looksLikeLegacy && legacyFormatException!=null) throw Throwables.propagate(legacyFormatException); return Response.serverError().entity("Unsupported format; not able to autodetect.").build(); }
Source:
<code><START> public boolean equalsSignature(Object obj) { <END> if (obj instanceof FunctionDesc) { return this.getSignature().equalsWithoutType(obj); } return false; }</code><technical_language>Please remove unused method</technical_language>

Target:
public boolean equalsSignature(Object obj) { if (obj instanceof FunctionDesc) { return this.getSignature().equalsWithoutType(((FunctionDesc) obj).getSignature()); } return false; }
Source:
<code>public boolean isClosed() { <START> return ehCacheManager.getStatus() != Status.AVAILABLE; <END> }</code><technical_language>This == UNINITIALIZED in line discussed for Cache</technical_language>

Target:
public boolean isClosed() { return ehCacheManager.getStatus() == Status.UNINITIALIZED; }
Source:
<code>public ListenableFuture<?> processFor(Duration duration) { checkLockNotHeld("Can not process for a duration while holding the driver lock"); requireNonNull(duration, "duration is null"); long maxRuntime = duration.roundTo(TimeUnit.NANOSECONDS); Optional<ListenableFuture<?>> result = tryWithLock(100, TimeUnit.MILLISECONDS, () -> { <START> driverContext.getYieldSignal().yieldAfter(maxRuntime, driverContext.getExecutor()); <END> driverContext.startProcessTimer(); try { long start = System.nanoTime(); do { ListenableFuture<?> future = processInternal(); if (!future.isDone()) { return future; } } while (System.nanoTime() - start < maxRuntime && !isFinishedInternal()); } finally { driverContext.getYieldSignal().reset(); driverContext.recordProcessed(); } return NOT_BLOCKED; }); return result.orElse(NOT_BLOCKED); }</code><technical_language>I feel yieldAfter is misleading. I expecting a lambda Runnable supplied a function a name. I propose setWithDelay line. other people think. This way, name is symmetric reset method</technical_language>

Target:
public ListenableFuture<?> processFor(Duration duration) { checkLockNotHeld("Can not process for a duration while holding the driver lock"); requireNonNull(duration, "duration is null"); long maxRuntime = duration.roundTo(TimeUnit.NANOSECONDS); Optional<ListenableFuture<?>> result = tryWithLock(100, TimeUnit.MILLISECONDS, () -> { driverContext.startProcessTimer(); driverContext.getYieldSignal().setWithDelay(maxRuntime, driverContext.getYieldExecutor()); try { long start = System.nanoTime(); do { ListenableFuture<?> future = processInternal(); if (!future.isDone()) { return wakeUpOnRevokeRequest(future); } } while (System.nanoTime() - start < maxRuntime && !isFinishedInternal()); } finally { driverContext.getYieldSignal().reset(); driverContext.recordProcessed(); } return NOT_BLOCKED; }); return result.orElse(NOT_BLOCKED); }
Source:
<code>@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) { writer.setBuffer(buf); if (!writer.isHeaderWritten()) { if (!writer.writeHeader(directType(), fieldsCount())) return false; writer.onHeaderWritten(); } switch (writer.state()) { case 0: if (!writer.writeMessage("msg", msg)) return false; writer.incrementState(); case 1: if (!writer.writeBoolean("ordered", ordered)) return false; writer.incrementState(); case 2: if (!writer.writeByte("plc", plc)) return false; writer.incrementState(); case 3: <START> if (!writer.writeUuid("secSubjId", secSubjId)) <END> return false; writer.incrementState(); case 4: if (!writer.writeBoolean("skipOnTimeout", skipOnTimeout)) return false; writer.incrementState(); case 5: if (!writer.writeLong("timeout", timeout)) return false; writer.incrementState(); case 6: if (!writer.writeByteArray("topicBytes", topicBytes)) return false; writer.incrementState(); case 7: if (!writer.writeInt("topicOrd", topicOrd)) return false; writer.incrementState(); } return true; }</code><technical_language>insert a new field middle of existing message? compatibility</technical_language>

Target:
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) { writer.setBuffer(buf); if (!writer.isHeaderWritten()) { if (!writer.writeHeader(directType(), fieldsCount())) return false; writer.onHeaderWritten(); } switch (writer.state()) { case 0: if (!writer.writeMessage("msg", msg)) return false; writer.incrementState(); case 1: if (!writer.writeBoolean("ordered", ordered)) return false; writer.incrementState(); case 2: if (!writer.writeByte("plc", plc)) return false; writer.incrementState(); case 3: if (!writer.writeBoolean("skipOnTimeout", skipOnTimeout)) return false; writer.incrementState(); case 4: if (!writer.writeLong("timeout", timeout)) return false; writer.incrementState(); case 5: if (!writer.writeByteArray("topicBytes", topicBytes)) return false; writer.incrementState(); case 6: if (!writer.writeInt("topicOrd", topicOrd)) return false; writer.incrementState(); } return true; }
Source:
<code>public SqlUserDefinedAggFunction(SqlIdentifier opName, SqlReturnTypeInference returnTypeInference, SqlOperandTypeInference operandTypeInference, SqlOperandTypeChecker operandTypeChecker, AggregateFunction function, boolean requiresOrder, boolean requiresOver, RelDataTypeFactory typeFactory) { super(Util.last(opName.names), opName, SqlKind.getSqlKindByName(opName.names.get(0)) != null <START> ? SqlKind.valueOf(opName.names.get(0)) : SqlKind.OTHER_FUNCTION, <END> returnTypeInference, operandTypeInference, operandTypeChecker, SqlFunctionCategory.USER_DEFINED_FUNCTION, requiresOrder, requiresOver); this.function = function; this.typeFactory = typeFactory; }</code><technical_language>this is right approach. do is "user-defined SUM function" treated standard SUM function giving a single check actual implementation. trigger some optimization rules alter results. For instance, Calcite replace user-defined AVG(...) standard SUM(...)/COUNT(...)</technical_language>

Target:
public SqlUserDefinedAggFunction(SqlIdentifier opName, SqlReturnTypeInference returnTypeInference, SqlOperandTypeInference operandTypeInference, SqlOperandTypeChecker operandTypeChecker, AggregateFunction function, boolean requiresOrder, boolean requiresOver, RelDataTypeFactory typeFactory) { super(Util.last(opName.names), opName, SqlKind.OTHER_FUNCTION, returnTypeInference, operandTypeInference, operandTypeChecker, SqlFunctionCategory.USER_DEFINED_FUNCTION, requiresOrder, requiresOver); this.function = function; this.typeFactory = typeFactory; }
Source:
<code>private boolean hasOpenableDRepresentations() { boolean hasOpenableDRepresentations = false; Collection<DRepresentation> representations = DialectManager.INSTANCE.getRepresentations(semanticElement, session); for (DRepresentation representation : representations) { if <START> (session.getSelectedViews().contains(representation.eContainer())) <END> { hasOpenableDRepresentations = true; break; } } return hasOpenableDRepresentations; }</code><technical_language>This is (relatively) costly, moved out of for loop</technical_language>

Target:
private boolean hasOpenableDRepresentations() { boolean hasOpenableDRepresentations = false; Collection<DRepresentation> representations = DialectManager.INSTANCE.getRepresentations(semanticElement, session); Collection<DView> selectedViews = session.getSelectedViews(); for (DRepresentation representation : representations) { if (selectedViews.contains(representation.eContainer())) { hasOpenableDRepresentations = true; break; } } return hasOpenableDRepresentations; }
Source:
<code>public void canReleaseLock() { LockEntry entry = lockStore.acquireBackupLock(TEST_REASON); <START> PersistentLockId entryId = ImmutablePersistentLockId.of(entry.instanceId()); <END> service.releaseLock(entryId); verify(lockStore, times(1)).releaseLock(entry); }</code><technical_language>hit acquire service. a bit weird interacting lock store</technical_language>

Target:
public void canReleaseLock() { PersistentLockId lockId = service.acquireBackupLock(TEST_REASON); LockEntry lockEntry = Iterables.getOnlyElement(lockStore.allLockEntries()); service.releaseLock(lockId); verify(lockStore, times(1)).releaseLock(eq(lockEntry)); }
Source:
<code>public S3TO(final Long id, final String uuid, final String accessKey, final String secretKey, final String endPoint, final String bucketName, final String signer, final Boolean httpsFlag, final Integer connectionTimeout, final Integer maxErrorRetry, final Integer socketTimeout, final Date created, final boolean enableRRS, final long maxUploadSize, final Integer connectionTtl, final Boolean useTCPKeepAlive) { <START> super(); <END> this.id = id; this.uuid = uuid; this.accessKey = accessKey; this.secretKey = secretKey; this.endPoint = endPoint; this.bucketName = bucketName; this.signer = signer; this.httpsFlag = httpsFlag; this.connectionTimeout = connectionTimeout; this.maxErrorRetry = maxErrorRetry; this.socketTimeout = socketTimeout; this.created = created; this.enableRRS = enableRRS; this.maxSingleUploadSizeInBytes = maxUploadSize; this.connectionTtl = connectionTtl; this.useTCPKeepAlive = useTCPKeepAlive; }</code><technical_language>remove this call remove public default constructor: used</technical_language>

Target:
public S3TO(final Long id, final String uuid, final String accessKey, final String secretKey, final String endPoint, final String bucketName, final String signer, final Boolean httpsFlag, final Integer connectionTimeout, final Integer maxErrorRetry, final Integer socketTimeout, final Date created, final boolean enableRRS, final long maxUploadSize, final Integer connectionTtl, final Boolean useTCPKeepAlive) { this.id = id; this.uuid = uuid; this.accessKey = accessKey; this.secretKey = secretKey; this.endPoint = endPoint; this.bucketName = bucketName; this.signer = signer; this.httpsFlag = httpsFlag; this.connectionTimeout = connectionTimeout; this.maxErrorRetry = maxErrorRetry; this.socketTimeout = socketTimeout; this.created = created; this.enableRRS = enableRRS; this.maxSingleUploadSizeInBytes = maxUploadSize; this.connectionTtl = connectionTtl; this.useTCPKeepAlive = useTCPKeepAlive; }
Source:
<code>public void flushCounters() { ConcurrentMap<CounterMetric, Integer> counters = ConcurrentMetricCounters.Counters.get(); ConcurrentMetricCounters.Counters.set(new ConcurrentHashMap<CounterMetric, Integer>()); for (CounterMetric counterMetric: counters.keySet()) { int count = counters.get(counterMetric); <START> this.postMetric(counterMetric.getMetricName(), count, counterMetric.getHostname(), counterMetric.getTags(), "rate"); <END> } }</code><technical_language>send rate count</technical_language>

Target:
public void flushCounters() { ConcurrentMap<CounterMetric, Integer> counters = ConcurrentMetricCounters.getInstance().getAndReset(); logger.fine("Run flushCounters method"); for (CounterMetric counterMetric: counters.keySet()) { int count = counters.get(counterMetric); logger.fine("Flushing: " + counterMetric.getMetricName() + " - " + count); this.postMetric(counterMetric.getMetricName(), count / 10, counterMetric.getHostname(), counterMetric.getTags(), "rate"); } }
Source:
<code>private void checkSubtree(Object element, boolean state) { TreeItem item = (TreeItem) <START> fCheckboxTreeViewer.testFindItem(element); <END> if (!state || (item != null)) { fObjects.put(element, state); for (Object o : ((ITreeContentProvider) fCheckboxTreeViewer.getContentProvider()).getChildren(element)) { checkSubtree(o, state); } } }</code><technical_language>getPatternFilter().isElementVisible()? ...and... answer is no, other external filters viewer, TimeGraphFilterDialog addFilter() method ;(</technical_language>

Target:
private void checkSubtree(Object element, boolean state) { if (!state || (fCheckboxTreeViewer.testFindItem(element) != null)) { if (state) { fObjects.add(element); } else { fObjects.remove(element); } for (Object o : ((ITreeContentProvider) fCheckboxTreeViewer.getContentProvider()).getChildren(element)) { checkSubtree(o, state); } } }
Source:
<code><START> public Plan getLogicalPlan(Session session, Statement statement, List<Expression> parameters, PlanNodeIdAllocator idAllocator, WarningCollector warningCollector) <END> { Analysis analysis = analyze(session, statement, parameters, warningCollector); LogicalPlanner logicalPlanner = new LogicalPlanner(session, planOptimizers, idAllocator, metadata, sqlParser, statsCalculator, costCalculator, warningCollector); return logicalPlanner.plan(analysis); }</code><technical_language>put idAllocator parameter a default overloaded getLogicalPlan</technical_language>

Target:
public Plan getLogicalPlan(Session session, Statement statement, List<Expression> parameters, PlanNodeIdAllocator idAllocator, WarningCollector warningCollector) { Analysis analysis = analyze(session, statement, parameters, warningCollector); LogicalPlanner logicalPlanner = new LogicalPlanner(true, session, planOptimizers, idAllocator, metadata, sqlParser, statsCalculator, costCalculator, warningCollector); return logicalPlanner.plan(analysis); }
Source:
<code>public static long dateValueFromDate(long ms) { ms += getTimeZone().getOffset(ms); long absoluteDay = ms / 86_400_000; <START> if (ms < 0 && (absoluteDay * 86_400_000 != ms)) { <END> absoluteDay--; } return dateValueFromAbsoluteDay(absoluteDay); }</code><technical_language>is this logic for? pull out constant give a name. thanks</technical_language>

Target:
public static long dateValueFromDate(long ms) { ms += getTimeZone().getOffset(ms); long absoluteDay = ms / MILLIS_PER_DAY; if (ms < 0 && (absoluteDay * MILLIS_PER_DAY != ms)) { absoluteDay--; } return dateValueFromAbsoluteDay(absoluteDay); }
Source:
<code>public <TM> MessageStream<TM> map(MapFunction<? super M, ? extends TM> mapFn) { <START> String opId = this.graph.getNextOpId(OpCode.MAP, null); <END> OperatorSpec<M, TM> op = OperatorSpecs.createMapOperatorSpec(mapFn, opId); this.operatorSpec.registerNextOperatorSpec(op); return new MessageStreamImpl<>(this.graph, op); }</code><technical_language>minor: getNextOpId(code, null) repeated times. add another getNextOpId(code) avoid typing null repeatedly. But, call</technical_language>

Target:
public <TM> MessageStream<TM> map(MapFunction<? super M, ? extends TM> mapFn) { String opId = this.graph.getNextOpId(OpCode.MAP); OperatorSpec<M, TM> op = OperatorSpecs.createMapOperatorSpec(mapFn, opId); this.operatorSpec.registerNextOperatorSpec(op); return new MessageStreamImpl<>(this.graph, op); }
Source:
<code>public OrcZstdDecompressor(OrcDataSourceId orcDataSourceId, int maxBufferSize, boolean zstdJniDecompressionEnabled) { this.orcDataSourceId = requireNonNull(orcDataSourceId, "orcDataSourceId is null"); this.maxBufferSize = maxBufferSize; if (zstdJniDecompressionEnabled) { <START> this.decompressor = (input, inputOffset, inputLength, output, outputOffset, maxOutputLength) -> (int) Zstd.decompressByteArray(output, 0, maxOutputLength, input, inputOffset, inputLength); <END> } else { ZstdDecompressor zstdDecompressor = new ZstdDecompressor(); this.decompressor = zstdDecompressor::decompress; } }</code><technical_language>java this.decompressor = (input, inputOffset, inputLength, output, outputOffset, maxOutputLength) -> { long size = Zstd.decompressByteArray(output, 0, maxOutputLength, input, inputOffset, inputLength); if (Zstd.isError(size)) { throw new RuntimeException(Zstd.getErrorName(size)); } return toIntExact(size); };</technical_language>

Target:
public OrcZstdDecompressor(OrcDataSourceId orcDataSourceId, int maxBufferSize, boolean zstdJniDecompressionEnabled) { this.orcDataSourceId = requireNonNull(orcDataSourceId, "orcDataSourceId is null"); this.maxBufferSize = maxBufferSize; if (zstdJniDecompressionEnabled) { this.decompressor = (input, inputOffset, inputLength, output, outputOffset, maxOutputLength) -> { long size = Zstd.decompressByteArray(output, 0, maxOutputLength, input, inputOffset, inputLength); if (Zstd.isError(size)) { String errorName = Zstd.getErrorName(size); throw new MalformedInputException(inputOffset, "Zstd JNI decompressor failed with " + errorName); } return toIntExact(size); }; } else { ZstdDecompressor zstdDecompressor = new ZstdDecompressor(); this.decompressor = zstdDecompressor::decompress; } }
Source:
<code>public HttpResponse doConfirmRename(@QueryParameter String newName) throws IOException { if (!isNameEditable()) { <START> throw new IllegalArgumentException("Trying to rename an item that has not editable name."); <END> } newName = newName == null ? null : newName.trim(); FormValidation validationError = doCheckNewName(newName); if (validationError.kind != FormValidation.Kind.OK) { throw new Failure(validationError.getMessage()); } renameTo(newName); return HttpResponses.redirectTo("../" + newName); }</code><technical_language>This user unfriendly. UI allow users get this far</technical_language>

Target:
public HttpResponse doConfirmRename(@QueryParameter String newName) throws IOException { newName = newName == null ? null : newName.trim(); FormValidation validationError = doCheckNewName(newName); if (validationError.kind != FormValidation.Kind.OK) { throw new Failure(validationError.getMessage()); } renameTo(newName); return HttpResponses.redirectTo("../" + newName); }
Source:
<code>public static void setUp() { System.setProperty("XD_HOME", "../.."); RandomConfigurationSupport randomConfigSupport = new RandomConfigurationSupport(); application = new SingleNodeApplication().run(); SingleNodeIntegrationTestSupport singleNodeIntegrationTestSupport = new SingleNodeIntegrationTestSupport( <START> application); <END> }</code><technical_language>variables (randomConfigSupport singleNodeIntegrationTestSupport) tests run ok - is some magic provide I aware of? Or, I remove them</technical_language>

Target:
public static void setUp() { System.setProperty("XD_HOME", "../.."); new RandomConfigurationSupport(); application = new SingleNodeApplication().run(); }
Source:
<code>public Map<String,Object> getProperties( String... keys ) { Objects.requireNonNull( keys, "Properties keys should be not null array." ); if ( keys.length == 0 ) { return Collections.emptyMap(); } KernelTransaction transaction = actions.kernelTransaction(); CursorFactory cursors = transaction.cursors(); int itemsToReturn = keys.length; Map<String,Object> properties = new HashMap<>( itemsToReturn ); <START> Token token = transaction.token(); <END> try ( Statement statement = actions.statement() ) { try ( Cursor<NodeItem> node = statement.readOperations().nodeCursorById( nodeId ) ) { try ( Cursor<PropertyItem> propertyCursor = statement.readOperations().nodeGetProperties( node.get() ) ) { return PropertyContainerProxyHelper.getProperties( statement, propertyCursor, keys ); } } catch ( EntityNotFoundException e ) { throw new NotFoundException( "Node not found", e ); } } }</code><technical_language>This is implementation</technical_language>

Target:
public Map<String,Object> getProperties( String... keys ) { Objects.requireNonNull( keys, "Properties keys should be not null array." ); if ( keys.length == 0 ) { return Collections.emptyMap(); } try ( Statement ignore = actions.statement() ) { KernelTransaction transaction = actions.kernelTransaction(); CursorFactory cursors = transaction.cursors(); int itemsToReturn = keys.length; Map<String,Object> properties = new HashMap<>( itemsToReturn ); Token token = transaction.token(); int[] propertyIds = new int[itemsToReturn]; for ( int i = 0; i < itemsToReturn; i++ ) { String key = keys[i]; if ( key == null ) { throw new NullPointerException( String.format( "Key %d was null", i ) ); } propertyIds[i] = token.propertyKey( key ); } try ( NodeCursor nodes = cursors.allocateNodeCursor(); PropertyCursor propertyCursor = cursors.allocatePropertyCursor() ) { transaction.dataRead().singleNode( nodeId, nodes ); if ( !nodes.next() ) { throw new NotFoundException( new EntityNotFoundException( EntityType.NODE, nodeId ) ); } nodes.properties( propertyCursor ); while ( propertyCursor.next() ) { for ( int propertyId : propertyIds ) { int currentKey = propertyCursor.propertyKey(); if ( propertyId == currentKey ) { properties.put( token.propertyKeyGetName( currentKey ), propertyCursor.propertyValue().asObjectCopy() ); } } } } catch ( PropertyKeyIdNotFoundKernelException e ) { throw new IllegalStateException( "Property key retrieved through kernel API should exist.", e ); } return properties; } }
Source:
<code>protected void releaseTransport(Transport transport) { <START> if (dedicatedTransport == null) { <END> super.releaseTransport(transport); } }</code><technical_language>This if (dedicatedTransport != transport)</technical_language>

Target:
protected void releaseTransport(Transport transport) { if (dedicatedTransport != transport) { super.releaseTransport(transport); } }
Source:
<code>public void testSaveAsync() throws Exception { String sessionToken = "sessionToken"; Task<Void> toAwait = Task.forResult(null); ParseCurrentInstallationController controller = mock(ParseCurrentInstallationController.class); ParseInstallation currentInstallation = new ParseInstallation(); when(controller.getAsync()) .thenReturn(Task.forResult(currentInstallation)); ParseCorePlugins.getInstance() .registerCurrentInstallationController(controller); ParseObject.State state = new ParseObject.State.Builder("_Installation") .put("deviceToken", "deviceToken") .build(); ParseInstallation installation = ParseInstallation.getCurrentInstallation(); assertNotNull(installation); installation.setState(state); ParseObjectController objController = mock(ParseObjectController.class); Task<ParseObject.State> taskError = Task.forError(new ParseException(ParseException.OBJECT_NOT_FOUND, "")); Task<ParseObject.State> task = Task.forResult(null); when(objController.saveAsync( any(ParseObject.State.class), any(ParseOperationSet.class), eq(sessionToken), any(ParseDecoder.class))) .thenReturn(taskError) .thenReturn(task); ParseCorePlugins.getInstance() .registerObjectController(objController); installation.saveAsync(sessionToken, toAwait); <START> verify(controller, times(1)).getAsync(); <END> verify(objController, times(2)).saveAsync( any(ParseObject.State.class), any(ParseOperationSet.class), eq(sessionToken), any(ParseDecoder.class)); }</code><technical_language>minor optimization -- this verify(controller).getAsync(); <LINK_0> Alias verify(mock, times(1)) E.g: verify(mock).someMethod("some arg"); is equivalent to: verify(mock, times(1)).someMethod("some arg");</technical_language>

Target:
public void testSaveAsync() throws Exception { String sessionToken = "sessionToken"; Task<Void> toAwait = Task.forResult(null); ParseCurrentInstallationController controller = mock(ParseCurrentInstallationController.class); ParseInstallation currentInstallation = new ParseInstallation(); when(controller.getAsync()) .thenReturn(Task.forResult(currentInstallation)); ParseCorePlugins.getInstance() .registerCurrentInstallationController(controller); ParseObject.State state = new ParseObject.State.Builder("_Installation") .put("deviceToken", "deviceToken") .build(); ParseInstallation installation = ParseInstallation.getCurrentInstallation(); assertNotNull(installation); installation.setState(state); ParseObjectController objController = mock(ParseObjectController.class); Task<ParseObject.State> taskError = Task.forError(new ParseException(ParseException.OBJECT_NOT_FOUND, "")); Task<ParseObject.State> task = Task.forResult(null); when(objController.saveAsync( any(ParseObject.State.class), any(ParseOperationSet.class), eq(sessionToken), any(ParseDecoder.class))) .thenReturn(taskError) .thenReturn(task); ParseCorePlugins.getInstance() .registerObjectController(objController); installation.saveAsync(sessionToken, toAwait); verify(controller).getAsync(); verify(objController, times(2)).saveAsync( any(ParseObject.State.class), any(ParseOperationSet.class), eq(sessionToken), any(ParseDecoder.class)); }
Source:
<code>void commitTransaction(boolean notifyLocalThread, Runnable runAfterCommit) { checkIfValid(); sharedGroupManager.commitAndContinueAsRead(); if (runAfterCommit != null) { runAfterCommit.run(); } for (Map.Entry<Handler, String> handlerIntegerEntry : handlers.entrySet()) { Handler handler = handlerIntegerEntry.getKey(); String realmPath = handlerIntegerEntry.getValue(); if (!notifyLocalThread && handler.equals(this.handler)) { continue; } Looper looper = handler.getLooper(); if (realmPath.equals(configuration.getPath()) && looper.getThread().isAlive()) { boolean messageHandled = true; if (looper == Looper.myLooper()) { Message msg = Message.obtain(); msg.what = HandlerController.LOCAL_COMMIT; if (!handler.hasMessages(HandlerController.LOCAL_COMMIT)) { <START> messageHandled = handler.sendMessageAtFrontOfQueue(msg); <END> } } else { if (!handler.hasMessages(HandlerController.REALM_CHANGED)) { messageHandled = handler.sendEmptyMessage(HandlerController.REALM_CHANGED); } } if (!messageHandled) { RealmLog.w("Cannot update Looper threads when the Looper has quit. Use realm.setAutoRefresh(false) " + "to prevent this."); } } } }</code><technical_language>unharmful do a handler.removeMessage(HandlerController.REALM_CHANGED); here. is minor. I fine it</technical_language>

Target:
void commitTransaction(boolean notifyLocalThread, Runnable runAfterCommit) { checkIfValid(); sharedGroupManager.commitAndContinueAsRead(); if (runAfterCommit != null) { runAfterCommit.run(); } for (Map.Entry<Handler, String> handlerIntegerEntry : handlers.entrySet()) { Handler handler = handlerIntegerEntry.getKey(); String realmPath = handlerIntegerEntry.getValue(); if (!notifyLocalThread && handler.equals(this.handler)) { continue; } Looper looper = handler.getLooper(); if (realmPath.equals(configuration.getPath()) && looper.getThread().isAlive()) { boolean messageHandled = true; if (looper == Looper.myLooper()) { Message msg = Message.obtain(); msg.what = HandlerController.LOCAL_COMMIT; if (!handler.hasMessages(HandlerController.LOCAL_COMMIT)) { handler.removeMessages(HandlerController.REALM_CHANGED); messageHandled = handler.sendMessageAtFrontOfQueue(msg); } } else { if (!handler.hasMessages(HandlerController.REALM_CHANGED)) { messageHandled = handler.sendEmptyMessage(HandlerController.REALM_CHANGED); } } if (!messageHandled) { RealmLog.w("Cannot update Looper threads when the Looper has quit. Use realm.setAutoRefresh(false) " + "to prevent this."); } } } }
Source:
<code>public static <SRC> KryoCloneUtils<SRC> createCloneUtils(Kryo kryo, SRC template) { <START> return new KryoCloneUtils<SRC>(new Kryo(), template); <END> }</code><technical_language>I guess pass kryo, create another Kryo</technical_language>

Target:
public static <SRC> KryoCloneUtils<SRC> createCloneUtils(Kryo kryo, SRC template) { return new KryoCloneUtils<>(kryo, template); }