code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
using CatalokoService.Helpers.DTO; using CatalokoService.Helpers.FacebookAuth; using CatalokoService.Models; using System; using System.Web.Mvc; namespace CatalokoService.Controllers { public class HomeController : Controller { CatalokoEntities bd = new CatalokoEntities(); public ActionResult Index() { ViewBag.Title = "Home Page"; return View(); } } }
albertoroque/cataloko
service/CatalokoService/CatalokoService/Controllers/ClienteController/HomeController.cs
C#
gpl-3.0
439
var Util = require( 'findhit-util' ); // ----------------------------------------------------------------------------- // Data handles wizard data into session function Data ( route ) { var session = route.req[ route.router.options.reqSessionKey ]; // If there isn't a `wiz` object on session, just add it if( ! session.wiz ) { session.wiz = {}; } // Save route on this instance this.route = route; // Gather session from session, or just create a new one this.session = session.wiz[ route.id ] || ( session.wiz[ route.id ] = {} ); // Add a control variable for changed state this.changed = false; return this; }; // Export Data module.exports = Data; /* instance methods */ Data.prototype.currentStep = function ( step ) { // If there is no `step` provided, it means that we wan't to get! // Otherwise, lets set it! }; /* Data.prototype.save = function () { }; Data.prototype.destroy = function () { }; */ Data.prototype.getFromStep = function ( step ) { };
brunocasanova/emvici-router
lib/type/wizard/control.js
JavaScript
gpl-3.0
1,035
using System; namespace RadarrAPI { public class ErrorViewModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); } }
jasonla/RadarrAPI.Update
src/RadarrAPI/Models/ErrorViewModel.cs
C#
gpl-3.0
200
/** Copyright (C) 2012 Delcyon, Inc. 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 com.delcyon.capo.protocol.server; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author jeremiah * */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface ClientRequestProcessorProvider { String name(); }
jahnje/delcyon-capo
java/com/delcyon/capo/protocol/server/ClientRequestProcessorProvider.java
Java
gpl-3.0
1,024
<html> <head> <title>datypus</title> <link rel="stylesheet" type="text/css" href="/css/datystyle.css"> <body> <div class="chart"></div> <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script> <script type="text/javascript"> var data = [4, 8, 15, 16, 2, 42]; var x = d3.scale.linear() .domain([0, d3.max(data)]) .range([0, 420]); d3.select(".chart") .selectAll("div") .data(data) .enter().append("div") .style("width", function(d) { return x(d) + "px"; }) .text(function(d) { return d; }); </script> </body> </html>
zbisch/platypus
index.html
HTML
gpl-3.0
738
/* * 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. * * 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, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* * ClusterMembership.java * Copyright (C) 2004 Mark Hall * */ package weka.filters.unsupervised.attribute; import weka.filters.Filter; import weka.filters.UnsupervisedFilter; import weka.filters.unsupervised.attribute.Remove; import weka.clusterers.Clusterer; import weka.clusterers.DensityBasedClusterer; import weka.core.Attribute; import weka.core.Instances; import weka.core.Instance; import weka.core.OptionHandler; import weka.core.Range; import weka.core.FastVector; import weka.core.Option; import weka.core.Utils; import java.util.Enumeration; import java.util.Vector; /** * A filter that uses a clusterer to obtain cluster membership values * for each input instance and outputs them as new instances. The * clusterer needs to be a density-based clusterer. If * a (nominal) class is set, then the clusterer will be run individually * for each class.<p> * * Valid filter-specific options are: <p> * * Full class name of clusterer to use. Clusterer options may be * specified at the end following a -- .(required)<p> * * -I range string <br> * The range of attributes the clusterer should ignore. Note: * the class attribute (if set) is automatically ignored during clustering.<p> * * @author Mark Hall ([email protected]) * @author Eibe Frank * @version $Revision: 1.7 $ */ public class ClusterMembership extends Filter implements UnsupervisedFilter, OptionHandler { /** The clusterer */ protected DensityBasedClusterer m_clusterer = new weka.clusterers.EM(); /** Array for storing the clusterers */ protected DensityBasedClusterer[] m_clusterers; /** Range of attributes to ignore */ protected Range m_ignoreAttributesRange; /** Filter for removing attributes */ protected Filter m_removeAttributes; /** The prior probability for each class */ protected double[] m_priors; /** * Sets the format of the input instances. * * @param instanceInfo an Instances object containing the input instance * structure (any instances contained in the object are ignored - only the * structure is required). * @return true if the outputFormat may be collected immediately * @exception Exception if the inputFormat can't be set successfully */ public boolean setInputFormat(Instances instanceInfo) throws Exception { super.setInputFormat(instanceInfo); m_removeAttributes = null; m_priors = null; return false; } /** * Signify that this batch of input to the filter is finished. * * @return true if there are instances pending output * @exception IllegalStateException if no input structure has been defined */ public boolean batchFinished() throws Exception { if (getInputFormat() == null) { throw new IllegalStateException("No input instance format defined"); } if (outputFormatPeek() == null) { Instances toFilter = getInputFormat(); Instances[] toFilterIgnoringAttributes; // Make subsets if class is nominal if ((toFilter.classIndex() >= 0) && toFilter.classAttribute().isNominal()) { toFilterIgnoringAttributes = new Instances[toFilter.numClasses()]; for (int i = 0; i < toFilter.numClasses(); i++) { toFilterIgnoringAttributes[i] = new Instances(toFilter, toFilter.numInstances()); } for (int i = 0; i < toFilter.numInstances(); i++) { toFilterIgnoringAttributes[(int)toFilter.instance(i).classValue()].add(toFilter.instance(i)); } m_priors = new double[toFilter.numClasses()]; for (int i = 0; i < toFilter.numClasses(); i++) { toFilterIgnoringAttributes[i].compactify(); m_priors[i] = toFilterIgnoringAttributes[i].sumOfWeights(); } Utils.normalize(m_priors); } else { toFilterIgnoringAttributes = new Instances[1]; toFilterIgnoringAttributes[0] = toFilter; m_priors = new double[1]; m_priors[0] = 1; } // filter out attributes if necessary if (m_ignoreAttributesRange != null || toFilter.classIndex() >= 0) { m_removeAttributes = new Remove(); String rangeString = ""; if (m_ignoreAttributesRange != null) { rangeString += m_ignoreAttributesRange.getRanges(); } if (toFilter.classIndex() >= 0) { if (rangeString.length() > 0) { rangeString += (","+(toFilter.classIndex()+1)); } else { rangeString = ""+(toFilter.classIndex()+1); } } ((Remove)m_removeAttributes).setAttributeIndices(rangeString); ((Remove)m_removeAttributes).setInvertSelection(false); ((Remove)m_removeAttributes).setInputFormat(toFilter); for (int i = 0; i < toFilterIgnoringAttributes.length; i++) { toFilterIgnoringAttributes[i] = Filter.useFilter(toFilterIgnoringAttributes[i], m_removeAttributes); } } // build the clusterers if ((toFilter.classIndex() <= 0) || !toFilter.classAttribute().isNominal()) { m_clusterers = DensityBasedClusterer.makeCopies(m_clusterer, 1); m_clusterers[0].buildClusterer(toFilterIgnoringAttributes[0]); } else { m_clusterers = DensityBasedClusterer.makeCopies(m_clusterer, toFilter.numClasses()); for (int i = 0; i < m_clusterers.length; i++) { if (toFilterIgnoringAttributes[i].numInstances() == 0) { m_clusterers[i] = null; } else { m_clusterers[i].buildClusterer(toFilterIgnoringAttributes[i]); } } } // create output dataset FastVector attInfo = new FastVector(); for (int j = 0; j < m_clusterers.length; j++) { if (m_clusterers[j] != null) { for (int i = 0; i < m_clusterers[j].numberOfClusters(); i++) { attInfo.addElement(new Attribute("pCluster_" + j + "_" + i)); } } } if (toFilter.classIndex() >= 0) { attInfo.addElement(toFilter.classAttribute().copy()); } attInfo.trimToSize(); Instances filtered = new Instances(toFilter.relationName()+"_clusterMembership", attInfo, 0); if (toFilter.classIndex() >= 0) { filtered.setClassIndex(filtered.numAttributes() - 1); } setOutputFormat(filtered); // build new dataset for (int i = 0; i < toFilter.numInstances(); i++) { convertInstance(toFilter.instance(i)); } } flushInput(); m_NewBatch = true; return (numPendingOutput() != 0); } /** * Input an instance for filtering. Ordinarily the instance is processed * and made available for output immediately. Some filters require all * instances be read before producing output. * * @param instance the input instance * @return true if the filtered instance may now be * collected with output(). * @exception IllegalStateException if no input format has been defined. */ public boolean input(Instance instance) throws Exception { if (getInputFormat() == null) { throw new IllegalStateException("No input instance format defined"); } if (m_NewBatch) { resetQueue(); m_NewBatch = false; } if (outputFormatPeek() != null) { convertInstance(instance); return true; } bufferInput(instance); return false; } /** * Converts logs back to density values. */ protected double[] logs2densities(int j, Instance in) throws Exception { double[] logs = m_clusterers[j].logJointDensitiesForInstance(in); for (int i = 0; i < logs.length; i++) { logs[i] += Math.log(m_priors[j]); } return logs; } /** * Convert a single instance over. The converted instance is added to * the end of the output queue. * * @param instance the instance to convert */ protected void convertInstance(Instance instance) throws Exception { // set up values double [] instanceVals = new double[outputFormatPeek().numAttributes()]; double [] tempvals; if (instance.classIndex() >= 0) { tempvals = new double[outputFormatPeek().numAttributes() - 1]; } else { tempvals = new double[outputFormatPeek().numAttributes()]; } int pos = 0; for (int j = 0; j < m_clusterers.length; j++) { if (m_clusterers[j] != null) { double [] probs; if (m_removeAttributes != null) { m_removeAttributes.input(instance); probs = logs2densities(j, m_removeAttributes.output()); } else { probs = logs2densities(j, instance); } System.arraycopy(probs, 0, tempvals, pos, probs.length); pos += probs.length; } } tempvals = Utils.logs2probs(tempvals); System.arraycopy(tempvals, 0, instanceVals, 0, tempvals.length); if (instance.classIndex() >= 0) { instanceVals[instanceVals.length - 1] = instance.classValue(); } push(new Instance(instance.weight(), instanceVals)); } /** * Returns an enumeration describing the available options. * * @return an enumeration of all the available options. */ public Enumeration listOptions() { Vector newVector = new Vector(2); newVector. addElement(new Option("\tFull name of clusterer to use (required).\n" + "\teg: weka.clusterers.EM", "W", 1, "-W <clusterer name>")); newVector. addElement(new Option("\tThe range of attributes the clusterer should ignore." +"\n\t(the class attribute is automatically ignored)", "I", 1,"-I <att1,att2-att4,...>")); return newVector.elements(); } /** * Parses the options for this object. Valid options are: <p> * * -W clusterer string <br> * Full class name of clusterer to use. Clusterer options may be * specified at the end following a -- .(required)<p> * * -I range string <br> * The range of attributes the clusterer should ignore. Note: * the class attribute (if set) is automatically ignored during clustering.<p> * * @param options the list of options as an array of strings * @exception Exception if an option is not supported */ public void setOptions(String[] options) throws Exception { String clustererString = Utils.getOption('W', options); if (clustererString.length() == 0) { throw new Exception("A clusterer must be specified" + " with the -W option."); } setDensityBasedClusterer((DensityBasedClusterer)Utils. forName(DensityBasedClusterer.class, clustererString, Utils.partitionOptions(options))); setIgnoredAttributeIndices(Utils.getOption('I', options)); Utils.checkForRemainingOptions(options); } /** * Gets the current settings of the filter. * * @return an array of strings suitable for passing to setOptions */ public String [] getOptions() { String [] clustererOptions = new String [0]; if ((m_clusterer != null) && (m_clusterer instanceof OptionHandler)) { clustererOptions = ((OptionHandler)m_clusterer).getOptions(); } String [] options = new String [clustererOptions.length + 5]; int current = 0; if (!getIgnoredAttributeIndices().equals("")) { options[current++] = "-I"; options[current++] = getIgnoredAttributeIndices(); } if (m_clusterer != null) { options[current++] = "-W"; options[current++] = getDensityBasedClusterer().getClass().getName(); } options[current++] = "--"; System.arraycopy(clustererOptions, 0, options, current, clustererOptions.length); current += clustererOptions.length; while (current < options.length) { options[current++] = ""; } return options; } /** * Returns a string describing this filter * * @return a description of the filter suitable for * displaying in the explorer/experimenter gui */ public String globalInfo() { return "A filter that uses a density-based clusterer to generate cluster " + "membership values; filtered instances are composed of these values " + "plus the class attribute (if set in the input data). If a (nominal) " + "class attribute is set, the clusterer is run separately for each " + "class. The class attribute (if set) and any user-specified " + "attributes are ignored during the clustering operation"; } /** * Returns a description of this option suitable for display * as a tip text in the gui. * * @return description of this option */ public String clustererTipText() { return "The clusterer that will generate membership values for the instances."; } /** * Set the clusterer for use in filtering * * @param newClusterer the clusterer to use */ public void setDensityBasedClusterer(DensityBasedClusterer newClusterer) { m_clusterer = newClusterer; } /** * Get the clusterer used by this filter * * @return the clusterer used */ public DensityBasedClusterer getDensityBasedClusterer() { return m_clusterer; } /** * Returns the tip text for this property * * @return tip text for this property suitable for * displaying in the explorer/experimenter gui */ public String ignoredAttributeIndicesTipText() { return "The range of attributes to be ignored by the clusterer. eg: first-3,5,9-last"; } /** * Gets ranges of attributes to be ignored. * * @return a string containing a comma-separated list of ranges */ public String getIgnoredAttributeIndices() { if (m_ignoreAttributesRange == null) { return ""; } else { return m_ignoreAttributesRange.getRanges(); } } /** * Sets the ranges of attributes to be ignored. If provided string * is null, no attributes will be ignored. * * @param rangeList a string representing the list of attributes. * eg: first-3,5,6-last * @exception IllegalArgumentException if an invalid range list is supplied */ public void setIgnoredAttributeIndices(String rangeList) { if ((rangeList == null) || (rangeList.length() == 0)) { m_ignoreAttributesRange = null; } else { m_ignoreAttributesRange = new Range(); m_ignoreAttributesRange.setRanges(rangeList); } } /** * Main method for testing this class. * * @param argv should contain arguments to the filter: use -h for help */ public static void main(String [] argv) { try { if (Utils.getFlag('b', argv)) { Filter.batchFilterFile(new ClusterMembership(), argv); } else { Filter.filterFile(new ClusterMembership(), argv); } } catch (Exception ex) { System.out.println(ex.getMessage()); } } }
paolopavan/cfr
src/weka/filters/unsupervised/attribute/ClusterMembership.java
Java
gpl-3.0
15,028
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe 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. * * MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.util.concurrent; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Supplier; /** * A supplier with a priority. * * <a href="http://stackoverflow.com/questions/34866757/how-do-i-use-completablefuture-supplyasync-together-with-priorityblockingqueue">stackoverflow</a> * * @author Matthias Eichner * * @param <T> the type of results supplied by this supplier */ public class MCRPrioritySupplier<T> implements Supplier<T>, MCRPrioritizable { private static AtomicLong CREATION_COUNTER = new AtomicLong(0); private Supplier<T> delegate; private int priority; private long created; public MCRPrioritySupplier(Supplier<T> delegate, int priority) { this.delegate = delegate; this.priority = priority; this.created = CREATION_COUNTER.incrementAndGet(); } @Override public T get() { return delegate.get(); } @Override public int getPriority() { return this.priority; } @Override public long getCreated() { return created; } /** * use this instead of {@link CompletableFuture#supplyAsync(Supplier, Executor)} * * This method keep the priority * @param es * @return */ public CompletableFuture<T> runAsync(ExecutorService es) { CompletableFuture<T> result = new CompletableFuture<>(); MCRPrioritySupplier<T> supplier = this; class MCRAsyncPrioritySupplier implements Runnable, MCRPrioritizable, CompletableFuture.AsynchronousCompletionTask { @Override @SuppressWarnings("PMD.AvoidCatchingThrowable") public void run() { try { if (!result.isDone()) { result.complete(supplier.get()); } } catch (Throwable t) { result.completeExceptionally(t); } } @Override public int getPriority() { return supplier.getPriority(); } @Override public long getCreated() { return supplier.getCreated(); } } es.execute(new MCRAsyncPrioritySupplier()); return result; } }
MyCoRe-Org/mycore
mycore-base/src/main/java/org/mycore/util/concurrent/MCRPrioritySupplier.java
Java
gpl-3.0
3,156
<ion-header> <ion-navbar> <ion-title>Login</ion-title> </ion-navbar> </ion-header> <ion-content padding> <!-- Shows error message is socket is not connected. --> <ion-item no-lines *ngIf="!loginManager.loginAvailable()"> <ion-label style="color: #ea6153"> Login service unavailable as cannot connect to server. </ion-label> </ion-item> <!-- Shows a login error message if one exists. --> <ion-item no-lines *ngIf="loginErrorMessage"> <ion-label style="color: #ea6153"> {{loginErrorMessage}} </ion-label> </ion-item> <form (ngSubmit)="doLogin()" [formGroup]="loginForm"> <!-- Username input field --> <ion-item> <ion-label>Username</ion-label> <ion-input type="text" formControlName="username"></ion-input> </ion-item> <!-- Invalid username error --> <ion-item no-lines *ngIf="!loginForm.controls.username.valid && loginForm.controls.username.dirty"> <ion-label style="color: #ea6153"> Invalid username. </ion-label> </ion-item> <!-- Password input field --> <ion-item> <ion-label>Password</ion-label> <ion-input type="password" formControlName="password"></ion-input> </ion-item> <!-- Invalid password error --> <ion-item no-lines *ngIf="!loginForm.controls.password.valid && loginForm.controls.password.dirty"> <ion-label style="color: #ea6153"> Invalid password </ion-label> </ion-item> <br /> <!-- Login button --> <span> <button ion-button type="submit" color="primary" [disabled]="!loginManager.loginAvailable()">Login</button> </span> <!-- Skip login button --> <span *ngIf="!popped"> <button type="button" ion-button color="dark" (click)="doLeavePage()" clear>Skip</button> </span> </form> </ion-content>
castlechef/words
ionic-app/WordsApp/src/pages/login/login.html
HTML
gpl-3.0
1,829
#include <iostream> using namespace std; int main() { int n, x, y; cin >> n; int a[n]; for (int i = 0; i < n; ++i) { cin >> a[i]; } x = a[1] - a[0]; y = a[2] - a[0]; for (int i = 2; i < n; ++i) { x = max(a[i] - a[i - 1], x); y = min(a[i] - a[i - 2], y); } cout << max(x, y); }
yamstudio/Codeforces
400/496A - Minimum Difficulty.cpp
C++
gpl-3.0
309
<?php namespace PrivCode; defined('ROOT_DIR') or die('Forbidden'); /** * Base Model Class * * @package Priv Code * @subpackage Libraries * @category Libraries * @author Supian M * @link http://www.priv-code.com */ use PrivCode\Database\Database; class BaseModel extends Database { public function __construct() { parent::__construct(); } } /* End of file URI.php */ /* Location: ./System/URI/URI.php */
SupianID/Framework
System/BaseModel.php
PHP
gpl-3.0
438
/* * 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 com.power.text.Run; import static com.power.text.dialogs.WebSearch.squerry; import java.awt.Desktop; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import javax.swing.JOptionPane; import static com.power.text.Main.searchbox; /** * * @author thecarisma */ public class WikiSearch { public static void wikisearch(){ String searchqueryw = searchbox.getText(); searchqueryw = searchqueryw.replace(' ', '-'); String squeryw = squerry.getText(); squeryw = squeryw.replace(' ', '-'); if ("".equals(searchqueryw)){ searchqueryw = squeryw ; } else {} String url = "https://www.wikipedia.org/wiki/" + searchqueryw ; try { URI uri = new URL(url).toURI(); Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null; if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) desktop.browse(uri); } catch (URISyntaxException | IOException e) { /* * I know this is bad practice * but we don't want to do anything clever for a specific error */ JOptionPane.showMessageDialog(null, e.getMessage()); // Copy URL to the clipboard so the user can paste it into their browser StringSelection stringSelection = new StringSelection(url); Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard(); clpbrd.setContents(stringSelection, null); // Notify the user of the failure System.out.println("This program just tried to open a webpage." + "\n" + "The URL has been copied to your clipboard, simply paste into your browser to accessWebpage: " + url); } } }
Thecarisma/powertext
Power Text/src/com/power/text/Run/WikiSearch.java
Java
gpl-3.0
2,201
/** * */ package org.jbpt.pm.bpmn; import org.jbpt.pm.IDataNode; /** * Interface class for BPMN Document. * * @author Cindy F�hnrich */ public interface IDocument extends IDataNode { /** * Marks this Document as list. */ public void markAsList(); /** * Unmarks this Document as list. */ public void unmarkAsList(); /** * Checks whether the current Document is a list. * @return */ public boolean isList(); }
BPT-NH/jpbt
jbpt-bpm/src/main/java/org/jbpt/pm/bpmn/IDocument.java
Java
gpl-3.0
447
#include <QtGui/QApplication> #include "xmlparser.h" #include "myfiledialog.h" #include <iostream> #include <QMessageBox> using namespace std; int main(int argc, char *argv[]) { QApplication a(argc, argv);/* MainWindow w; w.show();*/ MyFileDialog my;//Create dialog QString name=my.openFile();//Open dialog, and chose file. We get file path and file name as result cout<<name.toUtf8().constData()<<"Podaci uspješno uèitani!"; return 0; }
etf-sarajevo/etfimagesearch
XMLParser/main.cpp
C++
gpl-3.0
512
// // SuperTuxKart - a fun racing game with go-kart // Copyright (C) 2004-2005 Steve Baker <[email protected]> // Copyright (C) 2006 Joerg Henrichs, Steve Baker // // 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, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #ifndef HEADER_PLAYERKART_HPP #define HEADER_PLAYERKART_HPP #include "config/player.hpp" #include "karts/controller/controller.hpp" class AbstractKart; class Player; class SFXBase; /** PlayerKart manages control events from the player and moves * them to the Kart * * \ingroup controller */ class PlayerController : public Controller { private: int m_steer_val, m_steer_val_l, m_steer_val_r; int m_prev_accel; bool m_prev_brake; bool m_prev_nitro; float m_penalty_time; SFXBase *m_bzzt_sound; SFXBase *m_wee_sound; SFXBase *m_ugh_sound; SFXBase *m_grab_sound; SFXBase *m_full_sound; void steer(float, int); public: PlayerController (AbstractKart *kart, StateManager::ActivePlayer *_player, unsigned int player_index); ~PlayerController (); void update (float); void action (PlayerAction action, int value); void handleZipper (bool play_sound); void collectedItem (const Item &item, int add_info=-1, float previous_energy=0); virtual void skidBonusTriggered(); virtual void setPosition (int p); virtual void finishedRace (float time); virtual bool isPlayerController() const {return true;} virtual bool isNetworkController() const { return false; } virtual void reset (); void resetInputState (); virtual void crashed (const AbstractKart *k) {} virtual void crashed (const Material *m) {} // ------------------------------------------------------------------------ /** Player will always be able to get a slipstream bonus. */ virtual bool disableSlipstreamBonus() const { return false; } // ------------------------------------------------------------------------ /** Callback whenever a new lap is triggered. Used by the AI * to trigger a recomputation of the way to use. */ virtual void newLap(int lap) {} }; #endif
langresser/stk
src/karts/controller/player_controller.hpp
C++
gpl-3.0
3,156
// ArduinoJson - arduinojson.org // Copyright Benoit Blanchon 2014-2019 // MIT License #pragma once #include "../Array/ArrayShortcuts.hpp" #include "../Object/ObjectShortcuts.hpp" namespace ARDUINOJSON_NAMESPACE { template <typename TVariant> class VariantShortcuts : public ObjectShortcuts<TVariant>, public ArrayShortcuts<TVariant> { public: using ArrayShortcuts<TVariant>::createNestedArray; using ArrayShortcuts<TVariant>::createNestedObject; using ArrayShortcuts<TVariant>::operator[]; using ObjectShortcuts<TVariant>::createNestedArray; using ObjectShortcuts<TVariant>::createNestedObject; using ObjectShortcuts<TVariant>::operator[]; }; } // namespace ARDUINOJSON_NAMESPACE
felipehfj/Arduino
libraries/ArduinoJson/src/ArduinoJson/Operators/VariantShortcuts.hpp
C++
gpl-3.0
724
// 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 VTKPEAKMARKERFACTORY_TEST_H_ #define VTKPEAKMARKERFACTORY_TEST_H_ #include "MantidAPI/IPeaksWorkspace.h" #include "MantidAPI/Run.h" #include "MantidDataObjects/PeakShapeSpherical.h" #include "MantidDataObjects/PeaksWorkspace.h" #include "MantidKernel/WarningSuppressions.h" #include "MantidVatesAPI/vtkPeakMarkerFactory.h" #include "MockObjects.h" #include <vtkPolyData.h> #include <vtkSmartPointer.h> #include <cxxtest/TestSuite.h> #include <gmock/gmock.h> #include <gtest/gtest.h> using namespace Mantid; using namespace Mantid::Kernel; using namespace Mantid::API; using namespace Mantid::Geometry; using namespace Mantid::DataObjects; using namespace ::testing; using namespace Mantid::VATES; using Mantid::VATES::vtkPeakMarkerFactory; GNU_DIAG_OFF_SUGGEST_OVERRIDE class MockPeakShape : public Peak { public: MOCK_CONST_METHOD0(getHKL, Mantid::Kernel::V3D(void)); MOCK_CONST_METHOD0(getQLabFrame, Mantid::Kernel::V3D(void)); MOCK_CONST_METHOD0(getQSampleFrame, Mantid::Kernel::V3D(void)); MOCK_CONST_METHOD0(getPeakShape, const Mantid::Geometry::PeakShape &(void)); }; class MockPeak : public Peak { public: MOCK_CONST_METHOD0(getHKL, Mantid::Kernel::V3D(void)); MOCK_CONST_METHOD0(getQLabFrame, Mantid::Kernel::V3D(void)); MOCK_CONST_METHOD0(getQSampleFrame, Mantid::Kernel::V3D(void)); }; class MockPeaksWorkspace : public PeaksWorkspace { using Mantid::DataObjects::PeaksWorkspace::addPeak; public: MOCK_METHOD1(setInstrument, void(const Mantid::Geometry::Instrument_const_sptr &inst)); MOCK_CONST_METHOD0(clone, Mantid::DataObjects::PeaksWorkspace *()); MOCK_CONST_METHOD0(getNumberPeaks, int()); MOCK_METHOD1(removePeak, void(int peakNum)); MOCK_METHOD1(addPeak, void(const IPeak &ipeak)); MOCK_METHOD1(getPeak, Mantid::DataObjects::Peak &(int peakNum)); MOCK_CONST_METHOD1(getPeak, const Mantid::DataObjects::Peak &(int peakNum)); }; GNU_DIAG_ON_SUGGEST_OVERRIDE //===================================================================================== // Functional Tests //===================================================================================== class vtkPeakMarkerFactoryTest : public CxxTest::TestSuite { public: void do_test(MockPeak &peak1, vtkPeakMarkerFactory::ePeakDimensions dims) { FakeProgressAction updateProgress; auto pw_ptr = boost::make_shared<MockPeaksWorkspace>(); MockPeaksWorkspace &pw = *pw_ptr; // Peaks workspace will return 5 identical peaks EXPECT_CALL(pw, getNumberPeaks()).WillOnce(Return(5)); EXPECT_CALL(pw, getPeak(_)).WillRepeatedly(ReturnRef(peak1)); vtkPeakMarkerFactory factory("signal", dims); factory.initialize(pw_ptr); auto set = factory.create(updateProgress); // As the marker type are three axes(2 points), we expect 5*2*3 points // The angle is 0 degrees and the size is 0.3 TS_ASSERT(set); TS_ASSERT_EQUALS(set->GetNumberOfPoints(), 30); TS_ASSERT(testing::Mock::VerifyAndClearExpectations(&pw)); TS_ASSERT(testing::Mock::VerifyAndClearExpectations(&peak1)); } void test_progress_updates() { MockPeak peak1; EXPECT_CALL(peak1, getQLabFrame()).WillRepeatedly(Return(V3D(1, 2, 3))); EXPECT_CALL(peak1, getHKL()).Times(AnyNumber()); EXPECT_CALL(peak1, getQSampleFrame()).Times(AnyNumber()); MockProgressAction mockProgress; // Expectation checks that progress should be >= 0 and <= 100 and called at // least once! EXPECT_CALL(mockProgress, eventRaised(AllOf(Le(100), Ge(0)))) .Times(AtLeast(1)); boost::shared_ptr<MockPeaksWorkspace> pw_ptr = boost::make_shared<MockPeaksWorkspace>(); MockPeaksWorkspace &pw = *pw_ptr; // Peaks workspace will return 5 identical peaks EXPECT_CALL(pw, getNumberPeaks()).WillRepeatedly(Return(5)); EXPECT_CALL(pw, getPeak(_)).WillRepeatedly(ReturnRef(peak1)); vtkPeakMarkerFactory factory("signal", vtkPeakMarkerFactory::Peak_in_Q_lab); factory.initialize(pw_ptr); auto set = factory.create(mockProgress); TSM_ASSERT("Progress Updates not used as expected.", Mock::VerifyAndClearExpectations(&mockProgress)); } void test_q_lab() { MockPeak peak1; EXPECT_CALL(peak1, getQLabFrame()) .Times(5) .WillRepeatedly(Return(V3D(1, 2, 3))); EXPECT_CALL(peak1, getHKL()).Times(0); EXPECT_CALL(peak1, getQSampleFrame()).Times(0); do_test(peak1, vtkPeakMarkerFactory::Peak_in_Q_lab); } void test_q_sample() { MockPeak peak1; EXPECT_CALL(peak1, getQSampleFrame()) .Times(5) .WillRepeatedly(Return(V3D(1, 2, 3))); EXPECT_CALL(peak1, getHKL()).Times(0); EXPECT_CALL(peak1, getQLabFrame()).Times(0); do_test(peak1, vtkPeakMarkerFactory::Peak_in_Q_sample); } void test_hkl() { MockPeak peak1; EXPECT_CALL(peak1, getHKL()).Times(5).WillRepeatedly(Return(V3D(1, 2, 3))); EXPECT_CALL(peak1, getQLabFrame()).Times(0); EXPECT_CALL(peak1, getQSampleFrame()).Times(0); do_test(peak1, vtkPeakMarkerFactory::Peak_in_HKL); } void testIsValidThrowsWhenNoWorkspace() { using namespace Mantid::VATES; using namespace Mantid::API; IMDWorkspace *nullWorkspace = nullptr; Mantid::API::IMDWorkspace_sptr ws_sptr(nullWorkspace); vtkPeakMarkerFactory factory("signal"); TSM_ASSERT_THROWS( "No workspace, so should not be possible to complete initialization.", factory.initialize(ws_sptr), std::runtime_error); } void testCreateWithoutInitializeThrows() { FakeProgressAction progressUpdate; vtkPeakMarkerFactory factory("signal"); TS_ASSERT_THROWS(factory.create(progressUpdate), std::runtime_error); } void testTypeName() { vtkPeakMarkerFactory factory("signal"); TS_ASSERT_EQUALS("vtkPeakMarkerFactory", factory.getFactoryTypeName()); } void testGetPeakRadiusDefault() { vtkPeakMarkerFactory factory("signal"); TS_ASSERT_EQUALS(-1, factory.getIntegrationRadius()); } void testIsPeaksWorkspaceIntegratedDefault() { vtkPeakMarkerFactory factory("signal"); TS_ASSERT_EQUALS(false, factory.isPeaksWorkspaceIntegrated()); } void testGetPeakRadiusWhenNotIntegrated() { auto mockWorkspace = Mantid::Kernel::make_unique<MockPeaksWorkspace>(); const double expectedRadius = -1; // The default // Note that no PeaksRadius property has been set. vtkPeakMarkerFactory factory("signal"); factory.initialize( Mantid::API::IPeaksWorkspace_sptr(std::move(mockWorkspace))); TS_ASSERT_EQUALS(expectedRadius, factory.getIntegrationRadius()); } void testIsPeaksWorkspaceIntegratedWhenNotIntegrated() { auto mockWorkspace = Mantid::Kernel::make_unique<MockPeaksWorkspace>(); // Note that no PeaksRadius property has been set. vtkPeakMarkerFactory factory("signal"); factory.initialize( Mantid::API::IPeaksWorkspace_sptr(std::move(mockWorkspace))); TS_ASSERT_EQUALS( false, factory.isPeaksWorkspaceIntegrated()); // false is the default } void testGetPeakRadiusWhenIntegrated() { auto mockWorkspace = Mantid::Kernel::make_unique<MockPeaksWorkspace>(); const double expectedRadius = 4; mockWorkspace->mutableRun().addProperty("PeakRadius", expectedRadius, true); // Has a PeaksRadius so must // have been processed via // IntegratePeaksMD vtkPeakMarkerFactory factory("signal"); factory.initialize( Mantid::API::IPeaksWorkspace_sptr(std::move(mockWorkspace))); TS_ASSERT_EQUALS(expectedRadius, factory.getIntegrationRadius()); } void testIsPeaksWorkspaceIntegratedWhenIntegrated() { auto mockWorkspace = Mantid::Kernel::make_unique<MockPeaksWorkspace>(); const double expectedRadius = 4; mockWorkspace->mutableRun().addProperty("PeakRadius", expectedRadius, true); // Has a PeaksRadius so must // have been processed via // IntegratePeaksMD vtkPeakMarkerFactory factory("signal"); factory.initialize( Mantid::API::IPeaksWorkspace_sptr(std::move(mockWorkspace))); TS_ASSERT_EQUALS(true, factory.isPeaksWorkspaceIntegrated()); } void testShapeOfSphere() { FakeProgressAction updateProgress; auto pw_ptr = boost::make_shared<MockPeaksWorkspace>(); MockPeaksWorkspace &pw = *pw_ptr; double actualRadius = 2.0; PeakShapeSpherical sphere(actualRadius, Kernel::SpecialCoordinateSystem::QLab); MockPeakShape peak1; EXPECT_CALL(pw, getNumberPeaks()).WillOnce(Return(1)); EXPECT_CALL(pw, getPeak(_)).WillRepeatedly(ReturnRef(peak1)); EXPECT_CALL(peak1, getQLabFrame()).WillRepeatedly(Return(V3D(0., 0., 0.))); EXPECT_CALL(peak1, getPeakShape()).WillRepeatedly(ReturnRef(sphere)); vtkPeakMarkerFactory factory("signal"); factory.initialize(pw_ptr); auto set = factory.create(updateProgress); TS_ASSERT(set); TS_ASSERT_EQUALS(set->GetNumberOfPoints(), 300); for (vtkIdType i = 0; i < set->GetNumberOfPoints(); ++i) { double pt[3]; set->GetPoint(i, pt); double radius = std::sqrt(pt[0] * pt[0] + pt[1] * pt[1] + pt[2] * pt[2]); TS_ASSERT_DELTA(radius, actualRadius, 1.0e-5); } TS_ASSERT(testing::Mock::VerifyAndClearExpectations(&pw)); TS_ASSERT(testing::Mock::VerifyAndClearExpectations(&peak1)); } void testShapeOfEllipsoid() { FakeProgressAction updateProgress; auto pw_ptr = boost::make_shared<MockPeaksWorkspace>(); MockPeaksWorkspace &pw = *pw_ptr; // rotate in 60 degree increments in the x-y plane. for (size_t dir = 0; dir < 6; ++dir) { double theta = 2. * M_PI * static_cast<double>(dir) / 6.; std::vector<Mantid::Kernel::V3D> directions{ {cos(theta), -1. * sin(theta), 0.}, {sin(theta), cos(theta), 0.}, {0., 0., 1.}}; std::vector<double> abcRadii{1., 2., 3.}; // not using these but the constructor requires we set a value. std::vector<double> abcRadiiBackgroundInner{1., 2., 3.}; std::vector<double> abcRadiiBackgroundOuter{1., 2., 3.}; PeakShapeEllipsoid ellipsoid( directions, abcRadii, abcRadiiBackgroundInner, abcRadiiBackgroundOuter, Kernel::SpecialCoordinateSystem::QLab); MockPeakShape peak1; EXPECT_CALL(pw, getNumberPeaks()).WillOnce(Return(1)); EXPECT_CALL(pw, getPeak(_)).WillRepeatedly(ReturnRef(peak1)); EXPECT_CALL(peak1, getQLabFrame()) .WillRepeatedly(Return(V3D(0., 0., 0.))); EXPECT_CALL(peak1, getPeakShape()).WillRepeatedly(ReturnRef(ellipsoid)); vtkPeakMarkerFactory factory("signal"); factory.initialize(pw_ptr); auto set = factory.create(updateProgress); TS_ASSERT(set); TS_ASSERT_EQUALS(set->GetNumberOfPoints(), 300); // Use the standard equation of an ellipsoid to test the resulting // workspace. // https://en.wikipedia.org/wiki/Ellipsoid for (vtkIdType i = 0; i < set->GetNumberOfPoints(); ++i) { double pt[3]; set->GetPoint(i, pt); double rot_x = pt[0] * cos(theta) - pt[1] * sin(theta); double rot_y = pt[0] * sin(theta) + pt[1] * cos(theta); double test = rot_x * rot_x / (abcRadii[0] * abcRadii[0]) + rot_y * rot_y / (abcRadii[1] * abcRadii[1]) + pt[2] * pt[2] / (abcRadii[2] * abcRadii[2]); TS_ASSERT_DELTA(test, 1., 1.0e-5); } TS_ASSERT(testing::Mock::VerifyAndClearExpectations(&pw)); TS_ASSERT(testing::Mock::VerifyAndClearExpectations(&peak1)); } } }; #endif
mganeva/mantid
qt/paraview_ext/VatesAPI/test/vtkPeakMarkerFactoryTest.h
C
gpl-3.0
12,092
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace SimpleDownload { public partial class Downloader : Form { public Downloader() { InitializeComponent(); } public void Form1_Load(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { Download dn=new Download(); dn.DownloadFile(url.Text, @"c:\NewImages\"); } } }
abdesslem/QuikDownloader
src/Downloader.cs
C#
gpl-3.0
618
/** * 表示データ作成用テンプレート(patTemplate) * * LICENSE: This source file is licensed under the terms of the GNU General Public License. * * @package Magic3 Framework * @author 平田直毅(Naoki Hirata) <[email protected]> * @copyright Copyright 2006-2014 Magic3 Project. * @license http://www.gnu.org/copyleft/gpl.html GPL License * @version SVN: $Id$ * @link http://www.magic3.org */ <patTemplate:tmpl name="_widget"> <script type="text/javascript"> //<![CDATA[ function addItem(){ if (!window.confirm('項目を新規追加しますか?')) return false; document.main.act.value = 'add'; document.main.submit(); return true; } function updateItem(){ if (!window.confirm('設定を更新しますか?')) return false; document.main.act.value='update'; document.main.submit(); return true; } function selectItem() { document.main.act.value = 'select'; document.main.submit(); return true; } function listItem(){ document.main.task.value = 'list'; document.main.submit(); return true; } $(function(){ // WYSIWYGエディター作成 m3SetWysiwygEditor('item_html', 450); }); //]]> </script> <div align="center"> <br /> <!-- m3:ErrorMessage --> <form method="post" name="main"> <input type="hidden" name="task" /> <input type="hidden" name="act" /> <input type="hidden" name="serial" value="{SERIAL}" /> <!-- m3:PostParam --> <table width="90%"> <tr><td><label>汎用HTML詳細</label></td> <td align="right"><input type="button" class="button" onclick="listItem();" value="設定一覧" /> </td></tr> <tr><td colspan="2"> <table class="simple-table" style="margin: 0 auto;width:950px;"> <tbody> <tr> <td class="table-headside" width="150">名前</td> <td> <select name="item_id" onchange="selectItem();" {ID_DISABLED}> <option value="0">-- 新規登録 --</option> <patTemplate:tmpl name="title_list"> <option value="{VALUE}" {SELECTED}>{NAME}</option> </patTemplate:tmpl> </select> <patTemplate:tmpl name="item_name_visible" visibility="hidden"> <input type="text" name="item_name" value="{NAME}" size="40" maxlength="40" /> </patTemplate:tmpl> </td> </tr> <tr class="even"> <td class="table-headside">HTML</td> <td><textarea name="item_html">{HTML}</textarea></td> </tr> <tr> <td align="right" colspan="2"> <patTemplate:tmpl name="del_button" visibility="hidden"> <input type="button" class="button" onclick="deleteItem();" value="削除" /> </patTemplate:tmpl> <patTemplate:tmpl name="update_button" visibility="hidden"> <input type="button" class="button" onclick="updateItem();" value="更新" /> </patTemplate:tmpl> <patTemplate:tmpl name="add_button" visibility="hidden"> <input type="button" class="button" onclick="addItem();" value="新規追加" /> </patTemplate:tmpl> </td> </tr> </tbody> </table> </td></tr> </table> </form> </div> </patTemplate:tmpl>
magic3org/magic3
widgets/s/simple_html/include/template/admin.tmpl.html
HTML
gpl-3.0
3,059
reopen ====== The Repo+Open Project Framework Manifest license ------- [GNU GENERAL PUBLIC LICENSE Version 3](http://www.gnu.org/licenses/gpl-3.0-standalone.html)
tmc9031/reopen
README.md
Markdown
gpl-3.0
166
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Case Free Report Groups by View for Revit 2017")] [assembly: AssemblyDescription("Case Free Report Groups by View for Revit 2017")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Case Design, Inc.")] [assembly: AssemblyProduct("Case Free Report Groups by View for Revit 2017")] [assembly: AssemblyCopyright("Copyright © Case Design, Inc. 2014")] [assembly: AssemblyTrademark("Case Design, Inc.")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("372c7cb9-6d40-4880-91ff-16971c7e4661")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2014.6.2.0")] [assembly: AssemblyFileVersion("2014.6.2.0")]
kmorin/case-apps
2017/Case.ReportGroupsByView/Case.ReportGroupsByView/Properties/AssemblyInfo.cs
C#
gpl-3.0
1,571
<?php /* * Micrositio-Phoenix v1.0 Software para gestion de la planeación operativa. * PHP v5 * Autor: Prof. Jesus Antonio Peyrano Luna <[email protected]> * Nota aclaratoria: Este programa se distribuye bajo los terminos y disposiciones * definidos en la GPL v3.0, debidamente incluidos en el repositorio original. * Cualquier copia y/o redistribucion del presente, debe hacerse con una copia * adjunta de la licencia en todo momento. * Licencia: http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License */ header('Content-Type: text/html; charset=iso-8859-1'); //Forzar la codificación a ISO-8859-1. $sufijo= "col_"; echo ' <html> <link rel= "stylesheet" href= "./css/queryStyle.css"></style> <div id="paginado" style="display:none"> <input id="pagina" type="text" value="1"> <input id="pgcolonia" type="text" value=""> <input id="pgestado" type="text" value=""> <input id="pgciudad" type="text" value=""> <input id="pgcp" type="text" value=""> </div> <center><div id= "divbusqueda"> <form id="frmbusqueda" method="post" action=""> <table class="queryTable" colspan= "7"> <tr><td class= "queryRowsnormTR" width ="180">Por nombre de la colonia: </td><td class= "queryRowsnormTR" width ="250"><input type= "text" id= "nomcolonia"></td><td rowspan= "4"><img id="'.$sufijo.'buscar" align= "left" src= "./img/grids/view.png" width= "25" height= "25" alt="Buscar"/></td></tr> <tr><td class= "queryRowsnormTR">Por codigo postal: </td><td class= "queryRowsnormTR"><input type= "text" id= "cpcolonia"></td><td></td></tr> <tr><td class= "queryRowsnormTR">Por ciudad: </td><td class= "queryRowsnormTR"><input type= "text" id= "ciucolonia"></td><td></td></tr> <tr><td class= "queryRowsnormTR">Por estado: </td><td class= "queryRowsnormTR"><input type= "text" id= "estcolonia"></td><td></td></tr> </table> </form> </div></center>'; echo '<div id= "busRes">'; include_once("catColonias.php"); echo '</div> </html>'; ?>
antonio-peyrano/micrositio
v1.1.0/php/frontend/colonias/busColonias.php
PHP
gpl-3.0
2,393
from numpy import sqrt from pacal.standard_distr import NormalDistr, ChiSquareDistr from pacal.distr import Distr, SumDistr, DivDistr, InvDistr from pacal.distr import sqrt as distr_sqrt class NoncentralTDistr(DivDistr): def __init__(self, df = 2, mu = 0): d1 = NormalDistr(mu, 1) d2 = distr_sqrt(ChiSquareDistr(df) / df) super(NoncentralTDistr, self).__init__(d1, d2) self.df = df self.mu = mu def __str__(self): return "NoncentralTDistr(df={0},mu={1})#{2}".format(self.df, self.mu, self.id()) def getName(self): return "NoncT({0},{1})".format(self.df, self.mu) class NoncentralChiSquareDistr(SumDistr): def __new__(cls, df, lmbda = 0): assert df >= 1 d1 = NormalDistr(sqrt(lmbda))**2 if df == 1: return d1 d2 = ChiSquareDistr(df - 1) ncc2 = super(NoncentralChiSquareDistr, cls).__new__(cls, d1, d2) super(NoncentralChiSquareDistr, ncc2).__init__(d1, d2) ncc2.df = df ncc2.lmbda = lmbda return ncc2 def __init__(self, df, lmbda = 0): pass def __str__(self): return "NoncentralChiSquare(df={0},lambda={1})#{2}".format(self.df, self.lmbda, self.id()) def getName(self): return "NoncChi2({0},{1})".format(self.df, self.lmbda) class NoncentralBetaDistr(InvDistr): def __init__(self, alpha = 1, beta = 1, lmbda = 0): d = 1 + ChiSquareDistr(2.0 * beta) / NoncentralChiSquareDistr(2 * alpha, lmbda) super(NoncentralBetaDistr, self).__init__(d) self.alpha = alpha self.beta = beta self.lmbda = lmbda def __str__(self): return "NoncentralBetaDistr(alpha={0},beta={1},lambda={2})#{3}".format(self.alpha, self.beta, self.lmbda, self.id()) def getName(self): return "NoncBeta({0},{1},{2})".format(self.alpha, self.beta, self.lmbda) class NoncentralFDistr(DivDistr): def __init__(self, df1 = 1, df2 = 1, lmbda = 0): d1 = NoncentralChiSquareDistr(df1, lmbda) / df1 d2 = ChiSquareDistr(df2) / df2 super(NoncentralFDistr, self).__init__(d1, d2) self.df1 = df1 self.df2 = df2 self.lmbda = lmbda def __str__(self): return "NoncentralFDistr(df1={0},df2={1},lambda={2})#{3}".format(self.df1, self.df2, self.lmbda, self.id()) def getName(self): return "NoncF({0},{1},{2})".format(self.df1, self.df2, self.lmbda)
ianmtaylor1/pacal
pacal/stats/noncentral_distr.py
Python
gpl-3.0
2,437
IWitness.ErrorsView = Ember.View.extend({ classNames: ["error-bubble"], classNameBindings: ["isError"], isError: function() { return !!this.get("error"); }.property("error") });
djacobs/iWitness
app/views/errors_view.js
JavaScript
gpl-3.0
198
/* * Copyright 2008-2013, ETH Zürich, Samuel Welten, Michael Kuhn, Tobias Langner, * Sandro Affentranger, Lukas Bossard, Michael Grob, Rahul Jain, * Dominic Langenegger, Sonia Mayor Alonso, Roger Odermatt, Tobias Schlueter, * Yannick Stucki, Sebastian Wendland, Samuel Zehnder, Samuel Zihlmann, * Samuel Zweifel * * This file is part of Jukefox. * * Jukefox 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. Jukefox 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 * Jukefox. If not, see <http://www.gnu.org/licenses/>. */ package ch.ethz.dcg.jukefox.model.collection; public class MapTag extends BaseTag { float[] coordsPca2D; private float varianceOverPCA; public MapTag(int id, String name, float[] coordsPca2D, float varianceOverPCA) { super(id, name); this.coordsPca2D = coordsPca2D; this.varianceOverPCA = varianceOverPCA; } public float[] getCoordsPca2D() { return coordsPca2D; } public float getVarianceOverPCA() { return varianceOverPCA; } }
kuhnmi/jukefox
JukefoxModel/src/ch/ethz/dcg/jukefox/model/collection/MapTag.java
Java
gpl-3.0
1,428
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Page to handle actions associated with badges management. * * @package core * @subpackage badges * @copyright 2012 onwards Corplms Learning Solutions Ltd {@link http://www.corplmslms.com/} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @author Yuliya Bozhko <[email protected]> */ require_once(dirname(dirname(__FILE__)) . '/config.php'); require_once($CFG->libdir . '/badgeslib.php'); $badgeid = required_param('id', PARAM_INT); $copy = optional_param('copy', 0, PARAM_BOOL); $activate = optional_param('activate', 0, PARAM_BOOL); $deactivate = optional_param('lock', 0, PARAM_BOOL); $confirm = optional_param('confirm', 0, PARAM_BOOL); $return = optional_param('return', 0, PARAM_LOCALURL); require_login(); $badge = new badge($badgeid); $context = $badge->get_context(); $navurl = new moodle_url('/badges/index.php', array('type' => $badge->type)); if ($badge->type == BADGE_TYPE_COURSE) { require_login($badge->courseid); $navurl = new moodle_url('/badges/index.php', array('type' => $badge->type, 'id' => $badge->courseid)); $PAGE->set_pagelayout('standard'); navigation_node::override_active_url($navurl); } else { $PAGE->set_pagelayout('admin'); navigation_node::override_active_url($navurl, true); } $PAGE->set_context($context); $PAGE->set_url('/badges/action.php', array('id' => $badge->id)); if ($return !== 0) { $returnurl = new moodle_url($return); } else { $returnurl = new moodle_url('/badges/overview.php', array('id' => $badge->id)); } $returnurl->remove_params('awards'); if ($copy) { require_sesskey(); require_capability('moodle/badges:createbadge', $context); $cloneid = $badge->make_clone(); // If a user can edit badge details, they will be redirected to the edit page. if (has_capability('moodle/badges:configuredetails', $context)) { redirect(new moodle_url('/badges/edit.php', array('id' => $cloneid, 'action' => 'details'))); } redirect(new moodle_url('/badges/overview.php', array('id' => $cloneid))); } if ($activate) { require_capability('moodle/badges:configurecriteria', $context); $PAGE->url->param('activate', 1); $status = ($badge->status == BADGE_STATUS_INACTIVE) ? BADGE_STATUS_ACTIVE : BADGE_STATUS_ACTIVE_LOCKED; if ($confirm == 1) { require_sesskey(); list($valid, $message) = $badge->validate_criteria(); if ($valid) { $badge->set_status($status); if ($badge->type == BADGE_TYPE_SITE) { // Review on cron if there are more than 1000 users who can earn a site-level badge. $sql = 'SELECT COUNT(u.id) as num FROM {user} u LEFT JOIN {badge_issued} bi ON u.id = bi.userid AND bi.badgeid = :badgeid WHERE bi.badgeid IS NULL AND u.id != :guestid AND u.deleted = 0'; $toearn = $DB->get_record_sql($sql, array('badgeid' => $badge->id, 'guestid' => $CFG->siteguest)); if ($toearn->num < 1000) { $awards = $badge->review_all_criteria(); $returnurl->param('awards', $awards); } else { $returnurl->param('awards', 'cron'); } } else { $awards = $badge->review_all_criteria(); $returnurl->param('awards', $awards); } redirect($returnurl); } else { echo $OUTPUT->header(); echo $OUTPUT->notification(get_string('error:cannotact', 'badges', $badge->name) . $message); echo $OUTPUT->continue_button($returnurl); echo $OUTPUT->footer(); die(); } } $strheading = get_string('reviewbadge', 'badges'); $PAGE->navbar->add($strheading); $PAGE->set_title($strheading); $PAGE->set_heading($badge->name); echo $OUTPUT->header(); echo $OUTPUT->heading($strheading); $params = array('id' => $badge->id, 'activate' => 1, 'sesskey' => sesskey(), 'confirm' => 1, 'return' => $return); $url = new moodle_url('/badges/action.php', $params); if (!$badge->has_criteria()) { echo $OUTPUT->notification(get_string('error:cannotact', 'badges', $badge->name) . get_string('nocriteria', 'badges')); echo $OUTPUT->continue_button($returnurl); } else { $message = get_string('reviewconfirm', 'badges', $badge->name); echo $OUTPUT->confirm($message, $url, $returnurl); } echo $OUTPUT->footer(); die; } if ($deactivate) { require_sesskey(); require_capability('moodle/badges:configurecriteria', $context); $status = ($badge->status == BADGE_STATUS_ACTIVE) ? BADGE_STATUS_INACTIVE : BADGE_STATUS_INACTIVE_LOCKED; $badge->set_status($status); redirect($returnurl); }
mahalaxmi123/moodleanalytics
badges/action.php
PHP
gpl-3.0
5,588
/* * Copyright (C) 2011 Klaus Reimer <[email protected]> * See LICENSE.md for licensing information. */ package de.ailis.microblinks.l.lctrl.shell; import gnu.getopt.Getopt; import gnu.getopt.LongOpt; import java.util.Arrays; import de.ailis.microblinks.l.lctrl.resources.Resources; /** * Base class for all CLI programs. * * @author Klaus Reimer ([email protected]) */ public abstract class CLI { /** The command-line program name. */ private final String name; /** The short options. */ private final String shortOpts; /** The long options. */ private final LongOpt[] longOpts; /** Debug mode. */ private boolean debug = false; /** * Constructor. * * @param name * The command-line program name. * @param shortOpts * The short options. * @param longOpts * The long options. */ protected CLI(final String name, final String shortOpts, final LongOpt[] longOpts) { this.name = name; this.shortOpts = shortOpts; this.longOpts = longOpts; } /** * Displays command-line help. */ private void showHelp() { System.out.println(Resources.getText("help.txt")); } /** * Displays version information. */ private void showVersion() { System.out.println(Resources.getText("version.txt")); } /** * Displays the help hint. */ protected void showHelpHint() { System.out.println("Use --help to show usage information."); } /** * Prints error message to stderr and then exits with error code 1. * * @param message * The error message. * @param args * The error message arguments. */ protected void error(final String message, final Object... args) { System.err.print(this.name); System.err.print(": "); System.err.format(message, args); System.err.println(); showHelpHint(); System.exit(1); } /** * Processes all command line options. * * @param args * The command line arguments. * @throws Exception * When error occurs. * @return The index of the first non option argument. */ private int processOptions(final String[] args) throws Exception { final Getopt opts = new Getopt(this.name, args, this.shortOpts, this.longOpts); int opt; while ((opt = opts.getopt()) >= 0) { switch (opt) { case 'h': showHelp(); System.exit(0); break; case 'V': showVersion(); System.exit(0); break; case 'D': this.debug = true; break; case '?': showHelpHint(); System.exit(111); break; default: processOption(opt, opts.getOptarg()); } } return opts.getOptind(); } /** * Processes a single option. * * @param option * The option to process * @param arg * The optional option argument * @throws Exception * When an error occurred. */ protected abstract void processOption(final int option, final String arg) throws Exception; /** * Executes the program with the specified arguments. This is called from the run() method after options has been * processed. The specified arguments array only contains the non-option arguments. * * @param args * The non-option command-line arguments. * @throws Exception * When something goes wrong. */ protected abstract void execute(String[] args) throws Exception; /** * Runs the program. * * @param args * The command line arguments. */ public void run(final String[] args) { try { final int commandStart = processOptions(args); execute(Arrays.copyOfRange(args, commandStart, args.length)); } catch (final Exception e) { if (this.debug) { e.printStackTrace(System.err); } error(e.getMessage()); System.exit(1); } } /** * Checks if program runs in debug mode. * * @return True if debug mode, false if not. */ public boolean isDebug() { return this.debug; } }
microblinks/lctrl
src/main/java/de/ailis/microblinks/l/lctrl/shell/CLI.java
Java
gpl-3.0
4,729
/************************************************************************ ** ** @file vistoolspline.cpp ** @author Roman Telezhynskyi <dismine(at)gmail.com> ** @date 18 8, 2014 ** ** @brief ** @copyright ** This source code is part of the Valentina project, a pattern making ** program, whose allow create and modeling patterns of clothing. ** Copyright (C) 2013-2015 Valentina project ** <https://bitbucket.org/dismine/valentina> All Rights Reserved. ** ** Valentina 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. ** ** Valentina 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 Valentina. If not, see <http://www.gnu.org/licenses/>. ** *************************************************************************/ #include "vistoolspline.h" #include <QLineF> #include <QPainterPath> #include <QSharedPointer> #include <Qt> #include <new> #include "../ifc/ifcdef.h" #include "../vgeometry/vabstractcurve.h" #include "../vgeometry/vgeometrydef.h" #include "../vgeometry/vpointf.h" #include "../vgeometry/vspline.h" #include "../vpatterndb/vcontainer.h" #include "../vwidgets/vcontrolpointspline.h" #include "../vwidgets/scalesceneitems.h" #include "../visualization.h" #include "vispath.h" #include "../vmisc/vmodifierkey.h" const int EMPTY_ANGLE = -1; //--------------------------------------------------------------------------------------------------------------------- VisToolSpline::VisToolSpline(const VContainer *data, QGraphicsItem *parent) : VisPath(data, parent), object4Id(NULL_ID), point1(nullptr), point4(nullptr), angle1(EMPTY_ANGLE), angle2(EMPTY_ANGLE), kAsm1(1), kAsm2(1), kCurve(1), isLeftMousePressed(false), p2Selected(false), p3Selected(false), p2(), p3(), controlPoints() { point1 = InitPoint(supportColor, this); point4 = InitPoint(supportColor, this); //-V656 auto *controlPoint1 = new VControlPointSpline(1, SplinePointPosition::FirstPoint, this); controlPoint1->hide(); controlPoints.append(controlPoint1); auto *controlPoint2 = new VControlPointSpline(1, SplinePointPosition::LastPoint, this); controlPoint2->hide(); controlPoints.append(controlPoint2); } //--------------------------------------------------------------------------------------------------------------------- VisToolSpline::~VisToolSpline() { emit ToolTip(QString()); } //--------------------------------------------------------------------------------------------------------------------- void VisToolSpline::RefreshGeometry() { //Radius of point circle, but little bigger. Need handle with hover sizes. const static qreal radius = ScaledRadius(SceneScale(qApp->getCurrentScene()))*1.5; if (object1Id > NULL_ID) { const auto first = Visualization::data->GeometricObject<VPointF>(object1Id); DrawPoint(point1, static_cast<QPointF>(*first), supportColor); if (mode == Mode::Creation) { if (isLeftMousePressed && not p2Selected) { p2 = Visualization::scenePos; controlPoints[0]->RefreshCtrlPoint(1, SplinePointPosition::FirstPoint, p2, static_cast<QPointF>(*first)); if (not controlPoints[0]->isVisible()) { if (QLineF(static_cast<QPointF>(*first), p2).length() > radius) { controlPoints[0]->show(); } else { p2 = static_cast<QPointF>(*first); } } } else { p2Selected = true; } } if (object4Id <= NULL_ID) { VSpline spline(*first, p2, Visualization::scenePos, VPointF(Visualization::scenePos)); spline.SetApproximationScale(m_approximationScale); DrawPath(this, spline.GetPath(), mainColor, lineStyle, Qt::RoundCap); } else { const auto second = Visualization::data->GeometricObject<VPointF>(object4Id); DrawPoint(point4, static_cast<QPointF>(*second), supportColor); if (mode == Mode::Creation) { if (isLeftMousePressed && not p3Selected) { QLineF ctrlLine (static_cast<QPointF>(*second), Visualization::scenePos); ctrlLine.setAngle(ctrlLine.angle()+180); p3 = ctrlLine.p2(); controlPoints[1]->RefreshCtrlPoint(1, SplinePointPosition::LastPoint, p3, static_cast<QPointF>(*second)); if (not controlPoints[1]->isVisible()) { if (QLineF(static_cast<QPointF>(*second), p3).length() > radius) { controlPoints[1]->show(); } else { p3 = static_cast<QPointF>(*second); } } } else { p3Selected = true; } } if (VFuzzyComparePossibleNulls(angle1, EMPTY_ANGLE) || VFuzzyComparePossibleNulls(angle2, EMPTY_ANGLE)) { VSpline spline(*first, p2, p3, *second); spline.SetApproximationScale(m_approximationScale); DrawPath(this, spline.GetPath(), mainColor, lineStyle, Qt::RoundCap); } else { VSpline spline(*first, *second, angle1, angle2, kAsm1, kAsm2, kCurve); spline.SetApproximationScale(m_approximationScale); DrawPath(this, spline.GetPath(), spline.DirectionArrows(), mainColor, lineStyle, Qt::RoundCap); Visualization::toolTip = tr("Use <b>%1</b> for sticking angle!") .arg(VModifierKey::Shift()); emit ToolTip(Visualization::toolTip); } } } } //--------------------------------------------------------------------------------------------------------------------- void VisToolSpline::setObject4Id(const quint32 &value) { object4Id = value; } //--------------------------------------------------------------------------------------------------------------------- void VisToolSpline::SetAngle1(const qreal &value) { angle1 = value; } //--------------------------------------------------------------------------------------------------------------------- void VisToolSpline::SetAngle2(const qreal &value) { angle2 = value; } //--------------------------------------------------------------------------------------------------------------------- void VisToolSpline::SetKAsm1(const qreal &value) { kAsm1 = value; } //--------------------------------------------------------------------------------------------------------------------- void VisToolSpline::SetKAsm2(const qreal &value) { kAsm2 = value; } //--------------------------------------------------------------------------------------------------------------------- void VisToolSpline::SetKCurve(const qreal &value) { kCurve = value; } //--------------------------------------------------------------------------------------------------------------------- QPointF VisToolSpline::GetP2() const { return p2; } //--------------------------------------------------------------------------------------------------------------------- QPointF VisToolSpline::GetP3() const { return p3; } //--------------------------------------------------------------------------------------------------------------------- void VisToolSpline::MouseLeftPressed() { if (mode == Mode::Creation) { isLeftMousePressed = true; } } //--------------------------------------------------------------------------------------------------------------------- void VisToolSpline::MouseLeftReleased() { if (mode == Mode::Creation) { isLeftMousePressed = false; RefreshGeometry(); } }
dismine/Valentina_git
src/libs/vtools/visualization/path/vistoolspline.cpp
C++
gpl-3.0
8,739
<?php /** Copyright 2012-2014-2013 Nick Korbel This file is part of Booked Scheduler. Booked Scheduler 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. Booked Scheduler 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 Booked Scheduler. If not, see <http://www.gnu.org/licenses/>. */ require_once(ROOT_DIR . 'Pages/Admin/ManageConfigurationPage.php'); require_once(ROOT_DIR . 'Presenters/ActionPresenter.php'); class ConfigActions { const Update = 'update'; } class ManageConfigurationPresenter extends ActionPresenter { /** * @var IManageConfigurationPage */ private $page; /** * @var IConfigurationSettings */ private $configSettings; /** * @var */ private $configFilePath; private $deletedSettings = array('password.pattern'); public function __construct(IManageConfigurationPage $page, IConfigurationSettings $settings) { parent::__construct($page); $this->page = $page; $this->configSettings = $settings; $this->configFilePath = ROOT_DIR . 'config/config.php'; $this->configFilePathDist = ROOT_DIR . 'config/config.dist.php'; $this->AddAction(ConfigActions::Update, 'Update'); } public function PageLoad() { $shouldShowConfig = Configuration::Instance()->GetSectionKey(ConfigSection::PAGES, ConfigKeys::PAGES_ENABLE_CONFIGURATION, new BooleanConverter()); $this->page->SetIsPageEnabled($shouldShowConfig); if (!$shouldShowConfig) { Log::Debug('Show configuration UI is turned off. Not displaying the config values'); return; } $configFiles = $this->GetConfigFiles(); $this->page->SetConfigFileOptions($configFiles); $this->HandleSelectedConfigFile($configFiles); $isFileWritable = $this->configSettings->CanOverwriteFile($this->configFilePath); $this->page->SetIsConfigFileWritable($isFileWritable); if (!$isFileWritable) { Log::Debug('Config file is not writable'); return; } Log::Debug('Loading and displaying config file for editing by %s', ServiceLocator::GetServer()->GetUserSession()->Email); $this->BringConfigFileUpToDate(); $settings = $this->configSettings->GetSettings($this->configFilePath); foreach ($settings as $key => $value) { if (is_array($value)) { $section = $key; foreach ($value as $sectionkey => $sectionvalue) { if (!$this->ShouldBeSkipped($sectionkey, $section)) { $this->page->AddSectionSetting(new ConfigSetting($sectionkey, $section, $sectionvalue)); } } } else { if (!$this->ShouldBeSkipped($key)) { $this->page->AddSetting(new ConfigSetting($key, null, $value)); } } } $this->PopulateHomepages(); } private function PopulateHomepages() { $homepageValues = array(); $homepageOutput = array(); $pages = Pages::GetAvailablePages(); foreach ($pages as $pageid => $page) { $homepageValues[] = $pageid; $homepageOutput[] = Resources::GetInstance()->GetString($page['name']); } $this->page->SetHomepages($homepageValues, $homepageOutput); } public function Update() { $shouldShowConfig = Configuration::Instance()->GetSectionKey(ConfigSection::PAGES, ConfigKeys::PAGES_ENABLE_CONFIGURATION, new BooleanConverter()); if (!$shouldShowConfig) { Log::Debug('Show configuration UI is turned off. No updates are allowed'); return; } $configSettings = $this->page->GetSubmittedSettings(); $configFiles = $this->GetConfigFiles(); $this->HandleSelectedConfigFile($configFiles); $newSettings = array(); foreach ($configSettings as $setting) { if (!empty($setting->Section)) { $newSettings[$setting->Section][$setting->Key] = $setting->Value; } else { $newSettings[$setting->Key] = $setting->Value; } } $existingSettings = $this->configSettings->GetSettings($this->configFilePath); $mergedSettings = array_merge($existingSettings, $newSettings); foreach ($this->deletedSettings as $deletedSetting) { if (array_key_exists($deletedSetting, $mergedSettings)) { unset($mergedSettings[$deletedSetting]); } } Log::Debug("Saving %s settings", count($configSettings)); $this->configSettings->WriteSettings($this->configFilePath, $mergedSettings); Log::Debug('Config file saved by %s', ServiceLocator::GetServer()->GetUserSession()->Email); } private function ShouldBeSkipped($key, $section = null) { if ($section == ConfigSection::DATABASE || $section == ConfigSection::API) { return true; } if (in_array($key, $this->deletedSettings)) { return true; } switch ($key) { case ConfigKeys::INSTALLATION_PASSWORD: case ConfigKeys::PAGES_ENABLE_CONFIGURATION && $section == ConfigSection::PAGES: return true; default: return false; } } private function GetConfigFiles() { $files = array(new ConfigFileOption('config.php', '')); $pluginBaseDir = ROOT_DIR . 'plugins/'; if ($h = opendir($pluginBaseDir)) { while (false !== ($entry = readdir($h))) { $pluginDir = $pluginBaseDir . $entry; if (is_dir($pluginDir) && $entry != "." && $entry != "..") { $plugins = scandir($pluginDir); foreach ($plugins as $plugin) { if (is_dir("$pluginDir/$plugin") && $plugin != "." && $plugin != ".." && strpos($plugin,'Example') === false) { $configFiles = array_merge(glob("$pluginDir/$plugin/*.config.php"), glob("$pluginDir/$plugin/*.config.dist.php")); if (count($configFiles) > 0) { $files[] = new ConfigFileOption("$entry-$plugin", "$entry/$plugin"); } } } } } closedir($h); } return $files; } private function HandleSelectedConfigFile($configFiles) { $requestedConfigFile = $this->page->GetConfigFileToEdit(); if (!empty($requestedConfigFile)) { /** @var $file ConfigFileOption */ foreach ($configFiles as $file) { if ($file->Location == $requestedConfigFile) { $this->page->SetSelectedConfigFile($requestedConfigFile); $rootDir = ROOT_DIR . 'plugins/' . $requestedConfigFile; $distFile = glob("$rootDir/*config.dist.php"); $configFile = glob("$rootDir/*config.php"); if (count($distFile) == 1 && count($configFile) == 0) { copy($distFile[0], str_replace('.dist', '', $distFile[0])); } $configFile = glob("$rootDir/*config.php"); $this->configFilePath = $configFile[0]; $this->configFilePathDist = str_replace('.php', '.dist.php', $configFile[0]); } } } } private function BringConfigFileUpToDate() { if (!file_exists($this->configFilePathDist)) { return; } $configurator = new Configurator(); $configurator->Merge($this->configFilePath, $this->configFilePathDist); } } class ConfigFileOption { public function __construct($name, $location) { $this->Name = $name; $this->Location = $location; } } class ConfigSetting { public $Key; public $Section; public $Value; public $Type; public $Name; public function __construct($key, $section, $value) { $key = trim($key); $section = trim($section); $value = trim($value); $this->Name = $this->encode($key) . '|' . $this->encode($section); $this->Key = $key; $this->Section = $section; $this->Value = $value . ''; $type = strtolower($value) == 'true' || strtolower($value) == 'false' ? ConfigSettingType::Boolean : ConfigSettingType::String; $this->Type = $type; if ($type == ConfigSettingType::Boolean) { $this->Value = strtolower($this->Value); } } public static function ParseForm($key, $value) { $k = self::decode($key); $keyAndSection = explode('|', $k); return new ConfigSetting($keyAndSection[0], $keyAndSection[1], $value); } private static function encode($value) { return str_replace('.', '__', $value); } private static function decode($value) { return str_replace('__', '.', $value); } } class ConfigSettingType { const String = 'string'; const Boolean = 'boolean'; }
ksdtech/booked
Presenters/Admin/ManageConfigurationPresenter.php
PHP
gpl-3.0
8,379
#include <stdlib.h> #include <stdio.h> #include "array_heap.h" int array_init(array* arr, int size) { arr->data = realloc(NULL, sizeof(void*) * size); if (0 == (size_t)arr->data) { return -1; } arr->length = size; arr->index = 0; return 0; } int array_push(array* arr, void* data) { ((size_t*)arr->data)[arr->index] = (size_t)data; arr->index += 1; if (arr->index >= arr->length) { if (-1 == array_grow(arr, arr->length * 2)) { return -1; } } return arr->index - 1; } int array_grow(array* arr, int size) { if (size <= arr->length) { return -1; } arr->data = realloc(arr->data, sizeof(void*) * size); if (-1 == (size_t)arr->data) { return -1; } arr->length = size; return 0; } void array_free(array* arr, void (*free_element)(void*)) { int i; for (i = 0; i < arr->index; i += 1) { free_element((void*)((size_t*)arr->data)[i]); } free(arr->data); arr->index = -1; arr->length = 0; arr->data = NULL; }
kristov/vroom
module/array_heap.c
C
gpl-3.0
989
### Bienvenida Hora de inicio: 09:12 a.m. El Lic. Eduardo Holguín da la bienvenida y le concede la palabra al Arq. Rafael Pérez Fernández. ### Introducción El Arq. Rafael Pérez Fernández expone los objetivos del Plan Estratégico Metropolitano. Introducción por Lic. Rodrigo González Morales: Explicación de los resultados de la mesa anterior, presentación de los indicadores y futuros tendenciales de cada uno de los problemas de cada temática. El Arq. Rafael Pérez explica la mecánica del evento. Que en la elección de futuro deseable se llenará un formato de manera individual; luego se realizarán rondas para enriquecer de 15 minutos tomando nota de forma conjunta e interactiva. Al final se hará la integración y propuestas de objetivos y metas. ### Visión – Futuro Deseable Problema 1. Falta de seguridad * Una policía de carrera eficiente, con educación y con sueldos y prestaciones remunerados, sociedad apoyada por esta misma. * Disminuir la tasa de delitos 60 %, en la zona metropolita así como la victimización de los habitantes. * Abatir los índices de criminalidad; Recuperamos la confianza de la población. * Personal confiable y con enfoque en prevención de delito. * Confianza en todos los sectores, mínima inseguridad. * Una ciudadanía cívicamente educada. * Alto índice de confianza en la población, confianza en autoridades e instituciones. * Autoridades gozan de credibilidad, seguridad de las mujeres. * Torreón incluyente para inversión mano de obra remunerada, respeto a los recursos naturales, zona metro segura. * Contar y cumplir con indicadores de seguridad, cumplir 95 % de indicadores, fortalecer cultura de la legalidad. Prevención del delito. * Una vinculación con las instituciones educativas para poder regularizar los recursos. Participación ciudadana en la prevención social. * Erradicar la corrupción en las instancias de seguridad. * Que se llenen los demás espacios con cosas concretas. Y visión concreta para poder aterrizar. Problema 2. Ser municipio saludable * Especialistas atendiendo a las personas enfermas. * Disminuir los índices de morbilidad, acceso a salud de calidad para todos. * Prevención de enfermedades, eficiente infraestructura en sector salud. * Cultura de prevención, además de alta calidad en atención médica. * Zona metropolitana física y clínicamente sana. * Llegar a tener índices bajos y controlados. * Aumento de atención a la población, calidad en servicio público y control sanitario. * Municipio saludable. * Programas Federales, Estatales y Municipales coordinados para que se apliquen en el área de salud necesarias. * Ciudadanos conscientes. * Lograr acceso completo por parte de todos los ciudadanos a los servicios de salud. Lograr un estándar a nivel mundial. * Lograr el estándar de municipio saludable, respetando las leyes y reglamentos. Problema 3. Vocación educativa para una adecuada vinculación con el desarrollo social. * Incrementar en las escuelas un análisis de vocación profesional acorde con el desarrollo económico de la Ciudad. * Combatir rezago escolar, aumentar la calidad en la formación de investigadores en áreas científicas. * Multiplicación de programas de vinculación con la población, redirigir la atención a grupos de todo tipo, vulnerable, no vulnerable. * Se cumple con los estándares de calidad de la UNESCO, que se escoja una vocación universitaria específica en la comarca lagunera. * La zona metro opera con 4 dimensiones sociedad, instituciones de educación, gobierno y empresas. * Sustento académico desde el kínder a la universidad, de la misma forma sustento para desarrollarse. * Aumento en la calidad de la educación, aumentar las licenciaturas a nivel humanístico. * Enfoque de vocación en áreas que la sociedad requiere. * Las universidades se sustentan en base al desarrollo social * Formar ciudadanos del mundo respetuoso. * Vincular al educador con el educando. (Se menciona ejemplo de las adolescentes embarazadas en la actualidad ) Existe una desvinculación entre el profesor y el alumno, la educación atiende este aspecto. * Formación de ciudadanos responsables * Desde kinder y todos niveles se incluya curricular desde valores trabajo en equipo. * Formación de ciudadanos responsables. * Disminuir los índices de deserción escolar en secundaria y preparatoria. * Nota: Se integra al temas ciudadanos responsables que denuncian los atropellos Problema 4. Problema * Desarrolla en escuelas elementos de arte como musca, pintura. * Incrementa la calidad y cantidad de programas culturas y espacios públicos en un 50%, aumenta las bibliotecas e inmuebles históricos. * Multiplicación de espacios en cada barrio de la ciudad. Promoción de actividades de convivencia. * Dos niveles de infraestructura cultural. Todo tipo de artes, espacio de aprendizaje, otro espacio de disfrute. * Ser líder en desarrollo cultural y deportivo en el país. * Espacios distribuidos culturales y que se atienda las diferentes necesidades. * Alto porcentaje con acceso a centros culturales integrales. Promotores culturales y creadores. Acceso gratuito. * Identidad del ciudadano con su ciudad. * Se proyecta como zona turística espacios limpios cuidados, colonias espacios públicos accesibles. * Fusión entre respeto de la modernidad con raíces. * Disminuir la brecha cultural y deportiva, infraestructura que promueva la cultura. * Adaptada con accesibilidad y atraer a turismo, discapacidad de lugares denotar desarrollo del área. Problema 5. Problema * Compromiso a trabajar con grupos vulnerables, aumentar pensión de jubilados. * Disminuir índices de pobreza. * Vinculación de los programas institucionales de organismos públicos específicos. * Infraestructura para movilidad, atención a personas vulnerables, cultura de ayuda. * Reducción en las carencias, atención completa. * Fomento en las ONG y mayor apoyo. * Centros especializados para cada grupo vulnerable. * Programas sociales para disminuir grupos vulnerables. * Acceso a los servicios de salud al 100% mecanismos de bienestar físico. * Trabajo conjunto entre sociedad civil, gobierno y empresas, se trabaje con la sociedad, apego a las leyes * Identifica y monitorea a grupos vulnerables. La mesa termino antes de lo previsto la actividad por lo que se tomo un breve receso. ### Propuesta de objetivos y metas Se integraron las visiones y se agregaron a las que ya se tenían por parte de la mesa. Se llenaron los formatos. ### Conclusión Se establecieron las conclusiones de la mesa. ### Agradecimiento y despedida Hora de término: 01:08 p.m.
TRCIMPLAN/PEM
lib/Mesa2/CTDesarrolloSocialMinuta.md
Markdown
gpl-3.0
6,640
from ert.cwrap import CWrapper, BaseCClass from ert.enkf import ENKF_LIB from ert.util import StringList class SummaryKeyMatcher(BaseCClass): def __init__(self): c_ptr = SummaryKeyMatcher.cNamespace().alloc() super(SummaryKeyMatcher, self).__init__(c_ptr) def addSummaryKey(self, key): assert isinstance(key, str) return SummaryKeyMatcher.cNamespace().add_key(self, key) def __len__(self): return SummaryKeyMatcher.cNamespace().size(self) def __contains__(self, key): return SummaryKeyMatcher.cNamespace().match_key(self, key) def isRequired(self, key): """ @rtype: bool """ return SummaryKeyMatcher.cNamespace().is_required(self, key) def keys(self): """ @rtype: StringList """ return SummaryKeyMatcher.cNamespace().keys(self) def free(self): SummaryKeyMatcher.cNamespace().free(self) cwrapper = CWrapper(ENKF_LIB) cwrapper.registerObjectType("summary_key_matcher", SummaryKeyMatcher) SummaryKeyMatcher.cNamespace().alloc = cwrapper.prototype("c_void_p summary_key_matcher_alloc()") SummaryKeyMatcher.cNamespace().free = cwrapper.prototype("void summary_key_matcher_free(summary_key_matcher)") SummaryKeyMatcher.cNamespace().size = cwrapper.prototype("int summary_key_matcher_get_size(summary_key_matcher)") SummaryKeyMatcher.cNamespace().add_key = cwrapper.prototype("void summary_key_matcher_add_summary_key(summary_key_matcher, char*)") SummaryKeyMatcher.cNamespace().match_key = cwrapper.prototype("bool summary_key_matcher_match_summary_key(summary_key_matcher, char*)") SummaryKeyMatcher.cNamespace().keys = cwrapper.prototype("stringlist_obj summary_key_matcher_get_keys(summary_key_matcher)") SummaryKeyMatcher.cNamespace().is_required = cwrapper.prototype("bool summary_key_matcher_summary_key_is_required(summary_key_matcher, char*)")
iLoop2/ResInsight
ThirdParty/Ert/devel/python/python/ert/enkf/summary_key_matcher.py
Python
gpl-3.0
1,882
<?php /** * @module wysiwyg Admin * @version see info.php of this module * @authors Dietrich Roland Pehlke * @copyright 2010-2011 Dietrich Roland Pehlke * @license GNU General Public License * @license terms see info.php of this module * @platform see info.php of this module * @requirements PHP 5.2.x and higher */ // include class.secure.php to protect this file and the whole CMS! if (defined('WB_PATH')) { include(WB_PATH.'/framework/class.secure.php'); } else { $oneback = "../"; $root = $oneback; $level = 1; while (($level < 10) && (!file_exists($root.'/framework/class.secure.php'))) { $root .= $oneback; $level += 1; } if (file_exists($root.'/framework/class.secure.php')) { include($root.'/framework/class.secure.php'); } else { trigger_error(sprintf("[ <b>%s</b> ] Can't include class.secure.php!", $_SERVER['SCRIPT_NAME']), E_USER_ERROR); } } // end include class.secure.php // end include class.secure.php $database->query("DROP TABLE IF EXISTS `".TABLE_PREFIX."mod_editor_admin`"); $table = TABLE_PREFIX ."mod_wysiwyg_admin"; $database->query("DROP TABLE IF EXISTS `".$table."`"); $database->query("DELETE from `".TABLE_PREFIX."sections` where `section_id`='-1' AND `page_id`='-120'"); $database->query("DELETE from `".TABLE_PREFIX."mod_wysiwyg` where `section_id`='-1' AND `page_id`='-120'"); ?>
LEPTON-project/LEPTON_1
upload/modules/wysiwyg_admin/uninstall.php
PHP
gpl-3.0
1,358
#include <cmath> #include <iostream> #include <fstream> #include <cstdlib> #include "params.h" #include "pdg_name.h" #include "parameters.h" #include "LeptonMass.h" //#include "jednostki.h" #include "grv94_bodek.h" #include "dis_cr_sec.h" #include "fragmentation.h" #include "vect.h" #include "charge.h" #include "event1.h" #include <TMCParticle.h> #include <TPythia6.h> TPythia6 *pythia2 = new TPythia6 (); extern "C" int pycomp_ (const int *); void dishadr (event & e, bool current, double hama, double entra) { //////////////////////////////////////////////////////////////////////////// // Setting Pythia parameters // Done by Jaroslaw Nowak ////////////////////////////////////////////// //stabilne pi0 pythia2->SetMDCY (pycomp_ (&pizero), 1, 0); //C Thorpe: Adding Hyperons as stable dis particles pythia2->SetMDCY (pycomp_ (&Lambda), 1, 0); pythia2->SetMDCY (pycomp_ (&Sigma), 1, 0); pythia2->SetMDCY (pycomp_ (&SigmaP), 1, 0); pythia2->SetMDCY (pycomp_ (&SigmaM), 1, 0); // C Thorpe: Stablize kaons pythia22->SetMDCY ( pycomp_ (&DIS_PDG::Kplus) , 1, 0); pythia22->SetMDCY ( pycomp_ (&DIS_PDG::Kzero) , 1, 0); pythia22->SetMDCY ( pycomp_ (&DIS_PDG::Kminus) , 1, 0); pythia2->SetMSTU (20, 1); //advirsory warning for unphysical flavour switch off pythia2->SetMSTU (23, 1); //It sets counter of errors at 0 pythia2->SetMSTU (26, 0); //no warnings printed // PARJ(32)(D=1GeV) is, with quark masses added, used to define the minimum allowable enrgy of a colour singlet parton system pythia2->SetPARJ (33, 0.1); // PARJ(33)-PARJ(34)(D=0.8GeV, 1.5GeV) are, with quark masses added, used to define the remaining energy below which //the fragmentation of a parton system is stopped and two final hadrons formed. pythia2->SetPARJ (34, 0.5); pythia2->SetPARJ (35, 1.0); //PARJ(36) (D=2.0GeV) represents the dependence of the mass of final quark pair for defining the stopping point of the //fragmentation. Strongly corlated with PARJ(33-35) pythia2->SetPARJ (37, 1.); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1 //MSTJ(17) (D=2) number of attemps made to find two hadrons that have a combined mass below the cluster mass and thus allow // a cluster to decay rather than collaps pythia2->SetMSTJ (18, 3); //do not change ///////////////////////////////////////////////// // End of setting Pythia parameters //////////////////////////////////////////////// double Mtrue = (PDG::mass_proton+PDG::mass_neutron)/2; double Mtrue2 = Mtrue * Mtrue; double W2 = hama * hama; double nu = entra; vect nuc0 = e.in[1]; vect nu0 = e.in[0]; nu0.boost (-nuc0.speed ()); //neutrino 4-momentum in the target rest frame vec nulab = vec (nu0.x, nu0.y, nu0.z); //can be made simpler ??? int lepton = e.in[0].pdg; int nukleon = e.in[1].pdg; double m = lepton_mass (abs (lepton), current); //mass of the given lepton (see pgd header file) double m2 = m * m; double E = nu0.t; double E2 = E * E; int nParticle = 0; int nCharged = 0; int NPar = 0; Pyjets_t *pythiaParticle; //deklaracja event recordu double W1 = hama / GeV; //W1 w GeV-ach potrzebne do Pythii while (NPar < 5) { hadronization (E, hama, entra, m, lepton, nukleon, current); pythiaParticle = pythia2->GetPyjets (); NPar = pythia2->GetN (); } //////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////Kinematics /////////////////////////////////////////////// //////////// The input data is: neutrinoo 4-momentum, invariant hadronic mass and energy transfer //////////// With this data the kinematics is resolved //////////////////////////////////////////////////// /////////// We know that nu^2-q^2= (k-k')^2=m^2-2*k.k'= m^2-2*E*(E-nu)+ 2*E*sqrt((E-nu)^2-m^2)*cos theta /////////// /////////// (M+nu)^2-q^2=W^2 //////////// //////////// (k-q)^2= m^2 = nu^2-q^2 -2*E*nu + 2*E*q*cos beta ///////////// ///////////// theta is an angle between leptons and beta is an angle between neutrino and momentum transfer /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////// Of course it is not necessary to calculate vectors k' and q separately because of momentum conservation /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// double q = sqrt (kwad (Mtrue + nu) - W2); double kprim = sqrt (kwad (E - nu) - m2); double cth = (E2 + kprim * kprim - q * q) / 2 / E / kprim; vec kkprim; //the unit vector in the direction of scattered lepton kinfinder (nulab, kkprim, cth); //hopefully should produce kkprim kkprim = kprim * kkprim; //multiplied by its length vect lepton_out = vect (E - nu, kkprim.x, kkprim.y, kkprim.z); vec momtran = nulab - kkprim; vec hadrspeed = momtran / sqrt (W2 + q * q); nParticle = pythia2->GetN (); if (nParticle == 0) { cout << "nie ma czastek" << endl; cin.get (); } vect par[100]; double ks[100]; //int czy double ??? par[0] = lepton_out; //powrot do ukladu spoczywajacej tarczy par[0] = par[0].boost (nuc0.speed ()); //ok particle lept (par[0]); if (current == true && lepton > 0) { lept.pdg = lepton - 1; } if (current == true && lepton < 0) { lept.pdg = lepton + 1; } if (current == false) { lept.pdg = lepton; } e.out.push_back (lept); //final lepton; ok for (int i = 0; i < nParticle; i++) { par[i].t = pythiaParticle->P[3][i] * GeV; par[i].x = pythiaParticle->P[0][i] * GeV; par[i].y = pythiaParticle->P[1][i] * GeV; par[i].z = pythiaParticle->P[2][i] * GeV; rotation (par[i], momtran); ks[i] = pythiaParticle->K[0][i]; par[i] = par[i].boost (hadrspeed); //correct direction ??? par[i] = par[i].boost (nuc0.speed ()); particle part (par[i]); part.ks = pythiaParticle->K[0][i]; part.pdg = pythiaParticle->K[1][i]; part.orgin = pythiaParticle->K[2][i]; e.temp.push_back (part); if (ks[i] == 1) //condition for a real particle in the final state { e.out.push_back (part); } } }
NuWro/nuwro
src/dis/dishadr.cc
C++
gpl-3.0
6,276
package example; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.junit.Test; import com.piedra.excel.annotation.ExcelExport; import com.piedra.excel.util.ExcelExportor; /** * @Description: Excel导出工具 例子程序 * @Creator:linwb 2014-12-19 */ public class ExcelExportorExample { public static void main(String[] args) { new ExcelExportorExample().testSingleHeader(); new ExcelExportorExample().testMulHeaders(); } /** * @Description: 测试单表头 * @History * 1. 2014-12-19 linwb 创建方法 */ @Test public void testSingleHeader(){ OutputStream out = null; try { out = new FileOutputStream(new File("C://EXCEL-EXPORT-TEST.xls")); List<ExcelRow> stus = new ArrayList<ExcelRow>(); for(int i=0; i<11120; i++){ stus.add(new ExcelRow()); } new ExcelExportor<ExcelRow>().exportExcel("测试单表头", stus, out); System.out.println("excel导出成功!"); } catch (Exception e) { e.printStackTrace(); } finally { if(out!=null){ try { out.close(); } catch (IOException e) { //Ignore.. } finally{ out = null; } } } } /** * @Description: 测试多表头 * @History * 1. 2014-12-19 linwb 创建方法 */ @Test public void testMulHeaders(){ OutputStream out = null; try { out = new FileOutputStream(new File("C://EXCEL-EXPORT-TEST-MULTIHEADER.xls")); List<ExcelRowForMultiHeaders> stus = new ArrayList<ExcelRowForMultiHeaders>(); for(int i=0; i<1120; i++){ stus.add(new ExcelRowForMultiHeaders()); } new ExcelExportor<ExcelRowForMultiHeaders>().exportExcel("测试多表头", stus, out); System.out.println("excel导出成功!"); } catch (Exception e) { e.printStackTrace(); } finally { if(out!=null){ try { out.close(); } catch (IOException e) { //Ignore.. } finally{ out = null; } } } } } /** * @Description: Excel的一行对应的JavaBean类 * @Creator:linwb 2014-12-19 */ class ExcelRow { @ExcelExport(header="姓名",colWidth=50) private String name="AAAAAAAAAAASSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"; @ExcelExport(header="年龄") private int age=80; /** 这个属性没别注解,那么将不会出现在导出的excel文件中*/ private String clazz="SSSSSSSSS"; @ExcelExport(header="国家") private String country="RRRRRRR"; @ExcelExport(header="城市") private String city="EEEEEEEEE"; @ExcelExport(header="城镇") private String town="WWWWWWW"; /** 这个属性没别注解,那么将不会出现在导出的excel文件中*/ private String common="DDDDDDDD"; /** 如果colWidth <= 0 那么取默认的 15 */ @ExcelExport(header="出生日期",colWidth=-1) private Date birth = new Date(); public ExcelRow(){ } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getClazz() { return clazz; } public void setClazz(String clazz) { this.clazz = clazz; } public String getCommon() { return common; } public void setCommon(String common) { this.common = common; } public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getTown() { return town; } public void setTown(String town) { this.town = town; } } /** * @Description: Excel的一行对应的JavaBean类 * @Creator:linwb 2014-12-19 */ class ExcelRowForMultiHeaders { @ExcelExport(header="姓名",colspan="1",rowspan="3") private String name="无名氏"; @ExcelExport(header="省份,国家",colspan="1,5",rowspan="1,2") private String province="福建省"; @ExcelExport(header="城市",colspan="1",rowspan="1") private String city="福建省"; @ExcelExport(header="城镇",colspan="1",rowspan="1") private String town="不知何处"; @ExcelExport(header="年龄,年龄和备注",colspan="1,2",rowspan="1,1") private int age=80; @ExcelExport(header="备注?",colspan="1",rowspan="1") private String common="我是备注,我是备注"; @ExcelExport(header="我的生日",colspan="1",rowspan="3",datePattern="yyyy-MM-dd HH:mm:ss") private Date birth = new Date(); /** 这个属性没别注解,那么将不会出现在导出的excel文件中*/ private String clazz="我不会出现的,除非你给我 @ExcelExport 注解标记"; public ExcelRowForMultiHeaders(){ } public String getClazz() { return clazz; } public void setClazz(String clazz) { this.clazz = clazz; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getCommon() { return common; } public void setCommon(String common) { this.common = common; } public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getTown() { return town; } public void setTown(String town) { this.town = town; } }
webinglin/excelExportor
src/test/java/example/ExcelExportorExample.java
Java
gpl-3.0
6,820
/*************************************************************************** * Project file: NPlugins - NCore - BasicHttpClient.java * * Full Class name: fr.ribesg.com.mojang.api.http.BasicHttpClient * * * * Copyright (c) 2012-2014 Ribesg - www.ribesg.fr * * This file is under GPLv3 -> http://www.gnu.org/licenses/gpl-3.0.txt * * Please contact me at ribesg[at]yahoo.fr if you improve this file! * ***************************************************************************/ package fr.ribesg.com.mojang.api.http; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.Proxy; import java.net.URL; import java.util.List; public class BasicHttpClient implements HttpClient { private static BasicHttpClient instance; private BasicHttpClient() { } public static BasicHttpClient getInstance() { if (instance == null) { instance = new BasicHttpClient(); } return instance; } @Override public String post(final URL url, final HttpBody body, final List<HttpHeader> headers) throws IOException { return this.post(url, null, body, headers); } @Override public String post(final URL url, Proxy proxy, final HttpBody body, final List<HttpHeader> headers) throws IOException { if (proxy == null) { proxy = Proxy.NO_PROXY; } final HttpURLConnection connection = (HttpURLConnection)url.openConnection(proxy); connection.setRequestMethod("POST"); for (final HttpHeader header : headers) { connection.setRequestProperty(header.getName(), header.getValue()); } connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); final DataOutputStream writer = new DataOutputStream(connection.getOutputStream()); writer.write(body.getBytes()); writer.flush(); writer.close(); final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; final StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); response.append('\r'); } reader.close(); return response.toString(); } }
cnaude/NPlugins
NCore/src/main/java/fr/ribesg/com/mojang/api/http/BasicHttpClient.java
Java
gpl-3.0
2,563
/* Fomalhaut Copyright (C) 2014 mtgto 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/>. */ #import <RoutingHTTPServer/RoutingConnection.h> @interface RoutingConnection (Secure) @end
mtgto/Fomalhaut
FomalhautOSX/FomalhautOSX/RoutingConnection+Secure.h
C
gpl-3.0
761
#!/usr/bin/env node /*jshint -W100*/ 'use strict'; /** * ニコニコ動画ログインサンプル * * 以下のusernameとpasswordを書き換えてから実行してください */ var username = 'hogehoge'; var password = 'fugafuga'; var client = require('../index'); console.info('ニコニコTOPページにアクセスします'); client.fetch('http://nicovideo.jp/') .then(function (result) { console.info('ログインリンクをクリックします'); return result.$('#sideNav .loginBtn').click(); }) .then(function (result) { console.info('ログインフォームを送信します'); return result.$('#login_form').submit({ mail_tel: username, password: password }); }) .then(function (result) { console.info('ログイン可否をチェックします'); if (! result.response.headers['x-niconico-id']) { throw new Error('login failed'); } console.info('クッキー', result.response.cookies); console.info('マイページに移動します'); return client.fetch('http://www.nicovideo.jp/my/top'); }) .then(function (result) { console.info('マイページに表示されるアカウント名を取得します'); console.info(result.$('#siteHeaderUserNickNameContainer').text()); }) .catch(function (err) { console.error('エラーが発生しました', err.message); }) .finally(function () { console.info('終了します'); });
tohshige/test
express/example/niconico.js
JavaScript
gpl-3.0
1,404
// Copyright (c) 2018 - 2020, Marcin Drob // Kainote 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. // Kainote 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 Kainote. If not, see <http://www.gnu.org/licenses/>. #pragma once #include <wx/window.h> #include <wx/thread.h> //#define Get_Log LogHandler::Get() class LogWindow; class LogHandler { friend class LogWindow; private: LogHandler(wxWindow *parent); ~LogHandler(); static LogHandler *sthis; wxString logToAppend; wxString lastLog; LogWindow *lWindow = NULL; wxMutex mutex; wxWindow *parent; public: static void Create(wxWindow *parent); static LogHandler *Get(){ return sthis; } static void Destroy(); void LogMessage(const wxString &format, bool showMessage = true); static void ShowLogWindow(); //void LogMessage1(const wxString &format, ...); }; static void KaiLog(const wxString &text){ LogHandler * handler = LogHandler::Get(); if (handler) handler->LogMessage(text); } static void KaiLogSilent(const wxString &text) { LogHandler * handler = LogHandler::Get(); if (handler) handler->LogMessage(text, false); } static void KaiLogDebug(const wxString &text){ #if _DEBUG LogHandler * handler = LogHandler::Get(); if (handler) handler->LogMessage(text); #endif }
bjakja/Kainote
Kaiplayer/LogHandler.h
C
gpl-3.0
1,722
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_66) on Sat Nov 28 10:51:55 EST 2015 --> <title>VariableQuantumIndexWriter (MG4J (big) 5.4.1)</title> <meta name="date" content="2015-11-28"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="VariableQuantumIndexWriter (MG4J (big) 5.4.1)"; } } catch(err) { } //--> var methods = {"i0":6}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../it/unimi/di/big/mg4j/index/TooManyTermsException.html" title="class in it.unimi.di.big.mg4j.index"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li>Next&nbsp;Class</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?it/unimi/di/big/mg4j/index/VariableQuantumIndexWriter.html" target="_top">Frames</a></li> <li><a href="VariableQuantumIndexWriter.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">it.unimi.di.big.mg4j.index</div> <h2 title="Interface VariableQuantumIndexWriter" class="title">Interface VariableQuantumIndexWriter</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Known Implementing Classes:</dt> <dd><a href="../../../../../../it/unimi/di/big/mg4j/index/BitStreamHPIndexWriter.html" title="class in it.unimi.di.big.mg4j.index">BitStreamHPIndexWriter</a>, <a href="../../../../../../it/unimi/di/big/mg4j/index/SkipBitStreamIndexWriter.html" title="class in it.unimi.di.big.mg4j.index">SkipBitStreamIndexWriter</a></dd> </dl> <hr> <br> <pre>public interface <span class="typeNameLabel">VariableQuantumIndexWriter</span></pre> <div class="block">An index writer supporting variable quanta. <p>This interface provides an additional <a href="../../../../../../it/unimi/di/big/mg4j/index/VariableQuantumIndexWriter.html#newInvertedList-long-double-long-long-"><code>newInvertedList(long, double, long, long)</code></a> method that accepts additional information. That information is used to compute the correct quantum size for a specific list. This approach makes it possible to specify a target fraction of the index that will be used to store skipping information.</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>long</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../it/unimi/di/big/mg4j/index/VariableQuantumIndexWriter.html#newInvertedList-long-double-long-long-">newInvertedList</a></span>(long&nbsp;predictedFrequency, double&nbsp;skipFraction, long&nbsp;predictedSize, long&nbsp;predictedPositionsSize)</code> <div class="block">Starts a new inverted list.</div> </td> </tr> </table> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="newInvertedList-long-double-long-long-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>newInvertedList</h4> <pre>long&nbsp;newInvertedList(long&nbsp;predictedFrequency, double&nbsp;skipFraction, long&nbsp;predictedSize, long&nbsp;predictedPositionsSize) throws <a href="http://download.oracle.com/javase/6/docs/api/java/io/IOException.html?is-external=true" title="class or interface in java.io">IOException</a></pre> <div class="block">Starts a new inverted list. The previous inverted list, if any, is actually written to the underlying bit stream. <p>This method provides additional information that will be used to compute the correct quantum for the skip structure of the inverted list.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>predictedFrequency</code> - the predicted frequency of the inverted list; this might just be an approximation.</dd> <dd><code>skipFraction</code> - the fraction of the inverted list that will be dedicated to skipping structures.</dd> <dd><code>predictedSize</code> - the predicted size of the part of the inverted list that stores terms and counts.</dd> <dd><code>predictedPositionsSize</code> - the predicted size of the part of the inverted list that stores positions.</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>the position (in bits) of the underlying bit stream where the new inverted list starts.</dd> <dt><span class="throwsLabel">Throws:</span></dt> <dd><code><a href="http://download.oracle.com/javase/6/docs/api/java/lang/IllegalStateException.html?is-external=true" title="class or interface in java.lang">IllegalStateException</a></code> - if too few records were written for the previous inverted list.</dd> <dd><code><a href="http://download.oracle.com/javase/6/docs/api/java/io/IOException.html?is-external=true" title="class or interface in java.io">IOException</a></code></dd> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../it/unimi/di/big/mg4j/index/IndexWriter.html#newInvertedList--"><code>IndexWriter.newInvertedList()</code></a></dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../it/unimi/di/big/mg4j/index/TooManyTermsException.html" title="class in it.unimi.di.big.mg4j.index"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li>Next&nbsp;Class</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?it/unimi/di/big/mg4j/index/VariableQuantumIndexWriter.html" target="_top">Frames</a></li> <li><a href="VariableQuantumIndexWriter.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
JC-R/mg4j
docs/it/unimi/di/big/mg4j/index/VariableQuantumIndexWriter.html
HTML
gpl-3.0
10,581
#!/usr/bin/python # coding: utf8 import os import subprocess from '{% if cookiecutter.namespace %}{{ cookiecutter.namespace }}.{{ cookiecutter.project_slug }}{% else %}{{ cookiecutter.project_slug }}{% endif %}'.commands.base import BaseCommand from '{% if cookiecutter.namespace %}{{ cookiecutter.namespace }}.{{ cookiecutter.project_slug }}{% else %}{{ cookiecutter.project_slug }}{% endif %}' import PROJECT_DIR class Configure(BaseCommand): def execute(self): os.chdir(os.path.join(PROJECT_DIR, 'build')) subprocess.run(['cmake', PROJECT_DIR])
antoinedube/numeric-cookiecutter
{{cookiecutter.namespace+'.'+cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/commands/configure.py
Python
gpl-3.0
571
<a href tabindex="-1" ng-attr-title="{{match.label}}"> <span ng-bind-html="match.label.artist | uibTypeaheadHighlight:query"></span> <br> <small ng-bind-html="match.label.title | uibTypeaheadHighlight:query"></small> </a>
prismsoundzero/delicious-library-template
prismsoundzero.libraryhtmltemplate/Contents/Template/html/item-match.html
HTML
gpl-3.0
240
package Eac.event; import Eac.Eac; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.PlayerEvent; import net.minecraft.item.ItemStack; public class EacOnItemPickup extends Eac { @SubscribeEvent public void EacOnItemPickup(PlayerEvent.ItemPickupEvent e) { if (e.pickedUp.getEntityItem().isItemEqual(new ItemStack(oreAir))) { e.player.addStat(airoremined, 1); } else if (e.pickedUp.getEntityItem().isItemEqual(new ItemStack(oreShadow))) { e.player.addStat(shadoworemined, 1); } } }
EacMods/Eac
src/main/java/Eac/event/EacOnItemPickup.java
Java
gpl-3.0
596
class PasswordResetsController < ApplicationController def new end def create @user = User.find_by_email(params[:email]) if @user @user.deliver_reset_password_instructions! redirect_to root_path, notice: 'Instructions have been sent to your email.' else flash.now[:alert] = "Sorry but we don't recognise the email address \"#{params[:email]}\"." render :new end end def edit @user = User.load_from_reset_password_token(params[:id]) @token = params[:id] if @user.blank? not_authenticated return end end def update @user = User.load_from_reset_password_token(params[:id]) @token = params[:id] if @user.blank? not_authenticated return end @user.password_confirmation = params[:user][:password_confirmation] if @user.change_password!(params[:user][:password]) redirect_to signin_path, notice: 'Password was successfully updated.' else render :edit end end end
armoin/edinburgh_collected
app/controllers/password_resets_controller.rb
Ruby
gpl-3.0
1,003
/* * Copyright 2011 Mect s.r.l * * This file is part of FarosPLC. * * FarosPLC 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. * * FarosPLC 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 * FarosPLC. If not, see http://www.gnu.org/licenses/. */ /* * Filename: BuildNr.h */ /* application build number: */ #define PRODUCT_BUILD 4001 /* EOF */
MECTsrl/ATCMcontrol_RunTimeSystem
inc/BuildNr.h
C
gpl-3.0
809
// // DetailViewController.h // ScrollView+PaperFold+PageControl // // Created by Jun Seki on 13/06/2014. // Copyright (c) 2014 Poq Studio. All rights reserved. // #import <UIKit/UIKit.h> #import "PaperFoldView.h" #import "SwipeView.h" @interface DetailViewController : UIViewController <UISplitViewControllerDelegate,PaperFoldViewDelegate,SwipeViewDataSource, SwipeViewDelegate> @property (strong, nonatomic) id detailItem; @property (nonatomic, strong) IBOutlet PaperFoldView *paperFoldView; @property (nonatomic, strong) UIView *topView; @property (weak, nonatomic) IBOutlet UIScrollView *scrollView; @property (weak, nonatomic) IBOutlet UILabel *detailDescriptionLabel; @property (nonatomic, strong) IBOutlet SwipeView *swipeView; @property (nonatomic, strong) NSMutableArray *items; @end
kiddomk/ScrollView-PaperFold-PageControl
ScrollView+PaperFold+PageControl/DetailViewController.h
C
gpl-3.0
805
/* * This file is part of gap. * * gap is free software: you can redistribute it and/or modify * under the terms of the GNU General Public License as published by * Free Software Foundation, either version 3 of the License, or * your option) any later version. * * gap is distributed in the hope that it will be useful, * WITHOUT ANY WARRANTY; without even the implied warranty of * CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with gap. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _OPT_H #define _OPT_H #include <assert.h> #define OPT_RELAX_CAPACITY 0 #define OPT_RELAX_CAPACITY_NAME "capacity" #define OPT_RELAX_QUANTITY 1 #define OPT_RELAX_QUANTITY_NAME "quantity" typedef struct { double alpha; char *file; int relax; int verbose; } Options; void opt_free (Options * opt); static inline double opt_get_alpha (Options * opt) { return opt->alpha; } static inline char * opt_get_file (Options * opt) { return opt->file; } static inline int opt_get_relax (Options * opt) { return opt->relax; } static inline int opt_get_verbose (Options * opt) { return opt->verbose; } Options *opt_new (); static inline void opt_set_alpha (Options * opt, double alpha) { opt->alpha = alpha; } static inline void opt_set_file (Options * opt, char *file) { opt->file = file; } static inline void opt_set_relax (Options * opt, int relax) { opt->relax = relax; } static inline void opt_set_verbose (Options * opt, int verbose) { opt->verbose = verbose; } #endif
mattia-barbaresi/gap
src/opt.h
C
gpl-3.0
1,643
// 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
dimaleks/uDeviceX
src/mirheo/core/interactions/membrane/force_kernels/common.h
C
gpl-3.0
2,010
/** * 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); } }
fg-netzwerksicherheit/jaddemo
src/de/fhffm/jad/demo/jad/DataFrame.java
Java
gpl-3.0
2,330
/* 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 <[email protected]>. */ 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; } }
rindPHI/F3TextViewerFX
src/de/dominicscheurer/quicktxtview/view/FileViewerController.java
Java
gpl-3.0
9,526
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)) } }
Jargon4072/DS-ALGO_implementations
scala/rec.scala
Scala
gpl-3.0
227
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
sgsinclair/Voyant
src/main/webapp/app/notebook/util/Embed.js
JavaScript
gpl-3.0
5,429
<!-- 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>
rhdunn/cainteoir-engine
tests/html/tree-construction/4-in-head~basefont/self-closing.html
HTML
gpl-3.0
213
//=========================================================================== // Summary: // IDPKDocÊǸºÔðÎĵµ´ò¿ª£¬»ñÈ¡ÎĵµÒ»Ð©ÊôÐԵĽӿÚÀà¡£ // Usage: // ʹÓÃDPK_CreateDoc½øÐд´½¨£¬Ê¹ÓÃDPK_DestoryDocÏú»Ù¡£ // Remarks: // Null // Date: // 2011-9-15 // Author: // Zhang JingDan ([email protected]) //=========================================================================== #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
stevezuoli/OriginApp
Kernel/include/PDFKit/PDFLib/IDKPDoc.h
C
gpl-3.0
6,829
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/
hezag/tvseries-api
README.md
Markdown
gpl-3.0
6,813
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>(); } }
Platonymous/Stardew-Valley-Mods
CustomWallsAndFloorsRedux/Settings.cs
C#
gpl-3.0
282
/* * Copyright (C) 2006-2009 Daniel Prevost <[email protected]> * * 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 } /* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */
dprevost/photon
src/Common/Tests/Options/IsShortPresentNullHandle.c
C
gpl-3.0
2,353
<?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>
fxstein/Kunena-Forum
components/com_kunena/site/template/crypsisb3/layouts/announcement/list/row/default.php
PHP
gpl-3.0
1,524
<!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>
SebastianFath/3-axis-Gimbal.Arduino
processing-3.0.1/modes/java/reference/TAU.html
HTML
gpl-3.0
6,710
/* ============================================================ * QupZilla - WebKit based browser * Copyright (C) 2010-2014 David Rosca <[email protected]> * * 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
ThaFireDragonOfDeath/qupzilla
src/lib/adblock/adblockicon.h
C
gpl-3.0
1,738
// 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('>'); } }; }
Lester-Dowling/studies
C++/boost/spirit/Mini-XML-2017/Unit-Tests/opening-tag.hpp
C++
gpl-3.0
778
// 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__
mganeva/mantid
Framework/Geometry/test/MeshObjectTest.h
C
gpl-3.0
45,834
//: 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); } }
silverweed/pokepon
pony/PartyFavor.java
Java
gpl-3.0
654
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); } }
bambit/BGallery
TIS.GSP.Business.Interfaces/IUserAccountCollection.cs
C#
gpl-3.0
5,022
var Base = require("./../plugin"); module.exports = class extends Base { isDisableSelfAttackPriority(self, rival) { return true; } isDisableEnemyAttackPriority(self, rival) { return true; } }
ssac/feh-guide
src/models/seal/hardy_bearing_3.js
JavaScript
gpl-3.0
208
////////////////////////////////////////////////// // 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;[email protected]&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
jbgi/replics
swans/jist/runtime/EntityRef.java
Java
gpl-3.0
6,768
#!/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='[email protected]', 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' ],)
txemagon/1984
modules/Telegram-bot-python/setup.py
Python
gpl-3.0
2,168
#!/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
fangxinmiao/projects
Architeture/OS/Linux/Distributions/LFS/build-scripts/blfs-7.6-systemv/p/perl-modules/URI-1.65/build.sh
Shell
gpl-3.0
865
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 <[email protected]> */ 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")); } }
jimdowling/gvod
bootstrap/ISPFriendliness-Distances/src/test/java/se/sics/asdistances/ASDistancesTest.java
Java
gpl-3.0
796
#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())); }
mmshihov/microcode
cmilitwostateselect.cpp
C++
gpl-3.0
4,032
#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; }
jessicaleemraz/mindshare-wp-code-review
css/style.css
CSS
gpl-3.0
326
/********************************************************* ********************************************************* ** DO NOT EDIT ** ** ** ** THIS FILE AS BEEN GENERATED AUTOMATICALLY ** ** BY UPA PORTABLE GENERATOR ** ** (c) vpc ** ** ** ********************************************************* ********************************************************/ namespace Net.TheVpc.Upa.Impl.Event { /** * * @author [email protected] */ 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; } } }
thevpc/upa
upa-impl-core/src/main/csharp/Sources/Auto/Event/UpdateFormulaObjectEventCallback.cs
C#
gpl-3.0
2,055
/* -*- c++ -*- */ /* * Copyright 2019-2020 Daniel Estevez <[email protected]> * * 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 */
daniestevez/gr-satellites
lib/distributed_syncframe_soft_impl.h
C
gpl-3.0
1,024
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* 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 [email protected]. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /**@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
LiangliangNan/PolyFit
3rd_scip/scip/struct_concsolver.h
C
gpl-3.0
5,663
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;
grim210/defimulator
defimulator/snes/cartridge/cartridge.hpp
C++
gpl-3.0
2,519
<?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); } } } }
edoschatz/taskada
src/Schatz/CrmBundle/Controller/Leads/LeadsController.php
PHP
gpl-3.0
4,047
# -*- 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', ), ]
yangxianbo/jym
account/migrations/0004_auto_20160525_1032.py
Python
gpl-3.0
591
#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
moves-rwth/storm
src/storm/storage/memorystructure/NondeterministicMemoryStructureBuilder.h
C
gpl-3.0
2,271
/* * 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; } }
eternia16/javaGithubUpdater
src/main/java/nl/hyranasoftware/githubupdater/domain/Asset.java
Java
gpl-3.0
3,243
/***************************************************************************** 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_ */
Extant-1/ThieVR
game/Http/HttpRequest.h
C
gpl-3.0
2,733
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
gohdan/DFC
known_files/hashes/manager/controllers/default/resource/update.class.php
PHP
gpl-3.0
285
#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); }
kelseymh/secindex_proto
rocksdb-index.cc
C++
gpl-3.0
706
### # 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
greenriver/hmis-warehouse
app/models/reports/system_performance/fy2015/measure_three.rb
Ruby
gpl-3.0
237
#!/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 $?
qiq/hector_core
test/process.sh
Shell
gpl-3.0
475
<?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); } # ------------------------------------------------------- }
bruceklotz/providence-with-Backup
app/controllers/find/SearchObjectsAdvancedController.php
PHP
gpl-3.0
5,413
/* * 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_ */
SanderMertens/opensplice
src/api/dcps/isocpp/include/org/opensplice/core/policy/CorePolicy.hpp
C++
gpl-3.0
28,610
<?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); } }
WoWRoster/wowroster_dev
admin/addon_install.php
PHP
gpl-3.0
21,161
# odoo_ml_quality_module
r-castro/odoo_ml_quality_module
README.md
Markdown
gpl-3.0
24
<!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>
Nitrosito/ED
Practicas/Practica2/source/html/search/typedefs_1.html
HTML
gpl-3.0
1,019
<?php namespace Paged; /** * Выводит список как маркерованный * * @category Basic library * @package Paged * @author Peter S. Gribanov <[email protected]> * @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()); } }
peter-gribanov/php-paged
classes/views/ViewList.php
PHP
gpl-3.0
1,223
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'))
seanballais/botos
tests/test_results_exporter_view.py
Python
gpl-3.0
18,942
/* 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); }
FHust/ISEAFramework
src/geometry/unit_vector.cpp
C++
gpl-3.0
760
<?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).' ...'; } } ?>
figomago/joomla-jobboard
pkg_jobboard_1.2.7.1_lite/site/views/list/view.feed.php
PHP
gpl-3.0
4,860
/* 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 }
spatialmodel/inmap
emissions/slca/eieio/spatialemis.go
GO
gpl-3.0
6,205
<?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; } } }
stan-bg/opencart
upload/admin/controller/total/shipping.php
PHP
gpl-3.0
3,431
// // 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; } }
ramsodev/DitaManagement
dita/dita.concept/src/net/ramso/dita/concept/SynblkClass.java
Java
gpl-3.0
14,623
<?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 ] ] ); } }
edwardspec/mediawiki-moderation
tests/phpunit/consequence/RejectOneConsequenceTest.php
PHP
gpl-3.0
3,757
/* * 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; } }
ridoo/dao-series-api
dao/src/main/java/org/n52/series/db/beans/parameter/Parameter.java
Java
gpl-3.0
2,458
/* 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: <[email protected]>. * * 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 */
macmanes-lab/BinPacker
glpk-4.40/src/glpapi16.c
C
gpl-3.0
18,723
#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
mstubinis/Serenity
SerenityLib/include/serenity/resources/mesh/animation/Skeleton.h
C
gpl-3.0
3,682
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); } }
sickel/measem
app/src/main/java/com/mortensickel/measemulator/MainActivity.java
Java
gpl-3.0
13,932