auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void toJson(JsonNodeFactory factory, ObjectNode node) { if (query != null) { node.set("query", query.toJson()); } if (projection != null) { node.set("projection", projection.toJson()); } if (sort != null) { node.set("sort", sort.toJson()); } if (from != null && to != null) { ArrayNode arr = factory.arrayNode(); arr.add(from); if(to>0) arr.add(to); node.set("range", arr); } }

Target:
public void toJson(JsonNodeFactory factory, ObjectNode node) { if (query != null) { node.set("query", query.toJson()); } if (projection != null) { node.set("projection", projection.toJson()); } if (sort != null) { node.set("sort", sort.toJson()); } if (from != null) { ArrayNode arr = factory.arrayNode(); arr.add(from); if( to != null) arr.add(to); else arr.addNull(); node.set("range", arr); } }
Source:
public InputStream getInputStream(long lobId, long byteCount) throws IOException { MVStore.TxCounter txCounter = initialize(); try { Object[] value = lobMap.get(lobId); if (value == null) { throw DbException.get(ErrorCode.LOB_CLOSED_ON_TIMEOUT_1, "" + lobId); } byte[] streamStoreId = (byte[]) value[0]; InputStream inputStream = streamStore.get(streamStoreId); return new FilterInputStream(inputStream) { @Override public int read(byte[] b, int off, int len) throws IOException { MVStore.TxCounter txCounter = initialize(); try { return super.read(b, off, len); } finally { deregisterVersionUsage(txCounter); } } }; } finally { deregisterVersionUsage(txCounter); } }

Target:
public InputStream getInputStream(long lobId, long byteCount) throws IOException { MVStore.TxCounter txCounter = mvStore.registerVersionUsage(); try { Object[] value = lobMap.get(lobId); if (value == null) { throw DbException.get(ErrorCode.LOB_CLOSED_ON_TIMEOUT_1, "" + lobId); } byte[] streamStoreId = (byte[]) value[0]; InputStream inputStream = streamStore.get(streamStoreId); return new FilterInputStream(inputStream) { @Override public int read(byte[] b, int off, int len) throws IOException { MVStore.TxCounter txCounter = mvStore.registerVersionUsage(); try { return super.read(b, off, len); } finally { mvStore.deregisterVersionUsage(txCounter); } } @Override public int read() throws IOException { MVStore.TxCounter txCounter = mvStore.registerVersionUsage(); try { return super.read(); } finally { mvStore.deregisterVersionUsage(txCounter); } } }; } finally { mvStore.deregisterVersionUsage(txCounter); } }
Source:
private void search(){ String title = NbBundle.getMessage(this.getClass(), "CommonFilesPanel.search.results.title"); String pathText = NbBundle.getMessage(this.getClass(), "CommonFilesPanel.search.results.pathText"); Case currentCase = Case.getCurrentCase(); List<AbstractFile> contentList = null; try { SleuthkitCase tskDb = currentCase.getSleuthkitCase(); contentList = tskDb.findAllFilesWhere("1 == 1 GROUP BY md5 HAVING COUNT(*) > 1;"); } catch (TskCoreException ex) { Logger logger = Logger.getLogger(this.getClass().getName()); logger.log(Level.WARNING, "Error while trying to get common files.", ex); } if (contentList == null) { contentList = Collections.<AbstractFile>emptyList(); } CommonFilesNode sn = new CommonFilesNode(contentList); final TopComponent searchResultWin = DataResultTopComponent.createInstance( title, pathText, new TableFilterNode(sn, true, sn.getName()), contentList.size()); searchResultWin.requestActive(); }

Target:
private void search() { String title = Bundle.CommonFilesPanel_search_results_title(); String pathText = Bundle.CommonFilesPanel_search_results_pathText(); new SwingWorker<Void, Void>() { private int count = 0; private TableFilterNode tfn = null; @Override @SuppressWarnings("FinallyDiscardsException") protected Void doInBackground() throws Exception { List<AbstractFile> contentList; try { Case currentCase = Case.getOpenCase(); SleuthkitCase tskDb = currentCase.getSleuthkitCase(); contentList = tskDb.findAllFilesWhere("1 == 1 GROUP BY md5 HAVING COUNT(*) > 1;"); CommonFilesNode cfn = new CommonFilesNode(contentList); tfn = new TableFilterNode(cfn, true, cfn.getName()); count = contentList.size(); } catch (TskCoreException | NoCurrentCaseException ex) { LOGGER.log(Level.WARNING, "Error while trying to get common files.", ex); contentList = Collections.<AbstractFile>emptyList(); CommonFilesNode cfn = new CommonFilesNode(contentList); tfn = new TableFilterNode(cfn, true, cfn.getName()); } finally { return null; } } @Override protected void done() { try { super.done(); get(); TopComponent component = DataResultTopComponent.createInstance( title, pathText, tfn, count); component.requestActive(); } catch (InterruptedException | ExecutionException ex) { JOptionPane.showMessageDialog(WindowManager.getDefault().getMainWindow(), ex.getCause().getMessage(), "Some went wrong finding common files.", JOptionPane.ERROR_MESSAGE); } } }.execute(); }
Source:
public boolean handleSelectedOption(MenuItem item) { if (item.getItemId() == R.id.option_friendadd) { new AsyncFriendRequest(context, selectedPersona().getPersonaId()).execute(comClient); } else if (item.getItemId() == R.id.option_frienddel) { new AsyncFriendRemove(context, selectedPersona().getPersonaId()).execute(comClient); } return true; }

Target:
public boolean handleSelectedOption(MenuItem item) { if (item.getItemId() == R.id.option_friendadd) { new AsyncFriendRequest(context, BF3Droid.getUserId()).execute(comClient); } else if (item.getItemId() == R.id.option_frienddel) { new AsyncFriendRemove(context, BF3Droid.getUserId()).execute(comClient); } return true; }
Source:
public C list() { List<Q> collection = getBackendCollection(queryType, queryParams); if (collection == null || collection.isEmpty()) { throw new WebApplicationException(Response.Status.NOT_FOUND); } return mapCollection(collection); }

Target:
public C list() { List<Q> collection = getBackendCollection(queryType, queryParams); if (CollectionUtils.isEmpty(collection)) { throw new WebApplicationException(Response.Status.NOT_FOUND); } return mapCollection(collection); }
Source:
public SamzaResourceRequest(int numCores, int memoryMB, String preferredHost, String processorId, Instant requestTimestamp, Set<FaultDomain> faultDomains) { this.numCores = numCores; this.memoryMB = memoryMB; this.preferredHost = preferredHost; this.requestId = UUID.randomUUID().toString(); this.processorId = processorId; this.requestTimestamp = requestTimestamp; if (faultDomains == null) { this.faultDomains = new HashSet<>(); } else { this.faultDomains = faultDomains; } log.info("SamzaResourceRequest created for Processor ID: on host: at time: with Request ID: and the following list of fault domains: {}", this.processorId, this.preferredHost, this.requestTimestamp, this.requestId, this.faultDomains.toString()); }

Target:
public SamzaResourceRequest(int numCores, int memoryMB, String preferredHost, String processorId, Instant requestTimestamp, Set<FaultDomain> faultDomains) { Preconditions.checkNotNull(faultDomains, "Set of fault domains should not be null."); this.numCores = numCores; this.memoryMB = memoryMB; this.preferredHost = preferredHost; this.requestId = UUID.randomUUID().toString(); this.processorId = processorId; this.requestTimestamp = requestTimestamp; this.faultDomains = faultDomains; log.info("SamzaResourceRequest created for Processor ID: on host: at time: with Request ID: and the following list of fault domains: {}", this.processorId, this.preferredHost, this.requestTimestamp, this.requestId, this.faultDomains.toString()); }
Source:
public void setVanished(final boolean set) { vanished = set; if (set) { for (User user : ess.getOnlineUsers()) { if (!user.isAuthorized("essentials.vanish.see")) { user.getBase().hidePlayer(getBase()); } } setHidden(true); this.getBase().setMetadata("vanished", new FixedMetadataValue(Essentials, true)); ess.getVanishedPlayersNew().add(getName()); if (isAuthorized("essentials.vanish.effect")) { this.getBase().addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, Integer.MAX_VALUE, 1, false)); } } else { for (Player p : ess.getOnlinePlayers()) { p.showPlayer(getBase()); } setHidden(false); this.getBase().removeMetadata("vanished", Essentials); ess.getVanishedPlayersNew().remove(getName()); if (isAuthorized("essentials.vanish.effect")) { this.getBase().removePotionEffect(PotionEffectType.INVISIBILITY); } } }

Target:
public void setVanished(final boolean set) { vanished = set; if (set) { for (User user : ess.getOnlineUsers()) { if (!user.isAuthorized("essentials.vanish.see")) { user.getBase().hidePlayer(getBase()); } } setHidden(true); this.getBase().setMetadata("vanished", new FixedMetadataValue(this.ess, true)); ess.getVanishedPlayersNew().add(getName()); if (isAuthorized("essentials.vanish.effect")) { this.getBase().addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, Integer.MAX_VALUE, 1, false)); } } else { for (Player p : ess.getOnlinePlayers()) { p.showPlayer(getBase()); } setHidden(false); this.getBase().removeMetadata("vanished", this.ess); ess.getVanishedPlayersNew().remove(getName()); if (isAuthorized("essentials.vanish.effect")) { this.getBase().removePotionEffect(PotionEffectType.INVISIBILITY); } } }
Source:
public final void submit(Config userConf) throws AlreadyAliveException, InvalidTopologyException { if (this.httpServerResultsUrl == null) { TopologyBuilder builder = new TopologyBuilder(); Config conf = buildConfig(new BasicConfig()); if (userConf != null) { conf.putAll(userConf); } HeronSubmitter.submitTopology(topologyName, conf, buildTopology(builder).createTopology()); } else { TopologyTestTopologyBuilder builder = new TopologyTestTopologyBuilder(httpServerResultsUrl); Config conf = buildConfig(new BasicConfig()); conf.setTopologyReliabilityMode(Config.TopologyReliabilityMode.EFFECTIVELY_ONCE); conf.setTopologyStatefulCheckpointIntervalSecs(CHECKPOINT_INTERVAL); if (userConf != null) { conf.putAll(userConf); } HeronSubmitter.submitTopology(topologyName, conf, buildStatefulTopology(builder).createTopology()); } }

Target:
public final void submit(Config userConf) throws AlreadyAliveException, InvalidTopologyException { Config conf = buildConfig(new BasicConfig()); if (userConf != null) { conf.putAll(userConf); } if (this.httpServerResultsUrl == null) { TopologyBuilder builder = new TopologyBuilder(); HeronSubmitter.submitTopology(topologyName, conf, buildTopology(builder).createTopology()); } else { TopologyTestTopologyBuilder builder = new TopologyTestTopologyBuilder(httpServerResultsUrl); conf.setTopologyReliabilityMode(Config.TopologyReliabilityMode.EFFECTIVELY_ONCE); conf.setTopologyStatefulCheckpointIntervalSecs(CHECKPOINT_INTERVAL); HeronSubmitter.submitTopology(topologyName, conf, buildStatefulTopology(builder).createTopology()); } }
Source:
public int pollKey() { size--; if (size < 0) { throw new IllegalStateException("collection is already empty!?"); } Entry<Integer, GHIntHashSet> e = map.firstEntry(); GHIntHashSet set = e.getValue(); if (set.isEmpty()) { throw new IllegalStateException("internal set is already empty!?"); } Iterator<IntCursor> iter = set.iterator(); final int val = iter.next().value; set.removeAll(new IntPredicate() { @Override public boolean apply(int value) { return value == val; } }); if (set.isEmpty()) { map.remove(e.getKey()); } return val; }

Target:
public int pollKey() { size--; if (size < 0) { throw new IllegalStateException("collection is already empty!?"); } Entry<Integer, GHIntHashSet> e = map.firstEntry(); GHIntHashSet set = e.getValue(); if (set.isEmpty()) { throw new IllegalStateException("internal set is already empty!?"); } Iterator<IntCursor> iter = set.iterator(); final int val = iter.next().value; set.remove(val); if (set.isEmpty()) { map.remove(e.getKey()); } return val; }
Source:
protected void ping(InetAddress address) throws Exception { Socket socket = null; int ping = 1; for (; ; ) { if (isDebug()) { LOGGER.debug("Trial #{}/{} - creating socket connected to on port {}", ping, getMaxPings(), address, getPort()); } try { socket = new Socket(address, getPort()); break; } catch (ConnectException ce) { LOGGER.debug("Trial #{}/{} - exception caught: while creating socket connected to on port {}", ping, getMaxPings(), ce, address, getPort()); ping++; if (ping <= getMaxPings()) { LOGGER.debug("Waiting milliseconds before retrying ...", getPingIntervalMilli()); Thread.sleep(getPingIntervalMilli()); } else { break; } } } if (socket == null) { throw new ConnectException("maxPings exceeded: " + getMaxPings() + ". Giving up. The clamd daemon seems not to be running"); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "ASCII")); PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); LOGGER.debug("Sending: \"PING\" to ...", address); writer.println("PING"); writer.flush(); boolean pongReceived = false; for (; ; ) { String answer = reader.readLine(); if (answer != null) { answer = answer.trim(); LOGGER.debug("Received: \"{}\"", answer); answer = answer.trim(); if (answer.equals("PONG")) { pongReceived = true; } } else { break; } } reader.close(); writer.close(); if (!pongReceived) { throw new ConnectException("Bad answer from \"PING\" probe: expecting \"PONG\""); } } finally { socket.close(); } }

Target:
protected void ping(InetAddress address) throws Exception { Socket socket = null; int ping = 1; for (; ; ) { if (isDebug()) { LOGGER.debug("Trial #{}/{} - creating socket connected to on port {}", ping, getMaxPings(), address, getPort()); } try { socket = new Socket(address, getPort()); break; } catch (ConnectException ce) { LOGGER.debug("Trial #{}/{} - exception caught while creating socket connected to on port {}", ping, getMaxPings(), address, getPort(), ce); ping++; if (ping <= getMaxPings()) { LOGGER.debug("Waiting milliseconds before retrying ...", getPingIntervalMilli()); Thread.sleep(getPingIntervalMilli()); } else { break; } } } if (socket == null) { throw new ConnectException("maxPings exceeded: " + getMaxPings() + ". Giving up. The clamd daemon seems not to be running"); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "ASCII")); PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); LOGGER.debug("Sending: \"PING\" to ...", address); writer.println("PING"); writer.flush(); boolean pongReceived = false; for (; ; ) { String answer = reader.readLine(); if (answer != null) { answer = answer.trim(); LOGGER.debug("Received: \"{}\"", answer); answer = answer.trim(); if (answer.equals("PONG")) { pongReceived = true; } } else { break; } } reader.close(); writer.close(); if (!pongReceived) { throw new ConnectException("Bad answer from \"PING\" probe: expecting \"PONG\""); } } finally { socket.close(); } }
Source:
protected void onPause() { super.onPause(); mMapView.pause(); }

Target:
protected void onPause() { mMapView.pause(); super.onPause(); }
Source:
public Map<Dependency, FileValidationStatus> getValidationStatuses(final Set<Dependency> deps, final String validationKey) throws SQLException { Map<Dependency, FileValidationStatus> depValidationStatuses = new HashMap<>(); if (deps.isEmpty()) { return depValidationStatuses; } Map<String, Dependency> hashAndFileNameToDep = new HashMap<>(); Connection conn = null; ResultSet rs = null; PreparedStatement stmnt = null; try { conn = this.dbOperator.getDataSource().getConnection(); if (conn == null) { throw new SQLException("Null connection"); } conn.setAutoCommit(false); stmnt = conn.prepareStatement( String .format("SELECT file_name, file_sha1, validation_status FROM validated_dependencies " + "WHERE validation_key = ? AND (%s)", makeStrWithQuestionMarks(deps.size()))); stmnt.setString(1, validationKey); int index = 2; for (Dependency d : deps) { stmnt.setString(index++, d.getFileName()); stmnt.setString(index++, d.getSHA1()); hashAndFileNameToDep.put(d.getFileName() + d.getSHA1(), d); } rs = stmnt.executeQuery(); conn.commit(); while (rs.next()) { Dependency d = hashAndFileNameToDep.remove(rs.getString(1) + rs.getString(2)); FileValidationStatus v = FileValidationStatus.valueOf(rs.getInt(3)); depValidationStatuses.put(d, v); } hashAndFileNameToDep.values().stream() .forEach(d -> depValidationStatuses.put(d, FileValidationStatus.NEW)); } catch (final SQLException ex) { log.error("Transaction failed: ", ex); throw ex; } finally { DbUtils.closeQuietly(rs); DbUtils.closeQuietly(stmnt); DbUtils.closeQuietly(conn); } return depValidationStatuses; }

Target:
public Map<Dependency, FileValidationStatus> getValidationStatuses(final Set<Dependency> deps, final String validationKey) throws SQLException { Map<Dependency, FileValidationStatus> depValidationStatuses = new HashMap<>(); if (deps.isEmpty()) { return depValidationStatuses; } Map<String, Dependency> hashAndFileNameToDep = new HashMap<>(); Connection conn = null; ResultSet rs = null; PreparedStatement stmnt = null; try { conn = this.dbOperator.getDataSource().getConnection(); if (conn == null) { throw new SQLException("Null connection"); } stmnt = conn.prepareStatement( String .format("SELECT file_name, file_sha1, validation_status FROM validated_dependencies " + "WHERE validation_key = ? AND (%s)", makeStrWithQuestionMarks(deps.size()))); stmnt.setString(1, validationKey); int index = 2; for (Dependency d : deps) { stmnt.setString(index++, d.getFileName()); stmnt.setString(index++, d.getSHA1()); hashAndFileNameToDep.put(d.getFileName() + d.getSHA1(), d); } rs = stmnt.executeQuery(); while (rs.next()) { Dependency d = hashAndFileNameToDep.remove(rs.getString(1) + rs.getString(2)); FileValidationStatus v = FileValidationStatus.valueOf(rs.getInt(3)); depValidationStatuses.put(d, v); } hashAndFileNameToDep.values().stream() .forEach(d -> depValidationStatuses.put(d, FileValidationStatus.NEW)); } catch (final SQLException ex) { log.error("Transaction failed: ", ex); throw ex; } finally { DbUtils.closeQuietly(conn, stmnt, rs); } return depValidationStatuses; }
Source:
private void recursivelyExpandGroups(final Set<String> groupDNs, final LdapSchema schema, final DirContext ctx, final String groupDN) { if (groupDNs.add(groupDN) && schema.accountMemberField != null) { Set<String> cachedGroupDNs = groupsByInclude.getIfPresent(groupDN); if (cachedGroupDNs != null) { for (String cachedGroupDN : cachedGroupDNs) { recursivelyExpandGroups(groupDNs, schema, ctx, cachedGroupDN); } } else { try { final Name compositeGroupName = new CompositeName().add(groupDN); final Attribute in = ctx.getAttributes(compositeGroupName).get(schema.accountMemberField); cachedGroupDNs = new HashSet<String>(); if (in != null) { final NamingEnumeration<?> groups = in.getAll(); try { while (groups.hasMore()) { final String nextDN = (String) groups.next(); cachedGroupDNs.add(nextDN); recursivelyExpandGroups(groupDNs, schema, ctx, nextDN); } } catch (PartialResultException e) { } } groupsByInclude.put(groupDN, cachedGroupDNs); } catch (NamingException e) { LdapRealm.log.warn("Could not find group " + groupDN, e); } } } }

Target:
private void recursivelyExpandGroups(final Set<String> groupDNs, final LdapSchema schema, final DirContext ctx, final String groupDN) { if (groupDNs.add(groupDN) && schema.accountMemberField != null) { ImmutableSet<String> cachedGroupDNs = groupsByInclude.getIfPresent(groupDN); if (cachedGroupDNs == null) { ImmutableSet.Builder<String> dns = ImmutableSet.builder(); try { final Name compositeGroupName = new CompositeName().add(groupDN); final Attribute in = ctx.getAttributes(compositeGroupName).get(schema.accountMemberField); if (in != null) { final NamingEnumeration<?> groups = in.getAll(); try { while (groups.hasMore()) { dns.add((String) groups.next()); } } catch (PartialResultException e) { } } } catch (NamingException e) { LdapRealm.log.warn("Could not find group " + groupDN, e); } cachedGroupDNs = dns.build(); groupsByInclude.put(groupDN, cachedGroupDNs); } for (String dn : cachedGroupDNs) { recursivelyExpandGroups(groupDNs, schema, ctx, dn); } } }
Source:
public void draw(T value, Canvas canvas) { Texture texture = getTexture(value); if (marginTop + texture.getHeight() + marginBottom > canvas.size().y) { int iconHeight = canvas.size().y - marginTop - marginBottom; canvas.drawTexture(texture, Rect2i.createFromMinAndSize(marginLeft, marginTop, texture.getWidth(), iconHeight)); } else { int iconVerticalPosition = (canvas.size().y - texture.getHeight()) / 2; canvas.drawTexture(texture, Rect2i.createFromMinAndSize(marginLeft, iconVerticalPosition, texture.getWidth(), texture.getHeight())); } String text = getString(value); int iconWidth = marginLeft + texture.getWidth() + marginRight; if (wrap) { canvas.drawText(text, Rect2i.createFromMinAndSize(iconWidth, 0, canvas.getRegion().width() - iconWidth, canvas.getRegion().height())); } else { int width = canvas.size().x - iconWidth; Font font = canvas.getCurrentStyle().getFont(); if (font.getWidth(text) <= width) { canvas.drawText(text); } else { String shortText = "..."; StringBuilder sb = new StringBuilder(text); while (sb.length() > 0) { shortText = sb.toString() + "..."; if (font.getWidth(shortText) <= width) { break; } sb.setLength(sb.length() - 1); } canvas.drawText(shortText); } } }

Target:
public void draw(T value, Canvas canvas) { Texture texture = getTexture(value); if (marginTop + texture.getHeight() + marginBottom > canvas.size().y) { int iconHeight = canvas.size().y - marginTop - marginBottom; canvas.drawTexture(texture, Rect2i.createFromMinAndSize(marginLeft, marginTop, texture.getWidth(), iconHeight)); } else { int iconVerticalPosition = (canvas.size().y - texture.getHeight()) / 2; canvas.drawTexture(texture, Rect2i.createFromMinAndSize(marginLeft, iconVerticalPosition, texture.getWidth(), texture.getHeight())); } String text = getString(value); int iconWidth = marginLeft + texture.getWidth() + marginRight; if (wrap) { canvas.drawText(text, Rect2i.createFromMinAndSize(iconWidth, 0, canvas.getRegion().width() - iconWidth, canvas.getRegion().height())); } else { int width = canvas.size().x - iconWidth; Font font = canvas.getCurrentStyle().getFont(); if (font.getWidth(text) <= width) { canvas.drawText(text); } else { String shortText = "..."; StringBuilder sb = new StringBuilder(text); while (sb.length() > 0) { shortText = sb.toString() + "..."; if (font.getWidth(shortText) <= width) { break; } sb.setLength(sb.length() - 1); } canvas.drawText(shortText, Rect2i.createFromMinAndSize(iconWidth, 0, canvas.getRegion().width() - iconWidth, canvas.getRegion().height())); } } }
Source:
private void disposeInternal() { logger.debug("Disposing bridge '{}'", getThing().getUID().getId()); super.dispose(); if (discoveryService != null) { discoveryService.stopScan(); unregisterDeviceDiscoveryService(); } if (gateway != null) { gateway.dispose(); } if (config != null) { portPool.release(config.getXmlCallbackPort()); portPool.release(config.getBinCallbackPort()); } }

Target:
private void disposeInternal() { logger.debug("Disposing bridge '{}'", getThing().getUID().getId()); if (discoveryService != null) { discoveryService.stopScan(); unregisterDeviceDiscoveryService(); } if (gateway != null) { gateway.dispose(); } if (config != null) { portPool.release(config.getXmlCallbackPort()); portPool.release(config.getBinCallbackPort()); } }
Source:
public static void init() { Debug.log("Loading Paper support module..."); ScriptEvent.registerScriptEvent(new PlayerEquipsArmorScriptEvent()); ScriptEvent.registerScriptEvent(new PlayerJumpsPaperScriptEventImpl()); ScriptEvent.registerScriptEvent(new PlayerSpectatesEntityScriptEvent()); ScriptEvent.registerScriptEvent(new EntityKnocksbackEntityScriptEvent()); ScriptEvent.registerScriptEvent(new PlayerStopsSpectatingScriptEvent()); ScriptEvent.registerScriptEvent(new ProjectileCollideScriptEvent()); ScriptEvent.registerScriptEvent(new TNTPrimesScriptEvent()); PropertyParser.registerProperty(EntityCanTick.class, EntityTag.class); }

Target:
public static void init() { Debug.log("Loading Paper support module..."); ScriptEvent.registerScriptEvent(new EntityKnocksbackEntityScriptEvent()); ScriptEvent.registerScriptEvent(new PlayerEquipsArmorScriptEvent()); ScriptEvent.registerScriptEvent(new PlayerJumpsPaperScriptEventImpl()); ScriptEvent.registerScriptEvent(new PlayerSpectatesEntityScriptEvent()); ScriptEvent.registerScriptEvent(new PlayerStopsSpectatingScriptEvent()); ScriptEvent.registerScriptEvent(new ProjectileCollideScriptEvent()); ScriptEvent.registerScriptEvent(new TNTPrimesScriptEvent()); PropertyParser.registerProperty(EntityCanTick.class, EntityTag.class); }
Source:
private Session getSession(URI sessionModelURI, boolean restore) { Session sessionFromURI; try { sessionFromURI = SessionManager.INSTANCE.getExistingSession(sessionModelURI); if (sessionFromURI == null && restore) { status = Status.OK_STATUS; SubMonitor subMonitor = SubMonitor.convert(new NullProgressMonitor(), "Get session", 1); sessionFromURI = SessionManager.INSTANCE.openSession(sessionModelURI, subMonitor, SiriusEditPlugin.getPlugin().getUiCallback()); } } catch (OperationCanceledException e) { sessionFromURI = null; status = new Status(IStatus.CANCEL, SiriusEditPlugin.ID, e.getLocalizedMessage(), e); } catch (RuntimeException e) { sessionFromURI = null; status = new Status(IStatus.ERROR, SiriusEditPlugin.ID, e.getLocalizedMessage(), e); } return sessionFromURI; }

Target:
private Session getSession(URI sessionModelURI, boolean restore) { Session sessionFromURI; try { sessionFromURI = SessionManager.INSTANCE.getExistingSession(sessionModelURI); if (sessionFromURI == null && restore) { status = Status.OK_STATUS; sessionFromURI = SessionManager.INSTANCE.openSession(sessionModelURI, new NullProgressMonitor(), SiriusEditPlugin.getPlugin().getUiCallback()); } if (sessionFromURI != null && sessionFromURI.isOpen()) { IEditingSession uiSession = SessionUIManager.INSTANCE.getUISession(sessionFromURI); if (uiSession == null && restore) { uiSession = SessionUIManager.INSTANCE.getOrCreateUISession(sessionFromURI); } if (uiSession != null && !uiSession.isOpen()) { uiSession.open(); } } } catch (OperationCanceledException e) { sessionFromURI = null; status = new Status(IStatus.CANCEL, SiriusEditPlugin.ID, e.getLocalizedMessage(), e); } catch (RuntimeException e) { sessionFromURI = null; status = new Status(IStatus.ERROR, SiriusEditPlugin.ID, e.getLocalizedMessage(), e); } return sessionFromURI; }
Source:
public <P extends ProviderProxy<?>> P create(Provider<?> provider) { if (provider.getIsDummy()) { return (P) new DummyNetworkProviderProxy(provider); } switch (provider.getType()) { case EXTERNAL_NETWORK: return (P) new ExternalNetworkProviderProxy((Provider<OpenstackNetworkProviderProperties>) provider); case FOREMAN: return (P) new ForemanHostProviderProxy(provider); case OPENSTACK_NETWORK: return (P) new OpenstackNetworkProviderProxy((Provider<OpenstackNetworkProviderProperties>) provider); case OPENSTACK_IMAGE: return (P) new OpenStackImageProviderProxy((Provider<OpenStackImageProviderProperties>) provider); case OPENSTACK_VOLUME: return (P) new OpenStackVolumeProviderProxy((Provider<OpenStackVolumeProviderProperties>) provider); case VMWARE: return (P) Injector.injectMembers(new VmwareVmProviderProxy((Provider<VmwareVmProviderProperties>) provider)); case KVM: return (P) Injector.injectMembers(new KVMVmProviderProxy((Provider<KVMVmProviderProperties>) provider)); case XEN: return (P) Injector.injectMembers(new XENVmProviderProxy((Provider<XENVmProviderProperties>) provider)); default: return null; } }

Target:
public <P extends ProviderProxy<?>> P create(Provider<?> provider) { switch (provider.getType()) { case EXTERNAL_NETWORK: if (provider.getIsDummy()) { return (P) new DummyNetworkProviderProxy(provider); } return (P) new ExternalNetworkProviderProxy((Provider<OpenstackNetworkProviderProperties>) provider); case FOREMAN: return (P) new ForemanHostProviderProxy(provider); case OPENSTACK_NETWORK: if (provider.getIsDummy()) { return (P) new DummyNetworkProviderProxy(provider); } return (P) new OpenstackNetworkProviderProxy((Provider<OpenstackNetworkProviderProperties>) provider); case OPENSTACK_IMAGE: return (P) new OpenStackImageProviderProxy((Provider<OpenStackImageProviderProperties>) provider); case OPENSTACK_VOLUME: return (P) new OpenStackVolumeProviderProxy((Provider<OpenStackVolumeProviderProperties>) provider); case VMWARE: return (P) Injector.injectMembers(new VmwareVmProviderProxy((Provider<VmwareVmProviderProperties>) provider)); case KVM: return (P) Injector.injectMembers(new KVMVmProviderProxy((Provider<KVMVmProviderProperties>) provider)); case XEN: return (P) Injector.injectMembers(new XENVmProviderProxy((Provider<XENVmProviderProperties>) provider)); default: return null; } }
Source:
public void testSizeLimitReachWaits() throws InterruptedException { ExecutorService pool = Executors.newCachedThreadPool(); try { final HeapSizeManager underTest = new HeapSizeManager(1l, 1, executorService); long id = underTest.registerOperationWithHeapSize(5l); assertTrue(underTest.hasInflightRequests()); final AtomicBoolean secondRequestRegistered = new AtomicBoolean(); pool.submit(new Runnable() { @Override public void run() { try { underTest.registerOperationWithHeapSize(5l); secondRequestRegistered.set(true); } catch (InterruptedException e) { e.printStackTrace(); } } }); Thread.sleep(10); assertFalse(secondRequestRegistered.get()); underTest.markOperationCompleted(id); Thread.sleep(10); assertTrue(secondRequestRegistered.get()); } finally { pool.shutdownNow(); } }

Target:
public void testSizeLimitReachWaits() throws InterruptedException { ExecutorService pool = Executors.newCachedThreadPool(); try { final HeapSizeManager underTest = new HeapSizeManager(1l, 1, executorService); long id = underTest.registerOperationWithHeapSize(5l); assertTrue(underTest.hasInflightRequests()); assertTrue(underTest.isFull()); final AtomicBoolean secondRequestRegistered = new AtomicBoolean(); pool.submit(new Runnable() { @Override public void run() { try { underTest.registerOperationWithHeapSize(5l); secondRequestRegistered.set(true); } catch (InterruptedException e) { throw new RuntimeException(e); } } }); Thread.sleep(10); assertFalse(secondRequestRegistered.get()); underTest.markOperationCompleted(id); Thread.sleep(10); assertTrue(secondRequestRegistered.get()); } finally { pool.shutdownNow(); } }
Source:
public RepositoryCacheConfig fromConfig(Config config) { setExpireAfter( config.getLong("core", null, "repositoryCacheExpireAfter", getExpireAfter())); setCleanupDelay( config.getLong("core", null, "repositoryCacheCleanupDelay", AUTO_CLEANUP_DELAY)); return this; }

Target:
public RepositoryCacheConfig fromConfig(Config config) { setExpireAfter( config.getTimeUnit("core", null, "repositoryCacheExpireAfter", getExpireAfter(), TimeUnit.MILLISECONDS)); setCleanupDelay( config.getTimeUnit("core", null, "repositoryCacheCleanupDelay", AUTO_CLEANUP_DELAY, TimeUnit.MILLISECONDS)); return this; }
Source:
public boolean performOk() { for(int i=0; i<envVariables.length; i++) envVariables[i].store(); return true; }

Target:
public boolean performOk() { for (StringFieldEditor envVariable : envVariables) { envVariable.store(); } return true; }
Source:
public void checkDebug() { debug = getContext().getConfiguration().get(GenomixJobConf.DEBUG_KMERS) != null; if (problemKmers == null) { problemKmers = new ArrayList<VKmer>(); if (getContext().getConfiguration().get(GenomixJobConf.DEBUG_KMERS) != null) { for (String kmer : getContext().getConfiguration().get(GenomixJobConf.DEBUG_KMERS).split(",")) { problemKmers.add(new VKmer(kmer)); } Node.problemKmers = problemKmers; } } verbose = false; verbose |= debug; for (VKmer problemKmer : problemKmers) { verbose |= debug && (getVertexValue().getNode().findEdge(problemKmer) != null || getVertexId().equals(problemKmer)); } }

Target:
public void checkDebug() { debug = getContext().getConfiguration().get(GenomixJobConf.DEBUG_KMERS) != null; if (problemKmers == null) { problemKmers = new ArrayList<VKmer>(); if (getContext().getConfiguration().get(GenomixJobConf.DEBUG_KMERS) != null) { for (String kmer : getContext().getConfiguration().get(GenomixJobConf.DEBUG_KMERS).split(",")) { problemKmers.add(new VKmer(kmer)); } Node.problemKmers = problemKmers; } } verbose = false; for (VKmer problemKmer : problemKmers) { verbose |= debug && (getVertexValue().getNode().findEdge(problemKmer) != null || getVertexId().equals(problemKmer)); } }
Source:
public void setVariable(final TestSuite testSuite, final String identifier, final String content, @ScriptParameter(defaultValue = ScriptParameter.NULL) final String description, @ScriptParameter(defaultValue = ScriptParameter.NULL) final String path) { testSuite.getModel().setVariable(identifier, content, description, new Path(path)); }

Target:
public void setVariable(final TestSuite testSuite, final String identifier, final String content, @ScriptParameter(defaultValue = ScriptParameter.NULL) final String description, @ScriptParameter(defaultValue = ScriptParameter.NULL) final String path) { final IPath validPath = (path == null) ? Path.ROOT : new Path(path); testSuite.getModel().setVariable(identifier, content, description, validPath); }
Source:
private Map<String, Guid> getAllDestinationInterfacesIdByName() { if (allDestinationInterfacesIdByName == null) { allDestinationInterfacesIdByName = interfaceDao.getAllInterfacesForVds(getDestinationHostId()) .stream() .collect(Collectors.toMap(VdsNetworkInterface::getName, NetworkInterface::getId)); } return allDestinationInterfacesIdByName; }

Target:
private Map<String, Guid> getAllDestinationInterfacesIdByName() { if (allDestinationInterfacesIdByName == null) { allDestinationInterfacesIdByName = getUnfilteredDestinationInterfaces() .stream() .collect(Collectors.toMap(VdsNetworkInterface::getName, NetworkInterface::getId)); } return allDestinationInterfacesIdByName; }
Source:
public void testCheckAccessNullThreadGroup() { carbonSecurityManager = mock(CarbonSecurityManager.class); ThreadGroup threadGroup = null; assertNull(threadGroup); carbonSecurityManager.checkAccess(threadGroup); }

Target:
public void testCheckAccessNullThreadGroup() { System.setProperty("denied.system.properties", "mockDeniedProperty"); carbonSecurityManager = new CarbonSecurityManager(); ThreadGroup threadGroup = null; assertNull(threadGroup); carbonSecurityManager.checkAccess(threadGroup); }
Source:
public static <T> Digraph<T> buildFilteredDigraph(Digraph<T> initialGraph, Predicate<T> filterOut, Class<T> clazz) { Digraph<T> res = new Digraph<>(clazz); Set<T> toRemove = new LinkedHashSet<>(); for (Vertex<T> vertex : initialGraph.vertexList) { T id = vertex.id; if (!filterOut.test(id)) { res.addVertex(id); } else { toRemove.add(id); } } if (res.vertexList.size() < 2) { return res; } final Set<Edge<T>> edgesWithRemovedRef = new LinkedHashSet<>(); initialGraph.getEdges().forEach(edge -> { if (toRemove.contains(edge.from) || toRemove.contains(edge.to)) { edgesWithRemovedRef.add(edge); } else { res.addEdge(edge.from, edge.to); } }); for (T idToRemove : toRemove) { edgesWithRemovedRef.removeIf(edge -> edge.from == idToRemove && edge.to == idToRemove); Set<Edge<T>> incoming = new LinkedHashSet<>(); Set<Edge<T>> outgoing = new LinkedHashSet<>(); for (Edge<T> edge : edgesWithRemovedRef) { if (edge.from == idToRemove) { outgoing.add(edge); } if (edge.to == idToRemove) { incoming.add(edge); } } edgesWithRemovedRef.removeAll(incoming); edgesWithRemovedRef.removeAll(outgoing); incoming.forEach(incomingEdge -> outgoing.forEach(outgoingEdge -> { Edge<T> edge = new Edge<>(incomingEdge.from, outgoingEdge.to); if (toRemove.contains(edge.from) || toRemove.contains(edge.to)) { edgesWithRemovedRef.add(edge); } else { res.addEdge(edge.from, edge.to); } })); } if (!edgesWithRemovedRef.isEmpty()) { throw new IllegalStateException("There should be no remaining edge at this point."); } return res; }

Target:
public static <T> Digraph<T> buildFilteredDigraph(Digraph<T> initialGraph, Predicate<T> filterOut, Class<T> clazz) { Digraph<T> res = new Digraph<>(clazz); Set<T> toRemoveIds = new LinkedHashSet<>(); for (Vertex<T> vertex : initialGraph.vertexList) { T id = vertex.id; if (!filterOut.test(id)) { res.addVertex(id); } else { toRemoveIds.add(id); } } if (res.vertexList.size() < 2) { return res; } final Set<Edge<T>> edgesToReplace = new LinkedHashSet<>(); initialGraph.getEdges().forEach(edge -> { if (toRemoveIds.contains(edge.from) || toRemoveIds.contains(edge.to)) { edgesToReplace.add(edge); } else { res.addEdge(edge.from, edge.to); } }); for (T toRemove : toRemoveIds) { edgesToReplace.removeIf(edge -> edge.from == toRemove && edge.to == toRemove); Set<Edge<T>> incoming = edgesToReplace.stream().filter(edge -> edge.to == toRemove).collect(Collectors.toSet()); Set<Edge<T>> outgoing = edgesToReplace.stream().filter(edge -> edge.from == toRemove).collect(Collectors.toSet()); edgesToReplace.removeAll(incoming); edgesToReplace.removeAll(outgoing); incoming.forEach(incomingEdge -> outgoing.forEach(outgoingEdge -> { Edge<T> edge = new Edge<>(incomingEdge.from, outgoingEdge.to); if (toRemoveIds.contains(edge.from) || toRemoveIds.contains(edge.to)) { edgesToReplace.add(edge); } else { res.addEdge(edge.from, edge.to); } })); } if (!edgesToReplace.isEmpty()) { throw new IllegalStateException(edgesToReplace.size() + " edges are remaining at this point: " + edgesToReplace.toString() + "\nThere should be none. This indicates a bug in the graph filtering algorithm"); } return res; }
Source:
public String getWithSleep() throws InterruptedException { Thread.sleep(SLEEP_TIME); return "success"; }

Target:
public String getWithSleep() throws InterruptedException { TimeUnit.MILLISECONDS.sleep(SLEEP_TIME_IN_MILLIS); return "success"; }
Source:
public void display(OutputStream out) { final PrintWriter stdout; try { stdout = new PrintWriter(new BufferedWriter(new OutputStreamWriter(out, "UTF-8"))); } catch (UnsupportedEncodingException e) { throw new RuntimeException("JVM lacks UTF-8 encoding", e); } try { final Map<String, DashboardInfo> dashboards; if (level != null) { switch (level) { case PROJECT: final Project.NameKey projectName = new Project.NameKey(entityName); final ProjectState projectState = projectCache.get(projectName); DashboardInfo defaultInfo = findProjectDefaultDashboard(projectState); if (defaultDashboard) { dashboards = Maps.newTreeMap(); if (defaultInfo != null) { dashboards.put(defaultInfo.id, defaultInfo); } } else { dashboards = allDashboardsFor(projectState, defaultInfo.id); } break; default: throw new IllegalStateException("unsupported dashboard level: " + level); } } else { dashboards = Maps.newTreeMap(); } format.newGson().toJson(dashboards, new TypeToken<Map<String, DashboardInfo>>() {}.getType(), stdout); stdout.print('\n'); } finally { stdout.flush(); } }

Target:
public void display(OutputStream out) { final PrintWriter stdout; try { stdout = new PrintWriter(new BufferedWriter(new OutputStreamWriter(out, "UTF-8"))); } catch (UnsupportedEncodingException e) { throw new RuntimeException("JVM lacks UTF-8 encoding", e); } try { final Map<String, DashboardInfo> dashboards; if (level != null) { switch (level) { case PROJECT: final Project.NameKey projectName = new Project.NameKey(entityName); final ProjectState projectState = projectCache.get(projectName); DashboardInfo defaultInfo = findProjectDefaultDashboard(projectState); if (defaultDashboard) { dashboards = Maps.newTreeMap(); if (defaultInfo != null) { dashboards.put(defaultInfo.id, defaultInfo); } } else { dashboards = allDashboardsFor(projectState, defaultInfo != null ? defaultInfo.id : null); } break; default: throw new IllegalStateException("unsupported dashboard level: " + level); } } else { dashboards = Maps.newTreeMap(); } format.newGson().toJson(dashboards, new TypeToken<Map<String, DashboardInfo>>() {}.getType(), stdout); stdout.print('\n'); } finally { stdout.flush(); } }
Source:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; if (!FiltersHelper.isAuthenticated(req)) { chain.doFilter(request, response); String headerValue = req.getHeader("Authorization"); if (headerValue != null && headerValue.startsWith("Basic ")) { String credentials = headerValue.substring("Basic".length()); String userPass = new String(Base64.decodeBase64(credentials), Charset.defaultCharset().toString()); String[] creds = userPass.split(":", 2); if (creds != null && creds.length == 2) { handleCredentials(request, creds[0], creds[1], getSeparator(creds[0])); } } } chain.doFilter(request, response); }

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; if (!FiltersHelper.isAuthenticated(req)) { chain.doFilter(request, response); String headerValue = req.getHeader("Authorization"); if (headerValue != null && headerValue.startsWith("Basic ")) { String[] creds = new String( Base64.decodeBase64(headerValue.substring("Basic".length())), Charset.forName("UTF-8") ).split(":", 2); handleCredentials(request, creds); } } chain.doFilter(request, response); }
Source:
public ItemUseHandler getItemHandler() { return e -> { if (e.getClickedBlock().isPresent()) { Block block = e.getClickedBlock().get(); ItemStack item = e.getItem(); Player p = e.getPlayer(); if (!getID().equals("TEST_CLIMBING_PICK") && p.getLocation().distance(block.getLocation()) > 1.5) return; if (e.getClickedFace() == BlockFace.DOWN || e.getClickedFace() == BlockFace.UP) return; if (!users.contains(p.getUniqueId())) { Vector velocity = new Vector(1, 1, 1); if (!getID().equals("TEST_CLIMBING_PICK")) { velocity = p.getVelocity(); } Material mat = block.getType(); if (materialSpeeds.getValue().containsKey(mat.name())) { double launch = materialSpeeds.getValue().get(mat.name()); if (item.getEnchantments().containsKey(Enchantment.DIG_SPEED)) { launch += (item.getEnchantmentLevel(Enchantment.DIG_SPEED) * 0.2); } velocity = velocity.setY(velocity.getY() + launch); } users.add(p.getUniqueId()); Bukkit.getScheduler().runTaskLaterAsynchronously(SlimefunPlugin.instance, () -> users.remove(p.getUniqueId()), 4L); ClimbingPickLaunchEvent event = new ClimbingPickLaunchEvent(p, velocity, item); Bukkit.getPluginManager().callEvent(event); } } }; }

Target:
public ItemUseHandler getItemHandler() { return e -> { if (!e.getClickedBlock().isPresent()) return; Block block = e.getClickedBlock().get(); ItemStack item = e.getItem(); Player p = e.getPlayer(); if (p.getLocation().distanceSquared(block.getLocation()) > 2.25) return; if (e.getClickedFace() == BlockFace.DOWN || e.getClickedFace() == BlockFace.UP) return; if (!users.contains(p.getUniqueId())) { double launch = materialSpeeds.getOrDefault(block.getType(), 0D); Vector velocity = new Vector(0, 0, 0); if (launch > 0.05) { int efficiencyLevel = item.getEnchantments().getOrDefault(Enchantment.DIG_SPEED, 0); if (efficiencyLevel != 0){ launch += (efficiencyLevel * 0.2); } velocity.setY(launch); users.add(p.getUniqueId()); Bukkit.getScheduler().runTaskLater(SlimefunPlugin.instance(), () -> users.remove(p.getUniqueId()), 4L); } ClimbingPickLaunchEvent event = new ClimbingPickLaunchEvent(p, velocity, this, item, block); Bukkit.getPluginManager().callEvent(event); if (!event.isCancelled()) { p.setVelocity(event.getVelocity()); p.getWorld().playEffect(block.getLocation(), Effect.STEP_SOUND, 1); if (p.getGameMode() != GameMode.CREATIVE) { damageItem(p, e.getItem()); } } } }; }
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FieldType fieldType = (FieldType) o; return id != null ? id.equals(fieldType.id) : fieldType.id == null; }

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FieldType fieldType = (FieldType) o; return id != null ? id.equals(fieldType.id) : fieldType.id == null; }
Source:
public Command(String[] cmd, String[] envVars) { if (cmd != null) { this.cmd = new String[cmd.length]; System.arraycopy(cmd, 0, this.cmd, 0, cmd.length); } if (envVars != null) { this.envVars = new String[envVars.length]; System.arraycopy(envVars, 0, this.envVars, 0, envVars.length); } }

Target:
public Command(String[] cmd, String[] envVars) { if (cmd != null) { this.cmd = Arrays.copyOf(cmd, cmd.length); } if (envVars != null) { this.envVars = Arrays.copyOf(envVars, envVars.length); } }
Source:
public void startDownload(List<DiskImage> disks) { log.info("Start download for disks: " + Linq.getDiskAliases(disks)); List<ActionParametersBase> transferDiskImageParametersList = new ArrayList<>(); disks.forEach(disk -> transferDiskImageParametersList.add( DownloadImageHandler.createInitParams(disk))); Frontend.getInstance().runMultipleAction(ActionType.TransferDiskImage, transferDiskImageParametersList, callback()); }

Target:
public void startDownload(List<DiskImage> disks) { log.info("Start download for disks: " + Linq.getDiskAliases(disks)); List<ActionParametersBase> transferDiskImageParameters = new ArrayList<>(); disks.forEach(disk -> transferDiskImageParameters.add( DownloadImageHandler.createInitParams(disk))); Frontend.getInstance().runMultipleAction(ActionType.TransferDiskImage, transferDiskImageParameters, callback()); }
Source:
private int calculatePortalHeight() { for (height = 0; height < 21; ++height) { boolean flag = false; for (int i = 0; i < width; ++i) { Location location = offsetImmutable(bottomLeft, left.getOppositeFace(), i) .add(0, height, 0); Material material = location.getBlock().getType(); if (!canBuildThrough(material)) { flag = true; break; } if (material == Material.PORTAL) { ++portalBlockCount; } if (i == 0) { material = offsetImmutable(location, left, 1).getBlock().getType(); if (material != Material.OBSIDIAN) { flag = true; break; } } else if (i == width - 1) { material = offsetImmutable(location, left, -1).getBlock().getType(); if (material != Material.OBSIDIAN) { flag = true; break; } } } if (flag) { break; } } for (int j = 0; j < width; ++j) { if (offsetImmutable(bottomLeft, left, -j).add(0, height, 0).getBlock().getType() != Material.OBSIDIAN) { height = 0; break; } } if (height <= 21 && height >= 3) { return height; } else { bottomLeft = null; width = 0; height = 0; return 0; } }

Target:
private int calculatePortalHeight() { for (height = 0; height < MAX_PORTAL_WIDTH_HEIGHT; ++height) { boolean flag = false; for (int i = 0; i < width; ++i) { Location location = offsetImmutable(bottomLeft, left.getOppositeFace(), i) .add(0, height, 0); Material material = location.getBlock().getType(); if (!canBuildThrough(material)) { flag = true; break; } if (material == Material.PORTAL) { ++portalBlockCount; } if (i == 0) { material = offsetImmutable(location, left, 1).getBlock().getType(); if (material != Material.OBSIDIAN) { flag = true; break; } } else if (i == width - 1) { material = offsetImmutable(location, left, -1).getBlock().getType(); if (material != Material.OBSIDIAN) { flag = true; break; } } } if (flag) { break; } } for (int j = 0; j < width; ++j) { if (offsetImmutable(bottomLeft, left, -j).add(0, height, 0).getBlock().getType() != Material.OBSIDIAN) { height = 0; break; } } if (height <= MAX_PORTAL_WIDTH_HEIGHT && height >= MIN_PORTAL_HEIGHT) { return height; } bottomLeft = null; width = 0; height = 0; return 0; }