auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private IAction createSelectionPathCopyAction(final TreeViewer viewer) { IStructuredSelection selection = (IStructuredSelection) viewer .getSelection(); String copyPathActionText = (selection.size() <= 1) ? UIText.StagingView_CopyPath : UIText.StagingView_CopyPaths; IBindingService bindingService = AdapterUtils .adapt(PlatformUI.getWorkbench(), IBindingService.class); if (bindingService != null) { String keyBinding = bindingService.getBestActiveBindingFormattedFor( IWorkbenchCommandConstants.EDIT_COPY); if (keyBinding != null) { copyPathActionText += '\t' + keyBinding; } } IAction copyAction = new Action(copyPathActionText) { @Override public void run() { copyPathOfSelectionToClipboard(viewer); } }; copyAction.setActionDefinitionId(IWorkbenchCommandConstants.EDIT_COPY); return copyAction; }

Target:
private IAction createSelectionPathCopyAction(final TreeViewer viewer) { IStructuredSelection selection = (IStructuredSelection) viewer .getSelection(); String copyPathActionText = (selection.size() <= 1) ? UIText.StagingView_CopyPath : UIText.StagingView_CopyPaths; IAction copyAction = ActionUtils.createGlobalAction(ActionFactory.COPY, () -> copyPathOfSelectionToClipboard(viewer)); copyAction.setText(copyPathActionText); return copyAction; }
Source:
public double getCDF(long x) { final ImmutableList.Builder<Double> builder = ImmutableList.builder(); final long value = x; inOrderTraversal(root, new Callback() { protected double sum = 0.0; public boolean process(Node node) { long lower = Math.max(min, node.getLowerBound()); long upper = Math.min(max, node.getUpperBound()); if(value >= upper) { sum += node.weightedCount; if (node.isLeaf() && value == upper) { builder.add(sum); return false; } return true; } else if(value < lower) { builder.add(sum); return false; } else { double ratio = (value - lower) / (double) (upper - lower); if (node.right == null && node.left != null) { long middle = Math.min(max, node.getMiddle()); ratio = Math.max(0, value - middle) / (double) (upper - middle); sum += node.weightedCount * ratio; } else { sum += node.weightedCount * ratio; } } return true; } }, TraversalOrder.FORWARD); List<Double> tmp = builder.build(); if(tmp.size() == 0) { return 1.0; } else { return tmp.get(0) / weightedCount; } }

Target:
private double getCDF(long x) { double[] totalWeight = {0.0}; inOrderTraversal(root, new Callback() { protected double sum = 0.0; public boolean process(Node node) { long lower = Math.max(min, node.getLowerBound()); long upper = Math.min(max, node.getUpperBound()); if (x >= upper) { sum += node.weightedCount; if (node.isLeaf() && x == upper) { totalWeight[0] = sum; return false; } totalWeight[0] = sum; return true; } else if (x < lower) { totalWeight[0] = sum; return false; } else { double ratio = (x - lower) / (double) (upper - lower); if (max <= upper && node.right == null && node.left != null) { long middle = Math.min(max, node.getMiddle()); ratio = Math.min(middle - lower, x - lower) / (double) Math.max(1, middle - lower); } else if (max >= lower && node.left == null && node.right != null) { long middle = Math.max(min, node.getMiddle()); ratio = Math.max(0, x - middle) / (double) Math.max(1, upper - middle); } sum += node.weightedCount * ratio; } totalWeight[0] = sum; return true; } }, TraversalOrder.FORWARD); return totalWeight[0] / weightedCount; }
Source:
public void test_first_3_bytes() throws IOException { byte[] data = new byte[1024 * 1024]; random.nextBytes(data); long[] coords = new long[]{0, 1, 1, 2, 2, 3}; CoordSpanInputSteam csis = new CoordSpanInputSteam(new ByteArraySeekableStream(data), coords); Assert.assertEquals(csis.read(), 0xFF & data[0]); Assert.assertEquals(csis.read(), 0xFF & data[1]); Assert.assertEquals(csis.read(), 0xFF & data[2]); Assert.assertEquals(csis.read(), -1); }

Target:
public void test_first_3_bytes() throws IOException { byte[] data = new byte[1024 * 1024]; new Random(TestUtil.RANDOM_SEED).nextBytes(data); long[] coords = new long[]{0, 1, 1, 2, 2, 3}; CoordSpanInputSteam csis = new CoordSpanInputSteam(new ByteArraySeekableStream(data), coords); Assert.assertEquals(csis.read(), 0xFF & data[0]); Assert.assertEquals(csis.read(), 0xFF & data[1]); Assert.assertEquals(csis.read(), 0xFF & data[2]); Assert.assertEquals(csis.read(), -1); }
Source:
public AuthenticatorMapper get() { Map<String, Authenticator> authenticatorMap = Maps.newLinkedHashMap(); List<String> authenticators = authConfig.getAuthenticatorChain(); if (authenticators == null || authenticators.isEmpty()) { Map<String, Authenticator> defaultMap = Maps.newHashMap(); defaultMap.put("allowAll", new AllowAllAuthenticator()); return new AuthenticatorMapper(defaultMap, "allowAll"); } for (String authenticatorName : authenticators) { final String authenticatorPropertyBase = StringUtils.format(AUTHENTICATOR_PROPERTIES_FORMAT_STRING, authenticatorName); final JsonConfigProvider<Authenticator> authenticatorProvider = new JsonConfigProvider<>( authenticatorPropertyBase, Authenticator.class ); authenticatorProvider.inject(props, configurator); Supplier<Authenticator> authenticatorSupplier = authenticatorProvider.get(); if (authenticatorSupplier == null) { throw new ISE("Could not create authenticator with name: %s", authenticatorName); } Authenticator authenticator = authenticatorSupplier.get(); authenticatorMap.put(authenticatorName, authenticator); } return new AuthenticatorMapper(authenticatorMap, authConfig.getEscalatedAuthenticator()); }

Target:
public AuthenticatorMapper get() { Map<String, Authenticator> authenticatorMap = Maps.newLinkedHashMap(); List<String> authenticators = authConfig.getAuthenticatorChain(); if (authenticators == null) { authenticatorMap.put("allowAll", new AllowAllAuthenticator()); return new AuthenticatorMapper(authenticatorMap, "allowAll"); } if (authenticators.isEmpty()) { throw new IAE("Must have at least one Authenticator configured."); } for (String authenticatorName : authenticators) { final String authenticatorPropertyBase = StringUtils.format(AUTHENTICATOR_PROPERTIES_FORMAT_STRING, authenticatorName); final JsonConfigProvider<Authenticator> authenticatorProvider = new JsonConfigProvider<>( authenticatorPropertyBase, Authenticator.class ); authenticatorProvider.inject(props, configurator); Supplier<Authenticator> authenticatorSupplier = authenticatorProvider.get(); if (authenticatorSupplier == null) { throw new ISE("Could not create authenticator with name: %s", authenticatorName); } Authenticator authenticator = authenticatorSupplier.get(); authenticatorMap.put(authenticatorName, authenticator); } return new AuthenticatorMapper(authenticatorMap, authConfig.getEscalatedAuthenticator()); }
Source:
private void verifyDistributedQueue() { Assert.assertEquals(true, distributedQueue.size() == DATA_COUNT); Iterator<?> it = distributedQueue.iterator(); int index = 0; while (it.hasNext()) { Assert.assertEquals(index, it.next()); index++; } }

Target:
private void verifyDistributedQueue() { Assert.assertEquals(true, distributedQueue.size() == DATA_COUNT); int index = 0; for (Object o : distributedQueue) { Assert.assertEquals(index++, o); } }
Source:
public void test_update_by_id_where_no_row_is_matching() throws Exception { execute("create table test (id int primary key, message string) clustered into 2 shards"); execute("insert into test values(1, 'msg');"); assertEquals(1, response.rowCount()); refresh(); execute("update test set message='updated' where id = 99 returning id"); assertThat(response.cols()[0], is("id")); assertThat(response.rowCount(), is(0L)); refresh(); }

Target:
public void test_update_by_id_where_no_row_is_matching() throws Exception { execute("create table test (id int primary key, message string) clustered into 2 shards"); execute("insert into test values(1, 'msg');"); assertEquals(1, response.rowCount()); refresh(); execute("update test set message='updated' where id = 99 returning id"); assertThat(response.cols()[0], is("id")); assertThat(response.rowCount(), is(0L)); }
Source:
public ImmutableValue<Boolean> charged() { return ImmutableSpongeValue.cachedOf(Keys.CREEPER_CHARGED, false, this.value); }

Target:
public ImmutableValue<Boolean> charged() { return cachedValue; }
Source:
public void unscheduleJob(SchedulableJob job) { assertArgumentNotNull(job); JobId jobId=null; if (job instanceof CronSchedulableJob) { jobId=new CronJobId(job.getMotechEvent()); } else if (job instanceof RepeatingSchedulableJob) { jobId=new RepeatingJobId(job.getMotechEvent()); } else if (job instanceof RepeatingPeriodSchedulableJob) { jobId=new RepeatingPeriodJobId(job.getMotechEvent()); } else if (job instanceof RunOnceSchedulableJob) { jobId=new RunOnceJobId(job.getMotechEvent()); } else if (job instanceof DayOfWeekSchedulableJob){ jobId=new DayOfWeekJobId(job.getMotechEvent()); } unscheduleJob(jobId); }

Target:
public void unscheduleJob(SchedulableJob job) { assertArgumentNotNull(job); JobId jobId = null; if (job instanceof CronSchedulableJob) { jobId = new CronJobId(job.getMotechEvent()); } else if (job instanceof RepeatingSchedulableJob) { jobId = new RepeatingJobId(job.getMotechEvent()); } else if (job instanceof RepeatingPeriodSchedulableJob) { jobId = new RepeatingPeriodJobId(job.getMotechEvent()); } else if (job instanceof RunOnceSchedulableJob) { jobId = new RunOnceJobId(job.getMotechEvent()); } else if (job instanceof DayOfWeekSchedulableJob) { jobId = new CronJobId(job.getMotechEvent()); } unscheduleJob(jobId); }
Source:
public <ReqT, RespT> ClientCall<ReqT, RespT> newCall( MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions) { Preconditions.checkState(!shutdown, "Cannot perform operations on a closed connection"); int currentRequestNum = requestCount.getAndIncrement(); ImmutableList<ChannelAndMetrics> channelsList = channels.get(); int index = Math.abs(currentRequestNum % channelsList.size()); ChannelAndMetrics channelAndMetrics = channelsList.get(index); final Context timeContext = channelAndMetrics.timer.time(); ClientCall<ReqT, RespT> delegate = channelAndMetrics.channel.newCall(methodDescriptor, callOptions); return new CheckedForwardingClientCall<ReqT, RespT>(delegate) { @Override protected void checkedStart(ClientCall.Listener<RespT> responseListener, Metadata headers) throws Exception { for (HeaderInterceptor interceptor : headerInterceptors) { interceptor.updateHeaders(headers); } ClientCall.Listener<RespT> wrappedListener = wrap(responseListener, timeContext); delegate().start(wrappedListener, headers); } }; }

Target:
public <ReqT, RespT> ClientCall<ReqT, RespT> newCall( MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions) { Preconditions.checkState(!shutdown, "Cannot perform operations on a closed connection"); return getNextChannel().newCall(methodDescriptor, callOptions); }
Source:
public static List<String> validateClass(Class<? extends Messages> classUnderTest) throws URISyntaxException, IOException { List<String> errors = new ArrayList<>(); if (classUnderTest.isInterface()) { File messagesDir = new File(classUnderTest.getResource(".") .toURI().toASCIIString().replaceAll("file:", "")); List<Method> messagesMethods = Arrays.asList(classUnderTest.getMethods()); Properties defaultProperties = loadDefaultProperties(classUnderTest); for (Method method : messagesMethods) { checkPlaceHolders(method, defaultProperties, classUnderTest.getSimpleName() + ".properties", errors); } File[] localePropertiesFiles = getMessagesLocalePropertiesFiles(messagesDir, classUnderTest.getSimpleName()); if (localePropertiesFiles != null) { for (File localeFile : localePropertiesFiles) { Properties localeProperties = loadProperties(localeFile); String localeFileName = localeFile.getName(); for (Method method : messagesMethods) { checkForMissingDefault(method, defaultProperties, localeProperties, localeFileName, errors); checkPlaceHolders(method, localeProperties, localeFileName, errors); } } } if (defaultProperties.size() == 0 && localePropertiesFiles == null) { errors.add("Class under test does not have a default or any locale specific properties files: " + classUnderTest.getName()); } } else { errors.add("Class under test is not an interface: " + classUnderTest.getName()); } return errors; }

Target:
public static List<String> validateClass(Class<? extends Messages> classUnderTest) throws URISyntaxException, IOException { List<String> errors = new ArrayList<>(); System.out.println("working on class: " + classUnderTest); if (classUnderTest.isInterface()) { File messagesDir = new File(classUnderTest.getResource(".") .toURI().toASCIIString().replaceAll("file:", "")); List<Method> messagesMethods = Arrays.asList(classUnderTest.getMethods()); Properties defaultProperties = loadDefaultProperties(classUnderTest); for (Method method : messagesMethods) { checkPlaceHolders(method, defaultProperties, classUnderTest.getSimpleName() + ".properties", errors); } File[] localePropertiesFiles = getMessagesLocalePropertiesFiles(messagesDir, classUnderTest.getSimpleName()); if (localePropertiesFiles != null) { for (File localeFile : localePropertiesFiles) { Properties localeProperties = loadProperties(localeFile); String localeFileName = localeFile.getName(); for (Method method : messagesMethods) { checkForMissingDefault(method, defaultProperties, localeProperties, localeFileName, errors); checkPlaceHolders(method, localeProperties, localeFileName, errors); } } } if (defaultProperties.size() == 0 && localePropertiesFiles == null) { errors.add("Class under test does not have a default or any locale specific properties files: " + classUnderTest.getName()); } } else { errors.add("Class under test is not an interface: " + classUnderTest.getName()); } return errors; }
Source:
public RexNode field(RexNode e, String name) { if (!e.getType().isStruct()) { throw new IllegalArgumentException("Requested field " + name + " in non-struct expression " + e.toString() + " (type: " + e.getType() + ")"); } return getRexBuilder().makeFieldAccess(e, name, false); }

Target:
public RexNode field(RexNode e, String name) { return getRexBuilder().makeFieldAccess(e, name, false); }
Source:
private static Object getFormulaCellValueAsObject(final Workbook workbook, final Cell cell) { try { return getDoubleAsNumber(cell.getNumericCellValue()); } catch (final Exception e) { if (logger.isInfoEnabled()) { logger.info("Failed to fetch cached/precalculated formula value of cell: " + cell, e); } } try { if (logger.isInfoEnabled()) { logger .info("cell is a formula. Attempting to evaluate: {}", getCellCoordinates(cell), cell .getCellFormula()); } final FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); final Cell evaluatedCell = evaluator.evaluateInCell(cell); return getCellValueAsObject(workbook, evaluatedCell); } catch (final FormulaParseException e) { logger.error("Parse exception occurred while evaluating cell formula: " + cell, e); } catch (final IllegalArgumentException e) { logger.error("Illegal formula argument occurred while evaluating cell formula: " + cell, e); } catch (final RuntimeException e) { logger.error("Unexpected exception occurred while evaluating cell formula: " + cell, e); } return cell.getCellFormula(); }

Target:
private static Object getFormulaCellValueAsObject(final Workbook workbook, final Cell cell) { try { return getDoubleAsNumber(cell.getNumericCellValue()); } catch (final Exception e) { if (logger.isInfoEnabled()) { logger.info("Failed to fetch cached/precalculated formula value of cell: " + cell, e); } } final Cell evaluatedCell = getEvaluatedCell(workbook, cell); if (evaluatedCell != null) { return getCellValueAsObject(workbook, evaluatedCell); } else { return cell.getCellFormula(); } }
Source:
SmtpEmailSender(@GerritServerConfig final Config cfg) { enabled = cfg.getBoolean("sendemail", null, "enable", true); connectTimeout = cfg.getInt("sendemail", "connectTimeout", DEFAULT_CONNECT_TIMEOUT); smtpHost = cfg.getString("sendemail", null, "smtpserver"); if (smtpHost == null) { smtpHost = "127.0.0.1"; } smtpEncryption = ConfigUtil.getEnum(cfg, "sendemail", null, "smtpencryption", Encryption.NONE); sslVerify = cfg.getBoolean("sendemail", null, "sslverify", true); final int defaultPort; switch (smtpEncryption) { case SSL: defaultPort = 465; break; case NONE: case TLS: default: defaultPort = 25; break; } smtpPort = cfg.getInt("sendemail", null, "smtpserverport", defaultPort); smtpUser = cfg.getString("sendemail", null, "smtpuser"); smtpPass = cfg.getString("sendemail", null, "smtppass"); Set<String> rcpt = new HashSet<String>(); for (String addr : cfg.getStringList("sendemail", null, "allowrcpt")) { rcpt.add(addr); } allowrcpt = Collections.unmodifiableSet(rcpt); importance = cfg.getString("sendemail", null, "importance"); expiryDays = cfg.getInt("sendemail", null, "expiryDays", 0); }

Target:
SmtpEmailSender(@GerritServerConfig final Config cfg) { enabled = cfg.getBoolean("sendemail", null, "enable", true); connectTimeout = Ints.checkedCast(ConfigUtil.getTimeUnit(cfg, "sendemail", null, "connectTimeout", DEFAULT_CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)); smtpHost = cfg.getString("sendemail", null, "smtpserver"); if (smtpHost == null) { smtpHost = "127.0.0.1"; } smtpEncryption = ConfigUtil.getEnum(cfg, "sendemail", null, "smtpencryption", Encryption.NONE); sslVerify = cfg.getBoolean("sendemail", null, "sslverify", true); final int defaultPort; switch (smtpEncryption) { case SSL: defaultPort = 465; break; case NONE: case TLS: default: defaultPort = 25; break; } smtpPort = cfg.getInt("sendemail", null, "smtpserverport", defaultPort); smtpUser = cfg.getString("sendemail", null, "smtpuser"); smtpPass = cfg.getString("sendemail", null, "smtppass"); Set<String> rcpt = new HashSet<String>(); for (String addr : cfg.getStringList("sendemail", null, "allowrcpt")) { rcpt.add(addr); } allowrcpt = Collections.unmodifiableSet(rcpt); importance = cfg.getString("sendemail", null, "importance"); expiryDays = cfg.getInt("sendemail", null, "expiryDays", 0); }
Source:
public static MongoCredential credentialFromJson(ObjectNode node) { String userName = null; String password = null; String source = null; JsonNode xnode = node.get("mechanism"); if (xnode == null) { throw new IllegalArgumentException("mechanism is required in credentials"); } String mech = xnode.asText(); xnode = node.get("userName"); if (xnode != null) { userName = xnode.asText(); } xnode = node.get("password"); if (xnode != null) { password = xnode.asText(); } xnode = node.get("source"); if (xnode != null) { source = xnode.asText(); } MongoCredential cr = null; if (null != mech) { switch (mech) { case "GSSAPI_MECHANISM": cr = MongoCredential.createGSSAPICredential(userName); break; case "MONGODB_CR_MECHANISM": cr = MongoCredential.createMongoCRCredential(userName, source, password == null ? null : password.toCharArray()); break; case "MONGODB_X509_MECHANISM": cr = MongoCredential.createMongoX509Credential(userName); break; case "PLAIN_MECHANISM": cr = MongoCredential.createPlainCredential(userName, source, password == null ? null : password.toCharArray()); break; case "SCRAM_SHA_1_MECHANISM": cr = MongoCredential.createScramSha1Credential(userName,source, password==null?null:password.toCharArray()); break; default: throw new IllegalArgumentException("invalid mechanism:" + mech + ", must be one of " + "GSSAPI_MECHANISM, MONGODB_CR_MECHANISM, " + "MONGODB_X5090_MECHANISM, or PLAIN_MECHANISM"); } } return cr; }

Target:
public static MongoCredential credentialFromJson(ObjectNode node) { String userName = null; String password = null; String source = null; JsonNode xnode = node.get("mechanism"); if (xnode == null) { throw new IllegalArgumentException("mechanism is required in credentials"); } String mech = xnode.asText(); xnode = node.get("userName"); if (xnode != null) { userName = xnode.asText(); } xnode = node.get("password"); if (xnode != null) { password = xnode.asText(); } xnode = node.get("source"); if (xnode != null) { source = xnode.asText(); } MongoCredential cr = null; if (null != mech) { switch (mech) { case "GSSAPI_MECHANISM": cr = MongoCredential.createGSSAPICredential(userName); break; case "MONGODB_CR_MECHANISM": cr = MongoCredential.createMongoCRCredential(userName, source, password == null ? null : password.toCharArray()); break; case "MONGODB_X509_MECHANISM": cr = MongoCredential.createMongoX509Credential(userName); break; case "PLAIN_MECHANISM": cr = MongoCredential.createPlainCredential(userName, source, password == null ? null : password.toCharArray()); break; case "SCRAM_SHA_1_MECHANISM": cr = MongoCredential.createScramSha1Credential(userName,source, password==null?null:password.toCharArray()); break; default: throw new IllegalArgumentException("invalid mechanism:" + mech + ", must be one of " + "GSSAPI_MECHANISM, MONGODB_CR_MECHANISM, " + "MONGODB_X5090_MECHANISM, SCRAM_SHA_1_MECHANISM or PLAIN_MECHANISM"); } } return cr; }
Source:
ValueGroup valueType() { return NUMBER; }

Target:
ValueGroup valueType() { return valueType; }
Source:
public void usernamePassword_nullPassword() { SyncCredentials creds = SyncCredentials.usernamePassword("foo", null, true); Map<String, Object> userInfo = creds.getUserInfo(); assertEquals(null, userInfo.get("password")); }

Target:
public void usernamePassword_nullPassword() { SyncCredentials creds = SyncCredentials.usernamePassword("foo", null, true); assertUsernamePassword(creds, "foo", null, true); }
Source:
public void process(String tuple) { JSONObject jo = null; try { jo = new JSONObject(tuple); if (jo.getString(Result.FIELD_TYPE).equals(DataResultDimensional.TYPE)) { String id = jo.getString(Result.FIELD_ID); JSONArray dataArray = jo.getJSONArray(Result.FIELD_DATA); boolean isEmpty = ((dataArray == null) || (dataArray.length() == 0)); cacheTuple(id, tuple, isEmpty); } else { logger.info("Invalid type: {}, by pass.", jo.getString(Result.FIELD_TYPE)); output.emit(tuple); } } catch (JSONException ex) { logger.warn("Invalid json. {}", ex.getMessage()); throw new RuntimeException(ex); } }

Target:
public void process(String tuple) { JSONObject jo = null; try { jo = new JSONObject(tuple); if (jo.getString(Result.FIELD_TYPE).equals(DataResultDimensional.TYPE)) { String id = jo.getString(Result.FIELD_ID); if (handledIds.contains(id)) return; JSONArray dataArray = jo.getJSONArray(Result.FIELD_DATA); boolean isEmpty = ((dataArray == null) || (dataArray.length() == 0)); if (!isEmpty) { output.emit(tuple); handledIds.add(id); if(idToEmptyTupleMap.containsKey(id)) { idToEmptyTupleMap.remove(id); } } else { Set<String> emptyTupleIds = idToEmptyTupleMap.keySet(); if (!emptyTupleIds.contains(id)) { idToEmptyTupleMap.put(id, tuple); } } } else { logger.debug("Invalid type: {}, by pass.", jo.getString(Result.FIELD_TYPE)); output.emit(tuple); } } catch (JSONException ex) { throw new RuntimeException(ex); } }
Source:
protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException, MaxMoneyException { if(sign.getLine(3).startsWith(tl("signFormatWorth")) && updateFromWorth(sign, player, ess, ess.getSettings().getEcoBuyMultiplier())) { return false; } Trade items = getTrade(sign, 1, 2, player, ess); Trade charge = getTrade(sign, 3, ess); if (ess.getSettings().isAllowBulkBuySell() && player.getBase().isSneaking()) { ItemStack heldItem = player.getItemInHand(); if (items.getItemStack().isSimilar(heldItem)) { int initialItemAmount = items.getItemStack().getAmount(); int newItemAmount = heldItem.getAmount(); ItemStack item = items.getItemStack(); item.setAmount(newItemAmount); items = new Trade(item, ess); BigDecimal chargeAmount = charge.getMoney(); BigDecimal pricePerSingleItem = chargeAmount.divide(new BigDecimal(initialItemAmount)); pricePerSingleItem = pricePerSingleItem.multiply(new BigDecimal(newItemAmount)); charge = new Trade(pricePerSingleItem, ess); } } charge.isAffordableFor(player); if (!items.pay(player)) { throw new ChargeException("Inventory full"); } charge.charge(player); Trade.log("Sign", "Buy", "Interact", username, charge, username, items, sign.getBlock().getLocation(), ess); return true; }

Target:
protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException, MaxMoneyException { if(sign.getLine(3).startsWith(tl("signFormatWorth")) && updateFromWorthMultiplied(sign, player, ess)) { return false; } Trade items = getTrade(sign, 1, 2, player, ess); Trade charge = getTrade(sign, 3, ess); if (ess.getSettings().isAllowBulkBuySell() && player.getBase().isSneaking()) { ItemStack heldItem = player.getItemInHand(); if (items.getItemStack().isSimilar(heldItem)) { int initialItemAmount = items.getItemStack().getAmount(); int newItemAmount = heldItem.getAmount(); ItemStack item = items.getItemStack(); item.setAmount(newItemAmount); items = new Trade(item, ess); BigDecimal chargeAmount = charge.getMoney(); BigDecimal pricePerSingleItem = chargeAmount.divide(new BigDecimal(initialItemAmount)); pricePerSingleItem = pricePerSingleItem.multiply(new BigDecimal(newItemAmount)); charge = new Trade(pricePerSingleItem, ess); } } charge.isAffordableFor(player); if (!items.pay(player)) { throw new ChargeException("Inventory full"); } charge.charge(player); Trade.log("Sign", "Buy", "Interact", username, charge, username, items, sign.getBlock().getLocation(), ess); return true; }
Source:
private void search(HybridFile directory, final SearchFilter filter) { if (directory.isDirectory(activity.get())) { directory.forEachChildrenFile( activity.get(), rootMode, file -> { if (!isCancelled() && !(file.getName().startsWith("."))) { if (filter.searchFilter(file.getName(activity.get()))) { publishProgress(file); } if (file.isDirectory() && !isCancelled()) { search(file, filter); } } }); } else { Log.d(TAG, "Cannot search " + directory.getPath() + ": Permission Denied"); } }

Target:
private void search(HybridFile directory, final SearchFilter filter) { if (directory.isDirectory(activity.get())) { directory.forEachChildrenFile( activity.get(), rootMode, file -> { boolean showHiddenFiles = PreferenceManager.getDefaultSharedPreferences(activity.get()) .getBoolean(PREFERENCE_SHOW_HIDDENFILES, false); if ((!isCancelled() && (showHiddenFiles || !file.isHidden()))) { if (filter.searchFilter(file.getName(activity.get()))) { publishProgress(file); } if (file.isDirectory() && !isCancelled()) { search(file, filter); } } }); } else { Log.d(TAG, "Cannot search " + directory.getPath() + ": Permission Denied"); } }
Source:
private void commonStatusChangeHandler(BindingValidationStatus<?> event, AbstractTextField<?> field) { Label statusLabel = (Label) field.getData(); setVisible(statusLabel, !event.getStatus().equals(Status.UNRESOLVED)); switch (event.getStatus()) { case OK: statusLabel.setText(" "); statusLabel.setClassName("ok"); statusLabel.removeClassName("error"); ((HasStyle) statusLabel.getParent().get()).setClassName(VALID); break; case ERROR: statusLabel.removeClassName("ok"); statusLabel.setClassName("error"); statusLabel.setText(event.getMessage().orElse("Unknown error")); ((HasStyle) statusLabel.getParent().get()).removeClassName(VALID); default: break; } }

Target:
private void commonStatusChangeHandler(BindingValidationStatus<?> event, AbstractTextField<?> field) { Label statusLabel = (Label) field.getData(); setVisible(statusLabel, !event.getStatus().equals(Status.UNRESOLVED)); switch (event.getStatus()) { case OK: statusLabel.setText(""); statusLabel.setClassName(OK); statusLabel.removeClassName(ERROR); ((HasStyle) statusLabel.getParent().get()).setClassName(VALID); break; case ERROR: statusLabel.removeClassName(OK); statusLabel.setClassName(ERROR); statusLabel.setText(event.getMessage().orElse("Unknown error")); ((HasStyle) statusLabel.getParent().get()).removeClassName(VALID); default: break; } }
Source:
public boolean getBoolean(int columnIndex) throws SQLException { checkResultSet(columnIndex); if (wasNullFlag) { return false; } int col = columnIndex - 1; if (Oid.BOOL == fields[col].getOID()) { return 't' == (char) (this_row[col][0] & 0xFF); } if (isBinary(columnIndex)) { return BooleanTypeUtil.castToBoolean(readDoubleValue(this_row[col], fields[col].getOID(), "boolean")); } return BooleanTypeUtil.castToBoolean(getString(columnIndex)); }

Target:
public boolean getBoolean(int columnIndex) throws SQLException { checkResultSet(columnIndex); if (wasNullFlag) { return false; } int col = columnIndex - 1; if (Oid.BOOL == fields[col].getOID()) { final byte[] v = this_row[col]; return (1 == v.length) && (116 == v[0]); } if (isBinary(columnIndex)) { return BooleanTypeUtil.castToBoolean(readDoubleValue(this_row[col], fields[col].getOID(), "boolean")); } return BooleanTypeUtil.castToBoolean(getString(columnIndex)); }
Source:
public Seq<CharSeq> split(String regex, int limit) { final String[] javaStrings = back.split(regex, limit); final IndexedSeq<CharSeq> result = Vector.empty(); for (int i = 0; i < javaStrings.length; i++) { result.append(CharSeq.of(javaStrings[i])); } return result; }

Target:
public Seq<CharSeq> split(String regex, int limit) { final String[] javaStrings = back.split(regex, limit); final CharSeq[] strings = new CharSeq[javaStrings.length]; for (int i = 0; i < strings.length; i++) { strings[i] = of(javaStrings[i]); } return Vector.of(strings); }
Source:
public PTableStatsImpl() { regionGuidePosts = new HashMap<String, byte[][]>(); }

Target:
public PTableStatsImpl() { }
Source:
private void encode() { List<byte[]> dataListRLP = new ArrayList<>(); for (Value value: dataList) { if (value == null) continue; dataListRLP.add(value.asBytes()); } byte[][] encodedElementArray = dataListRLP.toArray(new byte[dataListRLP.size()][]); this.encoded = RLP.encodeList(encodedElementArray); }

Target:
private void encode() { List<byte[]> dataListRLP = new ArrayList<>(); for (Value value: dataList) { if (value == null) continue; dataListRLP.add(RLP.encodeElement(value.asBytes())); } byte[][] encodedElementArray = dataListRLP.toArray(new byte[dataListRLP.size()][]); this.encoded = RLP.encodeList(encodedElementArray); }
Source:
public final void drain() { long n; boolean term; synchronized (this) { if (emitting) { return; } emitting = true; term = terminated; } n = requestedCount.get(); boolean skipFinal = false; try { BackpressureQueueCallback a = actual; while (true) { int emitted = 0; while (n > 0 || term) { Object o; if (term) { o = a.peek(); if (o == null) { skipFinal = true; Throwable e = exception; a.complete(e); return; } if (n == 0) { break; } } o = a.poll(); if (o == null) { break; } else { if (a.accept(o)) { skipFinal = true; return; } n--; emitted++; } } synchronized (this) { term = terminated; boolean more = a.peek() != null; if (requestedCount.get() == Long.MAX_VALUE) { if (!more && !term) { skipFinal = true; emitting = false; return; } n = Long.MAX_VALUE; } else { n = requestedCount.addAndGet(-emitted); if ((n == 0 || !more) && (!term || more)) { skipFinal = true; emitting = false; return; } } } } } finally { if (!skipFinal) { synchronized (this) { emitting = false; } } } }

Target:
public final void drain() { long n; boolean term; synchronized (this) { if (emitting) { return; } emitting = true; term = terminated; } n = get(); boolean skipFinal = false; try { BackpressureQueueCallback a = actual; while (true) { int emitted = 0; while (n > 0 || term) { Object o; if (term) { o = a.peek(); if (o == null) { skipFinal = true; Throwable e = exception; a.complete(e); return; } if (n == 0) { break; } } o = a.poll(); if (o == null) { break; } else { if (a.accept(o)) { skipFinal = true; return; } n--; emitted++; } } synchronized (this) { term = terminated; boolean more = a.peek() != null; if (get() == Long.MAX_VALUE) { if (!more && !term) { skipFinal = true; emitting = false; return; } n = Long.MAX_VALUE; } else { n = addAndGet(-emitted); if ((n == 0 || !more) && (!term || more)) { skipFinal = true; emitting = false; return; } } } } } finally { if (!skipFinal) { synchronized (this) { emitting = false; } } } }
Source:
private void addSupportForCustomServiceOffering(long vmId, long serviceOfferingId, long vmSnapshotId) { ServiceOfferingVO serviceOfferingVO = _serviceOfferingDao.findById(serviceOfferingId); if (serviceOfferingVO.isDynamic()) { List<UserVmDetailVO> vmDetails = _userVmDetailsDao.listDetails(vmId); for (UserVmDetailVO detail : vmDetails) { if(detail.getName().equalsIgnoreCase("cpuNumber") || detail.getName().equalsIgnoreCase("cpuSpeed") || detail.getName().equalsIgnoreCase("memory")) { _vmSnapshotDetailsDao.addDetail(vmSnapshotId, detail.getName(), detail.getValue(), true); } } } }

Target:
protected void addSupportForCustomServiceOffering(long vmId, long serviceOfferingId, long vmSnapshotId) { ServiceOfferingVO serviceOfferingVO = _serviceOfferingDao.findById(serviceOfferingId); if (serviceOfferingVO.isDynamic()) { List<UserVmDetailVO> vmDetails = _userVmDetailsDao.listDetails(vmId); List<VMSnapshotDetailsVO> vmSnapshotDetails = new ArrayList<VMSnapshotDetailsVO>(); for (UserVmDetailVO detail : vmDetails) { if(detail.getName().equalsIgnoreCase("cpuNumber") || detail.getName().equalsIgnoreCase("cpuSpeed") || detail.getName().equalsIgnoreCase("memory")) { vmSnapshotDetails.add(new VMSnapshotDetailsVO(vmSnapshotId, detail.getName(), detail.getValue(), detail.isDisplay())); } } _vmSnapshotDetailsDao.saveDetails(vmSnapshotDetails); } }
Source:
private void initializeOutput(FetchRequest req) { Set<String> caps = req.getClientCapabilities(); boolean sideband = caps.contains(OPTION_SIDE_BAND) || caps.contains(OPTION_SIDE_BAND_64K); if (sideband) { errOut = new SideBandErrorWriter(); int bufsz = SideBandOutputStream.SMALL_BUF; if (req.getClientCapabilities().contains(OPTION_SIDE_BAND_64K)) { bufsz = SideBandOutputStream.MAX_BUF; } packOut = new SideBandOutputStream(SideBandOutputStream.CH_DATA, bufsz, rawOut); if (!req.getClientCapabilities().contains(OPTION_NO_PROGRESS)) { msgOut = new SideBandOutputStream( SideBandOutputStream.CH_PROGRESS, bufsz, rawOut); progressMonitor = new SideBandProgressMonitor(msgOut); } } else { packOut = rawOut; } }

Target:
private void initializeOutput(FetchRequest req) { boolean sideband = isSideband(req); if (sideband) { errOut = new SideBandErrorWriter(); int bufsz = SideBandOutputStream.SMALL_BUF; if (req.getClientCapabilities().contains(OPTION_SIDE_BAND_64K)) { bufsz = SideBandOutputStream.MAX_BUF; } packOut = new SideBandOutputStream(SideBandOutputStream.CH_DATA, bufsz, rawOut); if (!req.getClientCapabilities().contains(OPTION_NO_PROGRESS)) { msgOut = new SideBandOutputStream( SideBandOutputStream.CH_PROGRESS, bufsz, rawOut); monitor = new SideBandProgressMonitor(msgOut); } } else { packOut = rawOut; } }
Source:
public static EObject getParentOf(EObject eObject) { if (eObject == null) { return null; } CDOObject cdoObject = CDOUtil.getCDOObject(eObject); if (cdoObject.cdoView() == null || cdoObject.cdoView().isClosed()) { return null; } EObject container = eObject.eContainer(); if (container != null) { return container; } if (eObject instanceof CDOResource) { CDOResource resource = (CDOResource)eObject; if (resource.isRoot()) { return null; } } Resource resource = eObject.eResource(); if (resource instanceof CDOResource) { return (CDOResource)resource; } if (eObject instanceof CDOResourceNode) { CDOView view = ((CDOResourceNode)eObject).cdoView(); if (view != null) { return view.getRootResource(); } } return null; }

Target:
public static EObject getParentOf(EObject eObject) { if (eObject == null) { return null; } CDOObject cdoObject = CDOUtil.getCDOObject(eObject, false); if (cdoObject != null && FSMUtil.isInvalid(cdoObject)) { return null; } EObject container = eObject.eContainer(); if (container != null) { return container; } if (eObject instanceof CDOResource) { CDOResource resource = (CDOResource)eObject; if (resource.isRoot()) { return null; } } Resource resource = eObject.eResource(); if (resource instanceof CDOResource) { return (CDOResource)resource; } if (eObject instanceof CDOResourceNode) { CDOView view = ((CDOResourceNode)eObject).cdoView(); if (view != null) { return view.getRootResource(); } } return null; }
Source:
public void testLoadPropertiesWithEmptyPropertiesFile() throws Exception { File emptyFile = temporaryFolder.newFile("tempFile"); Properties testProperties = PROPERTIES_LOADER.loadProperties(emptyFile.getPath(), null); Properties emptyProperties = new Properties(); Assert.assertEquals("Returns empty properties", emptyProperties, testProperties); }

Target:
public void testLoadPropertiesWithEmptyPropertiesFile() throws Exception { File emptyFile = temporaryFolder.newFile("tempFile"); Properties testProperties = PROPERTIES_LOADER.loadProperties(emptyFile.getPath(), null); assertThat(testProperties.entrySet(), is(empty())); }
Source:
private void runCallback() { try { callback.runWithRetry(); } catch (Exception e) { log.error("Callback failed and was not able to perform its cleanup task. " + "Closing the TransactionManager.", e); callbackException = Optional.of(e); close(); return; } callbackDone = true; }

Target:
private void runCallback() { try { callback.runWithRetry(txManager); checkAndSetStatus(ImmutableSet.of(State.INITIALIZING), State.READY); } catch (Throwable e) { log.error("Callback failed and was not able to perform its cleanup task. " + "Closing the TransactionManager.", e); callbackThrowable = e; closeInternal(State.CLOSED_BY_CALLBACK_FAILURE); } }
Source:
private static boolean in(Object x, Object y, Environment env, Location location) throws EvalException { if (env.getSemantics().incompatibleDepsetIsNotIterable() && y instanceof SkylarkNestedSet) { throw new EvalException( location, "argument of type '" + EvalUtils.getDataTypeName(y) + "' is not iterable. " + "in operator only works on lists, tuples, dicts and strings. " + "Use --incompatible_depset_is_not_iterable=false to temporarily disable " + "this check."); } else if (y instanceof SkylarkDict && !EvalUtils.isImmutable(x)) { throw new EvalException( location, "'in <dict>' requires hashable type as left operand, not '" + EvalUtils.getDataTypeName(x) + "'"); } else if (y instanceof SkylarkQueryable) { return ((SkylarkQueryable) y).containsKey(x, location, env.getStarlarkContext()); } else if (y instanceof String) { if (x instanceof String) { return ((String) y).contains((String) x); } else { throw new EvalException( location, "'in <string>' requires string as left operand, not '" + EvalUtils.getDataTypeName(x) + "'"); } } else { throw new EvalException( location, "argument of type '" + EvalUtils.getDataTypeName(y) + "' is not iterable. " + "in operator only works on lists, tuples, dicts and strings."); } }

Target:
private static boolean in(Object x, Object y, Environment env, Location location) throws EvalException { if (env.getSemantics().incompatibleDepsetIsNotIterable() && y instanceof SkylarkNestedSet) { throw new EvalException( location, "argument of type '" + EvalUtils.getDataTypeName(y) + "' is not iterable. " + "in operator only works on lists, tuples, dicts and strings. " + "Use --incompatible_depset_is_not_iterable=false to temporarily disable " + "this check."); } else if (y instanceof SkylarkQueryable) { return ((SkylarkQueryable) y).containsKey(x, location, env.getStarlarkContext()); } else if (y instanceof String) { if (x instanceof String) { return ((String) y).contains((String) x); } else { throw new EvalException( location, "'in <string>' requires string as left operand, not '" + EvalUtils.getDataTypeName(x) + "'"); } } else { throw new EvalException( location, "argument of type '" + EvalUtils.getDataTypeName(y) + "' is not iterable. " + "in operator only works on lists, tuples, dicts and strings."); } }
Source:
public List<Container> listContainers(final ListContainersParam... params) throws DockerException, InterruptedException { WebTarget resource = resource() .path("containers").path("json"); final Map<String, List<String>> filters = newHashMap(); for (ListContainersParam param : params) { if (param instanceof ListContainersFilterParam) { List<String> filterValueList; if (filters.containsKey(param.name())) { filterValueList = filters.get(param.name()); } else { filterValueList = Lists.newArrayList(); } filterValueList.add(param.value()); filters.put(param.name(), filterValueList); } else { try { final String encodedName = URLEncoder.encode(param.name(), UTF_8.name()); final String encodedValue = URLEncoder.encode(param.value(), UTF_8.name()); resource = resource.queryParam(encodedName, encodedValue); } catch (UnsupportedEncodingException e) { throw new DockerException(e); } } } try { if (!filters.isEmpty()) { final StringWriter writer = new StringWriter(); final JsonGenerator generator = objectMapper().getFactory().createGenerator(writer); generator.writeObject(filters); generator.close(); final String encoded = URLEncoder.encode(writer.toString(), UTF_8.name()); resource = resource.queryParam("filters", encoded); } } catch (IOException e) { throw new DockerException(e); } return request(GET, CONTAINER_LIST, resource, resource.request(APPLICATION_JSON_TYPE)); }

Target:
public List<Container> listContainers(final ListContainersParam... params) throws DockerException, InterruptedException { WebTarget resource = resource() .path("containers").path("json"); final Map<String, List<String>> filters = newHashMap(); for (ListContainersParam param : params) { if (param instanceof ListContainersFilterParam) { List<String> filterValueList; if (filters.containsKey(param.name())) { filterValueList = filters.get(param.name()); } else { filterValueList = Lists.newArrayList(); } filterValueList.add(param.value()); filters.put(param.name(), filterValueList); } else { try { final String encodedName = URLEncoder.encode(param.name(), UTF_8.name()); final String encodedValue = URLEncoder.encode(param.value(), UTF_8.name()); resource = resource.queryParam(encodedName, encodedValue); } catch (UnsupportedEncodingException e) { throw new DockerException(e); } } } resource = resource.queryParam("filters", urlEncodeFilters(filters)); return request(GET, CONTAINER_LIST, resource, resource.request(APPLICATION_JSON_TYPE)); }
Source:
private void completeMissingDataInParameters() { NicNameNicIdCompleter nicNameNicIdCompleter = new NicNameNicIdCompleter(getExistingNics()); nicNameNicIdCompleter.completeNetworkAttachments(getParameters().getNetworkAttachments()); nicNameNicIdCompleter.completeBonds(getParameters().getCreateOrUpdateBonds()); nicNameNicIdCompleter.completeNetworkAttachments(getExistingAttachments()); nicNameNicIdCompleter.completeLabels(getParameters().getLabels()); getParameters().getNetworkAttachments() .stream() .map(NetworkAttachment::getIpConfiguration) .forEach(ipConfigurationCompleter::completeDefaultIpConfiguration); networkIdNetworkNameCompleter.completeNetworkAttachments( getParameters().getNetworkAttachments(), getNetworkBusinessEntityMap()); networkIdNetworkNameCompleter.completeNetworkAttachments( getExistingAttachments(), getNetworkBusinessEntityMap()); NicLabelsCompleter labelsCompleter = new NicLabelsCompleter(getParameters(), getExistingAttachments(), getClusterNetworks(), getExistingNicsBusinessEntityMap()); labelsCompleter.completeNetworkAttachments(); fillInUnsetIpConfigs(); }

Target:
private void completeMissingDataInParameters() { NicNameNicIdCompleter nicNameNicIdCompleter = new NicNameNicIdCompleter(getExistingNics()); nicNameNicIdCompleter.completeNetworkAttachments(getParameters().getNetworkAttachments()); nicNameNicIdCompleter.completeBonds(getParameters().getCreateOrUpdateBonds()); nicNameNicIdCompleter.completeNetworkAttachments(getExistingAttachments()); nicNameNicIdCompleter.completeLabels(getParameters().getLabels()); ipConfigurationCompleter.fillInUnsetIpConfigs(getParameters().getNetworkAttachments()); networkIdNetworkNameCompleter.completeNetworkAttachments( getParameters().getNetworkAttachments(), getNetworkBusinessEntityMap()); networkIdNetworkNameCompleter.completeNetworkAttachments( getExistingAttachments(), getNetworkBusinessEntityMap()); NicLabelsCompleter labelsCompleter = new NicLabelsCompleter(getParameters(), getExistingAttachments(), getClusterNetworks(), getExistingNicsBusinessEntityMap()); labelsCompleter.completeNetworkAttachments(); }
Source:
public void deleteElementAllRevisions() { when(service.getDateTime()).thenReturn(TIMESTAMP); when(dao.getElementRevisions(TEST_STUDY, "id", false)).thenReturn(ELEMENTS); service.deleteElementAllRevisions(TEST_STUDY, "id"); for(AppConfigElement element : ELEMENTS) { assertTrue(element.isDeleted()); assertNotEquals(TIMESTAMP.getMillis(), element.getCreatedOn()); assertEquals(TIMESTAMP.getMillis(), element.getModifiedOn()); } verify(dao, times(2)).saveElementRevision(elementCaptor.capture()); assertTrue(elementCaptor.getAllValues().get(0).isDeleted()); assertTrue(elementCaptor.getAllValues().get(1).isDeleted()); }

Target:
public void deleteElementAllRevisions() { when(dao.getElementRevisions(TEST_STUDY, "id", false)).thenReturn(elements); service.deleteElementAllRevisions(TEST_STUDY, "id"); for(AppConfigElement element : elements) { assertTrue(element.isDeleted()); assertNotEquals(TIMESTAMP.getMillis(), element.getCreatedOn()); assertEquals(TIMESTAMP.getMillis(), element.getModifiedOn()); } verify(dao, times(2)).saveElementRevision(elementCaptor.capture()); assertTrue(elementCaptor.getAllValues().get(0).isDeleted()); assertTrue(elementCaptor.getAllValues().get(1).isDeleted()); }
Source:
public void getStatesByApplicationIdShouldThrowIllegalArgumentExceptionWhenApplicationIsNull() { given(applicationsRepository.findOne(FIRST_ID)).willReturn(null); given(statesRepository.findByApplicationEntityOrderByStateIndexDesc(null)).willThrow(IllegalArgumentException.class); statesService.getStatesByApplicationId(FIRST_ID); }

Target:
public void getStatesByApplicationIdShouldThrowIllegalArgumentExceptionWhenApplicationIsNull() { given(applicationsRepository.findOne(FIRST_ID)).willReturn(null); statesService.getStatesByApplicationId(FIRST_ID); }
Source:
protected static RawQuery parseRawQuery(final String rawQuery, final Clause.Occur occur) throws RuleParseException { final List<String> rawQueryParts = Arrays.asList(rawQuery.split("%%", -1)); final int size = rawQueryParts.size(); if (size % 2 == 0) { throw new RuleParseException("Invalid use of parametrization in the definition of a RawQuery. " + "Parameters must begin and end with %%"); } if (size == 1) { return new StringRawQuery(null, rawQuery, occur, false); } else { final List<ParametrizedRawQuery.Part> parts = IntStream.range(0, size) .mapToObj(index -> index % 2 == 0 ? new ParametrizedRawQuery.Part(rawQueryParts.get(index), ParametrizedRawQuery.Part.Type.QUERY_PART) : new ParametrizedRawQuery.Part(rawQueryParts.get(index).trim(), ParametrizedRawQuery.Part.Type.PARAMETER)) .filter(part -> !part.isEmpty()) .collect(Collectors.toList()); return new ParametrizedRawQuery(null, parts, occur, false); } }

Target:
protected static RawQuery parseRawQuery(final String rawQuery, final Clause.Occur occur) throws RuleParseException { final List<String> rawQueryParts = Arrays.asList(rawQuery.split("%%", -1)); final int size = rawQueryParts.size(); if (size % 2 == 0) { throw new RuleParseException("Invalid use of parametrization in the definition of a RawQuery. " + "Parameters must begin and end with %%"); } if (size == 1) { return new StringRawQuery(null, rawQuery, occur, false); } else { final List<ParametrizedRawQuery.Part> parts = IntStream.range(0, size) .mapToObj(index -> index % 2 == 0 ? new ParametrizedRawQuery.Part(rawQueryParts.get(index), ParametrizedRawQuery.Part.Type.QUERY_PART) : new ParametrizedRawQuery.Part(rawQueryParts.get(index), ParametrizedRawQuery.Part.Type.PARAMETER)) .collect(Collectors.toList()); return new ParametrizedRawQuery(null, parts, occur, false); } }