auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public boolean execute(final String activeContextId, final EventHandler<AvroElasticMemoryMessage> callback) { final ActiveContext activeContext = activeContexts.remove(activeContextId); final boolean isSuccess; if (activeContext == null) { LOG.log(Level.WARNING, "Trying to remove active context {0}, which is not found", activeContextId); isSuccess = false; } else { deletedWorkerSet.add(activeContextId); <START> final RunningTask runningTask = contextIdToRunningTasks.get(activeContextId); <END> runningTask.close(); activeContext.close(); final int remainingNumWorkers = runningWorkerContextCount.decrementAndGet(); LOG.log(Level.FINE, "Worker has been deleted successfully. Remaining workers: {0}", remainingNumWorkers); isSuccess = true; } sendCallback(activeContextId, callback, isSuccess); return isSuccess; }</code><technical_language>I remove() reduce overhead closing task</technical_language>

Target:
public boolean execute(final String activeContextId, final EventHandler<AvroElasticMemoryMessage> callback) { final ActiveContext activeContext = activeContexts.remove(activeContextId); final boolean isSuccess; if (activeContext == null) { LOG.log(Level.WARNING, "Trying to remove active context {0}, which is not found", activeContextId); isSuccess = false; } else { deletedWorkerSet.add(activeContextId); final RunningTask runningTask = contextIdToRunningTasks.remove(activeContextId); runningTask.close(); activeContext.close(); final int remainingNumWorkers = runningWorkerContextCount.decrementAndGet(); LOG.log(Level.FINE, "Worker has been deleted successfully. Remaining workers: {0}", remainingNumWorkers); isSuccess = true; } sendCallback(activeContextId, callback, isSuccess); return isSuccess; }
Source:
<code><START> public void test() throws IOException, InterruptedException, ExecutionException { <END> XContentBuilder settings = jsonBuilder().startObject(); settings.startObject("analysis"); settings.startObject("analyzer"); settings.startObject("preserve"); settings.field("tokenizer", "whitespace"); settings.field("filter", "preserve_original_recorder", "lowercase", "preserve_original"); XContentBuilder mapping = jsonBuilder().startObject(); mapping.startObject("test").startObject("properties"); mapping.startObject("test"); mapping.field("type", "string"); mapping.field("analyzer", "preserve"); mapping.endObject(); assertAcked(prepareCreate("test").addMapping("test", mapping).setSettings(settings)); ensureGreen(); indexRandom(false, doc("all_lower", "hello world")); indexRandom(false, doc("mixed", "Hello World with more text")); refresh(); SearchResponse sr = client().prepareSearch("test").setTypes("test").setQuery(QueryBuilders.matchQuery("test", "hello")).get(); assertHitCount(sr, 2); assertSearchHits(sr, "all_lower", "mixed"); sr = client().prepareSearch("test").setTypes("test").setQuery(QueryBuilders.matchQuery("test", "Hello")).get(); assertHitCount(sr, 2); assertSearchHits(sr, "mixed", "all_lower"); }</code><technical_language>Test is name for a test method. a lot of setup here, extracted in a @BeforeClass method 2 test methods, called all_lower_case_search_prefers_lower_case_results exact_results_are_prefered_over_mixed_ones</technical_language>

Target:
public void test() throws IOException, InterruptedException, ExecutionException { XContentBuilder settings = jsonBuilder().startObject(); settings.startObject("analysis"); settings.startObject("analyzer"); settings.startObject("preserve"); settings.field("tokenizer", "whitespace"); settings.field("filter", "preserve_original_recorder", "lowercase", "preserve_original"); XContentBuilder mapping = jsonBuilder().startObject(); mapping.startObject("test").startObject("properties"); mapping.startObject("test"); mapping.field("type", "string"); mapping.field("analyzer", "preserve"); mapping.field("similarity", "bm25"); mapping.endObject(); assertAcked(prepareCreate("test").addMapping("test", mapping).setSettings(settings)); ensureGreen(); indexRandom(false, doc("all_lower", "hello world")); indexRandom(false, doc("mixed", "Hello World with more text")); refresh(); SearchResponse sr = client().prepareSearch("test").setTypes("test").setQuery(QueryBuilders.matchQuery("test", "hello")).get(); assertOrderedSearchHits(sr, "all_lower", "mixed"); sr = client().prepareSearch("test").setTypes("test").setQuery(QueryBuilders.matchPhraseQuery("test", "hello world")).get(); assertOrderedSearchHits(sr, "all_lower", "mixed"); sr = client().prepareSearch("test").setTypes("test").setQuery(QueryBuilders.matchQuery("test", "Hello")).get(); assertOrderedSearchHits(sr, "mixed", "all_lower"); sr = client().prepareSearch("test").setTypes("test").setQuery(QueryBuilders.matchPhraseQuery("test", "Hello World").analyzer("whitespace")).get(); assertOrderedSearchHits(sr, "mixed"); }
Source:
<code>public Response create(@ApiParam(value = "New user") UserDescriptor userDescriptor, @ApiParam(value = "Authentication token") @QueryParam("token") String token, @ApiParam(value = "User type") @QueryParam("temporary") @DefaultValue("false") Boolean isTemporary, @Context SecurityContext context) throws ForbiddenException, BadRequestException, UnauthorizedException, ConflictException, ServerException, NotFoundException { if (!context.isUserInRole("system/admin") && !userSelfCreationAllowed) { throw new ForbiddenException("Currently only admins can create accounts. Please contact our Admin Team for further info."); } final User user = context.isUserInRole("system/admin") ? fromEntity(userDescriptor) : fromToken(token); <START> if (isValidUserName(user.getName())) { <END> throw new BadRequestException("Username must contain only letters and digits"); } userManager.create(user, isTemporary); return status(CREATED).entity(injectLinks(toDescriptor(user), getServiceContext())).build(); }</code><technical_language>odd isValid call throw exception ? is a problem</technical_language>

Target:
public Response create(@ApiParam(value = "New user") UserDescriptor userDescriptor, @ApiParam(value = "Authentication token") @QueryParam("token") String token, @ApiParam(value = "User type") @QueryParam("temporary") @DefaultValue("false") Boolean isTemporary, @Context SecurityContext context) throws ForbiddenException, BadRequestException, UnauthorizedException, ConflictException, ServerException, NotFoundException { if (!context.isUserInRole("system/admin") && !userSelfCreationAllowed) { throw new ForbiddenException("Currently only admins can create accounts. Please contact our Admin Team for further info."); } final User user = context.isUserInRole("system/admin") ? fromEntity(userDescriptor) : fromToken(token); if (!isValidUserName(user.getName())) { throw new BadRequestException("Username must contain only letters and digits"); } userManager.create(user, isTemporary); return status(CREATED).entity(injectLinks(toDescriptor(user), getServiceContext())).build(); }
Source:
<code>public static ObjectId computeChangeId(final ObjectId treeId, final ObjectId firstParentId, final PersonIdent author, final PersonIdent committer, final String message) throws IOException { StringBuilder b = new StringBuilder(); b.append("tree "); b.append(ObjectId.toString(treeId)); b.append("\n"); if (firstParentId != null) { b.append("parent "); b.append(ObjectId.toString(firstParentId)); b.append("\n"); } b.append("author "); b.append(author.toExternalString()); b.append("\n"); b.append("committer "); b.append(committer.toExternalString()); b.append("\n\n"); b.append(clean(message)); ObjectWriter w = new ObjectWriter(null); byte[] bytes = b.toString().getBytes(Constants.CHARACTER_ENCODING); ByteArrayInputStream is = new ByteArrayInputStream(bytes); <START> ObjectId sha1 = w.computeObjectSha1(Constants.OBJ_COMMIT, bytes.length, <END> is); return sha1; }</code><technical_language>If do "return w.computeObjectSha1..." able fit entire method call line need wrap "is);" next line. If long, consider "raw" "bin" instead of "bytes" for encoded form of commit text</technical_language>

Target:
public static ObjectId computeChangeId(final ObjectId treeId, final ObjectId firstParentId, final PersonIdent author, final PersonIdent committer, final String message) throws IOException { String cleanMessage = clean(message); if (cleanMessage.length() == 0) return null; StringBuilder b = new StringBuilder(); b.append("tree "); b.append(ObjectId.toString(treeId)); b.append("\n"); if (firstParentId != null) { b.append("parent "); b.append(ObjectId.toString(firstParentId)); b.append("\n"); } b.append("author "); b.append(author.toExternalString()); b.append("\n"); b.append("committer "); b.append(committer.toExternalString()); b.append("\n\n"); b.append(cleanMessage); ObjectWriter w = new ObjectWriter(null); byte[] bytes = b.toString().getBytes(Constants.CHARACTER_ENCODING); ByteArrayInputStream is = new ByteArrayInputStream(bytes); ObjectId sha1 = w.computeObjectSha1(Constants.OBJ_COMMIT, bytes.length, is); return sha1; }
Source:
<code>public void saveCurrentWorkflow() { ConfigItem<WorkflowRepresentation> workflowRepresentation = new ConfigItem<WorkflowRepresentation>(); workflowRepresentation.setContent(getCurrentWorkflow()); try { getPersistence().persist(workflowRepresentation); } catch (InvalidConfigurationException e) { <START> throw new RuntimeException(e); <END> } catch (PersistenceException e) { throw new RuntimeException(e); } }</code><technical_language>btw, this is valid for runtime exceptions in thsi class</technical_language>

Target:
public void saveCurrentWorkflow() throws PersistenceException { ConfigItem<WorkflowRepresentation> workflowRepresentation = new ConfigItem<WorkflowRepresentation>(); workflowRepresentation.setContent(getCurrentWorkflow()); try { LOGGER.debug("Saving workflow " + getCurrentWorkflow().getName()); getPersistence().persist(workflowRepresentation); } catch (InvalidConfigurationException e) { LOGGER.error("Invalid Configuration: " + e.getMessage()); throw new PersistenceException(e); } }
Source:
<code>private long createTags(OseeConnection connection, Collection<IndexedResource> sources) throws OseeCoreException { SearchTagCollector tagCollector = new SearchTagCollector(); Set<Long> processed = new HashSet<Long>(); Map<Long, Collection<Long>> toStore = new HashMap<Long, Collection<Long>>(); for (IndexedResource source : sources) { long startItemTime = System.currentTimeMillis(); Long gamma = source.getGammaId(); if (processed.add(gamma)) { Set<Long> tags = new HashSet<Long>(); toStore.put(gamma, tags); tagCollector.setCurrentTag(gamma, tags); try { long typeUuid = source.getTypeUuid(); String taggerId = getTaggerIdByTypeUuid(typeUuid); if (taggingEngine.hasTagger(taggerId)) { Tagger tagger = taggingEngine.getTagger(taggerId); tagger.tagIt(source, tagCollector); if (isStorageAllowed(toStore)) { <START> if (getLogger().isDebugEnabled()) { <END> getLogger().debug("Stored a - [%s] - connectionId[%s] - [%s]", getTagQueueQueryId(), connection, toStore); } storeTags(connection, toStore); } } } catch (Exception ex) { } finally { long endItemTime = System.currentTimeMillis() - startItemTime; notifyOnIndexItemComplete(gamma, tags.size(), endItemTime); } } } if (!toStore.isEmpty()) { if (getLogger().isDebugEnabled()) { getLogger().debug("Stored b - [%s] - connectionId[%s] - [%s]", getTagQueueQueryId(), connection, toStore); } storeTags(connection, toStore); } return tagCollector.getTotalTags(); }</code><technical_language>Remove this - if (getLogger().isDebugEnabled()) check is needed logger configuration handles for</technical_language>

Target:
private long createTags(OseeConnection connection, Collection<IndexedResource> sources) throws OseeCoreException { SearchTagCollector tagCollector = new SearchTagCollector(); Set<Long> processed = new HashSet<Long>(); Map<Long, Collection<Long>> toStore = new HashMap<Long, Collection<Long>>(); for (IndexedResource source : sources) { long startItemTime = System.currentTimeMillis(); Long gamma = source.getGammaId(); if (processed.add(gamma)) { Set<Long> tags = new HashSet<Long>(); toStore.put(gamma, tags); tagCollector.setCurrentTag(gamma, tags); try { long typeUuid = source.getTypeUuid(); String taggerId = getTaggerIdByTypeUuid(typeUuid); if (taggingEngine.hasTagger(taggerId)) { Tagger tagger = taggingEngine.getTagger(taggerId); tagger.tagIt(source, tagCollector); if (isStorageAllowed(toStore)) { getLogger().debug("Stored a - [%s] - connectionId[%s] - [%s]", getTagQueueQueryId(), connection, toStore); storeTags(connection, toStore); } } else { getLogger().error("Field has no tagger provider and cannot be tagged - [Gamma: %s]", gamma); } } catch (Exception ex) { getLogger().error(ex, "Unable to tag - [%s]", gamma); } finally { long endItemTime = System.currentTimeMillis() - startItemTime; notifyOnIndexItemComplete(gamma, tags.size(), endItemTime); } } } if (!toStore.isEmpty()) { getLogger().debug("Stored b - [%s] - connectionId[%s] - [%s]", getTagQueueQueryId(), connection, toStore); storeTags(connection, toStore); } return tagCollector.getTotalTags(); }
Source:
<code>protected long getParam(JSONObject params, String name, long defaultValue) { try { <START> return params.getInt(name); <END> } catch (Exception e) { return defaultValue; } }</code><technical_language>getLong</technical_language>

Target:
protected long getParam(JSONObject params, String name, long defaultValue) { try { return params.getLong(name); } catch (Exception e) { return defaultValue; } }
Source:
<code><START> public void advance(long amountToAdd, TemporalUnit unit) { <END> now = now.plus(amountToAdd, unit); }</code><technical_language>this return Instant</technical_language>

Target:
public Instant advance(long amountToAdd, TemporalUnit unit) { now = now.plus(amountToAdd, unit); return instant(); }
Source:
<code><START> private void processDistributedObjectInfos(ClientMessage response) { <END> ClientGetDistributedObjectsCodec.ResponseParameters resultParameters = ClientGetDistributedObjectsCodec.decodeResponse(response); Collection<? extends DistributedObject> distributedObjects = getLocalDistributedObjects(); Set<DistributedObjectInfo> localDistributedObjects = new HashSet<DistributedObjectInfo>(); for (DistributedObject localInfo : distributedObjects) { localDistributedObjects.add(new DistributedObjectInfo(localInfo.getServiceName(), localInfo.getName())); } Collection<DistributedObjectInfo> newDistributedObjectInfo = resultParameters.response; for (DistributedObjectInfo distributedObjectInfo : newDistributedObjectInfo) { localDistributedObjects.remove(distributedObjectInfo); getOrCreateProxy(distributedObjectInfo.getServiceName(), distributedObjectInfo.getName(), true); } for (DistributedObjectInfo distributedObjectInfo : localDistributedObjects) { destroyProxyLocally(distributedObjectInfo.getServiceName(), distributedObjectInfo.getName()); } }</code><technical_language>do need synchronize this method? order change order type of DistributedObject events delivered local distributed object listeners</technical_language>

Target:
private synchronized void processDistributedObjectInfos(ClientMessage response) { ClientGetDistributedObjectsCodec.ResponseParameters resultParameters = ClientGetDistributedObjectsCodec.decodeResponse(response); Collection<? extends DistributedObject> distributedObjects = getLocalDistributedObjects(); Set<DistributedObjectInfo> localDistributedObjects = new HashSet<DistributedObjectInfo>(); for (DistributedObject localInfo : distributedObjects) { localDistributedObjects.add(new DistributedObjectInfo(localInfo.getServiceName(), localInfo.getName())); } Collection<DistributedObjectInfo> newDistributedObjectInfo = resultParameters.response; for (DistributedObjectInfo distributedObjectInfo : newDistributedObjectInfo) { localDistributedObjects.remove(distributedObjectInfo); getOrCreateProxy(distributedObjectInfo.getServiceName(), distributedObjectInfo.getName(), false); } for (DistributedObjectInfo distributedObjectInfo : localDistributedObjects) { destroyProxyLocally(distributedObjectInfo.getServiceName(), distributedObjectInfo.getName()); } }
Source:
<code>public void setWhiteListedRoutes(String s) { <START> if (s != null && !s.equals("")) <END> whiteListedRoutes = RouteMatcher.parse(s); else whiteListedRoutes = RouteMatcher.emptyMatcher(); }</code><technical_language>canonical of performing check is String.isEmpty(). If check for equality empty string, note reversing comparison elide null check: !("".equals(string))</technical_language>

Target:
public void setWhiteListedRoutes(String s) { if (!s.isEmpty()) { whiteListedRoutes = RouteMatcher.parse(s); } else { whiteListedRoutes = RouteMatcher.emptyMatcher(); } }
Source:
<code>public void close() throws IOException { <START> LOG.info("Processing remaining requests [docs = " + bulkDocs <END> + ", length = " + bulkLength + ", total docs = " + indexedDocs + "]"); createNewBulk = false; commit(); LOG.info("Processing to finalize last execute"); createNewBulk = false; commit(); client.close(); if (node != null) { node.close(); } }</code><technical_language>Logging improved parameterized messages <LINK_0></technical_language>

Target:
public void close() throws IOException { LOG.info("Processing remaining requests [docs = {}, length = {}, total docs = {}]" , bulkDocs, bulkLength, indexedDocs); createNewBulk = false; commit(); LOG.info("Processing to finalize last execute"); createNewBulk = false; commit(); client.close(); if (node != null) { node.close(); } }
Source:
<code>public void handleRequest(HttpServerExchange exchange) throws Exception { logger.debug("Health check from {}", exchange.getSourceAddress().getHostString()); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain; charset=utf-8"); if(shutdown) { exchange.setStatusCode(HTTP_UNAVAILABLE); exchange.getResponseSender().send("No p*ng for you, shutting down", StandardCharsets.UTF_8); logger.info("Return 503 on health check to indicate shutdown"); } else { <START> exchange.getResponseSender().send("Pong", StandardCharsets.UTF_8); <END> } }</code><technical_language>current ping handler sends lowercase pong in response body. While unlikely, deployments health checks check for exact response. (Also, I a personal preference for lowercase pongs.)</technical_language>

Target:
public void handleRequest(HttpServerExchange exchange) throws Exception { logger.debug("Health check from {}", exchange.getSourceAddress().getHostString()); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain; charset=utf-8"); if(shutdown) { exchange.setStatusCode(HTTP_UNAVAILABLE); exchange.getResponseSender().send("No p*ng for you, shutting down", StandardCharsets.UTF_8); logger.info("Return 503 on health check to indicate shutdown"); } else { exchange.getResponseSender().send("pong", StandardCharsets.UTF_8); } }
Source:
<code>public static synchronized @NonNull SymbolProviderManager getInstance() { if (INSTANCE == null) { List<@NonNull SymbolProviderFactoryWrapper> providers = new ArrayList<>(); IConfigurationElement[] configElements = Platform.getExtensionRegistry().getConfigurationElementsFor(EXTENSION_POINT_ID); for (IConfigurationElement element : configElements) { if (ELEM_NAME_PROVIDER.equals(element.getName())) { try { Object extension = element.createExecutableExtension(ATTR_CLASS); int priority = 0; try { priority = Integer.parseInt(element.getAttribute(ATTR_PRIORITY)); } catch (NumberFormatException e) { } providers.add(new SymbolProviderFactoryWrapper((ISymbolProviderFactory) extension, priority)); } catch (CoreException | ClassCastException e) { Activator.getDefault().logError("Exception while loading extensions", e); } } } <START> providers.sort(Comparator.<SymbolProviderFactoryWrapper> comparingLong(o -> o.priority).reversed()); <END> } return INSTANCE; }</code><technical_language>missing INSTANCE = new SymbolProviderManager(providers);</technical_language>

Target:
public static synchronized @NonNull SymbolProviderManager getInstance() { if (INSTANCE == null) { List<@NonNull SymbolProviderFactoryWrapper> providers = new ArrayList<>(); IConfigurationElement[] configElements = Platform.getExtensionRegistry().getConfigurationElementsFor(EXTENSION_POINT_ID); for (IConfigurationElement element : configElements) { if (ELEM_NAME_PROVIDER.equals(element.getName())) { try { Object extension = element.createExecutableExtension(ATTR_CLASS); int priority = 0; try { priority = Integer.parseInt(element.getAttribute(ATTR_PRIORITY)); } catch (NumberFormatException e) { } providers.add(new SymbolProviderFactoryWrapper((ISymbolProviderFactory) extension, priority)); } catch (CoreException | ClassCastException e) { Activator.getDefault().logError("Exception while loading extensions", e); } } } providers.sort(Comparator.<SymbolProviderFactoryWrapper> comparingLong(o -> o.priority).reversed()); INSTANCE = new SymbolProviderManager(providers); } return INSTANCE; }
Source:
<code>public void onEvent(FormStatusEvent event) { if (isShowing() && event.getStatus().getFormDefinition().equals(form)) { try { <START> editorArea.read(new StringReader(event.getStatus().getStatusHistory()), null); <END> } catch (IOException e) { log.warn("failed to load history", e); } } }</code><technical_language>Thanks for clarifications -- I realize issue total memory usage, I thought repeated allocation deallocation of larger objects. I expected buffer able hold MBs trouble a modern computer</technical_language>

Target:
public void onEvent(FormStatusEvent event) { if (isShowing() && event.getStatus().getFormDefinition().equals(form)) { try { Document doc = editorArea.getDocument(); String latestStatus = "\n" + event.getStatusString(); doc.insertString(doc.getLength(), latestStatus, null); } catch (BadLocationException e) { log.warn("failed to update history", e); } } }
Source:
<code>private ArrayList<Long> generateSpinnerSpeeds() { long initialSpeed = 100; ArrayList<Long> speedList = new ArrayList<>(); <START> speedList.add(-1l); <END> for (int i = 1; i <= 10; i++) { speedList.add(initialSpeed * i); } return speedList; }</code><technical_language>This reference new constant in library in case changes in future</technical_language>

Target:
private ArrayList<Long> generateSpinnerSpeeds() { long initialSpeed = 100; ArrayList<Long> speedList = new ArrayList<>(); speedList.add(mExpandableAdapter.CUSTOM_ANIMATION_DURATION_NOT_SET); for (int i = 1; i <= 10; i++) { speedList.add(initialSpeed * i); } return speedList; }
Source:
<code>public void throwsWhenIncorrectTypeInResponse() { assertThrows(AzureException.class, () -> { final Long eventHubName = 100L; final Date createdAtAsDate = new Date(1569275540L); final String[] partitionIds = new String[]{ "1", "foo", "bar", "baz" }; final Map<String, Object> values = new HashMap<>(); values.put(ManagementChannel.MANAGEMENT_ENTITY_NAME_KEY, eventHubName); values.put(ManagementChannel.MANAGEMENT_RESULT_CREATED_AT, createdAtAsDate); values.put(ManagementChannel.MANAGEMENT_RESULT_PARTITION_IDS, partitionIds); final AmqpValue amqpValue = new AmqpValue(values); final Message message = Proton.message(); message.setBody(amqpValue); <START> serializer.deserialize(message, EventHubProperties.class); <END> }); }</code><technical_language>this line in assertThrows(() -> {}), scope expect error be</technical_language>

Target:
public void throwsWhenIncorrectTypeInResponse() { final Long eventHubName = 100L; final Date createdAtAsDate = new Date(1569275540L); final String[] partitionIds = new String[]{"1", "foo", "bar", "baz"}; final Map<String, Object> values = new HashMap<>(); values.put(ManagementChannel.MANAGEMENT_ENTITY_NAME_KEY, eventHubName); values.put(ManagementChannel.MANAGEMENT_RESULT_CREATED_AT, createdAtAsDate); values.put(ManagementChannel.MANAGEMENT_RESULT_PARTITION_IDS, partitionIds); final AmqpValue amqpValue = new AmqpValue(values); final Message message = Proton.message(); message.setBody(amqpValue); assertThrows(AzureException.class, () -> { serializer.deserialize(message, EventHubProperties.class); }); }
Source:
<code>private boolean isRedo(Change newCh) { if (position < changes.size() - 1) { Change oldCh = changes.get(position + 1); boolean isEqual = oldCh.getChange().difference(newCh.getChange()).isEmpty(); <START> boolean isOpposite = oldCh.isPositive() == newCh.isPositive(); <END> return isEqual && isOpposite; } else { return false; } }</code><technical_language>This implementation returns false oldCh.isPositive() newCh.isPositive() true same. If this is is wanted here, name "isOpposite" is misleading changed</technical_language>

Target:
private boolean isRedo(Change newCh) { if (position < changes.size() - 1) { Change oldCh = changes.get(position + 1); boolean isEqual = oldCh.getChange().difference(newCh.getChange()).isEmpty(); boolean isSame = oldCh.isAddition() == newCh.isAddition(); return isEqual && isSame; } else { return false; } }
Source:
<code>private void cloneExistingGoalAsHistoryItem(UserAnonymized userAnonymizedEntity, Goal existingGoal) { Goal historyGoal = existingGoal.cloneAsHistoryItem(); existingGoal.setPreviousGoal(historyGoal); <START> WeekActivity.getRepository().findByGoal(existingGoal).stream().forEach(a -> a.setGoal(historyGoal)); <END> DayActivity.getRepository().findByGoal(existingGoal).stream().forEach(a -> a.setGoal(historyGoal)); }</code><technical_language>I hope this perform. write a specific update query in repositories more efficient (update DayActivity set goal = :historyGoal goal = :goal)</technical_language>

Target:
private void cloneExistingGoalAsHistoryItem(UserAnonymized userAnonymizedEntity, Goal existingGoal) { Goal historyGoal = existingGoal.cloneAsHistoryItem(); existingGoal.setPreviousVersionOfThisGoal(historyGoal); WeekActivity.getRepository().findByGoal(existingGoal).stream().forEach(a -> a.setGoal(historyGoal)); DayActivity.getRepository().findByGoal(existingGoal).stream().forEach(a -> a.setGoal(historyGoal)); }
Source:
<code>public abstract Object computeValue(Object row) throws HiveException; public abstract boolean isDistanceGreater(Object v1, Object v2, int amt); public abstract boolean isEqual(Object v1, Object v2); public abstract int computeStart(int rowIdx, PTFPartition p) throws HiveException; public abstract int computeEnd(int rowIdx, PTFPartition p) throws HiveException; public void handleCache(int rowIdx, PTFPartition p) throws HiveException { BoundaryCache cache = p.getBoundaryCache(); if (cache == null) { return; } if (rowIdx == 0) { cache.clear(); } if (cache.isComplete()) { return; } int cachePos = cache.approxCachePositionOf(rowIdx); if (cache.isEmpty()) { fillCacheUntilEndOrFull(rowIdx, p); <START> } else if (cachePos > 50 && cachePos <= 75) { <END> if (!start.isPreceding() && end.isFollowing()) { cache.evictHalf(); fillCacheUntilEndOrFull(rowIdx, p); } } else if (cachePos > 75 && cachePos <= 95) { if (start.isPreceding() && end.isFollowing()) { cache.evictHalf(); fillCacheUntilEndOrFull(rowIdx, p); } } else if (cachePos >= 95) { if (start.isPreceding() && !end.isFollowing()) { cache.evictHalf(); fillCacheUntilEndOrFull(rowIdx, p); } } }</code><technical_language>This is strange me. Do size of window in advance? cache accordingly? If window size is 5 cache 7 values (1 before, 1 after, 5 values)</technical_language>

Target:
public abstract Object computeValue(Object row) throws HiveException; public abstract boolean isDistanceGreater(Object v1, Object v2, int amt); public abstract boolean isEqual(Object v1, Object v2); public abstract int computeStart(int rowIdx, PTFPartition p) throws HiveException; public abstract int computeEnd(int rowIdx, PTFPartition p) throws HiveException; public void handleCache(int rowIdx, PTFPartition p) throws HiveException { BoundaryCache cache = p.getBoundaryCache(); if (cache == null) { return; } if (start.isUnbounded() && end.isUnbounded()) { return; } if (rowIdx == 0) { cache.clear(); } if (cache.isComplete()) { return; } if (cache.isEmpty()) { fillCacheUntilEndOrFull(rowIdx, p); return; } if (start.isPreceding()) { if (start.isUnbounded()) { if (end.isPreceding()) { Map.Entry<Integer, Object> maxEntry = cache.getMaxEntry(); if (maxEntry != null && maxEntry.getKey() <= rowIdx) { cache.evictOne(); } } else { checkIfCacheCanEvict(rowIdx, p, true); } } else { END is of FOLLOWING type: we should remove ranges preceding the current range beginning. Map.Entry<Integer, Object> maxEntry = cache.getMaxEntry(); if (maxEntry != null && maxEntry.getKey() <= rowIdx) { cache.evictOne(); } else if (end.isFollowing()) { int startIdx = computeStart(rowIdx, p); checkIfCacheCanEvict(startIdx - 1, p, true); } } } if (start.isCurrentRow()) { checkIfCacheCanEvict(rowIdx, p, false); } if (start.isFollowing()) { checkIfCacheCanEvict(rowIdx, p, true); } fillCacheUntilEndOrFull(rowIdx, p); }
Source:
<code>private static List<TagObject> activeTagList(TagModel model) { List<TagObject> result = new ArrayList<>(); if (model.getSelection()) { result.add(from(model, false)); } for(TagModel child: model.getChildren()) { List<TagObject> activeChildTags = activeTagList(child); <START> if (!activeChildTags.isEmpty()) { <END> result.addAll(activeChildTags); } } return result; }</code><technical_language>is this check necessary</technical_language>

Target:
private static List<TagObject> activeTagList(TagModel model) { List<TagObject> result = new ArrayList<>(); if (model.getSelection()) { result.add(from(model, false)); } for (TagModel child : model.getChildren()) { result.addAll(activeTagList(child)); } return result; }
Source:
<code>public void send(CommandSender sender) { sender.sendMessage(""); sender.sendMessage(ChatColor.GREEN + "===== Slimefun Lag Profiler ====="); sender.sendMessage(ChatColors.color("&6Total: &e" + NumberUtils.getAsMillis(totalElapsedTime))); sender.sendMessage(ChatColors.color("&6Performance: " + getPerformanceRating())); sender.sendMessage(ChatColors.color("&6Active Chunks: &e" + chunks.size())); sender.sendMessage(ChatColors.color("&6Active Blocks: &e" + totalTickedBlocks)); <START> sender.sendMessage(""); <END> summarizeTimings("Chunks", sender, entry -> { int count = profiler.getBlocksOfId(entry.getKey()); String time = NumberUtils.getAsMillis(entry.getValue()); if (count > 1) { String average = NumberUtils.getAsMillis(entry.getValue() / count); return entry.getKey() + " - " + count + "x (" + time + ", " + average + " avg/block)"; } else { return entry.getKey() + " - " + count + "x (" + time + ')'; } }, items.entrySet().stream()); sender.sendMessage(""); summarizeTimings("Blocks", sender, entry -> { int count = profiler.getBlocksInChunk(entry.getKey()); String time = NumberUtils.getAsMillis(entry.getValue()); return entry.getKey() + " - " + count + "x (" + time + ")"; }, chunks.entrySet().stream()); }</code><technical_language>\n is friend</technical_language>

Target:
public void send(CommandSender sender) { sender.sendMessage(""); sender.sendMessage(ChatColor.GREEN + "===== Slimefun Lag Profiler ====="); sender.sendMessage(ChatColor.GOLD + "Total: " + ChatColor.YELLOW + NumberUtils.getAsMillis(totalElapsedTime)); sender.sendMessage(ChatColor.GOLD + "Performance: " + getPerformanceRating()); sender.sendMessage(ChatColor.GOLD + "Active Chunks: " + ChatColor.YELLOW + chunks.size()); sender.sendMessage(ChatColor.GOLD + "Active Blocks: " + ChatColor.YELLOW + totalTickedBlocks); sender.sendMessage(""); summarizeTimings("Blocks", sender, entry -> { int count = profiler.getBlocksOfId(entry.getKey()); String time = NumberUtils.getAsMillis(entry.getValue()); if (count > 1) { String average = NumberUtils.getAsMillis(entry.getValue() / count); return entry.getKey() + " - " + count + "x (" + time + ", " + average + " avg/block)"; } else { return entry.getKey() + " - " + count + "x (" + time + ')'; } }, items.entrySet().stream()); sender.sendMessage(""); summarizeTimings("Chunks", sender, entry -> { int count = profiler.getBlocksInChunk(entry.getKey()); String time = NumberUtils.getAsMillis(entry.getValue()); return entry.getKey() + " - " + count + "x (" + time + ")"; }, chunks.entrySet().stream()); }
Source:
<code>public void deactivate(Object id) { <START> RequestBody emptyBody = RequestBody.create(null, new byte[0]);; <END> Request request = new Request.Builder().url(host + "/r/operators/" + id + "/deactivate").post(emptyBody).build(); client.newCall(request); }</code><technical_language>duplicated ;</technical_language>

Target:
public void deactivate(Object id) { RequestBody emptyBody = RequestBody.create(null, new byte[0]); Request request = new Request.Builder().url(host + "/r/operators/" + id + "/deactivate").post(emptyBody).build(); client.newCall(request); }
Source:
<code>public void uncaughtException(@NonNull Thread t, @NonNull Throwable e) { boolean strictModeThrowable = strictModeHandler.isStrictModeThrowable(e); for (Client client : clientMap.keySet()) { if (strictModeThrowable) { String violationDesc = strictModeHandler.getViolationDescription(e.getMessage()); MetaData metaData = new MetaData( Collections.<String, Object>singletonMap(KEY_STRICT_MODE_VIOLATION, violationDesc)); client.cacheAndNotify(e, Severity.ERROR, metaData); } <START> client.cacheAndNotify(e, Severity.ERROR, null); <END> } if (originalHandler != null) { originalHandler.uncaughtException(t, e); } else { System.err.printf("Exception in thread \"%s\" ", t.getName()); e.printStackTrace(System.err); } }</code><technical_language>I noticed reports in duplicate, strictmode metadata. I assume else clause wrapping this line</technical_language>

Target:
public void uncaughtException(@NonNull Thread t, @NonNull Throwable e) { boolean strictModeThrowable = strictModeHandler.isStrictModeThrowable(e); for (Client client : clientMap.keySet()) { MetaData metaData = null; if (strictModeThrowable) { String violationDesc = strictModeHandler.getViolationDescription(e.getMessage()); metaData = new MetaData(); metaData.addToTab(STRICT_MODE_TAB, STRICT_MODE_KEY, violationDesc); } client.cacheAndNotify(e, Severity.ERROR, metaData); } if (originalHandler != null) { originalHandler.uncaughtException(t, e); } else { System.err.printf("Exception in thread \"%s\" ", t.getName()); e.printStackTrace(System.err); } }
Source:
<code>public IProject[] getTrackedProjects() { IProject[] projects = new IProject[trackedProjects.keySet().size()]; <START> return trackedProjects.keySet().toArray(projects); <END> }</code><technical_language>I this 'return trackedProjects.keySet().toArray(new IProject[0])' . If array passed in is large enough, a new created of proper type store Set's content, size calculation needed</technical_language>

Target:
public IProject[] getTrackedProjects() { return trackedProjects.keySet().toArray(new IProject[0]); }
Source:
<code>public synchronized void stop(StopContext context) { final ContentRepositoryCleaner contentCleaner = this.deploymentContentCleaner; this.deploymentContentCleaner = null; contentCleaner.stopScan(); <START> scheduledExecutorValue.getValue().shutdown(); <END> }</code><technical_language>If depend external service, shut down, it. If do executor shut down, block shut down. other this block cleanup-in-progress completes (I checked; ContentRepositoryCleaner.stopScan() does.) ModelContoller service (ServerService DomainModelControllerService) shut while a scan is in progress. If blocks, need StopContext.asynchronous() API</technical_language>

Target:
public synchronized void stop(StopContext context) { final ContentRepositoryCleaner contentCleaner = this.deploymentContentCleaner; this.deploymentContentCleaner = null; contentCleaner.stopScan(); }
Source:
<code>public List<ConfigItem> generateConfig(final NetworkElementCommand cmd) { final SetMonitorServiceCommand command = (SetMonitorServiceCommand) cmd; <START> final MonitorService monitorService = new MonitorService( command.getConfiguration(), cmd.getAccessDetail(SetMonitorServiceCommand.ROUTER_MONITORING_ENABLED), cmd.getAccessDetail(SetMonitorServiceCommand.ROUTER_HEALTH_CHECKS_ENABLED)); try { monitorService.setHealthChecksBasicRunInterval(Integer.parseInt(cmd.getAccessDetail(SetMonitorServiceCommand.ROUTER_HEALTH_CHECKS_BASIC_INTERVAL))); } catch (NumberFormatException exception) { s_logger.error("Unexpected health check basic interval set" + cmd.getAccessDetail(SetMonitorServiceCommand.ROUTER_HEALTH_CHECKS_BASIC_INTERVAL) + ". Exception: " + exception + "Will use default value"); } try { monitorService.setHealthChecksAdvanceRunInterval(Integer.parseInt(cmd.getAccessDetail(SetMonitorServiceCommand.ROUTER_HEALTH_CHECKS_ADVANCED_INTERVAL))); } catch (NumberFormatException exception) { s_logger.error("Unexpected health check advance interval set" + cmd.getAccessDetail(SetMonitorServiceCommand.ROUTER_HEALTH_CHECKS_ADVANCED_INTERVAL) + ". Exception: " + exception + "Will use default value"); } monitorService.setExcludedHealthChecks(cmd.getAccessDetail(SetMonitorServiceCommand.ROUTER_HEALTH_CHECKS_EXCLUDED)); monitorService.setAdditionalData(command.getAdditionalData()); monitorService.setDeleteFromProcessedCache(command.shouldDeleteFromProcessedCache()); List<ConfigItem> configItems = generateConfigItems(monitorService); if (configItems != null && command.shouldReconfigureAfterUpdate()) { configItems.add(new ScriptConfigItem(VRScripts.CONFIGURE, "monitor_service.json")); } <END> return configItems; }</code><technical_language>extra done. Please move private package scope methods good descriptive names (for posterity ;)</technical_language>

Target:
public List<ConfigItem> generateConfig(final NetworkElementCommand cmd) { final SetMonitorServiceCommand command = (SetMonitorServiceCommand) cmd; final MonitorService monitorService = new MonitorService( command.getConfiguration(), cmd.getAccessDetail(SetMonitorServiceCommand.ROUTER_MONITORING_ENABLED), cmd.getAccessDetail(SetMonitorServiceCommand.ROUTER_HEALTH_CHECKS_ENABLED)); setupHealthChecksRelatedInfo(monitorService, command); monitorService.setDeleteFromProcessedCache(command.shouldDeleteFromProcessedCache()); List<ConfigItem> configItems = generateConfigItems(monitorService); if (configItems != null && command.shouldReconfigureAfterUpdate()) { configItems.add(new ScriptConfigItem(VRScripts.CONFIGURE, "monitor_service.json")); } return configItems; }
Source:
<code>public void testRenameNullFile() { Path path = new Path("/directory1/"); assertThrows("src must not be null", NullPointerException.class, () -> ghfs.rename(null, null)); assertThrows("src must not be null", NullPointerException.class, () -> ghfs.rename(null, path)); <START> assertThrows("dst must not be null", NullPointerException.class, () -> ghfs.rename(null, null)); <END> assertThrows("dst must not be null", NullPointerException.class, () -> ghfs.rename(null, path)); }</code><technical_language>This is a duplicate test case, I (null, null) test case, if (path, null) (null, path) test cases</technical_language>

Target:
public void testRenameNullFile() { Path path = new Path("/directory1/"); assertThrows( "src and dst must not be null", NullPointerException.class, () -> ghfs.rename(null, null)); assertThrows("src must not be null", NullPointerException.class, () -> ghfs.rename(null, path)); assertThrows("dst must not be null", NullPointerException.class, () -> ghfs.rename(path, null)); }
Source:
<code>protected void onInit() { super.onInit(); if (principalMapping != null && !principalMapping.isEmpty() || groupPrincipalMapping != null && !groupPrincipalMapping.isEmpty()) { try { mapper.loadMappingTable(principalMapping, groupPrincipalMapping); } catch (PrincipalMappingException e) { LOGGER.error("PrincipalMappingException in onInit", e); } } try { <START> hadoopConfig = new Configuration(false); <END> hadoopGroups = new Groups(hadoopConfig); } catch (final Exception e) { LOGGER.error("Exception in onInit", e); } }</code><technical_language>this load default</technical_language>

Target:
protected void onInit() { super.onInit(); if (principalMapping != null && !principalMapping.isEmpty() || groupPrincipalMapping != null && !groupPrincipalMapping.isEmpty()) { try { mapper.loadMappingTable(principalMapping, groupPrincipalMapping); } catch (PrincipalMappingException e) { LOGGER.error("PrincipalMappingException in onInit", e); } } try { hadoopConfig = new Configuration(); hadoopGroups = new Groups(hadoopConfig); } catch (final Exception e) { LOGGER.error("Exception in onInit", e); } }
Source:
<code>public boolean eligible() { return false; <START> } <END></code><technical_language>eligible() is supposed ... in "do enough information reply?" building reason property in consume() method, want return true false based reason property filled. normal pattern for a patient snapshot is follows: for (Obs o: obsList) { if (snapshot.consume(o)) { // consuming observation changed a property if (snapshot.eligible()) { // snapshot a conclusion return snapshot.generateResult(); } } } This requires a generateResult() method snapshot (which yet) return a formatted Result object</technical_language>

Target:
public boolean eligible() { if (this.getProperty("why").equals("DEAD")) { this.setProperty("reason", "DEAD | " + this.getProperty("obsDate")); return true; } else if (this.getProperty("why").equals("TO | (Ampath) ")) { this.setProperty("reason", "TO | (Ampath) " + this.getProperty("obsDate")); return true; } else if (this.getProperty("why").equals("TO | (Non-Ampath) ")) { this.setProperty("reason", "TO | (Non-Ampath) " + this.getProperty("obsDate")); return true; } else if (this.getProperty("why").equals("LTFU")) { this.setProperty("reason", "LTFU | " + this.getProperty("obsDate")); return true; } return false; }
Source:
<code>public ListBoxModel doFillPriorityIdItems(@AncestorInPath final Item item) { ListBoxModel items = new ListBoxModel().add(""); <START> ItemGroup parent = item == null ? null : item.getParent(); <END> List<JiraSite> sites = parent instanceof Folder ? JiraFolderProperty.getSitesFromFolders( parent ) : JiraGlobalConfiguration.get().getSites(); for (JiraSite site : sites) { JiraSession session = parent instanceof Folder ? site.getSession(item) : site.getSession(); if (session != null) { for (Priority priority : session.getPriorities()) { items.add("[" + site.getName() + "] " + priority.getName(), String.valueOf(priority.getId())); } } } return items; }</code><technical_language>next lines unreadable for me, prefer if/else parentheses ternary condition</technical_language>

Target:
public ListBoxModel doFillPriorityIdItems(@AncestorInPath final Item item) { ListBoxModel items = new ListBoxModel().add(""); List<JiraSite> sites = JiraSite.getJiraSites(item); for (JiraSite site : sites) { JiraSession session = site.getSession(item); if (session != null) { for (Priority priority : session.getPriorities()) { items.add("[" + site.getName() + "] " + priority.getName(), String.valueOf(priority.getId())); } } } return items; }
Source:
<code>public Mono<Void> send(Iterable<EventData> events, SendOptions options) { if (events == null) { <START> return Mono.error(logger.logExceptionAsError(new NullPointerException("'events' cannot be null."))); <END> } else if (options == null) { return Mono.error(logger.logExceptionAsError(new NullPointerException("'options' cannot be null."))); } return send(Flux.fromIterable(events), options); }</code><technical_language>FluxUtils in azure-core a convenience method for this monoError(logger, ex)</technical_language>

Target:
public Mono<Void> send(Iterable<EventData> events, SendOptions options) { if (events == null) { return monoError(logger, new NullPointerException("'events' cannot be null.")); } else if (options == null) { return monoError(logger, new NullPointerException("'options' cannot be null.")); } return send(Flux.fromIterable(events), options); }
Source:
<code>public void testRouteStartSuccess() throws Exception { <START> getMockEndpoint("mock:fcrepo:{{fcrepo.baseUri}}").expectedMessageCount(1); <END> createContext(); String body = createBody(); template.sendBodyAndHeaders("direct-vm:createThumbnail", body, createEvent(fileID, eventTypes)); assertMockEndpointsSatisfied(); }</code><technical_language>actual "success" outcome of this part of route "direct:images" endpoint reached, test for in of tests</technical_language>

Target:
public void testRouteStartSuccess() throws Exception { getMockEndpoint("mock:direct:images").expectedMessageCount(1); createContext(enhancementRoute); template.sendBodyAndHeaders("", createEvent(fileID, eventTypes)); assertMockEndpointsSatisfied(); }
Source:
<code>public Result adaptResponse(Row response) { if (response == null) { return new Result(); } <START> SortedSet<Cell> hbaseCells = new TreeSet<>(KeyValue.COMPARATOR); <END> byte[] rowKey = ByteStringer.extract(response.getKey()); for (com.google.cloud.bigtable.data.v2.models.RowCell rowCell : response.getCells()) { if (rowCell.getLabels().size() > 0) { continue; } byte[] familyNameBytes = Bytes.toBytes(rowCell.getFamily()); byte[] columnQualifier = ByteStringer.extract(rowCell.getQualifier()); long hbaseTimestamp = TimestampConverter.bigtable2hbase(rowCell.getTimestamp()); RowCell keyValue = new RowCell( rowKey, familyNameBytes, columnQualifier, hbaseTimestamp, ByteStringer.extract(rowCell.getValue())); hbaseCells.add(keyValue); } return Result.create(hbaseCells.toArray(new Cell[hbaseCells.size()])); }</code><technical_language>This slow down. need sort Row's cells more efficiently. algorithm for somewhere</technical_language>

Target:
public Result adaptResponse(Row response) { if (response == null) { return new Result(); } ImmutableList.Builder<Cell> hbaseCellBuilder = ImmutableList.builder(); byte[] rowKey = ByteStringer.extract(response.getKey()); for (com.google.cloud.bigtable.data.v2.models.RowCell rowCell : response.getCells()) { if (rowCell.getLabels().size() > 0) { continue; } byte[] familyNameBytes = Bytes.toBytes(rowCell.getFamily()); byte[] columnQualifier = ByteStringer.extract(rowCell.getQualifier()); long hbaseTimestamp = TimestampConverter.bigtable2hbase(rowCell.getTimestamp()); RowCell keyValue = new RowCell( rowKey, familyNameBytes, columnQualifier, hbaseTimestamp, ByteStringer.extract(rowCell.getValue())); hbaseCellBuilder.add(keyValue); } ImmutableList<Cell> hbaseCells = hbaseCellBuilder.build(); return Result.create(hbaseCells.toArray(new Cell[hbaseCells.size()])); }
Source:
<code>public void setException(Exception e) { <START> if (e == null) { <END> this.e = null; } else { this.e = new RuntimeException(e); } }</code><technical_language>this.e = e == null ? e : new RuntimeException(e);</technical_language>

Target:
public void setException(Exception e) { this.e = e == null ? null : new RuntimeException(e); }
Source:
<code>public LayerNormBp(SameDiff sameDiff, SDVariable input, SDVariable gain, SDVariable bias, SDVariable gradient, int... dimensions) { <START> super(null, sameDiff, new SDVariable[] {input, gain, bias, gradient}, false); <END> this.dimensions = dimensions; addIArgument(dimensions); }</code><technical_language>LayerNorm - add null entry SDVariable array</technical_language>

Target:
public LayerNormBp(SameDiff sameDiff, SDVariable input, SDVariable gain, SDVariable bias, SDVariable gradient, int... dimensions) { super(null, sameDiff, new SDVariable[] {input, gain, bias, gradient}, false); Preconditions.checkArgument(bias != null, "LayerNormBp: Use constructor without bias argument if bias is null / not available."); setDimensions(dimensions); }
Source:
<code>public Object sampleVal() { checkHasParams(); double[][] mat = new double[d][1]; for (int i = 0; i < d; i++) { mat[i][0] = UnivarGaussian.STANDARD.sampleValue(); } MatrixLib temp = MatrixFactory.fromArray(mat); <START> return mean.transpose().plus(sqrtCovariance.timesMat(temp)); <END> }</code><technical_language>need transpose. I suppose row vector. result is row vector</technical_language>

Target:
public Object sampleVal() { return sample_value(); }
Source:
<code>public List<SshPair> getPairs(String owner, String service) throws ServerException { <START> return sshDao.get(owner, service).stream().collect(Collectors.toList()); <END> }</code><technical_language>List<SshPair>? is kind of weird stuff methods return Impl while this doesn't. changing method return type type returned dao, remove this useless collect</technical_language>

Target:
public List<SshPairImpl> getPairs(String owner, String service) throws ServerException { return sshDao.get(owner, service); }