auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void setup() { InputStream resourceAsStream = contextClassLoader.getResourceAsStream(location); final ClassLoader oldLoader = Thread.currentThread().getContextClassLoader(); Source xsltSource = null; <START> try <END> { xsltSource = new StreamSource(resourceAsStream); TransformerFactory tf = TransformerFactory.newInstance(); tf.setURIResolver(new URIResolver() { @Override public Source resolve(String href, String base) throws TransformerException { if (StringUtils.contains(href, "http://")) { LOG.warn("Trying to fetch remote URL for XSLT. This is not possible; for speed reasons: " + href + ": " + base); return null; } return new StreamSource(Thread.currentThread().getContextClassLoader().getResourceAsStream(href)); } }); Thread.currentThread().setContextClassLoader(javax.xml.transform.TransformerFactory.class.getClassLoader()); xsltTransformer = tf.newTransformer(xsltSource); if (xsltParameters != null) { for (String key : xsltParameters.keySet()) { if (LOG.isDebugEnabled()) { LOG.debug("Setting property: " + key + " -> " + xsltParameters.get(key)); } xsltTransformer.setParameter(key, xsltParameters.get(key)); } } if (LOG.isDebugEnabled()) { LOG.debug("Created XSLT successfully: " + location); } } catch (Exception e) { throw new IllegalStateException("Not able to initialize the XSLT transformer.", e); } finally { Thread.currentThread().setContextClassLoader(oldLoader); } }</code><technical_language>Try Resources: try(InputStream resourceAsStream = contextClassLoader.getResourceAsStream(location))</technical_language>

Target:
public void setup() { try(InputStream resourceAsStream = contextClassLoader.getResourceAsStream(location)) { final Source xsltSource = new StreamSource(resourceAsStream); final TransformerFactory tf = TransformerFactory.newInstance(); tf.setURIResolver(new URIResolver() { @Override public Source resolve(String href, String base) throws TransformerException { if (StringUtils.contains(href, "http://")) { LOG.warn("Trying to fetch remote URL for XSLT. This is not possible; for speed reasons: " + href + ": " + base); return null; } return new StreamSource(Thread.currentThread().getContextClassLoader().getResourceAsStream(href)); } }); ClassLoaders.executeIn(TransformerFactory.class.getClassLoader(), new Callable<Object>(){ @Override public Object call() throws Exception { xsltTransformer = tf.newTransformer(xsltSource); return null; } }); if (xsltParameters != null) { for (String key : xsltParameters.keySet()) { if (LOG.isDebugEnabled()) { LOG.debug("Setting property: " + key + " -> " + xsltParameters.get(key)); } xsltTransformer.setParameter(key, xsltParameters.get(key)); } } if (LOG.isDebugEnabled()) { LOG.debug("Created XSLT successfully: " + location); } } catch (Exception e) { throw new IllegalStateException("Not able to initialize the XSLT transformer.", e); } }
Source:
<code>public void setTextFromFile(String filepath) { try { byte[] encoded = Files.readAllBytes(Paths.get(filepath)); this.text = new String(encoded); } catch (IOException ex) { System.err.println("Cannot read '" + filepath + "': " + ex); <START> System.exit(1); <END> } }</code><technical_language>Do system.exit, this is a main program. Throw exception return a boolean check in main program</technical_language>

Target:
public void setTextFromFile(String filepath) throws IOException { byte[] encoded = Files.readAllBytes(Paths.get(filepath)); this.text = new String(encoded); }
Source:
<code>static ThreadJob joinRun(ThreadJob threadJob, IProgressMonitor monitor) { if (isCanceled(monitor)) throw new OperationCanceledException(); InternalJob blockingJob = manager.findBlockingJob(threadJob); Thread blocker = blockingJob == null ? null : blockingJob.getThread(); ThreadJob result; boolean setInterruptFlagAtEnd = <START> JobManager.reactToInterruption ? false : Thread.interrupted(); <END> boolean interruptedDuringWaitForRun; try { if (manager.getLockManager().aboutToWait(blocker)) return threadJob; result = waitForRun(threadJob, monitor, blockingJob, blocker); } finally { interruptedDuringWaitForRun = Thread.interrupted(); manager.getLockManager().aboutToRelease(); if (setInterruptFlagAtEnd) { Thread.currentThread().interrupt(); } } if (interruptedDuringWaitForRun) { throw new OperationCanceledException(); } return result; }</code><technical_language>Antipattern. Simpler: JobManager.reactToInterruption && Thread.interrupted()</technical_language>

Target:
static ThreadJob joinRun(ThreadJob threadJob, IProgressMonitor monitor) { if (isCanceled(monitor)) throw new OperationCanceledException(); InternalJob blockingJob = manager.findBlockingJob(threadJob); Thread blocker = blockingJob == null ? null : blockingJob.getThread(); ThreadJob result; boolean setInterruptFlagAtEnd = !JobManager.reactToInterruption && Thread.interrupted(); boolean interruptedDuringWaitForRun; try { if (manager.getLockManager().aboutToWait(blocker)) return threadJob; result = waitForRun(threadJob, monitor, blockingJob, blocker); } finally { interruptedDuringWaitForRun = Thread.interrupted(); manager.getLockManager().aboutToRelease(); if (setInterruptFlagAtEnd) { Thread.currentThread().interrupt(); } } if (interruptedDuringWaitForRun) { throw new OperationCanceledException(); } return result; }
Source:
<code>public int compare(CtElement o1, CtElement o2) { if (!o1.getPosition().isValidPosition() && !o2.getPosition().isValidPosition()) { <START> return o1.equals(o2) ? 0 : -1; <END> } 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; }</code><technical_language>Nice fix. glance I problem transitive antisymmetric property. LGTM</technical_language>

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:
<code>public HourSpinner( long value, double min, double max, int minStep, int maxStep, boolean constrained, String valueBoxLabelText, <START> ValueSpinnerResources resources, <END> 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); }</code><technical_language>this is</technical_language>

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:
<code>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); <START> int result = dialog.open(); <END> labelProvider.dispose(); if (result == IStatus.OK) { return (IDockerConnection) dialog.getFirstResult(); } return null; }</code><technical_language>I 4 connections dialog shows 4 lines <unknown> a label</technical_language>

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:
<code>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")) <START> .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"))); <END> }</code><technical_language>worldpay_3ds_flex</technical_language>

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:
<code>public ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context, @QueryParameter String host, @QueryParameter String port) { AccessControlled _context = (context instanceof AccessControlled ? (AccessControlled) context : Jenkins.getInstance()); <START> if (_context != null && !_context.hasPermission(Computer.CONFIGURE)) { <END> 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))); }</code><technical_language>bug: ditto</technical_language>

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:
<code>public void setUp() { <START> fTrace = setupTrace(TmfTestTrace.A_TEST_10K.getFullPath()); <END> }</code><technical_language>"TmfTestTrace.A_TEST_10K" saved in a local TmfTestTrace variable, is repeated</technical_language>

Target:
public void setUp() { fTrace = setupTrace(TEST_TRACE.getFullPath()); }
Source:
<code><START> public LiteralTree NUMERIC_LITERAL() { <END> return b.<LiteralTree>nonterminal() .is(f.numericLiteral(b.token(PHPLexicalGrammar.NUMERIC_LITERAL))); }</code><technical_language>![MAJOR](<LINK_1> Rename this method name match regular expression '^[a-z][a-zA-Z0-9]*$'. [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
public LiteralTree NUMERIC_LITERAL() { return b.<LiteralTree>nonterminal(Kind.NUMERIC_LITERAL) .is(f.numericLiteral(b.token(PHPLexicalGrammar.NUMERIC_LITERAL))); }
Source:
<code>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"); <START> Preconditions.checkArgument(scheduleMap.containsKey("value") && CronExpression <END> .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"); }</code><technical_language>Is this check duplicate of line 101</technical_language>

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:
<code>public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) { <START> if (_timeRangeMSToSegmentSearchTree == null) { <END> 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; }</code><technical_language>Cache _timeRangeMSToSegmentSearchTree a local variable in case is swapped this method</technical_language>

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:
<code>public boolean deleteShardingKey(String namespace, String realm, String shardingKey) { synchronized (this) { <START> if (!_routingDataWriterMap.containsKey(namespace)) { <END> 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; } }</code><technical_language>move synchronized</technical_language>

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:
<code>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) { <START> CompletableFuture<Snapshot> error = new CompletableFuture<>(); <END> 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; }); }); }</code><technical_language>change Futures.errored()</technical_language>

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:
<code>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; <START> try { retrogen = retrogenMap.get("retrogen_"+gen.getKey()); } catch(NullPointerException e) { retrogen = false; } <END> if(retrogen) { gen.getValue().place(world, world.getChunkProvider().getChunkGenerator(), random, new BlockPos(16*chunkX, 0, 16*chunkZ)); } } } } }</code><technical_language>This block strange... catching NPEs checking is null</technical_language>

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:
<code>private void handleRelatedAlarms(OnmsAlarm situation) { if (!situation.isSituation()) { return; } Map<Integer, AlarmAssociationAndFact> associationFacts = alarmAssociationById.get(situation.getId()); <START> if (associationFacts == null) { <END> 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)); } } }</code><technical_language>replaced call computeIfAbsent</technical_language>

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:
<code>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); <START> snapshots = snapshots.stream().filter(snapshot -> snapshot.getType() != SnapshotType.ACTIVE || hasNoPreviewSnapshot) .collect(Collectors.toList()); snapshots.sort(comparator); <END> if (snapshots.stream().anyMatch(s -> s.getStatus() == SnapshotStatus.IN_PREVIEW)) { updatePreviewedDiskSnapshots(snapshots); } else { updateItems(snapshots); } }</code><technical_language>This done in a single call: snapshots = snapshots.stream().filter(/*...*/).sorted(comparator).collect(Collectors.toList());</technical_language>

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:
<code>public boolean isSamePartType(Part part) { <START> return part instanceof CombatInformationCenter && cost == part.getStickerPrice(); <END> }</code><technical_language>Money is a reference type needs .equals() instead of ==. need calculateCost is called first. suggestion return part instanceof CombatInformationCenter && getStickerPrice().equals(part.getStickerPrice());</technical_language>

Target:
public boolean isSamePartType(Part part) { calculateCost(); return part instanceof CombatInformationCenter && getStickerPrice().equals(part.getStickerPrice()); }
Source:
<code>public ITmfTrace getTrace() { for (ITmfTrace trace : TmfTraceManager.getInstance().getOpenedTraces()) { if (trace.getResource().equals(getResource())) { return trace; } } for (ITmfTrace trace : TmfTraceManager.getInstance().getOpenedTraces()) { <START> for (ITmfTrace t : TmfTraceManager.getTraceSet(trace)) { <END> if (getResource().equals(t.getResource())) { return t; } } } return null; }</code><technical_language>merge this for previous TmfTraceManager.getTraceSetWithExperiment(trace)</technical_language>

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:
<code>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())); } <START> return (myValues.size() <= index) ? new String() : myValues.get(index); <END> }</code><technical_language>s/new String()/""</technical_language>

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:
<code>public void verifyLowerCamelCase(String constructType, ParserRuleContext ctx) { String constructName = ctx.getText(); if (!CharFormatUtil.isLowerCamelCase(constructName)) { <START> Location location = new Location(ctx.getStart().getLine(), ctx.getStart().getCharPositionInLine() + 1); <END> this.printer.error(constructType + Messages.LOWER_CAMEL_CASE, location); } }</code><technical_language>Replace this call new Location() a call getContextStartLocation()</technical_language>

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:
<code>private String <START> generateDomainXml() <END> 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; }</code><technical_language>Do nice reuse code HotPlugNicVDSCommand</technical_language>

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:
<code>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()) <START> message += " Please disable logging on this loadbalancer."; <END> 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()); }</code><technical_language>I want do is validate a user is enable logging a load balancer a UDP protocol if so, throw a bad request exception. I care is in database. Likewise, if connection logging is enabled user changes protocol a non-UDP protocol a UDP protocol throw a bad request exception asking disable connection logging first. Thoughts</technical_language>

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:
<code>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); <START> generator.setRandom(new Random()); <END> 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); }</code><technical_language>worries. Thanks for fix. :)</technical_language>

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:
<code>JSONValue getFunctionSuggestion(final String label, final String insertText) { final JSONObject suggestion = makeJSONObject(); <START> final int CompletionItemKindFunction = 1; <END> 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; }</code><technical_language>Camel case please</technical_language>

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:
<code>public String getName() { <START> return "Yubikey Authentication"; <END> }</code><technical_language>Small typo: YubiKey? I is capitalized well</technical_language>

Target:
public String getName() { return "YubiKey Authentication"; }
Source:
<code>public ByteBuf tlswrap(ByteBuf src, ByteBufAllocator allocator) { SSLSession session = m_sslEngine.getSession(); int packetBufferSize = session.getPacketBufferSize(); <START> int applicationBufferSize = session.getApplicationBufferSize(); <END> 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; } }</code><technical_language>Is guaranteed a cleartext message of size applicationBufferSize, encryption of size <= packetBufferSize</technical_language>

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:
<code>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) { <START> Logger.error(this, e.getMessage(), e); <END> } } return result; }</code><technical_language>Please log content's Identifier relationship name too</technical_language>

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:
<code>public String getSystemDefaultTheme() { <START> if ((context.getResources().getConfiguration().uiMode & <END> 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); }</code><technical_language>suggest turning this a ternary</technical_language>

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:
<code>public synchronized ProcessTaskWrapper<RET> newTask() { <START> Entity entity = null; <END> 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(); }</code><technical_language>This change entity if a machine is explicitly. (Also in put / fetch variants.)</technical_language>

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:
<code>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; <START> } else if (key.equals(MAILBOX_ID)) { END> final String[] values = ir.readSimpleList(); if (values != null && values.length >= 1) { mailboxId = values[0]; resps[i] = null; break; } } ir.reset(); } }</code><technical_language>u switch MAILBOX_ID check</technical_language>

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:
<code>EpollDomainTransportFactory() { <START> try { <END> 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"); } }</code><technical_language>Duplicated code, try share/reuse</technical_language>

Target:
EpollDomainTransportFactory() { ReflectionUtil.loadEpollClass(); }
Source:
<code>public void setUp() throws Exception { Context context = InstrumentationRegistry.getTargetContext(); sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); bundle = new Bundle(); <START> Project project = new DefaultProjectCreator().createDefaultProject(PROJECT_NAME, <END> 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); }</code><technical_language>please dont create a default project this is awefully slow overkill for need. empty project a single brick sprite in sufficient</technical_language>

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:
<code>public void purgeDeletedSecretCodeSnippets() { SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); secretAsyncClient.purgeDeletedSecret("deletedSecretName") .doOnSuccess(purgeResponse -> <START> System.out.println("Successfully Purged deleted Secret \n")); <END> END: com.azure.keyvault.secrets.secretclient.purgeDeletedSecret#string }</code><technical_language>need \n</technical_language>

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:
<code>public List<Message> createSpawnMessage() { double x, y, z, yaw, pitch, speed; x = location.getX(); <START> y = location.getY() + 1.75; <END> 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()) ); }</code><technical_language>Do need spoof location in packet create ender pearl correct location server side (by adding 1.75 throwLoc)</technical_language>

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()) ); }