auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Object visit(ASTAdditiveExpression node, Object data) { Context context = (Context) data; node.childrenAccept(this, context); BinaryOperation current = null; List<String> symbols = node.getOperators(); LinkedList<ExpressionStatement> statements = new LinkedList<>(); for (int i = 0; i < symbols.size() + 1; i++) { statements.addFirst((ExpressionStatement) context.objectStack.pop()); } int i = 2; for (String symbol : symbols) { if (current == null) { current = new BinaryOperation(operationFrom(symbol), statements.get(0), statements.get(1)); } else { current = new BinaryOperation(operationFrom(symbol), current, statements.get(i)); i = i + 1; } } context.objectStack.push(current); node.setIrElement(current); return data; }

Target:
public Object visit(ASTAdditiveExpression node, Object data) { Context context = (Context) data; node.childrenAccept(this, context); List<OperatorType> operators = node.getOperators() .stream() .map(this::operationFrom) .collect(Collectors.toList()); List<ExpressionStatement> statements = operatorStatements(context, operators.size()); ExpressionStatement operation = assembleBinaryOperation(statements, operators); context.objectStack.push(operation); node.setIrElement(operation); return data; }
Source:
public Map act(Redirector redirector, SourceResolver resolver, Map objectModel, String source, Parameters parameters) throws Exception { org.dspace.core.Context context = ContextUtil.obtainContext(objectModel); context.abort(); return EMPTY_MAP; }

Target:
public Map act(Redirector redirector, SourceResolver resolver, Map objectModel, String source, Parameters parameters) throws Exception { ContextUtil.abortContext(ObjectModelHelper.getRequest(objectModel)); return EMPTY_MAP; }
Source:
public void dispose() { super.dispose(); for (IAction action : this.actions) { action.removePropertyChangeListener(listener); } }

Target:
public void dispose() { for (IAction action : this.actions) { action.removePropertyChangeListener(listener); } super.dispose(); }
Source:
public void fixedZkHosts() { Properties props = new Properties(); props.put(curatorHostKey, "hostA"); props.put(exhibitorHostsKey, "[]"); Injector injector = newInjector(props); injector.getInstance(CuratorFramework.class); EnsembleProvider ensembleProvider = injector.getInstance(EnsembleProvider.class); Assert.assertTrue( "EnsembleProvider should be FixedEnsembleProvider", ensembleProvider instanceof FixedEnsembleProvider ); Assert.assertEquals( "The connectionString should be 'hostA'", "hostA", ensembleProvider.getConnectionString() ); }

Target:
public void fixedZkHosts() { Properties props = new Properties(); props.put(curatorHostKey, "hostA"); Injector injector = newInjector(props); injector.getInstance(CuratorFramework.class); EnsembleProvider ensembleProvider = injector.getInstance(EnsembleProvider.class); Assert.assertTrue( "EnsembleProvider should be FixedEnsembleProvider", ensembleProvider instanceof FixedEnsembleProvider ); Assert.assertEquals( "The connectionString should be 'hostA'", "hostA", ensembleProvider.getConnectionString() ); }
Source:
public ClusterManager() { try { zeplServerHost = RemoteInterpreterUtils.findAvailableHostAddress(); String clusterAddr = zconf.getClusterAddress(); if (!StringUtils.isEmpty(clusterAddr)) { String cluster[] = clusterAddr.split(","); for (int i = 0; i < cluster.length; i++) { String[] parts = cluster[i].split(":"); String clusterHost = parts[0]; int clusterPort = Integer.valueOf(parts[1]); if (zeplServerHost.equalsIgnoreCase(clusterHost)) { raftServerPort = clusterPort; } Node node = Node.builder().withId(cluster[i]) .withAddress(Address.from(clusterHost, clusterPort)).build(); clusterNodes.add(node); raftAddressMap.put(MemberId.from(cluster[i]), Address.from(clusterHost, clusterPort)); clusterMemberIds.add(MemberId.from(cluster[i])); } } } catch (UnknownHostException e) { e.printStackTrace(); } catch (SocketException e) { e.printStackTrace(); return; } }

Target:
public ClusterManager() { try { zeplServerHost = RemoteInterpreterUtils.findAvailableHostAddress(); String clusterAddr = zconf.getClusterAddress(); if (!StringUtils.isEmpty(clusterAddr)) { String cluster[] = clusterAddr.split(","); for (int i = 0; i < cluster.length; i++) { String[] parts = cluster[i].split(":"); String clusterHost = parts[0]; int clusterPort = Integer.valueOf(parts[1]); if (zeplServerHost.equalsIgnoreCase(clusterHost)) { raftServerPort = clusterPort; } Node node = Node.builder().withId(cluster[i]) .withAddress(Address.from(clusterHost, clusterPort)).build(); clusterNodes.add(node); raftAddressMap.put(MemberId.from(cluster[i]), Address.from(clusterHost, clusterPort)); clusterMemberIds.add(MemberId.from(cluster[i])); } } } catch (UnknownHostException e) { LOGGER.error(e.getMessage()); } catch (SocketException e) { LOGGER.error(e.getMessage()); } }
Source:
public void shouldProvisionServiceAndIngressWhenNotFound() { Mockito.when( externalServiceExposureStrategy.getExternalPath(Mockito.anyString(), Mockito.any())) .thenReturn("some-server-path"); final int PORT = 8080; final String SERVER_PORT_NAME = "server-" + PORT; CommandImpl command = new CommandImpl("a", "a", "a", new PreviewUrlImpl(PORT, null), Collections.emptyMap()); KubernetesEnvironment env = KubernetesEnvironment.builder() .setCommands(singletonList(new CommandImpl(command))) .build(); assertTrue(env.getIngresses().isEmpty()); assertTrue(env.getServices().isEmpty()); previewUrlExposer.expose(env); assertEquals(env.getIngresses().size(), 1); assertEquals(env.getServices().size(), 1); Service provisionedService = env.getServices().values().iterator().next(); ServicePort provisionedServicePort = provisionedService.getSpec().getPorts().get(0); assertEquals(provisionedServicePort.getName(), SERVER_PORT_NAME); assertEquals(provisionedServicePort.getPort().intValue(), PORT); Ingress provisionedIngress = env.getIngresses().values().iterator().next(); IngressBackend provisionedIngressBackend = provisionedIngress.getSpec().getRules().get(0).getHttp().getPaths().get(0).getBackend(); assertEquals(provisionedIngressBackend.getServicePort().getStrVal(), SERVER_PORT_NAME); assertEquals( provisionedIngressBackend.getServiceName(), provisionedService.getMetadata().getName()); }

Target:
public void shouldProvisionServiceAndIngressWhenNotFound() throws InternalInfrastructureException { Mockito.when( externalServiceExposureStrategy.getExternalPath(Mockito.anyString(), Mockito.any())) .thenReturn("some-server-path"); final int PORT = 8080; final String SERVER_PORT_NAME = "server-" + PORT; CommandImpl command = new CommandImpl("a", "a", "a", new PreviewUrlImpl(PORT, null), Collections.emptyMap()); KubernetesEnvironment env = KubernetesEnvironment.builder() .setCommands(singletonList(new CommandImpl(command))) .setIngresses(new HashMap<>()) .setServices(new HashMap<>()) .build(); previewUrlExposer.expose(env); assertEquals(env.getIngresses().size(), 1); assertEquals(env.getServices().size(), 1); Service provisionedService = env.getServices().values().iterator().next(); ServicePort provisionedServicePort = provisionedService.getSpec().getPorts().get(0); assertEquals(provisionedServicePort.getName(), SERVER_PORT_NAME); assertEquals(provisionedServicePort.getPort().intValue(), PORT); Ingress provisionedIngress = env.getIngresses().values().iterator().next(); IngressBackend provisionedIngressBackend = provisionedIngress.getSpec().getRules().get(0).getHttp().getPaths().get(0).getBackend(); assertEquals(provisionedIngressBackend.getServicePort().getStrVal(), SERVER_PORT_NAME); assertEquals( provisionedIngressBackend.getServiceName(), provisionedService.getMetadata().getName()); }
Source:
protected IValidation[] getClonedNameValidators(Object object) { VM vm = ((ImportVmData) object).getVm(); final int length = AsyncDataProvider.IsWindowsOsType(vm.getOs()) ? UnitVmModel.WINDOWS_VM_NAME_MAX_LIMIT : UnitVmModel.NON_WINDOWS_VM_NAME_MAX_LIMIT; return new IValidation[] { new NotEmptyValidation(), new LengthValidation(length), new I18NNameValidation() { @Override protected String composeMessage() { return ConstantsManager.getInstance() .getMessages() .nameMustConataionOnlyAlphanumericChars(length); }; }, new UniqueNameValidator(assignedVmNames) }; }

Target:
protected IValidation[] getClonedNameValidators(Object object) { final int maxClonedNameLength = getMaxClonedNameLength(object); return new IValidation[] { new NotEmptyValidation(), new LengthValidation(maxClonedNameLength), new I18NNameValidation() { @Override protected String composeMessage() { return ConstantsManager.getInstance() .getMessages() .nameMustConataionOnlyAlphanumericChars(maxClonedNameLength); }; }, new UniqueClonedNameValidator(assignedVmNames) }; }
Source:
protected int getArtifactKeyCount(IQueryResult<IInstallableUnit> ius) { int count = 0; for (IInstallableUnit iInstallableUnit : ius) count += iInstallableUnit.getArtifacts().size(); return count; }

Target:
protected int getArtifactKeyCount(IQueryResult<IInstallableUnit> ius) { int count = 0; for (IInstallableUnit iu : ius) count += iu.getArtifacts().size(); return count; }
Source:
public IRoute chooseRoute(List<IRoute> routes) { final IRoute[] selectedRoute = new IRoute[1]; Display.getDefault().syncExec(() -> { ensureHasShell(); SelectRouteDialog routeDialog = new SelectRouteDialog(routes, shell); if (Dialog.OK == routeDialog.open()) { selectedRoute[0] = routeDialog.getSelectedRoute(); rememberChoice = routeDialog.isRememberChoice(); } }); return selectedRoute[0]; }

Target:
public IRoute chooseRoute(List<IRoute> routes) { final IRoute[] selectedRoute = new IRoute[1]; Display.getDefault().syncExec(() -> { SelectRouteDialog routeDialog = new SelectRouteDialog(routes, PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell()); if (Dialog.OK == routeDialog.open()) { selectedRoute[0] = routeDialog.getSelectedRoute(); rememberChoice = routeDialog.isRememberChoice(); } }); return selectedRoute[0]; }
Source:
private void ensureSize() { while (true) { long addressToRemove; Lock entryWriteLock; lruLock.lock(); try { if (currentSize > maxSize) { int hashCode = UNSAFE.getInt(firstAddress + 24); entryWriteLock = locks.getLockFromHashCode(hashCode).writeLock(); if (!entryWriteLock.tryLock()) { addressToRemove = 0; } else { addressToRemove = UNSAFE.getLong(firstAddress); } } else { break; } } finally { lruLock.unlock(); } if (addressToRemove == 0) { entryWriteLock.lock(); try { lruLock.lock(); try { if (currentSize > maxSize) { int hashCode = UNSAFE.getInt(firstAddress + 24); Lock innerLock = locks.getLockFromHashCode(hashCode).writeLock(); if (innerLock == entryWriteLock) { addressToRemove = UNSAFE.getLong(firstAddress); } else { addressToRemove = 0; } } else { break; } } finally { lruLock.unlock(); } } finally { if (addressToRemove == 0) { entryWriteLock.unlock(); } } } if (addressToRemove != 0) { if (trace) { log.tracef("Removing entry: %d due to eviction due to size %d being larger than maximum of %d", addressToRemove, currentSize, maxSize); } try { InternalCacheEntry<WrappedBytes, WrappedBytes> ice = offHeapEntryFactory.fromMemory(addressToRemove); performRemove(addressToRemove, offHeapEntryFactory.getKey(addressToRemove)); evictionManager.onEntryEviction(Collections.singletonMap(ice.getKey(), ice)); } finally { entryWriteLock.unlock(); } } } }

Target:
private void ensureSize() { while (true) { long addressToRemove; Lock entryWriteLock; lruLock.lock(); try { if (currentSize <= maxSize) { break; } int hashCode = UNSAFE.getInt(firstAddress + 24); entryWriteLock = locks.getLockFromHashCode(hashCode).writeLock(); if (!entryWriteLock.tryLock()) { addressToRemove = 0; } else { addressToRemove = UNSAFE.getLong(firstAddress); } } finally { lruLock.unlock(); } if (addressToRemove == 0) { entryWriteLock.lock(); try { lruLock.lock(); try { if (currentSize <= maxSize) { break; } int hashCode = UNSAFE.getInt(firstAddress + 24); Lock innerLock = locks.getLockFromHashCode(hashCode).writeLock(); if (innerLock == entryWriteLock) { addressToRemove = UNSAFE.getLong(firstAddress); } else { addressToRemove = 0; } } finally { lruLock.unlock(); } } finally { if (addressToRemove == 0) { entryWriteLock.unlock(); } } } if (addressToRemove != 0) { if (trace) { log.tracef("Removing entry: %d due to eviction due to size %d being larger than maximum of %d", addressToRemove, currentSize, maxSize); } try { InternalCacheEntry<WrappedBytes, WrappedBytes> ice = offHeapEntryFactory.fromMemory(addressToRemove); performRemove(addressToRemove, offHeapEntryFactory.getKey(addressToRemove)); evictionManager.onEntryEviction(Collections.singletonMap(ice.getKey(), ice)); } finally { entryWriteLock.unlock(); } } } }
Source:
public VeluxProduct(BCgetProducts.BCproduct productDescr) { this.name = new ProductName(productDescr.getName()); this.bridgeProductIndex = new ProductBridgeIndex(productDescr.getId()); String productTypeId = productDescr.getCategory().replaceAll("\\s", "_").toUpperCase(); try { this.typeId = ProductTypeId.valueOf(productTypeId); } catch (IllegalArgumentException iae) { logger.error( "PLEASE REPORT THIS TO MAINTAINER: VeluxProduct({},{}) has found an unregistered ProductTypeId.", productTypeId, productDescr.getTypeId()); } if (this.getTypeId().getTypeId() != productDescr.getTypeId()) { logger.error( "PLEASE REPORT THIS TO MAINTAINER: VeluxProduct({},{}) has found two different typeIds which differ ({} vs. {}.", productTypeId, productDescr.getTypeId(), this.getTypeId().getTypeId(), productDescr.getTypeId()); } }

Target:
public VeluxProduct(BCgetProducts.BCproduct productDescr) { this.name = new ProductName(productDescr.getName()); this.bridgeProductIndex = new ProductBridgeIndex(productDescr.getId()); String productTypeId = productDescr.getCategory().replaceAll("\\s", "_").toUpperCase(); try { this.typeId = ProductTypeId.valueOf(productTypeId); } catch (IllegalArgumentException iae) { logger.warn( "Please report this to maintainer: VeluxProduct({},{}) has found an unregistered ProductTypeId.", productTypeId, productDescr.getTypeId()); } if (this.getTypeId().getTypeId() != productDescr.getTypeId()) { logger.warn( "Please report this to maintainer: VeluxProduct({},{}) has found two different typeIds which differ ({} vs. {}.", productTypeId, productDescr.getTypeId(), this.getTypeId().getTypeId(), productDescr.getTypeId()); } }
Source:
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { int rows = DEFAULT_ROWS; if (System.getProperty(THRESHOLD_ALARM_COUNT_PROPERTY) != null) { try { rows = Integer.valueOf(System.getProperty(THRESHOLD_ALARM_COUNT_PROPERTY)); } catch (NumberFormatException e) { } } String ueiFilter = System.getProperty(UEI_FILTER_PROPERTY, UEI_DEFAULT_FILTER); Filter[] filters = new Filter[1]; filters[0] = new PartialUEIFilter(ueiFilter); m_alarmCriteria = new AlarmCriteria(filters, SortStyle.ID, AcknowledgeType.UNACKNOWLEDGED, rows, 0); ArrayList<OnmsAlarm> thresholdAlarmList = new ArrayList<OnmsAlarm>(Arrays.asList(m_webAlarmRepository.getMatchingAlarms(AlarmUtil.getOnmsCriteria(m_alarmCriteria)))); int moreCount = thresholdAlarmList.size() - rows; ModelAndView modelAndView = new ModelAndView(getSuccessView()); if (rows == 0 || thresholdAlarmList.size() < rows) { modelAndView.addObject("thresholdAlarmList", thresholdAlarmList); } else { modelAndView.addObject("thresholdAlarmList", thresholdAlarmList.subList(0, rows)); } modelAndView.addObject("moreCount", moreCount); modelAndView.addObject("ueiFilter",ueiFilter); return modelAndView; }

Target:
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { int rows = Integer.getInteger(THRESHOLD_ALARM_COUNT_PROPERTY, DEFAULT_ROWS); String ueiFilter = System.getProperty(UEI_FILTER_PROPERTY, UEI_DEFAULT_FILTER); Filter[] filters = new Filter[1]; filters[0] = new PartialUEIFilter(ueiFilter); m_alarmCriteria = new AlarmCriteria(filters, SortStyle.ID, AcknowledgeType.UNACKNOWLEDGED, rows + 1, 0); ArrayList<OnmsAlarm> thresholdAlarmList = new ArrayList<OnmsAlarm>(Arrays.asList(m_webAlarmRepository.getMatchingAlarms(AlarmUtil.getOnmsCriteria(m_alarmCriteria)))); int moreCount = thresholdAlarmList.size() - rows; ModelAndView modelAndView = new ModelAndView(getSuccessView()); if (rows == 0 || thresholdAlarmList.size() < rows) { modelAndView.addObject("thresholdAlarmList", thresholdAlarmList); } else { modelAndView.addObject("thresholdAlarmList", thresholdAlarmList.subList(0, rows)); } modelAndView.addObject("moreCount", moreCount); modelAndView.addObject("ueiFilter",ueiFilter); return modelAndView; }
Source:
@Config(reportSdk = GINGERBREAD) @Test public void allowExpiredSetsCacheControl() throws Exception { server.enqueue(new MockResponse()); loader.load(URL, false); RecordedRequest request1 = server.takeRequest(); assertThat(request1.getHeader("Cache-Control")).isNull(); server.enqueue(new MockResponse()); loader.load(URL, true); RecordedRequest request2 = server.takeRequest(); assertThat(request2.getHeader("Cache-Control")).isEqualTo("only-if-cached"); }

Target:
@Test public void allowExpiredSetsCacheControl() throws Exception { server.enqueue(new MockResponse()); loader.load(URL, false); RecordedRequest request1 = server.takeRequest(); assertThat(request1.getHeader("Cache-Control")).isNull(); server.enqueue(new MockResponse()); loader.load(URL, true); RecordedRequest request2 = server.takeRequest(); assertThat(request2.getHeader("Cache-Control")).isEqualTo("only-if-cached"); }
Source:
public void ParserCorrectlyConvertsLocationToPrettyJSON() throws Exception { Parser parser = new Parser(null); String expected = "{\n" + " \"_type\" : \"location\",\n" + " \"batt\" : 30,\n" + " \"acc\" : 10,\n" + " \"vac\" : 0,\n" + " \"lat\" : 50.1,\n" + " \"lon\" : 60.2,\n" + " \"alt\" : 20.0,\n" + " \"tst\" : 123456789,\n" + " \"conn\" : \"TestConn\"\n" + "}"; assertEquals(expected, parser.toJsonPlainPretty(messageLocation)); }

Target:
public void ParserCorrectlyConvertsLocationToPrettyJSON() throws Exception { Parser parser = new Parser(null); String expected = getResourceFileAsString("prettyLocation.json"); assertEquals(expected, parser.toJsonPlainPretty(messageLocation)); }
Source:
public void clearData() { try { setData(NULL_CERT); } catch (CertificateException e) { e.printStackTrace(); } }

Target:
public void clearData() { try { setData(NULL_CERT); } catch (CertificateException e) { log.warn("Could not clear certificate data: " + e.getMessage(), e); } }
Source:
private void reportFailure(Failure failure) { String trace = failure.getTrace(); if (trace.length() > MAX_TRACE_SIZE) { trace = failure.getTrimmedTrace(); if (trace.length() > MAX_TRACE_SIZE) { Log.w( TAG, String.format("Stack trace too long, trimmed to first %s characters.", MAX_TRACE_SIZE)); trace = trace.substring(0, MAX_TRACE_SIZE) + "\n"; } } testResult.putString(REPORT_KEY_STACK, trace); testResult.putString( Instrumentation.REPORT_KEY_STREAMRESULT, String.format( "\nError in %s:\n%s", failure.getDescription().getDisplayName(), failure.getTrace())); }

Target:
private void reportFailure(Failure failure) { String trace = failure.getTrace(); if (trace.length() > MAX_TRACE_SIZE) { Log.w( TAG, String.format("Stack trace too long, trimmed to first %s characters.", MAX_TRACE_SIZE)); trace = trace.substring(0, MAX_TRACE_SIZE) + "\n"; } testResult.putString(REPORT_KEY_STACK, trace); testResult.putString( Instrumentation.REPORT_KEY_STREAMRESULT, String.format( "\nError in %s:\n%s", failure.getDescription().getDisplayName(), failure.getTrace())); }
Source:
private boolean isInvalidCommandTypeError(Throwable throwable) { String message = ""; if (throwable.getMessage() != null) { message = throwable.getMessage(); } else if (throwable.getCause() != null) { message = throwable.getCause().getMessage(); } return message.contains("Invalid command type"); }

Target:
private boolean isInvalidCommandTypeError(Throwable throwable) { String message = ""; if (throwable.getMessage() != null) { message = throwable.getMessage(); } else if (throwable.getCause() != null && throwable.getCause().getMessage() != null) { message = throwable.getCause().getMessage(); } return message.contains("Invalid command type"); }
Source:
public static File extractTestMappingsZip(File testMappingsZip) { File testMappingsDir = null; try { testMappingsDir = ZipUtil2.extractZipToTemp(testMappingsZip, TEST_MAPPINGS_ZIP); } catch (IOException e) { RuntimeException runtimeException = new RuntimeException( String.format( "IO error (%s) when extracting test mappings zip (%s)", e.getMessage(), testMappingsZip.getAbsolutePath()), e); throw runtimeException; } return testMappingsDir; }

Target:
public static File extractTestMappingsZip(File testMappingsZip) { File testMappingsDir = null; try { testMappingsDir = ZipUtil2.extractZipToTemp(testMappingsZip, TEST_MAPPINGS_ZIP); } catch (IOException e) { throw new RuntimeException( String.format( "IO exception (%s) when extracting test mappings zip (%s)", e.getMessage(), testMappingsZip.getAbsolutePath()), e); } return testMappingsDir; }
Source:
public String getTaskServerLogsByTag(String jobId, String taskTag) throws UnknownJobException, NotConnectedException, PermissionException { JobId id = JobIdImpl.makeJobId(jobId); frontendState.checkJobOwner("getTaskServerLogs", id, "You do not have permission to get the task logs of this job"); Set<TaskId> tasksIds = new HashSet<>(); for (TaskState taskState : frontendState.getJobState(id).getTaskByTag(taskTag)) { tasksIds.add(taskState.getId()); } return ServerJobAndTaskLogs.getJobLog(id, tasksIds); }

Target:
public String getTaskServerLogsByTag(String jobId, String taskTag) throws UnknownJobException, NotConnectedException, PermissionException { JobId id = JobIdImpl.makeJobId(jobId); frontendState.checkJobOwner("getTaskServerLogsByTag", id, "You do not have permission to get the task logs of this job"); List<TaskState> lTaskState = frontendState.getJobState(id).getTasksByTag(taskTag); Set<TaskId> tasksIds = new HashSet<>(lTaskState.size()); for (TaskState taskState : lTaskState) { tasksIds.add(taskState.getId()); } return ServerJobAndTaskLogs.getJobLog(id, tasksIds); }
Source:
private Optional<OnmsNode> getNode(String nodeCriteria) { if (nodeCriteria == null || nodeCriteria.trim().isEmpty()) { return Optional.empty(); } try { return Optional.ofNullable(nodeDao.get(nodeCriteria)); } catch (Exception e) { LOG.error("error while trying to match node from {}", nodeCriteria); } return Optional.empty(); }

Target:
private Optional<OnmsNode> getNode(String nodeCriteria) { if (nodeCriteria == null || nodeCriteria.trim().isEmpty()) { return Optional.empty(); } try { return Optional.ofNullable(nodeDao.get(nodeCriteria)); } catch (Exception e) { LOG.error("Error while trying to load node for criteria: {}. No node will be returned.", nodeCriteria, e); } return Optional.empty(); }
Source:
public String getEntityTypeAsString() { return DEFAULT_DISPLAY_NAME; }

Target:
public String getEntityTypeAsString() { return ATTRIBUTE_NAME; }
Source:
public static boolean contentEqualsIgnoreEOL(final Reader input1, final Reader input2) throws IOException { if (input1 == input2) { return true; } final BufferedReader br1 = toBufferedReader(input1); final BufferedReader br2 = toBufferedReader(input2); String line1 = br1.readLine(); String line2 = br2.readLine(); while (line1 != null && line1.equals(line2)) { line1 = br1.readLine(); line2 = br2.readLine(); } return line1 == null && line2 == null; }

Target:
public static boolean contentEqualsIgnoreEOL(final Reader input1, final Reader input2) throws IOException { if (input1 == input2) { return true; } final BufferedReader br1 = toBufferedReader(input1); final BufferedReader br2 = toBufferedReader(input2); String line1 = br1.readLine(); String line2 = br2.readLine(); while (line1 != null && line1.equals(line2)) { line1 = br1.readLine(); line2 = br2.readLine(); } return Objects.equals(line1, line2); }
Source:
protected EntitySpec<?> getMemberSpec() { EntitySpec<?> result = super.getMemberSpec(); if (result != null) return result; return EntitySpec.create(RiakNode.class); }

Target:
protected EntitySpec<?> getMemberSpec() { return getConfig(MEMBER_SPEC, EntitySpec.create(RiakNode.class)); }
Source:
public String getContainerName() { return URLParser.parse(this.azureBlobStorage.getUrl(), logger).getContainerName(); }

Target:
public final String getContainerName() { return URLParser.parse(this.azureBlobStorage.getUrl(), logger).getContainerName(); }
Source:
public void injectMocks() { Assert.assertNotNull(target.bar); }

Target:
public void injectMocks() { Assert.assertEquals(foo, target.getFoo()); Assert.assertNotNull(target.getBar()); }
Source:
private State createState(Class<? extends Item> itemType, String transformedResponse) { try { if (itemType.isAssignableFrom(SwitchItem.class)) { int value = Math.round(Float.parseFloat(transformedResponse)); if (value > 0) return OnOffType.ON; else return OnOffType.OFF; } else if (itemType.isAssignableFrom(DimmerItem.class)) { return new PercentType(Math.round(Float .parseFloat(transformedResponse))); } else if (itemType.isAssignableFrom(ContactItem.class)) { int value = Math.round(Float.parseFloat(transformedResponse)); if (value > 0) return OpenClosedType.OPEN; else return OpenClosedType.CLOSED; } else if (itemType.isAssignableFrom(NumberItem.class)) { return DecimalType.valueOf(transformedResponse); } else { return StringType.valueOf(transformedResponse); } } catch (Exception e) { logger.debug("Couldn't create state of type '{}' for value '{}'", itemType, transformedResponse); return StringType.valueOf(transformedResponse); } }

Target:
private State createState(Class<? extends Item> itemType, String transformedResponse) { try { if (itemType.isAssignableFrom(SwitchItem.class)) { int value = Math.round(Float.parseFloat(transformedResponse)); if (value > 0) { return OnOffType.ON; } else { return OnOffType.OFF; } } else if (itemType.isAssignableFrom(DimmerItem.class)) { return new PercentType(Math.round(Float.parseFloat(transformedResponse))); } else if (itemType.isAssignableFrom(ContactItem.class)) { int value = Math.round(Float.parseFloat(transformedResponse)); if (value > 0) { return OpenClosedType.OPEN; } else { return OpenClosedType.CLOSED; } } else if (itemType.isAssignableFrom(NumberItem.class)) { return DecimalType.valueOf(transformedResponse); } else { return StringType.valueOf(transformedResponse); } } catch (Exception e) { logger.debug("Couldn't create state of type '{}' for value '{}'", itemType, transformedResponse); return StringType.valueOf(transformedResponse); } }
Source:
public Fragment getItem(int pos) { CourseComponent unit = getUnit(pos); CourseUnitFragment unitFragment; if (unit instanceof VideoBlockModel) { unitFragment = CourseUnitVideoFragment.newInstance((VideoBlockModel) unit); } else if (!unit.isMultiDevice()) { unitFragment = CourseUnitMobileNotSupportedFragment.newInstance(unit); } else if (unit.getType() != BlockType.VIDEO && unit.getType() != BlockType.HTML && unit.getType() != BlockType.OTHERS && unit.getType() != BlockType.DISCUSSION && unit.getType() != BlockType.PROBLEM) { unitFragment = CourseUnitEmptyFragment.newInstance(unit); } else if (unit instanceof HtmlBlockModel) { if (!NetworkUtil.isConnected(CourseUnitNavigationActivity.this)) { unitFragment = CourseUnitNotAvailableFragment.newInstance(unit); } else { unitFragment = CourseUnitWebviewFragment.newInstance((HtmlBlockModel) unit); } } else { unitFragment = CourseUnitMobileNotSupportedFragment.newInstance(unit); } unitFragment.setHasComponentCallback(CourseUnitNavigationActivity.this); return unitFragment; }

Target:
public Fragment getItem(int pos) { CourseComponent unit = getUnit(pos); CourseUnitFragment unitFragment; if (unit instanceof VideoBlockModel) { unitFragment = CourseUnitVideoFragment.newInstance((VideoBlockModel) unit); } else if (!unit.isMultiDevice()) { unitFragment = CourseUnitMobileNotSupportedFragment.newInstance(unit); } else if (unit.getType() != BlockType.VIDEO && unit.getType() != BlockType.HTML && unit.getType() != BlockType.OTHERS && unit.getType() != BlockType.DISCUSSION && unit.getType() != BlockType.PROBLEM) { unitFragment = CourseUnitEmptyFragment.newInstance(unit); } else if (unit instanceof HtmlBlockModel) { unitFragment = CourseUnitWebviewFragment.newInstance((HtmlBlockModel) unit); } else { unitFragment = CourseUnitMobileNotSupportedFragment.newInstance(unit); } unitFragment.setHasComponentCallback(CourseUnitNavigationActivity.this); return unitFragment; }
Source:
Map<String, String> processJsonInputs(List<CompilerInput> inputsToProcess) { RewriteJsonToModule rewriteJson = new RewriteJsonToModule(this); for (CompilerInput input : inputsToProcess) { if (!input.getSourceFile().getOriginalPath().endsWith(".json")) { continue; } input.setCompiler(this); try { input.getSourceFile().setCode("(" + input.getSourceFile().getCode() + ")"); } catch (Exception e) { continue; } Node root = input.getAstRoot(this); if (root == null) { continue; } rewriteJson.process(null, root); } return rewriteJson.getPackageJsonMainEntries(); }

Target:
Map<String, String> processJsonInputs(List<CompilerInput> inputsToProcess) { RewriteJsonToModule rewriteJson = new RewriteJsonToModule(this); for (CompilerInput input : inputsToProcess) { if (!input.getSourceFile().getOriginalPath().endsWith(".json")) { continue; } input.setCompiler(this); try { input.getSourceFile().setCode("(" + input.getSourceFile().getCode() + ")"); } catch (IOException e) { this.getErrorManager().report(CheckLevel.ERROR, JSError.make(AbstractCompiler.READ_ERROR, input.getSourceFile().getOriginalPath())); continue; } Node root = input.getAstRoot(this); rewriteJson.process(null, root); } return rewriteJson.getPackageJsonMainEntries(); }
Source:
public List<FeatureDetails> getAllFeatures() { List<FeatureDetails> features = new ArrayList<FeatureDetails>(); try { for (Feature feature : featuresService.listFeatures()) { if (isPermittedToViewFeature(feature.getName())) { features.add(getFeatureView(feature)); } } } catch (Exception ex) { LOGGER.warn("Could not obtain all features.", ex); } return features; }

Target:
public List<FeatureDetails> getAllFeatures() { List<FeatureDetails> features = new ArrayList<>(); try { for (Feature feature : featuresService.listFeatures()) { if (isPermittedToViewFeature(feature.getName())) { features.add(getFeatureView(feature)); } } } catch (Exception ex) { LOGGER.warn("Could not obtain all features.", ex); } return features; }
Source:
public static List<Entity> generateBAForNova(AtBScenario scenario, List<Entity> starUnits, String factionCode, int skill, int quality, Campaign campaign) { List<Entity> transportedUnits = new ArrayList<>(); if(!Faction.getFaction(factionCode).isClan() && (starUnits.size() != 5)) { return transportedUnits; } int roll = Compute.d6(2); int novaTarget = 8; if (factionCode.equals("CHH") || factionCode.equals("CSL")) { novaTarget = 6; } else if (factionCode.equals("CBS")) { novaTarget = 13; } if(roll < novaTarget) { return transportedUnits; } Entity actualTransport = null; for(Entity transport : starUnits) { if(transport instanceof Mech && transport.isOmni()) { if((actualTransport == null) || (actualTransport.getWalkMP() < transport.getWalkMP())) { actualTransport = transport; } } } if(actualTransport == null) { return transportedUnits; } UnitGeneratorParameters params = new UnitGeneratorParameters(); params.setFaction(factionCode); params.setQuality(quality); params.setYear(campaign.getGameYear()); params.addMissionRole(MissionRole.MECHANIZED_BA); params.setWeightClass(UNIT_WEIGHT_UNSPECIFIED); Entity transportedUnit = generateTransportedBAUnit(params, IUnitGenerator.NO_WEIGHT_LIMIT, skill, campaign); transportedUnit.setDeployRound(actualTransport.getDeployRound()); scenario.addTransportRelationship(actualTransport.getExternalIdAsString(), transportedUnit.getExternalIdAsString()); transportedUnits.add(transportedUnit); return transportedUnits; }

Target:
public static List<Entity> generateBAForNova(AtBScenario scenario, List<Entity> starUnits, String factionCode, int skill, int quality, Campaign campaign) { List<Entity> transportedUnits = new ArrayList<>(); if(!Faction.getFaction(factionCode).isClan() && (starUnits.size() != 5)) { return transportedUnits; } int roll = Compute.d6(2); int novaTarget = 8; if (factionCode.equals("CHH") || factionCode.equals("CSL")) { novaTarget = 6; } else if (factionCode.equals("CBS")) { novaTarget = 13; } if(roll < novaTarget) { return transportedUnits; } Entity actualTransport = null; for(Entity transport : starUnits) { if(transport instanceof Mech && transport.isOmni()) { if((actualTransport == null) || (actualTransport.getWalkMP() < transport.getWalkMP())) { actualTransport = transport; } } } if(actualTransport == null) { return transportedUnits; } UnitGeneratorParameters params = new UnitGeneratorParameters(); params.setFaction(factionCode); params.setQuality(quality); params.setYear(campaign.getGameYear()); params.addMissionRole(MissionRole.MECHANIZED_BA); params.setWeightClass(UNIT_WEIGHT_UNSPECIFIED); Entity transportedUnit = generateTransportedBAUnit(params, IUnitGenerator.NO_WEIGHT_LIMIT, skill, campaign); if(transportedUnit == null) { return transportedUnits; } transportedUnit.setDeployRound(actualTransport.getDeployRound()); scenario.addTransportRelationship(actualTransport.getExternalIdAsString(), transportedUnit.getExternalIdAsString()); transportedUnits.add(transportedUnit); return transportedUnits; }
Source:
private static SegmentElements parse(String dataSource, String identifier) { if (!identifier.startsWith(dataSource + DataSegment.delimiter)) { return null; } String remaining = identifier.substring(dataSource.length() + 1); String[] splits = remaining.split(DataSegment.delimiter); if (splits.length < 2) { return null; } DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); DateTime start = formatter.parseDateTime(splits[0]); DateTime end = formatter.parseDateTime(splits[1]); String version = splits.length > 2 ? splits[2] : null; String trail = splits.length > 3 ? join(splits, DataSegment.delimiter, 3, splits.length) : null; return new SegmentElements( dataSource, new Interval(start.getMillis(), end.getMillis()), version, trail ); }

Target:
private static SegmentIdentifierParts parse(String dataSource, String identifier) { if (!identifier.startsWith(String.format("%s_", dataSource))) { LOGGER.info("Invalid identifier %s", identifier); return null; } String remaining = identifier.substring(dataSource.length() + 1); String[] splits = remaining.split(DataSegment.delimiter); if (splits.length < 3) { LOGGER.info("Invalid identifier %s", identifier); return null; } DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); DateTime start = formatter.parseDateTime(splits[0]); DateTime end = formatter.parseDateTime(splits[1]); String version = splits[2]; String trail = splits.length > 3 ? join(splits, DataSegment.delimiter, 3, splits.length) : null; return new SegmentIdentifierParts( dataSource, new Interval(start.getMillis(), end.getMillis()), version, trail ); }
Source:
public CompletionStage<?> invokeAsync(ComponentRegistry componentRegistry) throws Throwable { final boolean trace = log.isTraceEnabled(); LogFactory.pushNDC(cacheName, trace); try { if (applyState) { StateConsumer stateConsumer = componentRegistry.getStateTransferManager().getStateConsumer(); return (CompletionStage) stateConsumer.applyState(getOrigin(), topologyId, pushTransfer, stateChunks); } else { StateReceiver stateReceiver = componentRegistry.getConflictManager().running().getStateReceiver(); stateReceiver.receiveState(getOrigin(), topologyId, stateChunks); } return CompletableFutures.completedNull(); } finally { LogFactory.popNDC(trace); } }

Target:
public CompletionStage<?> invokeAsync(ComponentRegistry componentRegistry) throws Throwable { final boolean trace = log.isTraceEnabled(); LogFactory.pushNDC(cacheName, trace); try { if (applyState) { StateConsumer stateConsumer = componentRegistry.getStateTransferManager().getStateConsumer(); return stateConsumer.applyState(getOrigin(), topologyId, pushTransfer, stateChunks); } else { StateReceiver stateReceiver = componentRegistry.getConflictManager().running().getStateReceiver(); stateReceiver.receiveState(getOrigin(), topologyId, stateChunks); } return CompletableFutures.completedNull(); } finally { LogFactory.popNDC(trace); } }
Source:
public Page getOutput() { if (finished) { return null; } if (unfinishedWork != null) { boolean workDone = unfinishedWork.process(); aggregationBuilder.updateMemory(); if (!workDone) { return null; } unfinishedWork = null; } if (outputPages == null) { if (finishing) { if (!inputProcessed && produceDefaultOutput) { finished = true; return getGlobalAggregationOutput(); } if (aggregationBuilder == null) { finished = true; return null; } } if (!finishing && (aggregationBuilder == null || !aggregationBuilder.isFull()) && pendingInput == null) { return null; } outputPages = aggregationBuilder.buildResult(); } if (!outputPages.process()) { return null; } if (outputPages.isFinished()) { resetAggregationBuilder(); return null; } return outputPages.getResult(); }

Target:
public Page getOutput() { if (finished) { return null; } if (unfinishedWork != null) { boolean workDone = unfinishedWork.process(); aggregationBuilder.updateMemory(); if (!workDone) { return null; } unfinishedWork = null; } if (outputPages == null) { if (finishing) { if (!inputProcessed && produceDefaultOutput) { finished = true; return getGlobalAggregationOutput(); } if (aggregationBuilder == null) { finished = true; return null; } } if (!finishing && (aggregationBuilder == null || !aggregationBuilder.isFull())) { return null; } outputPages = aggregationBuilder.buildResult(); } if (!outputPages.process()) { return null; } if (outputPages.isFinished()) { closeAggregationBuilder(); return null; } return outputPages.getResult(); }
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AsyncTaskEntity other = (AsyncTaskEntity) obj; return ObjectUtils.objectsEqual(taskId, other.taskId) && ObjectUtils.objectsEqual(entityId, other.entityId) && ObjectUtils.objectsEqual(entityType, other.entityType); }

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } AsyncTaskEntity other = (AsyncTaskEntity) obj; return ObjectUtils.objectsEqual(taskId, other.taskId) && ObjectUtils.objectsEqual(entityId, other.entityId) && ObjectUtils.objectsEqual(entityType, other.entityType); }
Source:
public Response get(@PathParam("path") String path, @QueryParam("command") String commandStr) { ZooKeeperCommand cmd; try { cmd = ZooKeeperCommand.valueOf(commandStr); } catch (Exception e) { return badRequest("Invalid ZooKeeper command: " + commandStr); } ServerContext _serverContext = (ServerContext) _application.getProperties().get(ContextPropertyKeys.SERVER_CONTEXT.name()); _zkBaseDataAccessor = _serverContext.getByteArrayZkBaseDataAccessor(); path = "/" + path; switch (cmd) { case exists: return exists(path); case getBinaryData: return getData(path, cmd); case getStringData: return getData(path, cmd); case getChildren: return getChildren(path); default: LOG.error("Unsupported command :" + commandStr); return badRequest("Unsupported command :" + commandStr); } }

Target:
public Response get(@PathParam("path") String path, @QueryParam("command") String commandStr) { ZooKeeperCommand cmd = getZooKeeperCommandIfPresent(commandStr); if (cmd == null) { return badRequest("Invalid ZooKeeper command: " + commandStr); } ServerContext _serverContext = (ServerContext) _application.getProperties().get(ContextPropertyKeys.SERVER_CONTEXT.name()); _zkBaseDataAccessor = _serverContext.getByteArrayZkBaseDataAccessor(); path = "/" + path; if (!isPathValid(path)) { String errMsg = "The given path is not a valid ZooKeeper path: " + path; LOG.info(errMsg); return badRequest(errMsg); } switch (cmd) { case exists: return exists(_zkBaseDataAccessor, path); case getBinaryData: return getBinaryData(_zkBaseDataAccessor, path); case getStringData: return getStringData(_zkBaseDataAccessor, path); case getChildren: return getChildren(_zkBaseDataAccessor, path); default: String errMsg = "Unsupported command: " + commandStr; LOG.error(errMsg); return badRequest(errMsg); } }
Source:
public void fetchesRawContent() throws Exception { final String raw = "the raw"; final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple(HttpURLConnection.HTTP_OK, raw) ).start(); final InputStream stream = new RtContent( new ApacheRequest(container.home()), this.repo(), "raw" ).raw(); try { MatcherAssert.assertThat( IOUtils.toString(stream), Matchers.is(raw) ); MatcherAssert.assertThat( container.take().headers().get(HttpHeaders.ACCEPT).get(0), Matchers.is("application/vnd.github.v3.raw") ); } finally { stream.close(); container.stop(); } }

Target:
public void fetchesRawContent() throws Exception { final String raw = "the raw \u20ac"; final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple(HttpURLConnection.HTTP_OK, raw) ).start(); final InputStream stream = new RtContent( new ApacheRequest(container.home()), this.repo(), "raw" ).raw(); try { MatcherAssert.assertThat( IOUtils.toString(stream, Charsets.UTF_8), Matchers.is(raw) ); MatcherAssert.assertThat( container.take().headers().get(HttpHeaders.ACCEPT).get(0), Matchers.is("application/vnd.github.v3.raw") ); } finally { stream.close(); container.stop(); } }
Source:
public void phaseStarted(LocalSearchPhaseScope phaseScope) { super.phaseStarted(phaseScope); if (initialLevel != null) { for (double initialLevelLevel : ScoreUtils.extractLevelDoubles(initialLevel)) { if (initialLevelLevel < 0.0) { throw new IllegalArgumentException("The initial level (" + initialLevel + ") cannot have negative level (" + initialLevelLevel + ")."); } } initialLevelScoreLevels = ScoreUtils.extractLevelDoubles(initialLevel); levelScoreLevels = initialLevelScoreLevels; } else { initialLevelScoreLevelsNegative = ScoreUtils.extractLevelDoubles(phaseScope.getBestScore()); logger.info(phaseScope.getBestScore().toShortString()); levelScoreLevels = initialLevelScoreLevelsNegative; for (int i = 0; i < levelScoreLevels.length; i++) { if (Math.abs(levelScoreLevels[i]) < THRESHOLD) { logger.info(Double.toString(levelScoreLevels[i])); continue; } levelScoreLevels[i] = -levelScoreLevels[i]+5; logger.info(Double.toString(levelScoreLevels[i])); } } levelsLength = levelScoreLevels.length; }

Target:
public void phaseStarted(LocalSearchPhaseScope phaseScope) { super.phaseStarted(phaseScope); if (initialWaterLevel != null) { for (double initialLevelLevel : ScoreUtils.extractLevelDoubles(initialWaterLevel)) { if (initialLevelLevel < 0.0) { throw new IllegalArgumentException("The initial level (" + initialWaterLevel + ") cannot have negative level (" + initialLevelLevel + ")."); } } currentWaterLevel = initialWaterLevel; } else { currentWaterLevel = phaseScope.getBestScore().negate(); } }
Source:
final SQLException checkException(final SQLException sqle) { final String sqlState = sqle.getSQLState(); if (sqlState != null) { if (sqlState.startsWith("08") || SQL_ERRORS.contains(sqlState)) { if (delegate != ClosedConnection.CLOSED_CONNECTION) { LOGGER.warn("{} - Connection marked as broken because of SQLSTATE({}), ErrorCode({})", poolEntry.getPoolName(), delegate, sqlState, sqle.getErrorCode(), sqle); leakTask.cancel(); poolEntry.evict("(connection is broken)"); delegate = ClosedConnection.CLOSED_CONNECTION; } } else { final SQLException nse = sqle.getNextException(); if (nse != null && nse != sqle) { checkException(nse); } } } return sqle; }

Target:
final SQLException checkException(final SQLException sqle) { final String sqlState = sqle.getSQLState(); if (sqlState != null && delegate != ClosedConnection.CLOSED_CONNECTION) { if (sqlState.startsWith("08") || SQL_ERRORS.contains(sqlState)) { LOGGER.warn("{} - Connection marked as broken because of SQLSTATE({}), ErrorCode({})", poolEntry.getPoolName(), delegate, sqlState, sqle.getErrorCode(), sqle); leakTask.cancel(); poolEntry.evict("(connection is broken)"); delegate = ClosedConnection.CLOSED_CONNECTION; } else { final SQLException nse = sqle.getNextException(); if (nse != null && nse != sqle) { checkException(nse); } } } return sqle; }
Source:
public AzureBlobStorageImpl() { new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy(), new CookiePolicy()).build(); }

Target:
public AzureBlobStorageImpl() { this(new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy(), new CookiePolicy()).build()); }
Source:
private List<Vector3i> getBlockLocations(Location<World> worldLocation, int height, int width) { WorldBorder worldBorder = (WorldBorder) worldLocation.getExtent().getWorldBorder(); int worldBorderMinX = GenericMath.floor(worldBorder.minX()); int worldBorderMinZ = GenericMath.floor(worldBorder.minZ()); int worldBorderMaxX = GenericMath.floor(worldBorder.maxX()); int worldBorderMaxZ = GenericMath.floor(worldBorder.maxZ()); int worldMaxY = worldLocation.getExtent().getBlockMax().getY(); Vector3i vectorLocation = worldLocation.getBlockPosition(); int minY = GenericMath.clamp(vectorLocation.getY() - height, 0, worldMaxY); int maxY = GenericMath.clamp(vectorLocation.getY() + height, 0, worldMaxY); int minX = GenericMath.clamp(vectorLocation.getX() - width, worldBorderMinX, worldBorderMaxX); int maxX = GenericMath.clamp(vectorLocation.getX() + width, worldBorderMinX, worldBorderMaxX); int minZ = GenericMath.clamp(vectorLocation.getZ() - width, worldBorderMinZ, worldBorderMaxZ); int maxZ = GenericMath.clamp(vectorLocation.getZ() + width, worldBorderMinZ, worldBorderMaxZ); List<Vector3i> vectors = new ArrayList<>(); for (int x = minX; x <= maxX; x++) { for (int y = minY; y <= maxY; y++) { for (int z = minZ; z <= maxZ; z++) { vectors.add(new Vector3i(x, y, z)); } } } return vectors.stream() .sorted((first, second) -> Integer.compare(vectorLocation.distanceSquared(first), vectorLocation.distanceSquared(second))) .collect(Collectors.toList()); }

Target:
private Stream<Vector3i> getBlockLocations(Location<World> worldLocation, int height, int width) { WorldBorder worldBorder = (WorldBorder) worldLocation.getExtent().getWorldBorder(); int worldBorderMinX = GenericMath.floor(worldBorder.minX()); int worldBorderMinZ = GenericMath.floor(worldBorder.minZ()); int worldBorderMaxX = GenericMath.floor(worldBorder.maxX()); int worldBorderMaxZ = GenericMath.floor(worldBorder.maxZ()); int worldMaxY = worldLocation.getExtent().getBlockMax().getY(); Vector3i vectorLocation = worldLocation.getBlockPosition(); int minY = GenericMath.clamp(vectorLocation.getY() - height, 0, worldMaxY); int maxY = GenericMath.clamp(vectorLocation.getY() + height, 0, worldMaxY); int minX = GenericMath.clamp(vectorLocation.getX() - width, worldBorderMinX, worldBorderMaxX); int maxX = GenericMath.clamp(vectorLocation.getX() + width, worldBorderMinX, worldBorderMaxX); int minZ = GenericMath.clamp(vectorLocation.getZ() - width, worldBorderMinZ, worldBorderMaxZ); int maxZ = GenericMath.clamp(vectorLocation.getZ() + width, worldBorderMinZ, worldBorderMaxZ); List<Vector3i> vectors = new ArrayList<>(); for (int x = minX; x <= maxX; x++) { for (int y = minY; y <= maxY; y++) { for (int z = minZ; z <= maxZ; z++) { vectors.add(new Vector3i(x, y, z)); } } } return vectors.stream().sorted(Comparator.comparingInt(vectorLocation::distanceSquared)); }