auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public int compare(CtElement o1, CtElement o2) { if (!o1.getPosition().isValidPosition() && !o2.getPosition().isValidPosition()) { return o1.equals(o2) ? 0 : -1; } if (!o1.getPosition().isValidPosition()) { return -1; } if (!o2.getPosition().isValidPosition()) { return 1; } int pos1 = o1.getPosition().getSourceStart(); int pos2 = o2.getPosition().getSourceStart(); if (pos1 == pos2) { int pos3 = o1.getPosition().getSourceEnd(); int pos4 = o2.getPosition().getSourceEnd(); if (pos3 == pos4) { return 0; } return (pos3 < pos4) ? -1 : 1; } return (pos1 < pos2) ? -1 : 1; }

Target:
public int compare(CtElement o1, CtElement o2) { if (!o1.getPosition().isValidPosition() && !o2.getPosition().isValidPosition()) { return o1.equals(o2) ? 0 : ((o1.hashCode() < o2.hashCode()) ? -1 : 1); } if (!o1.getPosition().isValidPosition()) { return -1; } if (!o2.getPosition().isValidPosition()) { return 1; } int pos1 = o1.getPosition().getSourceStart(); int pos2 = o2.getPosition().getSourceStart(); if (pos1 == pos2) { int pos3 = o1.getPosition().getSourceEnd(); int pos4 = o2.getPosition().getSourceEnd(); if (pos3 == pos4) { return 0; } return (pos3 < pos4) ? -1 : 1; } return (pos1 < pos2) ? -1 : 1; }
Source:
public HourSpinner( long value, double min, double max, int minStep, int maxStep, boolean constrained, String valueBoxLabelText, ValueSpinnerResources resources, SpinnerResources images ) { super(); setStylePrimaryName(STYLENAME_DEFAULT); long spinnerMin = (long) (min * 100); long spinnerMax = (long) (max * 100); if (images == null) { spinner = new Spinner( spinnerListener, value, spinnerMin, spinnerMax, minStep, maxStep, constrained ); } else { spinner = new Spinner( spinnerListener, value, spinnerMin, spinnerMax, minStep, maxStep, constrained, images ); } valueBox.setStyleName(TEXTBOX_STYLE); valueBox.addKeyPressHandler(keyPressHandler); spinnerContainer.add(valueBox); FlowPanel arrowsPanel = new FlowPanel(); arrowsPanel.setStylePrimaryName(ARROW_STYLE); arrowsPanel.add(spinner.getIncrementArrow()); arrowsPanel.add(spinner.getDecrementArrow()); spinnerContainer.add(arrowsPanel); valueBoxLabel = new Label(valueBoxLabelText); add(spinnerContainer); add(valueBoxLabel); }

Target:
public HourSpinner( long value, double min, double max, int minStep, int maxStep, boolean constrained, String valueBoxLabelText, ValueSpinnerResources resources, SpinnerResources images ) { super(); setStylePrimaryName(STYLENAME_DEFAULT); if (resources != null) { defaultResources = resources; } long spinnerMin = (long) (min * 100); long spinnerMax = (long) (max * 100); if (images == null) { spinner = new Spinner( spinnerListener, value, spinnerMin, spinnerMax, minStep, maxStep, constrained ); } else { spinner = new Spinner( spinnerListener, value, spinnerMin, spinnerMax, minStep, maxStep, constrained, images ); } valueBox.setStyleName(TEXTBOX_STYLE); valueBox.addKeyPressHandler(keyPressHandler); spinnerContainer.add(valueBox); FlowPanel arrowsPanel = new FlowPanel(); arrowsPanel.setStylePrimaryName(ARROW_STYLE); arrowsPanel.add(spinner.getIncrementArrow()); arrowsPanel.add(spinner.getDecrementArrow()); spinnerContainer.add(arrowsPanel); valueBoxLabel = new Label(valueBoxLabelText); add(spinnerContainer); add(valueBoxLabel); }
Source:
protected IDockerConnection chooseConnection( IDockerConnection[] connections) { IDebugModelPresentation labelProvider = DebugUITools .newDebugModelPresentation(); ElementListSelectionDialog dialog = new ElementListSelectionDialog( getActiveWorkbenchShell(), labelProvider); dialog.setElements(connections); dialog.setTitle( LaunchMessages.getString(LaunchShortcut_Connection_Selection)); dialog.setMessage( LaunchMessages.getString(LaunchShortcut_Choose_Connection)); dialog.setMultipleSelection(false); int result = dialog.open(); labelProvider.dispose(); if (result == IStatus.OK) { return (IDockerConnection) dialog.getFirstResult(); } return null; }

Target:
protected IDockerConnection chooseConnection( IDockerConnection[] connections) { IDebugModelPresentation labelProvider = DebugUITools .newDebugModelPresentation(); ElementListSelectionDialog dialog = new ElementListSelectionDialog( getActiveWorkbenchShell(), new ConnectionSelectionLabelProvider() { }); dialog.setElements(connections); dialog.setTitle( LaunchMessages.getString(LaunchShortcut_Connection_Selection)); dialog.setMessage( LaunchMessages.getString(LaunchShortcut_Choose_Connection)); dialog.setMultipleSelection(false); int result = dialog.open(); labelProvider.dispose(); if (result == IStatus.OK) { return (IDockerConnection) dialog.getFirstResult(); } return null; }
Source:
public void shouldReturn3dsFlexCredentials_whenGatewayAccountHasCreds() { String gatewayAccountId = createAGatewayAccountFor("worldpay", "a-description", "analytics-id"); databaseTestHelper.insertWorldpay3dsFlexCredential(Long.valueOf(gatewayAccountId), "macKey", "issuer", "org_unit_id", 2L); givenSetup() .get("/v1/frontend/accounts/" + gatewayAccountId) .then() .statusCode(200) .body("$", hasKey("worldpay_3ds_flex")) .body("worldpay_3ds_flex.issuer", is("issuer")) .body("worldpay_3ds_flex.organisational_unit_id", is("org_unit_id")) .body("wordpay_3ds_flex", not(hasKey("jwt_mac_key"))) .body("wordpay_3ds_flex", not(hasKey("version"))) .body("wordpay_3ds_flex", not(hasKey("gateway_account_id"))); }

Target:
public void shouldReturn3dsFlexCredentials_whenGatewayAccountHasCreds() { String gatewayAccountId = createAGatewayAccountFor("worldpay", "a-description", "analytics-id"); databaseTestHelper.insertWorldpay3dsFlexCredential(Long.valueOf(gatewayAccountId), "macKey", "issuer", "org_unit_id", 2L); givenSetup() .get("/v1/frontend/accounts/" + gatewayAccountId) .then() .statusCode(200) .body("$", hasKey("worldpay_3ds_flex")) .body("worldpay_3ds_flex.issuer", is("issuer")) .body("worldpay_3ds_flex.organisational_unit_id", is("org_unit_id")) .body("worldpay_3ds_flex", not(hasKey("jwt_mac_key"))) .body("worldpay_3ds_flex", not(hasKey("version"))) .body("worldpay_3ds_flex", not(hasKey("gateway_account_id"))); }
Source:
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context, @QueryParameter String host, @QueryParameter String port) { AccessControlled _context = (context instanceof AccessControlled ? (AccessControlled) context : Jenkins.getInstance()); if (_context != null && !_context.hasPermission(Computer.CONFIGURE)) { return new ListBoxModel(); } int portValue = Integer.parseInt(port); return new StandardUsernameListBoxModel().withMatching(SSHAuthenticator.matcher(Connection.class), CredentialsProvider.lookupCredentials(StandardUsernameCredentials.class, context, ACL.SYSTEM, SSHLauncher.SSH_SCHEME, new HostnamePortRequirement(host, portValue))); }

Target:
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context, @QueryParameter String host, @QueryParameter String port) { AccessControlled _context = (context instanceof AccessControlled ? (AccessControlled) context : Jenkins.getInstance()); if (_context == null || !_context.hasPermission(Computer.CONFIGURE)) { return new ListBoxModel(); } int portValue = Integer.parseInt(port); return new StandardUsernameListBoxModel().withMatching(SSHAuthenticator.matcher(Connection.class), CredentialsProvider.lookupCredentials(StandardUsernameCredentials.class, context, ACL.SYSTEM, SSHLauncher.SSH_SCHEME, new HostnamePortRequirement(host, portValue))); }
Source:
public void setUp() { fTrace = setupTrace(TmfTestTrace.A_TEST_10K.getFullPath()); }

Target:
public void setUp() { fTrace = setupTrace(TEST_TRACE.getFullPath()); }
Source:
public LiteralTree NUMERIC_LITERAL() { return b.<LiteralTree>nonterminal() .is(f.numericLiteral(b.token(PHPLexicalGrammar.NUMERIC_LITERAL))); }

Target:
public LiteralTree NUMERIC_LITERAL() { return b.<LiteralTree>nonterminal(Kind.NUMERIC_LITERAL) .is(f.numericLiteral(b.token(PHPLexicalGrammar.NUMERIC_LITERAL))); }
Source:
private void validateSchedule(final FlowTriggerBean flowTriggerBean) { final Map<String, String> scheduleMap = flowTriggerBean.getSchedule(); Preconditions.checkNotNull(scheduleMap, "flow trigger schedule must not be null"); Preconditions.checkArgument(scheduleMap.containsKey("type") && scheduleMap.get("type") .equals("cron"), "flow trigger schedule type must be cron"); Preconditions.checkArgument(scheduleMap.containsKey("value") && CronExpression .isValidExpression(scheduleMap.get("value")), "flow trigger schedule value must be a " + "valid cron expression"); Preconditions.checkArgument(scheduleMap.containsKey("value") && CronExpression .isValidExpression(scheduleMap.get("value")), "flow trigger schedule value must be a " + "valid cron expression"); Preconditions.checkArgument(scheduleMap.size() == 2, "flow trigger schedule must " + "contain type and value only"); }

Target:
private void validateSchedule(final FlowTriggerBean flowTriggerBean) { final Map<String, String> scheduleMap = flowTriggerBean.getSchedule(); Preconditions.checkNotNull(scheduleMap, "flow trigger schedule must not be null"); Preconditions.checkArgument( scheduleMap.containsKey(Constants.SCHEDULE_TYPE) && scheduleMap.get(Constants.SCHEDULE_TYPE) .equals(Constants.CRON_SCHEDULE_TYPE), "flow trigger schedule type must be cron"); Preconditions.checkArgument(scheduleMap.containsKey(Constants.SCHEDULE_VALUE) && CronExpression .isValidExpression(scheduleMap.get(Constants.SCHEDULE_VALUE)), "flow trigger schedule value must be a valid cron expression"); Preconditions.checkArgument(scheduleMap.size() == 2, "flow trigger schedule must " + "contain type and value only"); }
Source:
public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) { if (_timeRangeMSToSegmentSearchTree == null) { return segments; } FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest); if (filterQueryTree == null) { return segments; } List<Interval> ranges = getFilterTimeRange(filterQueryTree); if (ranges == null) { return segments; } if (ranges.size() == 0) { return Collections.emptySet(); } Set<String> selectedSegments = new HashSet<>(); for (Interval range : ranges) { Interval rangeMS = convertRangeToMS(range); for (Object segment : _timeRangeMSToSegmentSearchTree.searchAll(rangeMS)) { if (segments.contains(segment)) { selectedSegments.add((String) segment); } } } return selectedSegments; }

Target:
public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) { IntervalTree<String> intervalTree = _intervalTree; FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest); if (filterQueryTree == null) { return segments; } List<Interval> intervals = getFilterTimeIntervals(filterQueryTree); if (intervals == null) { return segments; } if (intervals.isEmpty()) { return Collections.emptySet(); } Set<String> selectedSegments = new HashSet<>(); for (Interval interval : intervals) { for (String segment : intervalTree.searchAll(interval)) { if (segments.contains(segment)) { selectedSegments.add(segment); } } } return selectedSegments; }
Source:
public boolean deleteShardingKey(String namespace, String realm, String shardingKey) { synchronized (this) { if (!_routingDataWriterMap.containsKey(namespace)) { throw new NoSuchElementException( "Failed to delete sharding key: Namespace " + namespace + " is not found!"); } boolean result = _routingDataWriterMap.get(namespace).deleteShardingKey(realm, shardingKey); refreshRoutingData(namespace); return result; } }

Target:
public boolean deleteShardingKey(String namespace, String realm, String shardingKey) { if (!_routingDataWriterMap.containsKey(namespace)) { throw new NoSuchElementException( "Failed to delete sharding key: Namespace " + namespace + " is not found!"); } synchronized (this) { boolean result = _routingDataWriterMap.get(namespace).deleteShardingKey(realm, shardingKey); refreshRoutingData(namespace); return result; } }
Source:
public CompletableFuture<Snapshot> mkdir(String newFolderName, Optional<SymmetricKey> requestedBaseReadKey, Optional<SymmetricKey> requestedBaseWriteKey, Optional<byte[]> desiredMapKey, boolean isSystemFolder, NetworkAccess network, Crypto crypto, Snapshot version, Committer committer) { if (!this.isDirectory()) { return Futures.errored(new IllegalStateException("Cannot mkdir in a file!")); } if (!isLegalName(newFolderName)) { return Futures.errored(new IllegalStateException("Illegal directory name: " + newFolderName)); } return hasChildWithName(version, newFolderName, crypto.hasher, network).thenCompose(hasChild -> { if (hasChild) { CompletableFuture<Snapshot> error = new CompletableFuture<>(); error.completeExceptionally(new IllegalStateException("Child already exists with name: " + newFolderName)); return error; } return pointer.fileAccess.mkdir(version, committer, newFolderName, network, writableFilePointer(), getChildsEntryWriter(), requestedBaseReadKey, requestedBaseWriteKey, desiredMapKey, isSystemFolder, crypto).thenApply(x -> { setModified(); return x; }); }); }

Target:
private CompletableFuture<Snapshot> mkdir(String newFolderName, Optional<SymmetricKey> requestedBaseReadKey, Optional<SymmetricKey> requestedBaseWriteKey, Optional<byte[]> desiredMapKey, boolean isSystemFolder, NetworkAccess network, Crypto crypto, Snapshot version, Committer committer) { if (!this.isDirectory()) { return Futures.errored(new IllegalStateException("Cannot mkdir in a file!")); } if (!isLegalName(newFolderName)) { return Futures.errored(new IllegalStateException("Illegal directory name: " + newFolderName)); } return hasChildWithName(version, newFolderName, crypto.hasher, network).thenCompose(hasChild -> { if (hasChild) { return Futures.errored(new IllegalStateException("Child already exists with name: " + newFolderName)); } return pointer.fileAccess.mkdir(version, committer, newFolderName, network, writableFilePointer(), getChildsEntryWriter(), requestedBaseReadKey, requestedBaseWriteKey, desiredMapKey, isSystemFolder, crypto).thenApply(x -> { setModified(); return x; }); }); }
Source:
public void generateOres(Random random, int chunkX, int chunkZ, World world, boolean newGeneration) { if(!oreDimBlacklist.contains(world.getDimension().getType().getRegistryName())) { if(newGeneration) { for(Entry<String, ConfiguredFeature<?>> gen : features.entrySet()) { gen.getValue().place(world, world.getChunkProvider().getChunkGenerator(), random, new BlockPos(16*chunkX, 0, 16*chunkZ)); } } else { for(Entry<String, ConfiguredFeature<?>> gen : retroFeatures.entrySet()) { boolean retrogen = false; try { retrogen = retrogenMap.get("retrogen_"+gen.getKey()); } catch(NullPointerException e) { retrogen = false; } if(retrogen) { gen.getValue().place(world, world.getChunkProvider().getChunkGenerator(), random, new BlockPos(16*chunkX, 0, 16*chunkZ)); } } } } }

Target:
public void generateOres(Random random, int chunkX, int chunkZ, World world, boolean newGeneration) { if(!oreDimBlacklist.contains(world.getDimension().getType().getRegistryName())) { if(newGeneration) { for(Entry<String, ConfiguredFeature<?>> gen : features.entrySet()) { gen.getValue().place(world, world.getChunkProvider().getChunkGenerator(), random, new BlockPos(16*chunkX, 0, 16*chunkZ)); } } else { for(Entry<String, ConfiguredFeature<?>> gen : retroFeatures.entrySet()) { if(retrogenMap.containsKey("retrogen_"+gen.getKey())&&retrogenMap.get("retrogen_"+gen.getKey())) { gen.getValue().place(world, world.getChunkProvider().getChunkGenerator(), random, new BlockPos(16*chunkX, 0, 16*chunkZ)); } } } } }
Source:
private void handleRelatedAlarms(OnmsAlarm situation) { if (!situation.isSituation()) { return; } Map<Integer, AlarmAssociationAndFact> associationFacts = alarmAssociationById.get(situation.getId()); if (associationFacts == null) { associationFacts = new HashMap<>(); alarmAssociationById.put(situation.getId(), associationFacts); } for (AlarmAssociation association : situation.getAssociatedAlarms()) { Integer alarmId = association.getRelatedAlarm().getId(); AlarmAssociationAndFact assocationFact = associationFacts.get(alarmId); if (assocationFact == null) { LOG.debug("Inserting alarm association into session: {}", association); final FactHandle fact = getKieSession().insert(association); associationFacts.put(alarmId, new AlarmAssociationAndFact(association, fact)); } else { FactHandle fact = assocationFact.getFact(); LOG.trace("Updating alarm assocation in session: {}", assocationFact); getKieSession().update(fact, association); associationFacts.put(alarmId, new AlarmAssociationAndFact(association, fact)); } } }

Target:
private void handleRelatedAlarms(OnmsAlarm situation) { if (!situation.isSituation()) { return; } alarmAssociationById.putIfAbsent(situation.getId(), new HashMap<>()); final Map<Integer, AlarmAssociationAndFact> associationFacts = alarmAssociationById.get(situation.getId()); for (AlarmAssociation association : situation.getAssociatedAlarms()) { Integer alarmId = association.getRelatedAlarm().getId(); AlarmAssociationAndFact assocationFact = associationFacts.get(alarmId); if (assocationFact == null) { LOG.debug("Inserting alarm association into session: {}", association); final FactHandle fact = getKieSession().insert(association); associationFacts.put(alarmId, new AlarmAssociationAndFact(association, fact)); } else { FactHandle fact = assocationFact.getFact(); LOG.trace("Updating alarm assocation in session: {}", assocationFact); getKieSession().update(fact, association); associationFacts.put(alarmId, new AlarmAssociationAndFact(association, fact)); } } associationFacts.values().stream() .map(fact -> fact.getAlarmAssociation().getRelatedAlarm().getId()) .filter(alarmId -> !situation.getRelatedAlarmIds().contains(alarmId)) .forEach(alarmId -> { final AlarmAssociationAndFact associationAndFact = associationFacts.remove(alarmId); if (associationAndFact != null) { LOG.debug("Deleting AlarmAssociationAndFact from session: {}", associationAndFact.getAlarmAssociation()); getKieSession().delete(associationAndFact.getFact()); } }); }
Source:
public void setItems(Collection<Snapshot> value) { List<Snapshot> snapshots = value != null ? new ArrayList<>(value) : new ArrayList<>(); snapshots.forEach(snapshot -> { SnapshotModel snapshotModel = snapshotsMap.computeIfAbsent(snapshot.getId(), id -> new SnapshotModel()); snapshotModel.setEntity(snapshot); }); boolean hasNoPreviewSnapshot = snapshots.stream().noneMatch(s -> s.getType() == SnapshotType.PREVIEW); snapshots = snapshots.stream().filter(snapshot -> snapshot.getType() != SnapshotType.ACTIVE || hasNoPreviewSnapshot) .collect(Collectors.toList()); snapshots.sort(comparator); if (snapshots.stream().anyMatch(s -> s.getStatus() == SnapshotStatus.IN_PREVIEW)) { updatePreviewedDiskSnapshots(snapshots); } else { updateItems(snapshots); } }

Target:
public void setItems(Collection<Snapshot> value) { List<Snapshot> snapshots = value != null ? new ArrayList<>(value) : new ArrayList<>(); snapshots.forEach(snapshot -> { SnapshotModel snapshotModel = snapshotsMap.computeIfAbsent(snapshot.getId(), id -> new SnapshotModel()); snapshotModel.setEntity(snapshot); }); boolean hasNoPreviewSnapshot = snapshots.stream().noneMatch(s -> s.getType() == SnapshotType.PREVIEW); snapshots = snapshots.stream().filter( snapshot -> snapshot.getType() != SnapshotType.ACTIVE || hasNoPreviewSnapshot ).sorted(comparator).collect(Collectors.toList()); if (snapshots.stream().anyMatch(s -> s.getStatus() == SnapshotStatus.IN_PREVIEW)) { updatePreviewedDiskSnapshots(snapshots); } else { updateItems(snapshots); } }
Source:
public boolean isSamePartType(Part part) { return part instanceof CombatInformationCenter && cost == part.getStickerPrice(); }

Target:
public boolean isSamePartType(Part part) { calculateCost(); return part instanceof CombatInformationCenter && getStickerPrice().equals(part.getStickerPrice()); }
Source:
public ITmfTrace getTrace() { for (ITmfTrace trace : TmfTraceManager.getInstance().getOpenedTraces()) { if (trace.getResource().equals(getResource())) { return trace; } } for (ITmfTrace trace : TmfTraceManager.getInstance().getOpenedTraces()) { for (ITmfTrace t : TmfTraceManager.getTraceSet(trace)) { if (getResource().equals(t.getResource())) { return t; } } } return null; }

Target:
public ITmfTrace getTrace() { for (ITmfTrace trace : TmfTraceManager.getInstance().getOpenedTraces()) { for (ITmfTrace t : TmfTraceManager.getTraceSetWithExperiment(trace)) { if (getResource().equals(t.getResource())) { return t; } } } return null; }
Source:
public String get(String name) { if (myMapping == null) { throw new IllegalStateException("No header mapping was specified, the record values can\'t be accessed by name"); } Integer index = myMapping.get(name); if (index == null) { throw new IllegalArgumentException(String.format("Mapping for %s not found, expected one of %s", name, myMapping.keySet())); } return (myValues.size() <= index) ? new String() : myValues.get(index); }

Target:
public String get(String name) { if (myMapping == null) { throw new IllegalStateException("No header mapping was specified, the record values can\'t be accessed by name"); } Integer index = myMapping.get(name); if (index == null) { throw new IllegalArgumentException(String.format("Mapping for %s not found, expected one of %s", name, myMapping.keySet())); } return (myValues.size() <= index) ? "" : myValues.get(index); }
Source:
public void verifyLowerCamelCase(String constructType, ParserRuleContext ctx) { String constructName = ctx.getText(); if (!CharFormatUtil.isLowerCamelCase(constructName)) { Location location = new Location(ctx.getStart().getLine(), ctx.getStart().getCharPositionInLine() + 1); this.printer.error(constructType + Messages.LOWER_CAMEL_CASE, location); } }

Target:
void verifyLowerCamelCase(String constructType, ParserRuleContext ctx) { String constructName = ctx.getText(); if (!CharFormatUtil.isLowerCamelCase(constructName)) { Location location = getContextStartLocation(ctx); this.printer.error(constructType + Messages.LOWER_CAMEL_CASE, location); } }
Source:
private String generateDomainXml() throws JAXBException { VmNic nic = getParameters().getNic(); VmDevice vmDevice = getParameters().getVmDevice(); LibvirtVmXmlBuilder builder = new LibvirtVmXmlBuilder( getParameters().getVm(), getVds().getId(), nic, vmDevice, vmInfoBuildUtils, nic.isPassthrough() ? Collections.singletonMap(nic.getId(), vmDevice.getHostDevice()) : Collections.emptyMap()); String libvirtXml = builder.buildHotplugNic(); String prettyLibvirtXml = XmlUtils.prettify(libvirtXml); if (prettyLibvirtXml != null) { log.info("NIC update: {}", prettyLibvirtXml); } return libvirtXml; }

Target:
private String generateDomainXml() { VmNic nic = getParameters().getNic(); VmDevice vmDevice = getParameters().getVmDevice(); LibvirtVmXmlBuilder builder = new LibvirtVmXmlBuilder( getParameters().getVm(), getVds().getId(), nic, vmDevice, vmInfoBuildUtils, nic.isPassthrough() ? Collections.singletonMap(nic.getId(), vmDevice.getHostDevice()) : Collections.emptyMap()); String libvirtXml = builder.buildHotplugNic(); String prettyLibvirtXml = XmlUtils.prettify(libvirtXml); if (prettyLibvirtXml != null) { log.info("NIC update: {}", prettyLibvirtXml); } return libvirtXml; }
Source:
public void update(LoadBalancer queueLb) throws EntityNotFoundException, ImmutableEntityException, UnprocessableEntityException, BadRequestException { LOG.debug("Entering " + getClass()); LoadBalancer dbLoadBalancer = loadBalancerRepository.getByIdAndAccountId(queueLb.getId(), queueLb.getAccountId()); if (queueLb.isConnectionLogging() != null && queueLb.isConnectionLogging() && dbLoadBalancer.isUdpProtocol()) { String message = "Protocol must be a non-UDP protocol for connection logging."; if(dbLoadBalancer.isConnectionLogging()) message += " Please disable logging on this loadbalancer."; LOG.warn(message); throw new BadRequestException(message); } LOG.debug("Updating the lb status to pending_update"); if (!loadBalancerRepository.testAndSetStatus(dbLoadBalancer.getAccountId(), dbLoadBalancer.getId(), LoadBalancerStatus.PENDING_UPDATE, false)) { String message = StringHelper.immutableLoadBalancer(dbLoadBalancer); LOG.warn(message); throw new ImmutableEntityException(message); } dbLoadBalancer.setConnectionLogging(queueLb.isConnectionLogging()); loadBalancerRepository.update(dbLoadBalancer); LOG.debug("Leaving " + getClass()); }

Target:
public void update(LoadBalancer queueLb) throws EntityNotFoundException, ImmutableEntityException, UnprocessableEntityException, BadRequestException { LOG.debug("Entering " + getClass()); LoadBalancer dbLoadBalancer = loadBalancerRepository.getByIdAndAccountId(queueLb.getId(), queueLb.getAccountId()); if (queueLb.isConnectionLogging() != null && queueLb.isConnectionLogging() && dbLoadBalancer.isUdpProtocol()) { String message = "Protocol must be a non-UDP protocol for connection logging."; LOG.warn(message); throw new BadRequestException(message); } LOG.debug("Updating the lb status to pending_update"); if (!loadBalancerRepository.testAndSetStatus(dbLoadBalancer.getAccountId(), dbLoadBalancer.getId(), LoadBalancerStatus.PENDING_UPDATE, false)) { String message = StringHelper.immutableLoadBalancer(dbLoadBalancer); LOG.warn(message); throw new ImmutableEntityException(message); } dbLoadBalancer.setConnectionLogging(queueLb.isConnectionLogging()); loadBalancerRepository.update(dbLoadBalancer); LOG.debug("Leaving " + getClass()); }
Source:
public void test() { int numNodes = 100; int total = 0; for (int i = 1; i <= 10; i++) { ErdosRenyiGenerator<String> generator = new ErdosRenyiGenerator<>(nodeFactory, numNodes, 0.1); generator.setRandom(new Random()); Graph<String> graph = generator.get(); Assert.assertTrue(graph.nodes().size() == numNodes); total += graph.edges().size(); } total /= 10.0; Assert.assertTrue(total > 495 - 50 && total < 495 + 50); }

Target:
public void test() { int numNodes = 100; int total = 0; for (int i = 1; i <= 10; i++) { ErdosRenyiGenerator<String> generator = new ErdosRenyiGenerator<>(nodeFactory, numNodes, 0.1); generator.setRandom(new Random(0)); Graph<String> graph = generator.get(); Assert.assertTrue(graph.nodes().size() == numNodes); total += graph.edges().size(); } total /= 10.0; Assert.assertTrue(total > 495 - 50 && total < 495 + 50); }
Source:
JSONValue getFunctionSuggestion(final String label, final String insertText) { final JSONObject suggestion = makeJSONObject(); final int CompletionItemKindFunction = 1; final int CompletionItemInsertTextRuleInsertAsSnippet = 4; suggestion.put("kind", makeJSONNumber(CompletionItemKindFunction)); suggestion.put("insertTextRules", makeJSONNumber(CompletionItemInsertTextRuleInsertAsSnippet)); suggestion.put("label", makeJSONString(label)); suggestion.put("insertText", makeJSONString(insertText)); return suggestion; }

Target:
JSONValue getFunctionSuggestion(final String label, final String insertText) { final JSONObject suggestion = makeJSONObject(); final int completionItemKindFunction = 1; final int completionItemInsertTextRuleInsertAsSnippet = 4; suggestion.put("kind", makeJSONNumber(completionItemKindFunction)); suggestion.put("insertTextRules", makeJSONNumber(completionItemInsertTextRuleInsertAsSnippet)); suggestion.put("label", makeJSONString(label)); suggestion.put("insertText", makeJSONString(insertText)); return suggestion; }
Source:
public String getName() { return "Yubikey Authentication"; }

Target:
public String getName() { return "YubiKey Authentication"; }
Source:
public ByteBuf tlswrap(ByteBuf src, ByteBufAllocator allocator) { SSLSession session = m_sslEngine.getSession(); int packetBufferSize = session.getPacketBufferSize(); int applicationBufferSize = session.getApplicationBufferSize(); int maxEncryptedSize = ((src.readableBytes() + applicationBufferSize - 1) / applicationBufferSize) * packetBufferSize; ByteBuf dest = allocator.buffer(maxEncryptedSize); try { assert dest.nioBufferCount() == 1 : "Should only have one buffer: " + dest.nioBufferCount(); ByteBuffer destNioBuf = dest.nioBuffer(dest.writerIndex(), dest.writableBytes()); ByteBuffer[] srcNioBuffers = src.nioBuffers(); do { SSLEngineResult result = null; try { result = m_sslEngine.wrap(srcNioBuffers, destNioBuf); } catch (SSLException | ReadOnlyBufferException | IllegalArgumentException | IllegalStateException e) { throw new TLSException("ssl engine wrap fault", e); } switch (result.getStatus()) { case OK: src.readerIndex(src.readerIndex() + result.bytesConsumed()); break; case BUFFER_OVERFLOW: throw new TLSException("SSL engine unexpectedly overflowed when enrypting"); case BUFFER_UNDERFLOW: throw new TLSException("SSL engine unexpectedly underflowed when encrypting"); case CLOSED: throw new TLSException("SSL engine is closed on ssl wrap of buffer."); } } while (src.isReadable()); dest.writerIndex(destNioBuf.position()); return dest; } catch (Throwable t) { dest.release(); throw t; } }

Target:
public ByteBuf tlswrap(ByteBuf src, ByteBufAllocator allocator) { SSLSession session = m_sslEngine.getSession(); int packetBufferSize = session.getPacketBufferSize(); CompositeByteBuf fullyEncrypted = null; ByteBuf piece = null; try { do { piece = allocator.buffer(packetBufferSize); assert piece.nioBufferCount() == 1 : "Should only have one buffer: " + piece.nioBufferCount(); ByteBuffer destNioBuf = piece.nioBuffer(0, piece.writableBytes()); ByteBuffer[] srcNioBuffers = src.nioBuffers(); SSLEngineResult result = null; try { result = m_sslEngine.wrap(srcNioBuffers, destNioBuf); } catch (SSLException | ReadOnlyBufferException | IllegalArgumentException | IllegalStateException e) { throw new TLSException("ssl engine wrap fault", e); } switch (result.getStatus()) { case OK: src.readerIndex(src.readerIndex() + result.bytesConsumed()); break; case BUFFER_OVERFLOW: throw new TLSException("SSL engine unexpectedly overflowed when encrypting"); case BUFFER_UNDERFLOW: throw new TLSException("SSL engine unexpectedly underflowed when encrypting"); case CLOSED: throw new TLSException("SSL engine is closed on ssl wrap of buffer."); } piece.writerIndex(destNioBuf.position()); if (fullyEncrypted == null) { if (!src.isReadable()) { return piece; } fullyEncrypted = allocator.compositeBuffer(1024); } fullyEncrypted.addComponent(true, piece); piece = null; } while (src.isReadable()); return fullyEncrypted; } catch (Throwable t) { if (piece != null) { piece.release(); } fullyEncrypted.release(); throw t; } }
Source:
private List<Contentlet> getRelatedParents(final Contentlet contentlet, final Relationship rel, final User user, final boolean respectFrontendRoles) throws DotSecurityException, DotDataException { final List<Contentlet> result = new ArrayList<>(); final String relationshipName = rel.getRelationTypeValue().toLowerCase(); SearchResponse response = APILocator.getEsSearchAPI() .esSearchRelated(contentlet.getIdentifier(), relationshipName, true,false, user, respectFrontendRoles); if (response.getHits() == null) { return result; } for (SearchHit sh : response.getHits()) { try { Map<String, Object> sourceMap = sh.getSourceAsMap(); if (sourceMap.get("identifier") != null) { result.add(findContentletByIdentifierAnyLanguage(sourceMap.get("identifier").toString())); } } catch (Exception e) { Logger.error(this, e.getMessage(), e); } } return result; }

Target:
private List<Contentlet> getRelatedParents(final Contentlet contentlet, final Relationship rel, final User user, final boolean respectFrontendRoles) throws DotSecurityException, DotDataException { if (getRelatedContentFromDB){ return FactoryLocator.getRelationshipFactory().dbRelatedContent(rel, contentlet, false); } else{ final List<Contentlet> result = new ArrayList<>(); final String relationshipName = rel.getRelationTypeValue().toLowerCase(); SearchResponse response = APILocator.getEsSearchAPI() .esSearchRelated(contentlet.getIdentifier(), relationshipName, true,false, user, respectFrontendRoles); if (response.getHits() == null) { return result; } for (SearchHit sh : response.getHits()) { Map<String, Object> sourceMap = sh.getSourceAsMap(); if (sourceMap.get("identifier") != null) { result.add(findContentletByIdentifierAnyLanguage(sourceMap.get("identifier").toString())); } } return result; } }
Source:
public String getSystemDefaultTheme() { if ((context.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES) { return context.getString(R.string.theme_dark_value); } return context.getString(R.string.theme_light_value); }

Target:
public String getSystemDefaultTheme() { return (context.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES ? THEME_MODE_DARK : THEME_MODE_LIGHT; }
Source:
public synchronized ProcessTaskWrapper<RET> newTask() { Entity entity = null; if (machine==null) { if (log.isDebugEnabled()) log.debug("Using an SshEffectorTask not in an effector without any machine; will attempt to infer the machine: "+this); entity = BrooklynTasks.getTargetOrContextEntity(Tasks.current()); if (entity!=null) machine(EffectorTasks.getSshMachine(entity)); } applySshFlags(getConfig(), entity, getMachine()); return super.newTask(); }

Target:
public synchronized ProcessTaskWrapper<RET> newTask() { Entity entity = BrooklynTasks.getTargetOrContextEntity(Tasks.current()); if (machine==null) { if (log.isDebugEnabled()) log.debug("Using an ssh task not in an effector without any machine; will attempt to infer the machine: "+this); if (entity!=null) machine(EffectorTasks.getSshMachine(entity)); } applySshFlags(getConfig(), entity, getMachine()); return super.newTask(); }
Source:
public ExtensionMailboxInfo(@Nonnull final IMAPResponse[] resps) throws ParsingException { super(resps); for (int i = 0; i < resps.length; i++) { if (resps[i] == null) { continue; } final IMAPResponse ir = resps[i]; ir.skipSpaces(); if (ir.readByte() != '[') { ir.reset(); continue; } String key = ir.readAtom(); if (key == null) { ir.reset(); continue; } key = key.toUpperCase(); if (key.equals(NOMODSEQ)) { isNoModSeq = true; } else if (key.equals(MAILBOX_ID)) { final String[] values = ir.readSimpleList(); if (values != null && values.length >= 1) { mailboxId = values[0]; resps[i] = null; break; } } ir.reset(); } }

Target:
public ExtensionMailboxInfo(@Nonnull final IMAPResponse[] resps) throws ParsingException { super(resps); for (int i = 0; i < resps.length; i++) { if (resps[i] == null) { continue; } final IMAPResponse ir = resps[i]; ir.skipSpaces(); if (ir.readByte() != '[') { ir.reset(); continue; } String key = ir.readAtom(); if (key == null) { ir.reset(); continue; } key = key.toUpperCase(); if (key.equals(MAILBOX_ID)) { final String[] values = ir.readSimpleList(); if (values != null && values.length >= 1) { mailboxId = values[0]; resps[i] = null; break; } } else if (key.equals(NOMODSEQ)) { isNoModSeq = true; } ir.reset(); } }
Source:
EpollDomainTransportFactory() { try { Class.forName("io.netty.channel.epoll.Epoll"); } catch (ClassNotFoundException e) { throw new IllegalStateException("The epoll transport is not available"); } if (!Epoll.isAvailable()) { throw new IllegalStateException("The epoll transport is not supported"); } }

Target:
EpollDomainTransportFactory() { ReflectionUtil.loadEpollClass(); }
Source:
public void setUp() throws Exception { Context context = InstrumentationRegistry.getTargetContext(); sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); bundle = new Bundle(); Project project = new DefaultProjectCreator().createDefaultProject(PROJECT_NAME, InstrumentationRegistry.getTargetContext(), false); Sprite firstSprite = new SingleSprite("firstSprite"); project.getDefaultScene().addSprite(firstSprite); ProjectSaveTask.task(project, context); Intent intent = new Intent(); intent.putExtra(PROJECT_DIR, project.getDirectory()); activityTestRule.launchActivity(intent); }

Target:
public void setUp() throws Exception { Context context = InstrumentationRegistry.getTargetContext(); sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); bundle = new Bundle(); Project project = new Project(context, PROJECT_NAME, false); Sprite firstSprite = new SingleSprite("firstSprite"); project.getDefaultScene().addSprite(firstSprite); ProjectSaveTask.task(project, context); Intent intent = new Intent(); intent.putExtra(PROJECT_DIR, project.getDirectory()); activityTestRule.launchActivity(intent); }
Source:
public void purgeDeletedSecretCodeSnippets() { SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); secretAsyncClient.purgeDeletedSecret("deletedSecretName") .doOnSuccess(purgeResponse -> System.out.println("Successfully Purged deleted Secret \n")); END: com.azure.keyvault.secrets.secretclient.purgeDeletedSecret#string }

Target:
public void purgeDeletedSecretCodeSnippets() { SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); secretAsyncClient.purgeDeletedSecret("deletedSecretName") .doOnSuccess(purgeResponse -> System.out.println("Successfully Purged deleted Secret")); END: com.azure.keyvault.secrets.secretclient.purgeDeletedSecret#string }
Source:
public List<Message> createSpawnMessage() { double x, y, z, yaw, pitch, speed; x = location.getX(); y = location.getY() + 1.75; z = location.getZ(); yaw = location.getYaw(); pitch = location.getPitch(); Vector vel = location.getDirection().multiply(2); setVelocity(vel); return Arrays.asList( new SpawnObjectMessage(id, getUniqueId(), SpawnObjectMessage.THROWN_ENDERPEARL, x, y, z, (int) yaw, (int) pitch), new EntityMetadataMessage(id, metadata.getEntryList()), new EntityTeleportMessage(id, x, y, z, (int)yaw, (int)pitch), new EntityVelocityMessage(id, getVelocity()) ); }

Target:
public List<Message> createSpawnMessage() { double x, y, z; int yaw,pitch; x = location.getX(); y = location.getY(); z = location.getZ(); yaw = Position.getIntYaw(location); pitch = Position.getIntPitch(location); Vector vel = location.getDirection().multiply(this.speed); setVelocity(vel); return Arrays.asList( new SpawnObjectMessage(id, getUniqueId(), SpawnObjectMessage.THROWN_ENDERPEARL, x, y, z, yaw, pitch), new EntityMetadataMessage(id, metadata.getEntryList()), new EntityTeleportMessage(id, x, y, z, yaw, pitch), new EntityVelocityMessage(id, getVelocity()) ); }
Source:
public void terminateTest(String testID) { logger.info("terminateTest: " + testID); try { BenchFlowTestState testState = testModelDAO.getTestState(testID); logger.info("Current status: " + testState); switch (testState) { case READY: readyQueue.remove(testID); cancelTask(testID); testModelDAO.setTestState(testID, TERMINATED); testModelDAO.setTestTerminatedState(testID, TestTerminatedState.PARTIALLY_COMPLETE); break; case WAITING: case START: cancelTask(testID); testModelDAO.setTestState(testID, TERMINATED); testModelDAO.setTestTerminatedState(testID, TestTerminatedState.PARTIALLY_COMPLETE); break; case RUNNING: TestRunningState runningState = testModelDAO.getTestRunningState(testID); testModelDAO.setTestRunningState(testID, TestRunningState.TERMINATING); cancelTask(testID); if (runningState == TestRunningState.HANDLE_EXPERIMENT_RESULT || runningState == TestRunningState.DETERMINE_EXECUTE_VALIDATION_SET) { logger.info("Need to execute AbortRunningTask"); AbortRunningTestTask abortRunningTestTask = new AbortRunningTestTask(testID); Future abortRunningTestTaskFuture = taskExecutorService.submit(abortRunningTestTask); try { abortRunningTestTaskFuture.get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } handleRunningTest(testID); break; case TERMINATED: break; default: break; } } catch (BenchFlowTestIDDoesNotExistException e) { e.printStackTrace(); } }

Target:
public void terminateTest(String testID) { logger.info("terminateTest: " + testID); try { BenchFlowTestState testState = testModelDAO.getTestState(testID); logger.info("Current status: " + testState); switch (testState) { case READY: readyQueue.remove(testID); cancelTask(testID); testModelDAO.setTestState(testID, TERMINATED); testModelDAO.setTestTerminatedState(testID, TestTerminatedState.PARTIALLY_COMPLETE); break; case WAITING: case START: cancelTask(testID); testModelDAO.setTestState(testID, TERMINATED); testModelDAO.setTestTerminatedState(testID, TestTerminatedState.PARTIALLY_COMPLETE); break; case RUNNING: TestRunningState runningState = testModelDAO.getTestRunningState(testID); testModelDAO.setTestRunningState(testID, TestRunningState.TERMINATING); cancelTask(testID); if (runningState == TestRunningState.HANDLE_EXPERIMENT_RESULT || runningState == TestRunningState.DETERMINE_EXECUTE_VALIDATION_SET) { logger.info("Need to execute AbortRunningTask"); AbortRunningTestTask abortRunningTestTask = new AbortRunningTestTask(testID); Future abortRunningTestTaskFuture = taskExecutorService.submit(abortRunningTestTask); try { abortRunningTestTaskFuture.get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } else { handleRunningTest(testID); } break; case TERMINATED: break; default: break; } } catch (BenchFlowTestIDDoesNotExistException e) { e.printStackTrace(); } }
Source:
public VariantContextBuilder(final VariantContext parent) { if( parent == null ) throw new IllegalArgumentException("BUG: VariantContextBuilder parent argument cannot be null in VariantContextBuilder"); this.alleles = parent.getAlleles(); this.contig = parent.getContig(); this.genotypes = parent.getGenotypes(); this.ID = parent.getID(); this.log10PError = parent.getLog10PError(); this.source = parent.getSource(); this.start = parent.getStart(); this.stop = parent.getEnd(); this.fullyDecoded = parent.isFullyDecoded(); this.attributes(parent.getAttributes()); if (parent.filtersWereApplied()) { this.filters(parent.getFilters()); } else { this.unfiltered(); } }

Target:
public VariantContextBuilder(final VariantContext parent) { if (parent == null) { throw new IllegalArgumentException("BUG: VariantContextBuilder parent argument cannot be null in VariantContextBuilder"); } this.alleles = parent.getAlleles(); this.contig = parent.getContig(); this.genotypes = parent.getGenotypes(); this.ID = parent.getID(); this.log10PError = parent.getLog10PError(); this.source = parent.getSource(); this.start = parent.getStart(); this.stop = parent.getEnd(); this.fullyDecoded = parent.isFullyDecoded(); this.attributes(parent.getAttributes()); if (parent.filtersWereApplied()) { this.filters(parent.getFilters()); } else { this.unfiltered(); } }
Source:
protected Pair<Long, Long> getProcMemoryRequirement() throws Exception { String strXms = getInitialMemorySize(); String strXmx = getMaxMemorySize(); long xms = azkaban.utils.Utils.parseMemString(strXms); long xmx = azkaban.utils.Utils.parseMemString(strXmx); Props azkabanProperties = AzkabanServer.getAzkabanProperties(); if (azkabanProperties != null) { String maxXms = azkabanProperties.getString(DirectoryFlowLoader.JOB_MAX_XMS, DirectoryFlowLoader.MAX_XMS_DEFAULT); String maxXmx = azkabanProperties.getString(DirectoryFlowLoader.JOB_MAX_XMX, DirectoryFlowLoader.MAX_XMX_DEFAULT); long sizeMaxXms = azkaban.utils.Utils.parseMemString(maxXms); long sizeMaxXmx = azkaban.utils.Utils.parseMemString(maxXmx); if (xms > sizeMaxXms) { throw new Exception(String.format("%s: Xms value has exceeded the allowed limit (max Xms = %s)", getId(), maxXms)); } if (xmx > sizeMaxXmx) { throw new Exception(String.format("%s: Xmx value has exceeded the allowed limit (max Xmx = %s)", getId(), maxXms)); } } return new Pair<Long, Long>(xms, xmx); }

Target:
protected Pair<Long, Long> getProcMemoryRequirement() throws Exception { String strXms = getInitialMemorySize(); String strXmx = getMaxMemorySize(); long xms = Utils.parseMemString(strXms); long xmx = Utils.parseMemString(strXmx); Props azkabanProperties = AzkabanServer.getAzkabanProperties(); if (azkabanProperties != null) { String maxXms = azkabanProperties.getString(DirectoryFlowLoader.JOB_MAX_XMS, DirectoryFlowLoader.MAX_XMS_DEFAULT); String maxXmx = azkabanProperties.getString(DirectoryFlowLoader.JOB_MAX_XMX, DirectoryFlowLoader.MAX_XMX_DEFAULT); long sizeMaxXms = Utils.parseMemString(maxXms); long sizeMaxXmx = Utils.parseMemString(maxXmx); if (xms > sizeMaxXms) { throw new Exception(String.format("%s: Xms value has exceeded the allowed limit (max Xms = %s)", getId(), maxXms)); } if (xmx > sizeMaxXmx) { throw new Exception(String.format("%s: Xmx value has exceeded the allowed limit (max Xmx = %s)", getId(), maxXms)); } } return new Pair<Long, Long>(xms, xmx); }
Source:
private void clickElement(final String selector) { Actions builder = new Actions(driver); builder.contextClick(wait.forElementClickable(By.cssSelector(selector))) .moveToElement(driver.findElement(By.cssSelector(selector))) .click(wait.forElementClickable(By.cssSelector(selector))) .perform(); }

Target:
private void clickElement(final String selector) { WebElement element = wait.forElementClickable(By.cssSelector(selector)); Actions builder = new Actions(driver); builder.contextClick(element) .moveToElement(element) .click(element) .perform(); }
Source:
private void buildInitialIndex() throws CorruptIndexException, IOException { Document meta = new Document(); meta.add(new StringField(F_VERSION, VERSION, Store.YES)); writer.addDocument(meta); writer.commit(); }

Target:
private void buildInitialIndex() throws CorruptIndexException, IOException { Document meta = new Document(); meta.add(new StoredField(F_VERSION, VERSION)); writer.addDocument(meta); writer.commit(); }
Source:
public LzoGenericBlockRecordReader(TypeRef<M> typeRef, BinaryConverter<M> binaryConverter) { super(typeRef, new BinaryBlockReader(null, binaryConverter), new GenericWritable<M>(binaryConverter)); LOG.info("LzoGenericBlockRecordReader, type args are " + typeRef.getRawClass()); }

Target:
public LzoGenericBlockRecordReader(TypeRef<M> typeRef, BinaryConverter<M> binaryConverter) { super(typeRef, new BinaryBlockReader(null, binaryConverter), new GenericWritable<M>(binaryConverter)); }
Source:
public void executeQueryFromFileZeroStatements() throws IOException { HiveShell shell = createHiveShell(); shell.start(); String hql = ""; File file = new File(tempFolder.getRoot(), "script.hql"); Files.write(hql, file, UTF_8); @SuppressWarnings("unused") List<String> results = shell.executeQuery(UTF_8, Paths.get(file.toURI()), "xxx", "yyy"); }

Target:
public void executeQueryFromFileZeroStatements() throws IOException { HiveShell shell = createHiveShell(); shell.start(); String hql = ""; File file = new File(tempFolder.getRoot(), "script.hql"); Files.write(hql, file, UTF_8); shell.executeQuery(UTF_8, Paths.get(file.toURI()), "xxx", "yyy"); }
Source:
public void createKieSessionFromSimpleDrlAndFireRules() { String drl = "package " + RULE_PKG_NAME + ";\n" + "\n" + "rule \"Dummy rule\"\n" + "when\n" + " String( this == \"MyValue\" )\n" + "then\n" + " System.out.println(\"Rule fired!\");\n" + "end"; KieHelper kieHelper = new KieHelper(); kieHelper.addContent(drl, ResourceType.DRL); KieBase kieBase = kieHelper.build(); Assert.assertFalse("At least one KiePackage expected!", kieBase.getKiePackages().isEmpty()); KiePackage testRulePackage = null; for (KiePackage kiePackage : kieBase.getKiePackages()) { if (RULE_PKG_NAME.equals(kiePackage.getName())) { testRulePackage = kiePackage; } } if (testRulePackage == null) { Assert.fail("Expected KiePackage " + RULE_PKG_NAME + " not found in " + kieBase.getKiePackages()); } KieSession kieSession = kieBase.newKieSession(); kieSession.insert("MyValue"); int rulesFired = kieSession.fireAllRules(); Assert.assertEquals("Unexpected number of rules fired!", 1, rulesFired); }

Target:
public void createKieSessionFromSimpleDrlAndFireRules() { String drl = "package " + RULE_PKG_NAME + ";\n" + "\n" + "rule \"Dummy rule\"\n" + "when\n" + " String( this == \"MyValue\" )\n" + "then\n" + " System.out.println(\"Rule fired!\");\n" + "end"; KieHelper kieHelper = new KieHelper(); kieHelper.addContent(drl, ResourceType.DRL); KieBase kieBase = kieHelper.build(); Assert.assertFalse("At least one KiePackage expected!", kieBase.getKiePackages().isEmpty()); Assert.assertTrue("Expected KiePackage " + RULE_PKG_NAME + " not found in " + kieBase.getKiePackages(), kieBase.getKiePackages().stream().anyMatch(kp -> RULE_PKG_NAME.equals(kp.getName())) ); KieSession kieSession = kieBase.newKieSession(); kieSession.insert("MyValue"); int rulesFired = kieSession.fireAllRules(); Assert.assertEquals("Unexpected number of rules fired!", 1, rulesFired); }
Source:
public void mockCreateCharge() { String payload = TestTemplateResourceLoader.load(STRIPE_AUTHORISATION_SUCCESS_RESPONSE); paymentServiceResponse(payload, "/v1/charges", APPLICATION_JSON); }

Target:
public void mockCreateCharge() { String payload = TestTemplateResourceLoader.load(STRIPE_AUTHORISATION_SUCCESS_RESPONSE); paymentServiceResponse(payload, "/v1/charges", APPLICATION_FORM_URLENCODED); }