List of usage examples for java.math BigInteger ZERO
BigInteger ZERO
To view the source code for java.math BigInteger ZERO.
Click Source Link
From source file:org.apache.blur.command.BaseCommandManager.java
protected BigInteger checkContents(FileStatus fileStatus, FileSystem fileSystem) throws IOException { if (fileStatus.isDir()) { LOG.debug("Scanning directory [{0}].", fileStatus.getPath()); BigInteger count = BigInteger.ZERO; Path path = fileStatus.getPath(); FileStatus[] listStatus = fileSystem.listStatus(path); for (FileStatus fs : listStatus) { count = count.add(checkContents(fs, fileSystem)); }//from w ww. j ava2 s . c om return count; } else { int hashCode = fileStatus.getPath().toString().hashCode(); long modificationTime = fileStatus.getModificationTime(); long len = fileStatus.getLen(); BigInteger bi = BigInteger.valueOf(hashCode) .add(BigInteger.valueOf(modificationTime).add(BigInteger.valueOf(len))); LOG.debug("File path hashcode [{0}], mod time [{1}], len [{2}] equals file code [{3}].", Integer.toString(hashCode), Long.toString(modificationTime), Long.toString(len), bi.toString(Character.MAX_RADIX)); return bi; } }
From source file:org.fenixedu.treasury.services.integration.erp.ERPExporter.java
private String generateERPFile(FinantialInstitution institution, DateTime fromDate, DateTime toDate, List<? extends FinantialDocument> allDocuments, Boolean generateAllCustomers, Boolean generateAllProducts, java.util.function.UnaryOperator<AuditFile> preProcessFunctionBeforeSerialize) { // Build SAFT-AuditFile AuditFile auditFile = new AuditFile(); // ThreadInformation information = // SaftThreadRegister.retrieveCurrentThreadInformation(); // Build SAFT-HEADER (Chapter 1 in AuditFile) Header header = this.createSAFTHeader(fromDate, toDate, institution, ERP_HEADER_VERSION_1_00_00); // SetHeader// w w w . ja v a 2 s . c o m auditFile.setHeader(header); // Build Master-Files oecd.standardauditfile_tax.pt_1.AuditFile.MasterFiles masterFiles = new oecd.standardauditfile_tax.pt_1.AuditFile.MasterFiles(); // SetMasterFiles auditFile.setMasterFiles(masterFiles); // Build SAFT-MovementOfGoods (Customer and Products are built inside) // ProductsTable (Chapter 2.4 in AuditFile) List<oecd.standardauditfile_tax.pt_1.Product> productList = masterFiles.getProduct(); Map<String, oecd.standardauditfile_tax.pt_1.Product> productMap = new HashMap<String, oecd.standardauditfile_tax.pt_1.Product>(); Set<String> productCodes = new HashSet<String>(); // ClientsTable (Chapter 2.2 in AuditFile) List<oecd.standardauditfile_tax.pt_1.Customer> customerList = masterFiles.getCustomer(); Map<String, oecd.standardauditfile_tax.pt_1.Customer> customerMap = new HashMap<String, oecd.standardauditfile_tax.pt_1.Customer>(); // Readd All Clients if needed if (generateAllCustomers) { logger.info("Reading all Customers in Institution " + institution.getCode()); Set<Customer> allCustomers = new HashSet<Customer>(); for (DebtAccount debt : institution.getDebtAccountsSet()) { allCustomers.add(debt.getCustomer()); } // Update the Total Objects Count // information.setTotalCounter(allCustomers.size() + // allProducts.size() + allDocuments.size() * 10); int i = 0; for (Customer customer : allCustomers) { oecd.standardauditfile_tax.pt_1.Customer saftCustomer = this .convertCustomerToSAFTCustomer(customer); // information.setCurrentCounter(information.getCurrentCounter() // + 1); customerMap.put(saftCustomer.getCustomerID(), saftCustomer); i++; if (i % 100 == 0) { logger.info("Processing " + i + "/" + allCustomers.size() + " Customers in Institution " + institution.getCode()); } } } // Readd All Products if needed if (generateAllProducts) { logger.info("Reading all Customers in Institution " + institution.getCode()); Set<Product> allProducts = institution.getAvailableProductsSet(); int i = 0; for (Product product : allProducts) { if (!productCodes.contains(product.getCode())) { oecd.standardauditfile_tax.pt_1.Product saftProduct = this.convertProductToSAFTProduct(product); productCodes.add(product.getCode()); productMap.put(saftProduct.getProductCode(), saftProduct); } i++; if (i % 100 == 0) { logger.info("Processing " + i + "/" + allProducts.size() + " Products in Institution " + institution.getCode()); } // information.setCurrentCounter(information.getCurrentCounter() // + 1); } } else { // information.setTotalCounter(allDocuments.size() * 10); // Update the Total Objects Count // information.setCurrentCounter(0); } // TaxTable (Chapter 2.5 in AuditFile) oecd.standardauditfile_tax.pt_1.TaxTable taxTable = new oecd.standardauditfile_tax.pt_1.TaxTable(); masterFiles.setTaxTable(taxTable); for (Vat vat : institution.getVatsSet()) { taxTable.getTaxTableEntry().add(this.convertVATtoTaxTableEntry(vat, institution)); } // Set MovementOfGoods in SourceDocuments(AuditFile) oecd.standardauditfile_tax.pt_1.SourceDocuments sourceDocuments = new oecd.standardauditfile_tax.pt_1.SourceDocuments(); auditFile.setSourceDocuments(sourceDocuments); SourceDocuments.SalesInvoices invoices = new SourceDocuments.SalesInvoices(); SourceDocuments.WorkingDocuments workingDocuments = new SourceDocuments.WorkingDocuments(); Payments paymentsDocuments = new Payments(); BigInteger numberOfPaymentsDocuments = BigInteger.ZERO; BigDecimal totalDebitOfPaymentsDocuments = BigDecimal.ZERO; BigDecimal totalCreditOfPaymentsDocuments = BigDecimal.ZERO; BigInteger numberOfWorkingDocuments = BigInteger.ZERO; BigDecimal totalDebitOfWorkingDocuments = BigDecimal.ZERO; BigDecimal totalCreditOfWorkingDocuments = BigDecimal.ZERO; invoices.setNumberOfEntries(BigInteger.ZERO); invoices.setTotalCredit(BigDecimal.ZERO); invoices.setTotalDebit(BigDecimal.ZERO); // int i = 0; for (FinantialDocument document : allDocuments) { if ((document.isCreditNote() || document.isDebitNote()) && (document.isClosed() || document.isAnnulled())) { try { WorkDocument workDocument = convertToSAFTWorkDocument((Invoice) document, customerMap, productMap); workingDocuments.getWorkDocument().add(workDocument); // AcumulateValues numberOfWorkingDocuments = numberOfWorkingDocuments.add(BigInteger.ONE); if (!document.isAnnulled()) { if (document.isDebitNote()) { totalDebitOfWorkingDocuments = totalDebitOfWorkingDocuments .add(workDocument.getDocumentTotals().getNetTotal()); } else if (document.isCreditNote()) { totalCreditOfWorkingDocuments = totalCreditOfWorkingDocuments .add(workDocument.getDocumentTotals().getNetTotal()); } } // i++; } catch (Exception ex) { logger.error("Error processing document " + document.getUiDocumentNumber() + ": " + ex.getLocalizedMessage()); throw ex; } } else { logger.info("Ignoring document " + document.getUiDocumentNumber() + " because is not closed yet."); } } // Update Totals of Workingdocuments workingDocuments.setNumberOfEntries(numberOfWorkingDocuments); workingDocuments.setTotalCredit(totalCreditOfWorkingDocuments.setScale(2, RoundingMode.HALF_EVEN)); workingDocuments.setTotalDebit(totalDebitOfWorkingDocuments.setScale(2, RoundingMode.HALF_EVEN)); sourceDocuments.setWorkingDocuments(workingDocuments); //PROCESSING PAYMENTS TABLE paymentsDocuments.setNumberOfEntries(BigInteger.ZERO); paymentsDocuments.setTotalCredit(BigDecimal.ZERO); paymentsDocuments.setTotalDebit(BigDecimal.ZERO); for (FinantialDocument document : allDocuments) { if (document.isSettlementNote() && (document.isClosed() || document.isAnnulled())) { try { Payment paymentDocument = convertToSAFTPaymentDocument((SettlementNote) document, customerMap, productMap); paymentsDocuments.getPayment().add(paymentDocument); // AcumulateValues numberOfPaymentsDocuments = numberOfPaymentsDocuments.add(BigInteger.ONE); if (!document.isAnnulled()) { totalCreditOfPaymentsDocuments = totalCreditOfPaymentsDocuments .add(((SettlementNote) document).getTotalCreditAmount()); totalDebitOfPaymentsDocuments = totalDebitOfPaymentsDocuments .add(((SettlementNote) document).getTotalDebitAmount()); } // i++; } catch (Exception ex) { // persistenceSupport.flush(); logger.error("Error processing document " + document.getUiDocumentNumber() + ": " + ex.getLocalizedMessage()); throw ex; } } else { logger.info("Ignoring document " + document.getUiDocumentNumber() + " because is not closed yet."); } } // Update Totals of Payment Documents paymentsDocuments.setNumberOfEntries(numberOfPaymentsDocuments); paymentsDocuments.setTotalCredit(totalCreditOfPaymentsDocuments.setScale(2, RoundingMode.HALF_EVEN)); paymentsDocuments.setTotalDebit(totalDebitOfPaymentsDocuments.setScale(2, RoundingMode.HALF_EVEN)); sourceDocuments.setPayments(paymentsDocuments); // Update the Customer Table in SAFT for (oecd.standardauditfile_tax.pt_1.Customer customer : customerMap.values()) { customerList.add(customer); } // Update the Product Table in SAFT for (oecd.standardauditfile_tax.pt_1.Product product : productMap.values()) { productList.add(product); } if (preProcessFunctionBeforeSerialize != null) { auditFile = preProcessFunctionBeforeSerialize.apply(auditFile); } String xml = exportAuditFileToXML(auditFile); logger.info("SAFT File export concluded with success."); return xml; }
From source file:org.geowebcache.diskquota.DiskQuotaMonitor.java
/** * Launches a background task to traverse the cache and compute the disk usage of each layer * that has no {@link LayerQuota#getUsedQuota() used quota} already loaded. * //from w w w .j a va2s . c om * @return * @throws InterruptedException */ private LayerCacheInfoBuilder launchCacheInfoGatheringThreads() throws InterruptedException { LayerCacheInfoBuilder cacheInfoBuilder; File cacheRoot; try { cacheRoot = new File(storageFinder.getDefaultPath()); } catch (ConfigurationException e) { throw new RuntimeException(e); } cacheInfoBuilder = new LayerCacheInfoBuilder(cacheRoot, cleanUpExecutorService, quotaUsageMonitor); for (String layerName : tileLayerDispatcher.getLayerNames()) { Quota usedQuota = quotaStore.getUsedQuotaByLayerName(layerName); if (usedQuota.getBytes().compareTo(BigInteger.ZERO) > 0) { log.debug("Using saved quota information for layer " + layerName + ": " + usedQuota.toNiceString()); } else { log.debug(layerName + " has no saved used quota information," + "traversing layer cache to compute its disk usage."); TileLayer tileLayer; try { tileLayer = tileLayerDispatcher.getTileLayer(layerName); } catch (GeoWebCacheException e) { e.printStackTrace(); continue; } cacheInfoBuilder.buildCacheInfo(tileLayer); } } return cacheInfoBuilder; }
From source file:jp.aegif.nemaki.cmis.factory.CmisService.java
/** * This method is customized based on OpenCMIS code */// w w w .j a va 2s . c o m @Override protected ObjectInfo getObjectInfoIntern(String repositoryId, ObjectData object) { // if the object has no properties, stop here if (object.getProperties() == null || object.getProperties().getProperties() == null) { throw new CmisRuntimeException("No properties!"); } ObjectInfoImpl info = new ObjectInfoImpl(); // get the repository info RepositoryInfo repositoryInfo = getRepositoryInfo(repositoryId, null); // general properties info.setObject(object); info.setId(object.getId()); info.setName(getStringProperty(object, PropertyIds.NAME)); info.setCreatedBy(getStringProperty(object, PropertyIds.CREATED_BY)); info.setCreationDate(getDateTimeProperty(object, PropertyIds.CREATED_BY)); info.setLastModificationDate(getDateTimeProperty(object, PropertyIds.LAST_MODIFICATION_DATE)); info.setTypeId(getIdProperty(object, PropertyIds.OBJECT_TYPE_ID)); info.setBaseType(object.getBaseTypeId()); // versioning info.setIsCurrentVersion(object.getBaseTypeId() == BaseTypeId.CMIS_DOCUMENT); info.setWorkingCopyId(null); info.setWorkingCopyOriginalId(null); info.setVersionSeriesId(getIdProperty(object, PropertyIds.VERSION_SERIES_ID)); if (info.getVersionSeriesId() != null) { Boolean isLatest = getBooleanProperty(object, PropertyIds.IS_LATEST_VERSION); info.setIsCurrentVersion(isLatest == null ? true : isLatest.booleanValue()); Boolean isCheckedOut = getBooleanProperty(object, PropertyIds.IS_VERSION_SERIES_CHECKED_OUT); if (isCheckedOut != null && isCheckedOut.booleanValue()) { info.setWorkingCopyId(getIdProperty(object, PropertyIds.VERSION_SERIES_CHECKED_OUT_ID)); // get latest version // // Nemaki Cusomization START //// /* * List<ObjectData> versions = getAllVersions(repositoryId, * object.getId(), info.getVersionSeriesId(), null, * Boolean.FALSE, null); if (versions != null && versions.size() * > 0) { * info.setWorkingCopyOriginalId(versions.get(0).getId()); } */ // NOTE:Spec2.2.7.6 only says the first element of // getAllVersions MUST be PWC. // When isCheckedOut = true, PWC MUST exsits, and // cmis:versionSeriesCheckedOutId is PWC id(2.1.13.5.1). info.setWorkingCopyOriginalId(getIdProperty(object, PropertyIds.VERSION_SERIES_CHECKED_OUT_ID)); // // Nemaki Cusomization END //// } } // content String fileName = getStringProperty(object, PropertyIds.CONTENT_STREAM_FILE_NAME); String mimeType = getStringProperty(object, PropertyIds.CONTENT_STREAM_MIME_TYPE); String streamId = getIdProperty(object, PropertyIds.CONTENT_STREAM_ID); BigInteger length = getIntegerProperty(object, PropertyIds.CONTENT_STREAM_LENGTH); boolean hasContent = fileName != null || mimeType != null || streamId != null || length != null; if (hasContent) { info.setHasContent(hasContent); info.setContentType(mimeType); info.setFileName(fileName); } else { info.setHasContent(false); info.setContentType(null); info.setFileName(null); } // parents if (object.getBaseTypeId() == BaseTypeId.CMIS_RELATIONSHIP) { info.setHasParent(false); } else if (object.getBaseTypeId() == BaseTypeId.CMIS_FOLDER) { info.setHasParent(!object.getId().equals(repositoryInfo.getRootFolderId())); // // Nemaki Cusomization START //// /* * } else { try { List<ObjectParentData> parents = * getObjectParents(repositoryId, object.getId(), null, * Boolean.FALSE, IncludeRelationships.NONE, "cmis:none", * Boolean.FALSE, null); info.setHasParent(parents.size() > 0); } * catch (CmisInvalidArgumentException e) { * info.setHasParent(false); } } */ } else { String objecTypeId = getIdProperty(object, PropertyIds.OBJECT_TYPE_ID); TypeDefinition typeDefinition = getTypeDefinition(repositoryId, objecTypeId, null); if (typeDefinition.isFileable()) { boolean unfiling = (repositoryInfo.getCapabilities().isUnfilingSupported() == null) ? false : repositoryInfo.getCapabilities().isUnfilingSupported(); if (unfiling) { List<ObjectParentData> parents = getObjectParents(repositoryId, object.getId(), null, Boolean.FALSE, IncludeRelationships.NONE, "cmis:none", Boolean.FALSE, null); info.setHasParent(parents != null && parents.size() >= 0); } else { info.setHasParent(true); } } else { info.setHasParent(false); } } // // Nemaki Cusomization END //// // policies and relationships info.setSupportsRelationships(false); info.setSupportsPolicies(false); TypeDefinitionList baseTypesList = getTypeChildren(repositoryId, null, Boolean.FALSE, BigInteger.valueOf(4), BigInteger.ZERO, null); for (TypeDefinition type : baseTypesList.getList()) { if (BaseTypeId.CMIS_RELATIONSHIP.value().equals(type.getId())) { info.setSupportsRelationships(true); } else if (BaseTypeId.CMIS_POLICY.value().equals(type.getId())) { info.setSupportsPolicies(true); } } // renditions info.setRenditionInfos(null); List<RenditionData> renditions = object.getRenditions(); if (renditions != null && renditions.size() > 0) { List<RenditionInfo> renditionInfos = new ArrayList<RenditionInfo>(); for (RenditionData rendition : renditions) { RenditionInfoImpl renditionInfo = new RenditionInfoImpl(); renditionInfo.setId(rendition.getStreamId()); renditionInfo.setKind(rendition.getKind()); renditionInfo.setContentType(rendition.getMimeType()); renditionInfo.setTitle(rendition.getTitle()); renditionInfo.setLength(rendition.getBigLength()); renditionInfos.add(renditionInfo); } info.setRenditionInfos(renditionInfos); } // relationships info.setRelationshipSourceIds(null); info.setRelationshipTargetIds(null); List<ObjectData> relationships = object.getRelationships(); if (relationships != null && relationships.size() > 0) { List<String> sourceIds = new ArrayList<String>(); List<String> targetIds = new ArrayList<String>(); for (ObjectData relationship : relationships) { String sourceId = getIdProperty(relationship, PropertyIds.SOURCE_ID); String targetId = getIdProperty(relationship, PropertyIds.TARGET_ID); if (object.getId().equals(sourceId)) { sourceIds.add(relationship.getId()); } if (object.getId().equals(targetId)) { targetIds.add(relationship.getId()); } } if (sourceIds.size() > 0) { info.setRelationshipSourceIds(sourceIds); } if (targetIds.size() > 0) { info.setRelationshipTargetIds(targetIds); } } // global settings info.setHasAcl(false); info.setSupportsDescendants(false); info.setSupportsFolderTree(false); RepositoryCapabilities capabilities = repositoryInfo.getCapabilities(); if (capabilities != null) { info.setHasAcl(capabilities.getAclCapability() == CapabilityAcl.DISCOVER || capabilities.getAclCapability() == CapabilityAcl.MANAGE); if (object.getBaseTypeId() == BaseTypeId.CMIS_FOLDER) { info.setSupportsDescendants(Boolean.TRUE.equals(capabilities.isGetDescendantsSupported())); info.setSupportsFolderTree(Boolean.TRUE.equals(capabilities.isGetFolderTreeSupported())); } } return info; }
From source file:org.alfresco.mobile.android.api.network.NetworkHttpInvoker.java
private static Response invoke(UrlBuilder url, String method, String contentType, Map<String, List<String>> httpHeaders, Output writer, boolean forceOutput, BigInteger offset, BigInteger length, Map<String, String> params) { try {/*from w w w . jav a 2 s . com*/ // Log.d("URL", url.toString()); // connect HttpURLConnection conn = (HttpURLConnection) (new URL(url.toString())).openConnection(); conn.setRequestMethod(method); conn.setDoInput(true); conn.setDoOutput(writer != null || forceOutput); conn.setAllowUserInteraction(false); conn.setUseCaches(false); conn.setRequestProperty("User-Agent", ClientVersion.OPENCMIS_CLIENT); // set content type if (contentType != null) { conn.setRequestProperty("Content-Type", contentType); } // set other headers if (httpHeaders != null) { for (Map.Entry<String, List<String>> header : httpHeaders.entrySet()) { if (header.getValue() != null) { for (String value : header.getValue()) { conn.addRequestProperty(header.getKey(), value); } } } } // range BigInteger tmpOffset = offset; if ((tmpOffset != null) || (length != null)) { StringBuilder sb = new StringBuilder("bytes="); if ((tmpOffset == null) || (tmpOffset.signum() == -1)) { tmpOffset = BigInteger.ZERO; } sb.append(tmpOffset.toString()); sb.append("-"); if ((length != null) && (length.signum() == 1)) { sb.append(tmpOffset.add(length.subtract(BigInteger.ONE)).toString()); } conn.setRequestProperty("Range", sb.toString()); } conn.setRequestProperty("Accept-Encoding", "gzip,deflate"); // add url form parameters if (params != null) { DataOutputStream ostream = null; OutputStream os = null; try { os = conn.getOutputStream(); ostream = new DataOutputStream(os); Set<String> parameters = params.keySet(); StringBuffer buf = new StringBuffer(); int paramCount = 0; for (String it : parameters) { String parameterName = it; String parameterValue = (String) params.get(parameterName); if (parameterValue != null) { parameterValue = URLEncoder.encode(parameterValue, "UTF-8"); if (paramCount > 0) { buf.append("&"); } buf.append(parameterName); buf.append("="); buf.append(parameterValue); ++paramCount; } } ostream.writeBytes(buf.toString()); } finally { if (ostream != null) { ostream.flush(); ostream.close(); } IOUtils.closeStream(os); } } // send data if (writer != null) { // conn.setChunkedStreamingMode((64 * 1024) - 1); OutputStream connOut = null; connOut = conn.getOutputStream(); OutputStream out = new BufferedOutputStream(connOut, BUFFER_SIZE); writer.write(out); out.flush(); } // connect conn.connect(); // get stream, if present int respCode = conn.getResponseCode(); InputStream inputStream = null; if ((respCode == HttpStatus.SC_OK) || (respCode == HttpStatus.SC_CREATED) || (respCode == HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION) || (respCode == HttpStatus.SC_PARTIAL_CONTENT)) { inputStream = conn.getInputStream(); } // get the response return new Response(respCode, conn.getResponseMessage(), conn.getHeaderFields(), inputStream, conn.getErrorStream()); } catch (Exception e) { throw new CmisConnectionException("Cannot access " + url + ": " + e.getMessage(), e); } }
From source file:com.teamj.distribuidas.web.ExcursionUserBean.java
public void selectDisabledRow(SelectEvent e) { this.subtotal = new BigDecimal(BigInteger.ZERO); this.totalArticulos = 0; //(excursionUserBean.excursionSelected.fechaLimite le excursionUserBean.today()) or (excursionUserBean.excursionSelected.maxAsistentes-fn:length(excursionUserBean.excursionSelected.usuarioExcursiones) le 0) for (int i = excursionArticulosSelected.size() - 1; i >= 0; i--) { if (excursionArticulosSelected.get(i).getArticulo().getStock() == 0) { this.excursionArticulosSelected.remove(i); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "No hay stock del artculo", "")); } else if ((this.excursionSelected.getFechaLimite().before(today()) || (this.excursionSelected.getMaxAsistentes() - this.excursionSelected.getUsuarioExcursiones().size() <= 0)) && this.excursionArticulosSelected.get(i).getArticulo().getDescripcion() != null && this.excursionArticulosSelected.get(i).getArticulo().getDescripcion() .equals(String.valueOf(this.excursionSelected.getId()))) { this.excursionArticulosSelected.remove(i); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "La fecha lmite para inscripcin de la excursin ha caducado", "")); } else {//from w w w. j av a 2 s. c om if (this.excursionArticulosSelected.get(i).getArticulo().getDescripcion() != null && this.excursionArticulosSelected.get(i).getArticulo().getDescripcion() .equals(String.valueOf(this.excursionSelected.getId()))) { this.derechoExcursionSeleccionada = this.excursionArticulosSelected.get(i).getArticulo() .getPrecio(); } else { this.totalArticulos += excursionArticulosSelected.get(i).getCantidad(); this.subtotal = this.subtotal.add(excursionArticulosSelected.get(i).getArticulo().getPrecio() .multiply(new BigDecimal(excursionArticulosSelected.get(i).getCantidad()))); } } } }
From source file:op.care.prescription.DlgOnDemand.java
private void txtEDosisFocusLost(FocusEvent e) { SYSTools.handleBigDecimalFocusLost(e, new BigDecimal(BigInteger.ZERO), new BigDecimal(1000), BigDecimal.ONE);//from w w w . ja va 2s .c o m }
From source file:org.kuali.kra.committee.print.ScheduleXmlStream.java
public Schedule getSchedule(CommitteeSchedule committeeSchedule) { Schedule schedule = Schedule.Factory.newInstance(); setScheduleMasterData(committeeSchedule, schedule.addNewScheduleMasterData()); PreviousSchedule prevSchedule = schedule.addNewPreviousSchedule(); setPreviousSchedule(committeeSchedule, prevSchedule.addNewScheduleMasterData()); NextSchedule nextScheduleType = schedule.addNewNextSchedule(); setNextSchedule(committeeSchedule, nextScheduleType.addNewScheduleMasterData()); getIrbPrintXmlUtilService().setMinutes(committeeSchedule, schedule); setAttendance(committeeSchedule, schedule); committeeSchedule.refreshReferenceObject("protocolSubmissions"); List<org.kuali.kra.irb.actions.submit.ProtocolSubmissionLite> submissions = committeeSchedule .getLatestProtocolSubmissions(); for (org.kuali.kra.irb.actions.submit.ProtocolSubmissionLite protocolSubmission : submissions) { ProtocolSubmission protocolSubmissionType = schedule.addNewProtocolSubmission(); SubmissionDetails protocolSubmissionDetail = protocolSubmissionType.addNewSubmissionDetails(); ProtocolSummary protocolSummary = protocolSubmissionType.addNewProtocolSummary(); ProtocolMasterData protocolMaster = protocolSummary.addNewProtocolMasterData(); String followUpAction = null; String actionTypeCode = null; Protocol protocol = getBusinessObjectService().findByPrimaryKey(Protocol.class, Collections.singletonMap("protocolId", protocolSubmission.getProtocolId())); List<ProtocolActionBase> protocolActions = protocol.getProtocolActions(); for (ProtocolActionBase protocolAction : protocolActions) { actionTypeCode = protocolAction.getProtocolActionTypeCode(); if (actionTypeCode.equals(EXPEDIT_ACTION_TYPE_CODE) || actionTypeCode.equals(EXEMPT_ACTION_TYPE_CODE)) { if (protocolAction.getFollowupActionCode() != null && protocolAction.getFollowupActionCode().equals(FOLLOW_UP_ACTION_CODE)) { followUpAction = protocolAction.getFollowupActionCode(); }//from ww w. j a va 2 s . co m break; } } protocolMaster.setProtocolNumber(protocol.getProtocolNumber()); protocolMaster.setSequenceNumber(new BigInteger(String.valueOf(protocol.getSequenceNumber()))); protocolMaster.setProtocolTitle(protocol.getTitle()); protocolMaster.setProtocolStatusCode(new BigInteger(String.valueOf(protocol.getProtocolStatusCode()))); protocolMaster.setProtocolStatusDesc(protocol.getProtocolStatus().getDescription()); protocolMaster.setProtocolTypeCode(new BigInteger(String.valueOf(protocol.getProtocolTypeCode()))); protocolMaster.setProtocolTypeDesc(protocol.getProtocolType().getDescription()); if (protocol.getDescription() != null) { protocolMaster.setProtocolDescription(protocol.getDescription()); } if (protocol.getApprovalDate() != null) { protocolMaster.setApprovalDate(getDateTimeService().getCalendar(protocol.getApprovalDate())); } if (protocol.getExpirationDate() != null) { protocolMaster.setExpirationDate(getDateTimeService().getCalendar(protocol.getExpirationDate())); } if (protocol.getFdaApplicationNumber() != null) { protocolMaster.setFdaApplicationNumber(protocol.getFdaApplicationNumber()); } if (protocol.getReferenceNumber1() != null) { protocolMaster.setRefNumber1(protocol.getReferenceNumber1()); } if (protocol.getReferenceNumber2() != null) { protocolMaster.setRefNumber2(protocol.getReferenceNumber2()); } protocolSubmissionDetail.setProtocolNumber(protocolSubmission.getProtocolNumber()); if (protocolSubmission.getProtocolSubmissionType() != null) { protocolSubmissionDetail .setSubmissionTypeDesc(protocolSubmission.getProtocolSubmissionType().getDescription()); } if (protocolSubmission.getProtocolReviewTypeCode() != null) { protocolSubmissionDetail .setProtocolReviewTypeCode(new BigInteger(protocolSubmission.getProtocolReviewTypeCode())); } if (protocolSubmission.getProtocolReviewType() != null) { protocolSubmissionDetail .setProtocolReviewTypeDesc(protocolSubmission.getProtocolReviewType().getDescription()); } if (protocolSubmission.getSubmissionTypeCode() != null) { protocolSubmissionDetail.setSubmissionTypeCode( new BigInteger(String.valueOf(protocolSubmission.getSubmissionTypeCode()))); } if (protocolSubmission.getProtocolSubmissionType() != null) { protocolSubmissionDetail .setSubmissionTypeDesc(protocolSubmission.getProtocolSubmissionType().getDescription()); } if (protocolSubmission.getSubmissionNumber() != null) { protocolSubmissionDetail.setSubmissionNumber( new BigInteger(String.valueOf(protocolSubmission.getSubmissionNumber()))); } if (protocolSubmission.getSubmissionStatusCode() != null) { protocolSubmissionDetail.setSubmissionStatusCode( new BigInteger(String.valueOf(protocolSubmission.getSubmissionStatusCode()))); } if (protocolSubmission.getSubmissionStatus() != null) { protocolSubmissionDetail .setSubmissionStatusDesc(protocolSubmission.getSubmissionStatus().getDescription()); } if (protocolSubmission.getSubmissionTypeQualifierCode() != null) { protocolSubmissionDetail.setSubmissionTypeQualifierCode( new BigInteger(protocolSubmission.getSubmissionTypeQualifierCode())); } if (protocolSubmission.getProtocolSubmissionQualifierType() != null) { protocolSubmissionDetail.setSubmissionTypeQualifierDesc( protocolSubmission.getProtocolSubmissionQualifierType().getDescription()); } if (protocolSubmission.getYesVoteCount() != null) { protocolSubmissionDetail.setYesVote(BigInteger.valueOf(protocolSubmission.getYesVoteCount())); } else { protocolSubmissionDetail.setYesVote(BigInteger.ZERO); } if (protocolSubmission.getNoVoteCount() != null) { protocolSubmissionDetail.setNoVote(BigInteger.valueOf(protocolSubmission.getNoVoteCount())); } else { protocolSubmissionDetail.setNoVote(BigInteger.ZERO); } if (protocolSubmission.getAbstainerCount() != null) { protocolSubmissionDetail .setAbstainerCount(BigInteger.valueOf(protocolSubmission.getAbstainerCount())); } else { protocolSubmissionDetail.setAbstainerCount(BigInteger.ZERO); } protocolSubmissionDetail.setVotingComments(protocolSubmission.getVotingComments()); setProtocolSubmissionAction(protocolSubmission, protocol, protocolSubmissionDetail); if (protocolSubmission.getSubmissionDate() != null) { protocolSubmissionDetail.setSubmissionDate( getDateTimeService().getCalendar(protocolSubmission.getSubmissionDate())); } setSubmissionCheckListinfo(protocolSubmission, protocolSubmissionDetail); setProtocolSubmissionReviewers(protocolSubmission, protocolSubmissionDetail); List<ProtocolPersonBase> protocolPersons = protocol.getProtocolPersons(); for (ProtocolPersonBase protocolPerson : protocolPersons) { if (protocolPerson.getProtocolPersonRoleId().equals(ProtocolPersonRole.ROLE_PRINCIPAL_INVESTIGATOR) || protocolPerson.getProtocolPersonRoleId() .equals(ProtocolPersonRole.ROLE_CO_INVESTIGATOR)) { Investigator investigator = protocolSummary.addNewInvestigator(); getIrbPrintXmlUtilService().setPersonRolodexType((ProtocolPerson) protocolPerson, investigator.addNewPerson()); if (protocolPerson.getProtocolPersonRoleId() .equals(ProtocolPersonRole.ROLE_PRINCIPAL_INVESTIGATOR)) { investigator.setPIFlag(true); } } } List<ProtocolRiskLevel> cvRiskLevels = protocol.getProtocolRiskLevels(); for (ProtocolRiskLevel protocolRiskLevelBean : cvRiskLevels) { edu.mit.irb.irbnamespace.ProtocolSummaryDocument.ProtocolSummary.RiskLevels riskLevelType = protocolSummary .addNewRiskLevels(); riskLevelType.setRiskLevelDescription(protocolRiskLevelBean.getRiskLevel().getDescription()); riskLevelType.setComments(protocolRiskLevelBean.getComments()); } List<ProtocolFundingSource> vecFundingSource = (List) protocol.getProtocolFundingSources(); int fundingSourceTypeCode; String fundingSourceName, fundingSourceCode; for (ProtocolFundingSource protocolFundingSourceBean : vecFundingSource) { protocolFundingSourceBean.refreshNonUpdateableReferences(); edu.mit.irb.irbnamespace.ProtocolSummaryDocument.ProtocolSummary.FundingSource fundingSource = protocolSummary .addNewFundingSource(); fundingSourceCode = protocolFundingSourceBean.getFundingSourceNumber(); fundingSourceTypeCode = Integer.valueOf(protocolFundingSourceBean.getFundingSourceTypeCode()); fundingSourceName = getFundingSourceNameForType(fundingSourceTypeCode, fundingSourceCode); fundingSource.setFundingSourceName(fundingSourceName); if (protocolFundingSourceBean.getFundingSourceType() != null) { fundingSource.setTypeOfFundingSource( protocolFundingSourceBean.getFundingSourceType().getDescription()); } } getIrbPrintXmlUtilService().setProcotolMinutes(committeeSchedule, protocolSubmission, protocolSubmissionType); } setOtherActionItems(committeeSchedule, schedule); return schedule; }
From source file:cc.redberry.core.number.Rational.java
@Override public boolean isZero() { //Here we do not use fraction.equals() because it has low performence return fraction.getNumerator().equals(BigInteger.ZERO);//.equals(BigFraction.ZERO); }
From source file:com.udojava.evalex.Expression.java
/** * Creates a new expression instance from an expression string with a given * default match context.//from w w w . j a v a 2 s .c om * * @param expression The expression. E.g. <code>"2.4*sin(3)/(2-4)"</code> or * <code>"sin(y)>0 & max(z, 3)>3"</code> */ public Expression(String expression, LinkedList<String> hist, Variables vars) { this.history = hist; this.expression = expression; mainVars = vars; addOperator(new Operator("+", 20, true, "Addition") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { if (v1.type == ValueType.ARRAY) { MyComplex vo = new MyComplex(v1.list); vo.list.add(v2); return vo; } return v1.add(v2); } }); addOperator(new Operator("-", 20, true, "Subtraction") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { if (v1.type == ValueType.ARRAY) { MyComplex vo = new MyComplex(v1.list); vo.list.removeIf(o -> o.equals(v2)); return vo; } return v1.subtract(v2); } }); addOperator(new Operator("*", 30, true, "Real number multiplication") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { return v1.multiply(v2); } }); addOperator(new Operator("/", 30, true, "Real number division") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { return v1.divide(v2); } }); addOperator(new Operator("%", 30, true, "Remainder of integer division") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { double r = v1.real % v2.real; return new MyComplex(r); } }); addOperator( new Operator("^", 40, false, "Exponentation. See: https://en.wikipedia.org/wiki/Exponentiation") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { return v1.pow(v2); } }); addOperator(new Operator("&&", 4, false, "Logical AND. Evaluates to 1 if both operands are not 0") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { boolean b1 = (v1.real == 0.0 && v2.real == 0.0); return new MyComplex(b1 ? 1 : 0); } }); addOperator(new Operator("||", 2, false, "Logical OR. Evaluates to 0 if both operands are 0") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { boolean b1 = (v1.real == 0.0 && v2.real == 0.0); return new MyComplex(b1 ? 0 : 1); } }); addOperator(new Operator(">", 10, false, "Greater than. See: See: https://en.wikipedia.org/wiki/Inequality_(mathematics)") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { if (v1.type == ValueType.REAL && v2.type == ValueType.REAL) { return new MyComplex(v1.real > v2.real ? 1 : 0); } else { return new MyComplex(v1.abs() > v2.abs() ? 1 : 0); } } }); addOperator(new Operator(">=", 10, false, "Greater or equal") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { if (v1.type == ValueType.REAL && v2.type == ValueType.REAL) { return new MyComplex(v1.real >= v2.real ? 1 : 0); } else { return new MyComplex(v1.abs() >= v2.abs() ? 1 : 0); } } }); addOperator(new Operator("<", 10, false, "Less than. See: https://en.wikipedia.org/wiki/Inequality_(mathematics)") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { if (v1.type == ValueType.REAL && v2.type == ValueType.REAL) { return new MyComplex(v1.real < v2.real ? 1 : 0); } else { return new MyComplex(v1.abs() < v2.abs() ? 1 : 0); } } }); addOperator(new Operator("<=", 10, false, "less or equal") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { if (v1.type == ValueType.REAL && v2.type == ValueType.REAL) { return new MyComplex(v1.real <= v2.real ? 1 : 0); } else { return new MyComplex(v1.abs() <= v2.abs() ? 1 : 0); } } }); addOperator(new Operator("->", 7, false, "Set variable v to new value ") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { if (v1 instanceof PitDecimal) { PitDecimal target = (PitDecimal) v1; String s = target.getVarToken(); setVariable(s, v2); return v2; } throw new ExpressionException("LHS not variable"); } }); addOperator(new Operator("=", 7, false, "Equality") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { if (v1.type == ValueType.REAL && v2.type == ValueType.REAL) { return new MyComplex(v1.real == v2.real ? 1 : 0); } else { return new MyComplex(v1.abs() == v2.abs() ? 1 : 0); } } }); addOperator(new Operator("!=", 7, false, "Inequality. See: https://en.wikipedia.org/wiki/Inequality_(mathematics)") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { if (v1.type == ValueType.REAL && v2.type == ValueType.REAL) { return new MyComplex(v1.real != v2.real ? 1 : 0); } else { return new MyComplex(v1.abs() != v2.abs() ? 1 : 0); } } }); addOperator( new Operator("or", 7, false, "Bitwise OR. See: https://en.wikipedia.org/wiki/Logical_disjunction") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { return new MyComplex((long) v1.real | (long) v2.real); } }); addOperator(new Operator("and", 7, false, "Bitwise AND. See: https://en.wikipedia.org/wiki/Logical_conjunction") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { return new MyComplex((long) v1.real & (long) v2.real); } }); addOperator(new Operator("xor", 7, false, "Bitwise XOR, See: https://en.wikipedia.org/wiki/Exclusive_or") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { return new MyComplex((long) v1.real ^ (long) v2.real); } }); addOperator(new Operator("!", 50, true, "Factorial. See https://en.wikipedia.org/wiki/Factorial") { public BigInteger factorial(long n) { BigInteger factorial = BigInteger.ONE; for (long i = 1; i <= n; i++) { factorial = factorial.multiply(BigInteger.valueOf(i)); } return factorial; } @Override public MyComplex eval(MyComplex v1, MyComplex v2) { BigInteger fact = factorial((long) v1.real); return new MyComplex(fact, BigInteger.ZERO); } }); addOperator(new Operator("~", 8, false, "Bitwise negation") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { BigInteger bi = v2.toBigIntegerReal(); int c = bi.bitLength(); if (c == 0) { return new MyComplex(1); } for (int s = 0; s < c; s++) { bi = bi.flipBit(s); } return new MyComplex(bi); } }); addOperator(new Operator("shl", 8, false, "Left Bit shift") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { return new MyComplex((long) v1.real << (long) v2.real); } }); addOperator(new Operator("shr", 8, false, "Right bit shift") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { return new MyComplex((long) v1.real >>> (long) v2.real); } }); addFunction(new Function("NOT", 1, "evaluates to 0 if argument != 0") { @Override public MyComplex eval(List<MyComplex> parameters) { boolean zero = parameters.get(0).abs() == 0; return new MyComplex(zero ? 1 : 0); } }); addFunction(new Function("RND", 2, "Give random number in the range between first and second argument") { @Override public MyComplex eval(List<MyComplex> parameters) { double low = parameters.get(0).real; double high = parameters.get(1).real; return new MyComplex(low + Math.random() * (high - low)); } }); MersenneTwister mers = new MersenneTwister(System.nanoTime()); addFunction(new Function("MRS", 0, "Mersenne twister random generator") { @Override public MyComplex eval(List<MyComplex> parameters) { return new MyComplex(mers.nextDouble()); } }); addFunction(new Function("BIN", 2, "Binomial Coefficient 'n choose k'") { @Override public MyComplex eval(List<MyComplex> parameters) { int n = (int) parameters.get(0).real; int k = (int) parameters.get(1).real; double d = CombinatoricsUtils.binomialCoefficientDouble(n, k); return new MyComplex(d); } }); addFunction(new Function("STIR", 2, "Stirling number of 2nd kind: http://mathworld.wolfram.com/StirlingNumberoftheSecondKind.html") { @Override public MyComplex eval(List<MyComplex> parameters) { int n = (int) parameters.get(0).real; int k = (int) parameters.get(1).real; double d = CombinatoricsUtils.stirlingS2(n, k); return new MyComplex(d); } }); addFunction(new Function("SIN", 1, "Sine function") { @Override public MyComplex eval(List<MyComplex> parameters) { return parameters.get(0).sin(); } }); addFunction(new Function("COS", 1, "Cosine function") { @Override public MyComplex eval(List<MyComplex> parameters) { return parameters.get(0).cos(); } }); addFunction(new Function("TAN", 1, "Tangent") { @Override public MyComplex eval(List<MyComplex> parameters) { return parameters.get(0).tan(); } }); addFunction(new Function("ASIN", 1, "Reverse Sine") { // added by av @Override public MyComplex eval(List<MyComplex> parameters) { return parameters.get(0).asin(); } }); addFunction(new Function("ACOS", 1, "Reverse Cosine") { // added by av @Override public MyComplex eval(List<MyComplex> parameters) { return parameters.get(0).acos(); } }); addFunction(new Function("ATAN", 1, "Reverse Tangent") { // added by av @Override public MyComplex eval(List<MyComplex> parameters) { return parameters.get(0).atan(); } }); addFunction(new Function("SINH", 1, "Hyperbolic Sine") { @Override public MyComplex eval(List<MyComplex> parameters) { return parameters.get(0).sinh(); } }); addFunction(new Function("COSH", 1, "Hyperbolic Cosine") { @Override public MyComplex eval(List<MyComplex> parameters) { return parameters.get(0).cosh(); } }); addFunction(new Function("TANH", 1, "Hyperbolic Tangent") { @Override public MyComplex eval(List<MyComplex> parameters) { return parameters.get(0).tanh(); } }); addFunction(new Function("RAD", 1, "Transform degree to radian") { @Override public MyComplex eval(List<MyComplex> parameters) { double d = Math.toRadians(parameters.get(0).real); return new MyComplex(d); } }); addFunction(new Function("DEG", 1, "Transform radian to degree") { @Override public MyComplex eval(List<MyComplex> parameters) { double d = Math.toDegrees(parameters.get(0).real); return new MyComplex(d); } }); addFunction(new Function("MAX", -1, "Find the biggest value in a list") { @Override public MyComplex eval(List<MyComplex> parameters) { MyComplex save = new MyComplex(Double.MIN_VALUE); if (parameters.size() == 0) { throw new ExpressionException("MAX requires at least one parameter"); } // if (parameters.get(0).type == ValueType.ARRAY) // parameters = parameters.get(0).list; if (parameters.get(0).type == ValueType.COMPLEX) { for (MyComplex parameter : parameters) { if (parameter.abs() > save.abs()) { save = parameter; } } save.type = ValueType.COMPLEX; } else { for (MyComplex parameter : parameters) { if (parameter.real > save.real) { save = parameter; } } save.type = ValueType.REAL; } return save; } }); /////////////////////////////////////////////////////// addFunction(new Function("IF", 3, "Conditional: give param3 if param1 is 0, otherwise param2") { @Override public MyComplex eval(List<MyComplex> parameters) { if (parameters.get(0).real == 0.0) { return parameters.get(2); } return parameters.get(1); } }); addFunction(new Function("PERC", 2, "Get param1 percent of param2") { @Override public MyComplex eval(List<MyComplex> parameters) { return parameters.get(0).divide(new MyComplex(100)).multiply(parameters.get(1)); } }); addFunction(new Function("PER", 2, "How many percent is param1 of param2") { @Override public MyComplex eval(List<MyComplex> parameters) { return parameters.get(0).multiply(new MyComplex(100)).divide(parameters.get(1)); } }); addFunction(new Function("H", 1, "Evaluate _history element") { @Override public MyComplex eval(List<MyComplex> parameters) { int i = (int) parameters.get(0).real; Expression ex = new Expression(history.get(i), history, mainVars); return ex.eval(); } }); addFunction(new Function("MERS", 1, "Calculate Mersenne Number") { @Override public MyComplex eval(List<MyComplex> parameters) { MyComplex p = parameters.get(0); return new MyComplex(2).pow(p).subtract(new MyComplex(1)); } }); addFunction(new Function("GCD", 2, "Find greatest common divisor of 2 values") { @Override public MyComplex eval(List<MyComplex> parameters) { double a = parameters.get(0).real; double b = parameters.get(1).real; long r = ArithmeticUtils.gcd((long) a, (long) b); return new MyComplex(r); } }); addFunction(new Function("LCM", 2, "Find least common multiple of 2 values") { @Override public MyComplex eval(List<MyComplex> parameters) { double a = parameters.get(0).real; double b = parameters.get(1).real; long r = ArithmeticUtils.lcm((long) a, (long) b); return new MyComplex(r); } }); addFunction(new Function("AMEAN", -1, "Arithmetic mean of a set of values") { @Override public MyComplex eval(List<MyComplex> parameters) { if (parameters.size() == 0) { throw new ExpressionException("MEAN requires at least one parameter"); } Mean m = new Mean(); double[] d = MyComplex.getRealArray(parameters); double d2 = m.evaluate(d); return new MyComplex(d2); } }); // addFunction(new Function("BYT", -1, // "Value from sequence of bytes") // { // @Override // public MyComplex eval (List<MyComplex> parameters) // { // if (parameters.size() == 0) // { // return MyComplex.ZERO; // } // BigInteger res = BigInteger.ZERO; // for (MyComplex parameter : parameters) // { // if (parameter.intValue() < 0 || parameter.intValue() > 255) // { // throw new ExpressionException("not a byte value"); // } // res = res.shiftLeft(8); // res = res.or(parameter.toBigInteger()); // } // return new MyComplex(res, BigInteger.ZERO); // } // }); addFunction(new Function("SEQ", 3, "Generate Sequence p1=start, p2=step, p3=count") { @Override public MyComplex eval(List<MyComplex> parameters) { double start = parameters.get(0).real; ArrayList<MyComplex> arr = new ArrayList<>(); for (int s = 0; s < (int) (parameters.get(2).real); s++) { arr.add(new MyComplex(start)); start += parameters.get(1).real; } return new MyComplex(arr); } }); addFunction(new Function("PROD", -1, "Product of real values") { @Override public MyComplex eval(List<MyComplex> parameters) { Product p = new Product(); double[] d = MyComplex.getRealArray(parameters); return new MyComplex(p.evaluate(d)); } }); addFunction(new Function("SUM", -1, "Sum of values") { @Override public MyComplex eval(List<MyComplex> parameters) { Sum p = new Sum(); double[] d = MyComplex.getRealArray(parameters); return new MyComplex(p.evaluate(d)); } }); addFunction(new Function("ANG", 1, "Angle phi of complex number in radians") { @Override public MyComplex eval(List<MyComplex> parameters) { double b = parameters.get(0).angle(); return new MyComplex(b); } }); addFunction(new Function("IM", 1, "Get imaginary part") { @Override public MyComplex eval(List<MyComplex> parameters) { return new MyComplex(parameters.get(0).imaginary); } }); addFunction(new Function("RE", 1, "Get real part") { @Override public MyComplex eval(List<MyComplex> parameters) { return new MyComplex(parameters.get(0).real); } }); addFunction(new Function("POL", 2, "Make complex number from polar coords. angle is first arg") { @Override public MyComplex eval(List<MyComplex> parameters) { double angle = parameters.get(0).real; double len = parameters.get(1).real; Complex c = ComplexUtils.polar2Complex(len, angle); return new MyComplex(c); } }); addFunction(new Function("GMEAN", -1, "Geometric mean of a set of values") { @Override public MyComplex eval(List<MyComplex> parameters) { if (parameters.size() == 0) { throw new ExpressionException("MEAN requires at least one parameter"); } GeometricMean m = new GeometricMean(); double[] d = MyComplex.getRealArray(parameters); double d2 = m.evaluate(d); return new MyComplex(d2); } }); addFunction(new Function("HMEAN", -1, "Harmonic mean of a set of values") { @Override public MyComplex eval(List<MyComplex> parameters) { if (parameters.size() == 0) { throw new ExpressionException("MEAN requires at least one parameter"); } MyComplex res = new MyComplex(0); int num = 0; for (MyComplex parameter : parameters) { res = res.add(new MyComplex(1).divide(parameter)); num++; } res = new MyComplex(res.abs()); return new MyComplex(num).divide(res); } }); addFunction(new Function("VAR", -1, "Variance of a set of values") { @Override public MyComplex eval(List<MyComplex> parameters) { if (parameters.size() == 0) { throw new ExpressionException("MEAN requires at least one parameter"); } double[] arr = new double[parameters.size()]; for (int s = 0; s < parameters.size(); s++) { arr[s] = parameters.get(s).real; } return new MyComplex(variance(arr)); } }); addFunction(new Function("NPR", 1, "Next prime number greater or equal the argument") { @Override public MyComplex eval(List<MyComplex> parameters) { return new MyComplex(nextPrime((int) parameters.get(0).real)); } }); addFunction(new Function("NSWP", 1, "Swap nibbles") { @Override public MyComplex eval(List<MyComplex> parameters) { BigInteger bi = parameters.get(0).toBigIntegerReal(); String s = bi.toString(16); s = new StringBuilder(s).reverse().toString(); return new MyComplex(new BigInteger(s, 16), BigInteger.ZERO); } }); addFunction(new Function("BSWP", 1, "Swap bytes") { @Override public MyComplex eval(List<MyComplex> parameters) { BigInteger bi = parameters.get(0).toBigIntegerReal(); String s = bi.toString(16); while (s.length() % 4 != 0) { s = s + "0"; } if (bi.intValue() < 256) { s = "00" + s; } s = Misc.reverseHex(s); return new MyComplex(new BigInteger(s, 16), BigInteger.ZERO); } }); addFunction(new Function("PYT", 2, "Pythagoras's result = sqrt(param1^2+param2^2) https://en.wikipedia.org/wiki/Pythagorean_theorem") { @Override public MyComplex eval(List<MyComplex> par) { double a = par.get(0).real; double b = par.get(1).real; return new MyComplex(Math.sqrt(a * a + b * b)); } }); addFunction(new Function("FIB", 1, "Fibonacci number") { // --Commented out by Inspection (2/19/2017 7:46 PM):private final Operator exp = operators.get("^"); @Override public MyComplex eval(List<MyComplex> par) { return Misc.iterativeFibonacci((int) par.get(0).real); } }); /////////////////////////////////////////////// addFunction(new Function("MIN", -1, "Find the smallest in a list of values") { @Override public MyComplex eval(List<MyComplex> parameters) { MyComplex save = new MyComplex(Double.MAX_VALUE); if (parameters.size() == 0) { throw new ExpressionException("MAX requires at least one parameter"); } if (parameters.get(0).type == ValueType.COMPLEX) { for (MyComplex parameter : parameters) { if (parameter.abs() < save.abs()) { save = parameter; } } save.type = ValueType.COMPLEX; } else { for (MyComplex parameter : parameters) { if (parameter.real < save.real) { save = parameter; } } save.type = ValueType.REAL; } return save; } }); addFunction(new Function("ABS", 1, "Get absolute value of a number") { @Override public MyComplex eval(List<MyComplex> parameters) { return new MyComplex(parameters.get(0).abs()); } }); addFunction(new Function("LN", 1, "Logarithm base e of the argument") { @Override public MyComplex eval(List<MyComplex> parameters) { double d = Math.log(parameters.get(0).real); return new MyComplex(d); } }); addFunction(new Function("LOG", 1, "Logarithm base 10 of the argument") { @Override public MyComplex eval(List<MyComplex> parameters) { double d = Math.log10(parameters.get(0).real); return new MyComplex(d); } }); addFunction(new Function("FLOOR", 1, "Rounds DOWN to nearest Integer") { @Override public MyComplex eval(List<MyComplex> parameters) { double d = Math.floor(parameters.get(0).real); return new MyComplex(d); } }); addFunction(new Function("CEIL", 1, "Rounds UP to nearest Integer") { @Override public MyComplex eval(List<MyComplex> parameters) { double d = Math.ceil(parameters.get(0).real); return new MyComplex(d); } }); addFunction(new Function("ROU", 1, "Rounds to nearest Integer") { @Override public MyComplex eval(List<MyComplex> parameters) { int d = (int) (parameters.get(0).real + 0.5); return new MyComplex(d); } }); addFunction(new Function("SQRT", 1, "Square root") { @Override public MyComplex eval(List<MyComplex> parameters) { MyComplex p = parameters.get(0); if (p.type == ValueType.REAL) { return new MyComplex(Math.sqrt(p.real)); } return p.sqrt(); } }); addFunction(new Function("ARR", -1, "Create array") { @Override public MyComplex eval(List<MyComplex> parameters) { return new MyComplex(parameters); } }); addFunction(new Function("POLY", -1, "Treat array as Polynom") { @Override public MyComplex eval(List<MyComplex> parameters) { double[] d = MyComplex.getRealArray(parameters); PolynomialFunction p = new PolynomialFunction(d); return new MyComplex(p); } }); addFunction(new Function("DRVE", -1, "Make derivative of polynomial") { @Override public MyComplex eval(List<MyComplex> parameters) { PolynomialFunction p; if (parameters.get(0).isPoly()) { p = new PolynomialFunction(parameters.get(0).getRealArray()); } else { double[] d = MyComplex.getRealArray(parameters); p = new PolynomialFunction(d); } return new MyComplex(p.polynomialDerivative()); } }); addFunction(new Function("ADRVE", -1, "Make antiderivative of polynomial. Constant is always zero") { @Override public MyComplex eval(List<MyComplex> parameters) { PolynomialFunction p; if (parameters.get(0).isPoly()) { p = new PolynomialFunction(parameters.get(0).getRealArray()); } else { double[] d = MyComplex.getRealArray(parameters); p = new PolynomialFunction(d); } return new MyComplex(Misc.antiDerive(p)); } }); addFunction(new Function("PVAL", 2, "Compute value of polynom for the given argument.") { @Override public MyComplex eval(List<MyComplex> parameters) { if (parameters.get(0).isPoly()) { PolynomialFunction p = new PolynomialFunction(parameters.get(0).getRealArray()); double v = p.value(parameters.get(1).real); return new MyComplex(v); } throw new ExpressionException("first arg must be polynomial"); } }); addFunction(new Function("INTGR", 3, "Numerical integration") { @Override public MyComplex eval(List<MyComplex> parameters) { if (parameters.get(0).isPoly()) { PolynomialFunction p = new PolynomialFunction(parameters.get(0).getRealArray()); double start = parameters.get(1).real; double end = parameters.get(2).real; SimpsonIntegrator si = new SimpsonIntegrator(); double d = si.integrate(1000, p, start, end); return new MyComplex(d); } throw new ExpressionException("first arg must be polynomial"); } }); }