code
stringlengths
4
1.01M
language
stringclasses
2 values
// Copyright 2020 ETH Zurich. All Rights Reserved. #pragma once #include "real.h" #include <mirheo/core/mesh/membrane.h> #include <mirheo/core/pvs/object_vector.h> #include <mirheo/core/pvs/views/ov.h> #include <mirheo/core/utils/cpu_gpu_defines.h> #include <mirheo/core/utils/cuda_common.h> #include <mirheo/core/utils/cuda_rng.h> namespace mirheo { /** Compute triangle area \param [in] v0 Vertex coordinates \param [in] v1 Vertex coordinates \param [in] v2 Vertex coordinates \return The triangle area */ __D__ inline mReal triangleArea(mReal3 v0, mReal3 v1, mReal3 v2) { return 0.5_mr * length(cross(v1 - v0, v2 - v0)); } /** Compute the volume of the tetrahedron spanned by the origin and the three input coordinates. The result is negative if the normal of the triangle points inside the tetrahedron. \param [in] v0 Vertex coordinates \param [in] v1 Vertex coordinates \param [in] v2 Vertex coordinates \return The signed volume of the tetrahedron */ __D__ inline mReal triangleSignedVolume(mReal3 v0, mReal3 v1, mReal3 v2) { return 0.1666666667_mr * (- v0.z*v1.y*v2.x + v0.z*v1.x*v2.y + v0.y*v1.z*v2.x - v0.x*v1.z*v2.y - v0.y*v1.x*v2.z + v0.x*v1.y*v2.z); } /** Compute the angle between two adjacent triangles. It is the positive angle between the two normals. \param [in] v0 Vertex coordinates \param [in] v1 Vertex coordinates \param [in] v2 Vertex coordinates \param [in] v3 Vertex coordinates \return The supplementary dihedral angle */ __D__ inline mReal supplementaryDihedralAngle(mReal3 v0, mReal3 v1, mReal3 v2, mReal3 v3) { /* v3 / \ v2 --- v0 \ / V v1 dihedral: 0123 */ mReal3 n, k, nk; n = cross(v1 - v0, v2 - v0); k = cross(v2 - v0, v3 - v0); nk = cross(n, k); mReal theta = atan2(length(nk), dot(n, k)); theta = dot(v2-v0, nk) < 0 ? theta : -theta; return theta; } } // namespace mirheo
Java
/** * Copyright (c) 2013 Jad * * This file is part of Jad. * Jad is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Jad is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Jad. If not, see <http://www.gnu.org/licenses/>. */ package de.fhffm.jad.demo.jad; import java.util.ArrayList; import de.fhffm.jad.data.DataWrapper; import de.fhffm.jad.data.EInputFields; import de.fhffm.jad.data.IDataFieldEnum; /** * This class synchronizes the access to our Data.Frame * Added Observations are stored in a local ArrayList. * Use 'write' to send everything to GNU R. * @author Denis Hock */ public class DataFrame { private static DataWrapper dw = null; private static ArrayList<String[]> rows = new ArrayList<>(); /** * @return Singleton Instance of the GNU R Data.Frame */ public static DataWrapper getDataFrame(){ if (dw == null){ //Create the data.frame for GNU R: dw = new DataWrapper("data"); clear(); } return dw; } /** * Delete the old observations and send all new observations to Gnu R * @return */ public synchronized static boolean write(){ if (rows.size() < 1){ return false; } //Clear the R-Data.Frame clear(); //Send all new Observations to Gnu R for(String[] row : rows) dw.addObservation(row); //Clear the local ArrayList rows.clear(); return true; } /** * These Observations are locally stored and wait for the write() command * @param row */ public synchronized static void add(String[] row){ //Store everything in an ArrayList rows.add(row); } /** * Clear local ArrayList and GNU R Data.Frame */ private static void clear(){ ArrayList<IDataFieldEnum> fields = new ArrayList<IDataFieldEnum>(); fields.add(EInputFields.ipsrc); fields.add(EInputFields.tcpdstport); fields.add(EInputFields.framelen); dw.createEmptyDataFrame(fields); } }
Java
/* This file is part of F3TextViewerFX. * * F3TextViewerFX is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * F3TextViewerFX is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with F3TextViewerFX. If not, see <http://www.gnu.org/licenses/>. * * Copyright 2015 by Dominic Scheurer <dscheurer@dominic-scheurer.de>. */ package de.dominicscheurer.quicktxtview.view; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.io.StringWriter; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.text.DecimalFormat; import java.util.Arrays; import java.util.Comparator; import java.util.Iterator; import java.util.Scanner; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import javafx.collections.transformation.FilteredList; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeView; import javafx.scene.web.WebEngine; import javafx.scene.web.WebView; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.util.PDFText2HTML; import de.dominicscheurer.quicktxtview.model.DirectoryTreeItem; import de.dominicscheurer.quicktxtview.model.FileSize; import de.dominicscheurer.quicktxtview.model.FileSize.FileSizeUnits; public class FileViewerController { public static final Comparator<File> FILE_ACCESS_CMP = (f1, f2) -> Long.compare(f1.lastModified(), f2.lastModified()); public static final Comparator<File> FILE_ACCESS_CMP_REVERSE = (f1, f2) -> Long.compare(f2.lastModified(), f1.lastModified()); public static final Comparator<File> FILE_NAME_CMP = (f1, f2) -> f1.getName().compareTo(f2.getName()); public static final Comparator<File> FILE_NAME_CMP_REVERSE = (f1, f2) -> f2.getName().compareTo(f1.getName()); private static final String FILE_VIEWER_CSS_FILE = "FileViewer.css"; private static final String ERROR_TEXT_FIELD_CSS_CLASS = "errorTextField"; private FileSize fileSizeThreshold = new FileSize(1, FileSizeUnits.MB); private Charset charset = Charset.defaultCharset(); private Comparator<File> fileComparator = FILE_ACCESS_CMP; @FXML private TreeView<File> fileSystemView; @FXML private WebView directoryContentView; @FXML private TextField filePatternTextField; @FXML private Label fileSizeThresholdLabel; private boolean isInShowContentsMode = false; private String fileTreeViewerCSS; private Pattern filePattern; @FXML private void initialize() { filePattern = Pattern.compile(filePatternTextField.getText()); filePatternTextField.setOnKeyReleased(event -> { final String input = filePatternTextField.getText(); try { Pattern p = Pattern.compile(input); filePattern = p; filePatternTextField.getStyleClass().remove(ERROR_TEXT_FIELD_CSS_CLASS); if (!fileSystemView.getSelectionModel().isEmpty()) { showDirectoryContents(fileSystemView.getSelectionModel().getSelectedItem()); } } catch (PatternSyntaxException e) { filePatternTextField.getStyleClass().add(ERROR_TEXT_FIELD_CSS_CLASS); } filePatternTextField.applyCss(); }); fileSystemView.getSelectionModel().selectedItemProperty().addListener( (observable, oldValue, newValue) -> showDirectoryContents(newValue)); { Scanner s = new Scanner(getClass().getResourceAsStream(FILE_VIEWER_CSS_FILE)); s.useDelimiter("\\A"); fileTreeViewerCSS = s.hasNext() ? s.next() : ""; s.close(); } DirectoryTreeItem[] roots = DirectoryTreeItem.getFileSystemRoots(); if (roots.length > 1) { TreeItem<File> dummyRoot = new TreeItem<File>(); dummyRoot.getChildren().addAll(roots); fileSystemView.setShowRoot(false); fileSystemView.setRoot(dummyRoot); } else { fileSystemView.setRoot(roots[0]); } fileSystemView.getRoot().setExpanded(true); refreshFileSizeLabel(); } public void toggleInShowContentsMode() { isInShowContentsMode = !isInShowContentsMode; refreshFileSystemView(); } public void setFileSizeThreshold(FileSize fileSizeThreshold) { this.fileSizeThreshold = fileSizeThreshold; refreshFileSystemView(); refreshFileSizeLabel(); } public FileSize getFileSizeThreshold() { return fileSizeThreshold; } public void setCharset(Charset charset) { this.charset = charset; refreshFileContentsView(); } public Charset getCharset() { return charset; } public Comparator<File> getFileComparator() { return fileComparator; } public void setFileComparator(Comparator<File> fileComparator) { this.fileComparator = fileComparator; refreshFileContentsView(); } private void refreshFileSizeLabel() { fileSizeThresholdLabel.setText(fileSizeThreshold.getSize() + " " + fileSizeThreshold.getUnit().toString()); } private void refreshFileContentsView() { if (!fileSystemView.getSelectionModel().isEmpty()) { showDirectoryContents(fileSystemView.getSelectionModel().getSelectedItem()); } } public void expandToDirectory(File file) { Iterator<Path> it = file.toPath().iterator(); //FIXME: The below root directory selection *might* not work for Windows systems. // => Do something with `file.toPath().getRoot()`. TreeItem<File> currentDir = fileSystemView.getRoot(); while (it.hasNext()) { final String currDirName = it.next().toString(); FilteredList<TreeItem<File>> matchingChildren = currentDir.getChildren().filtered(elem -> elem.getValue().getName().equals(currDirName)); if (matchingChildren.size() == 1) { matchingChildren.get(0).setExpanded(true); currentDir = matchingChildren.get(0); } } fileSystemView.getSelectionModel().clearSelection(); fileSystemView.getSelectionModel().select(currentDir); fileSystemView.scrollTo(fileSystemView.getSelectionModel().getSelectedIndex()); } private void showDirectoryContents(TreeItem<File> selectedDirectory) { if (selectedDirectory == null) { return; } final WebEngine webEngine = directoryContentView.getEngine(); webEngine.loadContent(!isInShowContentsMode ? getFileNamesInDirectoryHTML(selectedDirectory.getValue()) : getFileContentsInDirectoryHTML(selectedDirectory.getValue())); } private void refreshFileSystemView() { showDirectoryContents(fileSystemView.getSelectionModel().getSelectedItem()); } private String getFileNamesInDirectoryHTML(File directory) { final StringBuilder sb = new StringBuilder(); final DecimalFormat df = new DecimalFormat("0.00"); final File[] files = listFiles(directory); if (files == null) { return ""; } sb.append("<html><head>") .append("<style type=\"text/css\">") .append(fileTreeViewerCSS) .append("</style>") .append("</head><body><div id=\"fileList\"><ul>"); boolean even = false; for (File file : files) { sb.append("<li class=\"") .append(even ? "even" : "odd") .append("\"><span class=\"fileName\">") .append(file.getName()) .append("</span> <span class=\"fileSize\">(") .append(df.format((float) file.length() / 1024)) .append("K)</span>") .append("</li>"); even = !even; } sb.append("</ul></div></body></html>"); return sb.toString(); } private String getFileContentsInDirectoryHTML(File directory) { final StringBuilder sb = new StringBuilder(); final File[] files = listFiles(directory); if (files == null) { return ""; } sb.append("<html>") .append("<body>") .append("<style type=\"text/css\">") .append(fileTreeViewerCSS) .append("</style>"); for (File file : files) { try { String contentsString; if (file.getName().endsWith(".pdf")) { final PDDocument doc = PDDocument.load(file); final StringWriter writer = new StringWriter(); new PDFText2HTML("UTF-8").writeText(doc, writer); contentsString = writer.toString(); writer.close(); doc.close(); } else { byte[] encoded = Files.readAllBytes(file.toPath()); contentsString = new String(encoded, charset); contentsString = contentsString.replace("<", "&lt;"); contentsString = contentsString.replace(">", "&gt;"); contentsString = contentsString.replace("\n", "<br/>"); } sb.append("<div class=\"entry\"><h3>") .append(file.getName()) .append("</h3>") .append("<div class=\"content\">") .append(contentsString) .append("</div>") .append("</div>"); } catch (IOException e) {} } sb.append("</body></html>"); return sb.toString(); } private File[] listFiles(File directory) { if (directory == null) { return new File[0]; } File[] files = directory.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isFile() && filePattern.matcher(pathname.getName().toString()).matches() && pathname.length() <= fileSizeThreshold.toBytes(); } }); if (files == null) { return new File[0]; } Arrays.sort(files, fileComparator); return files; } }
Java
object rec{ def main(args: Array[String]){ def factorial(num: Int): BigInt={ if(num<=1){ 1 } else{ num*factorial(num-1) } } print("Factorial of 4 is: "+factorial(4)) } }
Java
Ext.define("Voyant.notebook.util.Embed", { transferable: ['embed'], embed: function() { // this is for instances embed.apply(this, arguments); }, constructor: function(config) { var me = this; }, statics: { i18n: {}, api: { embeddedParameters: undefined, embeddedConfig: undefined }, embed: function(cmp, config) { if (this.then) { this.then(function(embedded) { embed.call(embedded, cmp, config) }) } else if (Ext.isArray(cmp)) { Voyant.notebook.util.Show.SINGLE_LINE_MODE=true; show("<table><tr>"); cmp.forEach(function(embeddable) { show("<td>"); if (Ext.isArray(embeddable)) { if (embeddable[0].embeddable) { embeddable[0].embed.apply(embeddable[0], embeddable.slice(1)) } else { embed.apply(this, embeddable) } } else { embed.apply(this, embeddable); } show("</td>") }) // for (var i=0; i<arguments.length; i++) { // var unit = arguments[i]; // show("<td>") // unit[0].embed.call(unit[0], unit[1], unit[2]); // show("</td>") // } show("</tr></table>") Voyant.notebook.util.Show.SINGLE_LINE_MODE=false; return } else { // use the default (first) embeddable panel if no panel is specified if (this.embeddable && (!cmp || Ext.isObject(cmp))) { // if the first argument is an object, use it as config instead if (Ext.isObject(cmp)) {config = cmp;} cmp = this.embeddable[0]; } if (Ext.isString(cmp)) { cmp = Ext.ClassManager.getByAlias('widget.'+cmp.toLowerCase()) || Ext.ClassManager.get(cmp); } var isEmbedded = false; if (Ext.isFunction(cmp)) { var name = cmp.getName(); if (this.embeddable && Ext.Array.each(this.embeddable, function(item) { if (item==name) { config = config || {}; var embeddedParams = {}; for (key in Ext.ClassManager.get(Ext.getClassName(cmp)).api) { if (key in config) { embeddedParams[key] = config[key] } } if (!embeddedParams.corpus) { if (Ext.getClassName(this)=='Voyant.data.model.Corpus') { embeddedParams.corpus = this.getId(); } else if (this.getCorpus) { var corpus = this.getCorpus(); if (corpus) { embeddedParams.corpus = this.getCorpus().getId(); } } } Ext.applyIf(config, { style: 'width: '+(config.width || '90%') + (Ext.isNumber(config.width) ? 'px' : '')+ '; height: '+(config.height || '400px') + (Ext.isNumber(config.height) ? 'px' : '') }); delete config.width; delete config.height; var corpus = embeddedParams.corpus; delete embeddedParams.corpus; Ext.applyIf(embeddedParams, Voyant.application.getModifiedApiParams()); var embeddedConfigParamEncodded = Ext.encode(embeddedParams); var embeddedConfigParam = encodeURIComponent(embeddedConfigParamEncodded); var iframeId = Ext.id(); var url = Voyant.application.getBaseUrlFull()+"tool/"+name.substring(name.lastIndexOf(".")+1)+'/?'; if (true || embeddedConfigParam.length>1800) { show('<iframe style="'+config.style+'" id="'+iframeId+'" name="'+iframeId+'"></iframe>'); var dfd = Voyant.application.getDeferred(this); Ext.Ajax.request({ url: Voyant.application.getTromboneUrl(), params: { tool: 'resource.StoredResource', storeResource: embeddedConfigParam } }).then(function(response) { var json = Ext.util.JSON.decode(response.responseText); var params = { minimal: true, embeddedApiId: json.storedResource.id } if (corpus) { params.corpus = corpus; } Ext.applyIf(params, Voyant.application.getModifiedApiParams()); document.getElementById(iframeId).setAttribute("src",url+Ext.Object.toQueryString(params)); dfd.resolve(); }).otherwise(function(response) { showError(response); dfd.reject(); }) } else { show('<iframe src="'+url+embeddedConfigParam+'" style="'+config.style+'" id="'+iframeId+'" name="'+iframeId+'"></iframe>'); } isEmbedded = true; return false; } }, this)===true) { Voyant.notebook.util.Embed.showWidgetNotRecognized.call(this); } if (!isEmbedded) { var embedded = Ext.create(cmp, config); embedded.embed(config); isEmbedded = true; } } if (!isEmbedded) { Voyant.notebook.util.Embed.showWidgetNotRecognized.call(this); } } }, showWidgetNotRecognized: function() { var msg = Voyant.notebook.util.Embed.i18n.widgetNotRecognized; if (this.embeddable) { msg += Voyant.notebook.util.Embed.i18n.tryWidget+'<ul>'+this.embeddable.map(function(cmp) { var widget = cmp.substring(cmp.lastIndexOf(".")+1).toLowerCase() return "\"<a href='../../docs/#!/guide/"+widget+"' target='voyantdocs'>"+widget+"</a>\"" }).join(", ")+"</ul>" } showError(msg) } } }) embed = Voyant.notebook.util.Embed.embed
Java
<!-- This test case covers the following situation: 1. an open tag for a void element 2. the next token is a close tag that does not match (1) --> <html><head><basefont color="blue"></head><body></body></html>
Java
//=========================================================================== // Summary: // IDPKDocÊǸºÔðÎĵµ´ò¿ª£¬»ñÈ¡ÎĵµÒ»Ð©ÊôÐԵĽӿÚÀà¡£ // Usage: // ʹÓÃDPK_CreateDoc½øÐд´½¨£¬Ê¹ÓÃDPK_DestoryDocÏú»Ù¡£ // Remarks: // Null // Date: // 2011-9-15 // Author: // Zhang JingDan (zhangjingdan@duokan.com) //=========================================================================== #ifndef __KERNEL_PDFKIT_PDFLIB_IDKPDOC_H__ #define __KERNEL_PDFKIT_PDFLIB_IDKPDOC_H__ //=========================================================================== #include "KernelRetCode.h" #include "DKPTypeDef.h" class IDKPOutline; class IDKPPage; class IDKPPageEx; class IDkStream; //=========================================================================== class IDKPDoc { public: enum REARRANGE_PAGE_POSITION_TYPE { PREV_PAGE, // ÖØÅÅÉÏÒ»Ò³ LOCATION_PAGE, // ¸ù¾ÝλÖÃÌø×ªµÄÖØÅÅÒ³ NEXT_PAGE, // ÖØÅÅÏÂÒ»Ò³ }; //------------------------------------------- // Summary: // ´ò¿ªÎĵµ¡£ // Parameters: // [in] pFileOP - Ä¿±êÎĵµÎļþ¾ä±ú¡£ // Returns£º // ³É¹¦Ôò·µ»ØDKR_OK£¬Èç¹ûÐèÒª¿ÚÁîÔò·µ»Ø DKR_PDF_NEED_READ_PASSWORD£¬´ò¿ªÊ§°ÜÔò·µ»ØDKR_FAILED¡£ // SDK Version: // ´ÓDKP 1.0¿ªÊ¼Ö§³Ö //------------------------------------------- virtual DK_ReturnCode OpenDoc(IDkStream* pFileOP) = 0; //------------------------------------------- // Summary: // ´«Èë¿ÚÁîÒÔ´ò¿ªÎĵµ¡£ // Parameters: // [in] pFileOP - Ä¿±êÎĵµÎļþ¾ä±ú¡£ // [in] pPwd - ÃÜÂë¡£ // [in] length - ÃÜÂ볤¶È¡£ // Returns£º // ³É¹¦Ôò·µ»ØDK_TRUE£¬Èç¹ûÐèÒª¿ÚÁ´«Èë¿ÚÁî´íÎó£¬Ôò·µ»Ø DKR_PDF_READ_PASSWORD_INCORRECT£¬´ò¿ªÊ§°ÜÔò·µ»ØDK_FALSE¡£ // SDK Version: // ´ÓDKP 2.2.0¿ªÊ¼Ö§³Ö //------------------------------------------- virtual DK_ReturnCode OpenDoc(IDkStream* pFileOP, const DK_BYTE* pPwd, DK_INT length) = 0; //------------------------------------------- // Summary: // ¹Ø±ÕÎĵµ¡£ // SDK Version: // ´ÓDKP 1.0¿ªÊ¼Ö§³Ö //------------------------------------------- virtual DK_VOID CloseDoc() = 0; //------------------------------------------- // Summary: // »ñµÃÒ³Êý¡£ // Returns: // ³É¹¦Ôò·µ»ØÒ³Êý£¬·ñÔò·µ»Ø-1¡£ // SDK Version: // ´ÓDKP 1.0¿ªÊ¼Ö§³Ö //------------------------------------------- virtual DK_INT GetPageCount() = 0; //------------------------------------------- // Summary: // »æÖÆÖ¸¶¨Ò³ÃæÄÚÈÝ¡£ // Parameters: // [in] parrRenderInfo - »æÖƲÎÊý¡£ // Returns: // »æÖƳɹ¦Ôò·µ»Ø1£¬Ê§°ÜÔò·µ»ØÆäËûÖµ¡£ // SDK Version: // ´ÓDKP 1.0¿ªÊ¼Ö§³Ö //------------------------------------------- virtual DK_INT RenderPage(DK_RENDERINFO* parrRenderInfo) = 0; //------------------------------------------- // Summary: // »ñµÃÖ¸¶¨Ò³ÂëµÄÒ³¶ÔÏó¡£ // Parameters: // [in] nPageNum - Ò³Â룬ÓÉ1¿ªÊ¼¡£ // Returns: // ³É¹¦Ôò·µ»ØÖ¸¶¨Ò³ÂëµÄÒ³¶ÔÏó£¬Ê§°ÜÔò·µ»Ø¿Õ¡£ // SDK Version: // ´ÓDKP 1.0¿ªÊ¼Ö§³Ö //------------------------------------------- virtual IDKPPage* GetPage(DK_INT nPageNum) = 0; //------------------------------------------- // Summary: // ÊÍ·ÅÒ³¶ÔÏ󣬵÷ÓúóÒ³¶ÔÏóÖ¸Õë²»ÔÙ¿ÉÓã¬ÔÙ´ÎʹÓÃʱ±ØÐëµ÷ÓÃGetPage»ñÈ¡¶ÔÏó¡£ // Parameters: // [in] pPage - Ò³¶ÔÏóÖ¸Õë¡£ // [in] bAll - ÊÇ·ñÊÍ·ÅËùÓÐÄÚÈÝ¡£ // SDK Version: // ´ÓDKP 1.0¿ªÊ¼Ö§³Ö //------------------------------------------- virtual DK_VOID ReleasePage(IDKPPage* pPage, DK_BOOL bAll = DK_FALSE) = 0; //------------------------------------------- // Summary: // ÉèÖÃÁ÷ʽÅŰæÄ£Ê½£¬Ö»¶ÔÁ÷ʽҳÓÐЧ // Parameters: // [in] typeSetting - ÅŰæÄ£Ê½¡£ // Return Value: // Null // Availability: // ´ÓDKP 2.5.0¿ªÊ¼Ö§³Ö¡£ //------------------------------------------- virtual DK_VOID SetTypeSetting(const DKTYPESETTING &typeSetting) = 0; //------------------------------------------- // Summary: // »ñµÃÖ¸¶¨Á÷λÖõÄÖØÅÅÒ³¶ÔÏó¡£ // Parameters: // [in] pos - Ö¸¶¨ÆðʼλÖà // pos.nChapterIndex ±íʾҳÂ루ÆðʼҳΪ1£©; // pos.nParaIndex ±íʾͨ¹ýµ÷Óà IDKPPage º¯Êý GetPageTextContentStream »ñµÃµÄ PDKPTEXTINFONODE Á´±íϱê; // pos.nElemIndex ±íʾ PDKPTEXTINFONODE.DKPTEXTINFO.strContent ϱê; // [in] option - Ñ¡Ï°üÀ¨Ò³Ãæ¾ØÐΣ¬dpi£¬×ÖºÅËõ·ÅµÈ // [in] posType - Ò³Æ«ÒÆÀàÐÍ // [in/out] ppPageEx - Êä³öÒ³Ãæ¶ÔÏó // Returns: // ³É¹¦Ôò·µ»Ø DKR_OK // SDK Version: // ´ÓDKP 1.0¿ªÊ¼Ö§³Ö //------------------------------------------- virtual DK_ReturnCode GetPageEx(const DK_FLOWPOSITION& pos, const DKP_REARRANGE_PARSER_OPTION& option, REARRANGE_PAGE_POSITION_TYPE posType, IDKPPageEx** ppPageEx) = 0; //------------------------------------------- // Summary: // ÊÍ·ÅÖØÅÅÒ³¶ÔÏ󣬵÷ÓúóÖØÅÅÒ³¶ÔÏóÖ¸Õë²»ÔÙ¿ÉÓã¬ÔÙ´ÎʹÓÃʱ±ØÐëµ÷ÓÃGetPageEx»ñÈ¡¶ÔÏó¡£ // Parameters: // [in] pPage - ÖØÅÅÒ³¶ÔÏóÖ¸Õë¡£ // [in] bAll - ÊÇ·ñÊÍ·ÅËùÓÐÄÚÈÝ¡£ // SDK Version: // ´ÓDKP 1.0¿ªÊ¼Ö§³Ö //------------------------------------------- virtual DK_VOID ReleasePageEx(IDKPPageEx* pPage, DK_BOOL bAll = DK_FALSE) = 0; //------------------------------------------- // Summary: // »ñµÃĿ¼¶ÔÏó¡£ // Returns: // ³É¹¦Ôò·µ»ØÄ¿Â¼¶ÔÏó£¬Ê§°ÜÔò·µ»Ø¿Õ¡£ // SDK Version: // ´ÓDKP 1.0¿ªÊ¼Ö§³Ö //------------------------------------------- virtual IDKPOutline* GetOutline() = 0; //------------------------------------------- // Summary: // ÉèÖÃĬÈÏ×ÖÌåÃû×Ö¡£ // Parameters: // [in] pszDefaultFontFaceName - ×ÖÌåÃû×Ö¡£ // [in] charset - ×ÖÌå±àÂë¡£ // SDK Version: // ´ÓDKP 1.0¿ªÊ¼Ö§³Ö //------------------------------------------- virtual DK_VOID SetDefaultFontFaceName(const DK_WCHAR* pszDefaultFontFaceName, DK_CHARSET_TYPE charset) = 0; //------------------------------------------- // Summary: // »ñÈ¡ÎĵµµÄÔªÊý¾Ý¡£ // Parameters: // [out] pMetaData - ÔªÊý¾Ý,´«Èë¿Õ¼´¿É¡£ // SDK Version: // ´ÓDKP 1.0¿ªÊ¼Ö§³Ö //------------------------------------------- virtual DK_BOOL GetDocMetaData(PDKPMETADATA& pMetaData) = 0; virtual DK_BOOL ReleaseMetaData() = 0; //------------------------------------------- // Summary: // »ñÈ¡µ±Ç°ÎĵµµÄÖØÅÅģʽ¡£ // Parameters: // ÖØÅÅģʽÓÉÄÚºËÅжϣ¬ËùÓÐÒ³ÃæµÄÖØÅžù²ÉÓÃͬһÖÖÖØÅÅģʽ¡£ // SDK Version: // ´ÓDKP 2.4.0¿ªÊ¼Ö§³Ö //------------------------------------------- virtual DKP_REARRANGE_MODE GetRearrangeMode() = 0; public: virtual ~IDKPDoc() {} }; //=========================================================================== #endif
Java
TV Series API ========= TV Series API is developed to make it easier for anyone to feed their own versions of [Popcorn Time CE](https://github.com/PopcornTime-CE/desktop). It contains: - Metadata about TV Shows and individual episodes (taken from Trakt) - Multiple quality magnet links for every episode - Ability to easily filter content to the users' content Installation ============ ```sh # Install NodeJS, MongoDB and Git sudo apt-get install -y node mongodb git # Setup MongoDB dirs mkdir -p /data/db # Clone the repo git clone https://github.com/gnuns/tvseries-api.git # Install dependencies cd tvseries-api npm install # Fire it up! node index.js ``` Hint: the default port os set to `5000` currently, but can be changed in the `config.js` file. Routes ====== The API contains the following 'routes' which produce the example output `show/:imdb_id` - This returns all info and episodes for a particular show. Useful for the "show details" page in your app **Example** `https://<URL HERE>/show/tt1475582` returns the following: ``` { _id: "tt1475582", air_day: "Sunday", air_time: "8:30pm", country: "United Kingdom", images: { poster: "http://slurm.trakt.us/images/posters/178.11.jpg", fanart: "http://slurm.trakt.us/images/fanart/178.11.jpg", banner: "http://slurm.trakt.us/images/banners/178.11.jpg" }, imdb_id: "tt1475582", last_updated: 1406509936365, network: "BBC One", num_seasons: 3, rating: { hated: 157, loved: 12791, votes: 12948, percentage: 93 }, runtime: "90", slug: "sherlock", status: "Continuing", synopsis: "Sherlock depicts 'consulting detective' Sherlock Holmes, who assists the Metropolitan Police Service, primarily D.I. Greg Lestrade, in solving various crimes. Holmes is assisted by his flatmate, Dr. John Watson.", title: "Sherlock", tvdb_id: "176941", year: "2010", episodes: [ {"torrents": { "0": { "peers":0, "seeds":0, "url":"magnet:?xt=urn:btih:T6Y4FG35S54U3CWSV2OPAXRQVXHZJ4WV&dn=Sherlock.2x01.A.Scandal.In.Belgravia.HDTV.XviD-FoV&tr=udp://tracker.openbittorrent.com:80&tr=udp://tracker.publicbt.com:80&tr=udp://tracker.istole.it:80&tr=udp://open.demonii.com:80&tr=udp://tracker.coppersurfer.tk:80" }, "480p": { "peers":0, "seeds":0, "url":"magnet:?xt=urn:btih:T6Y4FG35S54U3CWSV2OPAXRQVXHZJ4WV&dn=Sherlock.2x01.A.Scandal.In.Belgravia.HDTV.XviD-FoV&tr=udp://tracker.openbittorrent.com:80&tr=udp://tracker.publicbt.com:80&tr=udp://tracker.istole.it:80&tr=udp://open.demonii.com:80&tr=udp://tracker.coppersurfer.tk:80"}, "720p": { "peers":0, "seeds":0, "url":"magnet:?xt=urn:btih:GHB4ZITTAO3AMXKNQ4ODBHMFT426NHYU&dn=Sherlock.2x01.A.Scandal.In.Belgravia.720p.HDTV.x264-FoV&tr=udp://tracker.openbittorrent.com:80&tr=udp://tracker.publicbt.com:80&tr=udp://tracker.istole.it:80&tr=udp://open.demonii.com:80&tr=udp://tracker.coppersurfer.tk:80" } }, "first_aired":1325449800, "overview":"Compromising photographs and a case of blackmail threaten the very heart of the British establishment, but for Sherlock and John the game is on in more ways than one as they find themselves battling international terrorism, rogue CIA agents, and a secret conspiracy involving the British government. This case will cast a darker shadow over their lives than they could ever imagine, as the great detective begins a long duel of wits with an antagonist as cold and ruthless and brilliant as himself: to Sherlock Holmes, Irene Adler will always be THE woman.", "title":"A Scandal in Belgravia", "episode":1, "season":2, "tvdb_id":4103396 } ...... ], genres: [ "Action", "Adventure", "Drama", "Crime", "Mystery", "Comedy", "Thriller" ] } ``` `shows/` This returns the number of pages available to list 50 shows at a time (used for pagination etc) `shows/:page` this retuns a list of 50 shows with metadata **Example** `https://<URL HERE>/shows/1` ``` [ { _id: "tt0944947", images: { poster: "http://slurm.trakt.us/images/posters/1395.79.jpg", fanart: "http://slurm.trakt.us/images/fanart/1395.79.jpg", banner: "http://slurm.trakt.us/images/banners/1395.79.jpg" }, imdb_id: "tt0944947", last_updated: 1406509464197, num_seasons: 4, slug: "game-of-thrones", title: "Game of Thrones", tvdb_id: "121361", year: "2011" }, { _id: "tt0903747", images: { poster: "http://slurm.trakt.us/images/posters/126.54.jpg", fanart: "http://slurm.trakt.us/images/fanart/126.54.jpg", banner: "http://slurm.trakt.us/images/banners/126.54.jpg" }, imdb_id: "tt0903747", last_updated: 1406509278746, num_seasons: 5, slug: "breaking-bad", title: "Breaking Bad", tvdb_id: "81189", year: "2008" }, { _id: "tt0898266", images: { poster: "http://slurm.trakt.us/images/posters/34.69.jpg", fanart: "http://slurm.trakt.us/images/fanart/34.69.jpg", banner: "http://slurm.trakt.us/images/banners/34.69.jpg" }, imdb_id: "tt0898266", last_updated: 1406509254635, num_seasons: 7, slug: "the-big-bang-theory", title: "The Big Bang Theory", tvdb_id: "80379", year: "2007" }, { _id: "tt1520211", images: { poster: "http://slurm.trakt.us/images/posters/124.39.jpg", fanart: "http://slurm.trakt.us/images/fanart/124.39.jpg", banner: "http://slurm.trakt.us/images/banners/124.39.jpg" }, imdb_id: "tt1520211", last_updated: 1406510162804, num_seasons: 4, slug: "the-walking-dead", title: "The Walking Dead", tvdb_id: "153021", year: "2010" }, ... ] ``` **Sorting** This route can be sorting and filtered with the following `query string `?sort=` Possible options are - Name (Sort by TV Show title) - Year (Year the TV Show first aired) - Updated (Sort by the most recently aired episode date) You can change the order of the sort by adding `&order=1` or `&order=-1` to the query string **Filtering** You can filter shows by keyowrds using the following `shows/1?keywords=` (Again the 1 is used for pagination) Live example ====== https://eztvapi.ml/
Java
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CustomWallsAndFloorsRedux { public class Settings { public List<Animation> AnimatedTiles { get; set; } = new List<Animation>(); } }
Java
/* * Copyright (C) 2006-2009 Daniel Prevost <dprevost@photonsoftware.org> * * This file is part of Photon (photonsoftware.org). * * This file may be distributed and/or modified under the terms of the * GNU General Public License version 2 or version 3 as published by the * Free Software Foundation and appearing in the file COPYING.GPL2 and * COPYING.GPL3 included in the packaging of this software. * * Licensees holding a valid Photon Commercial license can use this file * in accordance with the terms of their license. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ /* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */ #include "Common/Options.h" #include "Tests/PrintError.h" const bool expectedToPass = false; /* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */ int main() { #if defined(USE_DBC) int errcode = 0; char dummyArgs[100]; char *dummyPtrs[10]; psocOptionHandle handle; bool ok; struct psocOptStruct opts[5] = { { '3', "three", 1, "", "repeat the loop three times" }, { 'a', "address", 0, "QUASAR_ADDRESS", "tcp/ip port number of the server" }, { 'x', "", 1, "DISPLAY", "X display to use" }, { 'v', "verbose", 1, "", "try to explain what is going on" }, { 'z', "zzz", 1, "", "go to sleep..." } }; ok = psocSetSupportedOptions( 5, opts, &handle ); if ( ok != true ) { ERROR_EXIT( expectedToPass, NULL, ; ); } strcpy( dummyArgs, "OptionTest2 --address 12345 -v --zzz" ); /* 012345678901234567890123456789012345 */ dummyPtrs[0] = dummyArgs; dummyPtrs[1] = &dummyArgs[12]; dummyPtrs[2] = &dummyArgs[22]; dummyPtrs[3] = &dummyArgs[28]; dummyPtrs[4] = &dummyArgs[31]; dummyArgs[11] = 0; dummyArgs[21] = 0; dummyArgs[27] = 0; dummyArgs[30] = 0; errcode = psocValidateUserOptions( handle, 5, dummyPtrs, 1 ); if ( errcode != 0 ) { ERROR_EXIT( expectedToPass, NULL, ; ); } psocIsShortOptPresent( NULL, 'a' ); ERROR_EXIT( expectedToPass, NULL, ; ); #else return 1; #endif } /* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */
Java
<?php /** * Kunena Component * @package Kunena.Template.Crypsis * @subpackage Layout.Announcement * * @copyright (C) 2008 - 2016 Kunena Team. All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL * @link http://www.kunena.org **/ defined('_JEXEC') or die; $row = $this->row; $announcement = $this->announcement; ?> <tr> <td class="nowrap hidden-xs"> <?php echo $announcement->displayField('created', 'date_today'); ?> </td> <td class="nowrap"> <div class="overflow"> <?php echo JHtml::_('kunenaforum.link', $announcement->getUri(), $announcement->displayField('title'), null, 'follow'); ?> </div> </td> <?php if ($this->checkbox) : ?> <td class="center"> <?php if ($this->canPublish()) echo JHtml::_('kunenagrid.published', $row, $announcement->published, '', true); ?> </td> <td class="center"> <?php if ($this->canEdit()) echo JHtml::_('kunenagrid.task', $row, 'tick.png', JText::_('COM_KUNENA_ANN_EDIT'), 'edit', '', true); ?> </td> <td class="center"> <?php if ($this->canDelete()) echo JHtml::_('kunenagrid.task', $row, 'publish_x.png', JText::_('COM_KUNENA_ANN_DELETE'), 'delete', '', true); ?> </td> <td> <?php echo $announcement->getAuthor()->username; ?> </td> <?php endif; ?> <td class="center hidden-xs"> <?php echo $announcement->displayField('id'); ?> </td> <?php if ($this->checkbox) : ?> <td class="center"> <?php echo JHtml::_('kunenagrid.id', $row, $announcement->id); ?> </td> <?php endif; ?> </tr>
Java
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>TAU \ Language (API) \ Processing 2+</title> <link rel="icon" href="/favicon.ico" type="image/x-icon" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="Author" content="Processing Foundation" /> <meta name="Publisher" content="Processing Foundation" /> <meta name="Keywords" content="Processing, Sketchbook, Programming, Coding, Code, Art, Design" /> <meta name="Description" content="Processing is a flexible software sketchbook and a language for learning how to code within the context of the visual arts. Since 2001, Processing has promoted software literacy within the visual arts and visual literacy within technology." /> <meta name="Copyright" content="All contents copyright the Processing Foundation, Ben Fry, Casey Reas, and the MIT Media Laboratory" /> <script src="javascript/modernizr-2.6.2.touch.js" type="text/javascript"></script> <link href="css/style.css" rel="stylesheet" type="text/css" /> </head> <body id="Langauge-en" onload="" > <!-- ==================================== PAGE ============================ --> <div id="container"> <!-- ==================================== HEADER ============================ --> <div id="ribbon"> <ul class="left"> <li class="highlight"><a href="http://processing.org/">Processing</a></li> <li><a href="http://p5js.org/">p5.js</a></li> <li><a href="http://py.processing.org/">Processing.py</a></li> </ul> <ul class="right"> <li><a href="https://processingfoundation.org/">Processing Foundation</a></li> </ul> <div class="clear"></div> </div> <div id="header"> <a href="/" title="Back to the Processing cover."><div class="processing-logo no-cover" alt="Processing cover"></div></a> <form name="search" method="get" action="www.google.com/search"> <p><input type="hidden" name="as_sitesearch" value="processing.org" /> <input type="text" name="as_q" value="" size="20" class="text" /> <input type="submit" value=" " /></p> </form> </div> <a id="TOP" name="TOP"></a> <div id="navigation"> <div class="navBar" id="mainnav"> <a href="index.html" class='active'>Language</a><br> <a href="libraries/index.html" >Libraries</a><br> <a href="tools/index.html">Tools</a><br> <a href="environment/index.html">Environment</a><br> </div> <script> document.querySelectorAll(".processing-logo")[0].className = "processing-logo"; </script> </div> <!-- ==================================== CONTENT - Headers ============================ --> <div class="content"> <p class="ref-notice">This reference is for Processing 3.0+. If you have a previous version, use the reference included with your software in the Help menu. If you see any errors or have suggestions, <a href="https://github.com/processing/processing-docs/issues?state=open">please let us know</a>. If you prefer a more technical reference, visit the <a href="http://processing.github.io/processing-javadocs/core/">Processing Core Javadoc</a> and <a href="http://processing.github.io/processing-javadocs/libraries/">Libraries Javadoc</a>.</p> <table cellpadding="0" cellspacing="0" border="0" class="ref-item"> <tr class="name-row"> <th scope="row">Name</th> <td><h3>TAU</h3></td> </tr> <tr class=""> <tr class=""><th scope="row">Examples</th><td><div class="example"><img src="images/TWO_PI.png" alt="example pic" /><pre class="margin"> float x = width/2; float y = height/2; float d = width * 0.8; arc(x, y, d, d, 0, QUARTER_PI); arc(x, y, d-20, d-20, 0, HALF_PI); arc(x, y, d-40, d-40, 0, PI); arc(x, y, d-60, d-60, 0, TAU); </pre></div> </td></tr> <tr class=""> <th scope="row">Description</th> <td> TAU is an alias for TWO_PI, a mathematical constant with the value 6.28318530717958647693. It is twice the ratio of the circumference of a circle to its diameter. It is useful in combination with the trigonometric functions <b>sin()</b> and <b>cos()</b>. </td> </tr> <tr class=""><th scope="row">Related</th><td><a class="code" href="PI.html">PI</a><br /> <a class="code" href="TWO_PI.html">TWO_PI</a><br /> <a class="code" href="HALF_PI.html">HALF_PI</a><br /> <a class="code" href="QUARTER_PI.html">QUARTER_PI</a><br /></td></tr> </table> Updated on October 22, 2015 05:13:21pm EDT<br /><br /> <!-- Creative Commons License --> <div class="license"> <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/"><img alt="Creative Commons License" style="border: none" src="http://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png" /></a> </div> <!-- <?xpacket begin='' id=''?> <x:xmpmeta xmlns:x='adobe:ns:meta/'> <rdf:RDF xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'> <rdf:Description rdf:about='' xmlns:xapRights='http://ns.adobe.com/xap/1.0/rights/'> <xapRights:Marked>True</xapRights:Marked> </rdf:Description> <rdf:Description rdf:about='' xmlns:xapRights='http://ns.adobe.com/xap/1.0/rights/' > <xapRights:UsageTerms> <rdf:Alt> <rdf:li xml:lang='x-default' >This work is licensed under a &lt;a rel=&#34;license&#34; href=&#34;http://creativecommons.org/licenses/by-nc-sa/4.0/&#34;&gt;Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License&lt;/a&gt;.</rdf:li> <rdf:li xml:lang='en' >This work is licensed under a &lt;a rel=&#34;license&#34; href=&#34;http://creativecommons.org/licenses/by-nc-sa/4.0/&#34;&gt;Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License&lt;/a&gt;.</rdf:li> </rdf:Alt> </xapRights:UsageTerms> </rdf:Description> <rdf:Description rdf:about='' xmlns:cc='http://creativecommons.org/ns#'> <cc:license rdf:resource='http://creativecommons.org/licenses/by-nc-sa/4.0/'/> </rdf:Description> </rdf:RDF> </x:xmpmeta> <?xpacket end='r'?> --> </div> <!-- ==================================== FOOTER ============================ --> <div id="footer"> <div id="copyright">Processing is an open project intiated by <a href="http://benfry.com/">Ben Fry</a> and <a href="http://reas.com">Casey Reas</a>. It is developed by a <a href="http://processing.org/about/people/">team of volunteers</a>.</div> <div id="colophon"> <a href="copyright.html">&copy; Info</a> </div> </div> </div> <script src="javascript/jquery-1.9.1.min.js"></script> <script src="javascript/site.js" type="text/javascript"></script> </body> </html>
Java
/* ============================================================ * QupZilla - WebKit based browser * Copyright (C) 2010-2014 David Rosca <nowrep@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ============================================================ */ #ifndef ADBLOCKICON_H #define ADBLOCKICON_H #include "qzcommon.h" #include "clickablelabel.h" #include "adblockrule.h" class QMenu; class QUrl; class BrowserWindow; class QUPZILLA_EXPORT AdBlockIcon : public ClickableLabel { Q_OBJECT public: explicit AdBlockIcon(BrowserWindow* window, QWidget* parent = 0); ~AdBlockIcon(); void popupBlocked(const QString &ruleString, const QUrl &url); QAction* menuAction(); public slots: void setEnabled(bool enabled); void createMenu(QMenu* menu = 0); private slots: void showMenu(const QPoint &pos); void toggleCustomFilter(); void animateIcon(); void stopAnimation(); private: BrowserWindow* m_window; QAction* m_menuAction; QVector<QPair<AdBlockRule*, QUrl> > m_blockedPopups; QTimer* m_flashTimer; int m_timerTicks; bool m_enabled; }; #endif // ADBLOCKICON_H
Java
// opening-tag.hpp // Started 14 Aug 2018 #pragma once #include <string> #include <boost/spirit/include/qi.hpp> namespace client { // namespace fusion = boost::fusion; // namespace phoenix = boost::phoenix; namespace qi = boost::spirit::qi; namespace ascii = boost::spirit::ascii; template<typename Iterator> struct opening_tag : qi::grammar<Iterator, mini_xml_tag(), ascii::space_type> { qi::rule<Iterator, mini_xml_tag(), ascii::space_type> start; qi::rule<Iterator, std::string(), ascii::space_type> head; qi::rule<Iterator, std::string(), ascii::space_type> tail; opening_tag() : base_type{ start } { head %= qi::lexeme[+ascii::alnum]; tail %= qi::no_skip[*(qi::char_ - '>')]; start %= qi::lit('<') >> head >> tail >> qi::lit('>'); } }; }
Java
// Mantid Repository : https://github.com/mantidproject/mantid // // Copyright &copy; 2018 ISIS Rutherford Appleton Laboratory UKRI, // NScD Oak Ridge National Laboratory, European Spallation Source // & Institut Laue - Langevin // SPDX - License - Identifier: GPL - 3.0 + #ifndef MANTID_TESTMESHOBJECT__ #define MANTID_TESTMESHOBJECT__ #include "MantidGeometry/Math/Algebra.h" #include "MantidGeometry/Objects/MeshObject.h" #include "MantidGeometry/Objects/MeshObjectCommon.h" #include "MantidGeometry/Objects/ShapeFactory.h" #include "MantidGeometry/Objects/Track.h" #include "MantidGeometry/Rendering/GeometryHandler.h" #include "MantidKernel/Material.h" #include "MantidKernel/MersenneTwister.h" #include "MantidTestHelpers/ComponentCreationHelper.h" #include "MockRNG.h" #include <cxxtest/TestSuite.h> #include <Poco/DOM/AutoPtr.h> #include <Poco/DOM/Document.h> using namespace Mantid; using namespace Geometry; using Mantid::Kernel::V3D; namespace { std::unique_ptr<MeshObject> createCube(const double size, const V3D &centre) { /** * Create cube of side length size with specified centre, * parellel to axes and non-negative vertex coordinates. */ double min = 0.0 - 0.5 * size; double max = 0.5 * size; std::vector<V3D> vertices; vertices.emplace_back(centre + V3D(max, max, max)); vertices.emplace_back(centre + V3D(min, max, max)); vertices.emplace_back(centre + V3D(max, min, max)); vertices.emplace_back(centre + V3D(min, min, max)); vertices.emplace_back(centre + V3D(max, max, min)); vertices.emplace_back(centre + V3D(min, max, min)); vertices.emplace_back(centre + V3D(max, min, min)); vertices.emplace_back(centre + V3D(min, min, min)); std::vector<uint32_t> triangles; // top face of cube - z max triangles.insert(triangles.end(), {0, 1, 2}); triangles.insert(triangles.end(), {2, 1, 3}); // right face of cube - x max triangles.insert(triangles.end(), {0, 2, 4}); triangles.insert(triangles.end(), {4, 2, 6}); // back face of cube - y max triangles.insert(triangles.end(), {0, 4, 1}); triangles.insert(triangles.end(), {1, 4, 5}); // bottom face of cube - z min triangles.insert(triangles.end(), {7, 5, 6}); triangles.insert(triangles.end(), {6, 5, 4}); // left face of cube - x min triangles.insert(triangles.end(), {7, 3, 5}); triangles.insert(triangles.end(), {5, 3, 1}); // front fact of cube - y min triangles.insert(triangles.end(), {7, 6, 3}); triangles.insert(triangles.end(), {3, 6, 2}); // Use efficient constructor std::unique_ptr<MeshObject> retVal = Mantid::Kernel::make_unique<MeshObject>( std::move(triangles), std::move(vertices), Mantid::Kernel::Material()); return retVal; } std::unique_ptr<MeshObject> createCube(const double size) { /** * Create cube of side length size with vertex at origin, * parellel to axes and non-negative vertex coordinates. */ return createCube(size, V3D(0.5 * size, 0.5 * size, 0.5 * size)); } std::unique_ptr<MeshObject> createOctahedron() { /** * Create octahedron with vertices on the axes at -1 & +1. */ // The octahedron is made slightly bigger than this to // ensure interior points are not rounded to be outside // Opposite vertices have indices differing by 3. double u = 1.0000000001; std::vector<V3D> vertices; vertices.emplace_back(V3D(u, 0, 0)); vertices.emplace_back(V3D(0, u, 0)); vertices.emplace_back(V3D(0, 0, u)); vertices.emplace_back(V3D(-u, 0, 0)); vertices.emplace_back(V3D(0, -u, 0)); vertices.emplace_back(V3D(0, 0, -u)); std::vector<uint32_t> triangles; // +++ face triangles.insert(triangles.end(), {0, 1, 2}); //++- face triangles.insert(triangles.end(), {0, 5, 1}); // +-- face triangles.insert(triangles.end(), {0, 4, 5}); // +-+ face triangles.insert(triangles.end(), {0, 2, 4}); // --- face triangles.insert(triangles.end(), {3, 5, 4}); // --+ face triangles.insert(triangles.end(), {3, 4, 2}); // -++ face triangles.insert(triangles.end(), {3, 2, 1}); // -+- face triangles.insert(triangles.end(), {3, 1, 5}); // Use flexible constructor std::unique_ptr<MeshObject> retVal = Mantid::Kernel::make_unique<MeshObject>( triangles, vertices, Mantid::Kernel::Material()); return retVal; } std::unique_ptr<MeshObject> createLShape() { /** * Create an L shape with vertices at * (0,0,Z) (2,0,Z) (2,1,Z) (1,1,Z) (1,2,Z) & (0,2,Z), * where Z = 0 or 1. */ std::vector<V3D> vertices; vertices.emplace_back(V3D(0, 0, 0)); vertices.emplace_back(V3D(2, 0, 0)); vertices.emplace_back(V3D(2, 1, 0)); vertices.emplace_back(V3D(1, 1, 0)); vertices.emplace_back(V3D(1, 2, 0)); vertices.emplace_back(V3D(0, 2, 0)); vertices.emplace_back(V3D(0, 0, 1)); vertices.emplace_back(V3D(2, 0, 1)); vertices.emplace_back(V3D(2, 1, 1)); vertices.emplace_back(V3D(1, 1, 1)); vertices.emplace_back(V3D(1, 2, 1)); vertices.emplace_back(V3D(0, 2, 1)); std::vector<uint32_t> triangles; // z min triangles.insert(triangles.end(), {0, 5, 1}); triangles.insert(triangles.end(), {1, 3, 2}); triangles.insert(triangles.end(), {3, 5, 4}); // z max triangles.insert(triangles.end(), {6, 7, 11}); triangles.insert(triangles.end(), {11, 9, 10}); triangles.insert(triangles.end(), {9, 7, 8}); // y min triangles.insert(triangles.end(), {0, 1, 6}); triangles.insert(triangles.end(), {6, 1, 7}); // x max triangles.insert(triangles.end(), {1, 2, 7}); triangles.insert(triangles.end(), {7, 2, 8}); // y mid triangles.insert(triangles.end(), {2, 3, 8}); triangles.insert(triangles.end(), {8, 3, 9}); // x mid triangles.insert(triangles.end(), {3, 4, 9}); triangles.insert(triangles.end(), {9, 4, 10}); // y max triangles.insert(triangles.end(), {4, 5, 10}); triangles.insert(triangles.end(), {10, 5, 11}); // x min triangles.insert(triangles.end(), {5, 0, 11}); triangles.insert(triangles.end(), {11, 0, 6}); // Use efficient constructor std::unique_ptr<MeshObject> retVal = Mantid::Kernel::make_unique<MeshObject>( std::move(triangles), std::move(vertices), Mantid::Kernel::Material()); return retVal; } } // namespace class MeshObjectTest : public CxxTest::TestSuite { public: void testConstructor() { std::vector<V3D> vertices; vertices.emplace_back(V3D(0, 0, 0)); vertices.emplace_back(V3D(1, 0, 0)); vertices.emplace_back(V3D(0, 1, 0)); vertices.emplace_back(V3D(0, 0, 1)); std::vector<uint32_t> triangles; triangles.insert(triangles.end(), {1, 2, 3}); triangles.insert(triangles.end(), {2, 1, 0}); triangles.insert(triangles.end(), {3, 0, 1}); triangles.insert(triangles.end(), {0, 3, 2}); // Test flexible constructor TS_ASSERT_THROWS_NOTHING( MeshObject(triangles, vertices, Mantid::Kernel::Material())); // Test eficient constructor TS_ASSERT_THROWS_NOTHING(MeshObject( std::move(triangles), std::move(vertices), Mantid::Kernel::Material())); } void testClone() { auto geom_obj = createOctahedron(); std::unique_ptr<IObject> cloned; TS_ASSERT_THROWS_NOTHING(cloned.reset(geom_obj->clone())); TS_ASSERT(cloned); } void testMaterial() { using Mantid::Kernel::Material; std::vector<V3D> vertices; vertices.emplace_back(V3D(0, 0, 0)); vertices.emplace_back(V3D(1, 0, 0)); vertices.emplace_back(V3D(0, 1, 0)); vertices.emplace_back(V3D(0, 0, 1)); std::vector<uint32_t> triangles; triangles.insert(triangles.end(), {1, 2, 3}); triangles.insert(triangles.end(), {2, 1, 0}); triangles.insert(triangles.end(), {3, 0, 1}); triangles.insert(triangles.end(), {0, 3, 2}); auto testMaterial = Material("arm", PhysicalConstants::getNeutronAtom(13), 45.0); // Test material through flexible constructor auto obj1 = Mantid::Kernel::make_unique<MeshObject>(triangles, vertices, testMaterial); TSM_ASSERT_DELTA("Expected a number density of 45", 45.0, obj1->material().numberDensity(), 1e-12); // Test material through efficient constructor auto obj2 = Mantid::Kernel::make_unique<MeshObject>( std::move(triangles), std::move(vertices), testMaterial); TSM_ASSERT_DELTA("Expected a number density of 45", 45.0, obj2->material().numberDensity(), 1e-12); } void testCloneWithMaterial() { using Mantid::Kernel::Material; auto testMaterial = Material("arm", PhysicalConstants::getNeutronAtom(13), 45.0); auto geom_obj = createOctahedron(); std::unique_ptr<IObject> cloned_obj; TS_ASSERT_THROWS_NOTHING( cloned_obj.reset(geom_obj->cloneWithMaterial(testMaterial))); TSM_ASSERT_DELTA("Expected a number density of 45", 45.0, cloned_obj->material().numberDensity(), 1e-12); } void testHasValidShape() { auto geom_obj = createCube(1.0); TS_ASSERT(geom_obj->hasValidShape()); } void testGetBoundingBoxForCube() { auto geom_obj = createCube(4.1); const double tolerance(1e-10); const BoundingBox &bbox = geom_obj->getBoundingBox(); TS_ASSERT_DELTA(bbox.xMax(), 4.1, tolerance); TS_ASSERT_DELTA(bbox.yMax(), 4.1, tolerance); TS_ASSERT_DELTA(bbox.zMax(), 4.1, tolerance); TS_ASSERT_DELTA(bbox.xMin(), 0.0, tolerance); TS_ASSERT_DELTA(bbox.yMin(), 0.0, tolerance); TS_ASSERT_DELTA(bbox.zMin(), 0.0, tolerance); } void testGetBoundingBoxForOctahedron() { auto geom_obj = createOctahedron(); const double tolerance(1e-10); const BoundingBox &bbox = geom_obj->getBoundingBox(); TS_ASSERT_DELTA(bbox.xMax(), 1.0, tolerance); TS_ASSERT_DELTA(bbox.yMax(), 1.0, tolerance); TS_ASSERT_DELTA(bbox.zMax(), 1.0, tolerance); TS_ASSERT_DELTA(bbox.xMin(), -1.0, tolerance); TS_ASSERT_DELTA(bbox.yMin(), -1.0, tolerance); TS_ASSERT_DELTA(bbox.zMin(), -1.0, tolerance); } void testGetBoundingBoxForLShape() { auto geom_obj = createLShape(); const double tolerance(1e-10); const BoundingBox &bbox = geom_obj->getBoundingBox(); TS_ASSERT_DELTA(bbox.xMax(), 2.0, tolerance); TS_ASSERT_DELTA(bbox.yMax(), 2.0, tolerance); TS_ASSERT_DELTA(bbox.zMax(), 1.0, tolerance); TS_ASSERT_DELTA(bbox.xMin(), 0.0, tolerance); TS_ASSERT_DELTA(bbox.yMin(), 0.0, tolerance); TS_ASSERT_DELTA(bbox.zMin(), 0.0, tolerance); } void testInterceptCubeX() { std::vector<Link> expectedResults; auto geom_obj = createCube(4.0); Track track(V3D(-10, 1, 1), V3D(1, 0, 0)); // format = startPoint, endPoint, total distance so far expectedResults.emplace_back( Link(V3D(0, 1, 1), V3D(4, 1, 1), 14.0, *geom_obj)); checkTrackIntercept(std::move(geom_obj), track, expectedResults); } void testInterceptCubeXY() { std::vector<Link> expectedResults; auto geom_obj = createCube(4.0); Track track(V3D(-8, -6, 1), V3D(0.8, 0.6, 0)); // format = startPoint, endPoint, total distance so far expectedResults.emplace_back( Link(V3D(0, 0, 1), V3D(4, 3, 1), 15.0, *geom_obj)); checkTrackIntercept(std::move(geom_obj), track, expectedResults); } void testInterceptCubeMiss() { std::vector<Link> expectedResults; // left empty as there are no expected results auto geom_obj = createCube(4.0); V3D dir(1., 1., 0.); dir.normalize(); Track track(V3D(-10, 0, 0), dir); checkTrackIntercept(std::move(geom_obj), track, expectedResults); } void testInterceptOctahedronX() { std::vector<Link> expectedResults; auto geom_obj = createOctahedron(); Track track(V3D(-10, 0.2, 0.2), V3D(1, 0, 0)); // format = startPoint, endPoint, total distance so far expectedResults.emplace_back( Link(V3D(-0.6, 0.2, 0.2), V3D(0.6, 0.2, 0.2), 10.6, *geom_obj)); checkTrackIntercept(std::move(geom_obj), track, expectedResults); } void testInterceptOctahedronXthroughEdge() { std::vector<Link> expectedResults; auto geom_obj = createOctahedron(); Track track(V3D(-10, 0.2, 0.0), V3D(1, 0, 0)); // format = startPoint, endPoint, total distance so far expectedResults.emplace_back( Link(V3D(-0.8, 0.2, 0.0), V3D(0.8, 0.2, 0.0), 10.8, *geom_obj)); checkTrackIntercept(std::move(geom_obj), track, expectedResults); } void testInterceptOctahedronXthroughVertex() { std::vector<Link> expectedResults; auto geom_obj = createOctahedron(); Track track(V3D(-10, 0.0, 0.0), V3D(1, 0, 0)); // format = startPoint, endPoint, total distance so far expectedResults.emplace_back( Link(V3D(-1.0, 0.0, 0.0), V3D(1.0, 0.0, 0.0), 11.0, *geom_obj)); checkTrackIntercept(std::move(geom_obj), track, expectedResults); } void testInterceptLShapeTwoPass() { std::vector<Link> expectedResults; auto geom_obj = createLShape(); V3D dir(1., -1., 0.); dir.normalize(); Track track(V3D(0, 2.5, 0.5), dir); // format = startPoint, endPoint, total distance so far expectedResults.emplace_back( Link(V3D(0.5, 2, 0.5), V3D(1, 1.5, 0.5), 1.4142135, *geom_obj)); expectedResults.emplace_back( Link(V3D(1.5, 1, 0.5), V3D(2, 0.5, 0.5), 2.828427, *geom_obj)); checkTrackIntercept(std::move(geom_obj), track, expectedResults); } void testInterceptLShapeMiss() { std::vector<Link> expectedResults; // left empty as there are no expected results auto geom_obj = createLShape(); // Passes through convex hull of L-Shape Track track(V3D(1.1, 1.1, -1), V3D(0, 0, 1)); checkTrackIntercept(std::move(geom_obj), track, expectedResults); } void testTrackTwoIsolatedCubes() /** Test a track going through two objects */ { auto object1 = createCube(2.0, V3D(0.0, 0.0, 0.0)); auto object2 = createCube(2.0, V3D(5.5, 0.0, 0.0)); Track TL(Kernel::V3D(-5, 0, 0), Kernel::V3D(1, 0, 0)); // CARE: This CANNOT be called twice TS_ASSERT(object1->interceptSurface(TL) != 0); TS_ASSERT(object2->interceptSurface(TL) != 0); std::vector<Link> expectedResults; expectedResults.emplace_back( Link(V3D(-1, 0, 0), V3D(1, 0, 0), 6, *object1)); expectedResults.emplace_back( Link(V3D(4.5, 0, 0), V3D(6.5, 0, 0), 11.5, *object2)); checkTrackIntercept(TL, expectedResults); } void testTrackTwoTouchingCubes() /** Test a track going through two objects */ { auto object1 = createCube(2.0, V3D(0.0, 0.0, 0.0)); auto object2 = createCube(4.0, V3D(3.0, 0.0, 0.0)); Track TL(Kernel::V3D(-5, 0, 0), Kernel::V3D(1, 0, 0)); // CARE: This CANNOT be called twice TS_ASSERT(object1->interceptSurface(TL) != 0); TS_ASSERT(object2->interceptSurface(TL) != 0); std::vector<Link> expectedResults; expectedResults.emplace_back( Link(V3D(-1, 0, 0), V3D(1, 0, 0), 6, *object1)); expectedResults.emplace_back( Link(V3D(1, 0, 0), V3D(5, 0, 0), 10.0, *object2)); checkTrackIntercept(TL, expectedResults); } void checkTrackIntercept(Track &track, const std::vector<Link> &expectedResults) { size_t index = 0; for (auto it = track.cbegin(); it != track.cend(); ++it) { if (index < expectedResults.size()) { TS_ASSERT_DELTA(it->distFromStart, expectedResults[index].distFromStart, 1e-6); TS_ASSERT_DELTA(it->distInsideObject, expectedResults[index].distInsideObject, 1e-6); TS_ASSERT_EQUALS(it->componentID, expectedResults[index].componentID); TS_ASSERT_EQUALS(it->entryPoint, expectedResults[index].entryPoint); TS_ASSERT_EQUALS(it->exitPoint, expectedResults[index].exitPoint); } ++index; } TS_ASSERT_EQUALS(index, expectedResults.size()); } void checkTrackIntercept(IObject_uptr obj, Track &track, const std::vector<Link> &expectedResults) { int unitCount = obj->interceptSurface(track); TS_ASSERT_EQUALS(unitCount, expectedResults.size()); checkTrackIntercept(track, expectedResults); } void testIsOnSideCube() { auto geom_obj = createCube(1.0); // inside TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 0.5, 0.5)), false); // centre TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 0.1, 0.5)), false); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 0.9, 0.5)), false); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 0.5, 0.1)), false); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 0.5, 0.9)), false); // on the faces TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.0, 0.5, 0.5)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 0.5, 0.0)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 0.0, 0.5)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.0, 0.5, 0.5)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 0.5, 1.0)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 1.0, 0.5)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.0, 0.1, 0.9)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.1, 0.0, 0.9)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.0, 0.9, 0.1)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.1, 1.0, 0.9)), true); // on the edges TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 0.0, 0.0)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.0, 0.5, 0.0)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.0, 0.0, 0.5)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 0.0, 1.0)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.0, 0.5, 0.0)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.0, 1.0, 0.5)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 1.0, 1.0)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.0, 0.5, 1.0)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.0, 1.0, 0.5)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.1, 1.0, 0.0)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.0, 0.9, 0.0)), true); // on the vertices TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.0, 0.0, 0.0)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.0, 0.0, 1.0)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.0, 1.0, 0.0)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.0, 1.0, 1.0)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.0, 0.0, 0.0)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.0, 0.0, 1.0)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.0, 1.0, 0.0)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.0, 1.0, 1.0)), true); // out side TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 1.1, 0.5)), false); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, -0.1, 0.5)), false); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 0.5, -0.1)), false); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.1, 0.0, 1.1)), false); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.3, 0.9, 0.0)), false); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(-3.3, 2.0, 0.9)), false); } void testIsValidCube() { auto geom_obj = createCube(1.0); // inside TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 0.5, 0.5)), true); // centre TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 0.1, 0.5)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 0.9, 0.5)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 0.5, 0.1)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 0.5, 0.9)), true); // on the faces TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.0, 0.5, 0.5)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 0.5, 0.0)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 0.0, 0.5)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.0, 0.5, 0.5)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 0.5, 1.0)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 1.0, 0.5)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.0, 0.1, 0.9)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.1, 0.0, 0.9)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.0, 0.9, 0.1)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.1, 1.0, 0.9)), true); // on the edges TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 0.0, 0.0)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.0, 0.5, 0.0)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.0, 0.0, 0.5)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 0.0, 1.0)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.0, 0.5, 0.0)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.0, 1.0, 0.5)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 1.0, 1.0)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.0, 0.5, 1.0)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.0, 1.0, 0.5)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.1, 1.0, 0.0)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.0, 0.9, 0.0)), true); // on the vertices TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.0, 0.0, 0.0)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.0, 0.0, 1.0)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.0, 1.0, 0.0)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.0, 1.0, 1.0)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.0, 0.0, 0.0)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.0, 0.0, 1.0)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.0, 1.0, 0.0)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.0, 1.0, 1.0)), true); // out side TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 1.1, 0.5)), false); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, -0.1, 0.5)), false); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 0.5, -0.1)), false); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.1, 0.0, 1.1)), false); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.3, 0.9, 0.0)), false); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(-3.3, 2.0, 0.9)), false); } void testIsOnSideOctahedron() { auto geom_obj = createOctahedron(); // inside TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.0, 0.0, 0.0)), false); // centre TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 0.2, 0.2)), false); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.2, 0.5, -0.2)), false); // on face TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 0.3, 0.2)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, -0.3, 0.2)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.4, -0.4, -0.2)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(-0.4, 0.3, 0.3)), true); // on edge TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.0, 0.5, 0.5)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.0, -0.5, -0.5)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.7, 0.0, 0.3)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(-0.7, 0.0, -0.3)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.8, 0.2, 0.0)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(-0.8, 0.2, 0.0)), true); // on vertex TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.0, 0.0, 0.0)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(-1.0, 0.0, 0.0)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.0, 1.0, 0.0)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.0, -1.0, 0.0)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.0, 0.0, 1.0)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.0, 0.0, -1.0)), true); // out side TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.35, 0.35, 0.35)), false); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.35, -0.35, -0.35)), false); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(-0.35, 0.35, 0.35)), false); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(-0.35, 0.35, -0.35)), false); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(2.0, 2.0, 0.0)), false); } void testIsValidOctahedron() { auto geom_obj = createOctahedron(); // inside TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.0, 0.0, 0.0)), true); // centre TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 0.2, 0.2)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.2, 0.5, -0.2)), true); // on face TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 0.3, 0.2)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, -0.3, 0.2)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.4, -0.4, -0.2)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(-0.4, 0.3, 0.3)), true); // on edge TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.0, 0.5, 0.5)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.0, -0.5, -0.5)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.7, 0.0, 0.3)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(-0.7, 0.0, -0.3)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.8, 0.2, 0.0)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(-0.8, 0.2, 0.0)), true); // on vertex TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.0, 0.0, 0.0)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(-1.0, 0.0, 0.0)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.0, 1.0, 0.0)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.0, -1.0, 0.0)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.0, 0.0, 1.0)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.0, 0.0, -1.0)), true); // out side TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.35, 0.35, 0.35)), false); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.35, -0.35, -0.35)), false); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(-0.35, 0.35, 0.35)), false); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(-0.35, 0.35, -0.35)), false); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(2.0, 2.0, 0.0)), false); } void testIsOnSideLShape() { auto geom_obj = createLShape(); // inside TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 0.5, 0.5)), false); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.5, 0.5, 0.5)), false); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 1.5, 0.5)), false); // on front and back TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 0.5, 0.0)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.5, 0.5, 0.0)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 1.5, 0.0)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 0.5, 1.0)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.5, 0.5, 1.0)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 1.5, 1.0)), true); // on sides TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.0, 0.0, 0.5)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.0, 1.0, 0.5)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(2.0, 0.5, 0.5)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 2.0, 0.5)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.5, 1.0, 0.5)), true); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.0, 1.5, 0.5)), true); // out side TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 0.5, 1.5)), false); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(2.0, 2.0, 0.5)), false); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(2.0, 2.0, 0.0)), false); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.1, 1.1, 0.5)), false); TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.1, 1.1, 1.0)), false); } void testIsValidLShape() { auto geom_obj = createLShape(); // inside TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 0.5, 0.5)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.5, 0.5, 0.5)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 1.5, 0.5)), true); // on front and back TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 0.5, 0.0)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.5, 0.5, 0.0)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 1.5, 0.0)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 0.5, 1.0)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.5, 0.5, 1.0)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 1.5, 1.0)), true); // on sides TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.0, 0.0, 0.5)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.0, 1.0, 0.5)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(2.0, 0.5, 0.5)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 2.0, 0.5)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.5, 1.0, 0.5)), true); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.0, 1.5, 0.5)), true); // out side TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 0.5, 1.5)), false); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(2.0, 2.0, 0.5)), false); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(2.0, 2.0, 0.0)), false); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.1, 1.1, 0.5)), false); TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.1, 1.1, 1.0)), false); } void testCalcValidTypeCube() { auto geom_obj = createCube(1.0); // entry or exit on the normal TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.0, 0.5, 0.5), V3D(1, 0, 0)), 1); TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.0, 0.5, 0.5), V3D(-1, 0, 0)), -1); TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(1.0, 0.5, 0.5), V3D(1, 0, 0)), -1); TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(1.0, 0.5, 0.5), V3D(-1, 0, 0)), 1); TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.5, 0.0, 0.5), V3D(0, 1, 0)), 1); TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.5, 0.0, 0.5), V3D(0, -1, 0)), -1); TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.5, 1.0, 0.5), V3D(0, 1, 0)), -1); TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.5, 1.0, 0.5), V3D(0, -1, 0)), 1); // glancing blow on edge TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.0, 0.0, 0.5), V3D(1, -1, 0)), 0); TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.5, 0.0, 0.0), V3D(0, -1, 1)), 0); // entry of exit on edge TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.0, 0.0, 0.5), V3D(1, 1, 0)), 1); TS_ASSERT_EQUALS( geom_obj->calcValidType(V3D(0.0, 0.0, 0.5), V3D(-1, -1, 0)), -1); // not on the normal TS_ASSERT_EQUALS( geom_obj->calcValidType(V3D(0.0, 0.5, 0.5), V3D(0.5, 0.5, 0)), 1); TS_ASSERT_EQUALS( geom_obj->calcValidType(V3D(1.0, 0.5, 0.5), V3D(0.5, 0.5, 0)), -1); } void testCalcValidOctahedron() { auto geom_obj = createOctahedron(); // entry or exit on the normal TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.2, 0.3, 0.5), V3D(1, 1, 1)), -1); TS_ASSERT_EQUALS( geom_obj->calcValidType(V3D(0.2, 0.3, 0.5), V3D(-1, -1, -1)), 1); TS_ASSERT_EQUALS( geom_obj->calcValidType(V3D(-0.2, -0.3, -0.5), V3D(1, 1, 1)), 1); TS_ASSERT_EQUALS( geom_obj->calcValidType(V3D(-0.2, -0.3, -0.5), V3D(-1, -1, -1)), -1); TS_ASSERT_EQUALS( geom_obj->calcValidType(V3D(0.5, 0.2, -0.3), V3D(1, 1, -1)), -1); TS_ASSERT_EQUALS( geom_obj->calcValidType(V3D(0.5, 0.2, -0.3), V3D(-1, -1, 1)), 1); TS_ASSERT_EQUALS( geom_obj->calcValidType(V3D(-0.5, -0.2, 0.3), V3D(1, 1, -1)), 1); TS_ASSERT_EQUALS( geom_obj->calcValidType(V3D(-0.5, -0.2, 0.3), V3D(-1, -1, 1)), -1); // glancing blow on edge TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.0, 0.5, 0.5), V3D(1, 0, 0)), 0); // entry or exit at edge TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.0, -0.5, 0.5), V3D(0, 1, 0)), 1); TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.0, 0.5, 0.5), V3D(0, 1, 0)), -1); // not on the normal TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.2, 0.3, 0.5), V3D(0, 1, 0)), -1); TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.2, -0.3, 0.5), V3D(0, 1, 0)), 1); } void testCalcValidTypeLShape() { auto geom_obj = createLShape(); // entry or exit on the normal TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.0, 1.5, 0.5), V3D(1, 0, 0)), 1); TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.0, 1.5, 0.5), V3D(-1, 0, 0)), -1); TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(1.0, 1.5, 0.5), V3D(1, 0, 0)), -1); TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(1.0, 1.5, 0.5), V3D(-1, 0, 0)), 1); TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.5, 2.0, 0.5), V3D(0, 1, 0)), -1); TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.5, 2.0, 0.5), V3D(0, -1, 0)), 1); TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.5, 0.0, 0.5), V3D(0, 1, 0)), 1); TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.5, 0.0, 0.5), V3D(0, -1, 0)), -1); // glancing blow on edge TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.0, 0.0, 0.5), V3D(1, -1, 0)), 0); // glancing blow on edge from inside TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(1.0, 1.0, 0.5), V3D(1, -1, 0)), 0); // not on the normal TS_ASSERT_EQUALS( geom_obj->calcValidType(V3D(1.0, 1.5, 0.5), V3D(0.5, 0.5, 0)), -1); TS_ASSERT_EQUALS( geom_obj->calcValidType(V3D(1.0, 1.5, 0.5), V3D(-0.5, 0.5, 0)), 1); } void testFindPointInCube() { auto geom_obj = createCube(1.0); Kernel::V3D pt; TS_ASSERT_EQUALS(geom_obj->getPointInObject(pt), 1); TS_ASSERT_LESS_THAN_EQUALS(0.0, pt.X()); TS_ASSERT_LESS_THAN_EQUALS(pt.X(), 1.0); TS_ASSERT_LESS_THAN_EQUALS(0.0, pt.Y()); TS_ASSERT_LESS_THAN_EQUALS(pt.Y(), 1.0); TS_ASSERT_LESS_THAN_EQUALS(0.0, pt.Z()); TS_ASSERT_LESS_THAN_EQUALS(pt.Z(), 1.0); } void testFindPointInOctahedron() { auto geom_obj = createOctahedron(); Kernel::V3D pt; TS_ASSERT_EQUALS(geom_obj->getPointInObject(pt), 1); TS_ASSERT_LESS_THAN_EQUALS(fabs(pt.X()) + fabs(pt.Y()) + fabs(pt.Z()), 1.0); } void testFindPointInLShape() { auto geom_obj = createLShape(); Kernel::V3D pt; TS_ASSERT_EQUALS(geom_obj->getPointInObject(pt), 1); TS_ASSERT_LESS_THAN_EQUALS(0.0, pt.X()); TS_ASSERT_LESS_THAN_EQUALS(pt.X(), 2.0); TS_ASSERT_LESS_THAN_EQUALS(0.0, pt.Y()); TS_ASSERT_LESS_THAN_EQUALS(pt.Y(), 2.0); TS_ASSERT_LESS_THAN_EQUALS(0.0, pt.Z()); TS_ASSERT_LESS_THAN_EQUALS(pt.Z(), 1.0); TS_ASSERT(pt.X() <= 1.0 || pt.Y() <= 1.0) } void testGeneratePointInside() { using namespace ::testing; // Generate "random" sequence MockRNG rng; Sequence rand; EXPECT_CALL(rng, nextValue()).InSequence(rand).WillOnce(Return(0.45)); EXPECT_CALL(rng, nextValue()).InSequence(rand).WillOnce(Return(0.55)); EXPECT_CALL(rng, nextValue()).InSequence(rand).WillOnce(Return(0.65)); // Random sequence set up so as to give point (0.90, 1.10, 0.65) auto geom_obj = createLShape(); size_t maxAttempts(1); V3D point; TS_ASSERT_THROWS_NOTHING( point = geom_obj->generatePointInObject(rng, maxAttempts)); const double tolerance(1e-10); TS_ASSERT_DELTA(0.90, point.X(), tolerance); TS_ASSERT_DELTA(1.10, point.Y(), tolerance); TS_ASSERT_DELTA(0.65, point.Z(), tolerance); } void testGeneratePointInsideRespectsMaxAttempts() { using namespace ::testing; // Generate "random" sequence MockRNG rng; Sequence rand; EXPECT_CALL(rng, nextValue()).InSequence(rand).WillOnce(Return(0.1)); EXPECT_CALL(rng, nextValue()).InSequence(rand).WillOnce(Return(0.2)); EXPECT_CALL(rng, nextValue()).InSequence(rand).WillOnce(Return(0.3)); // Random sequence set up so as to give point (-0.8, -0.6, -0.4), // which is outside the octahedron auto geom_obj = createOctahedron(); size_t maxAttempts(1); TS_ASSERT_THROWS(geom_obj->generatePointInObject(rng, maxAttempts), std::runtime_error); } void testVolumeOfCube() { double size = 3.7; auto geom_obj = createCube(size); TS_ASSERT_DELTA(geom_obj->volume(), size * size * size, 1e-6) } void testVolumeOfOctahedron() { auto geom_obj = createOctahedron(); TS_ASSERT_DELTA(geom_obj->volume(), 4.0 / 3.0, 1e-3) } void testVolumeOfLShape() { auto geom_obj = createLShape(); TS_ASSERT_DELTA(geom_obj->volume(), 3.0, 1e-6) // 3.5 is the volume of the convex hull // 4.0 is the volume of the bounding box } void testSolidAngleCube() /** Test solid angle calculation for a cube. */ { auto geom_obj = createCube(1.0); // Cube centre at 0.5, 0.5, 0.5 double satol = 1e-3; // tolerance for solid angle // solid angle at distance 0.5 should be 4pi/6 by symmetry TS_ASSERT_DELTA(geom_obj->solidAngle(V3D(1.5, 0.5, 0.5)), M_PI * 2.0 / 3.0, satol); TS_ASSERT_DELTA(geom_obj->solidAngle(V3D(-0.5, 0.5, 0.5)), M_PI * 2.0 / 3.0, satol); TS_ASSERT_DELTA(geom_obj->solidAngle(V3D(0.5, 1.5, 0.5)), M_PI * 2.0 / 3.0, satol); TS_ASSERT_DELTA(geom_obj->solidAngle(V3D(0.5, -0.5, 0.5)), M_PI * 2.0 / 3.0, satol); TS_ASSERT_DELTA(geom_obj->solidAngle(V3D(0.5, 0.5, 1.5)), M_PI * 2.0 / 3.0, satol); TS_ASSERT_DELTA(geom_obj->solidAngle(V3D(0.5, 0.5, -0.5)), M_PI * 2.0 / 3.0, satol); } void testSolidAngleScaledCube() /** Test solid angle calculation for a cube that is scaled. */ { auto geom_obj = createCube(2.0); auto scale = V3D(0.5, 0.5, 0.5); double satol = 1e-3; // tolerance for solid angle // solid angle at distance 0.5 should be 4pi/6 by symmetry TS_ASSERT_DELTA(geom_obj->solidAngle(V3D(1.5, 0.5, 0.5), scale), M_PI * 2.0 / 3.0, satol); TS_ASSERT_DELTA(geom_obj->solidAngle(V3D(-0.5, 0.5, 0.5), scale), M_PI * 2.0 / 3.0, satol); TS_ASSERT_DELTA(geom_obj->solidAngle(V3D(0.5, 1.5, 0.5), scale), M_PI * 2.0 / 3.0, satol); TS_ASSERT_DELTA(geom_obj->solidAngle(V3D(0.5, -0.5, 0.5), scale), M_PI * 2.0 / 3.0, satol); TS_ASSERT_DELTA(geom_obj->solidAngle(V3D(0.5, 0.5, 1.5), scale), M_PI * 2.0 / 3.0, satol); TS_ASSERT_DELTA(geom_obj->solidAngle(V3D(0.5, 0.5, -0.5), scale), M_PI * 2.0 / 3.0, satol); } void testOutputForRendering() /* Here we test the output functions used in rendering */ { auto geom_obj = createOctahedron(); TS_ASSERT_EQUALS(geom_obj->numberOfTriangles(), 8); TS_ASSERT_EQUALS(geom_obj->numberOfVertices(), 6); TS_ASSERT_THROWS_NOTHING(geom_obj->getTriangles()); TS_ASSERT_THROWS_NOTHING(geom_obj->getVertices()); } void testRotation() /* Test Rotating a mesh */ { auto lShape = createLShape(); const double valueList[] = {0, -1, 0, 1, 0, 0, 0, 0, 1}; const std::vector<double> rotationMatrix = std::vector<double>(std::begin(valueList), std::end(valueList)); const Kernel::Matrix<double> rotation = Kernel::Matrix<double>(rotationMatrix); const double checkList[] = {0, 0, 0, 0, 2, 0, -1, 2, 0, -1, 1, 0, -2, 1, 0, -2, 0, 0, 0, 0, 1, 0, 2, 1, -1, 2, 1, -1, 1, 1, -2, 1, 1, -2, 0, 1}; auto checkVector = std::vector<double>(std::begin(checkList), std::end(checkList)); TS_ASSERT_THROWS_NOTHING(lShape->rotate(rotation)); auto rotated = lShape->getVertices(); TS_ASSERT_DELTA(rotated, checkVector, 1e-8); } void testTranslation() /* Test Translating a mesh */ { auto octahedron = createOctahedron(); V3D translation = V3D(1, 2, 3); const double checkList[] = {2, 2, 3, 1, 3, 3, 1, 2, 4, 0, 2, 3, 1, 1, 3, 1, 2, 2}; auto checkVector = std::vector<double>(std::begin(checkList), std::end(checkList)); TS_ASSERT_THROWS_NOTHING(octahedron->translate(translation)); auto moved = octahedron->getVertices(); TS_ASSERT_DELTA(moved, checkVector, 1e-8); } }; // ----------------------------------------------------------------------------- // Performance tests // ----------------------------------------------------------------------------- class MeshObjectTestPerformance : public CxxTest::TestSuite { public: // This pair of boilerplate methods prevent the suite being created statically // This means the constructor isn't called when running other tests static MeshObjectTestPerformance *createSuite() { return new MeshObjectTestPerformance(); } static void destroySuite(MeshObjectTestPerformance *suite) { delete suite; } MeshObjectTestPerformance() : rng(200000), octahedron(createOctahedron()), lShape(createLShape()), smallCube(createCube(0.2)) { testPoints = create_test_points(); testRays = create_test_rays(); translation = create_translation_vector(); rotation = create_rotation_matrix(); } void test_rotate(const Kernel::Matrix<double> &) { const size_t number(10000); for (size_t i = 0; i < number; ++i) { octahedron->rotate(rotation); } } void test_translate(Kernel::V3D) { const size_t number(10000); for (size_t i = 0; i < number; ++i) { octahedron->translate(translation); } } void test_isOnSide() { const size_t number(10000); for (size_t i = 0; i < number; ++i) { octahedron->isOnSide(testPoints[i % testPoints.size()]); } } void test_isValid() { const size_t number(10000); for (size_t i = 0; i < number; ++i) { octahedron->isValid(testPoints[i % testPoints.size()]); } } void test_calcValidType() { const size_t number(10000); for (size_t i = 0; i < number; ++i) { size_t j = i % testRays.size(); octahedron->calcValidType(testRays[j].startPoint(), testRays[j].direction()); } } void test_interceptSurface() { const size_t number(10000); Track testRay; for (size_t i = 0; i < number; ++i) { octahedron->interceptSurface(testRays[i % testRays.size()]); } } void test_solid_angle() { const size_t number(10000); for (size_t i = 0; i < number; ++i) { smallCube->solidAngle(testPoints[i % testPoints.size()]); } } void test_solid_angle_scaled() { const size_t number(10000); for (size_t i = 0; i < number; ++i) { smallCube->solidAngle(testPoints[i % testPoints.size()], V3D(0.5, 1.33, 1.5)); } } void test_volume() { const size_t numberOfRuns(10000); for (size_t i = 0; i < numberOfRuns; ++i) { octahedron->volume(); lShape->volume(); } } void test_getPointInObject() { const size_t numberOfRuns(1000); V3D pDummy; for (size_t i = 0; i < numberOfRuns; ++i) { octahedron->getPointInObject(pDummy); lShape->getPointInObject(pDummy); smallCube->getPointInObject(pDummy); } } void test_generatePointInside_Convex_Solid() { const size_t npoints(6000); const size_t maxAttempts(500); for (size_t i = 0; i < npoints; ++i) { octahedron->generatePointInObject(rng, maxAttempts); } } void test_generatePointInside_NonConvex_Solid() { const size_t npoints(6000); const size_t maxAttempts(500); for (size_t i = 0; i < npoints; ++i) { lShape->generatePointInObject(rng, maxAttempts); } } void test_output_for_rendering() { const size_t numberOfRuns(30000); for (size_t i = 0; i < numberOfRuns; ++i) { octahedron->getVertices(); octahedron->getTriangles(); lShape->getVertices(); lShape->getTriangles(); } } V3D create_test_point(size_t index, size_t dimension) { // Create a test point with coordinates within [-1.0, 0.0] // for applying to octahedron V3D output; double interval = 1.0 / static_cast<double>(dimension - 1); output.setX((static_cast<double>(index % dimension)) * interval); index /= dimension; output.setY((static_cast<double>(index % dimension)) * interval); index /= dimension; output.setZ((static_cast<double>(index % dimension)) * interval); return output; } std::vector<V3D> create_test_points() { // Create a vector of test points size_t dim = 5; size_t num = dim * dim * dim; std::vector<V3D> output; output.reserve(num); for (size_t i = 0; i < num; ++i) { output.push_back(create_test_point(i, dim)); } return output; } Track create_test_ray(size_t index, size_t startDim, size_t dirDim) { // create a test ray const V3D shift(0.01, -1.0 / 77, -1.0 / 117); V3D startPoint = create_test_point(index, startDim); V3D direction = V3D(0.0, 0.0, 0.0) - create_test_point(index, dirDim); direction += shift; // shift to avoid divide by zero error direction.normalize(); return Track(startPoint, direction); } std::vector<Track> create_test_rays() { size_t sDim = 3; size_t dDim = 2; size_t num = sDim * sDim * sDim * dDim * dDim * dDim; std::vector<Track> output; output.reserve(num); for (size_t i = 0; i < num; ++i) { output.push_back(create_test_ray(i, sDim, dDim)); } return output; } V3D create_translation_vector() { V3D translate = Kernel::V3D(5, 5, 15); return translate; } Kernel::Matrix<double> create_rotation_matrix() { double valueList[] = {0, -1, 0, 1, 0, 0, 0, 0, 1}; const std::vector<double> rotationMatrix = std::vector<double>(std::begin(valueList), std::end(valueList)); Kernel::Matrix<double> rotation = Kernel::Matrix<double>(rotationMatrix); return rotation; } private: Mantid::Kernel::MersenneTwister rng; std::unique_ptr<MeshObject> octahedron; std::unique_ptr<MeshObject> lShape; std::unique_ptr<MeshObject> smallCube; std::vector<V3D> testPoints; std::vector<Track> testRays; V3D translation; Kernel::Matrix<double> rotation; }; #endif // MANTID_TESTMESHOBJECT__
Java
//: pony/PartyFavor.java package pokepon.pony; import pokepon.enums.*; /** Party Favor * Good def and spa, lacks Hp and Speed * * @author silverweed */ public class PartyFavor extends Pony { public PartyFavor(int _level) { super(_level); name = "Party Favor"; type[0] = Type.LAUGHTER; type[1] = Type.HONESTY; race = Race.UNICORN; sex = Sex.MALE; baseHp = 60; baseAtk = 80; baseDef = 100; baseSpatk = 100; baseSpdef = 80; baseSpeed = 60; /* Learnable Moves */ learnableMoves.put("Tackle",1); learnableMoves.put("Hidden Talent",1); learnableMoves.put("Mirror Pond",1); learnableMoves.put("Dodge",1); } }
Java
using System; namespace GalleryServerPro.Business.Interfaces { /// <summary> /// A collection of <see cref="IUserAccount" /> objects. /// </summary> public interface IUserAccountCollection : System.Collections.Generic.ICollection<IUserAccount> { /// <summary> /// Gets a list of user names for accounts in the collection. This is equivalent to iterating through each <see cref="IUserAccount" /> /// and compiling a string array of the <see cref="IUserAccount.UserName" /> properties. /// </summary> /// <returns>Returns a string array of user names of accounts in the collection.</returns> string[] GetUserNames(); /// <summary> /// Sort the objects in this collection based on the <see cref="IUserAccount.UserName" /> property. /// </summary> void Sort(); /// <summary> /// Adds the user accounts to the current collection. /// </summary> /// <param name="userAccounts">The user accounts to add to the current collection.</param> /// <exception cref="ArgumentNullException">Thrown when <paramref name="userAccounts" /> is null.</exception> void AddRange(System.Collections.Generic.IEnumerable<IUserAccount> userAccounts); /// <summary> /// Gets a reference to the <see cref="IUserAccount" /> object at the specified index position. /// </summary> /// <param name="indexPosition">An integer specifying the position of the object within this collection to /// return. Zero returns the first item.</param> /// <returns>Returns a reference to the <see cref="IUserAccount" /> object at the specified index position.</returns> IUserAccount this[Int32 indexPosition] { get; set; } /// <summary> /// Searches for the specified object and returns the zero-based index of the first occurrence within the collection. /// </summary> /// <param name="gallery">The user account to locate in the collection. The value can be a null /// reference (Nothing in Visual Basic).</param> /// <returns>The zero-based index of the first occurrence of a user account within the collection, if found; /// otherwise, –1. </returns> Int32 IndexOf(IUserAccount gallery); /// <overloads> /// Determines whether a user is a member of the collection. /// </overloads> /// <summary> /// Determines whether the <paramref name="item"/> is a member of the collection. An object is considered a member /// of the collection if they both have the same <see cref="IUserAccount.UserName" />. /// </summary> /// <param name="item">An <see cref="IUserAccount"/> to determine whether it is a member of the current collection.</param> /// <returns>Returns <c>true</c> if <paramref name="item"/> is a member of the current collection; /// otherwise returns <c>false</c>.</returns> new bool Contains(IUserAccount item); /// <summary> /// Determines whether a user account with the specified <paramref name="userName"/> is a member of the collection. /// </summary> /// <param name="userName">The user name that uniquely identifies the user.</param> /// <returns>Returns <c>true</c> if <paramref name="userName"/> is a member of the current collection; /// otherwise returns <c>false</c>.</returns> bool Contains(string userName); /// <summary> /// Adds the specified user account. /// </summary> /// <param name="item">The user account to add.</param> new void Add(IUserAccount item); /// <summary> /// Find the user account in the collection that matches the specified <paramref name="userName" />. If no matching object is found, /// null is returned. /// </summary> /// <param name="userName">The user name that uniquely identifies the user.</param> /// <returns>Returns an <see cref="IUserAccount" />object from the collection that matches the specified <paramref name="userName" />, /// or null if no matching object is found.</returns> IUserAccount FindByUserName(string userName); /// <summary> /// Finds the users whose <see cref="IUserAccount.UserName" /> begins with the specified <paramref name="userNameSearchString" />. /// This method can be used to find a set of users that match the first few characters of a string. Returns an empty collection if /// no matches are found. The match is case-insensitive. Example: If <paramref name="userNameSearchString" />="Rob", this method /// returns users with names like "Rob", "Robert", and "robert" but not names such as "Boston Rob". /// </summary> /// <param name="userNameSearchString">A string to match against the beginning of a <see cref="IUserAccount.UserName" />. Do not /// specify a wildcard character. If value is null or an empty string, all users are returned.</param> /// <returns>Returns an <see cref="IUserAccountCollection" />object from the collection where the <see cref="IUserAccount.UserName" /> /// begins with the specified <paramref name="userNameSearchString" />, or an empty collection if no matching object is found.</returns> IUserAccountCollection FindAllByUserName(string userNameSearchString); } }
Java
var Base = require("./../plugin"); module.exports = class extends Base { isDisableSelfAttackPriority(self, rival) { return true; } isDisableEnemyAttackPriority(self, rival) { return true; } }
Java
////////////////////////////////////////////////// // JIST (Java In Simulation Time) Project // Timestamp: <EntityRef.java Sun 2005/03/13 11:10:16 barr rimbase.rimonbarr.com> // // Copyright (C) 2004 by Cornell University // All rights reserved. // Refer to LICENSE for terms and conditions of use. package jist.runtime; import java.lang.reflect.Method; import java.lang.reflect.InvocationHandler; import java.rmi.RemoteException; /** * Stores a reference to a (possibly remote) Entity object. A reference * consists of a serialized reference to a Controller and an index within that * Controller. * * @author Rimon Barr &lt;barr+jist@cs.cornell.edu&gt; * @version $Id: EntityRef.java,v 1.1 2007/04/09 18:49:26 drchoffnes Exp $ * @since JIST1.0 */ public class EntityRef implements InvocationHandler { /** * NULL reference constant. */ public static final EntityRef NULL = new EntityRefDist(null, -1); /** * Entity index within Controller. */ private final int index; /** * Initialise a new entity reference with given * Controller and Entity IDs. * * @param index entity ID */ public EntityRef(int index) { this.index = index; } /** * Return entity reference hashcode. * * @return entity reference hashcode */ public int hashCode() { return index; } /** * Test object equality. * * @param o object to test equality * @return object equality */ public boolean equals(Object o) { if(o==null) return false; if(!(o instanceof EntityRef)) return false; EntityRef er = (EntityRef)o; if(index!=er.index) return false; return true; } /** * Return controller of referenced entity. * * @return controller of referenced entity */ public ControllerRemote getController() { if(Main.SINGLE_CONTROLLER) { return Controller.activeController; } else { throw new RuntimeException("multiple controllers"); } } /** * Return index of referenced entity. * * @return index of referenced entity */ public int getIndex() { return index; } /** * Return toString of referenced entity. * * @return toString of referenced entity */ public String toString() { try { return "EntityRef:"+getController().toStringEntity(getIndex()); } catch(java.rmi.RemoteException e) { throw new RuntimeException(e); } } /** * Return class of referenced entity. * * @return class of referenced entity */ public Class getClassRef() { try { return getController().getEntityClass(getIndex()); } catch(java.rmi.RemoteException e) { throw new RuntimeException(e); } } ////////////////////////////////////////////////// // proxy entities // /** boolean type for null return. */ private static final Boolean RET_BOOLEAN = new Boolean(false); /** byte type for null return. */ private static final Byte RET_BYTE = new Byte((byte)0); /** char type for null return. */ private static final Character RET_CHARACTER = new Character((char)0); /** double type for null return. */ private static final Double RET_DOUBLE = new Double((double)0); /** float type for null return. */ private static final Float RET_FLOAT = new Float((float)0); /** int type for null return. */ private static final Integer RET_INTEGER = new Integer(0); /** long type for null return. */ private static final Long RET_LONG = new Long(0); /** short type for null return. */ private static final Short RET_SHORT = new Short((short)0); /** * Called whenever a proxy entity reference is invoked. Schedules the call * at the appropriate Controller. * * @param proxy proxy entity reference object whose method was invoked * @param method method invoked on entity reference object * @param args arguments of the method invocation * @return result of blocking event; null return for non-blocking events * @throws Throwable whatever was thrown by blocking events; never for non-blocking events */ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { if(Rewriter.isBlockingRuntimeProxy(method)) // todo: make Object methods blocking //|| method.getDeclaringClass()==Object.class) { return blockingInvoke(proxy, method, args); } else { // schedule a simulation event if(Main.SINGLE_CONTROLLER) { Controller.activeController.addEvent(method, this, args); } else { getController().addEvent(method, this, args); } return null; } } catch(RemoteException e) { throw new JistException("distributed simulation failure", e); } } /** * Helper method: called whenever a BLOCKING method on proxy entity reference * is invoked. Schedules the call at the appropriate Controller. * * @param proxy proxy entity reference object whose method was invoked * @param method method invoked on entity reference object * @param args arguments of the method invocation * @return result of blocking event * @throws Throwable whatever was thrown by blocking events */ private Object blockingInvoke(Object proxy, Method method, Object[] args) throws Throwable { Controller c = Controller.getActiveController(); if(c.isModeRestoreInst()) { // restore complete if(Controller.log.isDebugEnabled()) { Controller.log.debug("restored event state!"); } // return callback result return c.clearRestoreState(); } else { // calling blocking method c.registerCallEvent(method, this, args); // todo: darn Java; this junk slows down proxies Class ret = method.getReturnType(); if(ret==Void.TYPE) { return null; } else if(ret.isPrimitive()) { String retName = ret.getName(); switch(retName.charAt(0)) { case 'b': switch(retName.charAt(1)) { case 'o': return RET_BOOLEAN; case 'y': return RET_BYTE; default: throw new RuntimeException("unknown return type"); } case 'c': return RET_CHARACTER; case 'd': return RET_DOUBLE; case 'f': return RET_FLOAT; case 'i': return RET_INTEGER; case 'l': return RET_LONG; case 's': return RET_SHORT; default: throw new RuntimeException("unknown return type"); } } else { return null; } } } } // class: EntityRef
Java
#!/usr/bin/env python """The setup and build script for the python-telegram-bot library.""" import codecs import os from setuptools import setup, find_packages def requirements(): """Build the requirements list for this project""" requirements_list = [] with open('requirements.txt') as requirements: for install in requirements: requirements_list.append(install.strip()) return requirements_list packages = find_packages(exclude=['tests*']) with codecs.open('README.rst', 'r', 'utf-8') as fd: fn = os.path.join('telegram', 'version.py') with open(fn) as fh: code = compile(fh.read(), fn, 'exec') exec(code) setup(name='python-telegram-bot', version=__version__, author='Leandro Toledo', author_email='devs@python-telegram-bot.org', license='LGPLv3', url='https://python-telegram-bot.org/', keywords='python telegram bot api wrapper', description="We have made you a wrapper you can't refuse", long_description=fd.read(), packages=packages, install_requires=requirements(), extras_require={ 'json': 'ujson', 'socks': 'PySocks' }, include_package_data=True, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)', 'Operating System :: OS Independent', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Communications :: Chat', 'Topic :: Internet', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6' ],)
Java
#!/bin/bash -e . ../../../blfs.comm build_src() { srcfil=URI-1.65.tar.gz srcdir=URI-1.65 build_standard_perl_module } gen_control() { cat > $DEBIANDIR/control << EOF $PKGHDR Description: Uniform Resource Identifiers (absolute and relative) This module implements the URI class. Objects of this class represent "Uniform Resource Identifier references" as specified in RFC 2396 (and updated by RFC 2732). A Uniform Resource Identifier is a compact string of characters that identifies an abstract or physical resource. A Uniform Resource Identifier can be further classified as either a Uniform Resource Locator (URL) or a Uniform Resource Name (URN). The distinction between URL and URN does not matter to the URI class interface. A "URI-reference" is a URI that may have additional information attached in the form of a fragment identifier. EOF } build
Java
package se.sics.asdistances; import se.sics.asdistances.ASDistances; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import org.junit.*; /** * * @author Niklas Wahlén <nwahlen@kth.se> */ public class ASDistancesTest { ASDistances distances = null; public ASDistancesTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { distances = ASDistances.getInstance(); } @After public void tearDown() { } @Test public void testGetDistance() { System.out.println("Distance: " + distances.getDistance("193.10.67.148", "85.226.78.233")); } }
Java
#include "cmilitwostateselect.h" #include "ui_cmilitwostateselect.h" #include "cengine.h" #include "ctextout.h" void CMili2McuController::DoUpdateLogicView(const CEngineModel *engine) { if (engine->CurrentMcuType() == CEngineModel::MILI_MCU) mView->UpdateLogicView(engine); } void CMili2McuController::DoUpdateMemoryView(const CEngineModel *engine) { if (engine->CurrentMcuType() == CEngineModel::MILI_MCU) mView->UpdateMemoryView(engine); } void CMili2McuController::DoUpdateHintsView(const CEngineModel *engine) { if (engine->CurrentMcuType() == CEngineModel::MILI_MCU) mView->UpdateHintsView(engine); } // ------------------------------------------------------------- CMiliTwoStateSelect::CMiliTwoStateSelect(QWidget *parent) : QWidget(parent), ui(new Ui::CMiliTwoStateSelect), mMcuController(this) { ui->setupUi(this); } CMiliTwoStateSelect::~CMiliTwoStateSelect() { delete ui; } void CMiliTwoStateSelect::UpdateMemoryView(const CEngineModel *engine) { Q_ASSERT(engine != 0); Q_ASSERT(engine->CurrentMcuType() == CEngineModel::MILI_MCU); UpdateRG(engine); } void CMiliTwoStateSelect::UpdateLogicView(const CEngineModel *engine) { Q_ASSERT(engine != 0); Q_ASSERT(engine->CurrentMcuType() == CEngineModel::MILI_MCU); UpdateMS1(engine); UpdateMS2(engine); UpdateY(engine); } void CMiliTwoStateSelect::UpdateHintsView(const CEngineModel *engine) { Q_ASSERT(engine != 0); Q_ASSERT(engine->CurrentMcuType() == CEngineModel::MILI_MCU); ui->mRgMsbNoHint->setText(CTextOut::FormatDec(engine->StateDim() - 1)); ui->mYDimHint->setText(CTextOut::FormatDec(engine->McuControlOutputDim())); ui->mMs1MsbHint->setText(QString("p%1").arg(CTextOut::FormatDec(engine->McuControlInputDim() - 1))); ui->mMs2MsbHint->setText(CTextOut::FormatDec(engine->McuControlOutputDim() + engine->StateDim() - 1)); } void CMiliTwoStateSelect::UpdateRG(const CEngineModel *engine) { Q_ASSERT(engine != 0); Q_ASSERT(engine->CurrentMcuType() == CEngineModel::MILI_MCU); const CRegister *rg = engine->CurrentMcu()->Register(CMiliAutomate::STATE_REGISTER_INDEX); unsigned int stateDim = engine->StateDim(); ui->mRgVal->setText(CTextOut::FormatHex(rg->Output(), stateDim)); ui->mSVal->setText(CTextOut::FormatHex(rg->Output(), stateDim)); } void CMiliTwoStateSelect::UpdateMS1(const CEngineModel *engine) { Q_ASSERT(engine != 0); Q_ASSERT(engine->CurrentMcuType() == CEngineModel::MILI_MCU); const CMultiplexor *mux = engine->CurrentMcu()->Multiplexor(CMiliAutomate::GROUP_MUX_INDEX); ui->mMS1P0Val->setText(CTextOut::FormatBin(mux->Input(0), 1)); ui->mMS1P1Val->setText(CTextOut::FormatBin(mux->Input(1), 1)); unsigned int lastIndex = engine->McuControlInputDim() - 1; ui->mMS1PnVal->setText(CTextOut::FormatBin(mux->Input(lastIndex).AsInt(), 1)); ui->mMs1SelVal->setText(CTextOut::FormatHex(mux->InputIndex(), mux->IndexDim())); ui->mMs1Val->setText(CTextOut::FormatBin(mux->Output().AsInt(), 1)); } void CMiliTwoStateSelect::UpdateMS2(const CEngineModel *engine) { Q_ASSERT(engine != 0); Q_ASSERT(engine->CurrentMcuType() == CEngineModel::MILI_MCU); const CMultiplexor *mux = engine->CurrentMcu()->Multiplexor(CMiliAutomate::STATE_MUX_INDEX); ui->mMS2S0Val->setText(CTextOut::FormatHex(mux->Input(0))); ui->mMS2S1Val->setText(CTextOut::FormatHex(mux->Input(1))); ui->mMs2SVal->setText(CTextOut::FormatHex(mux->Output())); mux = engine->CurrentMcu()->Multiplexor(CMiliAutomate::CONTROL_MUX_INDEX); ui->mMS2Y0Val->setText(CTextOut::FormatHex(mux->Input(0))); ui->mMS2Y1Val->setText(CTextOut::FormatHex(mux->Input(1))); ui->mMs2YVal->setText(CTextOut::FormatHex(mux->Output())); } void CMiliTwoStateSelect::UpdateY(const CEngineModel *engine) { Q_ASSERT(engine != 0); Q_ASSERT(engine->CurrentMcuType() == CEngineModel::MILI_MCU); ui->mYVal->setText(CTextOut::FormatHex(engine->CurrentMcu()->ControlOutput())); }
Java
#creativeblock { clear:both; border-bottom: 1px #1d649d solid; border: 5px solid #f1f1f1; padding: 1%; margin: 1%; } #feaimg img{ width: 30%; float:left; padding-right: 2%; } #featitle { font-size: larger; font-weight: bold; color: #1d649d; } #featitle a { color: #1d649d; } #feacontent { } #feacontent a { color: #1d649d; }
Java
/********************************************************* ********************************************************* ** DO NOT EDIT ** ** ** ** THIS FILE AS BEEN GENERATED AUTOMATICALLY ** ** BY UPA PORTABLE GENERATOR ** ** (c) vpc ** ** ** ********************************************************* ********************************************************/ namespace Net.TheVpc.Upa.Impl.Event { /** * * @author taha.bensalah@gmail.com */ public class UpdateFormulaObjectEventCallback : Net.TheVpc.Upa.Impl.Event.SingleEntityObjectEventCallback { public UpdateFormulaObjectEventCallback(object o, System.Reflection.MethodInfo m, Net.TheVpc.Upa.CallbackType callbackType, Net.TheVpc.Upa.EventPhase phase, Net.TheVpc.Upa.ObjectType objectType, Net.TheVpc.Upa.Impl.Config.Callback.MethodArgumentsConverter converter, System.Collections.Generic.IDictionary<string , object> configuration) : base(o, m, callbackType, phase, objectType, converter, configuration){ } public override void Prepare(Net.TheVpc.Upa.Callbacks.UPAEvent @event) { Net.TheVpc.Upa.Callbacks.RemoveEvent ev = (Net.TheVpc.Upa.Callbacks.RemoveEvent) @event; ResolveIdList(ev, ev.GetFilterExpression()); } public override object Invoke(params object [] arguments) { Net.TheVpc.Upa.Callbacks.UpdateFormulaEvent ev = (Net.TheVpc.Upa.Callbacks.UpdateFormulaEvent) arguments[0]; foreach (object id in ResolveIdList(ev, ev.GetFilterExpression())) { Net.TheVpc.Upa.Callbacks.UpdateFormulaObjectEvent oe = new Net.TheVpc.Upa.Callbacks.UpdateFormulaObjectEvent(id, ev.GetUpdates(), ev.GetFilterExpression(), ev.GetContext(), GetPhase()); InvokeSingle(oe); } return null; } } }
Java
/* -*- c++ -*- */ /* * Copyright 2019-2020 Daniel Estevez <daniel@destevez.net> * * This file is part of gr-satellites * * SPDX-License-Identifier: GPL-3.0-or-later * */ #ifndef INCLUDED_SATELLITES_DISTRIBUTED_SYNCFRAME_SOFT_IMPL_H #define INCLUDED_SATELLITES_DISTRIBUTED_SYNCFRAME_SOFT_IMPL_H #include <satellites/distributed_syncframe_soft.h> #include <vector> namespace gr { namespace satellites { class distributed_syncframe_soft_impl : public distributed_syncframe_soft { private: const size_t d_threshold; const size_t d_step; std::vector<uint8_t> d_syncword; public: distributed_syncframe_soft_impl(int threshold, const std::string& syncword, int step); ~distributed_syncframe_soft_impl(); // Where all the action really happens int work(int noutput_items, gr_vector_const_void_star& input_items, gr_vector_void_star& output_items); }; } // namespace satellites } // namespace gr #endif /* INCLUDED_SATELLITES_DISTRIBUTED_SYNCFRAME_SOFT_IMPL_H */
Java
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and library */ /* SCIP --- Solving Constraint Integer Programs */ /* */ /* Copyright (C) 2002-2018 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* SCIP is distributed under the terms of the ZIB Academic License. */ /* */ /* You should have received a copy of the ZIB Academic License */ /* along with SCIP; see the file COPYING. If not email to scip@zib.de. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /**@file struct_concsolver.h * @ingroup INTERNALAPI * @brief datastructures for concurrent solvers * @author Robert Lion Gottwald */ /*---+----1----+----2----+----3----+----4----+----5----+----6----+----7----+----8----+----9----+----0----+----1----+----2*/ #ifndef __SCIP_STRUCT_CONCSOLVER_H__ #define __SCIP_STRUCT_CONCSOLVER_H__ #include "scip/def.h" #include "scip/type_concsolver.h" #include "scip/type_clock.h" #ifdef __cplusplus extern "C" { #endif /** concurrent solver data structure */ struct SCIP_ConcSolverType { int ninstances; /**< number of instances created from this concurrent solver type */ SCIP_Real prefprio; /**< the weight of the concurrent */ char* name; /**< name of concurrent solver */ SCIP_CONCSOLVERTYPEDATA* data; /**< user data of concurrent solver type */ SCIP_DECL_CONCSOLVERCREATEINST ((*concsolvercreateinst)); /**< creates an instance of the concurrent solver */ SCIP_DECL_CONCSOLVERDESTROYINST ((*concsolverdestroyinst)); /**< destroys an instance of the concurrent solver */ SCIP_DECL_CONCSOLVERINITSEEDS ((*concsolverinitseeds)); /**< initialize random seeds of concurrent solver */ SCIP_DECL_CONCSOLVEREXEC ((*concsolverexec)); /**< execution method of concurrent solver */ SCIP_DECL_CONCSOLVERCOPYSOLVINGDATA ((*concsolvercopysolvdata));/**< copies the solving data */ SCIP_DECL_CONCSOLVERSTOP ((*concsolverstop)); /**< terminate solving in concurrent solver */ SCIP_DECL_CONCSOLVERSYNCWRITE ((*concsolversyncwrite)); /**< synchronization method of concurrent solver for sharing it's data */ SCIP_DECL_CONCSOLVERSYNCREAD ((*concsolversyncread)); /**< synchronization method of concurrent solver for reading shared data */ SCIP_DECL_CONCSOLVERTYPEFREEDATA ((*concsolvertypefreedata));/**< frees user data of concurrent solver type */ }; /** concurrent solver data structure */ struct SCIP_ConcSolver { SCIP_CONCSOLVERTYPE* type; /**< type of this concurrent solver */ int idx; /**< index of initialized exernal solver */ char* name; /**< name of concurrent solver */ SCIP_CONCSOLVERDATA* data; /**< user data of concurrent solver */ SCIP_SYNCDATA* syncdata; /**< most recent synchronization data that has been read */ SCIP_Longint nsyncs; /**< total number of synchronizations */ SCIP_Real timesincelastsync; /**< time since the last synchronization */ SCIP_Real syncdelay; /**< current delay of synchronization data */ SCIP_Real syncfreq; /**< current synchronization frequency of the concurrent solver */ SCIP_Real solvingtime; /**< solving time with wall clock */ SCIP_Bool stopped; /**< flag to store if the concurrent solver has been stopped * through the SCIPconcsolverStop function */ SCIP_Longint nlpiterations; /**< number of lp iterations the concurrent solver used */ SCIP_Longint nnodes; /**< number of nodes the concurrent solver used */ SCIP_Longint nsolsrecvd; /**< number of solutions the concurrent solver received */ SCIP_Longint nsolsshared; /**< number of solutions the concurrent solver found */ SCIP_Longint ntighterbnds; /**< number of tighter global variable bounds the concurrent solver received */ SCIP_Longint ntighterintbnds; /**< number of tighter global variable bounds the concurrent solver received * on integer variables */ SCIP_CLOCK* totalsynctime; /**< total time used for synchronization, including idle time */ }; #ifdef __cplusplus } #endif #endif
Java
class Cartridge : property<Cartridge> { public: enum class Mode : unsigned { Normal, BsxSlotted, Bsx, SufamiTurbo, SuperGameBoy, }; enum class Region : unsigned { NTSC, PAL, }; //assigned externally to point to file-system datafiles (msu1 and serial) //example: "/path/to/filename.sfc" would set this to "/path/to/filename" readwrite<string> basename; readonly<bool> loaded; readonly<unsigned> crc32; readonly<string> sha256; readonly<Mode> mode; readonly<Region> region; readonly<unsigned> ram_size; readonly<bool> has_bsx_slot; readonly<bool> has_superfx; readonly<bool> has_sa1; readonly<bool> has_necdsp; readonly<bool> has_srtc; readonly<bool> has_sdd1; readonly<bool> has_spc7110; readonly<bool> has_spc7110rtc; readonly<bool> has_cx4; readonly<bool> has_obc1; readonly<bool> has_st0018; readonly<bool> has_msu1; readonly<bool> has_serial; struct Mapping { Memory *memory; MMIO *mmio; Bus::MapMode mode; unsigned banklo; unsigned bankhi; unsigned addrlo; unsigned addrhi; unsigned offset; unsigned size; Mapping(); Mapping(Memory&); Mapping(MMIO&); }; array<Mapping> mapping; void load(Mode, const lstring&); void unload(); void serialize(serializer&); Cartridge(); ~Cartridge(); private: void parse_xml(const lstring&); void parse_xml_cartridge(const char*); void parse_xml_bsx(const char*); void parse_xml_sufami_turbo(const char*, bool); void parse_xml_gameboy(const char*); void xml_parse_rom(xml_element&); void xml_parse_ram(xml_element&); void xml_parse_icd2(xml_element&); void xml_parse_superfx(xml_element&); void xml_parse_sa1(xml_element&); void xml_parse_necdsp(xml_element&); void xml_parse_bsx(xml_element&); void xml_parse_sufamiturbo(xml_element&); void xml_parse_supergameboy(xml_element&); void xml_parse_srtc(xml_element&); void xml_parse_sdd1(xml_element&); void xml_parse_spc7110(xml_element&); void xml_parse_cx4(xml_element&); void xml_parse_obc1(xml_element&); void xml_parse_setarisc(xml_element&); void xml_parse_msu1(xml_element&); void xml_parse_serial(xml_element&); void xml_parse_address(Mapping&, const string&); void xml_parse_mode(Mapping&, const string&); }; namespace memory { extern MappedRAM cartrom, cartram, cartrtc; extern MappedRAM bsxflash, bsxram, bsxpram; extern MappedRAM stArom, stAram; extern MappedRAM stBrom, stBram; }; extern Cartridge cartridge;
Java
<?php namespace Schatz\CrmBundle\Controller\Leads; use Schatz\CrmBundle\Constants\ContactStatusConstants; use Schatz\CrmBundle\Constants\ContactTypeConstants; use Schatz\GeneralBundle\Constants\PermissionsConstants; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class LeadsController extends Controller { const MENU = 'leads'; private $leads = array(); private $user; private $allCampaigns = array(); private $myCampaigns = array(); private $contactCampaigns = array(); private $allAssignedLeadsOrContacts = array(); public function indexAction($filter) { if ($this->get('user.permission')->checkPermission(PermissionsConstants::PERMISSION_7) and !$this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')) return $this->redirect($this->generateUrl('schatz_general_homepage')); $this->user = $this->getUser(); if (!$this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')) { $this->allCampaigns = $this->getDoctrine()->getRepository('SchatzCrmBundle:Campaign')->findAll(); if (!empty($this->allCampaigns)) { foreach ($this->allCampaigns as $campaign) { if (in_array($this->user->getId(), $campaign->getAssociates())) { $this->myCampaigns[] = $campaign; } } } $this->contactCampaigns = $this->getDoctrine()->getRepository('SchatzCrmBundle:ContactCampaign')->findAll(); if (!empty($this->contactCampaigns)) { foreach ($this->contactCampaigns as $contactCampaign) { if ($contactCampaign->getContact()->getFlag() == ContactTypeConstants::CONTACT_TYPE_2 and !in_array($contactCampaign->getContact(), $this->allAssignedLeadsOrContacts)) { $this->allAssignedLeadsOrContacts[] = $contactCampaign->getContact(); } } } } $this->_getLeads($filter); return $this->render('SchatzCrmBundle:Leads:index.html.twig', array( 'menu' => $this::MENU, 'leads' => $this->leads, 'filter' => $filter ) ); } private function _getLeads($filter) { if (empty($this->myCampaigns) and empty($this->allAssignedLeadsOrContacts) and !$this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')) { $this->leads = array(); } else { if ($filter == 'my_leads') { $this->leads = $this->getDoctrine()->getRepository('SchatzCrmBundle:Contact')->findAllLeadsOrContacts(ContactTypeConstants::CONTACT_TYPE_2, $this->myCampaigns, $this->user, $this->allAssignedLeadsOrContacts, null, $this->user); } else if ($filter == 'new') { $this->leads = $this->getDoctrine()->getRepository('SchatzCrmBundle:Contact')->findAllLeadsOrContacts(ContactTypeConstants::CONTACT_TYPE_2, $this->myCampaigns, $this->user, $this->allAssignedLeadsOrContacts, ContactStatusConstants::CONTACT_STATUS_1); } else if ($filter == 'contacted') { $this->leads = $this->getDoctrine()->getRepository('SchatzCrmBundle:Contact')->findAllLeadsOrContacts(ContactTypeConstants::CONTACT_TYPE_2, $this->myCampaigns, $this->user, $this->allAssignedLeadsOrContacts, ContactStatusConstants::CONTACT_STATUS_2); } else if ($filter == 'rejected') { $this->leads = $this->getDoctrine()->getRepository('SchatzCrmBundle:Contact')->findAllLeadsOrContacts(ContactTypeConstants::CONTACT_TYPE_2, $this->myCampaigns, $this->user, $this->allAssignedLeadsOrContacts, ContactStatusConstants::CONTACT_STATUS_3); } else { $this->leads = $this->getDoctrine()->getRepository('SchatzCrmBundle:Contact')->findAllLeadsOrContacts(ContactTypeConstants::CONTACT_TYPE_2, $this->myCampaigns, $this->user, $this->allAssignedLeadsOrContacts); } } } }
Java
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('account', '0003_remove_userprofile_is_check'), ] operations = [ migrations.RemoveField( model_name='userprofile', name='is_create', ), migrations.RemoveField( model_name='userprofile', name='is_delete', ), migrations.RemoveField( model_name='userprofile', name='is_modify', ), ]
Java
#pragma once #include "storm/storage/memorystructure/NondeterministicMemoryStructure.h" namespace storm { namespace storage { enum class NondeterministicMemoryStructurePattern { Trivial, FixedCounter, SelectiveCounter, FixedRing, SelectiveRing, SettableBits, Full }; std::string toString(NondeterministicMemoryStructurePattern const& pattern); class NondeterministicMemoryStructureBuilder { public: // Builds a memory structure with the given pattern and the given number of states. NondeterministicMemoryStructure build(NondeterministicMemoryStructurePattern pattern, uint64_t numStates) const; // Builds a memory structure that consists of just a single memory state NondeterministicMemoryStructure buildTrivialMemory() const; // Builds a memory structure that consists of a chain of the given number of states. // Every state has exactly one transition to the next state. The last state has just a selfloop. NondeterministicMemoryStructure buildFixedCountingMemory(uint64_t numStates) const; // Builds a memory structure that consists of a chain of the given number of states. // Every state has a selfloop and a transition to the next state. The last state just has a selfloop. NondeterministicMemoryStructure buildSelectiveCountingMemory(uint64_t numStates) const; // Builds a memory structure that consists of a ring of the given number of states. // Every state has a transition to the successor state NondeterministicMemoryStructure buildFixedRingMemory(uint64_t numStates) const; // Builds a memory structure that consists of a ring of the given number of states. // Every state has a transition to the successor state and a selfloop NondeterministicMemoryStructure buildSelectiveRingMemory(uint64_t numStates) const; // Builds a memory structure that represents floor(log(numStates)) bits that can only be set from zero to one or from zero to zero. NondeterministicMemoryStructure buildSettableBitsMemory(uint64_t numStates) const; // Builds a memory structure that consists of the given number of states which are fully connected. NondeterministicMemoryStructure buildFullyConnectedMemory(uint64_t numStates) const; }; } // namespace storage } // namespace storm
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package nl.hyranasoftware.githubupdater.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.util.Objects; import org.joda.time.DateTime; /** * * @author danny_000 */ @JsonIgnoreProperties(ignoreUnknown = true) public class Asset { String url; String browser_download_url; int id; String name; String label; String state; String content_type; long size; long download_count; DateTime created_at; DateTime updated_at; GithubUser uploader; public Asset() { } public Asset(String url, String browser_download_url, int id, String name, String label, String state, String content_type, long size, long download_count, DateTime created_at, DateTime updated_at, GithubUser uploader) { this.url = url; this.browser_download_url = browser_download_url; this.id = id; this.name = name; this.label = label; this.state = state; this.content_type = content_type; this.size = size; this.download_count = download_count; this.created_at = created_at; this.updated_at = updated_at; this.uploader = uploader; } public String getState() { return state; } public String getUrl() { return url; } public String getBrowser_download_url() { return browser_download_url; } public int getId() { return id; } public String getName() { return name; } public String getLabel() { return label; } public String getContent_type() { return content_type; } public long getSize() { return size; } public long getDownload_count() { return download_count; } public DateTime getCreated_at() { return created_at; } public DateTime getUpdated_at() { return updated_at; } public GithubUser getUploader() { return uploader; } @Override public int hashCode() { int hash = 7; hash = 79 * hash + Objects.hashCode(this.content_type); hash = 79 * hash + (int) (this.download_count ^ (this.download_count >>> 32)); hash = 79 * hash + Objects.hashCode(this.created_at); hash = 79 * hash + Objects.hashCode(this.updated_at); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Asset other = (Asset) obj; if (this.id != other.id) { return false; } if (!Objects.equals(this.name, other.name)) { return false; } if (!Objects.equals(this.content_type, other.content_type)) { return false; } return true; } @Override public String toString(){ return this.name; } }
Java
/***************************************************************************** The Dark Mod GPL Source Code This file is part of the The Dark Mod Source Code, originally based on the Doom 3 GPL Source Code as published in 2011. The Dark Mod Source Code is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For details, see LICENSE.TXT. Project: The Dark Mod (http://www.thedarkmod.com/) $Revision: 6569 $ (Revision of last commit) $Date: 2016-01-10 23:52:55 +0000 (Sun, 10 Jan 2016) $ (Date of last commit) $Author: grayman $ (Author of last commit) ******************************************************************************/ #ifndef _HTTP_REQUEST_H_ #define _HTTP_REQUEST_H_ #include <fstream> #include <boost/shared_ptr.hpp> class CHttpConnection; #include "../pugixml/pugixml.hpp" typedef void CURL; // Shared_ptr typedef typedef boost::shared_ptr<pugi::xml_document> XmlDocumentPtr; /** * greebo: An object representing a single HttpRequest, holding * the result (string) and status information. * * Use the Perform() method to execute the request. */ class CHttpRequest { public: enum RequestStatus { NOT_PERFORMED_YET, OK, // successful IN_PROGRESS, FAILED, ABORTED, }; private: // The connection we're working with CHttpConnection& _conn; // The URL we're supposed to query std::string _url; std::vector<char> _buffer; // The curl handle CURL* _handle; // The current state RequestStatus _status; std::string _destFilename; std::ofstream _destStream; // True if we should cancel the download bool _cancelFlag; double _progress; public: CHttpRequest(CHttpConnection& conn, const std::string& url); CHttpRequest(CHttpConnection& conn, const std::string& url, const std::string& destFilename); // Callbacks for CURL static size_t WriteMemoryCallback(void* ptr, size_t size, size_t nmemb, CHttpRequest* self); static size_t WriteFileCallback(void* ptr, size_t size, size_t nmemb, CHttpRequest* self); static int CHttpRequest::TDMHttpProgressFunc(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow); RequestStatus GetStatus(); // Perform the request void Perform(); void Cancel(); // Between 0.0 and 1.0 double GetProgressFraction(); // Returns the result string std::string GetResultString(); // Returns the result as XML document XmlDocumentPtr GetResultXml(); private: void InitRequest(); void UpdateProgress(); }; typedef boost::shared_ptr<CHttpRequest> CHttpRequestPtr; #endif /* _HTTP_REQUEST_H_ */
Java
ModX Revolution 2.5.0 = 88d852255e0a3c20e3abb5ec165b5684 ModX Revolution 2.3.3 = 5137fe8eb650573a752775acc90954b5 ModX Revolution 2.3.2 = 2500d1a81dd43e7e9f4a11e1712aeffb MODX Revolution 2.2.8 = cc299e05ed6fb94e4d9c4144bf553675 MODX Revolution 2.5.2 = f87541ee3ef82272d4442529fee1028e
Java
#include "RocksIndex.hh" #include <stdlib.h> #include <iostream> // Get command line arguments for array size (100M) and number of trials (1M) void arrayArgs(int argc, char* argv[], objectId_t& asize, int& reps) { asize = (argc>1) ? strtoull(argv[1], 0, 0) : 100000000; reps = (argc>2) ? strtol(argv[2], 0, 0) : 1000000; } // Main program goes here int main(int argc, char* argv[]) { objectId_t arraySize; int queryTrials; arrayArgs(argc, argv, arraySize, queryTrials); std::cout << "RocksDB Table " << arraySize << " elements, " << queryTrials << " trials" << std::endl; RocksIndex rocks(2); // Verbosity rocks.CreateTable(arraySize); rocks.ExerciseTable(queryTrials); }
Java
### # Copyright 2016 - 2022 Green River Data Analysis, LLC # # License detail: https://github.com/greenriver/hmis-warehouse/blob/production/LICENSE.md ### module Reports::SystemPerformance::Fy2015 class MeasureThree < Base end end
Java
#!/usr/bin/env bash . test_common.sh id=process rm -f $id.out ln -s "$test_base/test/$id.data.in" . 2>/dev/null test_server_start $id test pid=$! hector_client_set PE_test.run 1 hector_client -c "PROCESS PE_test" $HECTOR_HOST <$id.data.in >$id.data.out hector_client_wait M_simple[0].items 1000 hector_client_set PE_test.run 0 test_server_shutdown wait $! md5sum <$id.data.out >$id.log.result if [ -L $id.data.in ]; then rm $id.data.in fi test_compare_result $id exit $?
Java
<?php /* ---------------------------------------------------------------------- * app/controllers/find/AdvancedSearchObjectsController.php : controller for "advanced" object search request handling * ---------------------------------------------------------------------- * CollectiveAccess * Open-source collections management software * ---------------------------------------------------------------------- * * Software by Whirl-i-Gig (http://www.whirl-i-gig.com) * Copyright 2010-2015 Whirl-i-Gig * * For more information visit http://www.CollectiveAccess.org * * This program is free software; you may redistribute it and/or modify it under * the terms of the provided license as published by Whirl-i-Gig * * CollectiveAccess is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTIES whatsoever, including any implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * This source code is free and modifiable under the terms of * GNU General Public License. (http://www.gnu.org/copyleft/gpl.html). See * the "license.txt" file for details, or visit the CollectiveAccess web site at * http://www.CollectiveAccess.org * * ---------------------------------------------------------------------- */ require_once(__CA_LIB_DIR__."/ca/BaseAdvancedSearchController.php"); require_once(__CA_LIB_DIR__."/ca/Search/ObjectSearch.php"); require_once(__CA_LIB_DIR__."/ca/Browse/ObjectBrowse.php"); require_once(__CA_LIB_DIR__."/core/GeographicMap.php"); require_once(__CA_MODELS_DIR__."/ca_objects.php"); require_once(__CA_MODELS_DIR__."/ca_sets.php"); class SearchObjectsAdvancedController extends BaseAdvancedSearchController { # ------------------------------------------------------- /** * Name of subject table (ex. for an object search this is 'ca_objects') */ protected $ops_tablename = 'ca_objects'; /** * Number of items per search results page */ protected $opa_items_per_page = array(8, 16, 24, 32); /** * List of search-result views supported for this find * Is associative array: values are view labels, keys are view specifier to be incorporated into view name */ protected $opa_views; /** * Name of "find" used to defined result context for ResultContext object * Must be unique for the table and have a corresponding entry in find_navigation.conf */ protected $ops_find_type = 'advanced_search'; # ------------------------------------------------------- public function __construct(&$po_request, &$po_response, $pa_view_paths=null) { parent::__construct($po_request, $po_response, $pa_view_paths); $this->opa_views = array( 'thumbnail' => _t('thumbnails'), 'full' => _t('full'), 'list' => _t('list') ); $this->opo_browse = new ObjectBrowse($this->opo_result_context->getParameter('browse_id'), 'providence'); } # ------------------------------------------------------- /** * Advanced search handler (returns search form and results, if any) * Most logic is contained in the BaseAdvancedSearchController->Index() method; all you usually * need to do here is instantiate a new subject-appropriate subclass of BaseSearch * (eg. ObjectSearch for objects, EntitySearch for entities) and pass it to BaseAdvancedSearchController->Index() */ public function Index($pa_options=null) { $pa_options['search'] = $this->opo_browse; AssetLoadManager::register('imageScroller'); AssetLoadManager::register('tabUI'); AssetLoadManager::register('panel'); return parent::Index($pa_options); } # ------------------------------------------------------- /** * */ public function getPartialResult($pa_options=null) { $pa_options['search'] = $this->opo_browse; return parent::getPartialResult($pa_options); } # ------------------------------------------------------- /** * Ajax action that returns info on a mapped location based upon the 'id' request parameter. * 'id' is a list of object_ids to display information before. Each integer id is separated by a semicolon (";") * The "ca_objects_results_map_balloon_html" view in Results/ is used to render the content. */ public function getMapItemInfo() { $pa_object_ids = explode(';', $this->request->getParameter('id', pString)); $va_access_values = caGetUserAccessValues($this->request); $this->view->setVar('ids', $pa_object_ids); $this->view->setVar('access_values', $va_access_values); $this->render("Results/ca_objects_results_map_balloon_html.php"); } # ------------------------------------------------------- /** * Returns string representing the name of the item the search will return * * If $ps_mode is 'singular' [default] then the singular version of the name is returned, otherwise the plural is returned */ public function searchName($ps_mode='singular') { return ($ps_mode == 'singular') ? _t("object") : _t("objects"); } # ------------------------------------------------------- # Sidebar info handler # ------------------------------------------------------- /** * Returns "search tools" widget */ public function Tools($pa_parameters) { return parent::Tools($pa_parameters); } # ------------------------------------------------------- }
Java
/* * OpenSplice DDS * * This software and documentation are Copyright 2006 to 2012 PrismTech * Limited and its licensees. All rights reserved. See file: * * $OSPL_HOME/LICENSE * * for full copyright notice and license terms. * */ /** * @file */ #ifndef ORG_OPENSPLICE_CORE_POLICY_CORE_POLICY_IMPL_HPP_ #define ORG_OPENSPLICE_CORE_POLICY_CORE_POLICY_IMPL_HPP_ #include <dds/core/types.hpp> #include <dds/core/LengthUnlimited.hpp> #include <dds/core/Duration.hpp> //============================================================================== // DDS Policy Classes namespace org { namespace opensplice { namespace core { namespace policy { //============================================================================== /** * @internal The purpose of this QoS is to allow the application to attach additional * information to the created Entity objects such that when a remote application * discovers their existence it can access that information and use it for its * own purposes. One possible use of this QoS is to attach security credentials * or some other information that can be used by the remote application to * authenticate the source. In combination with operations such as * ignore_participant, ignore_publication, ignore_subscription, * and ignore_topic these QoS can assist an application to define and enforce * its own security policies. The use of this QoS is not limited to security, * rather it offers a simple, yet flexible extensibility mechanism. */ class UserData { public: /** * @internal Create a <code>UserData</code> instance with an empty user data. */ UserData() : value_() { } /** * @internal Create a <code>UserData</code> instance. * * @param seq the sequence of octet representing the user data */ explicit UserData(const dds::core::ByteSeq& seq) : value_(seq) { } /** * @internal Set the value for the user data. * * @param seq a sequence of octet representing the user data. */ void value(const dds::core::ByteSeq& seq) { value_ = seq; } /** * @internal Get/Set the user data. * * @return the sequence of octet representing the user data */ dds::core::ByteSeq& value() { return value_; } /** * @internal Get the user data. * * @return the sequence of octet representing the user data */ const dds::core::ByteSeq& value() const { return value_; } bool operator ==(const UserData& other) const { return other.value() == value_; } private: dds::core::ByteSeq value_; }; //============================================================================== /** * @internal The purpose of this QoS is to allow the application to attach additional * information to the created Publisher or Subscriber. * The value of the GROUP_DATA is available to the application on the * DataReader and DataWriter entities and is propagated by means of the * built-in topics. This QoS can be used by an application combination with * the DataReaderListener and DataWriterListener to implement matching policies * similar to those of the PARTITION QoS except the decision can be made based * on an application-defined policy. */ class GroupData { public: /** * @internal Create a <code>GroupData</code> instance. */ GroupData() : value_() { } /** * @internal Create a <code>GroupData</code> instance. * * @param seq the group data value */ explicit GroupData(const dds::core::ByteSeq& seq) : value_(seq) { } /** * @internal Set the value for this <code>GroupData</code> * * @param seq the group data value */ void value(const dds::core::ByteSeq& seq) { value_ = seq; } /** * @internal Get/Set the value for this <code>GroupData</code> * * @return the group data value */ dds::core::ByteSeq& value() { return value_; } /** * @internal Get the value for this <code>GroupData</code> * * @return the group data value */ const dds::core::ByteSeq& value() const { return value_; } bool operator ==(const GroupData& other) const { return other.value() == value_; } private: dds::core::ByteSeq value_; }; //============================================================================== /** * @internal The purpose of this QoS is to allow the application to attach additional * information to the created Topic such that when a remote application * discovers their existence it can examine the information and use it in * an application-defined way. In combination with the listeners on the * DataReader and DataWriter as well as by means of operations such as * ignore_topic, these QoS can assist an application to extend the provided QoS. */ class TopicData { public: TopicData() : value_() { } explicit TopicData(const dds::core::ByteSeq& seq) : value_(seq) { } void value(const dds::core::ByteSeq& seq) { value_ = seq; } const dds::core::ByteSeq& value() const { return value_; } dds::core::ByteSeq& value() { return value_; } bool operator ==(const TopicData& other) const { return other.value() == value_; } private: dds::core::ByteSeq value_; }; //============================================================================== /** * @internal This policy controls the behavior of the Entity as a factory for other * entities. This policy concerns only DomainParticipant (as factory for * Publisher, Subscriber, and Topic), Publisher (as factory for DataWriter), * and Subscriber (as factory for DataReader). This policy is mutable. * A change in the policy affects only the entities created after the change; * not the previously created entities. * The setting of autoenable_created_entities to TRUE indicates that the * newly created object will be enabled by default. * A setting of FALSE indicates that the Entity will not be automatically * enabled. The application will need to enable it explicitly by means of the * enable operation (see Section 7.1.2.1.1.7, ÒenableÓ). The default setting * of autoenable_created_entities = TRUE means that, by default, it is not * necessary to explicitly call enable on newly created entities. */ class EntityFactory { public: EntityFactory() {} explicit EntityFactory(bool auto_enable) : auto_enable_(auto_enable) { } void auto_enable(bool on) { auto_enable_ = on; } bool auto_enable() const { return auto_enable_; } bool& auto_enable() { return auto_enable_; } bool operator ==(const EntityFactory& other) const { return other.auto_enable() == auto_enable_; } private: bool auto_enable_; }; //============================================================================== /** * @internal The purpose of this QoS is to allow the application to take advantage of * transports capable of sending messages with different priorities. * This policy is considered a hint. The policy depends on the ability of the * underlying transports to set a priority on the messages they send. * Any value within the range of a 32-bit signed integer may be chosen; * higher values indicate higher priority. However, any further interpretation * of this policy is specific to a particular transport and a particular * implementation of the Service. For example, a particular transport is * permitted to treat a range of priority values as equivalent to one another. * It is expected that during transport configuration the application would * provide a mapping between the values of the TRANSPORT_PRIORITY set on * DataWriter and the values meaningful to each transport. This mapping would * then be used by the infrastructure when propagating the data written by * the DataWriter. */ class TransportPriority { public: TransportPriority() {} explicit TransportPriority(uint32_t prio) : value_(prio) { } public: void value(uint32_t prio) { value_ = prio; } uint32_t value() const { return value_; } uint32_t& value() { return value_; } bool operator ==(const TransportPriority& other) const { return other.value() == value_; } private: uint32_t value_; }; //============================================================================== /** * @internal The purpose of this QoS is to avoid delivering ÒstaleÓ data to the * application. Each data sample written by the DataWriter has an associated * expiration time beyond which the data should not be delivered to any * application. Once the sample expires, the data will be removed from the * DataReader caches as well as from the transient and persistent * information caches. The expiration time of each sample is computed by * adding the duration specified by the LIFESPAN QoS to the source timestamp. * As described in Section 7.1.2.4.2.11, Òwrite and Section 7.1.2.4.2.12, * write_w_timestamp the source timestamp is either automatically computed by * the Service each time the DataWriter write operation is called, or else * supplied by the application by means of the write_w_timestamp operation. * * This QoS relies on the sender and receiving applications having their clocks * sufficiently synchronized. If this is not the case and the Service can * detect it, the DataReader is allowed to use the reception timestamp instead * of the source timestamp in its computation of the expiration time. */ class Lifespan { public: Lifespan() {} explicit Lifespan(const dds::core::Duration& d) : duration_(d) { } public: void duration(const dds::core::Duration& d) { duration_ = d; } const dds::core::Duration duration() const { return duration_; } dds::core::Duration& duration() { return duration_; } bool operator ==(const Lifespan& other) const { return other.duration() == duration_; } private: dds::core::Duration duration_; }; //============================================================================== /** * @internal This policy is useful for cases where a Topic is expected to have each * instance updated periodically. On the publishing side this setting * establishes a contract that the application must meet. On the subscribing * side the setting establishes a minimum requirement for the remote publishers * that are expected to supply the data values. When the Service ÔmatchesÕ a * DataWriter and a DataReader it checks whether the settings are compatible * (i.e., offered deadline period<= requested deadline period) if they are not, * the two entities are informed (via the listener or condition mechanism) * of the incompatibility of the QoS settings and communication will not occur. * Assuming that the reader and writer ends have compatible settings, the * fulfillment of this contract is monitored by the Service and the application * is informed of any violations by means of the proper listener or condition. * The value offered is considered compatible with the value requested if and * only if the inequality Òoffered deadline period <= requested deadline periodÓ * evaluates to ÔTRUE.Õ The setting of the DEADLINE policy must be set * consistently with that of the TIME_BASED_FILTER. * For these two policies to be consistent the settings must be such that * Òdeadline period>= minimum_separation.Ó */ class Deadline { public: Deadline() {} explicit Deadline(const dds::core::Duration& d) : period_(d) { } public: void period(const dds::core::Duration& d) { period_ = d; } const dds::core::Duration period() const { return period_; } bool operator ==(const Deadline& other) const { return other.period() == period_; } private: dds::core::Duration period_; }; //============================================================================== class LatencyBudget { public: LatencyBudget() {} explicit LatencyBudget(const dds::core::Duration& d) : duration_(d) { } public: void duration(const dds::core::Duration& d) { duration_ = d; } const dds::core::Duration duration() const { return duration_; } dds::core::Duration& duration() { return duration_; } bool operator ==(const LatencyBudget& other) const { return other.duration() == duration_; } private: dds::core::Duration duration_; }; //============================================================================== class TimeBasedFilter { public: TimeBasedFilter() {} explicit TimeBasedFilter(const dds::core::Duration& min_separation) : min_sep_(min_separation) { } public: void min_separation(const dds::core::Duration& ms) { min_sep_ = ms; } const dds::core::Duration min_separation() const { return min_sep_; } dds::core::Duration& min_separation() { return min_sep_; } bool operator ==(const TimeBasedFilter& other) const { return other.min_separation() == min_sep_; } private: dds::core::Duration min_sep_; }; //============================================================================== class Partition { public: Partition() {} explicit Partition(const std::string& partition) : name_() { name_.push_back(partition); } explicit Partition(const dds::core::StringSeq& partitions) : name_(partitions) { } public: void name(const std::string& partition) { name_.clear(); name_.push_back(partition); } void name(const dds::core::StringSeq& partitions) { name_ = partitions; } const dds::core::StringSeq& name() const { return name_; } dds::core::StringSeq& name() { return name_; } bool operator ==(const Partition& other) const { return other.name() == name_; } private: dds::core::StringSeq name_; }; //============================================================================== class Ownership { public: public: Ownership() {} Ownership(dds::core::policy::OwnershipKind::Type kind) : kind_(kind) { } public: void kind(dds::core::policy::OwnershipKind::Type kind) { kind_ = kind; } dds::core::policy::OwnershipKind::Type kind() const { return kind_; } dds::core::policy::OwnershipKind::Type& kind() { return kind_; } bool operator ==(const Ownership& other) const { return other.kind() == kind_; } private: dds::core::policy::OwnershipKind::Type kind_; }; //============================================================================== #ifdef OMG_DDS_OWNERSHIP_SUPPORT class OwnershipStrength { public: OwnershipStrength() {} explicit OwnershipStrength(int32_t s) : s_(s) { } int32_t strength() const { return s_; } int32_t& strength() { return s_; } void strength(int32_t s) { s_ = s; } bool operator ==(const OwnershipStrength& other) const { return other.strength() == s_; } private: int32_t s_; }; #endif // OMG_DDS_OWNERSHIP_SUPPORT //============================================================================== class WriterDataLifecycle { public: WriterDataLifecycle() {} WriterDataLifecycle(bool autodispose) : autodispose_(autodispose) { } bool autodispose() const { return autodispose_; } bool& autodispose() { return autodispose_; } void autodispose(bool b) { autodispose_ = b; } bool operator ==(const WriterDataLifecycle& other) const { return other.autodispose() == autodispose_; } private: bool autodispose_; }; //============================================================================== class ReaderDataLifecycle { public: ReaderDataLifecycle() {} ReaderDataLifecycle(const dds::core::Duration& nowriter_delay, const dds::core::Duration& disposed_samples_delay) : autopurge_nowriter_samples_delay_(nowriter_delay), autopurge_disposed_samples_delay_(disposed_samples_delay) { } public: const dds::core::Duration autopurge_nowriter_samples_delay() const { return autopurge_nowriter_samples_delay_; } void autopurge_nowriter_samples_delay(const dds::core::Duration& d) { autopurge_nowriter_samples_delay_ = d; } const dds::core::Duration autopurge_disposed_samples_delay() const { return autopurge_disposed_samples_delay_; } void autopurge_disposed_samples_delay(const dds::core::Duration& d) { autopurge_disposed_samples_delay_ = d; } bool operator ==(const ReaderDataLifecycle& other) const { return other.autopurge_nowriter_samples_delay() == autopurge_nowriter_samples_delay_ && other.autopurge_disposed_samples_delay() == autopurge_disposed_samples_delay(); } private: dds::core::Duration autopurge_nowriter_samples_delay_; dds::core::Duration autopurge_disposed_samples_delay_; }; //============================================================================== class Durability { public: public: Durability() {} Durability(dds::core::policy::DurabilityKind::Type kind) : kind_(kind) { } public: void durability(dds::core::policy::DurabilityKind::Type kind) { kind_ = kind; } dds::core::policy::DurabilityKind::Type durability() const { return kind_; } dds::core::policy::DurabilityKind::Type& durability() { return kind_; } void kind(dds::core::policy::DurabilityKind::Type kind) { kind_ = kind; } dds::core::policy::DurabilityKind::Type& kind() { return kind_; } dds::core::policy::DurabilityKind::Type kind() const { return kind_; } bool operator ==(const Durability& other) const { return other.kind() == kind_; } public: dds::core::policy::DurabilityKind::Type kind_; }; //============================================================================== class Presentation { public: Presentation() {} Presentation(dds::core::policy::PresentationAccessScopeKind::Type access_scope, bool coherent_access, bool ordered_access) : access_scope_(access_scope), coherent_access_(coherent_access), ordered_access_(ordered_access) { } void access_scope(dds::core::policy::PresentationAccessScopeKind::Type as) { access_scope_ = as; } dds::core::policy::PresentationAccessScopeKind::Type& access_scope() { return access_scope_; } dds::core::policy::PresentationAccessScopeKind::Type access_scope() const { return access_scope_; } void coherent_access(bool on) { coherent_access_ = on; } bool& coherent_access() { return coherent_access_; } bool coherent_access() const { return coherent_access_; } void ordered_access(bool on) { ordered_access_ = on; } bool& ordered_access() { return ordered_access_; } bool ordered_access() const { return ordered_access_; } bool operator ==(const Presentation& other) const { return other.access_scope() == access_scope_ && other.coherent_access() == coherent_access_ && other.ordered_access() == ordered_access_; } private: dds::core::policy::PresentationAccessScopeKind::Type access_scope_; bool coherent_access_; bool ordered_access_; }; //============================================================================== class Reliability { public: public: Reliability() {} Reliability(dds::core::policy::ReliabilityKind::Type kind, const dds::core::Duration& max_blocking_time) : kind_(kind), max_blocking_time_(max_blocking_time) { } public: void kind(dds::core::policy::ReliabilityKind::Type kind) { kind_ = kind; } dds::core::policy::ReliabilityKind::Type kind() const { return kind_; } void max_blocking_time(const dds::core::Duration& d) { max_blocking_time_ = d; } const dds::core::Duration max_blocking_time() const { return max_blocking_time_; } bool operator ==(const Reliability& other) const { return other.kind() == kind_ && other.max_blocking_time() == max_blocking_time_; } private: dds::core::policy::ReliabilityKind::Type kind_; dds::core::Duration max_blocking_time_; }; //============================================================================== class DestinationOrder { public: DestinationOrder() {}; explicit DestinationOrder(dds::core::policy::DestinationOrderKind::Type kind) : kind_(kind) { } public: void kind(dds::core::policy::DestinationOrderKind::Type kind) { kind_ = kind; } dds::core::policy::DestinationOrderKind::Type& kind() { return kind_; } dds::core::policy::DestinationOrderKind::Type kind() const { return kind_; } bool operator ==(const DestinationOrder& other) const { return other.kind() == kind_; } private: dds::core::policy::DestinationOrderKind::Type kind_; }; //============================================================================== class History { public: History() {} History(dds::core::policy::HistoryKind::Type kind, int32_t depth) : kind_(kind), depth_(depth) { } dds::core::policy::HistoryKind::Type kind() const { return kind_; } dds::core::policy::HistoryKind::Type& kind() { return kind_; } void kind(dds::core::policy::HistoryKind::Type kind) { kind_ = kind; } int32_t depth() const { return depth_; } int32_t& depth() { return depth_; } void depth(int32_t depth) { depth_ = depth; } bool operator ==(const History& other) const { return other.kind() == kind_ && other.depth() == depth_; } private: dds::core::policy::HistoryKind::Type kind_; int32_t depth_; }; //============================================================================== class ResourceLimits { public: ResourceLimits() {} ResourceLimits(int32_t max_samples, int32_t max_instances, int32_t max_samples_per_instance) : max_samples_(max_samples), max_instances_(max_instances), max_samples_per_instance_(max_samples_per_instance) { } public: void max_samples(int32_t samples) { max_samples_ = samples; } int32_t& max_samples() { return max_samples_; } int32_t max_samples() const { return max_samples_; } void max_instances(int32_t max_instances) { max_instances_ = max_instances; } int32_t& max_instances() { return max_instances_; } int32_t max_instances() const { return max_instances_; } void max_samples_per_instance(int32_t max_samples_per_instance) { max_samples_per_instance_ = max_samples_per_instance; } int32_t& max_samples_per_instance() { return max_samples_per_instance_; } int32_t max_samples_per_instance() const { return max_samples_per_instance_; } bool operator ==(const ResourceLimits& other) const { return other.max_samples() == max_samples_ && other.max_instances() == max_instances_ && other.max_samples_per_instance() == max_samples_per_instance_; } private: int32_t max_samples_; int32_t max_instances_; int32_t max_samples_per_instance_; }; //============================================================================== class Liveliness { public: public: Liveliness() {} Liveliness(dds::core::policy::LivelinessKind::Type kind, dds::core::Duration lease_duration) : kind_(kind), lease_duration_(lease_duration) { } void kind(dds::core::policy::LivelinessKind::Type kind) { kind_ = kind; } dds::core::policy::LivelinessKind::Type& kind() { return kind_; } dds::core::policy::LivelinessKind::Type kind() const { return kind_; } void lease_duration(const dds::core::Duration& lease_duration) { lease_duration_ = lease_duration; } dds::core::Duration& lease_duration() { return lease_duration_; } const dds::core::Duration lease_duration() const { return lease_duration_; } bool operator ==(const Liveliness& other) const { return other.kind() == kind_ && other.lease_duration() == lease_duration_; } private: dds::core::policy::LivelinessKind::Type kind_; dds::core::Duration lease_duration_; }; //============================================================================== #ifdef OMG_DDS_PERSISTENCE_SUPPORT class DurabilityService { public: DurabilityService() {} DurabilityService(const dds::core::Duration& service_cleanup_delay, dds::core::policy::HistoryKind::Type history_kind, int32_t history_depth, int32_t max_samples, int32_t max_instances, int32_t max_samples_per_instance) : cleanup_delay_(service_cleanup_delay), history_kind_(history_kind), history_depth_(history_depth), max_samples_(max_samples), max_instances_(max_instances), max_samples_per_instance_(max_samples_per_instance) { } public: void service_cleanup_delay(const dds::core::Duration& d) { cleanup_delay_ = d; } const dds::core::Duration service_cleanup_delay() const { return cleanup_delay_; } void history_kind(dds::core::policy::HistoryKind::Type kind) { history_kind_ = kind; } dds::core::policy::HistoryKind::Type history_kind() const { return history_kind_; } void history_depth(int32_t depth) { history_depth_ = depth; } int32_t history_depth() const { return history_depth_; } void max_samples(int32_t max_samples) { max_samples_ = max_samples; } int32_t max_samples() const { return max_samples_; } void max_instances(int32_t max_instances) { max_instances_ = max_instances; } int32_t max_instances() const { return max_instances_; } void max_samples_per_instance(int32_t max_samples_per_instance) { max_samples_per_instance_ = max_samples_per_instance; } int32_t max_samples_per_instance() const { return max_samples_per_instance_; } bool operator ==(const DurabilityService& other) const { return other.service_cleanup_delay() == cleanup_delay_ && other.history_kind() == history_kind_ && other.history_depth() == history_depth_ && other.max_samples() == max_samples_ && other.max_instances() == max_instances_ && other.max_samples_per_instance() == max_samples_per_instance_; } private: dds::core::Duration cleanup_delay_; dds::core::policy::HistoryKind::Type history_kind_; int32_t history_depth_; int32_t max_samples_; int32_t max_instances_; int32_t max_samples_per_instance_; }; #endif // OMG_DDS_PERSISTENCE_SUPPORT #ifdef OMG_DDS_EXTENSIBLE_AND_DYNAMIC_TOPIC_TYPE_SUPPORT class DataRepresentation { }; #endif // OMG_DDS_EXTENSIBLE_AND_DYNAMIC_TOPIC_TYPE_SUPPORT #ifdef OMG_DDS_EXTENSIBLE_AND_DYNAMIC_TOPIC_TYPE_SUPPORT class TypeConsistencyEnforcement { }; #endif // OMG_DDS_EXTENSIBLE_AND_DYNAMIC_TOPIC_TYPE_SUPPORT } } } } // namespace org::opensplice::core::policy #endif /* ORG_OPENSPLICE_CORE_POLICY_CORE_POLICY_IMPL_HPP_ */
Java
<?php /** * WoWRoster.net WoWRoster * * AddOn installer * * @copyright 2002-2011 WoWRoster.net * @license http://www.gnu.org/licenses/gpl.html Licensed under the GNU General Public License v3. * @package WoWRoster * @subpackage RosterCP */ if( !defined('IN_ROSTER') || !defined('IN_ROSTER_ADMIN') ) { exit('Detected invalid access to this file!'); } $roster->output['title'] .= $roster->locale->act['pagebar_addoninst']; include(ROSTER_ADMIN . 'roster_config_functions.php'); include(ROSTER_LIB . 'install.lib.php'); $installer = new Install; $op = ( isset($_POST['op']) ? $_POST['op'] : '' ); $id = ( isset($_POST['id']) ? $_POST['id'] : '' ); switch( $op ) { case 'deactivate': processActive($id,0); break; case 'activate': processActive($id,1); break; case 'process': $processed = processAddon(); break; case 'default_page': processPage(); break; case 'access': processAccess(); break; default: break; } // This is here to refresh the addon list $roster->get_addon_data(); $l_default_page = explode('|',$roster->locale->act['admin']['default_page']); $roster->tpl->assign_vars(array( 'S_ADDON_LIST' => false, 'L_DEFAULT_PAGE' => $l_default_page[0], 'L_DEFAULT_PAGE_HELP' => makeOverlib($l_default_page[1],$l_default_page[0],'',0,'',',WRAP'), 'S_DEFAULT_SELECT' => pageNames(array('name'=>'default_page')), ) ); $addons = getAddonList(); $install = $uninstall = $active = $deactive = $upgrade = $purge = 0; if( !empty($addons) ) { $roster->tpl->assign_vars(array( 'S_ADDON_LIST' => true, 'L_TIP_STATUS_ACTIVE' => makeOverlib($roster->locale->act['installer_turn_off'],$roster->locale->act['installer_activated']), 'L_TIP_STATUS_INACTIVE' => makeOverlib($roster->locale->act['installer_turn_on'],$roster->locale->act['installer_deactivated']), 'L_TIP_INSTALL_OLD' => makeOverlib($roster->locale->act['installer_replace_files'],$roster->locale->act['installer_overwrite']), 'L_TIP_INSTALL' => makeOverlib($roster->locale->act['installer_click_uninstall'],$roster->locale->act['installer_installed']), 'L_TIP_UNINSTALL' => makeOverlib($roster->locale->act['installer_click_install'],$roster->locale->act['installer_not_installed']), ) ); foreach( $addons as $addon ) { if( !empty($addon['icon']) ) { if( strpos($addon['icon'],'.') !== false ) { $addon['icon'] = ROSTER_PATH . 'addons/' . $addon['basename'] . '/images/' . $addon['icon']; } else { $addon['icon'] = $roster->config['interface_url'] . 'Interface/Icons/' . $addon['icon'] . '.' . $roster->config['img_suffix']; } } else { $addon['icon'] = $roster->config['interface_url'] . 'Interface/Icons/inv_misc_questionmark.' . $roster->config['img_suffix']; } $roster->tpl->assign_block_vars('addon_list', array( 'ROW_CLASS' => $roster->switch_row_class(), 'ID' => ( isset($addon['id']) ? $addon['id'] : '' ), 'ICON' => $addon['icon'], 'FULLNAME' => $addon['fullname'], 'BASENAME' => $addon['basename'], 'VERSION' => $addon['version'], 'OLD_VERSION' => ( isset($addon['oldversion']) ? $addon['oldversion'] : '' ), 'DESCRIPTION' => $addon['description'], 'DEPENDENCY' => $addon['requires'], 'AUTHOR' => $addon['author'], 'ACTIVE' => ( isset($addon['active']) ? $addon['active'] : '' ), 'INSTALL' => $addon['install'], 'L_TIP_UPGRADE' => ( isset($addon['active']) ? makeOverlib(sprintf($roster->locale->act['installer_click_upgrade'],$addon['oldversion'],$addon['version']),$roster->locale->act['installer_upgrade_avail']) : '' ), 'ACCESS' => false //( isset($addon['access']) ? $roster->auth->rosterAccess(array('name' => 'access', 'value' => $addon['access'])) : false ) ) ); if ($addon['install'] == '3') { $install++; } if ($addon['install'] == '0') { $active++; } if ($addon['install'] == '2') { $deactive++; } if ($addon['install'] == '1') { $upgrade++; } if ($addon['install'] == '-1') { $purge++; } } $roster->tpl->assign_vars(array( 'AL_C_PURGE' => $purge, // -1 'AL_C_UPGRADE' => $upgrade, // 1 'AL_C_DEACTIVE' => $deactive, // 2 'AL_C_ACTIVE' => $active, // 0 'AL_C_INSTALL' => $install, // 3 )); } else { $installer->setmessages('No addons available!'); } /* echo '<!-- <pre>'; print_r($addons); echo '</pre> -->'; */ $errorstringout = $installer->geterrors(); $messagestringout = $installer->getmessages(); $sqlstringout = $installer->getsql(); // print the error messages if( !empty($errorstringout) ) { $roster->set_message($errorstringout, $roster->locale->act['installer_error'], 'error'); } // Print the update messages if( !empty($messagestringout) ) { $roster->set_message($messagestringout, $roster->locale->act['installer_log']); } $roster->tpl->set_filenames(array('body' => 'admin/addon_install.html')); $body = $roster->tpl->fetch('body'); /** som new js **/ $js = ' jQuery(document).ready( function($){ // this is the id of the ul to use var menu; jQuery(".tab-navigation ul li").click(function(e) { e.preventDefault(); menu = jQuery(this).parent().attr("id"); //alert(menu); //jQuery("."+menu+"").css("display","none"); jQuery(".tab-navigation ul#"+menu+" li").removeClass("selected"); var tab_class = jQuery(this).attr("id"); jQuery(".tab-navigation ul#"+menu+" li").each(function() { var v = jQuery(this).attr("id"); console.log( "hiding - "+v ); jQuery("div#"+v+"").hide(); }); //jQuery("."+menu+"#" + tab_class).siblings().hide(); jQuery("."+menu+"#" + tab_class).show(); jQuery(".tab-navigation ul#"+menu+" li#" + tab_class).addClass("selected"); }); function first() { var tab_class = jQuery(".tab-navigation ul li").first().attr("id"); console.log( "first - "+tab_class ); menu = jQuery(".tab-navigation ul").attr("id"); jQuery(".tab-navigation ul#"+menu+" li").each(function() { var v = jQuery(this).attr("id"); console.log( "hiding - "+v ); jQuery("div#"+v+"").hide(); }); jQuery("."+menu+"#" + tab_class).show(); jQuery(".tab-navigation ul#"+menu+" li#" + tab_class).addClass("selected"); } var init = first(); });'; roster_add_js($js, 'inline', 'header', false, false); /** * Gets the list of currently installed roster addons * * @return array */ function getAddonList() { global $roster, $installer; // Initialize output $addons = ''; $output = ''; if( $handle = @opendir(ROSTER_ADDONS) ) { while( false !== ($file = readdir($handle)) ) { if( $file != '.' && $file != '..' && $file != '.svn' && substr($file, strrpos($file, '.')+1) != 'txt') { $addons[] = $file; } } } usort($addons, 'strnatcasecmp'); if( is_array($addons) ) { foreach( $addons as $addon ) { $installfile = ROSTER_ADDONS . $addon . DIR_SEP . 'inc' . DIR_SEP . 'install.def.php'; $install_class = $addon . 'Install'; if( file_exists($installfile) ) { include_once($installfile); if( !class_exists($install_class) ) { $installer->seterrors(sprintf($roster->locale->act['installer_no_class'],$addon)); continue; } $addonstuff = new $install_class; if( array_key_exists($addon,$roster->addon_data) ) { $output[$addon]['id'] = $roster->addon_data[$addon]['addon_id']; $output[$addon]['active'] = $roster->addon_data[$addon]['active']; $output[$addon]['access'] = $roster->addon_data[$addon]['access']; $output[$addon]['oldversion'] = $roster->addon_data[$addon]['version']; // -1 = overwrote newer version // 0 = same version // 1 = upgrade available $output[$addon]['install'] = version_compare($addonstuff->version,$roster->addon_data[$addon]['version']); if ($output[$addon]['install'] == 0 && $output[$addon]['active'] == 0) { $output[$addon]['install'] = 2; } } /* else if ($output[$addon]['install'] == 0 && $output[$addon]['active'] == 0) { $output[$addon]['install'] = 2; }*/ else { $output[$addon]['install'] = 3; } // Save current locale array // Since we add all locales for localization, we save the current locale array // This is in case one addon has the same locale strings as another, and keeps them from overwritting one another $localetemp = $roster->locale->wordings; foreach( $roster->multilanguages as $lang ) { $roster->locale->add_locale_file(ROSTER_ADDONS . $addon . DIR_SEP . 'locale' . DIR_SEP . $lang . '.php',$lang); } $output[$addon]['basename'] = $addon; $output[$addon]['fullname'] = ( isset($roster->locale->act[$addonstuff->fullname]) ? $roster->locale->act[$addonstuff->fullname] : $addonstuff->fullname ); $output[$addon]['author'] = $addonstuff->credits[0]['name']; $output[$addon]['version'] = $addonstuff->version; $output[$addon]['icon'] = $addonstuff->icon; $output[$addon]['description'] = ( isset($roster->locale->act[$addonstuff->description]) ? $roster->locale->act[$addonstuff->description] : $addonstuff->description ); $output[$addon]['requires'] = (isset($addonstuff->requires) ? $roster->locale->act['tooltip_reg_requires'].' '.$addonstuff->requires : ''); unset($addonstuff); // Restore our locale array $roster->locale->wordings = $localetemp; unset($localetemp); } } } return $output; } /** * Sets addon active/inactive * * @param int $id * @param int $mode */ function processActive( $id , $mode ) { global $roster, $installer; $query = "SELECT `basename` FROM `" . $roster->db->table('addon') . "` WHERE `addon_id` = " . $id . ";"; $basename = $roster->db->query_first($query); $query = "UPDATE `" . $roster->db->table('addon') . "` SET `active` = '$mode' WHERE `addon_id` = '$id' LIMIT 1;"; $result = $roster->db->query($query); if( !$result ) { $installer->seterrors('Database Error: ' . $roster->db->error() . '<br />SQL: ' . $query); } else { $installer->setmessages(sprintf($roster->locale->act['installer_activate_' . $mode] ,$basename)); } } /** * Addon installer/upgrader/uninstaller * */ function processAddon() { global $roster, $installer; $addon_name = $_POST['addon']; if( preg_match('/[^a-zA-Z0-9_]/', $addon_name) ) { $installer->seterrors($roster->locale->act['invalid_char_module'],$roster->locale->act['installer_error']); return; } // Check for temp tables //$old_error_die = $roster->db->error_die(false); if( false === $roster->db->query("CREATE TEMPORARY TABLE `test` (id int);") ) { $installer->temp_tables = false; $roster->db->query("UPDATE `" . $roster->db->table('config') . "` SET `config_value` = '0' WHERE `id` = 1180;"); } else { $installer->temp_tables = true; } //$roster->db->error_die($old_error_die); // Include addon install definitions $addonDir = ROSTER_ADDONS . $addon_name . DIR_SEP; $addon_install_file = $addonDir . 'inc' . DIR_SEP . 'install.def.php'; $install_class = $addon_name . 'Install'; if( !file_exists($addon_install_file) ) { $installer->seterrors(sprintf($roster->locale->act['installer_no_installdef'],$addon_name),$roster->locale->act['installer_error']); return; } require($addon_install_file); $addon = new $install_class(); $addata = escape_array((array)$addon); $addata['basename'] = $addon_name; if( $addata['basename'] == '' ) { $installer->seterrors($roster->locale->act['installer_no_empty'],$roster->locale->act['installer_error']); return; } // Get existing addon record if available $query = 'SELECT * FROM `' . $roster->db->table('addon') . '` WHERE `basename` = "' . $addata['basename'] . '";'; $result = $roster->db->query($query); if( !$result ) { $installer->seterrors(sprintf($roster->locale->act['installer_fetch_failed'],$addata['basename']) . '.<br />MySQL said: ' . $roster->db->error(),$roster->locale->act['installer_error']); return; } $previous = $roster->db->fetch($result); $roster->db->free_result($result); // Give the installer the addon data $installer->addata = $addata; $success = false; // Save current locale array // Since we add all locales for localization, we save the current locale array // This is in case one addon has the same locale strings as another, and keeps them from overwritting one another $localetemp = $roster->locale->wordings; foreach( $roster->multilanguages as $lang ) { $roster->locale->add_locale_file(ROSTER_ADDONS . $addata['basename'] . DIR_SEP . 'locale' . DIR_SEP . $lang . '.php',$lang); } // Collect data for this install type switch( $_POST['type'] ) { case 'install': if( $previous ) { $installer->seterrors(sprintf($roster->locale->act['installer_addon_exist'],$installer->addata['basename'],$previous['fullname'])); break; } // check to see if any requred addons if so and not enabled disable addon after install and give a message if (isset($installer->addata['requires'])) { if (!active_addon($installer->addata['requires'])) { $installer->addata['active'] = false; $installer->setmessages('Addon Dependency "'.$installer->addata['requires'].'" not active or installed, "'.$installer->addata['fullname'].'" has been disabled'); break; } } $query = 'INSERT INTO `' . $roster->db->table('addon') . '` VALUES (NULL,"' . $installer->addata['basename'] . '","' . $installer->addata['version'] . '","' . (int)$installer->addata['active'] . '",0,"' . $installer->addata['fullname'] . '","' . $installer->addata['description'] . '","' . $roster->db->escape(serialize($installer->addata['credits'])) . '","' . $installer->addata['icon'] . '","' . $installer->addata['wrnet_id'] . '",NULL);'; $result = $roster->db->query($query); if( !$result ) { $installer->seterrors('DB error while creating new addon record. <br /> MySQL said:' . $roster->db->error(),$roster->locale->act['installer_error']); break; } $installer->addata['addon_id'] = $roster->db->insert_id(); // We backup the addon config table to prevent damage $installer->add_backup($roster->db->table('addon_config')); $success = $addon->install(); // Delete the addon record if there is an error if( !$success ) { $query = 'DELETE FROM `' . $roster->db->table('addon') . "` WHERE `addon_id` = '" . $installer->addata['addon_id'] . "';"; $result = $roster->db->query($query); } else { $installer->sql[] = 'UPDATE `' . $roster->db->table('addon') . '` SET `active` = ' . (int)$installer->addata['active'] . " WHERE `addon_id` = '" . $installer->addata['addon_id'] . "';"; $installer->sql[] = "INSERT INTO `" . $roster->db->table('permissions') . "` VALUES ('', 'roster', '" . $installer->addata['addon_id'] . "', 'addon', '".$installer->addata['fullname']."', 'addon_access_desc' , '".$installer->addata['basename']."_access');"; } break; case 'upgrade': if( !$previous ) { $installer->seterrors(sprintf($roster->locale->act['installer_no_upgrade'],$installer->addata['basename'])); break; } /* Carry Over from AP branch if( !in_array($previous['basename'],$addon->upgrades) ) { $installer->seterrors(sprintf($roster->locale->act['installer_not_upgradable'],$addon->fullname,$previous['fullname'],$previous['basename'])); break; } */ $query = "UPDATE `" . $roster->db->table('addon') . "` SET `basename`='" . $installer->addata['basename'] . "', `version`='" . $installer->addata['version'] . "', `active`=" . (int)$installer->addata['active'] . ", `fullname`='" . $installer->addata['fullname'] . "', `description`='" . $installer->addata['description'] . "', `credits`='" . serialize($installer->addata['credits']) . "', `icon`='" . $installer->addata['icon'] . "', `wrnet_id`='" . $installer->addata['wrnet_id'] . "' WHERE `addon_id`=" . $previous['addon_id'] . ';'; $result = $roster->db->query($query); if( !$result ) { $installer->seterrors('DB error while updating the addon record. <br /> MySQL said:' . $roster->db->error(),$roster->locale->act['installer_error']); break; } $installer->addata['addon_id'] = $previous['addon_id']; // We backup the addon config table to prevent damage $installer->add_backup($roster->db->table('addon_config')); $success = $addon->upgrade($previous['version']); break; case 'uninstall': if( !$previous ) { $installer->seterrors(sprintf($roster->locale->act['installer_no_uninstall'],$installer->addata['basename'])); break; } if( $previous['basename'] != $installer->addata['basename'] ) { $installer->seterrors(sprintf($roster->locale->act['installer_not_uninstallable'],$installer->addata['basename'],$previous['fullname'])); break; } $query = 'DELETE FROM `' . $roster->db->table('addon') . '` WHERE `addon_id`=' . $previous['addon_id'] . ';'; $result = $roster->db->query($query); if( !$result ) { $installer->seterrors('DB error while deleting the addon record. <br /> MySQL said:' . $roster->db->error(),$roster->locale->act['installer_error']); break; } $installer->addata['addon_id'] = $previous['addon_id']; // We backup the addon config table to prevent damage $installer->add_backup($roster->db->table('addon_config')); $success = $addon->uninstall(); if ($success) { $installer->remove_permissions($previous['addon_id']); } break; case 'purge': $success = purge($installer->addata['basename']); break; default: $installer->seterrors($roster->locale->act['installer_invalid_type']); $success = false; break; } if( !$success ) { $installer->seterrors($roster->locale->act['installer_no_success_sql']); return false; } else { $success = $installer->install(); $installer->setmessages(sprintf($roster->locale->act['installer_' . $_POST['type'] . '_' . $success],$installer->addata['basename'])); } // Restore our locale array $roster->locale->wordings = $localetemp; unset($localetemp); return true; } /** * Addon purge * Removes an addon with a bad install/upgrade/un-install * * @param string $dbname * @return bool */ function purge( $dbname ) { global $roster, $installer; // Delete addon tables under dbname. $query = 'SHOW TABLES LIKE "' . $roster->db->prefix . 'addons_' . $dbname . '%"'; $tables = $roster->db->query($query); if( !$tables ) { $installer->seterrors('Error while getting table names for ' . $dbname . '. MySQL said: ' . $roster->db->error(),$roster->locale->act['installer_error'],__FILE__,__LINE__,$query); return false; } if( $roster->db->num_rows($tables) ) { while ($row = $roster->db->fetch($tables)) { $query = 'DROP TABLE `' . $row[0] . '`;'; $dropped = $roster->db->query($query); if( !$dropped ) { $installer->seterrors('Error while dropping ' . $row[0] . '.<br />MySQL said: ' . $roster->db->error(),$roster->locale->act['installer_error'],__FILE__,__LINE__,$query); return false; } } } // Get the addon id for this basename $query = "SELECT `addon_id` FROM `" . $roster->db->table('addon') . "` WHERE `basename` = '" . $dbname . "';"; $addon_id = $roster->db->query_first($query); if( $addon_id !== false ) { // Delete menu entries $query = 'DELETE FROM `' . $roster->db->table('menu_button') . '` WHERE `addon_id` = "' . $addon_id . '";'; $roster->db->query($query) or $installer->seterrors('Error while deleting menu entries for ' . $dbname . '.<br />MySQL said: ' . $roster->db->error(),$roster->locale->act['installer_error'],__FILE__,__LINE__,$query); // Delete addon config entries $query = 'DELETE FROM `' . $roster->db->table('addon_config') . '` WHERE `addon_id` = "' . $addon_id . '";'; $roster->db->query($query) or $installer->seterrors('Error while deleting menu entries for ' . $dbname . '.<br />MySQL said: ' . $roster->db->error(),$roster->locale->act['installer_error'],__FILE__,__LINE__,$query); } // Delete addon table entry $query = 'DELETE FROM `' . $roster->db->table('addon') . '` WHERE `basename` = "' . $dbname . '"'; $roster->db->query($query) or $installer->seterrors('Error while deleting addon table entry for ' . $dbname . '.<br />MySQL said: ' . $roster->db->error(),$roster->locale->act['installer_error'],__FILE__,__LINE__,$query); return true; } function processPage() { global $roster; $default = ( $_POST['config_default_page'] ); $query = "UPDATE `" . $roster->db->table('config') . "` SET `config_value` = '$default' WHERE `id` = '1050';"; if( !$roster->db->query($query) ) { die_quietly($roster->db->error(),'Database Error',__FILE__,__LINE__,$query); } else { // Set this enforce_rules value to the right one since roster_config isn't refreshed here $roster->config['default_page'] = $default; $roster->set_message(sprintf($roster->locale->act['default_page_set'], $default)); } } function processAccess() { global $roster; $access = implode(":",$_POST['config_access']); $id = (int)$_POST['id']; $query = "UPDATE `" . $roster->db->table('addon') . "` SET `access` = '$access' WHERE `addon_id` = '$id';"; if( !$roster->db->query($query) ) { die_quietly($roster->db->error(),'Database Error',__FILE__,__LINE__,$query); } }
Java
# odoo_ml_quality_module
Java
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html><head><title></title> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta name="generator" content="Doxygen 1.8.6"> <link rel="stylesheet" type="text/css" href="search.css"/> <script type="text/javascript" src="typedefs_1.js"></script> <script type="text/javascript" src="search.js"></script> </head> <body class="SRPage"> <div id="SRIndex"> <div class="SRStatus" id="Loading">Cargando...</div> <div id="SRResults"></div> <script type="text/javascript"><!-- createResults(); --></script> <div class="SRStatus" id="Searching">Buscando...</div> <div class="SRStatus" id="NoMatches">Nada coincide</div> <script type="text/javascript"><!-- document.getElementById("Loading").style.display="none"; document.getElementById("NoMatches").style.display="none"; var searchResults = new SearchResults("searchResults"); searchResults.Search(); --></script> </div> </body> </html>
Java
<?php namespace Paged; /** * Выводит список как маркерованный * * @category Basic library * @package Paged * @author Peter S. Gribanov <info@peter-gribanov.ru> * @version 4.0 SVN: $Revision$ * @since $Date$ * @link $HeadURL$ * @link http://peter-gribanov.ru/#open-source/paged/paged_4-x * @copyright (c) 2008 by Peter S. Gribanov * @license http://peter-gribanov.ru/license GNU GPL Version 3 */ class ViewList extends PluginView { /** * Возвращает меню в виде списка * * @return array */ public function getList(){ $list = parent::getList(); $list_new = array(); foreach ($list as $item) $list_new[] = Template::getTemplate('list.php', array($item)); return $list_new; } /** * Возвращает меню упакованное в строку * * @return string */ public function getPack(){ return Template::getTemplate('list_pack.php', $this->getList()); } /** * Выводит меню упакованное в строку * * @return void */ public function showPack(){ Template::showTemplate('list_pack.php', $this->getList()); } }
Java
import io import openpyxl from django.test import ( Client, TestCase ) from django.urls import reverse from core.models import ( User, Batch, Section, Election, Candidate, CandidateParty, CandidatePosition, Vote, VoterProfile, Setting, UserType ) class ResultsExporter(TestCase): """ Tests the results xlsx exporter view. This subview may only process requests from logged in admin users. Other users will be redirected to '/'. This will also only accept GET requests. GET requests may have an election`parameter whose value must be the id of an election. The lack of an election parameter will result in the results of all elections to be exported, with each election having its own worksheet. Other URL parameters will be ignored. Invalid election parameter values, e.g. non-existent election IDs and non-integer parameters, will return an error message. View URL: '/results/export' """ @classmethod def setUpTestData(cls): batch_num = 0 section_num = 0 voter_num = 0 party_num = 0 position_num = 0 candidate_num = 0 num_elections = 2 voters = list() positions = dict() for i in range(num_elections): election = Election.objects.create(name='Election {}'.format(i)) positions[str(election.name)] = list() num_batches = 2 for j in range(num_batches): batch = Batch.objects.create(year=batch_num, election=election) batch_num += 1 num_sections = 2 if j == 0 else 1 for k in range(num_sections): section = Section.objects.create( section_name=str(section_num) ) section_num += 1 num_students = 2 for l in range(num_students): voter = User.objects.create( username='user{}'.format(voter_num), first_name=str(voter_num), last_name=str(voter_num), type=UserType.VOTER ) voter.set_password('voter') voter.save() voter_num += 1 VoterProfile.objects.create( user=voter, batch=batch, section=section ) voters.append(voter) num_positions = 3 for i in range(num_positions): position = CandidatePosition.objects.create( position_name='Position {}'.format(position_num), election=election ) positions[str(election.name)].append(position) position_num += 1 num_parties = 3 for j in range(num_parties): party = CandidateParty.objects.create( party_name='Party {}'.format(party_num), election=election ) party_num += 1 if j != 2: # Let every third party have no candidates. num_positions = 3 for k in range(num_positions): position = positions[str(election.name)][k] candidate = Candidate.objects.create( user=voters[candidate_num], party=party, position=position, election=election ) Vote.objects.create( user=voters[candidate_num], candidate=candidate, election=election ) candidate_num += 1 # Let's give one candidate an additional vote to really make sure that # we all got the correct number of votes. Vote.objects.create( user=voters[0], # NOTE: The voter in voter[1] is a Position 1 candidate of # Party 1, where the voter in voter[0] is a member. candidate=Candidate.objects.get(user=voters[1]), election=Election.objects.get(name='Election 0') ) _admin = User.objects.create(username='admin', type=UserType.ADMIN) _admin.set_password('root') _admin.save() def setUp(self): self.client.login(username='admin', password='root') def test_anonymous_get_requests_redirected_to_index(self): self.client.logout() response = self.client.get(reverse('results-export'), follow=True) self.assertRedirects(response, '/?next=%2Fadmin%2Fresults') def test_voter_get_requests_redirected_to_index(self): self.client.logout() self.client.login(username='user0', password='voter') response = self.client.get(reverse('results-export'), follow=True) self.assertRedirects(response, reverse('index')) def test_get_all_elections_xlsx(self): response = self.client.get(reverse('results-export')) self.assertEqual(response.status_code, 200) self.assertEqual( response['Content-Disposition'], 'attachment; filename="Election Results.xlsx"' ) wb = openpyxl.load_workbook(io.BytesIO(response.content)) self.assertEqual(len(wb.worksheets), 2) # Check first worksheet. ws = wb.worksheets[0] self.assertEqual(wb.sheetnames[0], 'Election 0') row_count = ws.max_row col_count = ws.max_column self.assertEqual(row_count, 25) self.assertEqual(col_count, 5) self.assertEqual(str(ws.cell(1, 1).value), 'Election 0 Results') self.assertEqual(str(ws.cell(2, 1).value), 'Candidates') cellContents = [ 'Position 0', 'Party 0', '0, 0', 'Party 1', '3, 3', 'Party 2', 'None', 'Position 1', 'Party 0', '1, 1', 'Party 1', '4, 4', 'Party 2', 'None', 'Position 2', 'Party 0', '2, 2', 'Party 1', '5, 5', 'Party 2', 'None' ] for cellIndex, content in enumerate(cellContents, 5): self.assertEqual(str(ws.cell(cellIndex, 1).value), content) self.assertEqual(str(ws.cell(2, 2).value), 'Number of Votes') self.assertEqual(str(ws.cell(3, 2).value), '0') self.assertEqual(str(ws.cell(4, 2).value), '0') # Section self.assertEqual(str(ws.cell(7, 2).value), '1') self.assertEqual(str(ws.cell(9, 2).value), '0') self.assertEqual(str(ws.cell(11, 2).value), 'N/A') self.assertEqual(str(ws.cell(14, 2).value), '2') self.assertEqual(str(ws.cell(16, 2).value), '0') self.assertEqual(str(ws.cell(18, 2).value), 'N/A') self.assertEqual(str(ws.cell(21, 2).value), '0') self.assertEqual(str(ws.cell(23, 2).value), '0') self.assertEqual(str(ws.cell(25, 2).value), 'N/A') self.assertEqual(str(ws.cell(4, 3).value), '1') # Section self.assertEqual(str(ws.cell(7, 3).value), '0') self.assertEqual(str(ws.cell(9, 3).value), '1') self.assertEqual(str(ws.cell(11, 2).value), 'N/A') self.assertEqual(str(ws.cell(14, 3).value), '0') self.assertEqual(str(ws.cell(16, 3).value), '0') self.assertEqual(str(ws.cell(18, 2).value), 'N/A') self.assertEqual(str(ws.cell(21, 3).value), '1') self.assertEqual(str(ws.cell(23, 3).value), '0') self.assertEqual(str(ws.cell(25, 2).value), 'N/A') self.assertEqual(str(ws.cell(3, 4).value), '1') self.assertEqual(str(ws.cell(4, 4).value), '2') # Section self.assertEqual(str(ws.cell(7, 4).value), '0') self.assertEqual(str(ws.cell(9, 4).value), '0') self.assertEqual(str(ws.cell(11, 2).value), 'N/A') self.assertEqual(str(ws.cell(14, 4).value), '0') self.assertEqual(str(ws.cell(16, 4).value), '1') self.assertEqual(str(ws.cell(18, 2).value), 'N/A') self.assertEqual(str(ws.cell(21, 4).value), '0') self.assertEqual(str(ws.cell(23, 4).value), '1') self.assertEqual(str(ws.cell(25, 2).value), 'N/A') self.assertEqual(str(ws.cell(3, 5).value), 'Total Votes') self.assertEqual(str(ws.cell(7, 5).value), '1') self.assertEqual(str(ws.cell(9, 5).value), '1') self.assertEqual(str(ws.cell(11, 2).value), 'N/A') self.assertEqual(str(ws.cell(14, 5).value), '2') self.assertEqual(str(ws.cell(16, 5).value), '1') self.assertEqual(str(ws.cell(18, 2).value), 'N/A') self.assertEqual(str(ws.cell(21, 5).value), '1') self.assertEqual(str(ws.cell(23, 5).value), '1') self.assertEqual(str(ws.cell(25, 2).value), 'N/A') # Check second worksheet. ws = wb.worksheets[1] self.assertEqual(wb.sheetnames[1], 'Election 1') row_count = ws.max_row col_count = ws.max_column self.assertEqual(row_count, 25) self.assertEqual(col_count, 5) self.assertEqual(str(ws.cell(1, 1).value), 'Election 1 Results') self.assertEqual(str(ws.cell(2, 1).value), 'Candidates') self.assertEqual(str(ws.cell(2, 1).value), 'Candidates') cellContents = [ 'Position 3', 'Party 3', '6, 6', 'Party 4', '9, 9', 'Party 5', 'None', 'Position 4', 'Party 3', '7, 7', 'Party 4', '10, 10', 'Party 5', 'None', 'Position 5', 'Party 3', '8, 8', 'Party 4', '11, 11', 'Party 5', 'None' ] for cellIndex, content in enumerate(cellContents, 5): self.assertEqual(str(ws.cell(cellIndex, 1).value), content) self.assertEqual(str(ws.cell(2, 2).value), 'Number of Votes') self.assertEqual(str(ws.cell(3, 2).value), '2') self.assertEqual(str(ws.cell(4, 2).value), '3') # Section self.assertEqual(str(ws.cell(7, 2).value), '1') self.assertEqual(str(ws.cell(9, 2).value), '0') self.assertEqual(str(ws.cell(11, 2).value), 'N/A') self.assertEqual(str(ws.cell(14, 2).value), '1') self.assertEqual(str(ws.cell(16, 2).value), '0') self.assertEqual(str(ws.cell(18, 2).value), 'N/A') self.assertEqual(str(ws.cell(21, 2).value), '0') self.assertEqual(str(ws.cell(23, 2).value), '0') self.assertEqual(str(ws.cell(25, 2).value), 'N/A') self.assertEqual(str(ws.cell(4, 3).value), '4') # Section self.assertEqual(str(ws.cell(7, 3).value), '0') self.assertEqual(str(ws.cell(9, 3).value), '1') self.assertEqual(str(ws.cell(11, 2).value), 'N/A') self.assertEqual(str(ws.cell(14, 3).value), '0') self.assertEqual(str(ws.cell(16, 3).value), '0') self.assertEqual(str(ws.cell(18, 2).value), 'N/A') self.assertEqual(str(ws.cell(21, 3).value), '1') self.assertEqual(str(ws.cell(23, 3).value), '0') self.assertEqual(str(ws.cell(25, 2).value), 'N/A') self.assertEqual(str(ws.cell(3, 4).value), '3') self.assertEqual(str(ws.cell(4, 4).value), '5') # Section self.assertEqual(str(ws.cell(7, 4).value), '0') self.assertEqual(str(ws.cell(9, 4).value), '0') self.assertEqual(str(ws.cell(11, 2).value), 'N/A') self.assertEqual(str(ws.cell(14, 4).value), '0') self.assertEqual(str(ws.cell(16, 4).value), '1') self.assertEqual(str(ws.cell(18, 2).value), 'N/A') self.assertEqual(str(ws.cell(21, 4).value), '0') self.assertEqual(str(ws.cell(23, 4).value), '1') self.assertEqual(str(ws.cell(25, 2).value), 'N/A') self.assertEqual(str(ws.cell(3, 5).value), 'Total Votes') self.assertEqual(str(ws.cell(7, 5).value), '1') self.assertEqual(str(ws.cell(9, 5).value), '1') self.assertEqual(str(ws.cell(11, 2).value), 'N/A') self.assertEqual(str(ws.cell(14, 5).value), '1') self.assertEqual(str(ws.cell(16, 5).value), '1') self.assertEqual(str(ws.cell(18, 2).value), 'N/A') self.assertEqual(str(ws.cell(21, 5).value), '1') self.assertEqual(str(ws.cell(23, 5).value), '1') self.assertEqual(str(ws.cell(25, 2).value), 'N/A') def test_get_election0_xlsx(self): response = self.client.get( reverse('results-export'), { 'election': str(Election.objects.get(name='Election 0').id) } ) self.assertEqual(response.status_code, 200) self.assertEqual( response['Content-Disposition'], 'attachment; filename="Election 0 Results.xlsx"' ) wb = openpyxl.load_workbook(io.BytesIO(response.content)) self.assertEqual(len(wb.worksheets), 1) # Check first worksheet. ws = wb.worksheets[0] self.assertEqual(wb.sheetnames[0], 'Election 0') row_count = ws.max_row col_count = ws.max_column self.assertEqual(row_count, 25) self.assertEqual(col_count, 5) self.assertEqual(str(ws.cell(1, 1).value), 'Election 0 Results') self.assertEqual(str(ws.cell(2, 1).value), 'Candidates') cellContents = [ 'Position 0', 'Party 0', '0, 0', 'Party 1', '3, 3', 'Party 2', 'None', 'Position 1', 'Party 0', '1, 1', 'Party 1', '4, 4', 'Party 2', 'None', 'Position 2', 'Party 0', '2, 2', 'Party 1', '5, 5', 'Party 2', 'None' ] for cellIndex, content in enumerate(cellContents, 5): self.assertEqual(str(ws.cell(cellIndex, 1).value), content) self.assertEqual(str(ws.cell(2, 2).value), 'Number of Votes') self.assertEqual(str(ws.cell(3, 2).value), '0') self.assertEqual(str(ws.cell(4, 2).value), '0') # Section self.assertEqual(str(ws.cell(7, 2).value), '1') self.assertEqual(str(ws.cell(9, 2).value), '0') self.assertEqual(str(ws.cell(11, 2).value), 'N/A') self.assertEqual(str(ws.cell(14, 2).value), '2') self.assertEqual(str(ws.cell(16, 2).value), '0') self.assertEqual(str(ws.cell(18, 2).value), 'N/A') self.assertEqual(str(ws.cell(21, 2).value), '0') self.assertEqual(str(ws.cell(23, 2).value), '0') self.assertEqual(str(ws.cell(25, 2).value), 'N/A') self.assertEqual(str(ws.cell(4, 3).value), '1') # Section self.assertEqual(str(ws.cell(7, 3).value), '0') self.assertEqual(str(ws.cell(9, 3).value), '1') self.assertEqual(str(ws.cell(11, 2).value), 'N/A') self.assertEqual(str(ws.cell(14, 3).value), '0') self.assertEqual(str(ws.cell(16, 3).value), '0') self.assertEqual(str(ws.cell(18, 2).value), 'N/A') self.assertEqual(str(ws.cell(21, 3).value), '1') self.assertEqual(str(ws.cell(23, 3).value), '0') self.assertEqual(str(ws.cell(25, 2).value), 'N/A') self.assertEqual(str(ws.cell(3, 4).value), '1') self.assertEqual(str(ws.cell(4, 4).value), '2') # Section self.assertEqual(str(ws.cell(7, 4).value), '0') self.assertEqual(str(ws.cell(9, 4).value), '0') self.assertEqual(str(ws.cell(11, 2).value), 'N/A') self.assertEqual(str(ws.cell(14, 4).value), '0') self.assertEqual(str(ws.cell(16, 4).value), '1') self.assertEqual(str(ws.cell(18, 2).value), 'N/A') self.assertEqual(str(ws.cell(21, 4).value), '0') self.assertEqual(str(ws.cell(23, 4).value), '1') self.assertEqual(str(ws.cell(25, 2).value), 'N/A') self.assertEqual(str(ws.cell(3, 5).value), 'Total Votes') self.assertEqual(str(ws.cell(7, 5).value), '1') self.assertEqual(str(ws.cell(9, 5).value), '1') self.assertEqual(str(ws.cell(11, 2).value), 'N/A') self.assertEqual(str(ws.cell(14, 5).value), '2') self.assertEqual(str(ws.cell(16, 5).value), '1') self.assertEqual(str(ws.cell(18, 2).value), 'N/A') self.assertEqual(str(ws.cell(21, 5).value), '1') self.assertEqual(str(ws.cell(23, 5).value), '1') self.assertEqual(str(ws.cell(25, 2).value), 'N/A') def test_get_with_invalid_election_id_non_existent_election_id(self): response = self.client.get( reverse('results-export'), { 'election': '69' }, HTTP_REFERER=reverse('results'), follow=True ) messages = list(response.context['messages']) self.assertEqual( messages[0].message, 'You specified an ID for a non-existent election.' ) self.assertRedirects(response, reverse('results')) def test_get_with_invalid_election_id_non_integer_election_id(self): response = self.client.get( reverse('results-export'), { 'election': 'hey' }, HTTP_REFERER=reverse('results'), follow=True ) messages = list(response.context['messages']) self.assertEqual( messages[0].message, 'You specified a non-integer election ID.' ) self.assertRedirects(response, reverse('results')) def test_ref_get_with_invalid_election_id_non_existent_election_id(self): response = self.client.get( reverse('results-export'), { 'election': '69' }, HTTP_REFERER=reverse('results'), follow=True ) messages = list(response.context['messages']) self.assertEqual( messages[0].message, 'You specified an ID for a non-existent election.' ) self.assertRedirects(response, reverse('results')) def test_ref_get_with_invalid_election_id_non_integer_election_id(self): response = self.client.get( reverse('results-export'), { 'election': 'hey' }, HTTP_REFERER=reverse('results'), follow=True ) messages = list(response.context['messages']) self.assertEqual( messages[0].message, 'You specified a non-integer election ID.' ) self.assertRedirects(response, reverse('results'))
Java
/* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #include "unit_vector.h" namespace geometry { template class UnitVector<double>; template const UnitVector<double> operator-(const UnitVector<double> &rhs); }
Java
<?php /** @package JobBoard @copyright Copyright (c)2010-2013 Figomago <http://figomago.wordpress.com> <http://figomago.wordpress.com> @license : GNU General Public License v3 or later ----------------------------------------------------------------------- */ defined('_JEXEC') or die('Restricted access'); require_once( JPATH_COMPONENT_ADMINISTRATOR.DS.'helpers'.DS.'jobboard_list.php' ); jimport( 'joomla.application.component.view'); jimport('joomla.utilities.date'); class JobboardViewList extends JView { function display($tpl = null) { if(!JobBoardListHelper::rssEnabled()) jexit(JText::_('COM_JOBBOARD_FEEDS_NOACCES') ); $catid = $this->selcat; $keywd = $this->keysrch; $document =& JFactory::getDocument(); $document->setLink(JRoute::_('index.php?option=com_jobboard&selcat='.$catid)); // get category name $db =& JFactory::getDBO(); $query = 'SELECT '.$db->nameQuote('type').' FROM '.$db->nameQuote('#__jobboard_categories').' WHERE '.$db->nameQuote('id').' = '.$catid; $db->setQuery($query); $seldesc = $db->loadResult(); // get "show location" settings: $query = 'SELECT '.$db->nameQuote('use_location').' FROM '.$db->nameQuote('#__jobboard_config').' WHERE '.$db->nameQuote('id').' = 1'; $db->setQuery($query); $use_location = $db->loadResult(); // get the items to add to the feed $where = ($catid == 1)? '' : ' WHERE c.'.$db->nameQuote('id').' = '.$catid; $tag_include = strlen($keywd); if($tag_include > 0 && $catid == 1) { $tag_requested = $this->checkTagRequest($keywd); $where .= ($tag_requested <> '')? " WHERE j.".$db->nameQuote('job_tags')." LIKE '%{$tag_requested}%' " : ''; } $limit = 10; $where .= ' AND (DATE_FORMAT(j.expiry_date,"%Y-%m-%d") >= CURDATE() OR DATE_FORMAT(j.expiry_date,"%Y-%m-%d") = 0000-00-00) '; $query = 'SELECT j.`id` , j.`post_date` , j.`job_title` , j.`job_type` , j.`country` , c.`type` AS category , cl.`description` AS job_level , j.`description` , j.`city` FROM `#__jobboard_jobs` AS j INNER JOIN `#__jobboard_categories` AS c ON (j.`category` = c.`id`) INNER JOIN `#__jobboard_career_levels` AS cl ON (j.`career_level` = cl.`id`) '.$where.' ORDER BY j.`post_date` DESC LIMIT '.$limit; $db->setQuery($query); $rows = $db->loadObjectList(); $site_name = $_SERVER['SERVER_NAME']; if($tag_requested <> ''){ $document->setDescription(JText::_('JOBS_WITH').' "'.ucfirst($tag_requested).'" '.JText::_('KEYWD_TAG')); $rss_title = $site_name. ': '.JText::_('JOBS_WITH').' "'.ucfirst($tag_requested).'" '; }else { $document->setDescription(JText::_('RSS_LATEST_JOBS').': '.$seldesc ); $rss_title = $site_name. ': '.JText::_('RSS_LATEST_JOBS').': '.$seldesc; } $document->setTitle($rss_title); foreach ($rows as $row) { // create a new feed item $job = new JFeedItem(); // assign values to the item $job_date = new JDate($row->post_date); $job_pubDate = new JDate(); $job->category = $row->category ; $job->date = $job_date->toRFC822(); $job->description = $this->trimDescr(html_entity_decode($this->escape($row->description)), '.'); $link = htmlentities('index.php?option=com_jobboard&view=job&id='.$row->id); $job->link = JRoute::_($link); $job->pubDate = $job_pubDate->toRFC822(); if($use_location) { $job_location = ($row->country <> 266)? ', '.$row->city : ', '.JText::_('WORK_FROM_ANYWHERE'); } else $job_location = ''; $job->title = JText::_('JOB_VACANCY').': '.html_entity_decode($this->escape($row->job_title.$job_location.' ('.JText::_($row->job_type).')')); // add item to the feed $document->addItem($job); } } function checkTagRequest($keywd) { $key_array = explode( ',' , $keywd); return (count($key_array) == 1)? $this->escape(trim(strtolower ( $key_array[0]) ) ) : ''; } function trimDescr($descr, $delim){ $first_bit = strstr($descr, '.', true); $remainder = strstr($descr, '.'); return $first_bit.'. '.strstr(substr($remainder, 1), '.', true).' ...'; } } ?>
Java
/* Copyright © 2017 the InMAP authors. This file is part of InMAP. InMAP is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. InMAP is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with InMAP. If not, see <http://www.gnu.org/licenses/>.*/ package eieio import ( "context" "fmt" "github.com/spatialmodel/inmap/emissions/slca" "github.com/spatialmodel/inmap/emissions/slca/eieio/eieiorpc" "github.com/spatialmodel/inmap/internal/hash" "gonum.org/v1/gonum/mat" ) type emissionsRequest struct { demand *mat.VecDense industries *Mask pol slca.Pollutant year Year loc Location aqm string } // Emissions returns spatially-explicit emissions caused by the // specified economic demand. Emitters // specifies the emitters emissions should be calculated for. // If emitters == nil, combined emissions for all emitters are calculated. func (e *SpatialEIO) Emissions(ctx context.Context, request *eieiorpc.EmissionsInput) (*eieiorpc.Vector, error) { e.loadEmissionsOnce.Do(func() { var c string if e.EIEIOCache != "" { c = e.EIEIOCache + "/individual" } e.emissionsCache = loadCacheOnce(func(ctx context.Context, request interface{}) (interface{}, error) { r := request.(*emissionsRequest) return e.emissions(ctx, r.demand, r.industries, r.aqm, r.pol, r.year, r.loc) // Actually calculate the emissions. }, 1, e.MemCacheSize, c, vectorMarshal, vectorUnmarshal) }) req := &emissionsRequest{ demand: rpc2vec(request.Demand), industries: rpc2mask(request.Emitters), pol: slca.Pollutant(request.Emission), year: Year(request.Year), loc: Location(request.Location), aqm: request.AQM, } rr := e.emissionsCache.NewRequest(ctx, req, "emissions_"+hash.Hash(req)) resultI, err := rr.Result() if err != nil { return nil, err } return vec2rpc(resultI.(*mat.VecDense)), nil } // emissions returns spatially-explicit emissions caused by the // specified economic demand. industries // specifies the industries emissions should be calculated for. // If industries == nil, combined emissions for all industries are calculated. func (e *SpatialEIO) emissions(ctx context.Context, demand *mat.VecDense, industries *Mask, aqm string, pol slca.Pollutant, year Year, loc Location) (*mat.VecDense, error) { // Calculate emission factors. matrix dimension: [# grid cells, # industries] ef, err := e.emissionFactors(ctx, aqm, pol, year) if err != nil { return nil, err } // Calculate economic activity. vector dimension: [# industries, 1] activity, err := e.economicImpactsSCC(demand, year, loc) if err != nil { return nil, err } if industries != nil { // Set activity in industries we're not interested in to zero. industries.Mask(activity) } r, _ := ef.Dims() emis := mat.NewVecDense(r, nil) emis.MulVec(ef, activity) return emis, nil } // EmissionsMatrix returns spatially- and industry-explicit emissions caused by the // specified economic demand. In the result matrix, the rows represent air quality // model grid cells and the columns represent emitters. func (e *SpatialEIO) EmissionsMatrix(ctx context.Context, request *eieiorpc.EmissionsMatrixInput) (*eieiorpc.Matrix, error) { ef, err := e.emissionFactors(ctx, request.AQM, slca.Pollutant(request.Emission), Year(request.Year)) // rows = grid cells, cols = industries if err != nil { return nil, err } activity, err := e.economicImpactsSCC(array2vec(request.Demand.Data), Year(request.Year), Location(request.Location)) // rows = industries if err != nil { return nil, err } r, c := ef.Dims() emis := mat.NewDense(r, c, nil) emis.Apply(func(_, j int, v float64) float64 { // Multiply each emissions factor column by the corresponding activity row. return v * activity.At(j, 0) }, ef) return mat2rpc(emis), nil } // emissionFactors returns spatially-explicit emissions per unit of economic // production for each industry. In the result matrix, the rows represent // air quality model grid cells and the columns represent industries. func (e *SpatialEIO) emissionFactors(ctx context.Context, aqm string, pol slca.Pollutant, year Year) (*mat.Dense, error) { e.loadEFOnce.Do(func() { e.emissionFactorCache = loadCacheOnce(e.emissionFactorsWorker, 1, 1, e.EIEIOCache, matrixMarshal, matrixUnmarshal) }) key := fmt.Sprintf("emissionFactors_%s_%v_%d", aqm, pol, year) rr := e.emissionFactorCache.NewRequest(ctx, aqmPolYear{aqm: aqm, pol: pol, year: year}, key) resultI, err := rr.Result() if err != nil { return nil, fmt.Errorf("eieio.emissionFactors: %s: %v", key, err) } return resultI.(*mat.Dense), nil } // emissionFactors returns spatially-explicit emissions per unit of economic // production for each industry. In the result matrix, the rows represent // air quality model grid cells and the columns represent industries. func (e *SpatialEIO) emissionFactorsWorker(ctx context.Context, request interface{}) (interface{}, error) { aqmpolyear := request.(aqmPolYear) prod, err := e.domesticProductionSCC(aqmpolyear.year) if err != nil { return nil, err } var emisFac *mat.Dense for i, refTemp := range e.SpatialRefs { if len(refTemp.SCCs) == 0 { return nil, fmt.Errorf("bea: industry %d; no SCCs", i) } ref := refTemp ref.EmisYear = int(aqmpolyear.year) ref.AQM = aqmpolyear.aqm industryEmis, err := e.CSTConfig.EmissionsSurrogate(ctx, aqmpolyear.pol, &ref) if err != nil { return nil, err } if i == 0 { emisFac = mat.NewDense(industryEmis.Shape[0], len(e.SpatialRefs), nil) } for r, v := range industryEmis.Elements { // The emissions factor is the industry emissions divided by the // industry economic production. if p := prod.At(i, 0); p != 0 { emisFac.Set(r, i, v/prod.At(i, 0)) } } } return emisFac, nil }
Java
<?php class ControllerTotalShipping extends Controller { private $error = array(); public function index() { $this->load->language('total/shipping'); $this->document->setTitle($this->language->get('heading_title')); $this->load->model('setting/setting'); if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) { $this->model_setting_setting->editSetting('shipping', $this->request->post); $this->session->data['success'] = $this->language->get('text_success'); $this->response->redirect($this->url->link('extension/total', 'token=' . $this->session->data['token'], 'SSL')); } $data['heading_title'] = $this->language->get('heading_title'); $data['text_enabled'] = $this->language->get('text_enabled'); $data['text_disabled'] = $this->language->get('text_disabled'); $data['entry_estimator'] = $this->language->get('entry_estimator'); $data['entry_status'] = $this->language->get('entry_status'); $data['entry_sort_order'] = $this->language->get('entry_sort_order'); $data['button_save'] = $this->language->get('button_save'); $data['button_cancel'] = $this->language->get('button_cancel'); if (isset($this->error['warning'])) { $data['error_warning'] = $this->error['warning']; } else { $data['error_warning'] = ''; } $data['breadcrumbs'] = array(); $data['breadcrumbs'][] = array( 'text' => $this->language->get('text_home'), 'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL') ); $data['breadcrumbs'][] = array( 'text' => $this->language->get('text_total'), 'href' => $this->url->link('extension/total', 'token=' . $this->session->data['token'], 'SSL') ); $data['breadcrumbs'][] = array( 'text' => $this->language->get('heading_title'), 'href' => $this->url->link('total/shipping', 'token=' . $this->session->data['token'], 'SSL') ); $data['action'] = $this->url->link('total/shipping', 'token=' . $this->session->data['token'], 'SSL'); $data['cancel'] = $this->url->link('extension/total', 'token=' . $this->session->data['token'], 'SSL'); if (isset($this->request->post['shipping_estimator'])) { $data['shipping_estimator'] = $this->request->post['shipping_estimator']; } else { $data['shipping_estimator'] = $this->config->get('shipping_estimator'); } if (isset($this->request->post['shipping_status'])) { $data['shipping_status'] = $this->request->post['shipping_status']; } else { $data['shipping_status'] = $this->config->get('shipping_status'); } if (isset($this->request->post['shipping_sort_order'])) { $data['shipping_sort_order'] = $this->request->post['shipping_sort_order']; } else { $data['shipping_sort_order'] = $this->config->get('shipping_sort_order'); } $data['header'] = $this->load->controller('common/header'); $data['footer'] = $this->load->controller('common/footer'); $this->response->setOutput($this->load->view('total/shipping.tpl', $data)); } protected function validate() { if (!$this->user->hasPermission('modify', 'total/shipping')) { $this->error['warning'] = $this->language->get('error_permission'); } if (!$this->error) { return true; } else { return false; } } }
Java
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.08.02 at 08:05:16 PM CEST // package net.ramso.dita.concept; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElements; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for synblk.class complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="synblk.class"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;group ref="{}synblk.content"/> * &lt;/sequence> * &lt;attGroup ref="{}synblk.attributes"/> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "synblk.class", propOrder = { "title", "groupseqOrGroupchoiceOrGroupcomp" }) @XmlSeeAlso({ Synblk.class }) public class SynblkClass { protected Title title; @XmlElements({ @XmlElement(name = "groupseq", type = Groupseq.class), @XmlElement(name = "groupchoice", type = Groupchoice.class), @XmlElement(name = "groupcomp", type = Groupcomp.class), @XmlElement(name = "fragref", type = Fragref.class), @XmlElement(name = "synnote", type = Synnote.class), @XmlElement(name = "synnoteref", type = Synnoteref.class), @XmlElement(name = "fragment", type = Fragment.class) }) protected List<java.lang.Object> groupseqOrGroupchoiceOrGroupcomp; @XmlAttribute(name = "outputclass") protected String outputclass; @XmlAttribute(name = "xtrc") protected String xtrc; @XmlAttribute(name = "xtrf") protected String xtrf; @XmlAttribute(name = "base") protected String base; @XmlAttribute(name = "rev") protected String rev; @XmlAttribute(name = "importance") protected ImportanceAttsClass importance; @XmlAttribute(name = "status") protected StatusAttsClass status; @XmlAttribute(name = "props") protected String props; @XmlAttribute(name = "platform") protected String platform; @XmlAttribute(name = "product") protected String product; @XmlAttribute(name = "audience") protected String audienceMod; @XmlAttribute(name = "otherprops") protected String otherprops; @XmlAttribute(name = "translate") protected YesnoAttClass translate; @XmlAttribute(name = "lang", namespace = "http://www.w3.org/XML/1998/namespace") protected String lang; @XmlAttribute(name = "dir") protected DirAttsClass dir; @XmlAttribute(name = "id") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "NMTOKEN") protected String id; @XmlAttribute(name = "conref") protected String conref; @XmlAttribute(name = "conrefend") protected String conrefend; @XmlAttribute(name = "conaction") protected ConactionAttClass conaction; @XmlAttribute(name = "conkeyref") protected String conkeyref; /** * Gets the value of the title property. * * @return * possible object is * {@link Title } * */ public Title getTitle() { return title; } /** * Sets the value of the title property. * * @param value * allowed object is * {@link Title } * */ public void setTitle(Title value) { this.title = value; } /** * Gets the value of the groupseqOrGroupchoiceOrGroupcomp property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the groupseqOrGroupchoiceOrGroupcomp property. * * <p> * For example, to add a new item, do as follows: * <pre> * getGroupseqOrGroupchoiceOrGroupcomp().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Groupseq } * {@link Groupchoice } * {@link Groupcomp } * {@link Fragref } * {@link Synnote } * {@link Synnoteref } * {@link Fragment } * * */ public List<java.lang.Object> getGroupseqOrGroupchoiceOrGroupcomp() { if (groupseqOrGroupchoiceOrGroupcomp == null) { groupseqOrGroupchoiceOrGroupcomp = new ArrayList<java.lang.Object>(); } return this.groupseqOrGroupchoiceOrGroupcomp; } /** * Gets the value of the outputclass property. * * @return * possible object is * {@link String } * */ public String getOutputclass() { return outputclass; } /** * Sets the value of the outputclass property. * * @param value * allowed object is * {@link String } * */ public void setOutputclass(String value) { this.outputclass = value; } /** * Gets the value of the xtrc property. * * @return * possible object is * {@link String } * */ public String getXtrc() { return xtrc; } /** * Sets the value of the xtrc property. * * @param value * allowed object is * {@link String } * */ public void setXtrc(String value) { this.xtrc = value; } /** * Gets the value of the xtrf property. * * @return * possible object is * {@link String } * */ public String getXtrf() { return xtrf; } /** * Sets the value of the xtrf property. * * @param value * allowed object is * {@link String } * */ public void setXtrf(String value) { this.xtrf = value; } /** * Gets the value of the base property. * * @return * possible object is * {@link String } * */ public String getBase() { return base; } /** * Sets the value of the base property. * * @param value * allowed object is * {@link String } * */ public void setBase(String value) { this.base = value; } /** * Gets the value of the rev property. * * @return * possible object is * {@link String } * */ public String getRev() { return rev; } /** * Sets the value of the rev property. * * @param value * allowed object is * {@link String } * */ public void setRev(String value) { this.rev = value; } /** * Gets the value of the importance property. * * @return * possible object is * {@link ImportanceAttsClass } * */ public ImportanceAttsClass getImportance() { return importance; } /** * Sets the value of the importance property. * * @param value * allowed object is * {@link ImportanceAttsClass } * */ public void setImportance(ImportanceAttsClass value) { this.importance = value; } /** * Gets the value of the status property. * * @return * possible object is * {@link StatusAttsClass } * */ public StatusAttsClass getStatus() { return status; } /** * Sets the value of the status property. * * @param value * allowed object is * {@link StatusAttsClass } * */ public void setStatus(StatusAttsClass value) { this.status = value; } /** * Gets the value of the props property. * * @return * possible object is * {@link String } * */ public String getProps() { return props; } /** * Sets the value of the props property. * * @param value * allowed object is * {@link String } * */ public void setProps(String value) { this.props = value; } /** * Gets the value of the platform property. * * @return * possible object is * {@link String } * */ public String getPlatform() { return platform; } /** * Sets the value of the platform property. * * @param value * allowed object is * {@link String } * */ public void setPlatform(String value) { this.platform = value; } /** * Gets the value of the product property. * * @return * possible object is * {@link String } * */ public String getProduct() { return product; } /** * Sets the value of the product property. * * @param value * allowed object is * {@link String } * */ public void setProduct(String value) { this.product = value; } /** * Gets the value of the audienceMod property. * * @return * possible object is * {@link String } * */ public String getAudienceMod() { return audienceMod; } /** * Sets the value of the audienceMod property. * * @param value * allowed object is * {@link String } * */ public void setAudienceMod(String value) { this.audienceMod = value; } /** * Gets the value of the otherprops property. * * @return * possible object is * {@link String } * */ public String getOtherprops() { return otherprops; } /** * Sets the value of the otherprops property. * * @param value * allowed object is * {@link String } * */ public void setOtherprops(String value) { this.otherprops = value; } /** * Gets the value of the translate property. * * @return * possible object is * {@link YesnoAttClass } * */ public YesnoAttClass getTranslate() { return translate; } /** * Sets the value of the translate property. * * @param value * allowed object is * {@link YesnoAttClass } * */ public void setTranslate(YesnoAttClass value) { this.translate = value; } /** * Gets the value of the lang property. * * @return * possible object is * {@link String } * */ public String getLang() { return lang; } /** * Sets the value of the lang property. * * @param value * allowed object is * {@link String } * */ public void setLang(String value) { this.lang = value; } /** * Gets the value of the dir property. * * @return * possible object is * {@link DirAttsClass } * */ public DirAttsClass getDir() { return dir; } /** * Sets the value of the dir property. * * @param value * allowed object is * {@link DirAttsClass } * */ public void setDir(DirAttsClass value) { this.dir = value; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the conref property. * * @return * possible object is * {@link String } * */ public String getConref() { return conref; } /** * Sets the value of the conref property. * * @param value * allowed object is * {@link String } * */ public void setConref(String value) { this.conref = value; } /** * Gets the value of the conrefend property. * * @return * possible object is * {@link String } * */ public String getConrefend() { return conrefend; } /** * Sets the value of the conrefend property. * * @param value * allowed object is * {@link String } * */ public void setConrefend(String value) { this.conrefend = value; } /** * Gets the value of the conaction property. * * @return * possible object is * {@link ConactionAttClass } * */ public ConactionAttClass getConaction() { return conaction; } /** * Sets the value of the conaction property. * * @param value * allowed object is * {@link ConactionAttClass } * */ public void setConaction(ConactionAttClass value) { this.conaction = value; } /** * Gets the value of the conkeyref property. * * @return * possible object is * {@link String } * */ public String getConkeyref() { return conkeyref; } /** * Sets the value of the conkeyref property. * * @param value * allowed object is * {@link String } * */ public void setConkeyref(String value) { this.conkeyref = value; } }
Java
<?php /* Extension:Moderation - MediaWiki extension. Copyright (C) 2020 Edward Chernenko. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. */ /** * @file * Unit test of RejectOneConsequence. */ use MediaWiki\Moderation\RejectOneConsequence; require_once __DIR__ . "/autoload.php"; /** * @group Database */ class RejectOneConsequenceTest extends ModerationUnitTestCase { use ModifyDbRowTestTrait; /** @var string[] */ protected $tablesUsed = [ 'moderation', 'user' ]; /** * Verify that RejectOneConsequence marks the database row as rejected and returns 1. * @covers MediaWiki\Moderation\RejectOneConsequence */ public function testRejectOne() { $moderator = User::createNew( 'Some moderator' ); $modid = $this->makeDbRow(); // Create and run the Consequence. $consequence = new RejectOneConsequence( $modid, $moderator ); $rejectedCount = $consequence->run(); $this->assertSame( 1, $rejectedCount ); // Check the state of the database. $this->assertWasRejected( $modid, $moderator ); } /** * Verify that RejectOneConsequence returns 0 for an already rejected edit. * @covers MediaWiki\Moderation\RejectOneConsequence */ public function testNoopRejectOne() { $moderator = User::createNew( 'Some moderator' ); $modid = $this->makeDbRow(); // Create and run the Consequence. $consequence1 = new RejectOneConsequence( $modid, $moderator ); $consequence1->run(); $consequence2 = new RejectOneConsequence( $modid, $moderator ); $rejectedCount = $consequence2->run(); $this->assertSame( 0, $rejectedCount ); // Despite $consequence2 doing nothing, the row should still be marked as rejected. $this->assertWasRejected( $modid, $moderator ); } /** * Verify that RejectOneConsequence does nothing if DB row is marked as merged or rejected. * @param array $fields Passed to $dbw->update( 'moderation', ... ) before the test. * @covers MediaWiki\Moderation\RejectOneConsequence * @dataProvider dataProviderNotApplicableRejectOne */ public function testNotApplicableRejectOne( array $fields ) { $moderator = User::createNew( 'Some moderator' ); $modid = $this->makeDbRow(); $dbw = wfGetDB( DB_MASTER ); $dbw->update( 'moderation', $fields, [ 'mod_id' => $modid ], __METHOD__ ); // Create and run the Consequence. $consequence = new RejectOneConsequence( $modid, $moderator ); $rejectedCount = $consequence->run(); $this->assertSame( 0, $rejectedCount ); } /** * Provide datasets for testNotApplicableRejectOne() runs. * @return array */ public function dataProviderNotApplicableRejectOne() { return [ 'already rejected' => [ [ 'mod_rejected' => 1 ] ], 'already merged' => [ [ 'mod_merged_revid' => 1234 ] ] ]; } /** * Assert that the change was marked as rejected in the database. * @param int $modid * @param User $moderator */ private function assertWasRejected( $modid, User $moderator ) { $this->assertSelect( 'moderation', [ 'mod_rejected', 'mod_rejected_by_user', 'mod_rejected_by_user_text', 'mod_preloadable', 'mod_rejected_batch', 'mod_rejected_auto' ], [ 'mod_id' => $modid ], [ [ 1, $moderator->getId(), $moderator->getName(), $modid, // mod_preloadable 0, // mod_rejected_batch 0, // mod_rejected_auto ] ] ); } }
Java
/* * Copyright (C) 2013-2017 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * If the program is linked with libraries which are licensed under one of * the following licenses, the combination of the program with the linked * library is not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed * under the aforementioned licenses, is permitted by the copyright holders * if the distribution is compliant with both the GNU General Public License * version 2 and the aforementioned licenses. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. */ package org.n52.series.db.beans.parameter; import java.util.HashMap; import java.util.Map; public abstract class Parameter<T> { private long parameterId; private long fkId; private String name; private T value; public Map<String, Object> toValueMap() { Map<String, Object> valueMap = new HashMap<>(); valueMap.put("name", getName()); valueMap.put("value", getValue()); return valueMap; } public long getParameterId() { return parameterId; } public void setParameterId(long parameterId) { this.parameterId = parameterId; } public long getFkId() { return fkId; } public void setFkId(long fkId) { this.fkId = fkId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isSetName() { return getName() != null; } public T getValue() { return value; } public void setValue(T value) { this.value = value; } public boolean isSetValue() { return getValue() != null; } }
Java
/* glpapi16.c (basic graph and network routines) */ /*********************************************************************** * This code is part of GLPK (GNU Linear Programming Kit). * * Copyright (C) 2000,01,02,03,04,05,06,07,08,2009 Andrew Makhorin, * Department for Applied Informatics, Moscow Aviation Institute, * Moscow, Russia. All rights reserved. E-mail: <mao@mai2.rcnet.ru>. * * GLPK is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GLPK is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public * License for more details. * * You should have received a copy of the GNU General Public License * along with GLPK. If not, see <http://www.gnu.org/licenses/>. ***********************************************************************/ #include "glpapi.h" /* CAUTION: DO NOT CHANGE THE LIMITS BELOW */ #define NV_MAX 100000000 /* = 100*10^6 */ /* maximal number of vertices in the graph */ #define NA_MAX 500000000 /* = 500*10^6 */ /* maximal number of arcs in the graph */ /*********************************************************************** * NAME * * glp_create_graph - create graph * * SYNOPSIS * * glp_graph *glp_create_graph(int v_size, int a_size); * * DESCRIPTION * * The routine creates a new graph, which initially is empty, i.e. has * no vertices and arcs. * * The parameter v_size specifies the size of data associated with each * vertex of the graph (0 to 256 bytes). * * The parameter a_size specifies the size of data associated with each * arc of the graph (0 to 256 bytes). * * RETURNS * * The routine returns a pointer to the graph created. */ static void create_graph(glp_graph *G, int v_size, int a_size) { G->pool = dmp_create_pool(); G->name = NULL; G->nv_max = 50; G->nv = G->na = 0; G->v = xcalloc(1+G->nv_max, sizeof(glp_vertex *)); G->index = NULL; G->v_size = v_size; G->a_size = a_size; return; } glp_graph *glp_create_graph(int v_size, int a_size) { glp_graph *G; if (!(0 <= v_size && v_size <= 256)) xerror("glp_create_graph: v_size = %d; invalid size of vertex " "data\n", v_size); if (!(0 <= a_size && a_size <= 256)) xerror("glp_create_graph: a_size = %d; invalid size of arc dat" "a\n", a_size); G = xmalloc(sizeof(glp_graph)); create_graph(G, v_size, a_size); return G; } /*********************************************************************** * NAME * * glp_set_graph_name - assign (change) graph name * * SYNOPSIS * * void glp_set_graph_name(glp_graph *G, const char *name); * * DESCRIPTION * * The routine glp_set_graph_name assigns a symbolic name specified by * the character string name (1 to 255 chars) to the graph. * * If the parameter name is NULL or an empty string, the routine erases * the existing symbolic name of the graph. */ void glp_set_graph_name(glp_graph *G, const char *name) { if (G->name != NULL) { dmp_free_atom(G->pool, G->name, strlen(G->name)+1); G->name = NULL; } if (!(name == NULL || name[0] == '\0')) { int j; for (j = 0; name[j] != '\0'; j++) { if (j == 256) xerror("glp_set_graph_name: graph name too long\n"); if (iscntrl((unsigned char)name[j])) xerror("glp_set_graph_name: graph name contains invalid " "character(s)\n"); } G->name = dmp_get_atom(G->pool, strlen(name)+1); strcpy(G->name, name); } return; } /*********************************************************************** * NAME * * glp_add_vertices - add new vertices to graph * * SYNOPSIS * * int glp_add_vertices(glp_graph *G, int nadd); * * DESCRIPTION * * The routine glp_add_vertices adds nadd vertices to the specified * graph. New vertices are always added to the end of the vertex list, * so ordinal numbers of existing vertices remain unchanged. * * Being added each new vertex is isolated (has no incident arcs). * * RETURNS * * The routine glp_add_vertices returns an ordinal number of the first * new vertex added to the graph. */ int glp_add_vertices(glp_graph *G, int nadd) { int i, nv_new; if (nadd < 1) xerror("glp_add_vertices: nadd = %d; invalid number of vertice" "s\n", nadd); if (nadd > NV_MAX - G->nv) xerror("glp_add_vertices: nadd = %d; too many vertices\n", nadd); /* determine new number of vertices */ nv_new = G->nv + nadd; /* increase the room, if necessary */ if (G->nv_max < nv_new) { glp_vertex **save = G->v; while (G->nv_max < nv_new) { G->nv_max += G->nv_max; xassert(G->nv_max > 0); } G->v = xcalloc(1+G->nv_max, sizeof(glp_vertex *)); memcpy(&G->v[1], &save[1], G->nv * sizeof(glp_vertex *)); xfree(save); } /* add new vertices to the end of the vertex list */ for (i = G->nv+1; i <= nv_new; i++) { glp_vertex *v; G->v[i] = v = dmp_get_atom(G->pool, sizeof(glp_vertex)); v->i = i; v->name = NULL; v->entry = NULL; if (G->v_size == 0) v->data = NULL; else { v->data = dmp_get_atom(G->pool, G->v_size); memset(v->data, 0, G->v_size); } v->temp = NULL; v->in = v->out = NULL; } /* set new number of vertices */ G->nv = nv_new; /* return the ordinal number of the first vertex added */ return nv_new - nadd + 1; } /**********************************************************************/ void glp_set_vertex_name(glp_graph *G, int i, const char *name) { /* assign (change) vertex name */ glp_vertex *v; if (!(1 <= i && i <= G->nv)) xerror("glp_set_vertex_name: i = %d; vertex number out of rang" "e\n", i); v = G->v[i]; if (v->name != NULL) { if (v->entry != NULL) { xassert(G->index != NULL); avl_delete_node(G->index, v->entry); v->entry = NULL; } dmp_free_atom(G->pool, v->name, strlen(v->name)+1); v->name = NULL; } if (!(name == NULL || name[0] == '\0')) { int k; for (k = 0; name[k] != '\0'; k++) { if (k == 256) xerror("glp_set_vertex_name: i = %d; vertex name too lon" "g\n", i); if (iscntrl((unsigned char)name[k])) xerror("glp_set_vertex_name: i = %d; vertex name contain" "s invalid character(s)\n", i); } v->name = dmp_get_atom(G->pool, strlen(name)+1); strcpy(v->name, name); if (G->index != NULL) { xassert(v->entry == NULL); v->entry = avl_insert_node(G->index, v->name); avl_set_node_link(v->entry, v); } } return; } /*********************************************************************** * NAME * * glp_add_arc - add new arc to graph * * SYNOPSIS * * glp_arc *glp_add_arc(glp_graph *G, int i, int j); * * DESCRIPTION * * The routine glp_add_arc adds a new arc to the specified graph. * * The parameters i and j specify the ordinal numbers of, resp., tail * and head vertices of the arc. Note that self-loops and multiple arcs * are allowed. * * RETURNS * * The routine glp_add_arc returns a pointer to the arc added. */ glp_arc *glp_add_arc(glp_graph *G, int i, int j) { glp_arc *a; if (!(1 <= i && i <= G->nv)) xerror("glp_add_arc: i = %d; tail vertex number out of range\n" , i); if (!(1 <= j && j <= G->nv)) xerror("glp_add_arc: j = %d; head vertex number out of range\n" , j); if (G->na == NA_MAX) xerror("glp_add_arc: too many arcs\n"); a = dmp_get_atom(G->pool, sizeof(glp_arc)); a->tail = G->v[i]; a->head = G->v[j]; if (G->a_size == 0) a->data = NULL; else { a->data = dmp_get_atom(G->pool, G->a_size); memset(a->data, 0, G->a_size); } a->temp = NULL; a->t_prev = NULL; a->t_next = G->v[i]->out; if (a->t_next != NULL) a->t_next->t_prev = a; a->h_prev = NULL; a->h_next = G->v[j]->in; if (a->h_next != NULL) a->h_next->h_prev = a; G->v[i]->out = G->v[j]->in = a; G->na++; return a; } /*********************************************************************** * NAME * * glp_del_vertices - delete vertices from graph * * SYNOPSIS * * void glp_del_vertices(glp_graph *G, int ndel, const int num[]); * * DESCRIPTION * * The routine glp_del_vertices deletes vertices along with all * incident arcs from the specified graph. Ordinal numbers of vertices * to be deleted should be placed in locations num[1], ..., num[ndel], * ndel > 0. * * Note that deleting vertices involves changing ordinal numbers of * other vertices remaining in the graph. New ordinal numbers of the * remaining vertices are assigned under the assumption that the * original order of vertices is not changed. */ void glp_del_vertices(glp_graph *G, int ndel, const int num[]) { glp_vertex *v; int i, k, nv_new; /* scan the list of vertices to be deleted */ if (!(1 <= ndel && ndel <= G->nv)) xerror("glp_del_vertices: ndel = %d; invalid number of vertice" "s\n", ndel); for (k = 1; k <= ndel; k++) { /* take the number of vertex to be deleted */ i = num[k]; /* obtain pointer to i-th vertex */ if (!(1 <= i && i <= G->nv)) xerror("glp_del_vertices: num[%d] = %d; vertex number out o" "f range\n", k, i); v = G->v[i]; /* check that the vertex is not marked yet */ if (v->i == 0) xerror("glp_del_vertices: num[%d] = %d; duplicate vertex nu" "mbers not allowed\n", k, i); /* erase symbolic name assigned to the vertex */ glp_set_vertex_name(G, i, NULL); xassert(v->name == NULL); xassert(v->entry == NULL); /* free vertex data, if allocated */ if (v->data != NULL) dmp_free_atom(G->pool, v->data, G->v_size); /* delete all incoming arcs */ while (v->in != NULL) glp_del_arc(G, v->in); /* delete all outgoing arcs */ while (v->out != NULL) glp_del_arc(G, v->out); /* mark the vertex to be deleted */ v->i = 0; } /* delete all marked vertices from the vertex list */ nv_new = 0; for (i = 1; i <= G->nv; i++) { /* obtain pointer to i-th vertex */ v = G->v[i]; /* check if the vertex is marked */ if (v->i == 0) { /* it is marked, delete it */ dmp_free_atom(G->pool, v, sizeof(glp_vertex)); } else { /* it is not marked, keep it */ v->i = ++nv_new; G->v[v->i] = v; } } /* set new number of vertices in the graph */ G->nv = nv_new; return; } /*********************************************************************** * NAME * * glp_del_arc - delete arc from graph * * SYNOPSIS * * void glp_del_arc(glp_graph *G, glp_arc *a); * * DESCRIPTION * * The routine glp_del_arc deletes an arc from the specified graph. * The arc to be deleted must exist. */ void glp_del_arc(glp_graph *G, glp_arc *a) { /* some sanity checks */ xassert(G->na > 0); xassert(1 <= a->tail->i && a->tail->i <= G->nv); xassert(a->tail == G->v[a->tail->i]); xassert(1 <= a->head->i && a->head->i <= G->nv); xassert(a->head == G->v[a->head->i]); /* remove the arc from the list of incoming arcs */ if (a->h_prev == NULL) a->head->in = a->h_next; else a->h_prev->h_next = a->h_next; if (a->h_next == NULL) ; else a->h_next->h_prev = a->h_prev; /* remove the arc from the list of outgoing arcs */ if (a->t_prev == NULL) a->tail->out = a->t_next; else a->t_prev->t_next = a->t_next; if (a->t_next == NULL) ; else a->t_next->t_prev = a->t_prev; /* free arc data, if allocated */ if (a->data != NULL) dmp_free_atom(G->pool, a->data, G->a_size); /* delete the arc from the graph */ dmp_free_atom(G->pool, a, sizeof(glp_arc)); G->na--; return; } /*********************************************************************** * NAME * * glp_erase_graph - erase graph content * * SYNOPSIS * * void glp_erase_graph(glp_graph *G, int v_size, int a_size); * * DESCRIPTION * * The routine glp_erase_graph erases the content of the specified * graph. The effect of this operation is the same as if the graph * would be deleted with the routine glp_delete_graph and then created * anew with the routine glp_create_graph, with exception that the * handle (pointer) to the graph remains valid. */ static void delete_graph(glp_graph *G) { dmp_delete_pool(G->pool); xfree(G->v); if (G->index != NULL) avl_delete_tree(G->index); return; } void glp_erase_graph(glp_graph *G, int v_size, int a_size) { if (!(0 <= v_size && v_size <= 256)) xerror("glp_erase_graph: v_size = %d; invalid size of vertex d" "ata\n", v_size); if (!(0 <= a_size && a_size <= 256)) xerror("glp_erase_graph: a_size = %d; invalid size of arc data" "\n", a_size); delete_graph(G); create_graph(G, v_size, a_size); return; } /*********************************************************************** * NAME * * glp_delete_graph - delete graph * * SYNOPSIS * * void glp_delete_graph(glp_graph *G); * * DESCRIPTION * * The routine glp_delete_graph deletes the specified graph and frees * all the memory allocated to this program object. */ void glp_delete_graph(glp_graph *G) { delete_graph(G); xfree(G); return; } /**********************************************************************/ void glp_create_v_index(glp_graph *G) { /* create vertex name index */ glp_vertex *v; int i; if (G->index == NULL) { G->index = avl_create_tree(avl_strcmp, NULL); for (i = 1; i <= G->nv; i++) { v = G->v[i]; xassert(v->entry == NULL); if (v->name != NULL) { v->entry = avl_insert_node(G->index, v->name); avl_set_node_link(v->entry, v); } } } return; } int glp_find_vertex(glp_graph *G, const char *name) { /* find vertex by its name */ AVLNODE *node; int i = 0; if (G->index == NULL) xerror("glp_find_vertex: vertex name index does not exist\n"); if (!(name == NULL || name[0] == '\0' || strlen(name) > 255)) { node = avl_find_node(G->index, name); if (node != NULL) i = ((glp_vertex *)avl_get_node_link(node))->i; } return i; } void glp_delete_v_index(glp_graph *G) { /* delete vertex name index */ int i; if (G->index != NULL) { avl_delete_tree(G->index), G->index = NULL; for (i = 1; i <= G->nv; i++) G->v[i]->entry = NULL; } return; } /*********************************************************************** * NAME * * glp_read_graph - read graph from plain text file * * SYNOPSIS * * int glp_read_graph(glp_graph *G, const char *fname); * * DESCRIPTION * * The routine glp_read_graph reads a graph from a plain text file. * * RETURNS * * If the operation was successful, the routine returns zero. Otherwise * it prints an error message and returns non-zero. */ int glp_read_graph(glp_graph *G, const char *fname) { glp_data *data; jmp_buf jump; int nv, na, i, j, k, ret; glp_erase_graph(G, G->v_size, G->a_size); xprintf("Reading graph from `%s'...\n", fname); data = glp_sdf_open_file(fname); if (data == NULL) { ret = 1; goto done; } if (setjmp(jump)) { ret = 1; goto done; } glp_sdf_set_jump(data, jump); nv = glp_sdf_read_int(data); if (nv < 0) glp_sdf_error(data, "invalid number of vertices\n"); na = glp_sdf_read_int(data); if (na < 0) glp_sdf_error(data, "invalid number of arcs\n"); xprintf("Graph has %d vert%s and %d arc%s\n", nv, nv == 1 ? "ex" : "ices", na, na == 1 ? "" : "s"); if (nv > 0) glp_add_vertices(G, nv); for (k = 1; k <= na; k++) { i = glp_sdf_read_int(data); if (!(1 <= i && i <= nv)) glp_sdf_error(data, "tail vertex number out of range\n"); j = glp_sdf_read_int(data); if (!(1 <= j && j <= nv)) glp_sdf_error(data, "head vertex number out of range\n"); glp_add_arc(G, i, j); } xprintf("%d lines were read\n", glp_sdf_line(data)); ret = 0; done: if (data != NULL) glp_sdf_close_file(data); return ret; } /*********************************************************************** * NAME * * glp_write_graph - write graph to plain text file * * SYNOPSIS * * int glp_write_graph(glp_graph *G, const char *fname). * * DESCRIPTION * * The routine glp_write_graph writes the specified graph to a plain * text file. * * RETURNS * * If the operation was successful, the routine returns zero. Otherwise * it prints an error message and returns non-zero. */ int glp_write_graph(glp_graph *G, const char *fname) { XFILE *fp; glp_vertex *v; glp_arc *a; int i, count, ret; xprintf("Writing graph to `%s'...\n", fname); fp = xfopen(fname, "w"), count = 0; if (fp == NULL) { xprintf("Unable to create `%s' - %s\n", fname, xerrmsg()); ret = 1; goto done; } xfprintf(fp, "%d %d\n", G->nv, G->na), count++; for (i = 1; i <= G->nv; i++) { v = G->v[i]; for (a = v->out; a != NULL; a = a->t_next) xfprintf(fp, "%d %d\n", a->tail->i, a->head->i), count++; } xfflush(fp); if (xferror(fp)) { xprintf("Write error on `%s' - %s\n", fname, xerrmsg()); ret = 1; goto done; } xprintf("%d lines were written\n", count); ret = 0; done: if (fp != NULL) xfclose(fp); return ret; } /* eof */
Java
#pragma once #ifndef ENGINE_MESH_SKELETON_H #define ENGINE_MESH_SKELETON_H class Mesh; class SMSH_File; struct MeshCPUData; struct MeshNodeData; struct MeshRequest; namespace Engine::priv { class PublicMesh; class MeshImportedData; class MeshLoader; class ModelInstanceAnimation; class ModelInstanceAnimationContainer; }; #include <serenity/resources/mesh/animation/AnimationData.h> #include <serenity/system/Macros.h> #include <serenity/utils/Utils.h> namespace Engine::priv { class MeshSkeleton final { friend class ::Mesh; friend struct ::MeshCPUData; friend class ::SMSH_File; friend class Engine::priv::MeshLoader; friend class Engine::priv::AnimationData; friend class Engine::priv::PublicMesh; friend class Engine::priv::ModelInstanceAnimation; friend class Engine::priv::ModelInstanceAnimationContainer; public: using AnimationDataMap = Engine::unordered_string_map<std::string, uint16_t>; private: AnimationDataMap m_AnimationMapping; //maps an animation name to its data glm::mat4 m_GlobalInverseTransform = glm::mat4{ 1.0f }; std::vector<BoneInfo> m_BoneInfo; std::vector<AnimationData> m_AnimationData; void clear() noexcept { m_GlobalInverseTransform = glm::mat4{ 1.0f }; } template<typename ... ARGS> int internal_add_animation_impl(std::string_view animName, ARGS&&... args) { if (hasAnimation(animName)) { return -1; } const uint16_t index = static_cast<uint16_t>(m_AnimationData.size()); m_AnimationMapping.emplace(std::piecewise_construct, std::forward_as_tuple(animName), std::forward_as_tuple(index)); m_AnimationData.emplace_back(std::forward<ARGS>(args)...); ENGINE_PRODUCTION_LOG("Added animation: " << animName); return index; } public: MeshSkeleton() = default; MeshSkeleton(const aiMesh&, const aiScene&, MeshRequest&, Engine::priv::MeshImportedData&); MeshSkeleton(const MeshSkeleton&) = delete; MeshSkeleton& operator=(const MeshSkeleton&) = delete; MeshSkeleton(MeshSkeleton&&) noexcept = default; MeshSkeleton& operator=(MeshSkeleton&&) = default; [[nodiscard]] inline AnimationDataMap& getAnimationData() noexcept { return m_AnimationMapping; } [[nodiscard]] inline uint16_t numBones() const noexcept { return (uint16_t)m_BoneInfo.size(); } [[nodiscard]] inline uint32_t numAnimations() const noexcept { return (uint32_t)m_AnimationData.size(); } [[nodiscard]] inline bool hasAnimation(std::string_view animName) const noexcept { return m_AnimationMapping.contains(animName); } inline void setBoneOffsetMatrix(uint16_t boneIdx, glm::mat4&& matrix) noexcept { m_BoneInfo[boneIdx].BoneOffset = std::move(matrix); } inline uint16_t getAnimationIndex(std::string_view animName) const noexcept { return m_AnimationMapping.find(animName)->second; } int addAnimation(std::string_view animName, const aiAnimation& anim, MeshRequest& request) { return internal_add_animation_impl(animName, anim, request); } int addAnimation(std::string_view animName, AnimationData&& animationData) { return internal_add_animation_impl(animName, std::move(animationData)); } }; }; #endif
Java
package com.mortensickel.measemulator; // http://maps.google.com/maps?q=loc:59.948509,10.602627 import com.google.android.gms.common.api.*; import android.content.Context; import android.text.*; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.view.animation.*; import android.app.*; import android.os.*; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.Handler.Callback; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.*; import android.view.View.*; import android.location.Location; import android.util.Log; import com.google.android.gms.location.*; import com.google.android.gms.common.*; import android.preference.*; import android.view.*; import android.content.*; import android.net.Uri; // import org.apache.http.impl.execchain.*; // Todo over a certain treshold, change calibration factor // TODO settable calibration factor // TODO finish icons // DONE location // DONE input background and source. Calculate activity from distance // TODO Use distribution map // DONE add settings menu // TODO generic skin // TODO handle pause and shutdown public class MainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,LocationListener { /* AUTOMESS: 0.44 pps = 0.1uSv/h ca 16. pulser pr nSv */ boolean poweron=false; long shutdowntime=0; long meastime; TextView tvTime,tvPulsedata, tvPause,tvAct, tvDoserate; long starttime = 0; public long pulses=0; Integer mode=0; final Integer MAXMODE=3; final int MODE_OFF=0; final int MODE_MOMENTANDOSE=1; final int MODE_DOSERATE=2; final int MODE_DOSE=3; public final String TAG="measem"; double calibration=4.4; public Integer sourceact=1; protected long lastpulses=0; public boolean gpsenabled = true; public Context context; public Integer gpsinterval=2000; private GoogleApiClient gac; private Location here,there; protected LocationRequest loreq; private LinearLayout llDebuginfo; private Double background=0.0; private float sourcestrength=1000; private boolean showDebug=false; private final String PULSES="pulses"; @Override public void onConnectionFailed(ConnectionResult p1) { // TODO: Implement this method } @Override public void onSaveInstanceState(Bundle savedInstanceState) { // Save the user's current game state savedInstanceState.putLong(PULSES,pulses); //savedInstanceState.putInt(PLAYER_LEVEL, mCurrentLevel); // Always call the superclass so it can save the view hierarchy state super.onSaveInstanceState(savedInstanceState); } public void onRestoreInstanceState(Bundle savedInstanceState) { // Always call the superclass so it can restore the view hierarchy super.onRestoreInstanceState(savedInstanceState); // Restore state members from saved instance pulses = savedInstanceState.getLong(PULSES); //mCurrentLevel = savedInstanceState.getInt(PLAYER_LEVEL); } protected void createLocationRequest(){ loreq = new LocationRequest(); loreq.setInterval(gpsinterval); loreq.setFastestInterval(100); loreq.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); } protected void startLocationUpdates(){ if(loreq==null){ createLocationRequest(); } LocationServices.FusedLocationApi.requestLocationUpdates(gac,loreq,this); } public void ConnectionCallbacks(){ } @Override public void onLocationChanged(Location p1) { here=p1; double distance=here.distanceTo(there); sourceact=(int)Math.round(background+sourcestrength/(distance*distance)); tvAct.setText(String.valueOf(sourceact)); } @Override public boolean onCreateOptionsMenu(Menu menu) { // TODO: Implement this method MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.mainmenu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.mnuSettings: Intent intent=new Intent(); intent.setClass(MainActivity.this,SetPreferenceActivity.class); startActivityForResult(intent,0); return true; case R.id.mnuSaveLoc: saveLocation(); return true; case R.id.mnuShowLoc: showLocation(); return true; } return super.onOptionsItemSelected(item); } protected void showLocation(){ String lat=String.valueOf(there.getLatitude()); String lon=String.valueOf(there.getLongitude()); Toast.makeText(getApplicationContext(),getString(R.string.SourceLocation)+lat+','+lon, Toast.LENGTH_LONG).show(); try { Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?q=loc:"+lat+","+lon)); startActivity(myIntent); } catch (ActivityNotFoundException e) { Toast.makeText(this, "No application can handle this request.",Toast.LENGTH_LONG).show(); e.printStackTrace(); } } protected void saveLocation(){ Location LastLocation = LocationServices.FusedLocationApi.getLastLocation( gac); if (LastLocation != null) { String lat=String.valueOf(LastLocation.getLatitude()); String lon=String.valueOf(LastLocation.getLongitude()); Toast.makeText(getApplicationContext(),getString(R.string.SourceLocation)+lat+','+lon, Toast.LENGTH_LONG).show(); there=LastLocation; SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); //SharedPreferences sp=this.getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor ed=sp.edit(); ed.putString("Latitude",lat); ed.putString("Longitude",lon); ed.apply(); ed.commit(); }else{ Toast.makeText(getApplicationContext(),getString(R.string.CouldNotGetLocation), Toast.LENGTH_LONG).show(); } } @Override public void onConnected(Bundle p1) { Location loc = LocationServices.FusedLocationApi.getLastLocation(gac); if(loc != null){ here=loc; } } @Override public void onConnectionSuspended(int p1) { // TODO: Implement this method } protected void onStart(){ gac.connect(); super.onStart(); } protected void onStop(){ gac.disconnect(); super.onStop(); } //this posts a message to the main thread from our timertask //and updates the textfield final Handler h = new Handler(new Callback() { @Override public boolean handleMessage(Message msg) { long millis = System.currentTimeMillis() - starttime; int seconds = (int) (millis / 1000); if(seconds>0){ double display=0; if( mode==MODE_MOMENTANDOSE){ if (lastpulses==0 || (lastpulses>pulses)){ display=0; }else{ display=((pulses-lastpulses)/calibration); } lastpulses=pulses; } if (mode==MODE_DOSERATE){ display=(double)pulses/(double)seconds/calibration; } if (mode==MODE_DOSE){ display=(double)pulses/calibration/3600; } tvDoserate.setText(String.format("%.2f",display)); } if(showDebug){ int minutes = seconds / 60; seconds = seconds % 60; tvTime.setText(String.format("%d:%02d", minutes, seconds)); } return false; } }); //runs without timer - reposting itself after a random interval Handler h2 = new Handler(); Runnable run = new Runnable() { @Override public void run() { int n=1; long pause=pause(getInterval()); h2.postDelayed(run,pause); if(showDebug){ tvPause.setText(String.format("%d",pause)); } receivepulse(n); } }; public Integer getInterval(){ Integer act=sourceact; if(act==0){ act=1; } Integer interval=5000/act; if (interval==0){ interval=1; } return(interval); } public long pause(Integer interval){ double pause=interval; if(interval > 5){ Random rng=new Random(); pause=rng.nextGaussian(); Integer sd=interval/4; pause=pause*sd+interval; if(pause<0){pause=0;} } return((long)pause); } public void receivepulse(int n){ LinearLayout myText = (LinearLayout) findViewById(R.id.llLed ); Animation anim = new AlphaAnimation(0.0f, 1.0f); anim.setDuration(20); //You can manage the time of the blink with this parameter anim.setStartOffset(20); anim.setRepeatMode(Animation.REVERSE); anim.setRepeatCount(0); myText.startAnimation(anim); pulses=pulses+1; Double sdev=Math.sqrt(pulses); if(showDebug){ tvPulsedata.setText(String.format("%d - %.1f - %.0f %%",pulses,sdev,sdev/pulses*100)); } } //tells handler to send a message class firstTask extends TimerTask { @Override public void run() { h.sendEmptyMessage(0); } } @Override protected void onResume() { // TODO: Implement this method super.onResume(); SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this); // lowprobCutoff = (double)sharedPref.getFloat("pref_key_lowprobcutoff", 1)/100; readPrefs(); //XlowprobCutoff= } private void readPrefs(){ SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this); String ret=sharedPref.getString("Latitude", "10"); Double lat= Double.parseDouble(ret); ret=sharedPref.getString("Longitude", "60"); Double lon= Double.parseDouble(ret); there.setLatitude(lat); there.setLongitude(lon); ret=sharedPref.getString("backgroundValue", "1"); background= Double.parseDouble(ret)/200; showDebug=sharedPref.getBoolean("showDebug", false); debugVisible(showDebug); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); readPrefs(); } Timer timer = new Timer(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); context=this; loadPref(context); /*SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE); double lat = getResources().get; long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue); SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE); // getString(R.string.preference_file_key), Context.MODE_PRIVATE); */ there = new Location("dummyprovider"); there.setLatitude(59.948509); there.setLongitude(10.602627); llDebuginfo=(LinearLayout)findViewById(R.id.llDebuginfo); llDebuginfo.setVisibility(View.GONE); gac=new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build(); tvTime = (TextView)findViewById(R.id.tvTime); tvPulsedata = (TextView)findViewById(R.id.tvPulsedata); tvPause = (TextView)findViewById(R.id.tvPause); tvDoserate = (TextView)findViewById(R.id.etDoserate); tvAct=(EditText)findViewById(R.id.activity); tvAct.addTextChangedListener(activityTW); switchMode(mode); Button b = (Button)findViewById(R.id.btPower); b.setOnClickListener(onOffClick); b=(Button)findViewById(R.id.btMode); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { modechange(v); } }); b=(Button)findViewById(R.id.btLight); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showDebug=!showDebug; } }); } @Override public void onPause() { super.onPause(); timer.cancel(); timer.purge(); h2.removeCallbacks(run); } TextWatcher activityTW = new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { String act=tvAct.getText().toString(); if(act.equals("")){act="1";} sourceact=Integer.parseInt(act); // TODO better errorchecking. // TODO disable if using geolocation }}; View.OnClickListener onOffClick = new View.OnClickListener() { @Override public void onClick(View v) { if(poweron){ long now=System.currentTimeMillis(); if(now> shutdowntime && now < shutdowntime+500){ timer.cancel(); timer.purge(); h2.removeCallbacks(run); pulses=0; poweron=false; mode=MODE_OFF; switchMode(mode); } shutdowntime = System.currentTimeMillis()+500; }else{ shutdowntime=0; starttime = System.currentTimeMillis(); timer = new Timer(); timer.schedule(new firstTask(), 0,500); startLocationUpdates(); h2.postDelayed(run, pause(getInterval())); mode=1; switchMode(mode); poweron=true; } } }; private void debugVisible(Boolean show){ View debug=findViewById(R.id.llDebuginfo); if(show){ debug.setVisibility(View.VISIBLE); }else{ debug.setVisibility(View.GONE); } } public void loadPref(Context ctx){ //SharedPreferences shpref=PreferenceManager.getDefaultSharedPreferences(ctx); PreferenceManager.setDefaultValues(ctx, R.xml.preferences, false); } public void modechange(View v){ if(mode > 0){ mode++; if (mode > MAXMODE){ mode=1; } switchMode(mode);} } public void switchMode(int mode){ int unit=0; switch(mode){ case MODE_MOMENTANDOSE: unit= R.string.ugyh; break; case MODE_DOSERATE: unit = R.string.ugyhint; break; case MODE_DOSE: unit = R.string.ugy; break; case MODE_OFF: unit= R.string.blank; tvDoserate.setText(""); break; } TextView tv=(TextView)findViewById(R.id.etUnit); tv.setText(unit); } }
Java
<?php // Esercizio: un numero che si dimezza sempre header('Content-Type: text/plain'); ini_set('display_errors', true); // MAI in produzione!!! ini_set('html_errors', 0); /** * Questa classe continua a dividere * il suo stato interno per un valore dato. */ class invert { /** * Il valore corrente * @var integer */ public $val = 1; /** * Il divisore * @var integer */ protected $_divisor = 3; /** * Esegue la divisione e restituisce il risultato * @return integer */ public function div() { $this->val = $this->val / $this->_divisor; return $this->val; } /** * Imposta il valore del divisore * @param integer $divisor * @return void */ public function setDivisor($divisor) { if ($divisor) { $this->_divisor = $divisor; } else { // Prendo dei provvedimenti } } } $sempreMeno = new invert; while ($sempreMeno->val > 1e-5) { echo $sempreMeno->div(), PHP_EOL; } // Tento di impostare un nuovo divisore... $sempreMeno->_divisor = 2; // ...ma devo usare la funzione $sempreMeno->setDivisor(2); echo $sempreMeno->div(), PHP_EOL;
Java
<?php /** * CodeIgniter * * An open source application development framework for PHP 5.2.4 or newer * * NOTICE OF LICENSE * * Licensed under the Open Software License version 3.0 * * This source file is subject to the Open Software License (OSL 3.0) that is * bundled with this package in the files license.txt / license.rst. It is * also available through the world wide web at this URL: * http://opensource.org/licenses/OSL-3.0 * If you did not receive a copy of the license and are unable to obtain it * through the world wide web, please send an email to * licensing@ellislab.com so we can send you a copy immediately. * * @package CodeIgniter * @author EllisLab Dev Team * @copyright Copyright (c) 2008 - 2013, EllisLab, Inc. (http://ellislab.com/) * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) * @link http://codeigniter.com * @since Version 1.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); /** * Database Utility Class * * @category Database * @author EllisLab Dev Team * @link http://codeigniter.com/user_guide/database/ */ abstract class CI_DB_utility { /** * Database object * * @var object */ protected $db; // -------------------------------------------------------------------- /** * List databases statement * * @var string */ protected $_list_databases = FALSE; /** * OPTIMIZE TABLE statement * * @var string */ protected $_optimize_table = FALSE; /** * REPAIR TABLE statement * * @var string */ protected $_repair_table = FALSE; // -------------------------------------------------------------------- /** * Class constructor * * @param object &$db Database object * @return void */ public function __construct(&$db) { $this->db =& $db; log_message('debug', 'Database Utility Class Initialized'); } // -------------------------------------------------------------------- /** * List databases * * @return array */ public function list_databases() { // Is there a cached result? if (isset($this->db->data_cache['db_names'])) { return $this->db->data_cache['db_names']; } elseif ($this->_list_databases === FALSE) { return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE; } $this->db->data_cache['db_names'] = array(); $query = $this->db->query($this->_list_databases); if ($query === FALSE) { return $this->db->data_cache['db_names']; } for ($i = 0, $query = $query->result_array(), $c = count($query); $i < $c; $i++) { $this->db->data_cache['db_names'][] = current($query[$i]); } return $this->db->data_cache['db_names']; } // -------------------------------------------------------------------- /** * Determine if a particular database exists * * @param string $database_name * @return bool */ public function database_exists($database_name) { return in_array($database_name, $this->list_databases()); } // -------------------------------------------------------------------- /** * Optimize Table * * @param string $table_name * @return mixed */ public function optimize_table($table_name) { if ($this->_optimize_table === FALSE) { return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE; } $query = $this->db->query(sprintf($this->_optimize_table, $this->db->escape_identifiers($table_name))); if ($query !== FALSE) { $query = $query->result_array(); return current($query); } return FALSE; } // -------------------------------------------------------------------- /** * Optimize Database * * @return mixed */ public function optimize_database() { if ($this->_optimize_table === FALSE) { return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE; } $result = array(); foreach ($this->db->list_tables() as $table_name) { $res = $this->db->query(sprintf($this->_optimize_table, $this->db->escape_identifiers($table_name))); if (is_bool($res)) { return $res; } // Build the result array... $res = $res->result_array(); $res = current($res); $key = str_replace($this->db->database.'.', '', current($res)); $keys = array_keys($res); unset($res[$keys[0]]); $result[$key] = $res; } return $result; } // -------------------------------------------------------------------- /** * Repair Table * * @param string $table_name * @return mixed */ public function repair_table($table_name) { if ($this->_repair_table === FALSE) { return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE; } $query = $this->db->query(sprintf($this->_repair_table, $this->db->escape_identifiers($table_name))); if (is_bool($query)) { return $query; } $query = $query->result_array(); return current($query); } // -------------------------------------------------------------------- /** * Generate CSV from a query result object * * @param object $query Query result object * @param string $delim Delimiter (default: ,) * @param string $newline Newline character (default: \n) * @param string $enclosure Enclosure (default: ") * @return string */ public function csv_from_result($query, $delim = ',', $newline = "\n", $enclosure = '"') { if ( ! is_object($query) OR ! method_exists($query, 'list_fields')) { show_error('You must submit a valid result object'); } $out = ''; // First generate the headings from the table column names foreach ($query->list_fields() as $name) { $out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $name).$enclosure.$delim; } $out = substr(rtrim($out), 0, -strlen($delim)).$newline; // Next blast through the result array and build out the rows while ($row = $query->unbuffered_row('array')) { foreach ($row as $item) { $out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $item).$enclosure.$delim; } $out = substr(rtrim($out), 0, -strlen($delim)).$newline; } return $out; } // -------------------------------------------------------------------- /** * Generate XML data from a query result object * * @param object $query Query result object * @param array $params Any preferences * @return string */ public function xml_from_result($query, $params = array()) { if ( ! is_object($query) OR ! method_exists($query, 'list_fields')) { show_error('You must submit a valid result object'); } // Set our default values foreach (array('root' => 'root', 'element' => 'element', 'newline' => "\n", 'tab' => "\t") as $key => $val) { if ( ! isset($params[$key])) { $params[$key] = $val; } } // Create variables for convenience extract($params); // Load the xml helper get_instance()->load->helper('xml'); // Generate the result $xml = '<'.$root.'>'.$newline; while ($row = $query->unbuffered_row()) { $xml .= $tab.'<'.$element.'>'.$newline; foreach ($row as $key => $val) { $xml .= $tab.$tab.'<'.$key.'>'.xml_convert($val).'</'.$key.'>'.$newline; } $xml .= $tab.'</'.$element.'>'.$newline; } return $xml.'</'.$root.'>'.$newline; } // -------------------------------------------------------------------- /** * Database Backup * * @param array $params * @return void */ public function backup($params = array()) { // If the parameters have not been submitted as an // array then we know that it is simply the table // name, which is a valid short cut. if (is_string($params)) { $params = array('tables' => $params); } // Set up our default preferences $prefs = array( 'tables' => array(), 'ignore' => array(), 'filename' => '', 'format' => 'gzip', // gzip, zip, txt 'add_drop' => TRUE, 'add_insert' => TRUE, 'newline' => "\n", 'foreign_key_checks' => TRUE ); // Did the user submit any preferences? If so set them.... if (count($params) > 0) { foreach ($prefs as $key => $val) { if (isset($params[$key])) { $prefs[$key] = $params[$key]; } } } // Are we backing up a complete database or individual tables? // If no table names were submitted we'll fetch the entire table list if (count($prefs['tables']) === 0) { $prefs['tables'] = $this->db->list_tables(); } // Validate the format if ( ! in_array($prefs['format'], array('gzip', 'zip', 'txt'), TRUE)) { $prefs['format'] = 'txt'; } // Is the encoder supported? If not, we'll either issue an // error or use plain text depending on the debug settings if (($prefs['format'] === 'gzip' && ! @function_exists('gzencode')) OR ($prefs['format'] === 'zip' && ! @function_exists('gzcompress'))) { if ($this->db->db_debug) { return $this->db->display_error('db_unsupported_compression'); } $prefs['format'] = 'txt'; } // Was a Zip file requested? if ($prefs['format'] === 'zip') { // Set the filename if not provided (only needed with Zip files) if ($prefs['filename'] === '') { $prefs['filename'] = (count($prefs['tables']) === 1 ? $prefs['tables'] : $this->db->database) .date('Y-m-d_H-i', time()).'.sql'; } else { // If they included the .zip file extension we'll remove it if (preg_match('|.+?\.zip$|', $prefs['filename'])) { $prefs['filename'] = str_replace('.zip', '', $prefs['filename']); } // Tack on the ".sql" file extension if needed if ( ! preg_match('|.+?\.sql$|', $prefs['filename'])) { $prefs['filename'] .= '.sql'; } } // Load the Zip class and output it $CI =& get_instance(); $CI->load->library('zip'); $CI->zip->add_data($prefs['filename'], $this->_backup($prefs)); return $CI->zip->get_zip(); } elseif ($prefs['format'] === 'txt') // Was a text file requested? { return $this->_backup($prefs); } elseif ($prefs['format'] === 'gzip') // Was a Gzip file requested? { return gzencode($this->_backup($prefs)); } return; } } /* End of file DB_utility.php */ /* Location: ./system/database/DB_utility.php */
Java
from mercurial import cmdutil _hgignore_content = """\ syntax: glob *~ *.pyc *.pyo *.bak cache/* databases/* sessions/* errors/* """ def commit(): app = request.args[0] path = apath(app, r=request) uio = ui.ui() uio.quiet = True if not os.environ.get('HGUSER') and not uio.config("ui", "username"): os.environ['HGUSER'] = 'web2py@localhost' try: r = hg.repository(ui=uio, path=path) except: r = hg.repository(ui=uio, path=path, create=True) hgignore = os.path.join(path, '.hgignore') if not os.path.exists(hgignore): open(hgignore, 'w').write(_hgignore_content) form = FORM('Comment:',INPUT(_name='comment',requires=IS_NOT_EMPTY()), INPUT(_type='submit',_value='Commit')) if form.accepts(request.vars,session): oldid = r[r.lookup('.')] cmdutil.addremove(r) r.commit(text=form.vars.comment) if r[r.lookup('.')] == oldid: response.flash = 'no changes' files = r[r.lookup('.')].files() return dict(form=form,files=TABLE(*[TR(file) for file in files]),repo=r)
Java
# coding=utf-8 """InaSAFE Disaster risk tool by Australian Aid - Flood Raster Impact on Population. Contact : ole.moller.nielsen@gmail.com .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. """ __author__ = 'Rizky Maulana Nugraha' from safe.common.utilities import OrderedDict from safe.defaults import ( default_minimum_needs, default_gender_postprocessor, age_postprocessor, minimum_needs_selector) from safe.impact_functions.impact_function_metadata import \ ImpactFunctionMetadata from safe.utilities.i18n import tr from safe.definitions import ( layer_mode_continuous, layer_geometry_raster, hazard_flood, hazard_category_single_event, unit_metres, unit_feet, count_exposure_unit, exposure_population ) class FloodEvacuationRasterHazardMetadata(ImpactFunctionMetadata): """Metadata for FloodEvacuationFunction. .. versionadded:: 2.1 We only need to re-implement as_dict(), all other behaviours are inherited from the abstract base class. """ @staticmethod def as_dict(): """Return metadata as a dictionary. This is a static method. You can use it to get the metadata in dictionary format for an impact function. :returns: A dictionary representing all the metadata for the concrete impact function. :rtype: dict """ dict_meta = { 'id': 'FloodEvacuationRasterHazardFunction', 'name': tr('Raster flood on population'), 'impact': tr('Need evacuation'), 'title': tr('Need evacuation'), 'function_type': 'old-style', 'author': 'AIFDR', 'date_implemented': 'N/A', 'overview': tr( 'To assess the impacts of flood inundation in raster ' 'format on population.'), 'detailed_description': tr( 'The population subject to inundation exceeding a ' 'threshold (default 1m) is calculated and returned as a ' 'raster layer. In addition the total number of affected ' 'people and the required needs based on the user ' 'defined minimum needs are reported. The threshold can be ' 'changed and even contain multiple numbers in which case ' 'evacuation and needs are calculated using the largest number ' 'with population breakdowns provided for the smaller numbers. ' 'The population raster is resampled to the resolution of the ' 'hazard raster and is rescaled so that the resampled ' 'population counts reflect estimates of population count ' 'per resampled cell. The resulting impact layer has the ' 'same resolution and reflects population count per cell ' 'which are affected by inundation.'), 'hazard_input': tr( 'A hazard raster layer where each cell represents flood ' 'depth (in meters).'), 'exposure_input': tr( 'An exposure raster layer where each cell represent ' 'population count.'), 'output': tr( 'Raster layer contains people affected and the minimum ' 'needs based on the people affected.'), 'actions': tr( 'Provide details about how many people would likely need ' 'to be evacuated, where they are located and what ' 'resources would be required to support them.'), 'limitations': [ tr('The default threshold of 1 meter was selected based ' 'on consensus, not hard evidence.') ], 'citations': [], 'layer_requirements': { 'hazard': { 'layer_mode': layer_mode_continuous, 'layer_geometries': [layer_geometry_raster], 'hazard_categories': [hazard_category_single_event], 'hazard_types': [hazard_flood], 'continuous_hazard_units': [unit_feet, unit_metres], 'vector_hazard_classifications': [], 'raster_hazard_classifications': [], 'additional_keywords': [] }, 'exposure': { 'layer_mode': layer_mode_continuous, 'layer_geometries': [layer_geometry_raster], 'exposure_types': [exposure_population], 'exposure_units': [count_exposure_unit], 'exposure_class_fields': [], 'additional_keywords': [] } }, 'parameters': OrderedDict([ ('thresholds [m]', [1.0]), ('postprocessors', OrderedDict([ ('Gender', default_gender_postprocessor()), ('Age', age_postprocessor()), ('MinimumNeeds', minimum_needs_selector()), ])), ('minimum needs', default_minimum_needs()) ]) } return dict_meta
Java
/** * */ package cz.geokuk.core.napoveda; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.net.MalformedURLException; import java.net.URL; import cz.geokuk.core.program.FConst; import cz.geokuk.framework.Action0; import cz.geokuk.util.process.BrowserOpener; /** * @author Martin Veverka * */ public class ZadatProblemAction extends Action0 { private static final long serialVersionUID = -2882817111560336824L; /** * @param aBoard */ public ZadatProblemAction() { super("Zadat problém ..."); putValue(SHORT_DESCRIPTION, "Zobrazí stránku na code.google.com, která umožní zadat chybu v Geokuku nebo požadavek na novou funkcionalitu."); putValue(MNEMONIC_KEY, KeyEvent.VK_P); } /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ @Override public void actionPerformed(final ActionEvent aE) { try { BrowserOpener.displayURL(new URL(FConst.POST_PROBLEM_URL)); } catch (final MalformedURLException e) { throw new RuntimeException(e); } } }
Java
/** * Copyright 2013, 2014 Ioana Ileana @ Telecom ParisTech * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ package instance; import java.util.ArrayList; public class Parser { private ArrayList<ArrayList<String>> m_relationals; private ArrayList<String[]> m_equalities; int m_pos; public Parser() { m_relationals = new ArrayList<ArrayList<String>>(); m_equalities = new ArrayList<String[]>(); m_pos=0; } public void flush() { m_pos = 0; m_relationals.clear(); m_equalities.clear(); } public boolean charIsValidForRelation(char c) { return ((c>='A' && c<='Z') || (c>='0' && c<='9') || (c=='_')); } public boolean charIsValidForTerm(char c) { return ((c>='a' && c<='z') || (c>='0' && c<='9') || (c=='_') || (c=='.') ); } public ArrayList<String> parseAtom(String line) { ArrayList<String> list = new ArrayList<String>(); String relation=""; while (m_pos<line.length()) { if (charIsValidForRelation(line.charAt(m_pos))) { relation+=line.charAt(m_pos); m_pos++; } else if (line.charAt(m_pos)=='(') { m_pos++; list.add(relation); parseTerms(line, list); return list; } else { m_pos++; } } return null; } public void parseTerms(String line, ArrayList<String> list) { while (m_pos<line.length()) { if (line.charAt(m_pos) == ')') { m_pos++; return; } else if (!charIsValidForTerm(line.charAt(m_pos))) m_pos++; else { String term=parseSingleTerm(line); list.add(term); } } } public String parseSingleTerm(String line) { String term=""; while (m_pos<line.length() && charIsValidForTerm(line.charAt(m_pos))) { term+=line.charAt(m_pos); m_pos++; } return term; } public void parseRelationals(String line) { m_pos = 0; while (m_pos<line.length()) { if (line.charAt(m_pos)<'A' || line.charAt(m_pos)>'Z') m_pos++; else { ArrayList<String> relStr = parseAtom(line); m_relationals.add(relStr); } } } public void parseEqualities(String line) { m_pos = 0; while (m_pos<line.length()) { if (!charIsValidForTerm(line.charAt(m_pos))) m_pos++; else parseEquality(line); } } public void parseEquality(String line) { String[] terms=new String[2]; terms[0] = parseSingleTerm(line); while (m_pos<line.length() && !charIsValidForTerm(line.charAt(m_pos))) m_pos++; terms[1] = parseSingleTerm(line); m_equalities.add(terms); } public ArrayList<String[]> getEqualities() { return m_equalities; } public ArrayList<ArrayList<String>> getRelationals() { return m_relationals; } public ArrayList<String> parseProvenance(String line) { ArrayList<String> provList = new ArrayList<String>(); while (m_pos < line.length()) { while (!charIsValidForTerm(line.charAt(m_pos))) m_pos++; String term = parseSingleTerm(line); if (!(term.equals(""))) { provList.add(term); } } return provList; } }
Java
(function() { 'use strict'; angular .module('app.grid') .service('GridDemoModelSerivce', GridDemoModelSerivce) .service('GridUtils',GridUtils) .factory('GridFactory',GridFactory) ; GridFactory.$inject = ['modelNode','$q','$filter']; function GridFactory(modelNode,$q,$filter) { return { buildGrid: function (option) { return new Grid(option,modelNode,$q,$filter); } } } function Grid(option,modelNode,$q,$filter) { var self = this; this.page = angular.extend({size: 9, no: 1}, option.page); this.sort = { column: option.sortColumn || '_id', direction: option.sortDirection ||-1, toggle: function (column) { if (column.sortable) { if (this.column === column.name) { this.direction = -this.direction || -1; } else { this.column = column.name; this.direction = -1; } self.paging(); } } }; this.searchForm = option.searchForm; this.rows = []; this.rawData = []; this.modelling = false; //必须有的 this.model = option.model; if (angular.isString(this.model)) { this.model = modelNode.services[this.model]; } if (!this.model) this.model = angular.noop; var promise; if (angular.isFunction(this.model)) { this.model = this.model(); } promise = $q.when(this.model).then(function (ret) { if (angular.isArray(ret)) { self.rawData = ret; } else { self.modelling = true; } self.setData = setData; self.query = query; self.paging = paging; return self; }); return promise; function setData(data) { self.rawData = data; } function query(param) { var queryParam = angular.extend({}, self.searchForm, param); if (self.modelling) { self.rows = self.model.page(self.page, queryParam, null, (self.sort.direction > 0 ? '' : '-') + self.sort.column); //服务端totals在查询数据时计算 self.model.totals(queryParam).$promise.then(function (ret) { self.page.totals = ret.totals; }); } else { if (self.rawData) self.rows = $filter('filter')(self.rawData, queryParam); } } function paging() { if (this.modelling) { this.query(); } } } GridDemoModelSerivce.$inject = ['Utils']; function GridDemoModelSerivce(Utils) { this.query = query; this.find = find; this.one = one; this.save = save; this.update = update; this.remove = remove; this._demoData_ = []; function query(refresh) { refresh = this._demoData_.length == 0 || refresh; if (refresh) { this._demoData_.length = 0; var MAX_NUM = 10 * 50; for (var i = 0; i < MAX_NUM; ++i) { var id = Utils.rand(0, MAX_NUM); this._demoData_.push({ id: i + 1, name: 'Name' + id, // 字符串类型 followers: Utils.rand(0, 100 * 1000 * 1000), // 数字类型 birthday: moment().subtract(Utils.rand(365, 365 * 50), 'day').toDate(), // 日期类型 summary: '这是一个测试' + i, income: Utils.rand(1000, 100000) // 金额类型 }); } } return this._demoData_; } function one(properties) { return _.findWhere(this._demoData_, properties); } function find(id) { return _.find(this._demoData_, function (item) { return item.id == id; }); } ///为了保证何$resource中的save功能一样此方法用于添加 function save(data) { //添加 this._demoData_.push(_.defaults(data, {})); //if (id != 'new') { // //修改 // var dest = _.bind(find, this, id); // _.extend(dest, data); //} //else { // //} } function update(id,data){ var dest = _.bind(find, this, id); _.extend(dest, data); } function remove(ids) { console.log(this._demoData_.length); this._demoData_ = _.reject(this._demoData_, function (item) { return _.contains(ids, item.id); }); console.log(this._demoData_.length); } } GridUtils.$inject = ['$filter','ViewUtils']; function GridUtils($filter,ViewUtils) { return { paging: paging, totals: totals, hide: hide, width: width, toggleOrderClass: toggleOrderClass, noResultsColspan: noResultsColspan, revertNumber: revertNumber, calcAge: calcAge, formatter: formatter, populateFilter: populateFilter, boolFilter: boolFilter, diFilter: diFilter, repeatInfoCombo: repeatInfoCombo, orFilter: orFilter }; function paging(items, vm) { if (!items) return []; if(vm.serverPaging){ //服务端分页 vm.paged = items; } else{ //客户端分页 var offset = (vm.page.no - 1) * vm.page.size; vm.paged = items.slice(offset, offset + vm.page.size); ////客户端totals在分页数据时计算 vm.page.totals = items.length;//客户端分页是立即触发结果 } return vm.paged; } function totals(items,filter,vm) { if (!items) return 0; if (vm.serverPaging) { //服务端分页 return vm.page.totals; } else { //客户端分页 return items.length || 0 } } function hide(column) { if (!column) return true; return column.hidden === true; } function width(column) { if (!column) return 0; return column.width || 100; } function toggleOrderClass(direction) { if (direction === -1) return "glyphicon-chevron-down"; else return "glyphicon-chevron-up"; } function noResultsColspan(vm) { if (!vm || !vm.columns) return 1; return 1 + vm.columns.length - _.where(vm.columns, {hidden: true}).length; } function revertNumber(num,notConvert) { if (num && !notConvert) { return -num; } return num; } function calcAge(rowValue) { return ViewUtils.age(rowValue) } function formatter(rowValue, columnName, columns) { var one = _.findWhere(columns, {name: columnName}); if(one && !one.hidden) { if (one.formatterData) { if(_.isArray(rowValue)){ return _.map(rowValue,function(o){ return one.formatterData[o]; }); } else{ return one.formatterData[rowValue]; } } } return rowValue; } function populateFilter(rowValue, key) { key = key || 'name'; if(_.isArray(rowValue)){ return _.map(rowValue,function(o){ console.log(o); return ViewUtils.getPropery(o, key); }); } else{ return ViewUtils.getPropery(o, key); } return rowValue; } function boolFilter(rowValue){ return {"1": "是", "0": "否", "true": "是", "false": "否"}[rowValue]; } function diFilter(rowValue,di) { if (_.isArray(rowValue)) { return _.map(rowValue, function (o) { return di[o] || (_.findWhere(di, {value: rowValue}) || {}).name; }); } else { return di[rowValue] || (_.findWhere(di, {value: rowValue}) || {}).name; } } function repeatInfoCombo(repeatValues, repeat_start) { if (_.isArray(repeatValues) && repeatValues.length > 0) { return _.map(repeatValues, function (r) { return r + repeat_start; }).join('\r\n'); } else { return repeat_start; } } /** * AngularJS default filter with the following expression: * "person in people | filter: {name: $select.search, age: $select.search}" * performs a AND between 'name: $select.search' and 'age: $select.search'. * We want to perform a OR. */ function orFilter(items, props) { var out = []; if (_.isArray(items)) { _.each(items,function (item) { var itemMatches = false; var keys = Object.keys(props); for (var i = 0; i < keys.length; i++) { var prop = keys[i]; var text = props[prop].toLowerCase(); if (item[prop].toString().toLowerCase().indexOf(text) !== -1) { itemMatches = true; break; } } if (itemMatches) { out.push(item); } }); } else { // Let the output be the input untouched out = items; } return out; }; } })();
Java
ForceTool ======= Allows administrators to force tool usage based on how they want it.
Java
package com.test.ipetrov.start; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.web.servlet.config.annotation.EnableWebMvc; @SpringBootApplication @EnableWebMvc @ComponentScan(basePackages = {"com.test.ipetrov.configuration", "com.test.ipetrov.portal"}) @EnableJpaRepositories(basePackages = "com.test.ipetrov") public class Application { public static void main(String[] args) { ApplicationContext context = SpringApplication.run(Application.class, args); } }
Java
import { Pipeline, Step } from '@ephox/agar'; import { Arr } from '@ephox/katamari'; import { LegacyUnit } from '@ephox/mcagar'; import Serializer from 'tinymce/core/api/dom/Serializer'; import DOMUtils from 'tinymce/core/api/dom/DOMUtils'; import TrimHtml from 'tinymce/core/dom/TrimHtml'; import ViewBlock from '../../module/test/ViewBlock'; import Zwsp from 'tinymce/core/text/Zwsp'; import { UnitTest } from '@ephox/bedrock'; declare const escape: any; UnitTest.asynctest('browser.tinymce.core.dom.SerializerTest', function () { const success = arguments[arguments.length - 2]; const failure = arguments[arguments.length - 1]; const suite = LegacyUnit.createSuite(); const DOM = DOMUtils.DOM; const viewBlock = ViewBlock(); const teardown = function () { viewBlock.update(''); }; const addTeardown = function (steps) { return Arr.bind(steps, function (step) { return [step, Step.sync(teardown)]; }); }; suite.test('Schema rules', function () { let ser = Serializer({ fix_list_elements : true }); ser.setRules('@[id|title|class|style],div,img[src|alt|-style|border],span,hr'); DOM.setHTML('test', '<img title="test" src="tinymce/ui/img/raster.gif" data-mce-src="tinymce/ui/img/raster.gif" alt="test" ' + 'border="0" style="border: 1px solid red" class="test" /><span id="test2">test</span><hr />'); LegacyUnit.equal( ser.serialize(DOM.get('test'), { getInner: true }), '<img title="test" class="test" src="tinymce/ui/img/raster.gif" ' + 'alt="test" border="0" /><span id="test2">test</span><hr />', 'Global rule' ); ser.setRules('*a[*],em/i[*],strong/b[*i*]'); DOM.setHTML('test', '<a href="test" data-mce-href="test">test</a><strong title="test" class="test">test2</strong><em title="test">test3</em>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<a href="test">test</a><strong title="test">test2</strong><em title="test">' + 'test3</em>', 'Wildcard rules'); ser.setRules('br,hr,input[type|name|value],div[id],span[id],strong/b,a,em/i,a[!href|!name],img[src|border=0|title={$uid}]'); DOM.setHTML('test', '<br /><hr /><input type="text" name="test" value="val" class="no" />' + '<span id="test2" class="no"><b class="no">abc</b><em class="no">123</em></span>123<a href="file.html" ' + 'data-mce-href="file.html">link</a><a name="anchor"></a><a>no</a><img src="tinymce/ui/img/raster.gif" ' + 'data-mce-src="tinymce/ui/img/raster.gif" />'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<div id="test"><br /><hr /><input type="text" name="test" value="val" />' + '<span id="test2"><strong>abc</strong><em>123</em></span>123<a href="file.html">link</a>' + '<a name="anchor"></a>no<img src="tinymce/ui/img/raster.gif" border="0" title="mce_0" /></div>', 'Output name and attribute rules'); ser.setRules('img[src|border=0|alt=]'); DOM.setHTML('test', '<img src="tinymce/ui/img/raster.gif" data-mce-src="tinymce/ui/img/raster.gif" border="0" alt="" />'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<img src="tinymce/ui/img/raster.gif" border="0" alt="" />', 'Default attribute with empty value'); ser.setRules('img[src|border=0|alt=],div[style|id],*[*]'); DOM.setHTML('test', '<img src="tinymce/ui/img/raster.gif" data-mce-src="tinymce/ui/img/raster.gif" /><hr />'); LegacyUnit.equal( ser.serialize(DOM.get('test'), { getInner: true }), '<img src="tinymce/ui/img/raster.gif" border="0" alt="" /><hr />' ); ser = Serializer({ valid_elements : 'img[src|border=0|alt=]', extended_valid_elements : 'div[id],img[src|alt=]' }); DOM.setHTML('test', '<img src="tinymce/ui/img/raster.gif" data-mce-src="tinymce/ui/img/raster.gif" alt="" />'); LegacyUnit.equal( ser.serialize(DOM.get('test')), '<div id="test"><img src="tinymce/ui/img/raster.gif" alt="" /></div>' ); ser = Serializer({ invalid_elements : 'hr,br' }); DOM.setHTML('test', '<img src="tinymce/ui/img/raster.gif" data-mce-src="tinymce/ui/img/raster.gif" /><hr /><br />'); LegacyUnit.equal( ser.serialize(DOM.get('test'), { getInner: true }), '<img src="tinymce/ui/img/raster.gif" />' ); }); suite.test('allow_unsafe_link_target (default)', function () { const ser = Serializer({ }); DOM.setHTML('test', '<a href="a" target="_blank">a</a><a href="b" target="_blank">b</a>'); LegacyUnit.equal( ser.serialize(DOM.get('test'), { getInner: true }), '<a href="a" target="_blank" rel="noopener">a</a><a href="b" target="_blank" rel="noopener">b</a>' ); DOM.setHTML('test', '<a href="a" rel="lightbox" target="_blank">a</a><a href="b" rel="lightbox" target="_blank">b</a>'); LegacyUnit.equal( ser.serialize(DOM.get('test'), { getInner: true }), '<a href="a" target="_blank" rel="lightbox noopener">a</a><a href="b" target="_blank" rel="lightbox noopener">b</a>' ); DOM.setHTML('test', '<a href="a" rel="lightbox x" target="_blank">a</a><a href="b" rel="lightbox x" target="_blank">b</a>'); LegacyUnit.equal( ser.serialize(DOM.get('test'), { getInner: true }), '<a href="a" target="_blank" rel="lightbox noopener x">a</a><a href="b" target="_blank" rel="lightbox noopener x">b</a>' ); DOM.setHTML('test', '<a href="a" rel="noopener a" target="_blank">a</a>'); LegacyUnit.equal( ser.serialize(DOM.get('test'), { getInner: true }), '<a href="a" target="_blank" rel="noopener a">a</a>' ); DOM.setHTML('test', '<a href="a" rel="a noopener b" target="_blank">a</a>'); LegacyUnit.equal( ser.serialize(DOM.get('test'), { getInner: true }), '<a href="a" target="_blank" rel="a noopener b">a</a>' ); }); suite.test('allow_unsafe_link_target (disabled)', function () { const ser = Serializer({ allow_unsafe_link_target: true }); DOM.setHTML('test', '<a href="a" target="_blank">a</a><a href="b" target="_blank">b</a>'); LegacyUnit.equal( ser.serialize(DOM.get('test'), { getInner: true }), '<a href="a" target="_blank">a</a><a href="b" target="_blank">b</a>' ); }); suite.test('format tree', function () { const ser = Serializer({ }); DOM.setHTML('test', 'a'); LegacyUnit.equal( ser.serialize(DOM.get('test'), { format: 'tree' }).name, 'body' ); }); suite.test('Entity encoding', function () { let ser; ser = Serializer({ entity_encoding : 'numeric' }); DOM.setHTML('test', '&lt;&gt;&amp;&quot;&nbsp;&aring;&auml;&ouml;'); LegacyUnit.equal(ser.serialize(DOM.get('test'), { getInner : true }), '&lt;&gt;&amp;"&#160;&#229;&#228;&#246;'); ser = Serializer({ entity_encoding : 'named' }); DOM.setHTML('test', '&lt;&gt;&amp;&quot;&nbsp;&aring;&auml;&ouml;'); LegacyUnit.equal(ser.serialize(DOM.get('test'), { getInner : true }), '&lt;&gt;&amp;"&nbsp;&aring;&auml;&ouml;'); ser = Serializer({ entity_encoding : 'named+numeric', entities : '160,nbsp,34,quot,38,amp,60,lt,62,gt' }); DOM.setHTML('test', '&lt;&gt;&amp;&quot;&nbsp;&aring;&auml;&ouml;'); LegacyUnit.equal(ser.serialize(DOM.get('test'), { getInner : true }), '&lt;&gt;&amp;"&nbsp;&#229;&#228;&#246;'); ser = Serializer({ entity_encoding : 'raw' }); DOM.setHTML('test', '&lt;&gt;&amp;&quot;&nbsp;&aring;&auml;&ouml;'); LegacyUnit.equal(ser.serialize(DOM.get('test'), { getInner : true }), '&lt;&gt;&amp;"\u00a0\u00e5\u00e4\u00f6'); }); suite.test('Form elements (general)', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules( 'form[method],label[for],input[type|name|value|checked|disabled|readonly|length|maxlength],select[multiple],' + 'option[value|selected],textarea[name|disabled|readonly]' ); DOM.setHTML('test', '<input type="text" />'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<input type="text" />'); DOM.setHTML('test', '<input type="text" value="text" length="128" maxlength="129" />'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<input type="text" value="text" length="128" maxlength="129" />'); DOM.setHTML('test', '<form method="post"><input type="hidden" name="method" value="get" /></form>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<form method="post"><input type="hidden" name="method" value="get" /></form>'); DOM.setHTML('test', '<label for="test">label</label>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<label for="test">label</label>'); DOM.setHTML('test', '<input type="checkbox" value="test" /><input type="button" /><textarea></textarea>'); // Edge will add an empty input value so remove that to normalize test since it doesn't break anything LegacyUnit.equal( ser.serialize(DOM.get('test')).replace(/ value=""/g, ''), '<input type="checkbox" value="test" /><input type="button" /><textarea></textarea>' ); }); suite.test('Form elements (checkbox)', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('form[method],label[for],input[type|name|value|checked|disabled|readonly|length|maxlength],select[multiple],option[value|selected]'); DOM.setHTML('test', '<input type="checkbox" value="1">'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<input type="checkbox" value="1" />'); DOM.setHTML('test', '<input type="checkbox" value="1" checked disabled readonly>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<input type="checkbox" value="1" checked="checked" disabled="disabled" readonly="readonly" />'); DOM.setHTML('test', '<input type="checkbox" value="1" checked="1" disabled="1" readonly="1">'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<input type="checkbox" value="1" checked="checked" disabled="disabled" readonly="readonly" />'); DOM.setHTML('test', '<input type="checkbox" value="1" checked="true" disabled="true" readonly="true">'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<input type="checkbox" value="1" checked="checked" disabled="disabled" readonly="readonly" />'); }); suite.test('Form elements (select)', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('form[method],label[for],input[type|name|value|checked|disabled|readonly|length|maxlength],select[multiple],option[value|selected]'); DOM.setHTML('test', '<select><option value="1">test1</option><option value="2" selected>test2</option></select>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<select><option value="1">test1</option><option value="2" selected="selected">test2</option></select>'); DOM.setHTML('test', '<select><option value="1">test1</option><option selected="1" value="2">test2</option></select>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<select><option value="1">test1</option><option value="2" selected="selected">test2</option></select>'); DOM.setHTML('test', '<select><option value="1">test1</option><option value="2" selected="true">test2</option></select>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<select><option value="1">test1</option><option value="2" selected="selected">test2</option></select>'); DOM.setHTML('test', '<select multiple></select>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<select multiple="multiple"></select>'); DOM.setHTML('test', '<select multiple="multiple"></select>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<select multiple="multiple"></select>'); DOM.setHTML('test', '<select multiple="1"></select>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<select multiple="multiple"></select>'); DOM.setHTML('test', '<select></select>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<select></select>'); }); suite.test('List elements', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('ul[compact],ol,li'); DOM.setHTML('test', '<ul compact></ul>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<ul compact="compact"></ul>'); DOM.setHTML('test', '<ul compact="compact"></ul>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<ul compact="compact"></ul>'); DOM.setHTML('test', '<ul compact="1"></ul>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<ul compact="compact"></ul>'); DOM.setHTML('test', '<ul></ul>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<ul></ul>'); DOM.setHTML('test', '<ol><li>a</li><ol><li>b</li><li>c</li></ol><li>e</li></ol>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<ol><li>a<ol><li>b</li><li>c</li></ol></li><li>e</li></ol>'); }); suite.test('Tables', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('table,tr,td[nowrap]'); DOM.setHTML('test', '<table><tr><td></td></tr></table>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<table><tr><td></td></tr></table>'); DOM.setHTML('test', '<table><tr><td nowrap></td></tr></table>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<table><tr><td nowrap="nowrap"></td></tr></table>'); DOM.setHTML('test', '<table><tr><td nowrap="nowrap"></td></tr></table>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<table><tr><td nowrap="nowrap"></td></tr></table>'); DOM.setHTML('test', '<table><tr><td nowrap="1"></td></tr></table>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<table><tr><td nowrap="nowrap"></td></tr></table>'); }); suite.test('Styles', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('*[*]'); DOM.setHTML('test', '<span style="border: 1px solid red" data-mce-style="border: 1px solid red;">test</span>'); LegacyUnit.equal(ser.serialize(DOM.get('test'), { getInner: true }), '<span style="border: 1px solid red;">test</span>'); }); suite.test('Comments', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('*[*]'); DOM.setHTML('test', '<!-- abc -->'); LegacyUnit.equal(ser.serialize(DOM.get('test'), { getInner: true }), '<!-- abc -->'); }); suite.test('Non HTML elements and attributes', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('*[*]'); ser.schema.addValidChildren('+div[prefix:test]'); DOM.setHTML('test', '<div test:attr="test">test</div>'); LegacyUnit.equal(ser.serialize(DOM.get('test'), { getInner : true }), '<div test:attr="test">test</div>'); DOM.setHTML('test', 'test1<prefix:test>Test</prefix:test>test2'); LegacyUnit.equal(ser.serialize(DOM.get('test'), { getInner: true }), 'test1<prefix:test>Test</prefix:test>test2'); }); suite.test('Padd empty elements', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('#p'); DOM.setHTML('test', '<p>test</p><p></p>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<p>test</p><p>&nbsp;</p>'); }); suite.test('Padd empty elements with BR', function () { const ser = Serializer({ padd_empty_with_br: true }); ser.setRules('#p,table,tr,#td,br'); DOM.setHTML('test', '<p>a</p><p></p>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<p>a</p><p><br /></p>'); DOM.setHTML('test', '<p>a</p><table><tr><td><br></td></tr></table>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<p>a</p><table><tr><td><br /></td></tr></table>'); }); suite.test('Do not padd empty elements with padded children', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('#p,#span,b'); DOM.setHTML('test', '<p><span></span></p><p><b><span></span></b></p>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<p><span>&nbsp;</span></p><p><b><span>&nbsp;</span></b></p>'); }); suite.test('Remove empty elements', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('-p'); DOM.setHTML('test', '<p>test</p><p></p>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<p>test</p>'); }); suite.test('Script with non JS type attribute', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<s' + 'cript type="mylanguage"></s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<s' + 'cript type="mylanguage"></s' + 'cript>'); }); suite.test('Script with tags inside a comment with element_format: xhtml', function () { const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<s' + 'cript>// <img src="test"><a href="#"></a></s' + 'cript>'); LegacyUnit.equal( ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<s' + 'cript>// <![CDATA[\n// <img src="test"><a href="#"></a>\n// ]]></s' + 'cript>' ); }); suite.test('Script with tags inside a comment', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<s' + 'cript>// <img src="test"><a href="#"></a></s' + 'cript>'); LegacyUnit.equal( ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<s' + 'cript>// <img src="test"><a href="#"></a></s' + 'cript>' ); }); suite.test('Script with less than with element_format: xhtml', function () { const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<s' + 'cript>1 < 2;</s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<s' + 'cript>// <![CDATA[\n1 < 2;\n// ]]></s' + 'cript>'); }); suite.test('Script with less than', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<s' + 'cript>1 < 2;</s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<s' + 'cript>1 < 2;</s' + 'cript>'); }); suite.test('Script with type attrib and less than with element_format: xhtml', function () { const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<s' + 'cript type="text/javascript">1 < 2;</s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<script type="text/javascript">// <![CDATA[\n1 < 2;\n// ]]></s' + 'cript>'); }); suite.test('Script with type attrib and less than', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<s' + 'cript type="text/javascript">1 < 2;</s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<script type=\"text/javascript\">1 < 2;</script>'); }); suite.test('Script with whitespace in beginning/end with element_format: xhtml', function () { const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script>\n\t1 < 2;\n\t if (2 < 1)\n\t\talert(1);\n</s' + 'cript>'); LegacyUnit.equal( ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<s' + 'cript>// <![CDATA[\n\t1 < 2;\n\t if (2 < 1)\n\t\talert(1);\n// ]]></s' + 'cript>' ); }); suite.test('Script with whitespace in beginning/end', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script>\n\t1 < 2;\n\t if (2 < 1)\n\t\talert(1);\n</s' + 'cript>'); LegacyUnit.equal( ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<script>\n\t1 < 2;\n\t if (2 < 1)\n\t\talert(1);\n</script>' ); }); suite.test('Script with a HTML comment and less than with element_format: xhtml', function () { const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script><!-- 1 < 2; // --></s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<s' + 'cript>// <![CDATA[\n1 < 2;\n// ]]></s' + 'cript>'); }); suite.test('Script with a HTML comment and less than', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script><!-- 1 < 2; // --></s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<script><!-- 1 < 2; // --></script>'); }); suite.test('Script with white space in beginning, comment and less than with element_format: xhtml', function () { const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script>\n\n<!-- 1 < 2;\n\n--></s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<s' + 'cript>// <![CDATA[\n1 < 2;\n// ]]></s' + 'cript>'); }); suite.test('Script with white space in beginning, comment and less than', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script>\n\n<!-- 1 < 2;\n\n--></s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<script>\n\n<!-- 1 < 2;\n\n--></script>'); }); suite.test('Script with comments and cdata with element_format: xhtml', function () { const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script>// <![CDATA[1 < 2; // ]]></s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<s' + 'cript>// <![CDATA[\n1 < 2;\n// ]]></s' + 'cript>'); }); suite.test('Script with comments and cdata', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script>// <![CDATA[1 < 2; // ]]></s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<script>// <![CDATA[1 < 2; // ]]></script>'); }); suite.test('Script with cdata with element_format: xhtml', function () { const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script><![CDATA[1 < 2; ]]></s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<s' + 'cript>// <![CDATA[\n1 < 2;\n// ]]></s' + 'cript>'); }); suite.test('Script with cdata', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script><![CDATA[1 < 2; ]]></s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<script><![CDATA[1 < 2; ]]></script>'); }); suite.test('Script whitespace in beginning/end and cdata with element_format: xhtml', function () { const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script>\n\n<![CDATA[\n\n1 < 2;\n\n]]>\n\n</s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<s' + 'cript>// <![CDATA[\n1 < 2;\n// ]]></s' + 'cript>'); }); suite.test('Script whitespace in beginning/end and cdata', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script>\n\n<![CDATA[\n\n1 < 2;\n\n]]>\n\n</s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<script>\n\n<![CDATA[\n\n1 < 2;\n\n]]>\n\n</script>'); }); suite.test('Whitespace preserve in pre', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('pre'); DOM.setHTML('test', '<pre> </pre>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<pre> </pre>'); }); suite.test('Script with src attr', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script src="test.js" data-mce-src="test.js"></s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<s' + 'cript src="test.js"></s' + 'cript>'); }); suite.test('Script with HTML comment, comment and CDATA with element_format: xhtml', function () { const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script><!--// <![CDATA[var hi = "hello";// ]]>--></s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<script>// <![CDATA[\nvar hi = \"hello\";\n// ]]></s' + 'cript>'); }); suite.test('Script with HTML comment, comment and CDATA', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script><!--// <![CDATA[var hi = "hello";// ]]>--></s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<script><!--// <![CDATA[var hi = \"hello\";// ]]>--></script>'); }); suite.test('Script with block comment around cdata with element_format: xhtml', function () { const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script>/* <![CDATA[ */\nvar hi = "hello";\n/* ]]> */</s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<script>// <![CDATA[\nvar hi = \"hello\";\n// ]]></s' + 'cript>'); }); suite.test('Script with block comment around cdata', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script>/* <![CDATA[ */\nvar hi = "hello";\n/* ]]> */</s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<script>/* <![CDATA[ */\nvar hi = \"hello\";\n/* ]]> */</script>'); }); suite.test('Script with html comment and block comment around cdata with element_format: xhtml', function () { const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script><!-- /* <![CDATA[ */\nvar hi = "hello";\n/* ]]>*/--></s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<script>// <![CDATA[\nvar hi = \"hello\";\n// ]]></s' + 'cript>'); }); suite.test('Script with html comment and block comment around cdata', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script><!-- /* <![CDATA[ */\nvar hi = "hello";\n/* ]]>*/--></s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<script><!-- /* <![CDATA[ */\nvar hi = \"hello\";\n/* ]]>*/--></script>'); }); suite.test('Script with line comment and html comment with element_format: xhtml', function () { const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script>// <!--\nvar hi = "hello";\n// --></s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<script>// <![CDATA[\nvar hi = \"hello\";\n// ]]></s' + 'cript>'); }); suite.test('Script with line comment and html comment', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script>// <!--\nvar hi = "hello";\n// --></s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<script>// <!--\nvar hi = \"hello\";\n// --></script>'); }); suite.test('Script with block comment around html comment with element_format: xhtml', function () { const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script>/* <!-- */\nvar hi = "hello";\n/*-->*/</s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<script>// <![CDATA[\nvar hi = \"hello\";\n// ]]></s' + 'cript>'); }); suite.test('Script with block comment around html comment', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script>/* <!-- */\nvar hi = "hello";\n/*-->*/</s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<script>/* <!-- */\nvar hi = \"hello\";\n/*-->*/</script>'); }); suite.test('Protected blocks', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('noscript[test]'); DOM.setHTML('test', '<!--mce:protected ' + escape('<noscript test="test"><br></noscript>') + '-->'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<noscript test="test"><br></noscript>'); DOM.setHTML('test', '<!--mce:protected ' + escape('<noscript><br></noscript>') + '-->'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<noscript><br></noscript>'); DOM.setHTML('test', '<!--mce:protected ' + escape('<noscript><!-- text --><br></noscript>') + '-->'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<noscript><!-- text --><br></noscript>'); }); suite.test('Style with whitespace at beginning with element_format: xhtml', function () { const ser = Serializer({ fix_list_elements : true, valid_children: '+body[style]', element_format: 'xhtml' }); ser.setRules('style'); DOM.setHTML('test', '<style> body { background:#fff }</style>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<style><!--\n body { background:#fff }\n--></style>'); }); suite.test('Style with whitespace at beginning', function () { const ser = Serializer({ fix_list_elements : true, valid_children: '+body[style]' }); ser.setRules('style'); DOM.setHTML('test', '<style> body { background:#fff }</style>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<style> body { background:#fff }</style>'); }); suite.test('Style with cdata with element_format: xhtml', function () { const ser = Serializer({ fix_list_elements : true, valid_children: '+body[style]', element_format: 'xhtml' }); ser.setRules('style'); DOM.setHTML('test', '<style>\r\n<![CDATA[\r\n body { background:#fff }]]></style>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<style><!--\nbody { background:#fff }\n--></style>'); }); suite.test('Style with cdata', function () { const ser = Serializer({ fix_list_elements : true, valid_children: '+body[style]' }); ser.setRules('style'); DOM.setHTML('test', '<style>\r\n<![CDATA[\r\n body { background:#fff }]]></style>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<style>\n<![CDATA[\n body { background:#fff }]]></style>'); }); suite.test('CDATA', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('span'); DOM.setHTML('test', '123<!--[CDATA[<test>]]-->abc'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '123<![CDATA[<test>]]>abc'); DOM.setHTML('test', '123<!--[CDATA[<te\n\nst>]]-->abc'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '123<![CDATA[<te\n\nst>]]>abc'); }); suite.test('BR at end of blocks', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('ul,li,br'); DOM.setHTML('test', '<ul><li>test<br /></li><li>test<br /></li><li>test<br /></li></ul>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<ul><li>test</li><li>test</li><li>test</li></ul>'); }); suite.test('Map elements', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('map[id|name],area[shape|coords|href|target|alt]'); DOM.setHTML( 'test', '<map id="planetmap" name="planetmap"><area shape="rect" coords="0,0,82,126" href="sun.htm" data-mce-href="sun.htm" target="_blank" alt="sun" /></map>' ); LegacyUnit.equal( ser.serialize(DOM.get('test')).toLowerCase(), '<map id="planetmap" name="planetmap"><area shape="rect" coords="0,0,82,126" href="sun.htm" target="_blank" alt="sun" /></map>' ); }); suite.test('Custom elements', function () { const ser = Serializer({ custom_elements: 'custom1,~custom2', valid_elements: 'custom1,custom2' }); document.createElement('custom1'); document.createElement('custom2'); DOM.setHTML('test', '<p><custom1>c1</custom1><custom2>c2</custom2></p>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<custom1>c1</custom1><custom2>c2</custom2>'); }); suite.test('Remove internal classes', function () { const ser = Serializer({ valid_elements: 'span[class]' }); DOM.setHTML('test', '<span class="a mce-item-X mce-item-selected b"></span>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<span class="a b"></span>'); DOM.setHTML('test', '<span class="a mce-item-X"></span>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<span class="a"></span>'); DOM.setHTML('test', '<span class="mce-item-X"></span>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<span></span>'); DOM.setHTML('test', '<span class="mce-item-X b"></span>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<span class=" b"></span>'); DOM.setHTML('test', '<span class="b mce-item-X"></span>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<span class="b"></span>'); }); suite.test('Restore tabindex', function () { const ser = Serializer({ valid_elements: 'span[tabindex]' }); DOM.setHTML('test', '<span data-mce-tabindex="42"></span>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<span tabindex="42"></span>'); }); suite.test('Trailing BR (IE11)', function () { const ser = Serializer({ valid_elements: 'p,br' }); DOM.setHTML('test', '<p>a</p><br><br>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<p>a</p>'); DOM.setHTML('test', 'a<br><br>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), 'a'); }); suite.test('addTempAttr', function () { const ser = Serializer({}); ser.addTempAttr('data-x'); ser.addTempAttr('data-y'); DOM.setHTML('test', '<p data-x="1" data-y="2" data-z="3">a</p>'); LegacyUnit.equal(ser.serialize(DOM.get('test'), { getInner: 1 }), '<p data-z="3">a</p>'); LegacyUnit.equal(TrimHtml.trimExternal(ser, '<p data-x="1" data-y="2" data-z="3">a</p>'), '<p data-z="3">a</p>'); }); suite.test('addTempAttr same attr twice', function () { const ser1 = Serializer({}); const ser2 = Serializer({}); ser1.addTempAttr('data-x'); ser2.addTempAttr('data-x'); DOM.setHTML('test', '<p data-x="1" data-z="3">a</p>'); LegacyUnit.equal(ser1.serialize(DOM.get('test'), { getInner: 1 }), '<p data-z="3">a</p>'); LegacyUnit.equal(TrimHtml.trimExternal(ser1, '<p data-x="1" data-z="3">a</p>'), '<p data-z="3">a</p>'); LegacyUnit.equal(ser2.serialize(DOM.get('test'), { getInner: 1 }), '<p data-z="3">a</p>'); LegacyUnit.equal(TrimHtml.trimExternal(ser2, '<p data-x="1" data-z="3">a</p>'), '<p data-z="3">a</p>'); }); suite.test('trim data-mce-bougs="all"', function () { const ser = Serializer({}); DOM.setHTML('test', 'a<p data-mce-bogus="all">b</p>c'); LegacyUnit.equal(ser.serialize(DOM.get('test'), { getInner: 1 }), 'ac'); LegacyUnit.equal(TrimHtml.trimExternal(ser, 'a<p data-mce-bogus="all">b</p>c'), 'ac'); }); suite.test('zwsp should not be treated as contents', function () { const ser = Serializer({ }); DOM.setHTML('test', '<p>' + Zwsp.ZWSP + '</p>'); LegacyUnit.equal( ser.serialize(DOM.get('test'), { getInner: true }), '<p>&nbsp;</p>' ); }); viewBlock.attach(); viewBlock.get().id = 'test'; Pipeline.async({}, addTeardown(suite.toSteps({})), function () { viewBlock.detach(); success(); }, failure); });
Java
<?php /** * Core Class To Style RAD Builder Components * @author Abhin Sharma * @dependency none * @since IOA Framework V1 */ if(!class_exists('RADStyler')) { class RADStyler { function registerbgColor($key='' ,$target='') { $code ='<h5 class="sub-styler-title">'.__('Set Background Color','ioa').'<i class="angle-downicon- ioa-front-icon"></i></h5><div class="sub-styler-section clearfix">'; $code .= getIOAInput(array( "label" => __("Background Color",'ioa') , "name" => $key."_bg_color" , "default" => "" , "type" => "colorpicker", "description" => "", "length" => 'small', "value" => "" , "data" => array( "target" => $target , "property" => "background-color" ) )); return $code.'</div>'; } function registerBorder($key='' ,$target='') { $code ='<h5 class="sub-styler-title">'.__('Set Border','ioa').'<i class="angle-downicon- ioa-front-icon"></i></h5><div class="sub-styler-section clearfix">'; $code .= getIOAInput(array( "label" => __("Top Border Color",'ioa') , "name" => $key."_tbr_color" , "default" => "" , "type" => "colorpicker", "description" => "", "length" => 'small', "value" => "" , "data" => array( "target" => $target , "property" => "border-top-color" ) )); $code .= getIOAInput(array( "label" => __("Top Border Size(ex : 1px)",'ioa') , "name" => $key."_tbr_width" , "default" => "" , "type" => "text", "description" => "", "length" => 'small', "class" => ' rad_style_property ', "value" => "0px" , "data" => array( "target" => $target , "property" => "border-top-width" ) )); $code .= getIOAInput(array( "label" => __("Bottom Border Color",'ioa') , "name" => $key."_bbr_color" , "default" => "" , "type" => "colorpicker", "description" => "", "length" => 'small', "value" => "" , "data" => array( "target" => $target , "property" => "border-bottom-color" ) )); $code .= getIOAInput(array( "label" => __("Bottom Border Size(ex : 1px)",'ioa') , "name" => $key."_bbr_width" , "default" => "" , "type" => "text", "description" => "", "length" => 'small', "class" => ' rad_style_property ', "value" => "0px" , "data" => array( "target" => $target , "property" => "border-bottom-width" ) )); return $code.'</div>'; } function registerbgImage($key ,$target) { $code ='<h5 class="sub-styler-title">'.__('Set Background Image','ioa').'<i class="angle-downicon- ioa-front-icon"></i></h5><div class="sub-styler-section clearfix">'; $code .= getIOAInput(array( "label" => __("Add Background Image",'ioa') , "name" => $key."_bg_image" , "default" => "" , "type" => "upload", "description" => "" , "length" => 'small' , "title" => __("Use as Background Image",'ioa'), "std" => "", "button" => __("Add Image",'ioa'), "class" => ' rad_style_property ', "data" => array( "target" => $target , "property" => "background-image" ) ) ); $code .= getIOAInput(array( "label" => __("Background Position",'ioa') , "name" => $key."_bgposition" , "default" => "top left" , "type" => "select", "class" => ' rad_style_property ', "description" => "" , "length" => 'medium' , "options" => array("top left","top right","bottom left","bottom right","center top","center center","center bottom","center left","center right"), "data" => array( "target" => $target , "property" => "background-position" ) ) ); $code .= getIOAInput(array( "label" => __("Background Cover",'ioa') , "name" => $key."_bgcover" , "default" => "auto" , "type" => "select", "class" => ' rad_style_property ', "description" => "" , "length" => 'medium' , "options" => array("auto","contain","cover"), "data" => array( "target" => $target , "property" => "background-size" ) ) ); $code .= getIOAInput(array( "label" => __("Background Repeat",'ioa') , "name" => $key."_bgrepeat" , "default" => "repeat" , "type" => "select", "description" => "" , "length" => 'medium' , "options" => array("repeat","repeat-x","repeat-y","no-repeat"), "class" => ' rad_style_property ', "data" => array( "target" => $target , "property" => "background-repeat" ) ) ); $code .= getIOAInput(array( "label" => __("Background Scroll",'ioa') , "name" => $key."_bgscroll" , "default" => "" , "type" => "select", "description" => "" , "length" => 'medium' , "options" => array("scroll","fixed"), "class" => ' rad_style_property ', "data" => array( "target" => $target , "property" => "background-attachment" ) ) ); return $code.'</div>'; } function registerbgGradient($key ,$target) { $code ='<h5 class="sub-styler-title">'.__('Set Background Gradient','ioa').'<i class="angle-downicon- ioa-front-icon"></i></h5><div class="sub-styler-section clearfix"><a class="set-rad-gradient button-default" href="">'.__('Apply','ioa').'</a> '; $code .= getIOAInput(array( "label" => __("Use Background Gradient",'ioa') , "name" => $key."_gradient_dir" , "default" => "no" , "type" => "select", "description" => "" , "length" => 'small' , "options" => array("horizontal" => __("Horizontal",'ioa'),"vertical"=> __("Vertical",'ioa'),"diagonaltl" => __("Diagonal Top Left",'ioa'),"diagonalbr" => __("Diagonal Bottom Right",'ioa') ), "class" => ' hasGradient dir ', "data" => array( "target" => $target , "property" => "removable" ) ) ); $code .= getIOAInput(array( "label" => __("Select Start Background Color for title area",'ioa') , "name" => $key."_grstart" , "default" => " << " , "type" => "colorpicker", "description" => " " , "length" => 'small' , "alpha" => false, "class" => ' hasGradient grstart no_listen ', "data" => array( "target" => $target , "property" => "background-image" ) ) ); $code .= getIOAInput(array( "label" => __("Select Start Background Color for title area",'ioa') , "name" => $key."_grend" , "default" => " << " , "type" => "colorpicker", "description" => " " , "length" => 'small' , "alpha" => false, "class" => ' hasGradient grend no_listen ', "data" => array( "target" => $target , "property" => "background-image" ) ) ); return $code.'</div>'; } } }
Java
--- title: '1º Aberto Gaúcho de Super Smash Bros. - Wii U Singles, Doubles e Crews! (22/07 e 23/07)' date: 2016-04-21 18:17:00 author: 'DASH|Vinikun' image: 'http://i.imgur.com/7w6udGs.jpg' ---
Java
#if defined (_MSC_VER) && !defined (_WIN64) #pragma warning(disable:4244) // boost::number_distance::distance() // converts 64 to 32 bits integers #endif #include <CGAL/Exact_predicates_inexact_constructions_kernel.h> #include <CGAL/IO/read_xyz_points.h> #include <CGAL/Point_with_normal_3.h> #include <CGAL/property_map.h> #include <CGAL/Shape_detection_3.h> #include <CGAL/Timer.h> #include <iostream> #include <fstream> // Type declarations typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel; typedef std::pair<Kernel::Point_3, Kernel::Vector_3> Point_with_normal; typedef std::vector<Point_with_normal> Pwn_vector; typedef CGAL::First_of_pair_property_map<Point_with_normal> Point_map; typedef CGAL::Second_of_pair_property_map<Point_with_normal> Normal_map; // In Shape_detection_traits the basic types, i.e., Point and Vector types // as well as iterator type and property maps, are defined. typedef CGAL::Shape_detection_3::Shape_detection_traits <Kernel, Pwn_vector, Point_map, Normal_map> Traits; typedef CGAL::Shape_detection_3::Efficient_RANSAC<Traits> Efficient_ransac; typedef CGAL::Shape_detection_3::Region_growing<Traits> Region_growing; typedef CGAL::Shape_detection_3::Plane<Traits> Plane; struct Timeout_callback { mutable int nb; mutable CGAL::Timer timer; const double limit; Timeout_callback(double limit) : nb(0), limit(limit) { timer.start(); } bool operator()(double advancement) const { // Avoid calling time() at every single iteration, which could // impact performances very badly ++ nb; if (nb % 1000 != 0) return true; // If the limit is reach, interrupt the algorithm if (timer.time() > limit) { std::cerr << "Algorithm takes too long, exiting (" << 100. * advancement << "% done)" << std::endl; return false; } return true; } }; // This program both works for RANSAC and Region Growing template <typename ShapeDetection> int run(const char* filename) { Pwn_vector points; std::ifstream stream(filename); if (!stream || !CGAL::read_xyz_points(stream, std::back_inserter(points), CGAL::parameters::point_map(Point_map()). normal_map(Normal_map()))) { std::cerr << "Error: cannot read file cube.pwn" << std::endl; return EXIT_FAILURE; } ShapeDetection shape_detection; shape_detection.set_input(points); shape_detection.template add_shape_factory<Plane>(); // Create callback that interrupts the algorithm if it takes more than half a second Timeout_callback timeout_callback(0.5); // Detects registered shapes with default parameters. shape_detection.detect(typename ShapeDetection::Parameters(), timeout_callback); return EXIT_SUCCESS; } int main (int argc, char** argv) { if (argc > 1 && std::string(argv[1]) == "-r") { std::cout << "Efficient RANSAC" << std::endl; return run<Efficient_ransac> ((argc > 2) ? argv[2] : "data/cube.pwn"); } std::cout << "Region Growing" << std::endl; return run<Region_growing> ((argc > 1) ? argv[1] : "data/cube.pwn"); }
Java
public class Rectangulo { public int Base; public int Altura; //Ejercicio realizado con ayuda de esta pagina:http://diagramas-de-flujo.blogspot.com/2013/02/calcular-perimetro-rectangulo-Java.html //aqui llamamos las dos variables que utilizaremos. Rectangulo(int Base, int Altura) { this.Base = Base; this.Altura = Altura; } //COmo pueden observar aqui se obtiene la base y se asigna el valor de la base. int getBase () { return Base; } //aqui devolvemos ese valor void setBase (int Base) { this.Base = Base; } //aqui de igual forma se obtiene la altura y se le asigna el valor int getAltura () { return Altura; } //aqui devuelve el valor de la altura void setAltura (int Altura) { this.Altura = Altura; } //aqui con una formula matematica se obtiene el perimetro hacemos una suma y una multiplicacion int getPerimetro() { return 2*(Base+Altura); } //aqui solo se hace un calculo matematico como la multiplicacion int getArea() { return Base*Altura; } }
Java
/* * This file is part of "U Turismu" project. * * U Turismu is an enterprise application in support of calabrian tour operators. * This system aims to promote tourist services provided by the operators * and to develop and improve tourism in Calabria. * * Copyright (C) 2012 "LagrecaSpaccarotella" team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uturismu.dao; import uturismu.dto.Booking; /** * @author "LagrecaSpaccarotella" team. * */ public interface BookingDao extends GenericDao<Booking> { }
Java
/** * Module dependencies. */ var express = require('express') , http = require('http') , path = require('path') , mongo = require('mongodb') , format = require('util').format; var app = express(); // all environments app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); // development only if ('development' == app.get('env')) { app.use(express.errorHandler()); } var server = new mongo.Server("localhost", 27017, {auto_reconnect: true}); var dbManager = new mongo.Db("applique-web", server, {safe:true}); dbManager.open(function(err, db) { require('./routes/index')(app, db); app.listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); }); });
Java
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2016 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "cmdlineparser.h" #include "cppcheck.h" #include "cppcheckexecutor.h" #include "filelister.h" #include "path.h" #include "settings.h" #include "timer.h" #include "check.h" #include "threadexecutor.h" // Threading model #include <algorithm> #include <iostream> #include <sstream> #include <fstream> #include <string> #include <cstring> #include <cstdlib> // EXIT_FAILURE #ifdef HAVE_RULES // xml is used for rules #include <tinyxml2.h> #endif static void AddFilesToList(const std::string& FileList, std::vector<std::string>& PathNames) { // To keep things initially simple, if the file can't be opened, just be silent and move on. std::istream *Files; std::ifstream Infile; if (FileList.compare("-") == 0) { // read from stdin Files = &std::cin; } else { Infile.open(FileList.c_str()); Files = &Infile; } if (Files && *Files) { std::string FileName; while (std::getline(*Files, FileName)) { // next line if (!FileName.empty()) { PathNames.push_back(FileName); } } } } static void AddInclPathsToList(const std::string& FileList, std::list<std::string>* PathNames) { // To keep things initially simple, if the file can't be opened, just be silent and move on. std::ifstream Files(FileList.c_str()); if (Files) { std::string PathName; while (std::getline(Files, PathName)) { // next line if (!PathName.empty()) { PathName = Path::removeQuotationMarks(PathName); PathName = Path::fromNativeSeparators(PathName); // If path doesn't end with / or \, add it #if GCC_VERSION >= 40600 if (PathName.back() != '/') #else if (PathName[PathName.size() - 1] != '/') #endif PathName += '/'; PathNames->push_back(PathName); } } } } static void AddPathsToSet(const std::string& FileName, std::set<std::string>* set) { std::list<std::string> templist; AddInclPathsToList(FileName, &templist); set->insert(templist.begin(), templist.end()); } CmdLineParser::CmdLineParser(Settings *settings) : _settings(settings) , _showHelp(false) , _showVersion(false) , _showErrorMessages(false) , _exitAfterPrint(false) { } void CmdLineParser::PrintMessage(const std::string &message) { std::cout << message << std::endl; } void CmdLineParser::PrintMessage(const char* message) { std::cout << message << std::endl; } bool CmdLineParser::ParseFromArgs(int argc, const char* const argv[]) { bool def = false; bool maxconfigs = false; for (int i = 1; i < argc; i++) { if (argv[i][0] == '-') { if (std::strcmp(argv[i], "--version") == 0) { _showVersion = true; _exitAfterPrint = true; return true; } // Flag used for various purposes during debugging else if (std::strcmp(argv[i], "--debug") == 0) _settings->debug = _settings->debugwarnings = true; // Show --debug output after the first simplifications else if (std::strcmp(argv[i], "--debug-normal") == 0) _settings->debugnormal = true; // Show debug warnings else if (std::strcmp(argv[i], "--debug-warnings") == 0) _settings->debugwarnings = true; // dump cppcheck data else if (std::strcmp(argv[i], "--dump") == 0) _settings->dump = true; // (Experimental) exception handling inside cppcheck client else if (std::strcmp(argv[i], "--exception-handling") == 0) _settings->exceptionHandling = true; else if (std::strncmp(argv[i], "--exception-handling=", 21) == 0) { _settings->exceptionHandling = true; const std::string exceptionOutfilename = &(argv[i][21]); CppCheckExecutor::setExceptionOutput((exceptionOutfilename=="stderr") ? stderr : stdout); } // Inconclusive checking else if (std::strcmp(argv[i], "--inconclusive") == 0) _settings->inconclusive = true; // Enforce language (--language=, -x) else if (std::strncmp(argv[i], "--language=", 11) == 0 || std::strcmp(argv[i], "-x") == 0) { std::string str; if (argv[i][2]) { str = argv[i]+11; } else { i++; if (i >= argc || argv[i][0] == '-') { PrintMessage("cppcheck: No language given to '-x' option."); return false; } str = argv[i]; } if (str == "c") _settings->enforcedLang = Settings::C; else if (str == "c++") _settings->enforcedLang = Settings::CPP; else { PrintMessage("cppcheck: Unknown language '" + str + "' enforced."); return false; } } // Filter errors else if (std::strncmp(argv[i], "--exitcode-suppressions=", 24) == 0) { // exitcode-suppressions=filename.txt std::string filename = 24 + argv[i]; std::ifstream f(filename.c_str()); if (!f.is_open()) { PrintMessage("cppcheck: Couldn't open the file: \"" + filename + "\"."); return false; } const std::string errmsg(_settings->nofail.parseFile(f)); if (!errmsg.empty()) { PrintMessage(errmsg); return false; } } // Filter errors else if (std::strncmp(argv[i], "--suppressions-list=", 20) == 0) { std::string filename = argv[i]+20; std::ifstream f(filename.c_str()); if (!f.is_open()) { std::string message("cppcheck: Couldn't open the file: \""); message += filename; message += "\"."; if (std::count(filename.begin(), filename.end(), ',') > 0 || std::count(filename.begin(), filename.end(), '.') > 1) { // If user tried to pass multiple files (we can only guess that) // e.g. like this: --suppressions-list=a.txt,b.txt // print more detailed error message to tell user how he can solve the problem message += "\nIf you want to pass two files, you can do it e.g. like this:"; message += "\n cppcheck --suppressions-list=a.txt --suppressions-list=b.txt file.cpp"; } PrintMessage(message); return false; } const std::string errmsg(_settings->nomsg.parseFile(f)); if (!errmsg.empty()) { PrintMessage(errmsg); return false; } } else if (std::strncmp(argv[i], "--suppress=", 11) == 0) { std::string suppression = argv[i]+11; const std::string errmsg(_settings->nomsg.addSuppressionLine(suppression)); if (!errmsg.empty()) { PrintMessage(errmsg); return false; } } // Enables inline suppressions. else if (std::strcmp(argv[i], "--inline-suppr") == 0) _settings->inlineSuppressions = true; // Verbose error messages (configuration info) else if (std::strcmp(argv[i], "-v") == 0 || std::strcmp(argv[i], "--verbose") == 0) _settings->verbose = true; // Force checking of files that have "too many" configurations else if (std::strcmp(argv[i], "-f") == 0 || std::strcmp(argv[i], "--force") == 0) _settings->force = true; // Output relative paths else if (std::strcmp(argv[i], "-rp") == 0 || std::strcmp(argv[i], "--relative-paths") == 0) _settings->relativePaths = true; else if (std::strncmp(argv[i], "-rp=", 4) == 0 || std::strncmp(argv[i], "--relative-paths=", 17) == 0) { _settings->relativePaths = true; if (argv[i][argv[i][3]=='='?4:17] != 0) { std::string paths = argv[i]+(argv[i][3]=='='?4:17); for (;;) { std::string::size_type pos = paths.find(';'); if (pos == std::string::npos) { _settings->basePaths.push_back(Path::fromNativeSeparators(paths)); break; } else { _settings->basePaths.push_back(Path::fromNativeSeparators(paths.substr(0, pos))); paths.erase(0, pos + 1); } } } else { PrintMessage("cppcheck: No paths specified for the '" + std::string(argv[i]) + "' option."); return false; } } // Write results in results.xml else if (std::strcmp(argv[i], "--xml") == 0) _settings->xml = true; // Define the XML file version (and enable XML output) else if (std::strncmp(argv[i], "--xml-version=", 14) == 0) { std::string numberString(argv[i]+14); std::istringstream iss(numberString); if (!(iss >> _settings->xml_version)) { PrintMessage("cppcheck: argument to '--xml-version' is not a number."); return false; } if (_settings->xml_version < 0 || _settings->xml_version > 2) { // We only have xml versions 1 and 2 PrintMessage("cppcheck: '--xml-version' can only be 1 or 2."); return false; } // Enable also XML if version is set _settings->xml = true; } // Only print something when there are errors else if (std::strcmp(argv[i], "-q") == 0 || std::strcmp(argv[i], "--quiet") == 0) _settings->quiet = true; // Append user-defined code to checked source code else if (std::strncmp(argv[i], "--append=", 9) == 0) { const std::string filename = 9 + argv[i]; if (!_settings->append(filename)) { PrintMessage("cppcheck: Couldn't open the file: \"" + filename + "\"."); return false; } } // Check configuration else if (std::strcmp(argv[i], "--check-config") == 0) { _settings->checkConfiguration = true; } // Check library definitions else if (std::strcmp(argv[i], "--check-library") == 0) { _settings->checkLibrary = true; } else if (std::strncmp(argv[i], "--enable=", 9) == 0) { const std::string errmsg = _settings->addEnabled(argv[i] + 9); if (!errmsg.empty()) { PrintMessage(errmsg); return false; } // when "style" is enabled, also enable "warning", "performance" and "portability" if (_settings->isEnabled("style")) { _settings->addEnabled("warning"); _settings->addEnabled("performance"); _settings->addEnabled("portability"); } } // --error-exitcode=1 else if (std::strncmp(argv[i], "--error-exitcode=", 17) == 0) { std::string temp = argv[i]+17; std::istringstream iss(temp); if (!(iss >> _settings->exitCode)) { _settings->exitCode = 0; PrintMessage("cppcheck: Argument must be an integer. Try something like '--error-exitcode=1'."); return false; } } // User define else if (std::strncmp(argv[i], "-D", 2) == 0) { std::string define; // "-D define" if (std::strcmp(argv[i], "-D") == 0) { ++i; if (i >= argc || argv[i][0] == '-') { PrintMessage("cppcheck: argument to '-D' is missing."); return false; } define = argv[i]; } // "-Ddefine" else { define = 2 + argv[i]; } // No "=", append a "=1" if (define.find('=') == std::string::npos) define += "=1"; if (!_settings->userDefines.empty()) _settings->userDefines += ";"; _settings->userDefines += define; def = true; } // User undef else if (std::strncmp(argv[i], "-U", 2) == 0) { std::string undef; // "-U undef" if (std::strcmp(argv[i], "-U") == 0) { ++i; if (i >= argc || argv[i][0] == '-') { PrintMessage("cppcheck: argument to '-U' is missing."); return false; } undef = argv[i]; } // "-Uundef" else { undef = 2 + argv[i]; } _settings->userUndefs.insert(undef); } // -E else if (std::strcmp(argv[i], "-E") == 0) { _settings->preprocessOnly = true; } // Include paths else if (std::strncmp(argv[i], "-I", 2) == 0) { std::string path; // "-I path/" if (std::strcmp(argv[i], "-I") == 0) { ++i; if (i >= argc || argv[i][0] == '-') { PrintMessage("cppcheck: argument to '-I' is missing."); return false; } path = argv[i]; } // "-Ipath/" else { path = 2 + argv[i]; } path = Path::removeQuotationMarks(path); path = Path::fromNativeSeparators(path); // If path doesn't end with / or \, add it #if GCC_VERSION >= 40600 if (path.back() != '/') #else if (path[path.size() - 1] != '/') #endif path += '/'; _settings->includePaths.push_back(path); } else if (std::strncmp(argv[i], "--include=", 10) == 0) { std::string path = argv[i] + 10; path = Path::fromNativeSeparators(path); _settings->userIncludes.push_back(path); } else if (std::strncmp(argv[i], "--includes-file=", 16) == 0) { // open this file and read every input file (1 file name per line) AddInclPathsToList(16 + argv[i], &_settings->includePaths); } else if (std::strncmp(argv[i], "--config-exclude=",17) ==0) { std::string path = argv[i] + 17; path = Path::fromNativeSeparators(path); _settings->configExcludePaths.insert(path); } else if (std::strncmp(argv[i], "--config-excludes-file=", 23) == 0) { // open this file and read every input file (1 file name per line) AddPathsToSet(23 + argv[i], &_settings->configExcludePaths); } // file list specified else if (std::strncmp(argv[i], "--file-list=", 12) == 0) { // open this file and read every input file (1 file name per line) AddFilesToList(12 + argv[i], _pathnames); } // Ignored paths else if (std::strncmp(argv[i], "-i", 2) == 0) { std::string path; // "-i path/" if (std::strcmp(argv[i], "-i") == 0) { ++i; if (i >= argc || argv[i][0] == '-') { PrintMessage("cppcheck: argument to '-i' is missing."); return false; } path = argv[i]; } // "-ipath/" else { path = 2 + argv[i]; } if (!path.empty()) { path = Path::removeQuotationMarks(path); path = Path::fromNativeSeparators(path); path = Path::simplifyPath(path); if (FileLister::isDirectory(path)) { // If directory name doesn't end with / or \, add it #if GCC_VERSION >= 40600 if (path.back() != '/') #else if (path[path.size() - 1] != '/') #endif path += '/'; } _ignoredPaths.push_back(path); } } // --library else if (std::strncmp(argv[i], "--library=", 10) == 0) { if (!CppCheckExecutor::tryLoadLibrary(_settings->library, argv[0], argv[i]+10)) return false; } // Report progress else if (std::strcmp(argv[i], "--report-progress") == 0) { _settings->reportProgress = true; } // --std else if (std::strcmp(argv[i], "--std=posix") == 0) { _settings->standards.posix = true; } else if (std::strcmp(argv[i], "--std=c89") == 0) { _settings->standards.c = Standards::C89; } else if (std::strcmp(argv[i], "--std=c99") == 0) { _settings->standards.c = Standards::C99; } else if (std::strcmp(argv[i], "--std=c11") == 0) { _settings->standards.c = Standards::C11; } else if (std::strcmp(argv[i], "--std=c++03") == 0) { _settings->standards.cpp = Standards::CPP03; } else if (std::strcmp(argv[i], "--std=c++11") == 0) { _settings->standards.cpp = Standards::CPP11; } // Output formatter else if (std::strcmp(argv[i], "--template") == 0 || std::strncmp(argv[i], "--template=", 11) == 0) { // "--template path/" if (argv[i][10] == '=') _settings->outputFormat = argv[i] + 11; else if ((i+1) < argc && argv[i+1][0] != '-') { ++i; _settings->outputFormat = argv[i]; } else { PrintMessage("cppcheck: argument to '--template' is missing."); return false; } if (_settings->outputFormat == "gcc") _settings->outputFormat = "{file}:{line}: {severity}: {message}"; else if (_settings->outputFormat == "vs") _settings->outputFormat = "{file}({line}): {severity}: {message}"; else if (_settings->outputFormat == "edit") _settings->outputFormat = "{file} +{line}: {severity}: {message}"; } // Checking threads else if (std::strncmp(argv[i], "-j", 2) == 0) { std::string numberString; // "-j 3" if (std::strcmp(argv[i], "-j") == 0) { ++i; if (i >= argc || argv[i][0] == '-') { PrintMessage("cppcheck: argument to '-j' is missing."); return false; } numberString = argv[i]; } // "-j3" else numberString = argv[i]+2; std::istringstream iss(numberString); if (!(iss >> _settings->jobs)) { PrintMessage("cppcheck: argument to '-j' is not a number."); return false; } if (_settings->jobs > 10000) { // This limit is here just to catch typos. If someone has // need for more jobs, this value should be increased. PrintMessage("cppcheck: argument for '-j' is allowed to be 10000 at max."); return false; } } else if (std::strncmp(argv[i], "-l", 2) == 0) { std::string numberString; // "-l 3" if (std::strcmp(argv[i], "-l") == 0) { ++i; if (i >= argc || argv[i][0] == '-') { PrintMessage("cppcheck: argument to '-l' is missing."); return false; } numberString = argv[i]; } // "-l3" else numberString = argv[i]+2; std::istringstream iss(numberString); if (!(iss >> _settings->loadAverage)) { PrintMessage("cppcheck: argument to '-l' is not a number."); return false; } } // print all possible error messages.. else if (std::strcmp(argv[i], "--errorlist") == 0) { _showErrorMessages = true; _settings->xml = true; _exitAfterPrint = true; } // documentation.. else if (std::strcmp(argv[i], "--doc") == 0) { std::ostringstream doc; // Get documentation.. for (std::list<Check *>::iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) { const std::string& name((*it)->name()); const std::string info((*it)->classInfo()); if (!name.empty() && !info.empty()) doc << "## " << name << " ##\n" << info << "\n"; } std::cout << doc.str(); _exitAfterPrint = true; return true; } // show timing information.. else if (std::strncmp(argv[i], "--showtime=", 11) == 0) { const std::string showtimeMode = argv[i] + 11; if (showtimeMode == "file") _settings->showtime = SHOWTIME_FILE; else if (showtimeMode == "summary") _settings->showtime = SHOWTIME_SUMMARY; else if (showtimeMode == "top5") _settings->showtime = SHOWTIME_TOP5; else if (showtimeMode.empty()) _settings->showtime = SHOWTIME_NONE; else { std::string message("cppcheck: error: unrecognized showtime mode: \""); message += showtimeMode; message += "\". Supported modes: file, summary, top5."; PrintMessage(message); return false; } } #ifdef HAVE_RULES // Rule given at command line else if (std::strncmp(argv[i], "--rule=", 7) == 0) { Settings::Rule rule; rule.pattern = 7 + argv[i]; _settings->rules.push_back(rule); } // Rule file else if (std::strncmp(argv[i], "--rule-file=", 12) == 0) { tinyxml2::XMLDocument doc; if (doc.LoadFile(12+argv[i]) == tinyxml2::XML_SUCCESS) { tinyxml2::XMLElement *node = doc.FirstChildElement(); for (; node && strcmp(node->Value(), "rule") == 0; node = node->NextSiblingElement()) { Settings::Rule rule; tinyxml2::XMLElement *tokenlist = node->FirstChildElement("tokenlist"); if (tokenlist) rule.tokenlist = tokenlist->GetText(); tinyxml2::XMLElement *pattern = node->FirstChildElement("pattern"); if (pattern) { rule.pattern = pattern->GetText(); } tinyxml2::XMLElement *message = node->FirstChildElement("message"); if (message) { tinyxml2::XMLElement *severity = message->FirstChildElement("severity"); if (severity) rule.severity = Severity::fromString(severity->GetText()); tinyxml2::XMLElement *id = message->FirstChildElement("id"); if (id) rule.id = id->GetText(); tinyxml2::XMLElement *summary = message->FirstChildElement("summary"); if (summary) rule.summary = summary->GetText() ? summary->GetText() : ""; } if (!rule.pattern.empty()) _settings->rules.push_back(rule); } } } #endif // Specify platform else if (std::strncmp(argv[i], "--platform=", 11) == 0) { std::string platform(11+argv[i]); if (platform == "win32A") _settings->platform(Settings::Win32A); else if (platform == "win32W") _settings->platform(Settings::Win32W); else if (platform == "win64") _settings->platform(Settings::Win64); else if (platform == "unix32") _settings->platform(Settings::Unix32); else if (platform == "unix64") _settings->platform(Settings::Unix64); else if (platform == "native") _settings->platform(Settings::Unspecified); else if (!_settings->platformFile(platform)) { std::string message("cppcheck: error: unrecognized platform: \""); message += platform; message += "\"."; PrintMessage(message); return false; } } // Set maximum number of #ifdef configurations to check else if (std::strncmp(argv[i], "--max-configs=", 14) == 0) { _settings->force = false; std::istringstream iss(14+argv[i]); if (!(iss >> _settings->maxConfigs)) { PrintMessage("cppcheck: argument to '--max-configs=' is not a number."); return false; } if (_settings->maxConfigs < 1) { PrintMessage("cppcheck: argument to '--max-configs=' must be greater than 0."); return false; } maxconfigs = true; } // Print help else if (std::strcmp(argv[i], "-h") == 0 || std::strcmp(argv[i], "--help") == 0) { _pathnames.clear(); _showHelp = true; _exitAfterPrint = true; break; } else { std::string message("cppcheck: error: unrecognized command line option: \""); message += argv[i]; message += "\"."; PrintMessage(message); return false; } } else { std::string path = Path::removeQuotationMarks(argv[i]); path = Path::fromNativeSeparators(path); _pathnames.push_back(path); } } if (_settings->force) _settings->maxConfigs = ~0U; else if ((def || _settings->preprocessOnly) && !maxconfigs) _settings->maxConfigs = 1U; if (_settings->isEnabled("unusedFunction") && _settings->jobs > 1) { PrintMessage("cppcheck: unusedFunction check can't be used with '-j' option. Disabling unusedFunction check."); } if (_settings->inconclusive && _settings->xml && _settings->xml_version == 1U) { PrintMessage("cppcheck: inconclusive messages will not be shown, because the old xml format is not compatible. It's recommended to use the new xml format (use --xml-version=2)."); } if (argc <= 1) { _showHelp = true; _exitAfterPrint = true; } if (_showHelp) { PrintHelp(); return true; } // Print error only if we have "real" command and expect files if (!_exitAfterPrint && _pathnames.empty()) { PrintMessage("cppcheck: No C or C++ source files found."); return false; } // Use paths _pathnames if no base paths for relative path output are given if (_settings->basePaths.empty() && _settings->relativePaths) _settings->basePaths = _pathnames; return true; } void CmdLineParser::PrintHelp() { std::cout << "Cppcheck - A tool for static C/C++ code analysis\n" "\n" "Syntax:\n" " cppcheck [OPTIONS] [files or paths]\n" "\n" "If a directory is given instead of a filename, *.cpp, *.cxx, *.cc, *.c++, *.c,\n" "*.tpp, and *.txx files are checked recursively from the given directory.\n\n" "Options:\n" " --append=<file> This allows you to provide information about functions\n" " by providing an implementation for them.\n" " --check-config Check cppcheck configuration. The normal code\n" " analysis is disabled by this flag.\n" " --check-library Show information messages when library files have\n" " incomplete info.\n" " --config-exclude=<dir>\n" " Path (prefix) to be excluded from configuration\n" " checking. Preprocessor configurations defined in\n" " headers (but not sources) matching the prefix will not\n" " be considered for evaluation.\n" " --config-excludes-file=<file>\n" " A file that contains a list of config-excludes\n" " --dump Dump xml data for each translation unit. The dump\n" " files have the extension .dump and contain ast,\n" " tokenlist, symboldatabase, valueflow.\n" " -D<ID> Define preprocessor symbol. Unless --max-configs or\n" " --force is used, Cppcheck will only check the given\n" " configuration when -D is used.\n" " Example: '-DDEBUG=1 -D__cplusplus'.\n" " -U<ID> Undefine preprocessor symbol. Use -U to explicitly\n" " hide certain #ifdef <ID> code paths from checking.\n" " Example: '-UDEBUG'\n" " -E Print preprocessor output on stdout and don't do any\n" " further processing.\n" " --enable=<id> Enable additional checks. The available ids are:\n" " * all\n" " Enable all checks. It is recommended to only\n" " use --enable=all when the whole program is\n" " scanned, because this enables unusedFunction.\n" " * warning\n" " Enable warning messages\n" " * style\n" " Enable all coding style checks. All messages\n" " with the severities 'style', 'performance' and\n" " 'portability' are enabled.\n" " * performance\n" " Enable performance messages\n" " * portability\n" " Enable portability messages\n" " * information\n" " Enable information messages\n" " * unusedFunction\n" " Check for unused functions. It is recommend\n" " to only enable this when the whole program is\n" " scanned.\n" " * missingInclude\n" " Warn if there are missing includes. For\n" " detailed information, use '--check-config'.\n" " Several ids can be given if you separate them with\n" " commas. See also --std\n" " --error-exitcode=<n> If errors are found, integer [n] is returned instead of\n" " the default '0'. '" << EXIT_FAILURE << "' is returned\n" " if arguments are not valid or if no input files are\n" " provided. Note that your operating system can modify\n" " this value, e.g. '256' can become '0'.\n" " --errorlist Print a list of all the error messages in XML format.\n" " --exitcode-suppressions=<file>\n" " Used when certain messages should be displayed but\n" " should not cause a non-zero exitcode.\n" " --file-list=<file> Specify the files to check in a text file. Add one\n" " filename per line. When file is '-,' the file list will\n" " be read from standard input.\n" " -f, --force Force checking of all configurations in files. If used\n" " together with '--max-configs=', the last option is the\n" " one that is effective.\n" " -h, --help Print this help.\n" " -I <dir> Give path to search for include files. Give several -I\n" " parameters to give several paths. First given path is\n" " searched for contained header files first. If paths are\n" " relative to source files, this is not needed.\n" " --includes-file=<file>\n" " Specify directory paths to search for included header\n" " files in a text file. Add one include path per line.\n" " First given path is searched for contained header\n" " files first. If paths are relative to source files,\n" " this is not needed.\n" " --include=<file>\n" " Force inclusion of a file before the checked file. Can\n" " be used for example when checking the Linux kernel,\n" " where autoconf.h needs to be included for every file\n" " compiled. Works the same way as the GCC -include\n" " option.\n" " -i <dir or file> Give a source file or source file directory to exclude\n" " from the check. This applies only to source files so\n" " header files included by source files are not matched.\n" " Directory name is matched to all parts of the path.\n" " --inconclusive Allow that Cppcheck reports even though the analysis is\n" " inconclusive.\n" " There are false positives with this option. Each result\n" " must be carefully investigated before you know if it is\n" " good or bad.\n" " --inline-suppr Enable inline suppressions. Use them by placing one or\n" " more comments, like: '// cppcheck-suppress warningId'\n" " on the lines before the warning to suppress.\n" " -j <jobs> Start <jobs> threads to do the checking simultaneously.\n" #ifdef THREADING_MODEL_FORK " -l <load> Specifies that no new threads should be started if\n" " there are other threads running and the load average is\n" " at least <load>.\n" #endif " --language=<language>, -x <language>\n" " Forces cppcheck to check all files as the given\n" " language. Valid values are: c, c++\n" " --library=<cfg>\n" " Load file <cfg> that contains information about types\n" " and functions. With such information Cppcheck\n" " understands your your code better and therefore you\n" " get better results. The std.cfg file that is\n" " distributed with Cppcheck is loaded automatically.\n" " For more information about library files, read the\n" " manual.\n" " --max-configs=<limit>\n" " Maximum number of configurations to check in a file\n" " before skipping it. Default is '12'. If used together\n" " with '--force', the last option is the one that is\n" " effective.\n" " --platform=<type>, --platform=<file>\n" " Specifies platform specific types and sizes. The\n" " available builtin platforms are:\n" " * unix32\n" " 32 bit unix variant\n" " * unix64\n" " 64 bit unix variant\n" " * win32A\n" " 32 bit Windows ASCII character encoding\n" " * win32W\n" " 32 bit Windows UNICODE character encoding\n" " * win64\n" " 64 bit Windows\n" " * native\n" " Unspecified platform. Type sizes of host system\n" " are assumed, but no further assumptions.\n" " -q, --quiet Do not show progress reports.\n" " -rp, --relative-paths\n" " -rp=<paths>, --relative-paths=<paths>\n" " Use relative paths in output. When given, <paths> are\n" " used as base. You can separate multiple paths by ';'.\n" " Otherwise path where source files are searched is used.\n" " We use string comparison to create relative paths, so\n" " using e.g. ~ for home folder does not work. It is\n" " currently only possible to apply the base paths to\n" " files that are on a lower level in the directory tree.\n" " --report-progress Report progress messages while checking a file.\n" #ifdef HAVE_RULES " --rule=<rule> Match regular expression.\n" " --rule-file=<file> Use given rule file. For more information, see: \n" " http://sourceforge.net/projects/cppcheck/files/Articles/\n" #endif " --std=<id> Set standard.\n" " The available options are:\n" " * posix\n" " POSIX compatible code\n" " * c89\n" " C code is C89 compatible\n" " * c99\n" " C code is C99 compatible\n" " * c11\n" " C code is C11 compatible (default)\n" " * c++03\n" " C++ code is C++03 compatible\n" " * c++11\n" " C++ code is C++11 compatible (default)\n" " More than one --std can be used:\n" " 'cppcheck --std=c99 --std=posix file.c'\n" " --suppress=<spec> Suppress warnings that match <spec>. The format of\n" " <spec> is:\n" " [error id]:[filename]:[line]\n" " The [filename] and [line] are optional. If [error id]\n" " is a wildcard '*', all error ids match.\n" " --suppressions-list=<file>\n" " Suppress warnings listed in the file. Each suppression\n" " is in the same format as <spec> above.\n" " --template='<text>' Format the error messages. E.g.\n" " '{file}:{line},{severity},{id},{message}' or\n" " '{file}({line}):({severity}) {message}' or\n" " '{callstack} {message}'\n" " Pre-defined templates: gcc, vs, edit.\n" " -v, --verbose Output more detailed error information.\n" " --version Print out version number.\n" " --xml Write results in xml format to error stream (stderr).\n" " --xml-version=<version>\n" " Select the XML file version. Currently versions 1 and\n" " 2 are available. The default version is 1." "\n" "Example usage:\n" " # Recursively check the current folder. Print the progress on the screen and\n" " # write errors to a file:\n" " cppcheck . 2> err.txt\n" "\n" " # Recursively check ../myproject/ and don't print progress:\n" " cppcheck --quiet ../myproject/\n" "\n" " # Check test.cpp, enable all checks:\n" " cppcheck --enable=all --inconclusive --std=posix test.cpp\n" "\n" " # Check f.cpp and search include files from inc1/ and inc2/:\n" " cppcheck -I inc1/ -I inc2/ f.cpp\n" "\n" "For more information:\n" " http://cppcheck.net/manual.pdf\n"; }
Java
### Relevant Articles: - [A Quick Guide to Apache Geode](https://www.baeldung.com/apache-geode)
Java
/* dx2vtk: OpenDX to VTK file format converter * Copyright (C) 2015 David J. Warne * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * @file vtkFileWriter.h * @brief Writes a vtk data file using the legacy format * * @details This library implements a light weight legacy vtk * format writer. This is intended to be used as a part of the * dx2vtk program. * * @author David J. Warne (david.warne@qut.edu.au) * @author High Performance Computing and Research Support * @author Queensland University of Technology * */ #ifndef __VTKFILEWRITER_H #define __VTKFILEWRITER_H #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <endian.h> /*data types*/ #define VTK_ASCII 0 #define VTK_BINARY 1 #define H2BE32(buf,size) \ { \ int iii; \ uint32_t * buf32; \ buf32 = (uint32_t *)(buf); \ for(iii=0;iii<(size);iii++) \ { \ buf32[iii] = htobe32(buf32[iii]); \ } \ } \ #define BE2H32(buf,size) \ { \ int iii; \ uint32_t * buf32; \ buf32 = (uint32_t *)(buf); \ for(iii=0;iii<(size);iii++) \ { \ buf32[iii] = be32toh(buf32[iii]); \ } \ } \ /*geometry*/ #define VTK_STRUCTURED_POINTS 0 #define VTK_STRUCTURED_GRID 1 #define VTK_UNSTRUCTURED_GRID 2 #define VTK_POLYDATA 3 #define VTK_RECTILINEAR_GRID 4 #define VTK_FIELD 5 #define VTK_VERTEX 1 #define VTK_POLY_VERTEX 2 #define VTK_LINE 3 #define VTK_POLY_LINE 4 #define VTK_TRIANGLE 5 #define VTK_TRIANGLE_STRIP 6 #define VTK_POLYGON 7 #define VTK_PIXEL 8 #define VTK_QUAD 9 #define VTK_TETRA 10 #define VTK_VOXEL 11 #define VTK_HEXAHEDRON 12 #define VTK_WEDGE 13 #define VTK_PYRAMID 14 #define VTK_QUADRATIC_EDGE 21 #define VTK_QUADRATIC_TRIANGLE 22 #define VTK_QUADRATIC_QUAD 23 #define VTK_QUADRATIC_TETRA 24 #define VTK_QUADRATIC_HEXAHEDRON 25 #define VTK_VERSION "4.2" #define VTK_TITLE_LENGTH 256 #define VTK_DIM 3 #define VTK_INT 0 #define VTK_FLOAT 1 #define VTK_SUCCESS 1 #define VTK_MEMORY_ERROR 0 #define VTK_FILE_NOT_FOUND_ERROR -1 #define VTK_INVALID_FILE_ERROR -2 #define VTK_NOT_SUPPORTED_ERROR -3 #define VTK_INVALID_USAGE_ERROR -4 #define VTK_NOT_IMPLEMENTED_YET_ERROR -5 #define VTK_FILE_ERROR -6 #ifndef VTK_TYPE_DEFAULT #define VTK_TYPE_DEFAULT VTK_ASCII #endif typedef struct vtkDataFile_struct vtkDataFile; typedef struct unstructuredGrid_struct unstructuredGrid; typedef struct structuredPoints_struct structuredPoints; typedef struct polydata_struct polydata; typedef struct vtkData_struct vtkData; typedef struct scalar_struct scalar; typedef struct vector_struct vector; struct scalar_struct { char name[32]; int type; void * data; }; struct vector_struct { char name[32]; int type; void *data; }; struct vtkData_struct { int numScalars; int numColorScalars; int numLookupTables; int numVectors; int numNormals; int numTextureCoords; int numTensors; int numFields; int size; /** @todo for now only support scalars and vectors */ scalar *scalar_data; vector *vector_data; }; struct vtkDataFile_struct { FILE *fp; char vtkVersion[4]; /*header version*/ char title[VTK_TITLE_LENGTH]; /**/ unsigned char dataType; unsigned char geometry; void * dataset; vtkData * pointdata; vtkData * celldata; }; struct structuredPoints_struct { int dimensions[VTK_DIM]; float origin[VTK_DIM]; float spacing[VTK_DIM]; }; struct structuredGrid_struct { int dimensions[VTK_DIM]; int numPoints; float *points; // numpoints*3; }; struct polydata_struct{ int numPoints; float * points; int numPolygons; int *numVerts; int *polygons; }; struct rectilinearGrid_struct{ int dimensions[VTK_DIM]; int numX; int numY; int numZ; float *X_coordinates; float *Y_coordinates; float *Z_coordinates; }; struct unstructuredGrid_struct{ int numPoints; float * points; int numCells; int cellSize; int *cells; int *numVerts; int *cellTypes; }; /*function prototypes */ int VTK_Open(vtkDataFile *file, char * filename); int VTK_Write(vtkDataFile *file); int VTK_WriteUnstructuredGrid(FILE *fp,unstructuredGrid *ug,char type); int VTK_WritePolydata(FILE *fp,polydata *pd,char type); int VTK_WriteStructuredPoints(FILE *fp,structuredPoints *sp,char type); int VTK_WriteData(FILE *fp,vtkData *data,char type); int VTK_Close(vtkDataFile*file); #endif
Java
/* * Copyright (C) ST-Ericsson SA 2010 * * License Terms: GNU General Public License v2 * Author: Naveen Kumar Gaddipati <naveen.gaddipati@stericsson.com> * * ux500 Scroll key and Keypad Encoder (SKE) header */ #ifndef __SKE_H #define __SKE_H #include <linux/input/matrix_keypad.h> /* register definitions for SKE peripheral */ #define SKE_CR 0x00 #define SKE_VAL0 0x04 #define SKE_VAL1 0x08 #define SKE_DBCR 0x0C #define SKE_IMSC 0x10 #define SKE_RIS 0x14 #define SKE_MIS 0x18 #define SKE_ICR 0x1C /* * Keypad module */ /** * struct keypad_platform_data - structure for platform specific data * @init: pointer to keypad init function * @exit: pointer to keypad deinitialisation function * @keymap_data: matrix scan code table for keycodes * @krow: maximum number of rows * @kcol: maximum number of columns * @debounce_ms: platform specific debounce time * @no_autorepeat: flag for auto repetition * @wakeup_enable: allow waking up the system */ struct ske_keypad_platform_data { int (*init)(void); int (*exit)(void); const struct matrix_keymap_data *keymap_data; u8 krow; u8 kcol; u8 debounce_ms; bool no_autorepeat; bool wakeup_enable; }; #endif /*__SKE_KPD_H*/
Java
<?php /** * Created by PhpStorm. * User: Ermin Islamagić - https://ermin.islamagic.com * Date: 22.8.2016 * Time: 09:37 */ // Check if root path is defined if (!defined("ROOT_PATH")) { // Show 403 if root path not defined header("HTTP/1.1 403 Forbidden"); exit; } /** * Class LocaleAppController */ class LocaleAppController extends Plugin { /** * LocaleAppController constructor. */ public function __construct() { $this->setLayout('ActionAdmin'); } /** * @param $const * @return null */ public static function getConst($const) { $registry = Registry::getInstance(); $store = $registry->get('Locale'); return isset($store[$const]) ? $store[$const] : NULL; } /** * @return array */ public function ActionCheckInstall() { $this->setLayout('ActionEmpty'); $result = array('status' => 'OK', 'code' => 200, 'text' => 'Operation succeeded', 'info' => array()); $folders = array(UPLOAD_PATH . 'locale'); foreach ($folders as $dir) { if (!is_writable($dir)) { $result['status'] = 'ERR'; $result['code'] = 101; $result['text'] = 'Permission requirement'; $result['info'][] = sprintf('Folder \'<span class="bold">%1$s</span>\' is not writable. You need to set write permissions (chmod 777) to directory located at \'<span class="bold">%1$s</span>\'', $dir); } } return $result; } }
Java
// // MSGRTickConnection.h // wehuibao // // Created by Ke Zeng on 13-6-20. // Copyright (c) 2013年 Zeng Ke. All rights reserved. // #import <Foundation/Foundation.h> typedef enum { MSGRTickConnectionStateNotConnected=0, MSGRTickConnectionStateConnecting, MSGRTickConnectionStateConnected, MSGRTickConnectionStateClosed, MSGRTickConnectionStateError } MSGRTickConnectionState; @class MSGRTickConnection; @protocol MSGRTickConnectionDelegate <NSObject> @optional - (void)connectionLost:(MSGRTickConnection *)connection; - (void)connection:(MSGRTickConnection *)connection error:(NSError *)error; @required - (void)connectionEstablished:(MSGRTickConnection *)connection; - (void)connection:(MSGRTickConnection *)connection receivedPacket:(id)packet withDirective:(NSString *)directive; @end @interface MSGRTickConnection: NSObject<NSStreamDelegate> @property (nonatomic) MSGRTickConnectionState state; @property (nonatomic) BOOL loginOK; @property (nonatomic, weak) id<MSGRTickConnectionDelegate> delegate; - (void)connect; - (void)close; - (void)sendPacket:(id)packet directive:(NSString *)directive; @end
Java
/*************************************************************************** begin : Thu Apr 24 15:54:58 CEST 2003 copyright : (C) 2003 by Giuseppe Lipari email : lipari@sssup.it ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include <algorithm> #include <string> #include <simul.hpp> #include <server.hpp> #include <jtrace.hpp> #include <task.hpp> #include <task.hpp> #include <waitinstr.hpp> namespace RTSim { using namespace std; using namespace MetaSim; // Init globals JavaTrace::TRACE_ENDIANESS JavaTrace::endianess = TRACE_UNKNOWN_ENDIAN; string JavaTrace::version = "1.2"; JavaTrace::JavaTrace(const char *name, bool tof, unsigned long int limit) :Trace(name, Trace::BINARY, tof), taskList(10) { if (endianess == TRACE_UNKNOWN_ENDIAN) probeEndianess(); const char cver[] = "version 1.2"; if (toFile) _os.write(cver, sizeof(cver)); filenum = 0; fileLimit = limit; } JavaTrace::~JavaTrace() { // WARNING: the data vector is cleared but its content isn't. It // must be deleted manually (close). if (toFile) Trace::close(); else data.clear(); } void JavaTrace::probeEndianess(void) { // Used for endianess check (Big/Little!) static char const big_endian[] = { static_cast<char const>(0xff), static_cast<char const>(0), static_cast<char const>(0xff), static_cast<char const>(0)}; static int const probe = 0xff00ff00; int *probePtr = (int *)(big_endian); if (*probePtr == probe) endianess = TRACE_BIG_ENDIAN; else endianess = TRACE_LITTLE_ENDIAN; //DBGFORCE("Endianess: " << (endianess == TRACE_LITTLE_ENDIAN ? "Little\n" : "Big\n")); } void JavaTrace::close() { if (toFile) Trace::close(); else { for (unsigned int i = 0; i < data.size(); i++) delete data[i]; data.clear(); } } void JavaTrace::record(Event* e) { DBGENTER(_JTRACE_DBG_LEV); TaskEvt* ee = dynamic_cast<TaskEvt*>(e); if (ee == NULL) { DBGPRINT("The event is not a TaskEvt"); return; } Task* task = ee->getTask(); if (task != NULL) { vector<int>::const_iterator p = find(taskList.begin(), taskList.end(), task->getID()); if (p == taskList.end()) { TraceNameEvent* a = new TraceNameEvent(ee->getLastTime(), task->getID(), task->getName()); if (toFile) a->write(_os); else data.push_back(a); taskList.push_back(task->getID()); } } // at this point we have to see what kind of event it is... if (dynamic_cast<ArrEvt*>(e) != NULL) { DBGPRINT("ArrEvt"); ArrEvt* tae = dynamic_cast<ArrEvt*>(e); TraceArrEvent* a = new TraceArrEvent(e->getLastTime(), task->getID()); if (toFile) a->write(_os); else data.push_back(a); Task* rttask = dynamic_cast<Task*>(task); if (rttask) { TraceDlineSetEvent* b = new TraceDlineSetEvent(tae->getLastTime(), rttask->getID(), rttask->getDeadline()); if (toFile) b->write(_os); else data.push_back(b); } } else if (dynamic_cast<EndEvt*>(e) != NULL) { DBGPRINT("EndEvt"); EndEvt* tee = dynamic_cast<EndEvt*>(e); TraceEndEvent* a = new TraceEndEvent(tee->getLastTime(), task->getID(), tee->getCPU()); if (toFile) a->write(_os); else data.push_back(a); } else if (dynamic_cast<DeschedEvt*>(e) != NULL) { DBGPRINT("DeschedEvt"); DeschedEvt *tde = dynamic_cast<DeschedEvt *>(e); TraceDeschedEvent* a = new TraceDeschedEvent(tde->getLastTime(), task->getID(), tde->getCPU()); if (toFile) a->write(_os); else data.push_back(a); } else if (dynamic_cast<WaitEvt*>(e) != NULL) { DBGPRINT("WaitEvt"); WaitEvt* we = dynamic_cast<WaitEvt*>(e); //WaitInstr* instr = dynamic_cast<WaitInstr*>(we->getInstr()); WaitInstr* instr = we->getInstr(); string res = instr->getResource(); TraceWaitEvent* a = new TraceWaitEvent(we->getLastTime(), task->getID(), res); if (toFile) a->write(_os); else data.push_back(a); } else if (dynamic_cast<SignalEvt*>(e) != NULL) { DBGPRINT("SignalEvt"); SignalEvt* se = dynamic_cast<SignalEvt*>(e); //SignalInstr* instr = dynamic_cast<SignalInstr*>(se->getInstr()); SignalInstr* instr = se->getInstr(); string res = instr->getResource(); TraceSignalEvent* a = new TraceSignalEvent(se->getLastTime(), task->getID(), res); if (toFile) a->write(_os); else data.push_back(a); } else if (dynamic_cast<SchedEvt*>(e) != NULL) { DBGPRINT("SchedEvt"); SchedEvt* tse = dynamic_cast<SchedEvt*>(e); TraceSchedEvent* a = new TraceSchedEvent(tse->getLastTime(), task->getID(), tse->getCPU()); if (toFile) a->write(_os); else data.push_back(a); // } else if (dynamic_cast<DlinePostEvt*>(e) != NULL) { // DBGPRINT("DlinePostEvt"); // DlinePostEvt* dpe = dynamic_cast<DlinePostEvt*>(e); // TraceDlinePostEvent* a = new TraceDlinePostEvent(dpe->getLastTime(), // task->getID(), // dpe->getPrevDline(), // dpe->getPostDline()); // if (toFile) a->write(_os); // else data.push_back(a); } else if (dynamic_cast<DeadEvt*>(e) != NULL) { DBGPRINT("DlineMissEvt"); DeadEvt* de = dynamic_cast<DeadEvt*>(e); TraceDlineMissEvent* a = new TraceDlineMissEvent(de->getLastTime(), task->getID()); if (toFile) a->write(_os); else data.push_back(a); } if (toFile) _os.flush(); } }
Java
# -*- coding: utf-8 -*- from django.shortcuts import render from django.http import HttpResponse from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.contrib.auth.decorators import login_required def centres(request): #Python练习项目管理中心Center return render(request, 'centres/centres.html') def upload(request): #文件上传 return render(request, 'centres/upload.html') def uploadfile(request): import os if request.method == "POST": # 请求方法为POST时,进行处理 myFile =request.FILES.get("myfile", None) # 获取上传的文件,如果没有文件,则默认为None if not myFile: #return HttpResponse("no files for upload!") return render(request, 'centres/upload.html',{'what':'no file for upload!'}) upfile = open(os.path.join("D:\\xHome\\data\\upload",myFile.name),'wb+') # 打开特定的文件进行二进制的写操作 for chunk in myFile.chunks(): # 分块写入文件 upfile.write(chunk) upfile.close() #return HttpResponse("upload over!") return render(request, 'centres/upload.html', {'what':'upload over!'})
Java
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.6"/> <title>Super Martin: Globals</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { searchBox.OnSelectItem(0); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">Super Martin </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.6 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="annotated.html"><span>Data&#160;Structures</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> <li class="current"><a href="globals.html"><span>Globals</span></a></li> </ul> </div> <div id="navrow3" class="tabs2"> <ul class="tablist"> <li class="current"><a href="globals.html"><span>All</span></a></li> <li><a href="globals_func.html"><span>Functions</span></a></li> <li><a href="globals_defs.html"><span>Macros</span></a></li> </ul> </div> <div id="navrow4" class="tabs3"> <ul class="tablist"> <li><a href="globals.html#index_a"><span>a</span></a></li> <li><a href="globals_b.html#index_b"><span>b</span></a></li> <li><a href="globals_c.html#index_c"><span>c</span></a></li> <li><a href="globals_d.html#index_d"><span>d</span></a></li> <li><a href="globals_e.html#index_e"><span>e</span></a></li> <li><a href="globals_f.html#index_f"><span>f</span></a></li> <li><a href="globals_g.html#index_g"><span>g</span></a></li> <li><a href="globals_i.html#index_i"><span>i</span></a></li> <li><a href="globals_j.html#index_j"><span>j</span></a></li> <li><a href="globals_k.html#index_k"><span>k</span></a></li> <li><a href="globals_l.html#index_l"><span>l</span></a></li> <li><a href="globals_m.html#index_m"><span>m</span></a></li> <li><a href="globals_n.html#index_n"><span>n</span></a></li> <li class="current"><a href="globals_o.html#index_o"><span>o</span></a></li> <li><a href="globals_p.html#index_p"><span>p</span></a></li> <li><a href="globals_r.html#index_r"><span>r</span></a></li> <li><a href="globals_s.html#index_s"><span>s</span></a></li> <li><a href="globals_t.html#index_t"><span>t</span></a></li> <li><a href="globals_u.html#index_u"><span>u</span></a></li> <li><a href="globals_w.html#index_w"><span>w</span></a></li> </ul> </div> </div><!-- top --> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Data Structures</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&#160;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&#160;</span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark">&#160;</span>Macros</a></div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="contents"> <div class="textblock">Here is a list of all documented functions, variables, defines, enums, and typedefs with links to the documentation:</div> <h3><a class="anchor" id="index_o"></a>- o -</h3><ul> <li>openFile() : <a class="el" href="file_8c.html#ab763060cbdd57fdb704871d896fc492a">file.c</a> , <a class="el" href="file_8h.html#a279d2082dd2ddcdbbce81da176f135b4">file.h</a> </li> <li>openLevel() : <a class="el" href="file__level_8h.html#a05b04a7e24539a2ae826cfb87ea4d859">file_level.h</a> , <a class="el" href="file__level_8c.html#a8464887031ce16d797b564fc7a9e661f">file_level.c</a> </li> <li>optionMenu() : <a class="el" href="menu__option_8c.html#a6f370e66ea56a5fdf95dfa2abfac5baa">menu_option.c</a> , <a class="el" href="menu__option_8h.html#a6f370e66ea56a5fdf95dfa2abfac5baa">menu_option.h</a> </li> <li>outOfList() : <a class="el" href="enemies_8h.html#a7774be61944dce2ae021e0e4442b4515">enemies.h</a> , <a class="el" href="enemies_8c.html#a7774be61944dce2ae021e0e4442b4515">enemies.c</a> </li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Mon Jun 2 2014 17:19:18 for Super Martin by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.6 </small></address> </body> </html>
Java
import cv2 import numpy as np np.set_printoptions(threshold=np.nan) import util as util import edge_detect import lineseg import drawedgelist # img = cv2.imread("img/Slide2.jpg", 0) img = cv2.imread("unsorted/Unit Tests/lambda.png", 0) im_size = img.shape returnedCanny = cv2.Canny(img, 50, 150, apertureSize = 3) cv2.imshow("newcanny", returnedCanny) skel_dst = util.morpho(returnedCanny) out = edge_detect.mask_contours(edge_detect.create_img(skel_dst)) res = [] # print(np.squeeze(out[0])) # print(out[0][0]) for i in range(len(out)): # Add the first point to the end so the shape closes current = np.squeeze(out[i]) # print('current', current) # print('first', out[i][0]) if current.shape[0] > 2: # res.append(np.concatenate((current, out[i][0]))) # print(res[-1]) res.append(current) # print(np.concatenate((np.squeeze(out[i]), out[i][0]))) res = np.array(res) util.sqz_contours(res) res = lineseg.lineseg(np.array([res[1]]), tol=5) print(res, "res") """ for x in range(len(res)): for y in range(lan ): """ drawedgelist.drawedgelist(res, img) """ seglist = [] for i in range(res.shape[0]): # print('shape', res[i].shape) if res[i].shape[0] > 2: # print(res[i]) # print(res[i][0]) seglist.append(np.concatenate((res[i], [res[i][0]]))) else: seglist.append(res[i]) seglist = np.array(seglist) """ #print(seglist, "seglist") #print(len(seglist), "seglist len") #print(seglist.shape, "seglistshape") #drawedgelist.drawedgelist(seglist) """ # ******* SECTION 2 ******* # SEGMENT AND LABEL THE CURVATURE LINES (CONVEX/CONCAVE). LineFeature, ListPoint = Lseg_to_Lfeat_v4.create_linefeatures(seglist, res, im_size) Line_new, ListPoint_new, line_merged = merge_lines_v4.merge_lines(LineFeature, ListPoint, 10, im_size) #print(Line_new, "line new") print(len(Line_new), "len line new") util.draw_lf(Line_new, blank_image) line_newC = LabelLineCurveFeature_v4.classify_curves(img, Line_new, ListPoint_new, 11)"""
Java
"use strict"; module.exports = function registerDefaultRoutes( baseUrl, app, opts ){ var controller = opts.controller; var listRouter = app.route( baseUrl ); if( opts.all ){ listRouter = listRouter.all( opts.all ); } if( opts.list ){ listRouter.get( opts.list ); } if( opts.create ){ listRouter.post( opts.create ); } listRouter.get( controller.list ) .post( controller.create ); var resourceRouter = app.route( baseUrl + "/:_id" ); if( opts.all ){ resourceRouter.all( opts.all ); } if( opts.retrieve ){ resourceRouter.get(opts.retrieve); } if(opts.update){ resourceRouter.patch(opts.update); } if(opts.remove){ resourceRouter.delete(opts.remove); } resourceRouter.get( controller.retrieve ) .patch( controller.update ) .delete( controller.remove ); return { list: listRouter, resources: resourceRouter }; };
Java
package it.ads.activitiesmanager.model.dao; import java.io.Serializable; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; //Segnala che si tratta di una classe DAO (o Repository) @Repository //Significa che tutti i metodi della classe sono definiti come @Transactional @Transactional public abstract class AbstractDao<T extends Serializable> { private Class<T> c; @PersistenceContext EntityManager em; public final void setClass(Class<T> c){ this.c = c; } public T find(Integer id) { return em.find(c,id); } public List<T> findAll(){ String SELECT = "SELECT * FROM " + c.getName(); Query query = em.createQuery(SELECT); return query.getResultList(); } public void save(T entity){ em.persist(entity); } public void update(T entity){ em.merge(entity); } public void delete(T entity){ em.remove(entity); } public void deleteById(Integer id){ T entity = find(id); delete(entity); } }
Java
----------------------------------- -- Area: Windurst Woods -- NPC: Amimi -- Type: Chocobo Renter ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/chocobo"); require("scripts/globals/status"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local level = player:getMainLvl(); local gil = player:getGil(); if (player:hasKeyItem(CHOCOBO_LICENSE) and level >= 15) then local price = getChocoboPrice(player); player:setLocalVar("chocoboPriceOffer",price); if (level >= 20) then level = 0; end player:startEvent(10004,price,gil,level); else player:startEvent(10007); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); local price = player:getLocalVar("chocoboPriceOffer"); if (csid == 10004 and option == 0) then if (player:delGil(price)) then updateChocoboPrice(player, price); if (player:getMainLvl() >= 20) then local duration = 1800 + (player:getMod(MOD_CHOCOBO_RIDING_TIME) * 60) player:addStatusEffectEx(dsp.effects.MOUNTED,dsp.effects.MOUNTED,0,0,duration,true); else player:addStatusEffectEx(dsp.effects.MOUNTED,dsp.effects.MOUNTED,0,0,900,true); end player:setPos(-122,-4,-520,0,0x74); end end end;
Java
#include "VRConstructionKit.h" #include "selection/VRSelector.h" #include "core/objects/geometry/VRGeometry.h" #include "core/objects/material/VRMaterial.h" #include "core/utils/toString.h" #include "core/utils/VRFunction.h" #include "core/setup/devices/VRDevice.h" #include "core/setup/devices/VRSignal.h" using namespace OSG; VRConstructionKit::VRConstructionKit() { snapping = VRSnappingEngine::create(); selector = VRSelector::create(); onSnap = VRSnappingEngine::VRSnapCb::create("on_snap_callback", bind(&VRConstructionKit::on_snap, this, placeholders::_1)); snapping->getSignalSnap()->add(onSnap); } VRConstructionKit::~VRConstructionKit() {} VRConstructionKitPtr VRConstructionKit::create() { return VRConstructionKitPtr(new VRConstructionKit()); } void VRConstructionKit::clear() { objects.clear(); selector->clear(); snapping->clear(); } VRSnappingEnginePtr VRConstructionKit::getSnappingEngine() { return snapping; } VRSelectorPtr VRConstructionKit::getSelector() { return selector; } vector<VRObjectPtr> VRConstructionKit::getObjects() { vector<VRObjectPtr> res; for (auto m : objects) res.push_back(m.second); return res; } bool VRConstructionKit::on_snap(VRSnappingEngine::EventSnapWeakPtr we) { if (!doConstruction) return true; auto e = we.lock(); if (!e) return true; if (!e->snap) { breakup(e->o1); return true; } if (!e->o1 || !e->o2) return true; VRObjectPtr p1 = e->o1->getDragParent(); VRObjectPtr p2 = e->o2->getParent(); if (p1 == 0 || p2 == 0) return true; if (p1 == p2) if (p1->hasTag("kit_group")) return true; if (p2->hasTag("kit_group")) { e->o1->rebaseDrag(p2); e->o1->setPickable(false); e->o2->setPickable(false); e->o1->setWorldMatrix(e->m); return true; } VRTransformPtr group = VRTransform::create("kit_group"); group->setPersistency(0); group->setPickable(true); group->addAttachment("kit_group", 0); p2->addChild(group); e->o1->rebaseDrag(group); Matrix4d m = e->o2->getWorldMatrix(); e->o2->switchParent(group); e->o1->setPickable(false); e->o2->setPickable(false); e->o1->setWorldMatrix(e->m); e->o2->setWorldMatrix(m); return true; } int VRConstructionKit::ID() { static int i = 0; i++; return i; } void VRConstructionKit::breakup(VRTransformPtr obj) { if (!doConstruction) return; if (obj == 0) return; auto p = obj->getParent(); if (p == 0) return; if (p->hasTag("kit_group")) { obj->switchParent( p->getParent() ); obj->setPickable(true); return; } p = obj->getDragParent(); if (p == 0) return; if (p->hasTag("kit_group")) { obj->rebaseDrag( p->getParent() ); obj->setPickable(true); } } int VRConstructionKit::addAnchorType(float size, Color3f color) { auto g = VRGeometry::create("anchor"); string bs = toString(size); g->setPrimitive("Box " + bs + " " + bs + " " + bs + " 1 1 1"); auto m = VRMaterial::create("anchor"); m->setDiffuse(color); g->setMaterial(m); int id = ID(); anchors[id] = g; return id; } void VRConstructionKit::toggleConstruction(bool active) { doConstruction = active; } void VRConstructionKit::addObject(VRTransformPtr t) { objects[t.get()] = t; snapping->addObject(t); } void VRConstructionKit::remObject(VRTransformPtr t) { objects.erase(t.get()); snapping->remObject(t); } VRGeometryPtr VRConstructionKit::addObjectAnchor(VRTransformPtr t, int a, Vec3d pos, float radius) { if (!anchors.count(a)) return 0; Vec3d d(0,1,0); Vec3d u(1,0,0); VRGeometryPtr anc = static_pointer_cast<VRGeometry>(anchors[a]->duplicate()); anc->setTransform(pos, d, u); anc->show(); anc->switchParent(t); snapping->addObjectAnchor(t, anc); snapping->addRule(VRSnappingEngine::POINT, VRSnappingEngine::POINT, Pose::create(), Pose::create(Vec3d(), d, u), radius, 0, t ); //snapping->addRule(VRSnappingEngine::POINT, VRSnappingEngine::POINT, Pose::create(), Pose::create(Vec3d(), Vec3d(1,0,0), Vec3d(0,1,0)), radius, 0, t ); //snapping->addRule(VRSnappingEngine::POINT, VRSnappingEngine::POINT, Pose::create(), Pose::create(), radius, 0, t ); return anc; }
Java
## A Vim plugin offers Nginx/Openresty syntax highlight and directives completion ![example](./example.png) This little plugin offers: 1. syntax highlight for Nginx configuration, with addition OpenResty enhancement. 1. syntax highlight for LuaJIT source file, with adddition OpenResty API highlight. 1. syntax-based directives completion. #### Support version This plugin supports OpenResty v1.21.4. #### How to use First of all, install this plugin with your favorite plugin manager. The syntax highlight is enabled once your file is detected as Nginx configuration. If Vim doesn't recognize the file type, you could add this to your `.vimrc`: ``` autocmd BufRead,BufNewFile pattern_matched_your_file(s) set filetype=nginx ``` For example, `autocmd BufRead,BufNewFile nginx_*.conf.tpl set filetype=nginx`. To complete the directives, type part of the word and then type `Ctrl+x Ctrl+o` to trigger it. If you are using [YouCompleteMe](https://github.com/Valloric/YouCompleteMe), set `let g:ycm_seed_identifiers_with_syntax = 1` in your `.vimrc`. #### Known issue There is a limit to render Lua snippet inside `_by_lua_block` directives. You need to close the block with `}` in separate line, and `}` should have the same indent with the `{`. It is a hack to distinguish from `}` of the inner Lua snippet. Anyway, if your configuration is in good format, the highlight should work smoothly.
Java
/* _ /_\ _ _ ___ ___ / _ \| '_/ -_|_-< /_/ \_\_| \___/__/ */ #include "Ares.h" /* Description: Function that is called when the library is loaded, use this as an entry point. */ int __attribute__((constructor)) Ares() { SDL2::SetupSwapWindow(); return 0; }
Java
#!/usr/bin/env python # setup of the grid parameters # default queue used for training training_queue = { 'queue':'q1dm', 'memfree':'16G', 'pe_opt':'pe_mth 2', 'hvmem':'8G', 'io_big':True } # the queue that is used solely for the final ISV training step isv_training_queue = { 'queue':'q1wm', 'memfree':'32G', 'pe_opt':'pe_mth 4', 'hvmem':'8G' } # number of audio files that one job should preprocess number_of_audio_files_per_job = 1000 preprocessing_queue = {} # number of features that one job should extract number_of_features_per_job = 600 extraction_queue = { 'queue':'q1d', 'memfree':'8G' } # number of features that one job should project number_of_projections_per_job = 600 projection_queue = { 'queue':'q1d', 'hvmem':'8G', 'memfree':'8G' } # number of models that one job should enroll number_of_models_per_enrol_job = 20 enrol_queue = { 'queue':'q1d', 'memfree':'4G', 'io_big':True } # number of models that one score job should process number_of_models_per_score_job = 20 score_queue = { 'queue':'q1d', 'memfree':'4G', 'io_big':True } grid_type = 'local' # on Idiap grid
Java
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title> Module: Ronin::Model::HasLicense::InstanceMethods &mdash; Ronin Documentation </title> <link rel="stylesheet" href="../../../css/style.css" type="text/css" media="screen" charset="utf-8" /> <link rel="stylesheet" href="../../../css/common.css" type="text/css" media="screen" charset="utf-8" /> <script type="text/javascript" charset="utf-8"> hasFrames = window.top.frames.main ? true : false; relpath = '../../../'; framesUrl = "../../../frames.html#!" + escape(window.location.href); </script> <script type="text/javascript" charset="utf-8" src="../../../js/jquery.js"></script> <script type="text/javascript" charset="utf-8" src="../../../js/app.js"></script> </head> <body> <div id="header"> <div id="menu"> <a href="../../../_index.html">Index (I)</a> &raquo; <span class='title'><span class='object_link'><a href="../../../Ronin.html" title="Ronin (module)">Ronin</a></span></span> &raquo; <span class='title'><span class='object_link'><a href="../../Model.html" title="Ronin::Model (module)">Model</a></span></span> &raquo; <span class='title'><span class='object_link'><a href="../HasLicense.html" title="Ronin::Model::HasLicense (module)">HasLicense</a></span></span> &raquo; <span class="title">InstanceMethods</span> <div class="noframes"><span class="title">(</span><a href="." target="_top">no frames</a><span class="title">)</span></div> </div> <div id="search"> <a class="full_list_link" id="class_list_link" href="../../../class_list.html"> Class List </a> <a class="full_list_link" id="method_list_link" href="../../../method_list.html"> Method List </a> <a class="full_list_link" id="file_list_link" href="../../../file_list.html"> File List </a> </div> <div class="clear"></div> </div> <iframe id="search_frame"></iframe> <div id="content"><h1>Module: Ronin::Model::HasLicense::InstanceMethods </h1> <dl class="box"> <dt class="r1 last">Defined in:</dt> <dd class="r1 last">lib/ronin/model/has_license.rb</dd> </dl> <div class="clear"></div> <h2>Overview</h2><div class="docstring"> <div class="discussion"> <p>Instance methods that are added when <span class='object_link'><a href="../HasLicense.html" title="Ronin::Model::HasLicense (module)">Ronin::Model::HasLicense</a></span> is included into a model.</p> </div> </div> <div class="tags"> </div> <h2> Instance Method Summary <small>(<a href="#" class="summary_toggle">collapse</a>)</small> </h2> <ul class="summary"> <li class="public deprecated"> <span class="summary_signature"> <a href="#license%21-instance_method" title="#license! (instance method)">- (Object) <strong>license!</strong>(name) </a> </span> <span class="deprecated note title">deprecated</span> <span class="summary_desc"><strong>Deprecated.</strong> <div class='inline'><p><code>license!</code> was deprecated in favor of <span class='object_link'><a href="#licensed_under-instance_method" title="Ronin::Model::HasLicense::InstanceMethods#licensed_under (method)">#licensed_under</a></span>.</p> </div></span> </li> <li class="public "> <span class="summary_signature"> <a href="#licensed_under-instance_method" title="#licensed_under (instance method)">- (License) <strong>licensed_under</strong>(name) </a> </span> <span class="summary_desc"><div class='inline'><p>Sets the license of the model.</p> </div></span> </li> </ul> <div id="instance_method_details" class="method_details_list"> <h2>Instance Method Details</h2> <div class="method_details first"> <h3 class="signature first" id="license!-instance_method"> - (<tt>Object</tt>) <strong>license!</strong>(name) </h3><div class="docstring"> <div class="discussion"> <div class="note deprecated"><strong>Deprecated.</strong> <div class='inline'><p><code>license!</code> was deprecated in favor of <span class='object_link'><a href="#licensed_under-instance_method" title="Ronin::Model::HasLicense::InstanceMethods#licensed_under (method)">#licensed_under</a></span>.</p> </div></div> </div> </div> <div class="tags"> <p class="tag_title">Since:</p> <ul class="since"> <li> <div class='inline'><p>1.0.0</p> </div> </li> </ul> </div><table class="source_code"> <tr> <td> <pre class="lines"> 123 124 125</pre> </td> <td> <pre class="code"><span class="info file"># File 'lib/ronin/model/has_license.rb', line 123</span> <span class='kw'>def</span> <span class='id identifier rubyid_license!'>license!</span><span class='lparen'>(</span><span class='id identifier rubyid_name'>name</span><span class='rparen'>)</span> <span class='id identifier rubyid_licensed_under'>licensed_under</span><span class='lparen'>(</span><span class='id identifier rubyid_name'>name</span><span class='rparen'>)</span> <span class='kw'>end</span></pre> </td> </tr> </table> </div> <div class="method_details "> <h3 class="signature " id="licensed_under-instance_method"> - (<tt><span class='object_link'><a href="../../License.html" title="Ronin::License (class)">License</a></span></tt>) <strong>licensed_under</strong>(name) </h3><div class="docstring"> <div class="discussion"> <p>Sets the license of the model.</p> </div> </div> <div class="tags"> <div class="examples"> <p class="tag_title">Examples:</p> <pre class="example code"><span class='id identifier rubyid_licensed_under'>licensed_under</span> <span class='symbol'>:mit</span></pre> </div> <p class="tag_title">Parameters:</p> <ul class="param"> <li> <span class='name'>name</span> <span class='type'>(<tt>Symbol</tt>, <tt>String</tt>)</span> &mdash; <div class='inline'><p>The name of the license to use.</p> </div> </li> </ul> <p class="tag_title">Returns:</p> <ul class="return"> <li> <span class='type'>(<tt><span class='object_link'><a href="../../License.html" title="Ronin::License (class)">License</a></span></tt>)</span> &mdash; <div class='inline'><p>The new license of the model.</p> </div> </li> </ul> <p class="tag_title">Since:</p> <ul class="since"> <li> <div class='inline'><p>1.3.0</p> </div> </li> </ul> </div><table class="source_code"> <tr> <td> <pre class="lines"> 114 115 116</pre> </td> <td> <pre class="code"><span class="info file"># File 'lib/ronin/model/has_license.rb', line 114</span> <span class='kw'>def</span> <span class='id identifier rubyid_licensed_under'>licensed_under</span><span class='lparen'>(</span><span class='id identifier rubyid_name'>name</span><span class='rparen'>)</span> <span class='kw'>self</span><span class='period'>.</span><span class='id identifier rubyid_license'>license</span> <span class='op'>=</span> <span class='const'>Ronin</span><span class='op'>::</span><span class='const'>License</span><span class='period'>.</span><span class='id identifier rubyid_predefined_resource'>predefined_resource</span><span class='lparen'>(</span><span class='id identifier rubyid_name'>name</span><span class='rparen'>)</span> <span class='kw'>end</span></pre> </td> </tr> </table> </div> </div> </div> <div id="footer"> Generated on Sat Jun 16 20:51:28 2012 by <a href="http://yardoc.org" title="Yay! A Ruby Documentation Tool" target="_parent">yard</a> 0.8.2.1 (ruby-1.9.3). </div> </body> </html>
Java
package ca.six.tomato.util; import org.json.JSONArray; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowEnvironment; import java.io.File; import ca.six.tomato.BuildConfig; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertTrue; /** * Created by songzhw on 2016-10-03 */ @RunWith(RobolectricTestRunner.class) @Config(constants = BuildConfig.class, sdk = 21) public class DataUtilsTest { @Test public void testFile() { File dstFile = ShadowEnvironment.getExternalStorageDirectory(); assertTrue(dstFile.exists()); System.out.println("szw isDirectory = " + dstFile.isDirectory()); //=> true System.out.println("szw isExisting = " + dstFile.exists()); //=> true System.out.println("szw path = " + dstFile.getPath()); //=> C:\Users\***\AppData\Local\Temp\android-tmp-robolectric7195966122073188215 } @Test public void testWriteString(){ File dstFile = ShadowEnvironment.getExternalStorageDirectory(); String path = dstFile.getPath() +"/tmp"; DataUtilKt.write("abc", path); String ret = DataUtilKt.read(path, false); assertEquals("abc", ret); } @Test public void testWriteJSON(){ File dstFile = ShadowEnvironment.getExternalStorageDirectory(); String path = dstFile.getPath() +"/tmp"; String content = " {\"clock\": \"clock1\", \"work\": 40, \"short\": 5, \"long\": 15}\n" + " {\"clock\": \"clock2\", \"work\": 30, \"short\": 5, \"long\": 15}\n" + " {\"clock\": \"clock3\", \"work\": 45, \"short\": 5, \"long\": 15}"; DataUtilKt.write(content, path); JSONArray ret = DataUtilKt.read(path); System.out.println("szw, ret = "+ret.toString()); assertNotNull(ret); } }
Java
/* * The basic test codes to check the AnglogIn. */ #include "mbed.h" static AnalogIn ain_x(A6); // connect joistics' x axis to A6 pin of mbed static AnalogIn ain_y(A5); // connect joistics' y axis to A5 pin of mbed static void printAnalogInput(AnalogIn *xin, AnalogIn *yin) { uint8_t point[2] = { 0 }; point[0] = (uint8_t)(xin->read()*100.0f + 0.5); point[1] = (uint8_t)(yin->read()*100.0f + 0.5); printf("x: %d, y: %d\n", point[0], point[1]); } int main() { while(1) { printAnalogInput(&ain_x, &ain_y); wait(0.2f); } }
Java
/*** * Copyright (c) 2013 John Krauss. * * This file is part of Crashmapper. * * Crashmapper is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Crashmapper is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Crashmapper. If not, see <http://www.gnu.org/licenses/>. * ***/ /*jslint browser: true, nomen: true, sloppy: true*/ /*globals Backbone, Crashmapper */ /** * @param {Object} options * @constructor * @extends Backbone.View */ Crashmapper.AppView = Backbone.View.extend({ id: 'app', /** * @this {Crashmapper.AppView} */ initialize: function () { this.about = new Crashmapper.AboutView({}).render(); this.about.$el.appendTo(this.$el).hide(); this.map = new Crashmapper.MapView({}); this.map.$el.appendTo(this.$el); }, /** * @this {Crashmapper.AppView} */ render: function () { return this; } });
Java
FROM golang:alpine AS builder RUN apk add --update git && go get github.com/fffaraz/microdns FROM alpine:latest COPY --from=builder /go/bin/microdns /usr/local/bin ENTRYPOINT ["microdns"]
Java
/* **************************************************************************** * * Copyright Saab AB, 2005-2013 (http://safirsdkcore.com) * * Created by: Lars Hagström / stlrha * ******************************************************************************* * * This file is part of Safir SDK Core. * * Safir SDK Core is free software: you can redistribute it and/or modify * it under the terms of version 3 of the GNU General Public License as * published by the Free Software Foundation. * * Safir SDK Core is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Safir SDK Core. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************/ using System; using System.Collections.Generic; using System.Text; namespace Safir.Dob.Typesystem { /// <summary> /// Base class for all Containers. /// <para/> ///This class contains common functionality for all Containers. /// Basically this amounts to the interface for nullability and /// the change flag. /// </summary> abstract public class ContainerBase { /// <summary> /// Default Constructor. /// <para/> /// Construct a container that is not changed. /// </summary> public ContainerBase() { m_bIsChanged = false; } /// <summary> /// Is the container set to null? /// </summary> /// <returns>True if the container is set to null.</returns> abstract public bool IsNull(); /// <summary> /// Set the container to null. /// </summary> abstract public void SetNull(); /// <summary> /// Is the change flag set on the container? /// <para/> /// The change flag gets updated every time the contained value changes. /// <para/> /// Note: If this is a container containing objects this call will recursively /// check change flags in the contained objects. /// </summary> /// <returns> True if the containers change flag is set.</returns> virtual public bool IsChanged() { return m_bIsChanged; } /// <summary> /// Set the containers change flag. /// <para/> /// It should be fairly unusual for an application to have to use this /// operation. There is nothing dangerous about it, but are you sure this /// is the operation you were after? /// <para/> /// The change flag is how receivers of objects can work out what the /// sender really wanted done on the object. /// <para/> /// Note: If this is a container containing one or more objects this call /// will recursively set all the change flags in the contained objects. /// </summary> /// <param name="changed">The value to set the change flag(s) to.</param> virtual public void SetChanged(bool changed) { m_bIsChanged = changed; } #region Cloning /// <summary> /// Create a copy of the Container. /// <para> /// This method is deprecated. /// </para> /// </summary> public dynamic Clone() { return this.DeepClone(); } /// <summary> /// Copy. /// </summary> /// <param name="other">Other ContainerBase.</param> virtual public void Copy(ContainerBase other) { ShallowCopy(other); } #endregion /// <summary> /// Flag accessible from subclasses. /// </summary> protected internal bool m_bIsChanged; virtual internal void ShallowCopy(ContainerBase other) { if (this.GetType() != other.GetType()) { throw new SoftwareViolationException("Invalid call to Copy, containers are not of same type"); } m_bIsChanged = other.m_bIsChanged; } } }
Java
#!/usr/bin/python2 # -*- coding: utf-8 -*- # coding=utf-8 import unittest from datetime import datetime from lib.escala import Escala import dirs dirs.DEFAULT_DIR = dirs.TestDir() class FrameTest(unittest.TestCase): def setUp(self): self.escala = Escala('fixtures/escala.xml') self.dir = dirs.TestDir() self.maxDiff = None def tearDown(self): pass def test_attributos_voo_1(self): p_voo = self.escala.escalas[0] self.assertEqual(p_voo.activity_date, datetime(2013, 3, 1, 11, 36)) self.assertEqual(p_voo.present_location, 'VCP') self.assertEqual(p_voo.flight_no, '4148') self.assertEqual(p_voo.origin, 'VCP') self.assertEqual(p_voo.destination, 'GYN') self.assertEqual(p_voo.actype, 'E95') self.assertTrue(p_voo.checkin) self.assertEqual(p_voo.checkin_time, datetime(2013, 3, 1, 10, 36)) self.assertEqual(p_voo.std, datetime(2013, 3, 1, 13, 13)) self.assertEqual(p_voo.sta, datetime(2013, 3, 1, 11, 36)) self.assertEqual(p_voo.activity_info, 'AD4148') self.assertFalse(p_voo.duty_design) def test_attributos_voo_17(self): p_voo = self.escala.escalas[17] self.assertEqual(p_voo.activity_date, datetime(2013, 10, 28, 3, 0)) self.assertEqual(p_voo.present_location, 'VCP') self.assertEqual(p_voo.flight_no, None) self.assertEqual(p_voo.origin, 'VCP') self.assertEqual(p_voo.destination, 'VCP') self.assertEqual(p_voo.activity_info, 'P04') self.assertEqual(p_voo.actype, None) self.assertEqual(p_voo.sta, datetime(2013, 10, 28, 3, 0)) self.assertEqual(p_voo.std, datetime(2013, 10, 28, 15, 0)) self.assertFalse(p_voo.checkin) self.assertEqual(p_voo.checkin_time, None) self.assertFalse(p_voo.duty_design) def test_attributos_voo_18(self): p_voo = self.escala.escalas[18] self.assertEqual(p_voo.activity_date, datetime(2013, 10, 29, 4, 58)) self.assertEqual(p_voo.present_location, 'VCP') self.assertEqual(p_voo.flight_no, '4050') self.assertEqual(p_voo.origin, 'VCP') self.assertEqual(p_voo.destination, 'FLN') self.assertEqual(p_voo.activity_info, 'AD4050') self.assertEqual(p_voo.actype, 'E95') self.assertEqual(p_voo.sta, datetime(2013, 10, 29, 4, 58)) self.assertEqual(p_voo.std, datetime(2013, 10, 29, 6, 15)) self.assertTrue(p_voo.checkin) self.assertEqual(p_voo.checkin_time, datetime(2013, 10, 29, 5, 8)) self.assertFalse(p_voo.duty_design) self.assertEqual(p_voo.horas_de_voo, '1:17') def test_attributos_quarto_voo(self): p_voo = self.escala.escalas[25] self.assertFalse(p_voo.checkin) self.assertEqual(p_voo.checkin_time, None) self.assertEqual(p_voo.flight_no, '2872') self.assertEqual(p_voo.activity_info, 'AD2872') def test_calculo_horas_voadas(self): s_horas = { 'h_diurno': '6:40', 'h_noturno': '6:47', 'h_total_voo': '13:27', 'h_faixa2': '0:00', 'h_sobreaviso': '40:00', 'h_reserva': '29:13' } self.assertEqual(self.escala.soma_horas(), s_horas) def test_ics(self): """ Check ICS output """ escala = Escala('fixtures/escala_ics.xml') f_result = open(self.dir.get_data_dir() + 'fixtures/escala.ics') self.assertEqual(escala.ics(), f_result.read()) f_result.close() def test_csv(self): """ Check CSV output """ f_result = open(self.dir.get_data_dir() + 'fixtures/escala.csv') self.assertEqual(self.escala.csv(), f_result.read()) f_result.close() def main(): unittest.main() if __name__ == '__main__': main()
Java
package net.thevpc.upa.impl; import net.thevpc.upa.*; import net.thevpc.upa.impl.transform.IdentityDataTypeTransform; import net.thevpc.upa.impl.util.NamingStrategy; import net.thevpc.upa.impl.util.NamingStrategyHelper; import net.thevpc.upa.impl.util.PlatformUtils; import net.thevpc.upa.types.*; import net.thevpc.upa.exceptions.UPAException; import net.thevpc.upa.filters.FieldFilter; import net.thevpc.upa.types.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public abstract class AbstractField extends AbstractUPAObject implements Field, Comparable<Object> { protected Entity entity; protected EntityItem parent; protected DataType dataType; protected Formula persistFormula; protected int persistFormulaOrder; protected Formula updateFormula; protected int updateFormulaOrder; protected Formula queryFormula; protected Object defaultObject; protected SearchOperator searchOperator = SearchOperator.DEFAULT; protected DataTypeTransform typeTransform; protected HashMap<String, Object> properties; protected FlagSet<UserFieldModifier> userModifiers = FlagSets.noneOf(UserFieldModifier.class); protected FlagSet<UserFieldModifier> userExcludeModifiers = FlagSets.noneOf(UserFieldModifier.class); protected FlagSet<FieldModifier> effectiveModifiers = FlagSets.noneOf(FieldModifier.class); protected boolean closed; protected Object unspecifiedValue = UnspecifiedValue.DEFAULT; private AccessLevel persistAccessLevel = AccessLevel.READ_WRITE; private AccessLevel updateAccessLevel = AccessLevel.READ_WRITE; private AccessLevel readAccessLevel = AccessLevel.READ_WRITE; private ProtectionLevel persistProtectionLevel = ProtectionLevel.PUBLIC; private ProtectionLevel updateProtectionLevel = ProtectionLevel.PUBLIC; private ProtectionLevel readProtectionLevel = ProtectionLevel.PUBLIC; private FieldPersister fieldPersister; private PropertyAccessType accessType; private List<Relationship> manyToOneRelationships; private List<Relationship> oneToOneRelationships; private boolean _customDefaultObject = false; private Object _typeDefaultObject = false; protected AbstractField() { } @Override public String getAbsoluteName() { return (getEntity() == null ? "?" : getEntity().getName()) + "." + getName(); } public EntityItem getParent() { return parent; } public void setParent(EntityItem item) { EntityItem old = this.parent; EntityItem recent = item; beforePropertyChangeSupport.firePropertyChange("parent", old, recent); this.parent = item; afterPropertyChangeSupport.firePropertyChange("parent", old, recent); } @Override public void commitModelChanges() { manyToOneRelationships = getManyToOneRelationshipsImpl(); oneToOneRelationships = getOneToOneRelationshipsImpl(); } public boolean is(FieldFilter filter) throws UPAException { return filter.accept(this); } public boolean isId() throws UPAException { return getModifiers().contains(FieldModifier.ID); } @Override public boolean isGeneratedId() throws UPAException { if (!isId()) { return false; } Formula persistFormula = getPersistFormula(); return (persistFormula != null); } public boolean isMain() throws UPAException { return getModifiers().contains(FieldModifier.MAIN); } @Override public boolean isSystem() { return getModifiers().contains(FieldModifier.SYSTEM); } public boolean isSummary() throws UPAException { return getModifiers().contains(FieldModifier.SUMMARY); } public List<Relationship> getManyToOneRelationships() { return manyToOneRelationships; } public List<Relationship> getOneToOneRelationships() { return oneToOneRelationships; } protected List<Relationship> getManyToOneRelationshipsImpl() { List<Relationship> relations = new ArrayList<Relationship>(); for (Relationship r : getPersistenceUnit().getRelationshipsBySource(getEntity())) { Field entityField = r.getSourceRole().getEntityField(); if (entityField != null && entityField.equals(this)) { relations.add(r); } else { List<Field> fields = r.getSourceRole().getFields(); for (Field field : fields) { if (field.equals(this)) { relations.add(r); } } } } return PlatformUtils.trimToSize(relations); } protected List<Relationship> getOneToOneRelationshipsImpl() { List<Relationship> relations = new ArrayList<Relationship>(); for (Relationship r : getPersistenceUnit().getRelationshipsBySource(getEntity())) { Field entityField = r.getSourceRole().getEntityField(); if (entityField != null && entityField.equals(this)) { relations.add(r); } else { List<Field> fields = r.getSourceRole().getFields(); for (Field field : fields) { if (field.equals(this)) { relations.add(r); } } } } return PlatformUtils.trimToSize(relations); } public void setFormula(Formula formula) { setPersistFormula(formula); setUpdateFormula(formula); } @Override public void setFormula(String formula) { setFormula(formula == null ? null : new ExpressionFormula(formula)); } public void setPersistFormula(Formula formula) { this.persistFormula = formula; } public void setUpdateFormula(Formula formula) { this.updateFormula = formula; } @Override public void setFormulaOrder(int order) { setPersistFormulaOrder(order); setUpdateFormulaOrder(order); } public int getUpdateFormulaOrder() { return updateFormulaOrder; } @Override public void setUpdateFormulaOrder(int order) { this.updateFormulaOrder = order; } public int getPersistFormulaOrder() { return persistFormulaOrder; } @Override public void setPersistFormulaOrder(int order) { this.persistFormulaOrder = order; } public Formula getUpdateFormula() { return updateFormula; } @Override public void setUpdateFormula(String formula) { setUpdateFormula(formula == null ? null : new ExpressionFormula(formula)); } public Formula getSelectFormula() { return queryFormula; } @Override public void setSelectFormula(String formula) { setSelectFormula(formula == null ? null : new ExpressionFormula(formula)); } public void setSelectFormula(Formula queryFormula) { this.queryFormula = queryFormula; } // public boolean isRequired() throws UPAException { // return (!isReadOnlyOnPersist() || !isReadOnlyOnUpdate()) && !getDataType().isNullable(); // } public String getPath() { EntityItem parent = getParent(); return parent == null ? ("/" + getName()) : (parent.getPath() + "/" + getName()); } @Override public PersistenceUnit getPersistenceUnit() { return entity.getPersistenceUnit(); } public Formula getPersistFormula() { return persistFormula; } @Override public void setPersistFormula(String formula) { setPersistFormula(formula == null ? null : new ExpressionFormula(formula)); } public Entity getEntity() { return entity; } public void setEntity(Entity entity) { this.entity = entity; } public DataType getDataType() { return dataType; } /** * called by PersistenceUnitFilter / Table You should not use it * * @param datatype datatype */ @Override public void setDataType(DataType datatype) { this.dataType = datatype; if (!getDataType().isNullable()) { _typeDefaultObject = getDataType().getDefaultValue(); } else { _typeDefaultObject = null; } } public Object getDefaultValue() { if (_customDefaultObject) { Object o = ((CustomDefaultObject) defaultObject).getObject(); if (o == null) { o = _typeDefaultObject; } return o; } else { Object o = defaultObject; if (o == null) { o = _typeDefaultObject; } return o; } } public Object getDefaultObject() { return defaultObject; } /** * called by PersistenceUnitFilter / Table You should not use it * * @param o default value witch may be san ObjectHandler */ public void setDefaultObject(Object o) { defaultObject = o; if (o instanceof CustomDefaultObject) { _customDefaultObject = true; } } public FlagSet<FieldModifier> getModifiers() { return effectiveModifiers; } public void setEffectiveModifiers(FlagSet<FieldModifier> effectiveModifiers) { this.effectiveModifiers = effectiveModifiers; } // public void addModifiers(long modifiers) { // setModifiers(getModifiers() | modifiers); // } // // public void removeModifiers(long modifiers) { // setModifiers(getModifiers() & ~modifiers); // } // public Expression getExpression() { // return formula == null ? null : formula.getExpression(); // } @Override public boolean equals(Object other) { return !(other == null || !(other instanceof Field)) && compareTo(other) == 0; } public int compareTo(Object other) { if (other == this) { return 0; } if (other == null) { return 1; } Field f = (Field) other; NamingStrategy comp = NamingStrategyHelper.getNamingStrategy(getEntity().getPersistenceUnit().isCaseSensitiveIdentifiers()); String s1 = entity != null ? comp.getUniformValue(entity.getName()) : ""; String s2 = f.getName() != null ? comp.getUniformValue(f.getEntity().getName()) : ""; int i = s1.compareTo(s2); if (i != 0) { return i; } else { String s3 = getName() != null ? comp.getUniformValue(getName()) : ""; String s4 = f.getName() != null ? comp.getUniformValue(f.getName()) : ""; i = s3.compareTo(s4); return i; } } @Override public FlagSet<UserFieldModifier> getUserModifiers() { return userModifiers; } // public void resetModifiers() { // modifiers = 0; // } public void setUserModifiers(FlagSet<UserFieldModifier> modifiers) { this.userModifiers = modifiers == null ? FlagSets.noneOf(UserFieldModifier.class) : modifiers; } @Override public FlagSet<UserFieldModifier> getUserExcludeModifiers() { return userExcludeModifiers; } public void setUserExcludeModifiers(FlagSet<UserFieldModifier> modifiers) { this.userExcludeModifiers = modifiers == null ? FlagSets.noneOf(UserFieldModifier.class) : modifiers; } @Override public String toString() { return getAbsoluteName(); } @Override public void close() throws UPAException { this.closed = true; } public boolean isClosed() { return closed; } @Override public Object getUnspecifiedValue() { return unspecifiedValue; } @Override public void setUnspecifiedValue(Object o) { this.unspecifiedValue = o; } public Object getUnspecifiedValueDecoded() { final Object fuv = getUnspecifiedValue(); if (UnspecifiedValue.DEFAULT.equals(fuv)) { return getDataType().getDefaultUnspecifiedValue(); } else { return fuv; } } public boolean isUnspecifiedValue(Object value) { Object v = getUnspecifiedValueDecoded(); return (v == value || (v != null && v.equals(value))); } public AccessLevel getPersistAccessLevel() { return persistAccessLevel; } public void setPersistAccessLevel(AccessLevel persistAccessLevel) { if (PlatformUtils.isUndefinedEnumValue(AccessLevel.class, persistAccessLevel)) { persistAccessLevel = AccessLevel.READ_WRITE; } this.persistAccessLevel = persistAccessLevel; } public AccessLevel getUpdateAccessLevel() { return updateAccessLevel; } public void setUpdateAccessLevel(AccessLevel updateAccessLevel) { if (PlatformUtils.isUndefinedEnumValue(AccessLevel.class, updateAccessLevel)) { updateAccessLevel = AccessLevel.READ_WRITE; } this.updateAccessLevel = updateAccessLevel; } public AccessLevel getReadAccessLevel() { return readAccessLevel; } public void setReadAccessLevel(AccessLevel readAccessLevel) { if (PlatformUtils.isUndefinedEnumValue(AccessLevel.class, readAccessLevel)) { readAccessLevel = AccessLevel.READ_ONLY; } if (readAccessLevel == AccessLevel.READ_WRITE) { readAccessLevel = AccessLevel.READ_ONLY; } this.readAccessLevel = readAccessLevel; } public void setAccessLevel(AccessLevel accessLevel) { setPersistAccessLevel(accessLevel); setUpdateAccessLevel(accessLevel); setReadAccessLevel(accessLevel); } public ProtectionLevel getPersistProtectionLevel() { return persistProtectionLevel; } public void setPersistProtectionLevel(ProtectionLevel persistProtectionLevel) { if (PlatformUtils.isUndefinedEnumValue(ProtectionLevel.class, persistProtectionLevel)) { persistProtectionLevel = ProtectionLevel.PUBLIC; } this.persistProtectionLevel = persistProtectionLevel; } public ProtectionLevel getUpdateProtectionLevel() { return updateProtectionLevel; } public void setUpdateProtectionLevel(ProtectionLevel updateProtectionLevel) { if (PlatformUtils.isUndefinedEnumValue(ProtectionLevel.class, updateProtectionLevel)) { updateProtectionLevel = ProtectionLevel.PUBLIC; } this.updateProtectionLevel = updateProtectionLevel; } public ProtectionLevel getReadProtectionLevel() { return readProtectionLevel; } public void setReadProtectionLevel(ProtectionLevel readProtectionLevel) { if (PlatformUtils.isUndefinedEnumValue(ProtectionLevel.class, readProtectionLevel)) { readProtectionLevel = ProtectionLevel.PUBLIC; } this.readProtectionLevel = readProtectionLevel; } public void setProtectionLevel(ProtectionLevel persistLevel) { setPersistProtectionLevel(persistLevel); setUpdateProtectionLevel(persistLevel); setReadProtectionLevel(persistLevel); } public SearchOperator getSearchOperator() { return searchOperator; } public void setSearchOperator(SearchOperator searchOperator) { this.searchOperator = searchOperator; } public FieldPersister getFieldPersister() { return fieldPersister; } public void setFieldPersister(FieldPersister fieldPersister) { this.fieldPersister = fieldPersister; } public DataTypeTransform getTypeTransform() { return typeTransform; } @Override public DataTypeTransform getEffectiveTypeTransform() { DataTypeTransform t = getTypeTransform(); if (t == null) { DataType d = getDataType(); if (d != null) { t = new IdentityDataTypeTransform(d); } } return t; } public void setTypeTransform(DataTypeTransform transform) { this.typeTransform = transform; } public PropertyAccessType getPropertyAccessType() { return accessType; } public void setPropertyAccessType(PropertyAccessType accessType) { this.accessType = accessType; } @Override public Object getMainValue(Object instance) { Object v = getValue(instance); if (v != null) { Relationship manyToOneRelationship = getManyToOneRelationship(); if (manyToOneRelationship != null) { v = manyToOneRelationship.getTargetEntity().getBuilder().getMainValue(v); } } return v; } @Override public Object getValue(Object instance) { if (instance instanceof Document) { return ((Document) instance).getObject(getName()); } return getEntity().getBuilder().getProperty(instance, getName()); } @Override public void setValue(Object instance, Object value) { getEntity().getBuilder().setProperty(instance, getName(), value); } @Override public void check(Object value) { getDataType().check(value, getName(), null); } @Override public boolean isManyToOne() { return getDataType() instanceof ManyToOneType; } @Override public boolean isOneToOne() { return getDataType() instanceof OneToOneType; } @Override public ManyToOneRelationship getManyToOneRelationship() { DataType dataType = getDataType(); if (dataType instanceof ManyToOneType) { return (ManyToOneRelationship) ((ManyToOneType) dataType).getRelationship(); } return null; } @Override public OneToOneRelationship getOneToOneRelationship() { DataType dataType = getDataType(); if (dataType instanceof OneToOneType) { return (OneToOneRelationship) ((OneToOneType) dataType).getRelationship(); } return null; } protected void fillFieldInfo(FieldInfo i) { Field f = this; fillObjectInfo(i); DataTypeInfo dataType = f.getDataType() == null ? null : f.getDataType().getInfo(); if (dataType != null) { UPAI18n d = getPersistenceGroup().getI18nOrDefault(); if (f.getDataType() instanceof EnumType) { List<Object> values = ((EnumType) f.getDataType()).getValues(); StringBuilder v = new StringBuilder(); for (Object o : values) { if (v.length() > 0) { v.append(","); } v.append(d.getEnum(o)); } dataType.getProperties().put("titles", String.valueOf(v)); } } i.setDataType(dataType); i.setId(f.isId()); i.setGeneratedId(f.isGeneratedId()); i.setModifiers(f.getModifiers().toArray()); i.setPersistAccessLevel(f.getPersistAccessLevel()); i.setUpdateAccessLevel(f.getUpdateAccessLevel()); i.setReadAccessLevel(f.getReadAccessLevel()); i.setPersistProtectionLevel(f.getPersistProtectionLevel()); i.setUpdateProtectionLevel(f.getUpdateProtectionLevel()); i.setReadProtectionLevel(f.getReadProtectionLevel()); i.setEffectivePersistAccessLevel(f.getEffectivePersistAccessLevel()); i.setEffectiveUpdateAccessLevel(f.getEffectiveUpdateAccessLevel()); i.setEffectiveReadAccessLevel(f.getEffectiveReadAccessLevel()); i.setMain(f.isMain()); i.setSystem(f.getModifiers().contains(FieldModifier.SYSTEM)); i.setSummary(f.isSummary()); i.setManyToOne(f.isManyToOne()); i.setPropertyAccessType(f.getPropertyAccessType()); Relationship r = f.getManyToOneRelationship(); i.setManyToOneRelationship(r == null ? null : r.getName()); } @Override public AccessLevel getEffectiveAccessLevel(AccessMode mode) { if (!PlatformUtils.isUndefinedEnumValue(AccessMode.class, mode)) { switch (mode) { case READ: return getEffectiveReadAccessLevel(); case PERSIST: return getEffectivePersistAccessLevel(); case UPDATE: return getEffectiveUpdateAccessLevel(); } } return AccessLevel.INACCESSIBLE; } @Override public AccessLevel getAccessLevel(AccessMode mode) { if (!PlatformUtils.isUndefinedEnumValue(AccessMode.class, mode)) { switch (mode) { case READ: return getReadAccessLevel(); case PERSIST: return getPersistAccessLevel(); case UPDATE: return getUpdateAccessLevel(); } } return AccessLevel.INACCESSIBLE; } @Override public ProtectionLevel getProtectionLevel(AccessMode mode) { if (!PlatformUtils.isUndefinedEnumValue(AccessMode.class, mode)) { switch (mode) { case READ: return getReadProtectionLevel(); case PERSIST: return getPersistProtectionLevel(); case UPDATE: return getUpdateProtectionLevel(); } } return ProtectionLevel.PRIVATE; } public AccessLevel getEffectivePersistAccessLevel() { if (isSystem()) { return AccessLevel.INACCESSIBLE; } AccessLevel al = getPersistAccessLevel(); ProtectionLevel pl = getPersistProtectionLevel(); if (PlatformUtils.isUndefinedEnumValue(AccessLevel.class, al)) { al = AccessLevel.READ_WRITE; } if (PlatformUtils.isUndefinedEnumValue(ProtectionLevel.class, pl)) { pl = ProtectionLevel.PUBLIC; } boolean hasFormula = getPersistFormula() != null; if (al == AccessLevel.READ_WRITE && hasFormula) { al = AccessLevel.READ_ONLY; } switch (al) { case INACCESSIBLE: { break; } case READ_ONLY: { switch (pl) { case PRIVATE: { al = AccessLevel.INACCESSIBLE; break; } case PROTECTED: { break; } case PUBLIC: { break; } } break; } case READ_WRITE: { switch (pl) { case PRIVATE: { al = AccessLevel.READ_ONLY; break; } case PROTECTED: { if (!getPersistenceUnit().getSecurityManager().isAllowedWrite(this)) { al = AccessLevel.READ_ONLY; } break; } case PUBLIC: { break; } } break; } } if (al != AccessLevel.INACCESSIBLE) { if (isGeneratedId()) { al = AccessLevel.INACCESSIBLE; } if (!getModifiers().contains(FieldModifier.PERSIST_DEFAULT)) { al = AccessLevel.INACCESSIBLE; } } return al; } public AccessLevel getEffectiveUpdateAccessLevel() { if (isSystem()) { return AccessLevel.INACCESSIBLE; } AccessLevel al = getUpdateAccessLevel(); ProtectionLevel pl = getUpdateProtectionLevel(); if (PlatformUtils.isUndefinedEnumValue(AccessLevel.class, al)) { al = AccessLevel.READ_WRITE; } if (PlatformUtils.isUndefinedEnumValue(ProtectionLevel.class, pl)) { pl = ProtectionLevel.PUBLIC; } boolean hasFormula = getUpdateFormula() != null; if (al == AccessLevel.READ_WRITE && hasFormula) { al = AccessLevel.READ_ONLY; } switch (al) { case INACCESSIBLE: { break; } case READ_ONLY: { switch (pl) { case PRIVATE: { al = AccessLevel.INACCESSIBLE; break; } case PROTECTED: { if (!getPersistenceUnit().getSecurityManager().isAllowedRead(this)) { al = AccessLevel.INACCESSIBLE; } break; } case PUBLIC: { break; } } break; } case READ_WRITE: { switch (pl) { case PRIVATE: { al = AccessLevel.READ_ONLY; break; } case PROTECTED: { if (!getPersistenceUnit().getSecurityManager().isAllowedWrite(this)) { al = AccessLevel.READ_ONLY; } if (!getPersistenceUnit().getSecurityManager().isAllowedRead(this)) { al = AccessLevel.INACCESSIBLE; } break; } case PUBLIC: { break; } } break; } } if (isId() && al == AccessLevel.READ_WRITE) { al = AccessLevel.READ_ONLY; } if (getModifiers().contains(FieldModifier.UPDATE_DEFAULT)) { // } else if (getModifiers().contains(FieldModifier.PERSIST_FORMULA) || getModifiers().contains(FieldModifier.PERSIST_SEQUENCE)) { if (al == AccessLevel.READ_WRITE) { al = AccessLevel.READ_ONLY; } } else if (getModifiers().contains(FieldModifier.PERSIST_FORMULA) || getModifiers().contains(FieldModifier.PERSIST_SEQUENCE)) { if (al == AccessLevel.READ_WRITE) { al = AccessLevel.READ_ONLY; } } return al; } public AccessLevel getEffectiveReadAccessLevel() { if (isSystem()) { return AccessLevel.INACCESSIBLE; } AccessLevel al = getReadAccessLevel(); ProtectionLevel pl = getReadProtectionLevel(); if (PlatformUtils.isUndefinedEnumValue(AccessLevel.class, al)) { al = AccessLevel.READ_WRITE; } if (PlatformUtils.isUndefinedEnumValue(ProtectionLevel.class, pl)) { pl = ProtectionLevel.PUBLIC; } if (al == AccessLevel.READ_WRITE) { al = AccessLevel.READ_ONLY; } if (al == AccessLevel.READ_ONLY) { if (!getModifiers().contains(FieldModifier.SELECT)) { al = AccessLevel.INACCESSIBLE; } } switch (al) { case INACCESSIBLE: { break; } case READ_ONLY: { switch (pl) { case PRIVATE: { al = AccessLevel.INACCESSIBLE; break; } case PROTECTED: { if (!getPersistenceUnit().getSecurityManager().isAllowedRead(this)) { al = AccessLevel.INACCESSIBLE; } break; } case PUBLIC: { break; } } break; } } return al; } }
Java
#include "../../VM/Handler/Opcode8030Handler.h" #include "../../VM/Script.h" namespace Falltergeist { namespace VM { namespace Handler { Opcode8030::Opcode8030(VM::Script *script, std::shared_ptr<ILogger> logger) : OpcodeHandler(script) { this->logger = std::move(logger); } void Opcode8030::_run() { logger->debug() << "[8030] [*] op_while(address, condition)" << std::endl; auto condition = _script->dataStack()->popLogical(); if (!condition) { _script->setProgramCounter(_script->dataStack()->popInteger()); } } } } }
Java
MT19937AR_OBJ = mt19937ar.o MT19937AR_H = mt19937ar.h ##################################################################### .PHONY : all clean help all: $(MT19937AR_OBJ) clean: @echo " CLEAN mt19937ar" @rm -rf *.o help: @echo "possible targets are 'all' 'clean' 'help'" @echo "'all' - builds $(MT19937AR_OBJ)" @echo "'clean' - deletes $(MT19937AR_OBJ)" @echo "'help' - outputs this message" ##################################################################### %.o: %.c $(MT19937AR_H) @echo " CC $<" @gcc -flto -fuse-linker-plugin -ffat-lto-objects -flto -fuse-linker-plugin -g -O2 -pipe -ffast-math -Wall -Wno-maybe-uninitialized -Wno-clobbered -Wempty-body -Wno-switch -Wno-missing-field-initializers -Wshadow -fno-strict-aliasing -DMAXCONN=16384 -I../common -DHAS_TLS -DHAVE_SETRLIMIT -DHAVE_STRNLEN -I/usr/include -DHAVE_MONOTONIC_CLOCK -c $(OUTPUT_OPTION) $<
Java
----------------------------------- -- Area: Windurst Woods -- NPC: Matata -- Type: Standard NPC -- Involved in quest: In a Stew -- !pos 131 -5 -109 241 ----------------------------------- require("scripts/globals/quests") ----------------------------------- function onTrade(player,npc,trade) end function onTrigger(player,npc) local IAS = player:getQuestStatus(WINDURST, IN_A_STEW) local IASvar = player:getVar("IASvar") local CB = player:getQuestStatus(WINDURST, CHOCOBILIOUS) -- IN A STEW if IAS == QUEST_ACCEPTED and IASvar == 1 then player:startEvent(233, 0, 0, 4545) -- In a Stew in progress elseif IAS == QUEST_ACCEPTED and IASvar == 2 then player:startEvent(237) -- In a Stew reminder elseif IAS == QUEST_COMPLETED then player:startEvent(241) -- new dialog after In a Stew -- CHOCOBILIOUS elseif CB == QUEST_COMPLETED then player:startEvent(226) -- Chocobilious complete -- STANDARD DIALOG else player:startEvent(223) end end function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) -- IN A STEW if csid == 233 then player:setVar("IASvar", 2) end end
Java
#include "report_mib_feature.h" #include "mib_feature_definition.h" #include "report_manager.h" #include "protocol.h" #include "bus_slave.h" #include "momo_config.h" #include "report_log.h" #include "report_comm_stream.h" #include "system_log.h" #include <string.h> #define BASE64_REPORT_MAX_LENGTH 160 //( 4 * ( ( RAW_REPORT_MAX_LENGTH + 2 ) / 3) ) extern char base64_report_buffer[BASE64_REPORT_MAX_LENGTH+1]; static void start_scheduled_reporting(void) { set_momo_state_flag( kStateFlagReportingEnabled, true ); start_report_scheduling(); } static void stop_scheduled_reporting(void) { set_momo_state_flag( kStateFlagReportingEnabled, false ); stop_report_scheduling(); } static void get_scheduled_reporting(void) { bus_slave_return_int16( get_momo_state_flag( kStateFlagReportingEnabled ) ); } static void send_report(void) { taskloop_add( post_report, NULL ); } static void set_reporting_interval(void) { set_report_scheduling_interval( plist_get_int16(0) ); } static void get_reporting_interval(void) { bus_slave_return_int16( current_momo_state.report_config.report_interval ); } static void set_reporting_route(void) { update_report_route( (plist_get_int16(0) >> 8) & 0xFF , plist_get_int16(0) & 0xFF , (const char*)plist_get_buffer(1) , plist_get_buffer_length() ); } static void get_reporting_route(void) { const char* route = get_report_route( ( plist_get_int16(0) >> 8 ) & 0xFF ); if ( !route ) { bus_slave_seterror( kUnknownError ); return; } uint8 start = plist_get_int16(0) & 0xFF; uint8 len = strlen( route ) - start; if ( len < 0 ) { bus_slave_seterror( kCallbackError ); return; } if ( len > kBusMaxMessageSize ) len = kBusMaxMessageSize; bus_slave_return_buffer( route + start, len ); } static void set_reporting_apn(void) { set_gprs_apn( (const char*)plist_get_buffer(0), plist_get_buffer_length() ); } static void get_reporting_apn(void) { bus_slave_return_buffer( current_momo_state.report_config.gprs_apn, strlen(current_momo_state.report_config.gprs_apn) ); } static void set_reporting_flags(void) { current_momo_state.report_config.report_flags = plist_get_int16(0); } static void get_reporting_flags(void) { bus_slave_return_int16( current_momo_state.report_config.report_flags ); } static void set_reporting_aggregates(void) { current_momo_state.report_config.bulk_aggregates = plist_get_int16(0); current_momo_state.report_config.interval_aggregates = plist_get_int16(1); } static void get_reporting_aggregates(void) { plist_set_int16( 0, current_momo_state.report_config.bulk_aggregates ); plist_set_int16( 1, current_momo_state.report_config.interval_aggregates ); bus_slave_setreturn( pack_return_status( kNoMIBError, 4 ) ); } static void build_report() { construct_report(); } static void get_report() { uint16 offset = plist_get_int16(0); memcpy(plist_get_buffer(0), base64_report_buffer+offset, 20); bus_slave_setreturn( pack_return_status(kNoMIBError, 20 )); } static void get_reporting_sequence(void) { bus_slave_return_int16( current_momo_state.report_config.transmit_sequence ); } static BYTE report_buffer[RAW_REPORT_MAX_LENGTH]; static void read_report_log_mib(void) { uint16 index = plist_get_int16(0); uint16 offset = plist_get_int16(1); if ( offset >= RAW_REPORT_MAX_LENGTH ) { bus_slave_seterror( kCallbackError ); return; } uint8 length = RAW_REPORT_MAX_LENGTH - offset; if ( length > kBusMaxMessageSize ) length = kBusMaxMessageSize; if ( report_log_read( index, (void*)&report_buffer, 1 ) == 0 ) { // No more entries bus_slave_seterror( kCallbackError ); return; } bus_slave_return_buffer( report_buffer+offset, length ); } static void count_report_log_mib(void) { bus_slave_return_int16( report_log_count() ); } static void clear_report_log_mib(void) { report_log_clear(); } static void handle_report_stream_success(void) { notify_report_success(); } static void handle_report_stream_failure(void) { notify_report_failure(); } DEFINE_MIB_FEATURE_COMMANDS(reporting) { { 0x00, send_report, plist_spec_empty() }, { 0x01, start_scheduled_reporting, plist_spec_empty() }, { 0x02, stop_scheduled_reporting, plist_spec_empty() }, { 0x03, set_reporting_interval, plist_spec(1, false) }, { 0x04, get_reporting_interval, plist_spec_empty() }, { 0x05, set_reporting_route, plist_spec(1, true) }, { 0x06, get_reporting_route, plist_spec(1, false) }, { 0x07, set_reporting_flags, plist_spec(1, false) }, { 0x08, get_reporting_flags, plist_spec_empty() }, { 0x09, set_reporting_aggregates, plist_spec(2, false) }, { 0x0A, get_reporting_aggregates, plist_spec_empty() }, { 0x0B, get_reporting_sequence, plist_spec_empty() }, { 0x0C, build_report, plist_spec_empty() }, { 0x0D, get_report, plist_spec(1, false) }, { 0x0E, get_scheduled_reporting, plist_spec_empty() }, { 0x0F, read_report_log_mib, plist_spec(2, false) }, { 0x10, count_report_log_mib, plist_spec_empty() }, { 0x11, clear_report_log_mib, plist_spec_empty() }, { 0x12, init_report_config, plist_spec_empty() }, { 0x13, set_reporting_apn, plist_spec(0,true) }, { 0x14, get_reporting_apn, plist_spec_empty() }, { 0xF0, handle_report_stream_success, plist_spec_empty() }, { 0xF1, handle_report_stream_failure, plist_spec_empty() } }; DEFINE_MIB_FEATURE(reporting);
Java
<?php /** * Fired during plugin activation. * * This class defines all code necessary to run during the plugin's activation. * * @link https://wordpress.org/plugins/woocommerce-role-based-price/ * @package Role Based Price For WooCommerce * @subpackage Role Based Price For WooCommerce/core * @since 3.0 */ class WooCommerce_Role_Based_Price_Activator { public function __construct() { } /** * Short Description. (use period) * * Long Description. * * @since 1.0.0 */ public static function activate() { require_once( WC_RBP_INC . 'helpers/class-version-check.php' ); require_once( WC_RBP_INC . 'helpers/class-dependencies.php' ); if( WooCommerce_Role_Based_Price_Dependencies(WC_RBP_DEPEN) ) { WooCommerce_Role_Based_Price_Version_Check::activation_check('3.7'); $message = '<h3> <center> ' . __("Thank you for installing <strong>Role Based Price For WooCommerce</strong> : <strong>Version 3.0 </strong>", WC_RBP_TXT) . '</center> </h3>'; $message .= '<p>' . __("We have worked entire 1 year to improve our plugin to best of our ability and we hope you will enjoy working with it. We are always open for your sugestions and feature requests", WC_RBP_TXT) . '</p>'; $message .= '</hr>'; $message .= '<p>' . __("If you have installed <strong>WPRB</strong> for the 1st time or upgrading from <strong> Version 2.8.7</strong> then you will need to update its' settings once again or this plugin will not function properly. ", WC_RBP_TXT); $url = admin_url('admin.php?page=woocommerce-role-based-price-settings'); $message .= '<a href="' . $url . '" class="button button-primary">' . __("Click Here to update the settings", WC_RBP_TXT) . '</a> </p>'; wc_rbp_admin_update($message, 1, 'activate_message', array(), array( 'wraper' => FALSE, 'times' => 1 )); set_transient('_welcome_redirect_wcrbp', TRUE, 60); } else { if( is_plugin_active(WC_RBP_FILE) ) { deactivate_plugins(WC_RBP_FILE); } wp_die(wc_rbp_dependency_message()); } } }
Java