auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void commitTransaction() throws Exception { int statusCode = 0, triesCount = 0; HttpResponse response = null; <START> LOGGER.info("Sending bulk request to elasticsearch cluster"); <END> String entity; synchronized (bulkBuilder) { entity = bulkBuilder.toString(); bulkBuilder = new StringBuilder(); } while (statusCode != HttpStatus.SC_OK && triesCount < serversList.size()) { triesCount++; String host = serversList.get(); String url = host + "/" + BULK_ENDPOINT; HttpPost httpRequest = new HttpPost(url); httpRequest.setEntity(new StringEntity(entity)); response = httpClient.execute(httpRequest); statusCode = response.getStatusLine().getStatusCode(); LOGGER.info("Status code from elasticsearch: " + statusCode); if (response.getEntity() != null) { LOGGER.debug("Status message from elasticsearch: " + EntityUtils.toString(response.getEntity(), "UTF-8")); } } if (statusCode != HttpStatus.SC_OK) { if (response.getEntity() != null) { throw new MorphlineRuntimeException(EntityUtils.toString(response.getEntity(), "UTF-8")); } else { throw new MorphlineRuntimeException("Elasticsearch status code was: " + statusCode); } } }</code><technical_language>downgrade INFO DEBUG avoid swamped spam in prod</technical_language>

Target:
public void commitTransaction() throws Exception { int statusCode = 0, triesCount = 0; HttpResponse response = null; LOGGER.debug("Sending bulk request to elasticsearch cluster"); String entity; entity = bulkBuilder.toString(); bulkBuilder = new StringBuilder(); while (statusCode != HttpStatus.SC_OK && triesCount < serversList.size()) { triesCount++; String host = serversList.get(); String url = host + "/" + BULK_ENDPOINT; HttpPost httpRequest = new HttpPost(url); httpRequest.setEntity(new StringEntity(entity)); response = httpClient.execute(httpRequest); statusCode = response.getStatusLine().getStatusCode(); LOGGER.debug("Status code from elasticsearch: " + statusCode); if (response.getEntity() != null) { LOGGER.debug("Status message from elasticsearch: " + EntityUtils.toString(response.getEntity(), "UTF-8")); } } if (statusCode != HttpStatus.SC_OK) { if (response.getEntity() != null) { throw new MorphlineRuntimeException(EntityUtils.toString(response.getEntity(), "UTF-8")); } else { throw new MorphlineRuntimeException("Elasticsearch status code was: " + statusCode); } } }
Source:
<code>public String getFooter(@NonNull List<Receipt> receipts) { if (!receipts.isEmpty()) { final PriceCurrency tripCurrency = receipts.get(0).getTrip().getTripCurrency(); final List<Price> prices = new ArrayList<>(); for (final Receipt receipt : receipts) { prices.add(receipt.getPrice()); } final Price netPrice = new PriceBuilderFactory().setPrices(prices, tripCurrency).build(); if (netPrice instanceof ImmutableNetPriceImpl) { <START> return ((ImmutableNetPriceImpl) netPrice).getCurrencyCodeFormattedNotExchangedPrice(); <END> } else { return netPrice.getDecimalFormattedPrice(); } } else { return ""; } }</code><technical_language>Meaning for this - return getCurrencyCodeFormattedPrice value</technical_language>

Target:
public String getFooter(@NonNull List<Receipt> receipts) { if (!receipts.isEmpty()) { final PriceCurrency tripCurrency = receipts.get(0).getTrip().getTripCurrency(); final List<Price> prices = new ArrayList<>(); for (final Receipt receipt : receipts) { prices.add(receipt.getPrice()); } return new PriceBuilderFactory().setPrices(prices, tripCurrency).build() .getCurrencyCodeFormattedPrice(); } else { return ""; } }
Source:
<code>public HcVaultKmsAead(Vault vault, String keyUri) { this.vault = vault; <START> this.encryptPath = PathBuilder.encryptionPath(keyUri); <END> this.decryptPath = PathBuilder.decryptionPath(keyUri); }</code><technical_language>I need PathBuilder, simple static functions: getEncryptionPath getDecryptionPath. functions validate keyUri matches this pattern: ^%s/*([a-zA-Z0-9.:]+)/keys/(.*)$</technical_language>

Target:
public HcVaultKmsAead(Vault vault, String keyUri) throws GeneralSecurityException { this.vault = vault; this.encryptPath = getEncryptPath(keyUri); this.decryptPath = getDecryptionPath(keyUri); }
Source:
<code>public String getOvnCentralByClusterId(Guid clusterId) { List<Network> clusterNetworks = networkDao.getAllForCluster(clusterId); for (Provider provider : providerDao.getAllByTypes(ProviderType.EXTERNAL_NETWORK)) { for (Network network : clusterNetworks) { ProviderNetwork providerNetwork = network.getProvidedBy(); if (providerNetwork != null <START> && (providerNetwork.getProviderId().equals(provider.getId()))) { <END> return NetworkUtils.getIpAddress(provider.getUrl()); } } } return null; }</code><technical_language>unnecessary :-) if (providerNetwork != null && providerNetwork.getProviderId().equals(provider.getId())) {</technical_language>

Target:
public String getOvnCentralByClusterId(Guid clusterId) { List<Network> clusterNetworks = networkDao.getAllForCluster(clusterId); for (Provider provider : providerDao.getAllByTypes(ProviderType.EXTERNAL_NETWORK)) { for (Network network : clusterNetworks) { ProviderNetwork providerNetwork = network.getProvidedBy(); if (providerNetwork != null && providerNetwork.getProviderId().equals(provider.getId())) { return NetworkUtils.getIpAddress(provider.getUrl()); } } } return null; }
Source:
<code>public void writeBatchToAllNonTxStores(Iterable<MarshallableEntry> entries, Predicate<? super StoreConfiguration> predicate, long flags) { if (!entries.iterator().hasNext()) return; storesMutex.readLock().lock(); try { checkStoreAvailability(); CompletableFuture batchFutures = CompletableFuture.allOf( nonTxWriters.stream() <START> .filter(writer -> !(writer instanceof FlagAffectedStore) || FlagAffectedStore.class.cast(writer).shouldWrite(flags)) <END> .filter(writer -> predicate.test(getStoreConfig(writer))) .map(writer -> writer.writeBatch(Flowable.fromIterable(entries))) .map(CompletionStage::toCompletableFuture) .toArray(CompletableFuture[]::new) ); try { batchFutures.get(); } catch (ExecutionException e) { throw new PersistenceException(e.getCause()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new PersistenceException(e); } } finally { storesMutex.readLock().unlock(); } }</code><technical_language>This alright for now, I change this if I get <LINK_0></technical_language>

Target:
public void writeBatchToAllNonTxStores(Iterable<MarshallableEntry> entries, Predicate<? super StoreConfiguration> predicate, long flags) { if (!entries.iterator().hasNext()) return; storesMutex.readLock().lock(); try { checkStoreAvailability(); CompletableFuture batchFutures = CompletableFuture.allOf( nonTxWriters.stream() .filter(writer -> !(writer instanceof FlagAffectedStore) || FlagAffectedStore.class.cast(writer).shouldWrite(flags)) .filter(writer -> predicate.test(getStoreConfig(writer))) .map(writer -> writer.bulkUpdate(Flowable.fromIterable(entries))) .map(CompletionStage::toCompletableFuture) .toArray(CompletableFuture[]::new) ); try { batchFutures.get(); } catch (ExecutionException e) { throw new PersistenceException(e.getCause()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new PersistenceException(e); } } finally { storesMutex.readLock().unlock(); } }
Source:
<code>private static boolean tryCdata(Scanner scanner) { scanner.next(); if (scanner.next('C') && scanner.next('D') && scanner.next('A') && scanner.next('T') && scanner.next('A') <START> && scanner.next('[')) { <END> while (scanner.find(']') >= 0) { if (scanner.next(']') && scanner.next(']') && scanner.next('>')) { return true; } } } return false; }</code><technical_language>overload next(...) method for multiple char increase more readability here. java if (scanner.next('C', 'D', 'A', 'T', 'A', '[') { .... //Scanner.java public boolean next(char... c) { for (char character: c) { if (!next(character)){ return false; } } return true; } //ScannerTest.java @Test public void testIsNextMultipleCharacter() { Scanner scanner = new Scanner(Collections.<CharSequence>singletonList("foo bar"), 0, 0); assertTrue(scanner.next('f', 'o', 'o', ' ', 'b', 'a', 'r')); assertFalse(scanner.next('r')); }</technical_language>

Target:
private static boolean tryCdata(Scanner scanner) { scanner.next(); if (scanner.next("CDATA[")) { while (scanner.find(']') >= 0) { if (scanner.next("]]>")) { return true; } else { scanner.next(); } } } return false; }
Source:
<code>public String format(final T e) { <START> String message <END> = "Error (" + e.getClass().getSimpleName() + "): " + e.getMessage(); if (e.getCause() != null && !Guard.isStringNullOrEmpty(e.getCause().getMessage())) { message += "\nCause: " + e.getCause().getMessage(); } return message; }</code><technical_language>I replace this a string builder</technical_language>

Target:
public String format(final T e) { final StringBuilder message = new StringBuilder("Error ("); message.append(e.getClass().getSimpleName()); message.append("): "); message.append(e.getMessage()); if (e.getCause() != null && !Guard.isStringNullOrEmpty(e.getCause().getMessage())) { message.append("\nCause: "); message.append(e.getCause().getMessage()); } return message.toString(); }
Source:
<code>private void rightClickBook(GlowPlayer player, ItemStack holding) { if (holding.getItemMeta() instanceof KnowledgeBookMeta) { KnowledgeBookMeta recipes = (KnowledgeBookMeta) holding.getItemMeta(); if (recipes.hasRecipes()) { for (NamespacedKey recipe : recipes.getRecipes()) { player.learnRecipe(((GlowServer) Bukkit.getServer()).getCraftingManager() .getRecipeByKey(recipe), true); } } <START> holding.setAmount(0); <END> } }</code><technical_language>set type air</technical_language>

Target:
private void rightClickBook(GlowPlayer player, ItemStack holding) { if (holding.getItemMeta() instanceof KnowledgeBookMeta) { KnowledgeBookMeta recipes = (KnowledgeBookMeta) holding.getItemMeta(); if (recipes.hasRecipes()) { for (NamespacedKey recipe : recipes.getRecipes()) { player.learnRecipe(((GlowServer) Bukkit.getServer()).getCraftingManager() .getRecipeByKey(recipe), true); } } if (player.getGameMode() != GameMode.CREATIVE) { holding.setAmount(0); } } }
Source:
<code>public Result<TopNResultValue> apply(Cursor cursor) { final DimensionSelector dimSelector = cursor.makeDimensionSelector( query.getDimensionSpec().getDimension(), query.getDimensionSpec().getExtractionFn() ); if (dimSelector == null) { return null; } TopNParams params = null; try { params = topNAlgorithm.makeInitParams(dimSelector, cursor); TopNResultBuilder resultBuilder = BaseTopNAlgorithm.makeResultBuilder(params, query); topNAlgorithm.run(params, resultBuilder, null); return resultBuilder.build(); } finally { <START> if (params != null) { <END> topNAlgorithm.cleanup(params); } } }</code><technical_language>shine some light happen</technical_language>

Target:
public Result<TopNResultValue> apply(Cursor cursor) { final DimensionSelector dimSelector = cursor.makeDimensionSelector( query.getDimensionSpec().getDimension(), query.getDimensionSpec().getExtractionFn() ); if (dimSelector == null) { return null; } TopNParams params = null; try { params = topNAlgorithm.makeInitParams(dimSelector, cursor); TopNResultBuilder resultBuilder = BaseTopNAlgorithm.makeResultBuilder(params, query); topNAlgorithm.run(params, resultBuilder, null); return resultBuilder.build(); } finally { topNAlgorithm.cleanup(params); } }
Source:
<code>public StorageServerConnections(String connection, String id, String iqn, String password, StorageType storageType, String userName, String port, String portal, String vfsType, String mountOptions, NfsVersion nfsVersion, Short nfsRetrans, Short nfsTimeo) { this.connection = connection; this.id = id; this.iqn = iqn; this.password = password; this.storageType = storageType; this.username = userName; this.port = port; this.portal = portal; this.vfsType = vfsType; this.mountOptions = mountOptions; this.nfsVersion = nfsVersion; <START> this.nfsRetrans = nfsRetrans; <END> this.nfsTimeo = nfsTimeo; }</code><technical_language>getStringValueToSet</technical_language>

Target:
public StorageServerConnections(String connection, String id, String iqn, String password, StorageType storageType, String userName, String port, String portal, String vfsType, String mountOptions, NfsVersion nfsVersion, Short nfsRetrans, Short nfsTimeo) { setconnection(connection); setid(id); setiqn(iqn); setpassword(password); setstorage_type(storageType); setuser_name(userName); setport(port); setportal(portal); setVfsType(vfsType); setMountOptions(mountOptions); setNfsVersion(nfsVersion); setNfsRetrans(nfsRetrans); setNfsTimeo(nfsTimeo); }
Source:
<code>private static void validateHeaders(Dictionary<String, String> manifest, boolean jreBundle) throws BundleException { for (String <START> DEFINED_OSGI_VALIDATE_HEADERS1 : <END> DEFINED_OSGI_VALIDATE_HEADERS) { String header = manifest.get(DEFINED_OSGI_VALIDATE_HEADERS1); if (header != null) { ManifestElement[] elements = ManifestElement.parseHeader(DEFINED_OSGI_VALIDATE_HEADERS1, header); checkForDuplicateDirectivesAttributes(DEFINED_OSGI_VALIDATE_HEADERS1, elements); if (DEFINED_OSGI_VALIDATE_HEADERS1 == Constants.IMPORT_PACKAGE) { checkImportExportSyntax(DEFINED_OSGI_VALIDATE_HEADERS1, elements, false, false, jreBundle); } if (DEFINED_OSGI_VALIDATE_HEADERS1 == Constants.DYNAMICIMPORT_PACKAGE) { checkImportExportSyntax(DEFINED_OSGI_VALIDATE_HEADERS1, elements, false, true, jreBundle); } if (DEFINED_OSGI_VALIDATE_HEADERS1 == Constants.EXPORT_PACKAGE) { checkImportExportSyntax(DEFINED_OSGI_VALIDATE_HEADERS1, elements, true, false, jreBundle); } if (DEFINED_OSGI_VALIDATE_HEADERS1 == Constants.FRAGMENT_HOST) { checkExtensionBundle(DEFINED_OSGI_VALIDATE_HEADERS1, elements); } } else if (DEFINED_OSGI_VALIDATE_HEADERS1 == Constants.BUNDLE_SYMBOLICNAME) { throw new BundleException(NLS.bind(StateMsg.HEADER_REQUIRED, Constants.BUNDLE_SYMBOLICNAME), BundleException.MANIFEST_ERROR); } } }</code><technical_language>name definedOSGiValidateHeader</technical_language>

Target:
private static void validateHeaders(Dictionary<String, String> manifest, boolean jreBundle) throws BundleException { for (String definedOSGiValidateHeader : DEFINED_OSGI_VALIDATE_HEADERS) { String header = manifest.get(definedOSGiValidateHeader); if (header != null) { ManifestElement[] elements = ManifestElement.parseHeader(definedOSGiValidateHeader, header); checkForDuplicateDirectivesAttributes(definedOSGiValidateHeader, elements); if (definedOSGiValidateHeader == Constants.IMPORT_PACKAGE) { checkImportExportSyntax(definedOSGiValidateHeader, elements, false, false, jreBundle); } if (definedOSGiValidateHeader == Constants.DYNAMICIMPORT_PACKAGE) { checkImportExportSyntax(definedOSGiValidateHeader, elements, false, true, jreBundle); } if (definedOSGiValidateHeader == Constants.EXPORT_PACKAGE) { checkImportExportSyntax(definedOSGiValidateHeader, elements, true, false, jreBundle); } if (definedOSGiValidateHeader == Constants.FRAGMENT_HOST) { checkExtensionBundle(definedOSGiValidateHeader, elements); } } else if (definedOSGiValidateHeader == Constants.BUNDLE_SYMBOLICNAME) { throw new BundleException(NLS.bind(StateMsg.HEADER_REQUIRED, Constants.BUNDLE_SYMBOLICNAME), BundleException.MANIFEST_ERROR); } } }
Source:
<code>protected void internalReceiveCommand(String itemName, Command command) { logger.debug("internalReceiveCommand({},{}) is called!", itemName, command); <START> } <END></code><technical_language>need override this method if handle commands updates</technical_language>

Target:
protected void internalReceiveCommand(String itemName, Command command) { writeToGiraHomeServerBuffered(itemName, command); }
Source:
<code>@Override public RexNode visitCall(RexCall call) { if (call.getOperator().getKind() == SqlKind.NOT) { RexNode child = call.getOperands().get(0); if (child.getKind() == SqlKind.LIKE) { List<RexNode> operands = FluentIterable.from(((RexCall) child).getOperands()) <START> .transform(new Function<RexNode, RexNode>() { <END> @Override public RexNode apply(RexNode rexNode) { return rexNode.accept(NotLikeConverter.this); } }).toList(); return rexBuilder.makeCall(SqlStdOperatorTable.NOT_LIKE, operands); } } return super.visitCall(call); }</code><technical_language>For new code, good stick Java 8 lambda syntax patch @julianhyde landed. is rexNode -> rexNode.accept(NotLikeConverter.this)</technical_language>

Target:
@Override public RexNode visitCall(RexCall call) { if (call.getOperator().getKind() == SqlKind.NOT) { RexNode child = call.getOperands().get(0); if (child.getKind() == SqlKind.LIKE) { List<RexNode> operands = ((RexCall) child).getOperands() .stream() .map(rexNode -> rexNode.accept(NotLikeConverter.this)) .collect(Collectors.toList()); return rexBuilder.makeCall(SqlStdOperatorTable.NOT_LIKE, operands); } } return super.visitCall(call); }
Source:
<code>public ResponderServer listen() { ChannelManager channelManager = msbContext.getChannelManager(); <START> boolean isAlreadySubscribed = channelManager.subscribe(namespace, <END> message -> { LOG.debug("Received message with id from topic {}", message.getId(), namespace); ResponderImpl responder = new ResponderImpl(messageTemplate, message, msbContext); onResponder(responder); }); if(isAlreadySubscribed) { throw new IllegalStateException("Only one instance of ResponderServer should be created"); } return this; }</code><technical_language>throw exception level in ChannelManager? This solution lead conflict DefaultChannelMonitorAggregator ResponderServer</technical_language>

Target:
public ResponderServer listen() { ChannelManager channelManager = msbContext.getChannelManager(); channelManager.subscribe(namespace, message -> { LOG.debug("Received message with id from topic {}", message.getId(), namespace); ResponderImpl responder = new ResponderImpl(messageTemplate, message, msbContext); onResponder(responder); }); return this; }
Source:
<code>private void addCrossCompilationOptions(ImmutableList.Builder<String> command) { if (shouldCrossCompile()) { command.add("-j"); javacOptions.appendOptionsTo( new OptionsConsumer() { @Override public void addOptionValue(String option, String value) { if (option.equals("sourcepath")) { return; } if (option.equals("classpath") && value.equals("''")) { return; <START> } <END> if (!Strings.isNullOrEmpty(value)) { command.add("-J" + String.format("%s=%s", option, value)); } } @Override public void addFlag(String flagName) { command.add("-F" + flagName); } @Override public void addExtras(Collection<String> extras) { for (String extra : extras) { if (extra.startsWith("-")) { addFlag(extra.substring(1)); } else { addFlag(extra); } } } }, resolver, filesystem); } }</code><technical_language>do need a behavior change in GroovycStep this change? this existing bug? If so, this done separately</technical_language>

Target:
private void addCrossCompilationOptions(ImmutableList.Builder<String> command) { if (shouldCrossCompile()) { command.add("-j"); javacOptions.appendOptionsTo( new OptionsConsumer() { @Override public void addOptionValue(String option, String value) { if (option.equals("sourcepath")) { return; } if (!Strings.isNullOrEmpty(value)) { command.add("-J" + String.format("%s=%s", option, value)); } } @Override public void addFlag(String flagName) { command.add("-F" + flagName); } @Override public void addExtras(Collection<String> extras) { for (String extra : extras) { if (extra.startsWith("-")) { addFlag(extra.substring(1)); } else { addFlag(extra); } } } }, resolver, filesystem); } }
Source:
<code>private StudentProfileAttributes extractProfileData() { StudentProfileAttributes editedProfile = new StudentProfileAttributes(); editedProfile.googleId = account.googleId; editedProfile.shortName = getRequestParamValue(Const.ParamsNames.STUDENT_SHORT_NAME); editedProfile.email = getRequestParamValue(Const.ParamsNames.STUDENT_PROFILE_EMAIL); editedProfile.institute = getRequestParamValue(Const.ParamsNames.STUDENT_PROFILE_INSTITUTION); editedProfile.nationality = getRequestParamValue(Const.ParamsNames.STUDENT_NATIONALITY); editedProfile.gender = getRequestParamValue(Const.ParamsNames.STUDENT_GENDER); editedProfile.moreInfo = getRequestParamValue(Const.ParamsNames.STUDENT_PROFILE_MOREINFO); editedProfile.pictureKey = ""; validatePostParameters(editedProfile); <START> trimStudentProfileValues(editedProfile); <END> return editedProfile; }</code><technical_language>trimming validating</technical_language>

Target:
private StudentProfileAttributes extractProfileData() { StudentProfileAttributes editedProfile = new StudentProfileAttributes(); editedProfile.googleId = account.googleId; editedProfile.shortName = getRequestParamValue(Const.ParamsNames.STUDENT_SHORT_NAME); editedProfile.email = getRequestParamValue(Const.ParamsNames.STUDENT_PROFILE_EMAIL); editedProfile.institute = getRequestParamValue(Const.ParamsNames.STUDENT_PROFILE_INSTITUTION); editedProfile.nationality = getRequestParamValue(Const.ParamsNames.STUDENT_NATIONALITY); editedProfile.gender = getRequestParamValue(Const.ParamsNames.STUDENT_GENDER); editedProfile.moreInfo = getRequestParamValue(Const.ParamsNames.STUDENT_PROFILE_MOREINFO); editedProfile.pictureKey = ""; preprocessParameters(editedProfile); validatePostParameters(editedProfile); return editedProfile; }
Source:
<code>public static Map<Role, List<ActionType>> getRolesWhichCanWorkWithAttribute(ActionType actionType, AttributeDefinition attrDef) throws InternalErrorException { String actType = actionType.getActionType().toLowerCase() + "%"; try { Map<Role, List<ActionType>> result = new HashMap<>(); List<Pair<Role, ActionType>> pairs = jdbc.query("select distinct roles.name, action_types.action_type from attributes_authz " + "join roles on attributes_authz.role_id=roles.id " + "join action_types on attributes_authz.action_type_id=action_types.id " + "where attributes_authz.attr_id=? and action_types.action_type like ?", (rs, arg1) -> new Pair<>(Role.valueOf(rs.getString("name").toUpperCase()), ActionType.valueOf(rs.getString("action_type").toUpperCase())), attrDef.getId(), actType); for (Pair<Role, ActionType> pair : pairs) { if (result.containsKey(pair.getLeft())) { List<ActionType> rights = new ArrayList<>(); rights.add(pair.getRight()); rights.addAll(result.get(pair.getLeft())); <START> result.replace(pair.getLeft(), rights); <END> } else { List<ActionType> rights = new ArrayList<>(); rights.add(pair.getRight()); result.put(pair.getLeft(), rights); } } return result; } catch (EmptyResultDataAccessException e) { return new HashMap<>(); } catch (RuntimeException e) { throw new InternalErrorException(e); } }</code><technical_language>do need create a new array list replace one. rights.get(pair.getLeft()).add(pair.getRight())</technical_language>

Target:
public static Map<Role, Set<ActionType>> getRolesWhichCanWorkWithAttribute(ActionType actionType, AttributeDefinition attrDef) throws InternalErrorException { String actType = actionType.getActionType().toLowerCase() + "%"; try { List<Pair<Role, ActionType>> pairs = jdbc.query("select distinct roles.name, action_types.action_type from attributes_authz " + "join roles on attributes_authz.role_id=roles.id " + "join action_types on attributes_authz.action_type_id=action_types.id " + "where attributes_authz.attr_id=? and action_types.action_type like ?", (rs, arg1) -> new Pair<>(Role.valueOf(rs.getString("name").toUpperCase()), ActionType.valueOf(rs.getString("action_type").toUpperCase())), attrDef.getId(), actType); Map<Role, Set<ActionType>> result = new HashMap<>(); for (Pair<Role, ActionType> pair : pairs) { if (result.containsKey(pair.getLeft())) { result.get(pair.getLeft()).add(pair.getRight()); } else { Set<ActionType> rights = new HashSet<>(); rights.add(pair.getRight()); result.put(pair.getLeft(), rights); } } return result; } catch (EmptyResultDataAccessException e) { return new HashMap<>(); } catch (RuntimeException e) { throw new InternalErrorException(e); } }
Source:
<code>private double getPenaltyDistribution(Distribution distribution, double scaleFactor) { <START> int[] result = analyzeDistribution(distribution); <END> int count = result[0]; int top1 = result[1]; int top2 = result[2]; if (scaleFactor == 1d) { return count * (penaltyMaxScale / penaltyMax); } if (top1 != top2) { double penalty = penaltyInfrequentResponse * (1d - scaleFactor) + penaltyMaxScale * scaleFactor; return (count - top1) * (penalty / penaltyMax); } else { double penalty = penaltyNoMajorityResponse * (1d - scaleFactor) + penaltyMaxScale * scaleFactor; return count * (penalty / penaltyMax); } }</code><technical_language>int[] statistics</technical_language>

Target:
private double getPenaltyDistribution(Distribution distribution, double scaleFactor) { int[] statistics = getStatistics(distribution); int count = statistics[0]; int top1 = statistics[1]; int top2 = statistics[2]; if (scaleFactor == 1d) { return count * (penaltyMaxScale / penaltyMax); } if (top1 != top2) { double penalty = penaltyInfrequentResponse * (1d - scaleFactor) + penaltyMaxScale * scaleFactor; return (count - top1) * (penalty / penaltyMax); } else { double penalty = penaltyNoMajorityResponse * (1d - scaleFactor) + penaltyMaxScale * scaleFactor; return count * (penalty / penaltyMax); } }
Source:
<code>public void testPANBroadcastSerialDataReceiveSubscribedRx16() throws Exception { Mockito.when(rx16Packet.getReceiveOptions()).thenReturn(RECEIVE_OPTIONS_BROADCAST_PAN); dataReader.addSerialDatatReceiveListener(receiveSerialDataListener); Whitebox.invokeMethod(dataReader, PACKET_RECEIVED_METHOD, rx16Packet); PowerMockito.verifyPrivate(dataReader, Mockito.times(1)).invoke(NOTIFY_SERIAL_DATA_RECEIVED_METHOD, XBEE_16BIT_ADDRESS.toString(), RECEIVED_DATA_BYTES, IS_BROADCAST_DATA); Mockito.verify(receiveSerialDataListener, Mockito.times(1)).broadcastSerialDataReceived(XBEE_16BIT_ADDRESS.toString(), RECEIVED_DATA_BYTES); <START> <END> assertEquals(XBEE_16BIT_ADDRESS.toString(), receiveSerialDataListener.getAddress()); assertArrayEquals(RECEIVED_DATA_BYTES, receiveSerialDataListener.getSerialData()); }</code><technical_language>Add a check verify serialDataReceived method called</technical_language>

Target:
public void testPANBroadcastSerialDataReceiveSubscribedRx16() throws Exception { Mockito.when(rx16Packet.getReceiveOptions()).thenReturn(RECEIVE_OPTIONS_BROADCAST_PAN); dataReader.addSerialDatatReceiveListener(receiveSerialDataListener); Whitebox.invokeMethod(dataReader, PACKET_RECEIVED_METHOD, rx16Packet); PowerMockito.verifyPrivate(dataReader, Mockito.times(1)).invoke(NOTIFY_SERIAL_DATA_RECEIVED_METHOD, XBEE_16BIT_ADDRESS.toString(), RECEIVED_DATA_BYTES, IS_BROADCAST_DATA); Mockito.verify(receiveSerialDataListener, Mockito.times(1)).broadcastSerialDataReceived(XBEE_16BIT_ADDRESS.toString(), RECEIVED_DATA_BYTES); Mockito.verify(receiveSerialDataListener, Mockito.never()).serialDataReceived(Mockito.anyString(), (byte[])Mockito.any()); assertEquals(XBEE_16BIT_ADDRESS.toString(), receiveSerialDataListener.getAddress()); assertArrayEquals(RECEIVED_DATA_BYTES, receiveSerialDataListener.getSerialData()); }
Source:
<code>public void beforeAll(ExtensionContext context) { Class<?> testClass = context.getTestClass() .orElseThrow(() -> new ExtensionConfigurationException("TestcontainersExtension is only supported for classes.")); Store store = context.getStore(NAMESPACE); List<TestLifecycleAware> lifecycleAwareContainers = findSharedContainers(testClass) <START> .peek(adapter -> store.getOrComputeIfAbsent(adapter.getKey(), k -> adapter.start())) <END> .filter(this::isTestLifecycleAware) .map(lifecycleAwareAdapter -> (TestLifecycleAware) lifecycleAwareAdapter.container) .collect(toList()); store.put(SHARED_LIFECYCLE_AWARE_CONTAINERS, lifecycleAwareContainers); signalBeforeTestToContainers(lifecycleAwareContainers, testDescriptionFrom(context)); }</code><technical_language>I peek is here, honest I feel clearer distinct passes collection. call start(), other find lifecycle aware containers. Combining pass is arguably more concise, harder happening</technical_language>

Target:
public void beforeAll(ExtensionContext context) { Class<?> testClass = context.getTestClass() .orElseThrow(() -> new ExtensionConfigurationException("TestcontainersExtension is only supported for classes.")); Store store = context.getStore(NAMESPACE); List<StoreAdapter> sharedContainersStoreAdapters = findSharedContainers(testClass); sharedContainersStoreAdapters.forEach(adapter -> store.getOrComputeIfAbsent(adapter.getKey(), k -> adapter.start())); List<TestLifecycleAware> lifecycleAwareContainers = sharedContainersStoreAdapters .stream() .filter(this::isTestLifecycleAware) .map(lifecycleAwareAdapter -> (TestLifecycleAware) lifecycleAwareAdapter.container) .collect(toList()); store.put(SHARED_LIFECYCLE_AWARE_CONTAINERS, lifecycleAwareContainers); signalBeforeTestToContainers(lifecycleAwareContainers, testDescriptionFrom(context)); }
Source:
<code>public <K, V> void assertContainsOnlyKeys(AssertionInfo info, Map<K, V> actual, Iterable<K> keys) { assertNotNull(info, actual); failIfNull(keys); if (actual.isEmpty() && !keys.iterator().hasNext()) { return; } if (!keys.iterator().hasNext()) { throw new IllegalArgumentException(ErrorMessages.iterableOfKeysToLookForIsEmpty()); } <START> final K[] keysAsArray = (K[]) StreamSupport.stream(keys.spliterator(), false).toArray(Object[]::new); <END> compareActualMapAndExpectedKeys(info, actual, keysAsArray); }</code><technical_language>Please org.assertj.core.util.Streams#stream instead</technical_language>

Target:
public <K, V> void assertContainsOnlyKeys(AssertionInfo info, Map<K, V> actual, Iterable<K> keys) { final K[] keysAsArray = keys != null ? (K[]) Streams.stream(keys).toArray(Object[]::new) : null; assertContainsOnlyKeys(info, actual, "keys iterable", keysAsArray); }
Source:
<code><START> private void clearSourceAndTargetFolder() { <END> File sourceDirectory = sourceFolder; for (File sourceFile : sourceDirectory.listFiles()) { sourceFile.delete(); } File targetDirectory = targetFolder; for (File targetFile : targetDirectory.listFiles()) { targetFile.delete(); } }</code><technical_language>@After for this method. need call manually test case. I get called if test case throws exception (which happen current implementation)</technical_language>

Target:
public void clearSourceAndTargetFolder() { deleteFiles(sourceFolder); deleteFiles(targetFolder); }
Source:
<code>public void validate() { <START> checkNotNullOrEmpty(configuration.getProjectId(), "project"); <END> checkNotNullOrEmpty(configuration.getZone(), "zone"); checkNotNullOrEmpty(configuration.getCluster(), "cluster"); checkNotNullOrEmpty(configuration.getTable(), "table"); }</code><technical_language>perform a remote (Cloud BigTable) operation check if key range is valid</technical_language>

Target:
public void validate() { CloudBigtableIO.validate(configuration, configuration.getTableId()); }
Source:
<code><START> public List<AnnotationTypeInfo> getAnnotations() { <END> return annotations; }</code><technical_language>missing doc</technical_language>

Target:
public List<AnnotationValueInfo> getAnnotations() { return annotations; }
Source:
<code>public ValidationResult networkNameNotUsedAsVdsmName() { <START> List<String> conflictingNetworks = getDbFacade() <END> .getNetworkDao() .getAllForDataCenter(network.getDataCenterId()) .stream() .filter(net -> !net.getId().equals(network.getId())) .filter(net -> net.getVdsmName().equals(network.getName())) .map(net -> net.getName()) .collect(toList()); if (conflictingNetworks.isEmpty()) { return ValidationResult.VALID; } Collection<String> nameReplacements = ReplacementUtils.replaceWith("ConflictingNetworks", conflictingNetworks); nameReplacements.add(getNetworkNameReplacement()); return new ValidationResult(EngineMessage.NETWORK_NAME_USED_AS_INTERFACE_NAME, nameReplacements); }</code><technical_language>Please injection get 'networkDao', 'DbFacade' is deprected. refer 'getManagementNetworkUtil()' for example</technical_language>

Target:
public ValidationResult networkNameNotUsedAsVdsmName() { List<String> conflictingNetworks = getDbFacade() .getNetworkDao() .getAllForDataCenter(network.getDataCenterId()) .stream() .filter(net -> !net.getId().equals(network.getId())) .filter(net -> net.getVdsmName().equals(network.getName())) .map(net -> net.getName()) .collect(toList()); if (conflictingNetworks.isEmpty()) { return ValidationResult.VALID; } Collection<String> nameReplacements = ReplacementUtils.replaceWith("ConflictingNetworks", conflictingNetworks); nameReplacements.add(getNetworkNameReplacement()); return new ValidationResult(EngineMessage.NETWORK_NAME_USED_AS_VDSM_INTERFACE_NAME, nameReplacements); }
Source:
<code>public static Properties defaultProperties() { Properties properties = ProfitBricksApiMetadata.defaultProperties(); properties.setProperty(PROPERTY_REGIONS, "de,us"); properties.setProperty(PROPERTY_REGION + ".de.zones", "de/fkb,de/fra"); properties.setProperty(PROPERTY_REGION + ".us.zones", "us/las,us/lasdev"); properties.setProperty(PROPERTY_ZONES, "de/fkb,de/fra,us/las,us/lasdev"); properties.setProperty(PROPERTY_ISO3166_CODES, "DE-BW,DE-HE,US_NV"); properties.setProperty(PROPERTY_REGION + ".de." + ISO3166_CODES, "DE-BW,DE-HE"); properties.setProperty(PROPERTY_REGION + ".us." + ISO3166_CODES, "US-NV"); properties.setProperty(PROPERTY_ZONE + ".de/fkb." + ISO3166_CODES, "DE-BW"); properties.setProperty(PROPERTY_ZONE + ".de/fra." + ISO3166_CODES, "DE-HE"); properties.setProperty(PROPERTY_ZONE + ".us/las." + ISO3166_CODES, "US-NV"); <START> properties.setProperty(PROPERTY_ZONE + ".us/lasdebv." + ISO3166_CODES, "US-NV"); <END> properties.put("jclouds.ssh.max-retries", "7"); properties.put("jclouds.ssh.retry-auth", "true"); long defaultTimeout = 60l * 60l; properties.put(POLL_TIMEOUT, defaultTimeout); properties.put(POLL_PERIOD, 2l); properties.put(POLL_MAX_PERIOD, 2l * 10l); properties.put(PROPERTY_SO_TIMEOUT, 60000 * 5); properties.put(PROPERTY_CONNECTION_TIMEOUT, 60000 * 5); return properties; }</code><technical_language>us/lasdebv is this intentional</technical_language>

Target:
public static Properties defaultProperties() { Properties properties = ProfitBricksApiMetadata.defaultProperties(); properties.setProperty(PROPERTY_REGIONS, "de,us"); properties.setProperty(PROPERTY_REGION + ".de.zones", "de/fkb,de/fra"); properties.setProperty(PROPERTY_REGION + ".us.zones", "us/las,us/lasdev"); properties.setProperty(PROPERTY_ZONES, "de/fkb,de/fra,us/las,us/lasdev"); properties.setProperty(PROPERTY_ISO3166_CODES, "DE-BW,DE-HE,US_NV"); properties.setProperty(PROPERTY_REGION + ".de." + ISO3166_CODES, "DE-BW,DE-HE"); properties.setProperty(PROPERTY_REGION + ".us." + ISO3166_CODES, "US-NV"); properties.setProperty(PROPERTY_ZONE + ".de/fkb." + ISO3166_CODES, "DE-BW"); properties.setProperty(PROPERTY_ZONE + ".de/fra." + ISO3166_CODES, "DE-HE"); properties.setProperty(PROPERTY_ZONE + ".us/las." + ISO3166_CODES, "US-NV"); properties.setProperty(PROPERTY_ZONE + ".us/lasdev." + ISO3166_CODES, "US-NV"); properties.put("jclouds.ssh.max-retries", "7"); properties.put("jclouds.ssh.retry-auth", "true"); long defaultTimeout = 60l * 60l; properties.put(POLL_TIMEOUT, defaultTimeout); properties.put(POLL_PERIOD, 2l); properties.put(POLL_MAX_PERIOD, 2l * 10l); properties.put(PROPERTY_SO_TIMEOUT, 60000 * 5); properties.put(PROPERTY_CONNECTION_TIMEOUT, 60000 * 5); return properties; }
Source:
<code>private synchronized void connectToCassandra() { Cluster.Builder clusterBuilder = Cluster.builder().addContactPoint(config.getHost()) .withPort(config.getPort().intValue()); keyspace = config.getKeyspace(); table = config.getTable(); <START> if (!Strings.isNullOrEmpty(config.getUser()) && !Strings.isNullOrEmpty(config.getPassword())) { <END> cluster = clusterBuilder.withCredentials(config.getUser(), config.getPassword()).build(); } else { cluster = clusterBuilder.build(); } Metadata metadata = cluster.getMetadata(); if (Objects.isNull(metadata.getKeyspace(keyspace))) { LOGGER.info("Keyspace does not exist. Creating Keyspace", keyspace); Map<String, Object> replication = new HashMap<String, Object>(); replication.put("class", "SimpleStrategy"); replication.put("replication_factor", 1); String createKeyspaceStmt = SchemaBuilder.createKeyspace(keyspace).with() .replication(replication).getQueryString(); cluster.connect().execute(createKeyspaceStmt); } session = cluster.connect(keyspace); KeyspaceMetadata ks = metadata.getKeyspace(keyspace); TableMetadata tableMetadata = ks.getTable(table); if (Objects.isNull(tableMetadata)) { LOGGER.info("Table does not exist in Keyspace {}. Creating Table", table, keyspace); String createTableStmt = SchemaBuilder.createTable(table) .addPartitionKey(config.getPartitionKeyColumn(), DataType.varchar()) .addColumn(config.getColumn(), DataType.blob()).getQueryString(); session.execute(createTableStmt); } createInsertStatement(); }</code><technical_language>StringUtils.isNotEmpty() instead</technical_language>

Target:
private synchronized void connectToCassandra() { Cluster.Builder clusterBuilder = Cluster.builder() .addContactPoints(config.getHost().toArray(new String[config.getHost().size()])) .withPort(config.getPort().intValue()); keyspace = config.getKeyspace(); table = config.getTable(); if (StringUtils.isNotEmpty(config.getUser()) && StringUtils.isNotEmpty(config.getPassword())) { cluster = clusterBuilder.withCredentials(config.getUser(), config.getPassword()).build(); } else { cluster = clusterBuilder.build(); } Metadata metadata = cluster.getMetadata(); if (Objects.isNull(metadata.getKeyspace(keyspace))) { LOGGER.info("Keyspace does not exist. Creating Keyspace", keyspace); Map<String, Object> replication = new HashMap<>(); replication.put("class", "SimpleStrategy"); replication.put("replication_factor", 1); String createKeyspaceStmt = SchemaBuilder.createKeyspace(keyspace).with() .replication(replication).getQueryString(); cluster.connect().execute(createKeyspaceStmt); } session = cluster.connect(keyspace); KeyspaceMetadata ks = metadata.getKeyspace(keyspace); TableMetadata tableMetadata = ks.getTable(table); if (Objects.isNull(tableMetadata)) { LOGGER.info("Table does not exist in Keyspace {}. Creating Table", table, keyspace); String createTableStmt = SchemaBuilder.createTable(table) .addPartitionKey(config.getPartitionKeyColumn(), DataType.varchar()) .addColumn(config.getColumn(), DataType.blob()).getQueryString(); session.execute(createTableStmt); } createInsertStatement(); }
Source:
<code>private String getVideoId(Uri playuri) { if (playuri.getHost().endsWith("youtube.com") || playuri.getHost().endsWith("youtu.be") || playuri.getHost().endsWith("vimeo.com")) { final Pattern pattern; if (playuri.getHost().endsWith("vimeo.com")) { pattern = Pattern.compile("^(?:https?:\\/\\/)?(?:www\\.|player\\.)?vimeo\\.com\\/(?:.*\\/)?(\\d+)(?:\\?.*)?$", Pattern.CASE_INSENSITIVE); } else { pattern = Pattern.compile("^(?:https?:\\/\\/)?(?:www\\.|m\\.)?youtu(?:\\.be|be\\.com)\\/watch\\?(?:.*&)?v=([\\w-]+)(?:&.*)?$", Pattern.CASE_INSENSITIVE); <START> } <END> final Matcher matcher = pattern.matcher(playuri.toString()); if (matcher.matches()) { return matcher.group(1); } } return null; }</code><technical_language>This breaks handling of Youtube URIs shared youtube app. URIs of form <LINK_0> test sharing website</technical_language>

Target:
private String getVideoId(Uri playuri) { if (playuri.getHost().endsWith("youtube.com") || playuri.getHost().endsWith("youtu.be") || playuri.getHost().endsWith("vimeo.com")) { final Pattern pattern; if (playuri.getHost().endsWith("vimeo.com")) { pattern = Pattern.compile("^(?:https?:\\/\\/)?(?:www\\.|player\\.)?vimeo\\.com\\/(?:.*\\/)?(\\d+)(?:\\?.*)?$", Pattern.CASE_INSENSITIVE); } else { pattern = Pattern.compile("^(?:https?:\\/\\/)?(?:www\\.|m\\.)?youtu(?:\\.be\\/|be\\.com\\/watch\\?v=)([\\w-]+)(?:[\\?&].*)?$", Pattern.CASE_INSENSITIVE); } final Matcher matcher = pattern.matcher(playuri.toString()); if (matcher.matches()) { return matcher.group(1); } } return null; }
Source:
<code>public void EditorEventTrackingTests_001_verifyEditPageEvent() { CommonUtils.deleteDirectory(PathsContent.harDirPath); try { <START> Thread.sleep(5000); <END> } catch (InterruptedException e) { e.printStackTrace(); } CommonFunctions.logOut(driver); WikiBasePageObject wiki = new WikiBasePageObject(driver, Global.DOMAIN); wiki.openWikiPage(); CommonFunctions.logInCookie(Properties.userNameStaff, Properties.passwordStaff); WikiArticlePageObject article = wiki.openRandomArticle(); WikiArticleEditMode edit = article.edit(); edit.enableWikiaTracker(); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } EventTrackingVerifier verifier = new EventTrackingVerifier(PathsContent.harDirPath); verifier.verifyEvent("editor-ck*view*edit-page"); verifier.verifyEvent("editor-ck*open*gallery-tool"); }</code><technical_language>sleep? why</technical_language>

Target:
public void EditorEventTrackingTests_001_verifyEditPageEvent() { CommonUtils.deleteDirectory(PathsContent.harDirPath); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } CommonFunctions.logOut(driver); WikiBasePageObject wiki = new WikiBasePageObject(driver, Global.DOMAIN); wiki.openWikiPage(); CommonFunctions.logInCookie(Properties.userNameStaff, Properties.passwordStaff); WikiArticlePageObject article = wiki.openRandomArticle(); WikiArticleEditMode edit = article.edit(); edit.enableWikiaTracker(); edit.clickGalleryButton(); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } EventTrackingVerifier verifier = new EventTrackingVerifier(PathsContent.harDirPath); verifier.verifyEvent(EventsContent.editPageEvent); verifier.verifyEvent(EventsContent.openGalleryEvent); }
Source:
<code>protected void startDeltaCounterListener(String strPort, SharedGraphiteHostAnnotator hostAnnotator, SenderTaskFactory senderTaskFactory) { final int port = Integer.parseInt(strPort); registerPrefixFilter(strPort); registerTimestampFilter(strPort); if (httpHealthCheckAllPorts) healthCheckManager.enableHealthcheck(port); new ReportableEntityHandlerFactoryImpl(senderTaskFactory, pushBlockedSamples, <START> flushThreads, () -> validationConfiguration); <END> ReportableEntityHandlerFactory deltaCounterHandlerFactory = new ReportableEntityHandlerFactory() { private Map<HandlerKey, ReportableEntityHandler> handlers = new HashMap<>(); @Override public ReportableEntityHandler getHandler(HandlerKey handlerKey) { return handlers.computeIfAbsent(handlerKey, k -> new DeltaCounterAccumulationHandlerImpl( handlerKey.getHandle(), pushBlockedSamples, senderTaskFactory.createSenderTasks(handlerKey, flushThreads), () -> validationConfiguration, deltaCountersAggregationIntervalSeconds)); } }; WavefrontPortUnificationHandler wavefrontPortUnificationHandler = new WavefrontPortUnificationHandler(strPort, tokenAuthenticator, healthCheckManager, decoderSupplier.get(), deltaCounterHandlerFactory, hostAnnotator, preprocessors.get(strPort)); startAsManagedThread(new TcpIngester(createInitializer(wavefrontPortUnificationHandler, strPort, pushListenerMaxReceivedLength, pushListenerHttpBufferSize, listenerIdleConnectionTimeout), port).withChildChannelOptions(childChannelOptions), "listener-deltaCounter-" + port); }</code><technical_language>This object is safely removed</technical_language>

Target:
protected void startDeltaCounterListener(String strPort, SharedGraphiteHostAnnotator hostAnnotator, SenderTaskFactory senderTaskFactory) { final int port = Integer.parseInt(strPort); registerPrefixFilter(strPort); registerTimestampFilter(strPort); if (httpHealthCheckAllPorts) healthCheckManager.enableHealthcheck(port); ReportableEntityHandlerFactory deltaCounterHandlerFactory = new ReportableEntityHandlerFactory() { private Map<HandlerKey, ReportableEntityHandler> handlers = new HashMap<>(); @Override public ReportableEntityHandler getHandler(HandlerKey handlerKey) { return handlers.computeIfAbsent(handlerKey, k -> new DeltaCounterAccumulationHandlerImpl( handlerKey.getHandle(), pushBlockedSamples, senderTaskFactory.createSenderTasks(handlerKey, flushThreads), () -> validationConfiguration, deltaCountersAggregationIntervalSeconds)); } }; WavefrontPortUnificationHandler wavefrontPortUnificationHandler = new WavefrontPortUnificationHandler(strPort, tokenAuthenticator, healthCheckManager, decoderSupplier.get(), deltaCounterHandlerFactory, hostAnnotator, preprocessors.get(strPort)); startAsManagedThread(new TcpIngester(createInitializer(wavefrontPortUnificationHandler, strPort, pushListenerMaxReceivedLength, pushListenerHttpBufferSize, listenerIdleConnectionTimeout), port).withChildChannelOptions(childChannelOptions), "listener-deltaCounter-" + port); }
Source:
<code>@Override public Single<List<Subtitle>> list(@NonNull final Media media) { return service.login(new String[]{"", "", Locale.getDefault().getLanguage(), USER_AGENT}) .flatMap((Function<LoginResponse, SingleSource<SearchResponse>>) loginResponse -> { List<Object> params = new ArrayList<>(); params.add(loginResponse.getTokem()); params.add(Collections.singletonList(new QuerySearchRequest(media.getTitle()))); return service.search(params); }) .map(SearchResponse::getData) .flatMapObservable(Observable::fromIterable) .groupBy(OpenSubItem::getLanguageCode) .concatMap((Function<GroupedObservable<String, OpenSubItem>, ObservableSource<OpenSubItem>>) observable -> observable.reduce((openSubItem, openSubItem2) -> { int diff = getItemScore(openSubItem2) - getItemScore(openSubItem); <START> if (diff > 0 || diff == 0) { <END> return openSubItem2; } else { return openSubItem; } }).toObservable()) .map(openSubItem -> { Map<String, String> meta = new HashMap<>(1); meta.put(META_DOWNLOAD_LINK, openSubItem.getDownalodLink().replace(".gz", ".srt")); return new Subtitle(openSubItem.getLanguageCode(), openSubItem.getLanguageName(), meta); }) .toSortedList((o1, o2) -> o1.getName().compareTo(o2.getName())); }</code><technical_language>diff >= 0</technical_language>

Target:
@Override public Single<List<Subtitle>> list(@NonNull final Media media) { return service.login(new String[]{"", "", Locale.getDefault().getLanguage(), USER_AGENT}) .flatMap((Function<LoginResponse, SingleSource<SearchResponse>>) loginResponse -> { List<Object> params = new ArrayList<>(); params.add(loginResponse.getTokem()); params.add(Collections.singletonList(new QuerySearchRequest(media.getTitle()))); return service.search(params); }) .map(SearchResponse::getData) .flatMapObservable(Observable::fromIterable) .groupBy(OpenSubItem::getLanguageCode) .concatMap((Function<GroupedObservable<String, OpenSubItem>, ObservableSource<OpenSubItem>>) observable -> observable.reduce((openSubItem, openSubItem2) -> { int diff = getItemScore(openSubItem2) - getItemScore(openSubItem); if (diff >= 0) { return openSubItem2; } else { return openSubItem; } }).toObservable()) .map(openSubItem -> { Map<String, String> meta = new HashMap<>(1); meta.put(META_DOWNLOAD_LINK, openSubItem.getDownalodLink().replace(".gz", ".srt")); return new Subtitle(openSubItem.getLanguageCode(), openSubItem.getLanguageName(), meta); }) .toSortedList((o1, o2) -> o1.getName().compareTo(o2.getName())); }