auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Void visitVariable(VariableTree node, Void p) { warnAboutTypeAnnotationsTooEarly(node, node.getModifiers()); Tree typeTree = node.getType(); <START> while (typeTree.getKind() == Tree.Kind.ARRAY_TYPE) { <END> typeTree = ((ArrayTypeTree) typeTree).getType(); } visitAnnotatedType(node.getModifiers().getAnnotations(), typeTree, node); Pair<Tree, AnnotatedTypeMirror> preAssignmentContext = visitorState.getAssignmentContext(); AnnotatedTypeMirror variableType; if (getCurrentPath().getParentPath() != null && getCurrentPath().getParentPath().getLeaf().getKind() == Tree.Kind.LAMBDA_EXPRESSION) { variableType = atypeFactory.getAnnotatedType(node); } else { variableType = atypeFactory.getAnnotatedTypeLhs(node); } visitorState.setAssignmentContext(Pair.of(node, variableType)); try { if (atypeFactory.getDependentTypesHelper() != null) { atypeFactory.getDependentTypesHelper().checkType(variableType, node); } if (node.getInitializer() != null) { commonAssignmentCheck(node, node.getInitializer(), "assignment.type.incompatible"); } else { validateTypeOf(node); } return super.visitVariable(node, p); } finally { visitorState.setAssignmentContext(preAssignmentContext); } }</code><technical_language>I understand ArrayTypes treated differently</technical_language>

Target:
public Void visitVariable(VariableTree node, Void p) { warnAboutTypeAnnotationsTooEarly(node, node.getModifiers()); visitAnnotatedType(node.getModifiers().getAnnotations(), node.getType()); Pair<Tree, AnnotatedTypeMirror> preAssignmentContext = visitorState.getAssignmentContext(); AnnotatedTypeMirror variableType; if (getCurrentPath().getParentPath() != null && getCurrentPath().getParentPath().getLeaf().getKind() == Tree.Kind.LAMBDA_EXPRESSION) { variableType = atypeFactory.getAnnotatedType(node); } else { variableType = atypeFactory.getAnnotatedTypeLhs(node); } visitorState.setAssignmentContext(Pair.of(node, variableType)); try { if (atypeFactory.getDependentTypesHelper() != null) { atypeFactory.getDependentTypesHelper().checkType(variableType, node); } if (node.getInitializer() != null) { commonAssignmentCheck(node, node.getInitializer(), "assignment.type.incompatible"); } else { validateTypeOf(node); } return super.visitVariable(node, p); } finally { visitorState.setAssignmentContext(preAssignmentContext); } }
Source:
<code>public boolean historyAvailable() { <START> if (testObject.getRun().getParent().getBuilds().isEmpty()) <END> return false; else return true; }</code><technical_language>This is equivalent code (was size >1, size >0)</technical_language>

Target:
public boolean historyAvailable() { if (testObject.getRun().getParent().getBuilds().size() > 1) return true; else return false; }
Source:
<code>private boolean extractZsetIncrementHeader(Message<?> message) { <START> if (message.getHeaders().containsKey(RedisHeaders.ZSET_INCREMENT_SCORE)) { <END> return this.zsetIncrementScoreExpression.getValue(this.evaluationContext, message, Boolean.class); } return false; }</code><technical_language>If open expression for user specification, this if test default FunctionExpression</technical_language>

Target:
private boolean extractZsetIncrementHeader(Message<?> message) { Boolean value = this.zsetIncrementScoreExpression.getValue(this.evaluationContext, message, Boolean.class); return value != null ? value : false; }
Source:
<code>beginRecognizeCustomForms(Flux<ByteBuffer> data, String modelId, long length, FormContentType formContentType, boolean includeTextDetails, Duration pollInterval) { <START> Objects.requireNonNull(data, "'data' is required and cannot be null."); Objects.requireNonNull(modelId, "'modelId' is required and cannot be null."); Objects.requireNonNull(formContentType, "'formContentType' is required and cannot be null."); <END> final Duration interval = pollInterval != null ? pollInterval : DEFAULT_DURATION; return new PollerFlux<OperationResult, IterableStream<RecognizedForm>>( interval, analyzeFormStreamActivationOperation(data, modelId, length, formContentType, includeTextDetails), createAnalyzeFormPollOperation(modelId), (activationResponse, context) -> Mono.error(new RuntimeException("Cancellation is not supported")), fetchAnalyzeFormResultOperation(modelId, includeTextDetails)); }</code><technical_language>Throwing exception in a method returning a reactor publisher issues downstream. Instead exceptions wrapped returned in error channel</technical_language>

Target:
beginRecognizeCustomForms(Flux<ByteBuffer> data, String modelId, long length, FormContentType formContentType, boolean includeTextDetails, Duration pollInterval) { final Duration interval = pollInterval != null ? pollInterval : DEFAULT_DURATION; return new PollerFlux<OperationResult, IterableStream<RecognizedForm>>( interval, analyzeFormStreamActivationOperation(data, modelId, length, formContentType, includeTextDetails), createAnalyzeFormPollOperation(modelId), (activationResponse, context) -> Mono.error(new RuntimeException("Cancellation is not supported")), fetchAnalyzeFormResultOperation(modelId, includeTextDetails)); }
Source:
<code>private void addMessageToSitesTree(final HistoryReference historyReference, final HttpMessage message) { if (View.isInitialised() && !EventQueue.isDispatchThread()) { EventQueue.invokeLater(new Runnable() { @Override public void run() { addMessageToSitesTree(historyReference, message); } }); return; } StructuralNode node = SessionStructure.addPath( Model.getSingleton().getSession(), historyReference, message, true); if (node != null) { try { addUriToAddedNodesModel(SessionStructure.getNodeName(message), message.getRequestHeader().getMethod(), ""); } catch (URIException e) { <START> log.error("Error while recording added node: " + e.getMessage(), e); <END> } } }</code><technical_language>searching code base for this message text is "recording" meaningful a user dev? this adding node tree</technical_language>

Target:
private void addMessageToSitesTree(final HistoryReference historyReference, final HttpMessage message) { if (View.isInitialised() && !EventQueue.isDispatchThread()) { EventQueue.invokeLater(new Runnable() { @Override public void run() { addMessageToSitesTree(historyReference, message); } }); return; } StructuralNode node = SessionStructure.addPath( Model.getSingleton().getSession(), historyReference, message, true); if (node != null) { try { addUriToAddedNodesModel(SessionStructure.getNodeName(message), message.getRequestHeader().getMethod(), ""); } catch (URIException e) { log.error("Error while adding node to added nodes model: " + e.getMessage(), e); } } }
Source:
<code>public void applyRightFloor(final PatchSetApproval a) { final IdentifiedUser user = userFactory.create(a.getAccountId()); short minAllowed = 0, maxAllowed = 0; for (final ProjectRight r : getAllRights(a.getCategoryId())) { final AccountGroup.Id grp = r.getAccountGroupId(); if (user.getEffectiveGroups().contains(grp)) { minAllowed = (short) Math.min(minAllowed, r.getMinValue()); maxAllowed = (short) Math.max(maxAllowed, r.getMaxValue()); } } <START> for (final RefRight refRight : getRefRights(a.getCategoryId())) { <END> final AccountGroup.Id grp = refRight.getAccountGroupId(); if (user.getEffectiveGroups().contains(grp)) { minAllowed = (short) Math.min(minAllowed, refRight.getMinValue()); maxAllowed = (short) Math.max(maxAllowed, refRight.getMaxValue()); } } if (a.getValue() < minAllowed) { a.setValue(minAllowed); dirty(a); } else if (a.getValue() > maxAllowed) { a.setValue(maxAllowed); dirty(a); } }</code><technical_language>This sufficient. scanning *ALL* rights granted in project, rights a specific set of branches. need destination branch of change account deciding RefRight objects consider in this loop. Also, do resolve conflict a ProjectRight grant a RefRight grant? E.g. if group is granted Code Review -2..+2 ProjectRight level Code Review -1..+1 RefRight level? This code stands -2..+2. Do want that? want favor RefRight ProjectRight... favor local ProjectRight inherited ProjectRight --All Projects--</technical_language>

Target:
public void applyRightFloor(final PatchSetApproval a) { final IdentifiedUser user = userFactory.create(a.getAccountId()); short projectMinAllowed = 0, projectMaxAllowed = 0; for (final ProjectRight r : getAllProjectRights(a.getCategoryId())) { final AccountGroup.Id grp = r.getAccountGroupId(); if (user.getEffectiveGroups().contains(grp)) { projectMinAllowed = (short) Math.min(projectMinAllowed, r.getMinValue()); projectMaxAllowed = (short) Math.max(projectMaxAllowed, r.getMaxValue()); } } short refMinAllowed = 0, refMaxAllowed = 0; String destRef = change.getDest().get(); for (final RefRight refRight : getRefRights(a.getCategoryId())) { if (RefControl.matches(destRef, refRight.getRefPattern())) { final AccountGroup.Id grp = refRight.getAccountGroupId(); if (user.getEffectiveGroups().contains(grp)) { refMinAllowed = (short) Math.min(refMinAllowed, refRight.getMinValue()); refMaxAllowed = (short) Math.max(refMaxAllowed, refRight.getMaxValue()); } } } short minAllowed = (short) Math.max(refMinAllowed, projectMinAllowed); short maxAllowed = (short) Math.min(refMaxAllowed, projectMaxAllowed); if (a.getValue() < minAllowed) { a.setValue(minAllowed); dirty(a); } else if (a.getValue() > maxAllowed) { a.setValue(maxAllowed); dirty(a); } }
Source:
<code>public Builder<ChannelFactory> configure(OperationContext context, ModelNode model) throws OperationFailedException { Resource resource = context.getCurrentAddress().equals(this.address) ? context.readResourceFromRoot(this.address, false) : PlaceholderResource.INSTANCE; <START> List<ValueDependency<ProtocolConfiguration>> list = new ArrayList<>(); <END> for (Resource.ResourceEntry entry : resource.getChildren(ProtocolResourceDefinition.WILDCARD_PATH.getKey())) { InjectedValueDependency<ProtocolConfiguration> protocolConfigurationInjectedValueDependency = new InjectedValueDependency<>(new ProtocolServiceNameProvider(this.address, entry.getPathElement()), ProtocolConfiguration.class); list.add(protocolConfigurationInjectedValueDependency); } this.protocols = list; String channelName = this.address.getParent().getLastElement().getValue(); this.parentChannel = new InjectedValueDependency<>(JGroupsRequirement.CHANNEL.getServiceName(context, channelName), Channel.class); this.parentFactory = new InjectedValueDependency<>(JGroupsRequirement.CHANNEL_SOURCE.getServiceName(context, channelName), ChannelFactory.class); return this; }</code><technical_language>ArrayList constructed fixed capacity</technical_language>

Target:
public Builder<ChannelFactory> configure(OperationContext context, ModelNode model) throws OperationFailedException { Resource resource = context.getCurrentAddress().equals(this.address) ? context.readResourceFromRoot(this.address, false) : PlaceholderResource.INSTANCE; final Set<Resource.ResourceEntry> children = resource.getChildren(ProtocolResourceDefinition.WILDCARD_PATH.getKey()); final List<ValueDependency<ProtocolConfiguration>> list = new ArrayList<>(children.size()); for (Resource.ResourceEntry entry : children) { list.add(new InjectedValueDependency<>(new ProtocolServiceNameProvider(this.address, entry.getPathElement()), ProtocolConfiguration.class)); } this.protocols = list; String channelName = this.address.getParent().getLastElement().getValue(); this.parentChannel = new InjectedValueDependency<>(JGroupsRequirement.CHANNEL.getServiceName(context, channelName), Channel.class); this.parentFactory = new InjectedValueDependency<>(JGroupsRequirement.CHANNEL_SOURCE.getServiceName(context, channelName), ChannelFactory.class); return this; }
Source:
<code>public ActiveMQMessage getAMQMessage() { <START> if (message == null) { <END> if (data != null) { try { message = (ActiveMQMessage) wireFormat.unmarshal(new ChannelBufferWrapper(data)); } catch (IOException e) { throw new ActiveMQPropertyConversionException(e.getMessage()); } return message; } else { return new ActiveMQMessage(); } } return message; }</code><technical_language>this need implementing</technical_language>

Target:
public org.apache.activemq.command.ActiveMQMessage getAMQMessage() { return message; }
Source:
<code>public void should_use_parameterized_task_work_dir() throws Exception { runner.setProperty("sonar.task", "views"); runner.setProperty("sonar.working.directory", "generated/reports"); dirs.init(runner); File workDir = new File(runner.property("sonar.working.directory", null)); assertThat(workDir).isNotNull(); <START> assertThat(workDir.getCanonicalPath()).contains("generated/reports"); <END> }</code><technical_language>work Windows</technical_language>

Target:
public void should_use_parameterized_task_work_dir() throws Exception { runner.setProperty("sonar.task", "views"); runner.setProperty("sonar.working.directory", "generated/reports"); dirs.init(runner); File workDir = new File(runner.property("sonar.working.directory", null)); assertThat(workDir).isNotNull(); assertThat(workDir.getCanonicalPath().replace("\\", "/")).contains("generated/reports"); }
Source:
<code>protected List<String> getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { boolean isConsole = sender.isPlayer(); if (args.length == 1) { if (isConsole || sender.isAuthorized("essentials.time.set", ess)) { return Lists.newArrayList("set", "add"); } else { return Collections.emptyList(); } } else if (args.length == 2) { if (args[0].equalsIgnoreCase("set")) { return Lists.newArrayList("sunrise", "day", "morning", "noon", "afternoon", "sunset", "night", "midnight"); } else if (args[0].equalsIgnoreCase("add")) { <START> return Lists.newArrayList("500", "1000", "1500", "2000", "2500", "3000"); <END> } else { return Collections.emptyList(); } } else if (args.length == 3 && (args[0].equalsIgnoreCase("set") || args[0].equalsIgnoreCase("add"))) { List<String> worlds = Lists.newArrayList(); for (World world : server.getWorlds()) { if (isConsole || sender.isAuthorized("essentials.time.world." + normalizeWorldName(world), ess)) { worlds.add(world.getName()); } } if (isConsole || sender.isAuthorized("essentials.time.world.all", ess)) { worlds.add("*"); } return worlds; } else { return Collections.emptyList(); } }</code><technical_language>Numbers a bit weird autocomplete (they ordered in lexicographical order), leave out 500 increment 1000 something, leave out completions entirely</technical_language>

Target:
protected List<String> getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { if (args.length == 1) { if (sender.isAuthorized("essentials.time.set", ess)) { return subCommands; } else { return Collections.emptyList(); } } else if (args.length == 2) { if (args[0].equalsIgnoreCase("set")) { return timeNames; } else if (args[0].equalsIgnoreCase("add")) { return timeNumbers; } else { return Collections.emptyList(); } } else if (args.length == 3 && (args[0].equalsIgnoreCase("set") || args[0].equalsIgnoreCase("add"))) { List<String> worlds = Lists.newArrayList(); for (World world : server.getWorlds()) { if (sender.isAuthorized("essentials.time.world." + normalizeWorldName(world), ess)) { worlds.add(world.getName()); } } if (sender.isAuthorized("essentials.time.world.all", ess)) { worlds.add("*"); } return worlds; } else { return Collections.emptyList(); } }
Source:
<code>public void isAliveShouldReturnTrueWhenRemoteRepositoryNotCached() { RemoteRepository remoteRepository = createMockedRemoteRepository(); boolean alive = remoteRepositoryAlivenessCacheManager.isAlive(remoteRepository); <START> assertTrue(alive); <END> }</code><technical_language>in days org.assertj for assertions :)</technical_language>

Target:
public void isAliveShouldReturnTrueWhenRemoteRepositoryNotCached() { Cache cache = getCache(); Boolean cacheValue = cache.get(REMOTE_REPOSITORY_URL, Boolean.class); boolean alive = remoteRepositoryAlivenessCacheManager.isAlive(remoteRepository); assertThat(cacheValue).isNull(); assertThat(alive).isTrue(); }
Source:
<code>public void onEvent(LockState state) { <START> if (state != LockState.AVAILABLE && UPDATER.compareAndSet(this, LockState.AVAILABLE, state)) { <END> for (ExtendedLockPromise lockPromise : lockPromiseList) { lockPromise.cancel(state); } } if (isAvailable()) { notifier.complete(null); } }</code><technical_language>this change state of composite promise sub-promises AVAILABLE</technical_language>

Target:
public void onEvent(LockState state) { if (state != LockState.ACQUIRED && UPDATER.compareAndSet(this, LockState.ACQUIRED, state)) { for (ExtendedLockPromise lockPromise : lockPromiseList) { lockPromise.cancel(state); } } if (isAvailable()) { notifier.complete(null); } }
Source:
<code>@Test public void configuratorTest() { driver.configuratorSetActionAcknowledgmentTimeout(5); <START> assertJSONElementContains(Setting.WAIT_ACTION_ACKNOWLEDGMENT_TIMEOUT, 5); <END> driver.configuratorSetKeyInjectionDelay(4); assertJSONElementContains(Setting.KEY_INJECTION_DELAY, 4); driver.configuratorSetScrollAcknowledgmentTimeout(3); assertJSONElementContains(Setting.WAIT_SCROLL_ACKNOWLEDGMENT_TIMEOUT, 3); driver.configuratorSetWaitForIdleTimeout(6); assertJSONElementContains(Setting.WAIT_FOR_IDLE_TIMEOUT, 6); driver.configuratorSetWaitForSelectorTimeout(1); assertJSONElementContains(Setting.WAIT_FOR_SELECTOR_TIMEOUT, 1); }</code><technical_language>timeout is in milliseconds. 500 more more understandable</technical_language>

Target:
@Test public void configuratorTest() { driver.configuratorSetActionAcknowledgmentTimeout(500); assertJSONElementContains(Setting.WAIT_ACTION_ACKNOWLEDGMENT_TIMEOUT, 500); driver.configuratorSetKeyInjectionDelay(400); assertJSONElementContains(Setting.KEY_INJECTION_DELAY, 400); driver.configuratorSetScrollAcknowledgmentTimeout(300); assertJSONElementContains(Setting.WAIT_SCROLL_ACKNOWLEDGMENT_TIMEOUT, 300); driver.configuratorSetWaitForIdleTimeout(600); assertJSONElementContains(Setting.WAIT_FOR_IDLE_TIMEOUT, 600); driver.configuratorSetWaitForSelectorTimeout(1000); assertJSONElementContains(Setting.WAIT_FOR_SELECTOR_TIMEOUT, 1000); }
Source:
<code>public boolean isAllowable() { long now = System.currentTimeMillis(); if (now > lastResetTime + interval) { token = buildLongAdder(rate); lastResetTime = now; } boolean flag = false; <START> while (token.sum() > 0 && !flag) { <END> token.decrement(); flag = true; } return flag; }</code><technical_language>token.sum() replaced getToken()</technical_language>

Target:
public boolean isAllowable() { long now = System.currentTimeMillis(); if (now > lastResetTime + interval) { token = buildLongAdder(rate); lastResetTime = now; } if (token.sum() < 0) { return false; } token.decrement(); return true; }
Source:
<code>private void checkComponentIndex(int cIndex) { if (cIndex < 0 || cIndex > componentCount) { <START> ensureAccessible(); <END> throw new IndexOutOfBoundsException(String.format( "cIndex: %d (expected: >= 0 && <= numComponents(%d))", cIndex, componentCount)); } }</code><technical_language>moving if changing behaviour? check throw IOOBE</technical_language>

Target:
private void checkComponentIndex(int cIndex) { ensureAccessible(); if (cIndex < 0 || cIndex > componentCount) { throw new IndexOutOfBoundsException(String.format( "cIndex: %d (expected: >= 0 && <= numComponents(%d))", cIndex, componentCount)); } }
Source:
<code>synchronized void <START> setPlaybackParams(final <END> PlaybackParams params) { PlaybackParams current = null; try { current = getPlaybackParams(); } catch (IllegalStateException e) { } MediaPlayer currentPlayer = getCurrentPlayer(); try { currentPlayer.setPlaybackParams(params); mPlaybackParams = params; } catch (IllegalStateException e) { mPlaybackParamsToSetAfterSetDataSource = params; } if (current != null && current.getSpeed() != params.getSpeed()) { notifyPlayerEvent(new PlayerEventNotifier() { @Override public void notify(PlayerEventCallback cb) { cb.onPlaybackSpeedChanged(mMediaPlayerConnectorImpl, params.getSpeed()); } }); final int currentState = mPlayer.getFirst().mMp2State; if (currentState != PLAYER_STATE_IDLE && currentState != PLAYER_STATE_ERROR) { if (params.getSpeed() == 0f) { setMp2State(currentPlayer, PLAYER_STATE_PAUSED); } else { setMp2State(currentPlayer, PLAYER_STATE_PLAYING); } } } }</code><technical_language>MP2 design doc, setPlaybackParams change state. change playback speed parameters/configuration. implies PlaybackParams.speed zero</technical_language>

Target:
synchronized void setPlaybackParams(final PlaybackParams params) { if (params == null || params.getSpeed() == 0f) { throw new IllegalArgumentException(); } PlaybackParams current = getPlaybackParams(); MediaPlayerSource firstPlayer = mPlayer.getFirst(); if (firstPlayer.mMp2State != PLAYER_STATE_PLAYING) { mPlaybackParamsToSetWhenStarting = params; } else { firstPlayer.mPlayer.setPlaybackParams(params); mPlaybackParamsToSetWhenStarting = null; } if (current != null && current.getSpeed() != params.getSpeed()) { notifyPlayerEvent(new PlayerEventNotifier() { @Override public void notify(PlayerEventCallback cb) { cb.onPlaybackSpeedChanged(mMediaPlayerConnectorImpl, params.getSpeed()); } }); } mPlaybackParams = params; }
Source:
<code>private boolean imageStorageValidation() { if (getDisk().getDiskStorageType() != DiskStorageType.IMAGE || !getVm().getStatus().isRunningOrPaused()) { return true; } DiskImage diskImage = (DiskImage) getDisk(); StorageDomain storageDomain = storageDomainDao.getForStoragePool( diskImage.getStorageIds().get(0), diskImage.getStoragePoolId()); StorageDomainValidator storageDomainValidator = getStorageDomainValidator(storageDomain); return validate(storageDomainValidator.isDomainExistAndActive()) && <START> validate(storageDomainValidator.isBackupDomain()); <END> }</code><technical_language>called 'isNotBackupDomain' clearer</technical_language>

Target:
private boolean imageStorageValidation() { if (getDisk().getDiskStorageType() != DiskStorageType.IMAGE || !getVm().getStatus().isRunningOrPaused()) { return true; } DiskImage diskImage = (DiskImage) getDisk(); StorageDomain storageDomain = storageDomainDao.getForStoragePool( diskImage.getStorageIds().get(0), diskImage.getStoragePoolId()); StorageDomainValidator storageDomainValidator = getStorageDomainValidator(storageDomain); return validate(storageDomainValidator.isDomainExistAndActive()) && validate(storageDomainValidator.isNotBackupDomain()); }
Source:
<code><START> private boolean isChainFinish() { RebalanceFuture fut = this; while (nonNull(fut)) { if (fut.isInitial() || !fut.isDone() || !fut.result()) return false; else fut = fut.next; } return true; } <END></code><technical_language>correct me. Consider a rebalance chain g1 -> g2 ->g3 for topVer=N, g2 is currently rebalancing. Topology is changed N + 1, g3 is incompatible cancelled. g2 finished rebalancing a chain completed g3.rebFut.result=false, should. Also, need copy reference _this_. correct implementation for like: private boolean isChainFinished() { assert isDone() : this; if (isInitial() || !result()) return false; RebalanceFuture fut = next; while (fut != null) { if (fut.isInitial() || !fut.isDone()) return false; else fut = fut.next; } return true; }</technical_language>

Target:
private boolean isChainFinish() { assert isDone() : this; if (isInitial() || !result()) return false; RebalanceFuture fut = next; while (nonNull(fut)) { if (fut.isInitial() || !fut.isDone()) return false; else fut = fut.next; } return true; }
Source:
<code>public int estimateMemoryUsage() { int memEstimate = BASE_MEMORY_USAGE; for (int i = 0; i < numElements; i++) { <START> memEstimate += dvd[i].estimateMemoryUsage(); <END> } return memEstimate; }</code><technical_language>check null reference dvd[i]</technical_language>

Target:
public int estimateMemoryUsage() { int memEstimate = BASE_MEMORY_USAGE; for (int i = 0; i < numElements; i++) { if (dvd[i] != null) memEstimate += dvd[i].estimateMemoryUsage(); } return memEstimate; }
Source:
<code><START> public String query() { <END> if (query == null) { synchronized (conn) { if (query == null) { query = path() == uri || queryStart == -1 ? null : queryStart > 0 && uri.length() > queryStart ? uri.substring(queryStart + 1) : HttpUtils.parseQuery(uri); } } } return query; }</code><technical_language>This unreadable chain of logic operations ternary blocks. I proper if statements preferred more readable</technical_language>

Target:
public String query() { if (query == null && uri != null) { query = path() == uri || queryStart == -1 ? null : queryStart > 0 && uri.length() > queryStart ? uri.substring(queryStart + 1) : HttpUtils.parseQuery(uri); } return query; }
Source:
<code>public T next() throws IOException { if (firstRead) { int firstByte = inputStream.read(); if (firstByte == -1) { return null; <START> } else { <END> inputStream.unread(firstByte); firstRead = false; } } if (streamParser.hasNext()) { try { return GSON.fromJson(streamParser.next(), messageClass); } catch (JsonIOException e) { throw new IOException(e); } catch (JsonParseException ignore) { } } return null; }</code><technical_language>in this case is avoid else statement? java int firstByte = inputStream.read(); if (firstByte == -1) { return null; } inputStream.unread(firstByte); firstRead = false;</technical_language>

Target:
public T next() throws IOException { if (firstRead) { int firstChar = reader.read(); if (firstChar == -1) { return null; } else { reader.unread(firstChar); firstRead = false; } } if (streamParser.hasNext()) { try { return GSON.fromJson(streamParser.next(), messageClass); } catch (JsonIOException e) { throw new IOException(e); } catch (JsonParseException ignore) { } } return null; }
Source:
<code>private List<String> filterConflictsInCourses(String feedbackSessionName, String[] coursesIdToCopyTo) { List<String> courses = new ArrayList<String>(); for (String courseIdToCopy : coursesIdToCopyTo) { FeedbackSessionAttributes existingFs = logic.getFeedbackSession(feedbackSessionName, courseIdToCopy); <START> boolean isFsAlreadyExist = existingFs != null; <END> if (isFsAlreadyExist) { courses.add(existingFs.getCourseId()); } } return courses; }</code><technical_language>hasExistingFs sounds</technical_language>

Target:
private List<String> filterConflictsInCourses(String feedbackSessionName, String[] coursesIdToCopyTo) { List<String> courses = new ArrayList<String>(); for (String courseIdToCopy : coursesIdToCopyTo) { FeedbackSessionAttributes existingFs = logic.getFeedbackSession(feedbackSessionName, courseIdToCopy); boolean hasExistingFs = existingFs != null; if (hasExistingFs) { courses.add(existingFs.getCourseId()); } } return courses; }
Source:
<code>public Storable get(StorableKey key) throws StorageException { Storable val = null; try { val = guavaCache.get(key); <START> } catch (CacheLoader.InvalidCacheLoadException e) { <END> log.debug("Failed to load nonexistent key [" + key + "]. Returning null value.", e); } catch (ExecutionException e) { throw new StorageException(e); } return val; }</code><technical_language>a - <LINK_0></technical_language>

Target:
public Storable get(StorableKey key) throws StorageException { Storable val = null; try { val = guavaCache.get(key); } catch (UncheckedExecutionException e) { if (e.getCause() instanceof NonexistentStorableKeyException) { log.debug("Failed to load nonexistent key [" + key + "]. Returning null value." + Thread.currentThread()); return val; } throw new StorageException(e); } catch (ExecutionException e) { throw new StorageException(e); } return val; }
Source:
<code>public void testInvalidProducerEpochFromProduce() throws InterruptedException { doInitTransactions(); transactionManager.beginTransaction(); transactionManager.failIfNotReadyForSend(); transactionManager.maybeAddPartitionToTransaction(tp0); Future<RecordMetadata> responseFuture = appendToAccumulator(tp0); assertFalse(responseFuture.isDone()); prepareAddPartitionsToTxnResponse(Errors.NONE, tp0, epoch, producerId); prepareProduceResponse(Errors.INVALID_PRODUCER_EPOCH, producerId, epoch); prepareProduceResponse(Errors.NONE, producerId, epoch); sender.runOnce(); runUntil(responseFuture::isDone); <START> assertFalse(transactionManager.hasError()); <END> }</code><technical_language>verify producer retry sending initPid txn coordinator</technical_language>

Target:
public void testInvalidProducerEpochFromProduce() throws InterruptedException { doInitTransactions(); transactionManager.beginTransaction(); transactionManager.failIfNotReadyForSend(); transactionManager.maybeAddPartitionToTransaction(tp0); Future<RecordMetadata> responseFuture = appendToAccumulator(tp0); assertFalse(responseFuture.isDone()); prepareAddPartitionsToTxnResponse(Errors.NONE, tp0, epoch, producerId); prepareProduceResponse(Errors.INVALID_PRODUCER_EPOCH, producerId, epoch); prepareProduceResponse(Errors.NONE, producerId, epoch); sender.runOnce(); runUntil(responseFuture::isDone); assertFalse(transactionManager.hasError()); transactionManager.beginCommit(); TransactionManager.TxnRequestHandler handler = transactionManager.nextRequest(false); assertNotNull(handler); assertTrue(handler.requestBuilder() instanceof EndTxnRequest.Builder); handler = transactionManager.nextRequest(false); assertNotNull(handler); assertTrue(handler.requestBuilder() instanceof InitProducerIdRequest.Builder); }
Source:
<code>public WFIterator() throws IOException { final InputStream inputStream = ParsingUtils.openInputStream(path, wrapper); final PositionalBufferedStream pbs; if (hasBlockCompressedExtension(path)) { <START> final InputStream is = new BlockCompressedInputStream(new BufferedInputStream(inputStream, 512000)); <END> pbs = new PositionalBufferedStream(is, 1000); } else { pbs = new PositionalBufferedStream(inputStream, 512000); } pbs.skip(header.getHeaderEnd()); source = codec.makeSourceFromStream(pbs); readNextRecord(); }</code><technical_language>tribble index gzip files too, bgzip. This limits usage of tribble bgzip..</technical_language>

Target:
public WFIterator() throws IOException { final InputStream inputStream = new BufferedInputStream(ParsingUtils.openInputStream(path, wrapper), 512000); final PositionalBufferedStream pbs; if (hasBlockCompressedExtension(path)) { final InputStream is = BlockCompressedInputStream.isValidFile(inputStream) ? new BlockCompressedInputStream(inputStream) : new GZIPInputStream(inputStream); pbs = new PositionalBufferedStream(is, 1000); } else { pbs = new PositionalBufferedStream(inputStream, 512000); } pbs.skip(header.getHeaderEnd()); source = codec.makeSourceFromStream(pbs); readNextRecord(); }
Source:
<code>public boolean equals(Object obj) { <START> if (this == obj) { <END> return true; } if (!(obj instanceof Provider)) { return false; } Provider other = (Provider) obj; if (!name.equals(other.name) || !role.equals(other.role) || enabled != other.enabled) { return false; } if (params.size() != other.params.size()) { return false; } for (Map.Entry<String, String> param : params.entrySet()) { if (!param.getValue().equals(other.params.get(param.getKey()))) { return false; } } return true; }</code><technical_language>I HashCodeBuilder above. EqualsBuilder (this require implement hashCode equals in Provider too)</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Provider)) { return false; } Provider other = (Provider) obj; return (new EqualsBuilder()).append(name, other.name) .append(role, other.role) .append(params, other.params) .append(enabled, other.enabled) .build(); }
Source:
<code>public void onLoginSuccess(final Credentials credentials) { <START> PullOrganisationCredentialsController pullOrganisationCredentialsController = <END> new PullOrganisationCredentialsController(credentials, loginActivity); IAsyncExecutor asyncExecutor = new AsyncExecutor(); IMainExecutor mainExecutor = new UIThreadExecutor(); PullOrganisationCredentialsUseCase pullOrganisationCredentialsUseCase = new PullOrganisationCredentialsUseCase(asyncExecutor, mainExecutor, pullOrganisationCredentialsController); pullOrganisationCredentialsUseCase.execute( new PullOrganisationCredentialsUseCase.Callback() { @Override public void onComplete() { CheckCredentialsWithOrgUnitUseCase checkCredentialsWithOrgUnitUseCase = new CheckCredentialsWithOrgUnitUseCase(); checkCredentialsWithOrgUnitUseCase.execute(credentials,LoginActivityStrategy.this); } @Override public void onError(String message) { loginActivity.hideProgressBar(); Log.e(this.getClass().getSimpleName(), message); loginActivity.showError(R.string.dialog_title_error); } @Override public void onNetworkError() { CheckCredentialsWithOrgUnitUseCase checkCredentialsWithOrgUnitUseCase = new CheckCredentialsWithOrgUnitUseCase(); checkCredentialsWithOrgUnitUseCase.execute(credentials,LoginActivityStrategy.this); } @Override public void onPullConversionError() { loginActivity.hideProgressBar(); Log.e(this.getClass().getSimpleName(), "Pull conversion error"); loginActivity.showError(R.string.dialog_pull_error); } @Override public void onInvalidCredentials() { loginActivity.hideProgressBar(); Log.e(this.getClass().getSimpleName(), "Invalid credentials"); loginActivity.showError(R.string.login_invalid_credentials); } }); }</code><technical_language>login step realized LoginUseCase</technical_language>

Target:
public void onLoginSuccess(final Credentials credentials) { loginActivity.checkAnnouncement(); }
Source:
<code>public List<Filter> build(Stack<Object> params) { <START> final Object value = params.pop(); <END> final Filter filter = new Filter(propertyName(), convertToComparisonOperator(part.getType()), value); filter.setOwnerEntityType(entityType); filter.setBooleanOperator(booleanOperator); filter.setNegated(isNegated()); setNestedAttributes(part, filter); applyCaseInsensitivityIfShouldIgnoreCase(part, filter); return Collections.singletonList(filter); }</code><technical_language>don final local variables</technical_language>

Target:
public List<Filter> build(Stack<Object> params) { Object value = params.pop(); Filter filter = new Filter(propertyName(), convertToComparisonOperator(part.getType()), value); filter.setOwnerEntityType(entityType); filter.setBooleanOperator(booleanOperator); filter.setNegated(isNegated()); setNestedAttributes(part, filter); applyCaseInsensitivityIfShouldIgnoreCase(part, filter); return Collections.singletonList(filter); }
Source:
<code>private void processApplicationDataRecord(final Record record) { DTLSSession session = null; Connection connection = connectionStore.get(record.getPeerAddress()); if (connection != null && (session = connection.getEstablishedSession()) != null) { RawData receivedApplicationMessage = null; synchronized (session) { if (session.isRecordProcessable(record.getEpoch(), record.getSequenceNumber())) { try { record.setSession(session); ApplicationMessage message = (ApplicationMessage) record.getFragment(); connection.handshakeCompleted(record.getPeerAddress()); session.markRecordAsRead(record.getEpoch(), record.getSequenceNumber()); if (messageHandler != null) { receivedApplicationMessage = createApplicationMessage(message, session); <START> } <END> } catch (HandshakeException | GeneralSecurityException e) { discardRecord(record, e); } } else { LOGGER.log(Level.FINER, "Discarding duplicate APPLICATION_DATA record received from peer [{0}]", record.getPeerAddress()); } } RawDataChannel channel = messageHandler; if (channel != null && receivedApplicationMessage != null) { channel.receiveData(receivedApplicationMessage); } } else { LOGGER.log(Level.FINER, "Discarding APPLICATION_DATA record received from peer [{0}] without an active session", new Object[]{record.getPeerAddress()}); } }</code><technical_language>this test</technical_language>

Target:
private void processApplicationDataRecord(final Record record) { DTLSSession session = null; Connection connection = connectionStore.get(record.getPeerAddress()); if (connection != null && (session = connection.getEstablishedSession()) != null) { RawData receivedApplicationMessage = null; synchronized (session) { if (session.isRecordProcessable(record.getEpoch(), record.getSequenceNumber())) { try { record.setSession(session); ApplicationMessage message = (ApplicationMessage) record.getFragment(); connection.handshakeCompleted(record.getPeerAddress()); session.markRecordAsRead(record.getEpoch(), record.getSequenceNumber()); receivedApplicationMessage = createApplicationMessage(message, session); } catch (HandshakeException | GeneralSecurityException e) { discardRecord(record, e); } } else { LOGGER.log(Level.FINER, "Discarding duplicate APPLICATION_DATA record received from peer [{0}]", record.getPeerAddress()); } } RawDataChannel channel = messageHandler; if (channel != null && receivedApplicationMessage != null) { channel.receiveData(receivedApplicationMessage); } } else { LOGGER.log(Level.FINER, "Discarding APPLICATION_DATA record received from peer [{0}] without an active session", new Object[]{record.getPeerAddress()}); } }
Source:
<code>public void twoSquares() { <START> String squareOf2 = "2S 2H 2C 8D 2H"; <END> String squareOf5 = "4S 5H 5S 5D 5C"; assertEquals(Arrays.asList(squareOf5), new Poker(Arrays.asList(squareOf2, squareOf5)).getBestHands()); }</code><technical_language>I this end in 2D 2H</technical_language>

Target:
public void twoSquares() { String squareOf2 = "2S 2H 2C 8D 2D"; String squareOf5 = "4S 5H 5S 5D 5C"; assertEquals(Collections.singletonList(squareOf5), new Poker(Arrays.asList(squareOf2, squareOf5)).getBestHands()); }
Source:
<code>static Long getAdjustedMemoryLimit(Job job, Long requestedLimit, AbstractAuditor<? extends AbstractAuditMessage> auditor) { if (requestedLimit == null || requestedLimit == DEFAULT_MAX_MODEL_MEMORY.getBytes()) { return null; } long jobLimitMegaBytes = job.getAnalysisLimits() == null || job.getAnalysisLimits().getModelMemoryLimit() == null ? <START> AnalysisLimits.DEFAULT_MODEL_MEMORY_LIMIT_MB : <END> job.getAnalysisLimits().getModelMemoryLimit(); long allowedMax = (long)(new ByteSizeValue(jobLimitMegaBytes, ByteSizeUnit.MB).getBytes() * 0.40); long adjustedMax = Math.min(requestedLimit, allowedMax - 1); if (adjustedMax != requestedLimit) { String msg = "requested forecast limit [" + requestedLimit + "] exceeded [" + allowedMax + "] (40% of the anomaly job memory limit). Reducing to allowed maximum before running forecast."; logger.warn("[{}] {}", job.getId(), msg); auditor.warning(job.getId(), msg); } return adjustedMax; }</code><technical_language>This PRE_6_1_DEFAULT_MODEL_MEMORY_LIMIT_MB. 6.1 model memory limit null, post-6.1 limit is explicitly set. (We do this achieve BWC changed default in 6.1.)</technical_language>

Target:
static Long getAdjustedMemoryLimit(Job job, Long requestedLimit, AbstractAuditor<? extends AbstractAuditMessage> auditor) { if (requestedLimit == null) { return null; } long jobLimitMegaBytes = job.getAnalysisLimits() == null || job.getAnalysisLimits().getModelMemoryLimit() == null ? AnalysisLimits.PRE_6_1_DEFAULT_MODEL_MEMORY_LIMIT_MB : job.getAnalysisLimits().getModelMemoryLimit(); long allowedMax = (long)(new ByteSizeValue(jobLimitMegaBytes, ByteSizeUnit.MB).getBytes() * 0.40); long adjustedMax = Math.min(requestedLimit, allowedMax - 1); if (adjustedMax != requestedLimit) { String msg = "requested forecast memory limit [" + requestedLimit + "] bytes is greater than or equal to [" + allowedMax + "] bytes (40% of the job memory limit). Reducing to [" + adjustedMax + "]."; logger.warn("[{}] {}", job.getId(), msg); auditor.warning(job.getId(), msg); } return adjustedMax; }
Source:
<code>static long calculateDiskCacheSize(File dir) { long size = MIN_DISK_CACHE_SIZE; try { StatFs statFs = new StatFs(dir.getAbsolutePath()); <START> long available = statFs.getBlockCount() * statFs.getBlockSize(); <END> size = available / 50; } catch (IllegalArgumentException ignored) { } return Math.max(Math.min(size, MAX_DISK_CACHE_SIZE), MIN_DISK_CACHE_SIZE); }</code><technical_language>I this overflow coerced a long end. cast of arguments a long ensure long multiplication is performed</technical_language>

Target:
static long calculateDiskCacheSize(File dir) { long size = MIN_DISK_CACHE_SIZE; try { StatFs statFs = new StatFs(dir.getAbsolutePath()); long available = ((long) statFs.getBlockCount()) * statFs.getBlockSize(); size = available / 50; } catch (IllegalArgumentException ignored) { } return Math.max(Math.min(size, MAX_DISK_CACHE_SIZE), MIN_DISK_CACHE_SIZE); }
Source:
<code>private void checkEmptyResultForTargetOnEmptyStorage(Query readCustomersQuery) { final StandStorage standStorageMock = mock(StandStorage.class); when(standStorageMock.readAllByType(any(TypeUrl.class))) .thenReturn(emptyIterator()); when(standStorageMock.readMultiple(any(Iterable.class))) .thenReturn(Collections.<EntityRecord>emptyIterator()); final Stand stand = prepareStandWithAggregateRepo(standStorageMock); final MemoizeQueryResponseObserver responseObserver = new MemoizeQueryResponseObserver(); stand.execute(readCustomersQuery, responseObserver); final List<Any> messageList = checkAndGetMessageList(responseObserver); assertTrue(messageList.isEmpty(), <START> "Query returned a non-empty response message list though the target was empty"); <END> }</code><technical_language>empty, I think</technical_language>

Target:
private void checkEmptyResultForTargetOnEmptyStorage(Query readCustomersQuery) { final StandStorage standStorageMock = mock(StandStorage.class); when(standStorageMock.readAllByType(any(TypeUrl.class))) .thenReturn(emptyIterator()); when(standStorageMock.readMultiple(any(Iterable.class))) .thenReturn(Collections.<EntityRecord>emptyIterator()); final Stand stand = prepareStandWithAggregateRepo(standStorageMock); final MemoizeQueryResponseObserver responseObserver = new MemoizeQueryResponseObserver(); stand.execute(readCustomersQuery, responseObserver); final List<Any> messageList = checkAndGetMessageList(responseObserver); assertTrue(messageList.isEmpty(), "Query returned a non-empty response message list though the target had been " + "empty"); }
Source:
<code>public SpockExecutionContext execute(SpockExecutionContext context, DynamicTestExecutor dynamicTestExecutor) throws Exception { verifyNotSkipped(featureInfo); ErrorInfoCollector errorInfoCollector = new ErrorInfoCollector(); context = context.withErrorInfoCollector(errorInfoCollector); ChildExecutor testExecutor = new ChildExecutor(dynamicTestExecutor); context.getRunner().runParameterizedFeature(context, testExecutor); errorInfoCollector.assertEmpty(); if (testExecutor.getExecutionCount() < 1) { throw new SpockExecutionException("Data provider has no data"); } if (featureInfo.isReportIterations()) { return context; } if (testExecutor.results.containsKey(FAILED)) { List<Throwable> failures = testExecutor.results .get(FAILED) .stream() .filter(Objects::nonNull) .collect(toList()); switch (failures.size()) { case 0: throw new SpockAssertionError("At least one iteration failed"); case 1: sneakyThrow(failures.get(0)); default: MultipleFailuresError multipleFailuresError = new MultipleFailuresError(null, failures); <START> multipleFailuresError.setStackTrace(failures.get(0).getStackTrace()); <END> throw multipleFailuresError; } } else if (!testExecutor.results.containsKey(SUCCESSFUL)) { List<Throwable> abortions = testExecutor.results .get(ABORTED) .stream() .filter(Objects::nonNull) .collect(toList()); Throwable abortion; switch (abortions.size()) { case 0: abortion = new TestAbortedException("All iterations were aborted"); break; case 1: abortion = abortions.get(0); break; default: abortion = new MultipleFailuresError(null, abortions); abortion.setStackTrace(abortions.get(0).getStackTrace()); break; } TestAbortedException testAbortedException; if (abortion instanceof TestAbortedException) { testAbortedException = (TestAbortedException) abortion; } else { testAbortedException = new TestAbortedException("All iterations were aborted", abortion); testAbortedException.setStackTrace(abortion.getStackTrace()); } throw testAbortedException; } return context; }</code><technical_language>sense duplicate stacktrace</technical_language>

Target:
public SpockExecutionContext execute(SpockExecutionContext context, DynamicTestExecutor dynamicTestExecutor) throws Exception { verifyNotSkipped(featureInfo); ErrorInfoCollector errorInfoCollector = new ErrorInfoCollector(); context = context.withErrorInfoCollector(errorInfoCollector); ParameterizedFeatureChildExecutor childExecutor = new ParameterizedFeatureChildExecutor(this, dynamicTestExecutor); context.getRunner().runParameterizedFeature(context, childExecutor); errorInfoCollector.assertEmpty(); if (childExecutor.getExecutionCount() < 1) { throw new SpockExecutionException("Data provider has no data"); } if (featureInfo.isReportIterations()) { return context; } Map<Status, Queue<Throwable>> childResults = childExecutor.getResults(); if (childResults.containsKey(FAILED)) { handleFailedChildren(childResults); } else if (!childResults.containsKey(SUCCESSFUL)) { handleOnlyAbortedChildren(childResults); } return context; }
Source:
<code>public boolean applyCrossSettingWithNamingRules(final CrossSetting crossSetting, final ImportedCrossesList importedCrossesList, final Integer userId, final Workbook workbook) { int entryIdCounter = 1; for (final ImportedCrosses importedCross : importedCrossesList.getImportedCrosses()) { populateSeedSource(importedCross, workbook); importedCross.setEntryCode(String.valueOf(entryIdCounter)); importedCross.setEntryId(entryIdCounter); <START> entryIdCounter = entryIdCounter + 1; <END> } final GermplasmListResult pairsResult = this.generateGermplasmNamePairs(crossSetting, importedCrossesList.getImportedCrosses(), userId, importedCrossesList.hasPlotDuplicate()); final List<Germplasm> germplasmList = this.extractGermplasmList(pairsResult.germplasmPairs); final Integer crossingNameTypeId = this.getIDForUserDefinedFieldCrossingName(); CrossingUtil.applyMethodNameType(this.germplasmDataManager, pairsResult.germplasmPairs, crossingNameTypeId); this.verifyGermplasmMethodPresent(germplasmList); this.save(crossSetting, importedCrossesList, pairsResult.germplasmPairs); return pairsResult.isTrimed; }</code><technical_language>@vmaletta entryIdCounter++;</technical_language>

Target:
public boolean applyCrossSettingWithNamingRules(final CrossSetting crossSetting, final ImportedCrossesList importedCrossesList, final Integer userId, final Workbook workbook) { int entryIdCounter = 1; for (final ImportedCrosses importedCross : importedCrossesList.getImportedCrosses()) { populateSeedSource(importedCross, workbook); importedCross.setEntryCode(String.valueOf(entryIdCounter)); importedCross.setEntryId(entryIdCounter); entryIdCounter++; } final GermplasmListResult pairsResult = this.generateGermplasmNamePairs(crossSetting, importedCrossesList.getImportedCrosses(), userId, importedCrossesList.hasPlotDuplicate()); final List<Germplasm> germplasmList = this.extractGermplasmList(pairsResult.germplasmPairs); final Integer crossingNameTypeId = this.getIDForUserDefinedFieldCrossingName(); CrossingUtil.applyMethodNameType(this.germplasmDataManager, pairsResult.germplasmPairs, crossingNameTypeId); this.verifyGermplasmMethodPresent(germplasmList); this.save(crossSetting, importedCrossesList, pairsResult.germplasmPairs); return pairsResult.isTrimed; }
Source:
<code>public void visitNode(Tree tree) { SwitchStatementTree switchStatementTree = (SwitchStatementTree) tree; List<CaseGroupTree> cases = switchStatementTree.cases(); <START> cases.stream().forEach(c -> c.accept(new NestedSwitchVisitor())); <END> }</code><technical_language>inline here: ((SwitchStatementTree) tree).cases().stream()..</technical_language>

Target:
public void visitNode(Tree tree) { NestedSwitchVisitor visitor = new NestedSwitchVisitor(); ((SwitchStatementTree) tree).cases().stream().forEach(c -> c.accept(visitor)); }