auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public void findDocument_CI() throws Exception { <END> db.getCollection("testCollectionIndex1").drop(); EntityMetadata emd = addCIIndexes(createMetadata()); controller.afterUpdateEntityInfo(null, emd.getEntityInfo(), false); JsonDoc doc = new JsonDoc(loadJsonNode("./testdataCI.json")); TestCRUDOperationContext ctx = new TestCRUDOperationContext("testEntity", CRUDOperation.INSERT); ctx.add(emd); ctx.addDocument(doc); controller.insert(ctx, null); controller.find(ctx, query("{'field':'field2.subArrayField.*', 'regex':'fieldTwoSubArrOne', 'options':'i'}"), projection("{'field':'field2.subArrayField.*'}"), null, null, null); }</code><technical_language>need a test for elemMatch. I do this is: - create a doc CI index in array element field - manually modify array index array._.field="someValue" array._.@mongoHidden.field="REALVALUE" - regex search for "realvalue", find it</technical_language>

Target:
public void findDocument_CI() throws Exception { db.getCollection("testCollectionIndex1").drop(); EntityMetadata emd = addCIIndexes(createMetadata()); controller.afterUpdateEntityInfo(null, emd.getEntityInfo(), false); JsonDoc doc = new JsonDoc(loadJsonNode("./testdataCI.json")); TestCRUDOperationContext ctx = new TestCRUDOperationContext("testEntity", CRUDOperation.INSERT); ctx.add(emd); ctx.addDocument(doc); controller.insert(ctx, null); ctx = new TestCRUDOperationContext("testEntity", CRUDOperation.FIND); ctx.add(emd); controller.find(ctx, query("{'field':'field2.subArrayField.*', 'regex':'fieldTwoSubArrOne', 'options':'i'}"), projection("{'field':'field2.subArrayField.*'}"), null, null, null); assertEquals(1, ctx.getDocuments().size()); }
Source:
<code>public Mono<ResponseEntity<?>> wakeup(@ApiParam("Internal id for workflow instance") @PathVariable("id") long id, @RequestBody @Valid @ApiParam("Expected states") WakeupRequest req) { return handleExceptions(() -> { <START> return wrapBlocking(() -> { <END> WakeupResponse response = new WakeupResponse(); List<String> expectedStates = ofNullable(req.expectedStates).orElseGet(Collections::emptyList); response.wakeupSuccess = workflowInstances.wakeupWorkflowInstance(id, expectedStates); return ok(response); }); }); }</code><technical_language>remove unnecessary { return x; } wrapBlocking</technical_language>

Target:
public Mono<ResponseEntity<?>> wakeup(@ApiParam("Internal id for workflow instance") @PathVariable("id") long id, @RequestBody @Valid @ApiParam("Expected states") WakeupRequest req) { return handleExceptions(() -> wrapBlocking(() -> { WakeupResponse response = new WakeupResponse(); List<String> expectedStates = ofNullable(req.expectedStates).orElseGet(Collections::emptyList); response.wakeupSuccess = workflowInstances.wakeupWorkflowInstance(id, expectedStates); return ok(response); })); }
Source:
<code>public static Map<String, Object> getModifiedEnvMap() { HashMap<String, Object> env = new HashMap<>(System.getenv().size()); for (String key : System.getenv().keySet()) { if (!StringUtils.contains(key, "__")) { continue; } <START> String lookup = StringUtils.lowerCase(StringUtils.replace(key, "__", ".")); <END> if(System.getenv(key) != null) { env.put(lookup, System.getenv(key)); log.debug("Found env " + lookup + " = " + System.getenv(key) + "."); } else { log.debug("Didn't found env " + lookup + "."); } } return env; }</code><technical_language>some keys camel case dspace.baseUrl. Unfortunately, I do values cased changing other property-related behavior</technical_language>

Target:
public static Map<String, Object> getModifiedEnvMap() { HashMap<String, Object> env = new HashMap<>(System.getenv().size()); for (String key : System.getenv().keySet()) { if (!StringUtils.contains(key, "__")) { continue; } String lookup = StringUtils.replace(key, "__P__", "."); lookup = StringUtils.replace(lookup, "__D__", "-"); if (System.getenv(key) != null) { env.put(lookup, System.getenv(key)); log.debug("Found env " + lookup + " = " + System.getenv(key) + "."); } else { log.debug("Didn't found env " + lookup + "."); } } return env; }
Source:
<code>public final Optional<String> promptForBoardName() { BoardNameDialog dlg = new BoardNameDialog(prefs, mainStage); <START> Optional<String> response = dlg.showAndWait(); <END> return response; }</code><technical_language>do return dlg.showAndWait()</technical_language>

Target:
public final Optional<String> promptForBoardName() { BoardNameDialog dlg = new BoardNameDialog(prefs, mainStage); return dlg.showAndWait(); }
Source:
<code>public <K, V> CachingTier<K, V> createCachingTier(Store.Configuration<K, V> storeConfig, ServiceConfiguration<?>... serviceConfigs) { if (serviceProvider == null) { throw new RuntimeException("ServiceProvider is null."); } CompoundCachingTierServiceConfiguration compoundCachingTierServiceConfiguration = findSingletonAmongst(CompoundCachingTierServiceConfiguration.class, (Object[])serviceConfigs); if (compoundCachingTierServiceConfiguration == null) { throw new IllegalArgumentException("Compound caching tier cannot be configured without explicit config"); } CachingTier.Provider higherProvider = serviceProvider.getService(compoundCachingTierServiceConfiguration.higherProvider()); <START> HigherCachingTier<K, V> higherCachingTier = (HigherCachingTier<K, V>) higherProvider.createCachingTier(storeConfig, serviceConfigs); <END> LowerCachingTier.Provider lowerProvider = serviceProvider.getService(compoundCachingTierServiceConfiguration.lowerProvider()); LowerCachingTier<K, V> lowerCachingTier = lowerProvider.createCachingTier(storeConfig, serviceConfigs); CompoundCachingTier<K, V> compoundCachingTier = new CompoundCachingTier<K, V>(higherCachingTier, lowerCachingTier); providersMap.put(compoundCachingTier, new AbstractMap.SimpleEntry<CachingTier.Provider, LowerCachingTier.Provider>(higherProvider, lowerProvider)); return compoundCachingTier; }</code><technical_language>a specialized provider interface for higher tier too</technical_language>

Target:
public <K, V> CachingTier<K, V> createCachingTier(Store.Configuration<K, V> storeConfig, ServiceConfiguration<?>... serviceConfigs) { if (serviceProvider == null) { throw new RuntimeException("ServiceProvider is null."); } CompoundCachingTierServiceConfiguration compoundCachingTierServiceConfiguration = findSingletonAmongst(CompoundCachingTierServiceConfiguration.class, (Object[])serviceConfigs); if (compoundCachingTierServiceConfiguration == null) { throw new IllegalArgumentException("Compound caching tier cannot be configured without explicit config"); } HigherCachingTier.Provider higherProvider = serviceProvider.getService(compoundCachingTierServiceConfiguration.higherProvider()); HigherCachingTier<K, V> higherCachingTier = higherProvider.createHigherCachingTier(storeConfig, serviceConfigs); LowerCachingTier.Provider lowerProvider = serviceProvider.getService(compoundCachingTierServiceConfiguration.lowerProvider()); LowerCachingTier<K, V> lowerCachingTier = lowerProvider.createCachingTier(storeConfig, serviceConfigs); CompoundCachingTier<K, V> compoundCachingTier = new CompoundCachingTier<K, V>(higherCachingTier, lowerCachingTier); providersMap.put(compoundCachingTier, new AbstractMap.SimpleEntry<HigherCachingTier.Provider, LowerCachingTier.Provider>(higherProvider, lowerProvider)); return compoundCachingTier; }
Source:
<code>public static String getFilterString(Map<String, List<String>> scopes) { StringBuilder sb = new StringBuilder(); for (Entry<String, List<String>> scope : scopes.entrySet()) { if (sb.length() > 0 && !scope.getValue().isEmpty()) { sb.append(" and "); <START> } <END> sb.append("("); boolean first = true; for (String value : scope.getValue()) { if (!first) { sb.append(" or "); } else { first = false; } sb.append(scope.getKey()); if ("null".equals(value)) { sb.append(" is null"); } else if (value.isEmpty()) { sb.append("=''"); } else { sb.append("='").append(value).append("'"); } } sb.append(")"); } return sb.toString(); }</code><technical_language>If reading this right add empty parens if of scopes is empty, e.g.: json { "scope1": ["foo"], "scope2": [], "scope3": bar } lead a query like: (scope1='foo') () (scope3='bar')</technical_language>

Target:
public static String getFilterString(Map<String, List<String>> scopes) { StringBuilder sb = new StringBuilder(); for (Entry<String, List<String>> scope : scopes.entrySet()) { if (scope.getValue().isEmpty()) continue; if (sb.length() > 0) { sb.append(" and "); } sb.append("("); boolean first = true; for (String value : scope.getValue()) { if (!first) { sb.append(" or "); } else { first = false; } sb.append(scope.getKey()); if (null == value) { sb.append(" is null"); } else if (value.isEmpty()) { sb.append("=''"); } else { sb.append("='").append(value).append("'"); } } sb.append(")"); } return sb.toString(); }
Source:
<code>private static void deleteFile(File file) throws IOException { if (file.isDirectory()) { for (File c : file.listFiles()) deleteFile(c); } if (!file.delete()) { <START> throw new FileNotFoundException("Failed to delete file: " + file); <END> } }</code><technical_language>file a directory - message misleading</technical_language>

Target:
private static void deleteFile(File file) throws IOException { if (file.isDirectory()) { for (File c : file.listFiles()) { deleteFile(c); } } if (!file.delete()) { throw new IllegalStateException("Failed to delete file or directory: " + file.getAbsolutePath()); } }
Source:
<code>public void testWriteAttribvuteWithReload() throws Exception { cli.sendLine("/subsystem=logging:read-attribute(name=add-logging-api-dependencies)"); CLIOpResult result = cli.readAllAsOpResult(); assertTrue(result.isIsOutcomeSuccess()); String value = (String) result.getResult(); assertThat(value, is("true")); cli.sendLine("/subsystem=logging:write-attribute(name=add-logging-api-dependencies, value=false)"); result = cli.readAllAsOpResult(); assertTrue(result.isIsOutcomeSuccess()); checkResponseHeadersForProcessState(result); <START> container.reload(TIMEOUT); <END> cli.sendLine("/subsystem=logging:read-attribute(name=add-logging-api-dependencies)"); result = cli.readAllAsOpResult(); assertTrue(result.isIsOutcomeSuccess()); value = (String) result.getResult(); assertThat(value, is("false")); cli.sendLine("/subsystem=logging:write-attribute(name=add-logging-api-dependencies, value=false)"); result = cli.readAllAsOpResult(); assertTrue(result.isIsOutcomeSuccess()); assertNoProcessState(result); cli.sendLine("/subsystem=logging:read-attribute(name=add-logging-api-dependencies)"); result = cli.readAllAsOpResult(); assertTrue(result.isIsOutcomeSuccess()); value = (String) result.getResult(); assertThat(value, is("false")); }</code><technical_language>this is a CLI test, CLI do reload</technical_language>

Target:
public void testWriteAttribvuteWithReload() throws Exception { cli.sendLine("/subsystem=logging:read-attribute(name=add-logging-api-dependencies)"); CLIOpResult result = cli.readAllAsOpResult(); assertTrue(result.isIsOutcomeSuccess()); String value = (String) result.getResult(); assertThat(value, is("true")); cli.sendLine("/subsystem=logging:write-attribute(name=add-logging-api-dependencies, value=false)"); result = cli.readAllAsOpResult(); assertTrue(result.isIsOutcomeSuccess()); checkResponseHeadersForProcessState(result); executeReload(); cli.sendLine("/subsystem=logging:read-attribute(name=add-logging-api-dependencies)"); result = cli.readAllAsOpResult(); assertTrue(result.isIsOutcomeSuccess()); value = (String) result.getResult(); assertThat(value, is("false")); cli.sendLine("/subsystem=logging:write-attribute(name=add-logging-api-dependencies, value=false)"); result = cli.readAllAsOpResult(); assertTrue(result.isIsOutcomeSuccess()); assertNoProcessState(result); cli.sendLine("/subsystem=logging:read-attribute(name=add-logging-api-dependencies)"); result = cli.readAllAsOpResult(); assertTrue(result.isIsOutcomeSuccess()); value = (String) result.getResult(); assertThat(value, is("false")); }
Source:
<code>protected void beforeTask() { VmReplicateDiskParameters migrationCompleteParams = new VmReplicateDiskParameters (getEnclosingCommand().getParameters().getVdsId(), getEnclosingCommand().getParameters().getVmId(), getEnclosingCommand().getParameters().getStoragePoolId().getValue(), getEnclosingCommand().getParameters().getSourceStorageDomainId(), getEnclosingCommand().getParameters().getTargetStorageDomainId(), getEnclosingCommand().getParameters().getImageGroupID(), getEnclosingCommand().getParameters().getDestinationImageId() ); try { VDSReturnValue returnValue = Backend.getInstance().getResourceManager(). RunVdsCommand(VDSCommandType.VmReplicateDiskFinish, migrationCompleteParams); <START> if (returnValue.getSucceeded()) { <END> moveDiskInDB(); updateImagesInfo(); ImagesHandler.updateImageStatus(getEnclosingCommand().getParameters().getDestinationImageId(), ImageStatus.OK); } else { handleBeforeTaskFailure(); throw new VdcBLLException(returnValue.getVdsError().getCode(), returnValue.getVdsError().getMessage()); } } catch (Exception ex) { handleBeforeTaskFailure(); throw ex; } }</code><technical_language>Suppose is unsuccessful:</technical_language>

Target:
protected void beforeTask() { VmReplicateDiskParameters migrationCompleteParams = new VmReplicateDiskParameters (getEnclosingCommand().getParameters().getVdsId(), getEnclosingCommand().getParameters().getVmId(), getEnclosingCommand().getParameters().getStoragePoolId().getValue(), getEnclosingCommand().getParameters().getSourceStorageDomainId(), getEnclosingCommand().getParameters().getTargetStorageDomainId(), getEnclosingCommand().getParameters().getImageGroupID(), getEnclosingCommand().getParameters().getDestinationImageId() ); VDSReturnValue ret = Backend.getInstance().getResourceManager(). RunVdsCommand(VDSCommandType.VmReplicateDiskFinish, migrationCompleteParams); if (ret.getSucceeded()) { moveDiskInDB(); updateImagesInfo(); ImagesHandler.updateImageStatus(getEnclosingCommand().getParameters().getDestinationImageId(), ImageStatus.OK); } else { log.errorFormat("Failed VmReplicateDiskFinish (Disk {0} , VM {1})", getEnclosingCommand().getParameters().getImageGroupID(), getEnclosingCommand().getParameters().getVmId()); throw new VdcBLLException(ret.getVdsError().getCode(), ret.getVdsError().getMessage()); } }
Source:
<code>public void refreshItemSetChoices(Hashtable<String, String> userAnswers) { OrderedHashtable<String, QueryPrompt> userInputDisplays = getNeededUserInputDisplays(); boolean dirty = true; <START> while (dirty) { <END> dirty = false; for (Enumeration en = userInputDisplays.keys(); en.hasMoreElements(); ) { String promptId = (String)en.nextElement(); QueryPrompt queryPrompt = userInputDisplays.get(promptId); if (queryPrompt.getInput() != null && queryPrompt.getInput().contentEquals(INPUT_TYPE_SELECT1)) { String answer = userAnswers.get(promptId); populateItemSetChoices(queryPrompt); Vector<SelectChoice> items = queryPrompt.getItemsetBinding().getChoices(); if (!checkForValidSelectValue(items, answer)) { userAnswers.put(promptId, ""); dirty = true; } } } } }</code><technical_language>minor point: sense this code converge, invalid choices blanked out, worst case scenario for 5 choice boxes is loop 5 times, blanking answer time blank. said, while(X) loops for challenging debugging if wrong plan, get a hang-and-kill explicit error. a style/future proofing perspective, I sense add explicit fallback in loop questions N times (where N is size of question set) throw a runtime exception if dirty flag is set Nth pass, continuing loop. ensures code functioning unexpectedly give explicit exception follow on, a hang, notified of crash logs</technical_language>

Target:
public void refreshItemSetChoices(Hashtable<String, String> userAnswers) { OrderedHashtable<String, QueryPrompt> userInputDisplays = getNeededUserInputDisplays(); boolean dirty = true; int index = 0; while (dirty) { if (index == userInputDisplays.size()) { throw new RuntimeException("Invalid itemset state encountered while trying to refresh itemset choices"); } dirty = false; for (Enumeration en = userInputDisplays.keys(); en.hasMoreElements(); ) { String promptId = (String)en.nextElement(); QueryPrompt queryPrompt = userInputDisplays.get(promptId); if (queryPrompt.getInput() != null && queryPrompt.getInput().contentEquals(INPUT_TYPE_SELECT1)) { String answer = userAnswers.get(promptId); populateItemSetChoices(queryPrompt); Vector<SelectChoice> items = queryPrompt.getItemsetBinding().getChoices(); if (!checkForValidSelectValue(items, answer)) { userAnswers.put(promptId, ""); dirty = true; } } } index++; } }
Source:
<code>protected boolean validate() { Guid vdsId = getVdsId(); VDS vds = vdsDao.get(vdsId); if (vds.getStatus() != VDSStatus.Maintenance && vds.getStatus() != VDSStatus.NonResponsive && vds.getStatus() != VDSStatus.Up && vds.getStatus() != VDSStatus.Error && vds.getStatus() != VDSStatus.PreparingForMaintenance && vds.getStatus() != VDSStatus.Down && vds.getStatus() != VDSStatus.InstallFailed) { <START> executeValidationFailure(); <END> return failValidation(EngineMessage.VDS_CANNOT_MAINTENANCE_VDS_IS_NOT_OPERATIONAL); } orderListOfRunningVmsOnVds(vdsId); for (VM vm : vms) { if (vm.isHostedEngine()) { if (!HostedEngineHelper.haveHostsAvailableforHE( vdsDao.getAllForClusterWithStatus(vds.getClusterId(), VDSStatus.Up), Collections.singletonList(vdsId))) { executeValidationFailure(); return failValidation(EngineMessage.VDS_CANNOT_MAINTENANCE_NO_ALTERNATE_HOST_FOR_HOSTED_ENGINE); } continue; } if ((getParameters().isInternal() && vm.getMigrationSupport() == MigrationSupport.IMPLICITLY_NON_MIGRATABLE) || vm.getMigrationSupport() == MigrationSupport.PINNED_TO_HOST) { nonMigratableVms.add(vm.getName()); executeValidationFailure(); return failValidation(EngineMessage.VDS_CANNOT_MAINTENANCE_IT_INCLUDES_NON_MIGRATABLE_VM); } } return true; }</code><technical_language>2 options here: 1. * override failValidation(...) method calls executeValidationFailure() * change executeValidationFailure return boolean invoke failValidation. 2. Rename validate() executeValidation(), validate() calling executeValidationFailure() in case of a failure (similar previous version of this patch)</technical_language>

Target:
protected boolean validate() { boolean result = executeValidation(); if (!result) { executeValidationFailure(); } return result; }
Source:
<code>public SerializationResult serializeWith(ObjectMapper objectMapper, int maxCharsNumber) throws JsonProcessingException { final String fullSerializedString = objectMapper.writeValueAsString(getDelegate()); if (fullSerializedString.length() <= maxCharsNumber) { return new SerializationResult(fullSerializedString, fullSerializedString); } else { final HashMap<String, Object> copiedMap = new HashMap<>(getDelegate()); final PriorityQueue<Map.Entry<String, String>> serializedValueEntries = new PriorityQueue<>( Comparator.comparing((Map.Entry<String, String> e) -> e.getValue().length()).reversed() ); for (Map.Entry<String, Object> e : copiedMap.entrySet()) { serializedValueEntries.add(new AbstractMap.SimpleImmutableEntry<>( e.getKey(), objectMapper.writeValueAsString(e.getValue()) )); } <START> while (!copiedMap.isEmpty() && !serializedValueEntries.isEmpty()) { <END> final Map.Entry<String, String> maxLengthEntry = serializedValueEntries.poll(); Preconditions.checkNotNull(maxLengthEntry); copiedMap.remove(maxLengthEntry.getKey()); final String reducedSerializedString = objectMapper.writeValueAsString(copiedMap); if (reducedSerializedString.length() <= maxCharsNumber) { return new SerializationResult(reducedSerializedString, fullSerializedString); } } final String serializedEmptyMap = objectMapper.writeValueAsString(copiedMap); return new SerializationResult(serializedEmptyMap, fullSerializedString); } }</code><technical_language>I get empty check copiedMap serializedValueEntries number of entries entries removed in loop</technical_language>

Target:
public SerializationResult serializeWith(ObjectMapper objectMapper, int maxCharsNumber) throws JsonProcessingException { final String fullSerializedString = objectMapper.writeValueAsString(getDelegate()); if (fullSerializedString.length() <= maxCharsNumber) { return new SerializationResult(fullSerializedString, fullSerializedString); } else { add(Key.TRUNCATED, true); final ObjectNode contextJsonNode = objectMapper.valueToTree(getDelegate()); final ArrayList<Map.Entry<String, JsonNode>> sortedNodesByLength = Lists.newArrayList(contextJsonNode.fields()); sortedNodesByLength.sort(valueLengthReversedComparator); int needToRemoveCharsNumber = fullSerializedString.length() - maxCharsNumber; for (Map.Entry<String, JsonNode> e : sortedNodesByLength) { final String fieldName = e.getKey(); final JsonNode node = e.getValue(); if (node.isArray()) { if (needToRemoveCharsNumber >= node.toString().length()) { contextJsonNode.remove(fieldName); needToRemoveCharsNumber = contextJsonNode.toString().length() - maxCharsNumber; } else { final ArrayNode arrayNode = (ArrayNode) node; needToRemoveCharsNumber -= removeNodeElementsToSatisfyCharsLimit(arrayNode, needToRemoveCharsNumber); if (arrayNode.size() == 0) { contextJsonNode.remove(fieldName); needToRemoveCharsNumber = contextJsonNode.toString().length() - maxCharsNumber; } } } else { contextJsonNode.remove(fieldName); needToRemoveCharsNumber = contextJsonNode.toString().length() - maxCharsNumber; } if (needToRemoveCharsNumber <= 0) { break; } } return new SerializationResult(contextJsonNode.toString(), fullSerializedString); } }
Source:
<code>public void testSendMessageThenAllowToExpireUsingTimeToLive() throws Exception { AddressSettings as = new AddressSettings(); as.setExpiryAddress(SimpleString.toSimpleString("DLQ")); HierarchicalRepository<AddressSettings> repos = server.getAddressSettingsRepository(); repos.addMatch("exampleQueue", as); Connection connection = null; ConnectionFactory connectionFactory = new JmsConnectionFactory("amqp://localhost:61616"); try { connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); String address = "exampleQueue"; Queue queue = session.createQueue(address); MessageProducer sender = session.createProducer(queue); sender.setTimeToLive(10); Message message = session.createMessage(); sender.send(message); connection.start(); MessageConsumer consumer = session.createConsumer(queue); <START> Message m = consumer.receive(5000); <END> Assert.assertNull(m); consumer.close(); consumer = session.createConsumer(session.createQueue("DLQ")); m = consumer.receive(5000); Assert.assertNotNull(m); consumer.close(); } finally { if (connection != null) { connection.close(); } } }</code><technical_language>a spend 5s waiting</technical_language>

Target:
public void testSendMessageThenAllowToExpireUsingTimeToLive() throws Exception { AddressSettings as = new AddressSettings(); as.setExpiryAddress(SimpleString.toSimpleString("DLQ")); HierarchicalRepository<AddressSettings> repos = server.getAddressSettingsRepository(); repos.addMatch("exampleQueue", as); Connection connection = null; ConnectionFactory connectionFactory = new JmsConnectionFactory("amqp://localhost:61616"); try { connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); String address = "exampleQueue"; Queue queue = session.createQueue(address); MessageProducer sender = session.createProducer(queue); sender.setTimeToLive(1); Message message = session.createMessage(); sender.send(message); connection.start(); MessageConsumer consumer = session.createConsumer(session.createQueue("DLQ")); Message m = consumer.receive(10000); Assert.assertNotNull(m); consumer.close(); consumer = session.createConsumer(queue); m = consumer.receiveNoWait(); Assert.assertNull(m); consumer.close(); } finally { if (connection != null) { connection.close(); } } }
Source:
<code>synchronized public void streamCommands() { if (this.getNextCommand() == null) { logger.log(Level.INFO, "There are no more commands to stream"); return; } <START> if (isPaused()) { <END> logger.log(Level.INFO, "Could not stream commands because the communicator is paused"); return; } while (this.getNextCommand() != null && !isPaused() && CommUtils.checkRoomInBuffer( this.sentBufferSize, this.getNextCommand().getCommandString(), this.getBufferSize()) && allowMoreCommands()) { GcodeCommand command = this.getNextCommand(); if (command.getCommandString().isEmpty()) { dispatchListenerEvents(COMMAND_SKIPPED, command); nextCommand = null; continue; } String commandString = command.getCommandString().trim(); this.activeCommandList.add(command); this.sentBufferSize += (commandString.length() + 1); this.sendMessageToConsoleListener(">>> " + commandString + "\n"); try { this.sendingCommand(commandString); conn.sendStringToComm(commandString + "\n"); dispatchListenerEvents(COMMAND_SENT, command); nextCommand = null; } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } }</code><technical_language>remove this block is handled in while loop</technical_language>

Target:
synchronized public void streamCommands() { if (this.getNextCommand() == null) { logger.log(Level.INFO, "There are no more commands to stream"); return; } while (this.getNextCommand() != null && !isPaused() && CommUtils.checkRoomInBuffer( this.sentBufferSize, this.getNextCommand().getCommandString(), this.getBufferSize()) && allowMoreCommands()) { GcodeCommand command = this.getNextCommand(); if (command.getCommandString().isEmpty()) { dispatchListenerEvents(COMMAND_SKIPPED, command); nextCommand = null; continue; } String commandString = command.getCommandString().trim(); this.activeCommandList.add(command); this.sentBufferSize += (commandString.length() + 1); this.sendMessageToConsoleListener(">>> " + commandString + "\n"); try { this.sendingCommand(commandString); conn.sendStringToComm(commandString + "\n"); dispatchListenerEvents(COMMAND_SENT, command); nextCommand = null; } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } }
Source:
<code>public static void validateParameters(Object obj, ParametersMap paramsMap) { if (paramsMap.size() == 0) { return; } Map<Boolean, List<Parameter>> cmdParams = getCommandParameters(obj); List<Parameter> paramNames = new ArrayList<Parameter>(); <START> for (Map.Entry<Parameter, Serializable> param : paramsMap.entrySet()) { <END> paramNames.add(param.getKey()); } if (!paramNames.containsAll(cmdParams.get(false))) { List<Parameter> copy = new ArrayList(cmdParams.get(true)); copy.removeAll(paramNames); throw new RequiredParametersMissingException(obj.getClass().getName(), copy); } paramNames.removeAll(cmdParams.get(false)); paramNames.removeAll(cmdParams.get(true)); if (paramNames.size() > 0) { StringBuilder buf = new StringBuilder(""); for (Parameter param : paramNames) { if (buf.length() > 0) { buf.append(" ,"); } buf.append(param.getName()); } log.warnFormat("Unknown parameters {0} found in command.", buf.toString()); } }</code><technical_language>support keySet() values() map level</technical_language>

Target:
public static List<String> validateParameters(Object obj, ParametersMap paramsMap) { List<String> messages = new ArrayList<String>(); if (paramsMap.size() > 0) { Map<Boolean, List<Parameter>> cmdParams = getCommandParameters(obj, messages); if (messages.isEmpty()) { List<Parameter> params = new ArrayList<Parameter>(paramsMap.keySet()); if (!params.containsAll(cmdParams.get(false))) { List<Parameter> copy = new ArrayList(cmdParams.get(false)); copy.removeAll(params); log.warnFormat("Required parameters {0} not found in command.", getParameterNames(copy)); messages.add(VdcBllMessages.REQUIRED_PARAMETER_MISSING.name()); } else { params.removeAll(cmdParams.get(false)); params.removeAll(cmdParams.get(true)); if (params.size() > 0) { log.warnFormat("Unknown parameters {0} found in command.", getParameterNames(params)); } } } } return messages; }
Source:
<code>public static void updateFeed(Feed feed, Context context) { Feed dirFeed = feed; String uriStr = dirFeed.getDownload_url(); File f = new File(uriStr.substring("file:".length())); File[] itemFiles = f.listFiles( new FilenameFilter() { @Override public boolean accept(File file, String s) { String m = getMimeType(s); return m != null && (m.startsWith("audio/") || m.startsWith("video/")); } <START> }); <END> List<FeedItem> newItems = dirFeed.getItems(); for (File it: itemFiles) { FeedItem found = feedContainsFile(dirFeed, it.getAbsolutePath()); if (found != null) { } else { FeedItem item = createFeedItem(it, dirFeed); newItems.add(item); } } File[] iconFiles = f.listFiles( new FilenameFilter() { @Override public boolean accept(File file, String s) { return s.toLowerCase().equals("folder.jpg") || s.toLowerCase().equals("folder.png"); } } ); if (iconFiles.length > 0) { dirFeed.setImageUrl( new Uri.Builder().scheme("file").path(iconFiles[0].getAbsolutePath()) .build().toString()); } Feed[] feeds = DBTasks.updateFeed(context, dirFeed); }</code><technical_language>Crashes if files. Please add like: if (itemFiles == null) { reportError(feed, "No media files in local folder"); return; }</technical_language>

Target:
public static void updateFeed(Feed feed, Context context) { Feed dirFeed = DBTasks.updateFeed(context, feed)[0]; String uriStr = dirFeed.getDownload_url(); File f = new File(uriStr.substring("file:".length())); if (!f.exists() || !f.canRead()) { reportError(feed, "Cannot read local directory"); return; } File[] itemFiles = f.listFiles((file, s) -> { String m = getMimeType(s); return m != null && (m.startsWith("audio/") || m.startsWith("video/")); }); List<FeedItem> newItems = dirFeed.getItems(); for (File it: itemFiles) { FeedItem found = feedContainsFile(dirFeed, it.getAbsolutePath()); if (found != null) { } else { FeedItem item = createFeedItem(it, dirFeed); newItems.add(item); } } File[] iconFiles = f.listFiles((file, s) -> s.toLowerCase().equals("folder.jpg") || s.toLowerCase().equals("folder.png")); if (iconFiles.length > 0) { Uri.Builder imageUri = new Uri.Builder() .scheme("file") .path(iconFiles[0].getAbsolutePath()); dirFeed.setImageUrl(imageUri.build().toString()); } DBTasks.updateFeed(context, dirFeed); }
Source:
<code>public void test2GhzNotQualifiedOther2GhzAvailable() { testStayOrSwitch(mThresholdQualifiedRssi2G - 1, false, mThresholdQualifiedRssi2G <START> + 1, false, <END> true); }</code><technical_language>delete</technical_language>

Target:
public void test2GhzNotQualifiedOther2GhzAvailable() { testStayOrSwitch(mThresholdQualifiedRssi2G - 1, false, mThresholdQualifiedRssi2G - 10, false, true); }
Source:
<code>public void configureMessageChannel(MessageChannel messageChannel, String channelName) { BindingProperties bindingProperties = channelBindingServiceProperties.getBindings().get(channelName); <START> if (bindingProperties != null && bindingProperties.getTrackHistory() != null && <END> bindingProperties.getTrackHistory().equals(Boolean.TRUE)) { if (messageChannel instanceof ChannelInterceptorAware) { ((ChannelInterceptorAware) messageChannel).addInterceptor(new ChannelInterceptorAdapter() { @Override public Message<?> preSend(Message<?> message, MessageChannel channel) { @SuppressWarnings("unchecked") Collection<Map<String, Object>> history = (Collection<Map<String, Object>>) message.getHeaders().get(HISTORY_TRACKING_HEADER); if (history == null) { history = new ArrayList<Map<String, Object>>(1); } else { history = new ArrayList<Map<String, Object>>(history); } Map<String, Object> map = new LinkedHashMap<String, Object>(); map.put("thread", Thread.currentThread().getName()); history.add(channelBindingServiceProperties.asMapProperties()); Message<?> out = messageBuilderFactory .fromMessage(message) .setHeader(HISTORY_TRACKING_HEADER, history) .build(); map.put("timestamp", out.getHeaders().getTimestamp()); return out; } }); } } }</code><technical_language>if invert need 2nd null check, e.g.: if (Boolean.TRUE.equals(bindingProperties.getTrackHistory())) {..</technical_language>

Target:
public void configureMessageChannel(MessageChannel messageChannel, String channelName) { BindingProperties bindingProperties = channelBindingServiceProperties.getBindings().get(channelName); if (bindingProperties != null && Boolean.TRUE.equals(bindingProperties.getTrackHistory())) { if (messageChannel instanceof ChannelInterceptorAware) { ((ChannelInterceptorAware) messageChannel).addInterceptor(new ChannelInterceptorAdapter() { @Override public Message<?> preSend(Message<?> message, MessageChannel channel) { @SuppressWarnings("unchecked") Collection<Map<String, Object>> history = (Collection<Map<String, Object>>) message.getHeaders().get(HISTORY_TRACKING_HEADER); if (history == null) { history = new ArrayList<>(1); } else { history = new ArrayList<>(history); } Map<String, Object> map = new LinkedHashMap<String, Object>(); map.put("thread", Thread.currentThread().getName()); history.add(channelBindingServiceProperties.asMapProperties()); Message<?> out = messageBuilderFactory .fromMessage(message) .setHeader(HISTORY_TRACKING_HEADER, history) .build(); map.put("timestamp", out.getHeaders().getTimestamp()); return out; } }); } } }
Source:
<code>private static StructuredProperty buildMainTitle(String softwareTitle, String repositoryName) { return buildTitle( <START> MessageFormat.format(SOFTWARE_TITLE_MAIN_TEMPLATE, new Object[] { softwareTitle, repositoryName }), <END> InfoSpaceConstants.SEMANTIC_CLASS_MAIN_TITLE); }</code><technical_language>I array creation is redundant replaced giving varargs explicitly</technical_language>

Target:
private static StructuredProperty buildMainTitle(String softwareTitle, String repositoryName) { return buildTitle(MessageFormat.format(SOFTWARE_TITLE_MAIN_TEMPLATE, softwareTitle, repositoryName), InfoSpaceConstants.SEMANTIC_CLASS_MAIN_TITLE); }
Source:
<code>public void visitNode(Tree tree) { if (!hasSemantic()) { return; } MethodTree method = (MethodTree) tree; <START> if (!INPUT_STREAM_READ.matches(method) || method.block() == null) { <END> return; } method.accept(new ReturnStatementVisitor()); }</code><technical_language>I switch conditions</technical_language>

Target:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } MethodTree method = (MethodTree) tree; if (method.block() != null && INPUT_STREAM_READ.matches(method)) { method.accept(new ReturnStatementVisitor()); } }
Source:
<code>private boolean match(final MethodNode methodNode, final String superClassName) { vars.put("this", THIS); cursor = methodNode.instructions.getFirst(); nextIsVar(Opcodes.ALOAD, "this"); nextIs(Opcodes.INVOKESPECIAL); MethodInsnNode m = (MethodInsnNode) cursor; if (m != null && superClassName.equals(m.owner) && "<init>".equals(m.name) && ("()V").equals(m.desc)) { nextIs(Opcodes.RETURN); <START> return cursor != null; <END> } return false; }</code><technical_language>If nextIs() boolean return value, write this as: return nextIs(Opcodes.Return) in other existing filters</technical_language>

Target:
private boolean match(final MethodNode methodNode, final String superClassName) { cursor = methodNode.instructions.getFirst(); skipNonOpcodes(); if (cursor.getOpcode() != Opcodes.ALOAD || ((VarInsnNode) cursor).var != 0) { return false; } nextIs(Opcodes.INVOKESPECIAL); MethodInsnNode m = (MethodInsnNode) cursor; if (m != null && superClassName.equals(m.owner) && "<init>".equals(m.name) && ("()V").equals(m.desc)) { nextIs(Opcodes.RETURN); return cursor != null; } return false; }
Source:
<code>public static Map<String, Object> toProperties(DarkClusterConfigMap config) <START> { <END> if (config == null) { return Collections.emptyMap(); } else { Map<String, Object> darkProps = new HashMap<>(); for (Map.Entry<String,DarkClusterConfig> entry : config.entrySet()) { String darkClusterName = entry.getKey(); DarkClusterConfig darkClusterConfig = entry.getValue(); Map<String, Object> prop = new HashMap<>(); if (darkClusterConfig.hasMultiplier()) { prop.put(PropertyKeys.DARK_CLUSTER_MULTIPLIER, darkClusterConfig.getMultiplier().toString()); } if (darkClusterConfig.hasDispatcherOutboundMaxRate()) { prop.put(PropertyKeys.DARK_CLUSTER_OUTBOUND_MAX_RATE, darkClusterConfig.getDispatcherOutboundMaxRate().toString()); } if (darkClusterConfig.hasDispatcherOutboundTargetRate()) { prop.put(PropertyKeys.DARK_CLUSTER_OUTBOUND_TARGET_RATE, darkClusterConfig.getDispatcherOutboundTargetRate().toString()); } if (darkClusterConfig.hasMultiplierStrategyList()) { MultiplierStrategyTypeArray myArray = darkClusterConfig.getMultiplierStrategyList(); List<String> strategyList = new ArrayList<>(); for (multiplierStrategyType type : myArray) { strategyList.add(type.toString()); } prop.put(PropertyKeys.DARK_CLUSTER_MULTIPLIER_STRATEGY_LIST, strategyList); } if (darkClusterConfig.hasTransportClientProperties()) { prop.put(PropertyKeys.DARK_CLUSTER_TRANSPORT_CLIENT_PROPERTIES, TransportClientPropertiesConverter.toProperties(darkClusterConfig.getTransportClientProperties())); } darkProps.put(darkClusterName, prop); } return darkProps; } }</code><technical_language>this behavior of Jackson serialize selectively replace transport properties output of TransportClientPropertiesConverter</technical_language>

Target:
public static Map<String, Object> toProperties(DarkClusterConfigMap config) { if (config == null) { return Collections.emptyMap(); } else { Map<String, Object> darkProps = new HashMap<>(); for (Map.Entry<String,DarkClusterConfig> entry : config.entrySet()) { String darkClusterName = entry.getKey(); DarkClusterConfig darkClusterConfig = entry.getValue(); Map<String, Object> prop = new HashMap<>(); if (darkClusterConfig.hasMultiplier()) { prop.put(PropertyKeys.DARK_CLUSTER_MULTIPLIER, darkClusterConfig.getMultiplier().toString()); } if (darkClusterConfig.hasDarkClusterStrategyPrioritizedList()) { DarkClusterStrategyNameArray strategyNameArray = darkClusterConfig.getDarkClusterStrategyPrioritizedList(); List<String> strategyList = new ArrayList<>(); for (DarkClusterStrategyName type : strategyNameArray) { strategyList.add(type.toString()); } prop.put(PropertyKeys.DARK_CLUSTER_STRATEGY_LIST, strategyList); } if (darkClusterConfig.hasTransportClientProperties()) { prop.put(PropertyKeys.DARK_CLUSTER_TRANSPORT_CLIENT_PROPERTIES, TransportClientPropertiesConverter.toProperties(darkClusterConfig.getTransportClientProperties())); } darkProps.put(darkClusterName, prop); } return darkProps; } }
Source:
<code>private boolean checkValidationAppliesToReturnType(ExecutableElement validationAppliesToMethod) { final DeclaredType constraintTargetType = annotationApiHelper.getDeclaredTypeByName( "javax.validation.ConstraintTarget" ); boolean res = validationAppliesToMethod.getReturnType().accept( new TypeKindVisitor6<Boolean, Void>() { @Override public Boolean visitDeclared(DeclaredType t, Void p) { if ( typeUtils.isSameType( constraintTargetType, t ) ) { return true; } return false; } }, null ); <START> return Boolean.TRUE.equals( res ); <END> }</code><technical_language>Is advantage simply returning res</technical_language>

Target:
private boolean checkValidationAppliesToReturnType(ExecutableElement validationAppliesToMethod) { final DeclaredType constraintTargetType = annotationApiHelper.getDeclaredTypeByName( BeanValidationTypes.CONSTRAINT_TARGET ); return validationAppliesToMethod.getReturnType().accept( new TypeKindVisitor6<Boolean, Void>() { @Override public Boolean visitDeclared(DeclaredType t, Void p) { if ( typeUtils.isSameType( constraintTargetType, t ) ) { return true; } return false; } }, null ); }
Source:
<code>protected VolumeType(String id, String name, @Nullable Date created, @Nullable Date updated, @Nullable Map<String, String> extraSpecs) { this.id = checkNotNull(id, "id"); this.name = checkNotNull(name, "name"); this.created = Optional.fromNullable(created); this.updated = Optional.fromNullable(updated); <START> this.extraSpecs = extraSpecs == null ? new HashMap<String, String>() : ImmutableMap.copyOf(extraSpecs); <END> }</code><technical_language>want immutable collections, use: java this.extraSpecs = extraSpecs == null ? ImmutableMap.of() : ImmutableMap.copyOf(extraSpecs);</technical_language>

Target:
protected VolumeType(String id, String name, @Nullable Date created, @Nullable Date updated, @Nullable Map<String, String> extraSpecs) { this.id = checkNotNull(id, "id"); this.name = checkNotNull(name, "name"); this.created = Optional.fromNullable(created); this.updated = Optional.fromNullable(updated); if (extraSpecs == null) this.extraSpecs = ImmutableMap.of(); else this.extraSpecs = ImmutableMap.copyOf(extraSpecs); }
Source:
<code>public boolean onOptionsItemSelected(MenuItem item) { Fragment currentFragment = getSupportFragmentManager().findFragmentByTag(Transitions.currentContent); if (item.getItemId() == android.R.id.home && !(currentFragment instanceof ConnectFragment)) { toggle(); if(getSlidingMenu().isMenuShowing() && menu.isAdded()){ setTitle(((ITitleable)menu).getTitle()); } <START> else{ <END> Fragment cur = getSupportFragmentManager() .findFragmentByTag(Transitions.currentContent); setTitle(((ITitleable)cur).getTitle()); } return true; } return false; }</code><technical_language>Suggest rewrite this hold ITitleable in a local variable, call setTitle once. This simplify code</technical_language>

Target:
public boolean onOptionsItemSelected(MenuItem item) { Fragment currentFragment = getSupportFragmentManager().findFragmentByTag(Transitions.currentContent); if (item.getItemId() == android.R.id.home && !(currentFragment instanceof ConnectFragment)) { toggle(); int title = ((ITitleable)currentFragment).getTitle(); if(getSlidingMenu().isMenuShowing() && menu.isAdded()){ title = ((ITitleable)menu).getTitle(); } setTitle(title); return true; } return false; }
Source:
<code>TableAsyncClient(String tableName, HttpPipeline pipeline, String url, TablesServiceVersion serviceVersion, SerializerAdapter serializerAdapter) { try { final URI uri = URI.create(url); <START> this.accountName = uri.getHost().split("\\.", 2)[0]; <END> this.tableUrl = uri.resolve("/" + tableName).toString(); logger.verbose("Table Service URI: {}", uri); } catch (IllegalArgumentException ex) { throw logger.logExceptionAsError(ex); } this.implementation = new AzureTableImplBuilder() .url(url) .serializerAdapter(serializerAdapter) .pipeline(pipeline) .version(serviceVersion.getVersion()) .buildClient(); this.tableName = tableName; }</code><technical_language>nit: Change this a constant "\\." reused in ctors locations</technical_language>

Target:
TableAsyncClient(String tableName, HttpPipeline pipeline, String url, TablesServiceVersion serviceVersion, SerializerAdapter serializerAdapter) { this(tableName, new AzureTableImplBuilder() .url(url) .serializerAdapter(serializerAdapter) .pipeline(pipeline) .version(serviceVersion.getVersion()) .buildClient() ); }
Source:
<code>private static void searchResultsCoverageFromPage(SearchIndexAsyncClient searchClient) { PagedFluxBase<SearchResult, SearchPagedResponse> results = searchClient.search("*", <START> new SearchOptions().setMinimumCoverage(73.5), <END> new RequestOptions()); System.out.println("Coverage = " + results .byPage() .take(1) .map(SearchPagedResponse::getCoverage).blockLast()); }</code><technical_language>A minor issue -- In practice, customers typically pick a number 80 for coverage. 73.5 oddly precise</technical_language>

Target:
private static void searchResultsCoverageFromPage(SearchIndexAsyncClient searchClient) { PagedFluxBase<SearchResult, SearchPagedResponse> results = searchClient.search("*", new SearchOptions().setMinimumCoverage(80.0), new RequestOptions()); System.out.println("Coverage = " + results .byPage() .take(1) .map(SearchPagedResponse::getCoverage).blockLast()); }
Source:
<code>protected DocumentModel createHiddenFolder(CoreSession session, String parentPath, String name) { DocumentModel dm = session.createDocumentModel(parentPath, name, "HiddenFolder"); dm.setProperty("dublincore", "title", name); dm.setProperty("dublincore", "description", ""); Framework.doPrivileged(() -> dm.setProperty("dublincore", "created", Calendar.getInstance())); DocumentModel parent = session.createDocument(dm); <START> setFolderPermissions(session, dm); <END> return parent; }</code><technical_language>do need this change</technical_language>

Target:
protected DocumentModel createHiddenFolder(CoreSession session, String parentPath, String name) { DocumentModel dm = session.createDocumentModel(parentPath, name, "HiddenFolder"); dm.setProperty("dublincore", "title", name); dm.setProperty("dublincore", "description", ""); Framework.doPrivileged(() -> dm.setProperty("dublincore", "created", Calendar.getInstance())); DocumentModel parent = session.createDocument(dm); setFolderPermissions(session, parent); return parent; }
Source:
<code>static Realm createInstance(RealmCache cache) { RealmConfiguration configuration = cache.getConfiguration(); try { <START> return createAndValidate(cache); <END> } catch (RealmMigrationNeededException e) { if (configuration.shouldDeleteRealmIfMigrationNeeded()) { deleteRealm(configuration); } else { try { if (configuration.getMigration() != null) { migrateRealm(configuration, e); } } catch (FileNotFoundException fileNotFoundException) { throw new RealmFileException(RealmFileException.Kind.NOT_FOUND, fileNotFoundException); } } return createAndValidate(cache); } }</code><technical_language>naming of this method/variable bugs me, I set finger it. I guess this point sounds validating cache, instead of a new Realm instance. createAndValidateRealmFromCache(cache) that</technical_language>

Target:
static Realm createInstance(RealmCache cache) { RealmConfiguration configuration = cache.getConfiguration(); try { return createAndValidateFromCache(cache); } catch (RealmMigrationNeededException e) { if (configuration.shouldDeleteRealmIfMigrationNeeded()) { deleteRealm(configuration); } else { try { if (configuration.getMigration() != null) { migrateRealm(configuration, e); } } catch (FileNotFoundException fileNotFoundException) { throw new RealmFileException(RealmFileException.Kind.NOT_FOUND, fileNotFoundException); } } return createAndValidateFromCache(cache); } }
Source:
<code>protected int doWork() { <START> IOUtil.assertFileIsReadable(INPUT); <END> MetricsFile<CrosscheckMetric, ?> metricsFile = getMetricsFile(); try { metricsFile.read(new FileReader(INPUT)); } catch (FileNotFoundException e) { e.printStackTrace(); return 1; } clusterMetrics(metricsFile.getMetrics()).write(OUTPUT); return 0; }</code><technical_language>if OUTPUT is non-null, assert is writeable</technical_language>

Target:
protected int doWork() { IOUtil.assertFileIsReadable(INPUT); if(OUTPUT != null) IOUtil.assertFileIsWritable(OUTPUT); final MetricsFile<CrosscheckMetric, ?> metricsFile = getMetricsFile(); try { metricsFile.read(new FileReader(INPUT)); } catch (FileNotFoundException e) { e.printStackTrace(); return 1; } clusterMetrics(metricsFile.getMetrics()).write(OUTPUT); return 0; }
Source:
<code>private void attachAccessibilityDelegateOnBind(ViewHolder holder) { if (isAccessibilityEnabled()) { final View itemView = holder.itemView; if (ViewCompat.getImportantForAccessibility(itemView) == ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO) { ViewCompat.setImportantForAccessibility(itemView, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES); } RecyclerViewAccessibilityDelegate.ItemDelegate itemDelegate = (RecyclerViewAccessibilityDelegate.ItemDelegate) mAccessibilityDelegate.getItemDelegate(); AccessibilityDelegateCompat appDelegate = itemDelegate.getAppAccessibilityDelegate(); if (appDelegate != null) { <START> ViewCompat.setAccessibilityDelegate(holder.itemView, appDelegate); <END> } else { ViewCompat.setAccessibilityDelegate(holder.itemView, itemDelegate); } } }</code><technical_language>This results in bug before... set item delegate, handle calling out appdelegate</technical_language>

Target:
private void attachAccessibilityDelegateOnBind(ViewHolder holder) { if (isAccessibilityEnabled()) { final View itemView = holder.itemView; if (ViewCompat.getImportantForAccessibility(itemView) == ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO) { ViewCompat.setImportantForAccessibility(itemView, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES); } RecyclerViewAccessibilityDelegate.ItemDelegate itemDelegate = (RecyclerViewAccessibilityDelegate.ItemDelegate) mAccessibilityDelegate.getItemDelegate(); AccessibilityDelegateCompat appDelegate = itemDelegate.getAppAccessibilityDelegate(holder.itemView); ViewCompat.setAccessibilityDelegate(holder.itemView, appDelegate); } }
Source:
<code>public void handleSelections() { for (View view : getViews()) { <START> if (view != null) { <END> handleSelection(view); } } }</code><technical_language>This check is redundant check this in handleSelection()</technical_language>

Target:
public void handleSelections() { for (View view : getViews()) { handleSelection(view); } }