code
stringlengths
4
1.01M
language
stringclasses
2 values
package org.usfirst.frc369.Robot2017Code.subsystems; import org.usfirst.frc369.Robot2017Code.Robot; import edu.wpi.first.wpilibj.Relay; import edu.wpi.first.wpilibj.command.Subsystem; /** * */ public class LED extends Subsystem { // Put methods for controlling this subsystem // here. Call these from Commands. public void initDefaultCommand() { // Set the default command for a subsystem here. //setDefaultCommand(new MySpecialCommand()); } public void LEDOn(){ Robot.LEDSys.equals(Relay.Value.kForward); } public void LEDelse(){ Robot.LEDSys.equals(Relay.Value.kReverse); } public void LEDOff(){ Robot.LEDSys.equals(Relay.Value.kOff); } }
Java
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="description" content="Javadoc API documentation for Fresco." /> <link rel="shortcut icon" type="image/x-icon" href="../../../../favicon.ico" /> <title> com.facebook.imagepipeline.nativecode Details - Fresco API | Fresco </title> <link href="../../../../../assets/doclava-developer-docs.css" rel="stylesheet" type="text/css" /> <link href="../../../../../assets/customizations.css" rel="stylesheet" type="text/css" /> <script src="../../../../../assets/search_autocomplete.js" type="text/javascript"></script> <script src="../../../../../assets/jquery-resizable.min.js" type="text/javascript"></script> <script src="../../../../../assets/doclava-developer-docs.js" type="text/javascript"></script> <script src="../../../../../assets/prettify.js" type="text/javascript"></script> <script type="text/javascript"> setToRoot("../../../../", "../../../../../assets/"); </script> <script src="../../../../../assets/doclava-developer-reference.js" type="text/javascript"></script> <script src="../../../../../assets/navtree_data.js" type="text/javascript"></script> <script src="../../../../../assets/customizations.js" type="text/javascript"></script> <noscript> <style type="text/css"> html,body{overflow:auto;} #body-content{position:relative; top:0;} #doc-content{overflow:visible;border-left:3px solid #666;} #side-nav{padding:0;} #side-nav .toggle-list ul {display:block;} #resize-packages-nav{border-bottom:3px solid #666;} </style> </noscript> </head> <body class=""> <div id="header"> <div id="headerLeft"> <span id="masthead-title"><a href="../../../../packages.html">Fresco</a></span> </div> <div id="headerRight"> <div id="search" > <div id="searchForm"> <form accept-charset="utf-8" class="gsc-search-box" onsubmit="return submit_search()"> <table class="gsc-search-box" cellpadding="0" cellspacing="0"><tbody> <tr> <td class="gsc-input"> <input id="search_autocomplete" class="gsc-input" type="text" size="33" autocomplete="off" title="search developer docs" name="q" value="search developer docs" onFocus="search_focus_changed(this, true)" onBlur="search_focus_changed(this, false)" onkeydown="return search_changed(event, true, '../../../../')" onkeyup="return search_changed(event, false, '../../../../')" /> <div id="search_filtered_div" class="no-display"> <table id="search_filtered" cellspacing=0> </table> </div> </td> <!-- <td class="gsc-search-button"> <input type="submit" value="Search" title="search" id="search-button" class="gsc-search-button" /> </td> <td class="gsc-clear-button"> <div title="clear results" class="gsc-clear-button">&nbsp;</div> </td> --> </tr></tbody> </table> </form> </div><!-- searchForm --> </div><!-- search --> </div> </div><!-- header --> <div class="g-section g-tpl-240" id="body-content"> <div class="g-unit g-first side-nav-resizable" id="side-nav"> <div id="swapper"> <div id="nav-panels"> <div id="resize-packages-nav"> <div id="packages-nav"> <div id="index-links"> <a href="../../../../packages.html" >Packages</a> | <a href="../../../../classes.html" >Classes</a> </div> <ul> <li class="api apilevel-"> <a href="../../../../com/facebook/animated/gif/package-summary.html">com.facebook.animated.gif</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/animated/webp/package-summary.html">com.facebook.animated.webp</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/binaryresource/package-summary.html">com.facebook.binaryresource</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/cache/common/package-summary.html">com.facebook.cache.common</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/cache/disk/package-summary.html">com.facebook.cache.disk</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/activitylistener/package-summary.html">com.facebook.common.activitylistener</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/disk/package-summary.html">com.facebook.common.disk</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/executors/package-summary.html">com.facebook.common.executors</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/file/package-summary.html">com.facebook.common.file</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/internal/package-summary.html">com.facebook.common.internal</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/lifecycle/package-summary.html">com.facebook.common.lifecycle</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/logging/package-summary.html">com.facebook.common.logging</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/media/package-summary.html">com.facebook.common.media</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/memory/package-summary.html">com.facebook.common.memory</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/references/package-summary.html">com.facebook.common.references</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/soloader/package-summary.html">com.facebook.common.soloader</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/statfs/package-summary.html">com.facebook.common.statfs</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/streams/package-summary.html">com.facebook.common.streams</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/time/package-summary.html">com.facebook.common.time</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/util/package-summary.html">com.facebook.common.util</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/webp/package-summary.html">com.facebook.common.webp</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/datasource/package-summary.html">com.facebook.datasource</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawable/base/package-summary.html">com.facebook.drawable.base</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/backends/pipeline/package-summary.html">com.facebook.drawee.backends.pipeline</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/backends/volley/package-summary.html">com.facebook.drawee.backends.volley</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/components/package-summary.html">com.facebook.drawee.components</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/controller/package-summary.html">com.facebook.drawee.controller</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/debug/package-summary.html">com.facebook.drawee.debug</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/drawable/package-summary.html">com.facebook.drawee.drawable</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/generic/package-summary.html">com.facebook.drawee.generic</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/gestures/package-summary.html">com.facebook.drawee.gestures</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/interfaces/package-summary.html">com.facebook.drawee.interfaces</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/span/package-summary.html">com.facebook.drawee.span</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/view/package-summary.html">com.facebook.drawee.view</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/backend/package-summary.html">com.facebook.fresco.animation.backend</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/bitmap/package-summary.html">com.facebook.fresco.animation.bitmap</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/bitmap/cache/package-summary.html">com.facebook.fresco.animation.bitmap.cache</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/bitmap/preparation/package-summary.html">com.facebook.fresco.animation.bitmap.preparation</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/bitmap/wrapper/package-summary.html">com.facebook.fresco.animation.bitmap.wrapper</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/drawable/package-summary.html">com.facebook.fresco.animation.drawable</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/drawable/animator/package-summary.html">com.facebook.fresco.animation.drawable.animator</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/factory/package-summary.html">com.facebook.fresco.animation.factory</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/frame/package-summary.html">com.facebook.fresco.animation.frame</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imageformat/package-summary.html">com.facebook.imageformat</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/animated/base/package-summary.html">com.facebook.imagepipeline.animated.base</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/animated/factory/package-summary.html">com.facebook.imagepipeline.animated.factory</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/animated/impl/package-summary.html">com.facebook.imagepipeline.animated.impl</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/animated/util/package-summary.html">com.facebook.imagepipeline.animated.util</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/backends/okhttp3/package-summary.html">com.facebook.imagepipeline.backends.okhttp3</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/backends/volley/package-summary.html">com.facebook.imagepipeline.backends.volley</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/bitmaps/package-summary.html">com.facebook.imagepipeline.bitmaps</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/cache/package-summary.html">com.facebook.imagepipeline.cache</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/common/package-summary.html">com.facebook.imagepipeline.common</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/core/package-summary.html">com.facebook.imagepipeline.core</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/datasource/package-summary.html">com.facebook.imagepipeline.datasource</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/decoder/package-summary.html">com.facebook.imagepipeline.decoder</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/drawable/package-summary.html">com.facebook.imagepipeline.drawable</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/image/package-summary.html">com.facebook.imagepipeline.image</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/listener/package-summary.html">com.facebook.imagepipeline.listener</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/memory/package-summary.html">com.facebook.imagepipeline.memory</a></li> <li class="selected api apilevel-"> <a href="../../../../com/facebook/imagepipeline/nativecode/package-summary.html">com.facebook.imagepipeline.nativecode</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/platform/package-summary.html">com.facebook.imagepipeline.platform</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/postprocessors/package-summary.html">com.facebook.imagepipeline.postprocessors</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/producers/package-summary.html">com.facebook.imagepipeline.producers</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/request/package-summary.html">com.facebook.imagepipeline.request</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imageutils/package-summary.html">com.facebook.imageutils</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/webpsupport/package-summary.html">com.facebook.webpsupport</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/widget/text/span/package-summary.html">com.facebook.widget.text.span</a></li> </ul><br/> </div> <!-- end packages --> </div> <!-- end resize-packages --> <div id="classes-nav"> <ul> <li><h2>Interfaces</h2> <ul> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/nativecode/WebpTranscoder.html">WebpTranscoder</a></li> </ul> </li> <li><h2>Classes</h2> <ul> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/nativecode/Bitmaps.html">Bitmaps</a></li> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/nativecode/ImagePipelineNativeLoader.html">ImagePipelineNativeLoader</a></li> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/nativecode/JpegTranscoder.html">JpegTranscoder</a></li> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/nativecode/NativeBlurFilter.html">NativeBlurFilter</a></li> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/nativecode/NativeRoundingFilter.html">NativeRoundingFilter</a></li> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/nativecode/StaticWebpNativeLoader.html">StaticWebpNativeLoader</a></li> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/nativecode/WebpTranscoderFactory.html">WebpTranscoderFactory</a></li> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/nativecode/WebpTranscoderImpl.html">WebpTranscoderImpl</a></li> </ul> </li> </ul><br/> </div><!-- end classes --> </div><!-- end nav-panels --> <div id="nav-tree" style="display:none"> <div id="index-links"> <a href="../../../../packages.html" >Packages</a> | <a href="../../../../classes.html" >Classes</a> </div> </div><!-- end nav-tree --> </div><!-- end swapper --> </div> <!-- end side-nav --> <script> if (!isMobile) { //$("<a href='#' id='nav-swap' onclick='swapNav();return false;' style='font-size:10px;line-height:9px;margin-left:1em;text-decoration:none;'><span id='tree-link'>Use Tree Navigation</span><span id='panel-link' style='display:none'>Use Panel Navigation</span></a>").appendTo("#side-nav"); chooseDefaultNav(); if ($("#nav-tree").is(':visible')) { init_default_navtree("../../../../"); } else { addLoadEvent(function() { scrollIntoView("packages-nav"); scrollIntoView("classes-nav"); }); } //$("#swapper").css({borderBottom:"2px solid #aaa"}); } else { swapNav(); // tree view should be used on mobile } </script> <div class="g-unit" id="doc-content"> <div id="api-info-block"> <div class="api-level"> </div> </div> <div id="jd-header"> package <h1>com.facebook.imagepipeline.nativecode</b></h1> <div class="jd-nav"> <a class="jd-navlink" href="package-summary.html">Classes</a> | Description </div> </div><!-- end header --> <div id="naMessage"></div> <div id="jd-content" class="api apilevel-"> <div class="jd-descr"> <p></p> </div> <div id="footer"> +Generated by <a href="http://code.google.com/p/doclava/">Doclava</a>. +</div> <!-- end footer - @generated --> </div><!-- end jd-content --> </div> <!-- end doc-content --> </div> <!-- end body-content --> <script type="text/javascript"> init(); /* initialize doclava-developer-docs.js */ </script> </body> </html>
Java
var NETKI_PUBAPI_HOST = 'https://pubapi.netki.com'; var NETKI_API_HOST = 'https://api.netki.com'; var SHORTCODES = { 'btc': 'Bitcoin', 'tbtc': 'Bitcoin Testnet', 'ltc': 'Litecoin', 'dgc': 'Dogecoin', 'nmc': 'Namecoin', 'tusd': 'tetherUSD', 'teur': 'tetherEUR', 'tjpy': 'tetherJPY', 'oap': 'Open Asset', 'fct': 'Factom Factoid', 'fec': 'Factom Entry Credit', 'eth': 'Ethereum Ether' }; function isWalletName(walletName) { var pattern = /^(?!:\/\/)([a-zA-Z0-9]+\.)?[a-zA-Z0-9][a-zA-Z0-9-]+\.[a-zA-Z]{2,24}?$/i; return pattern.test(walletName); }
Java
<?php /** * Cache subsystem library * @package Cotonti * @version 0.9.10 * @author Cotonti Team * @copyright Copyright (c) Cotonti Team 2009-2014 * @license BSD */ defined('COT_CODE') or die('Wrong URL'); /** * Stores the list of advanced cachers provided by the host * @var array */ $cot_cache_drivers = array(); /** * Default cache realm */ define('COT_DEFAULT_REALM', 'cot'); /** * Default time to live for temporary cache objects */ define('COT_DEFAULT_TTL', 3600); /** * Default cache type, uneffective */ define('COT_CACHE_TYPE_ALL', 0); /** * Disk cache type */ define('COT_CACHE_TYPE_DISK', 1); /** * Database cache type */ define('COT_CACHE_TYPE_DB', 2); /** * Shared memory cache type */ define('COT_CACHE_TYPE_MEMORY', 3); /** * Page cache type */ define('COT_CACHE_TYPE_PAGE', 4); /** * Default cache type */ define('COT_CACHE_TYPE_DEFAULT', COT_CACHE_TYPE_DB); /** * Abstract class containing code common for all cache drivers * @author Cotonti Team */ abstract class Cache_driver { /** * Clears all cache entries served by current driver * @param string $realm Cache realm name, to clear specific realm only * @return bool */ abstract public function clear($realm = COT_DEFAULT_REALM); /** * Checks if an object is stored in cache * @param string $id Object identifier * @param string $realm Cache realm * @return bool */ abstract public function exists($id, $realm = COT_DEFAULT_REALM); /** * Returns value of cached image * @param string $id Object identifier * @param string $realm Realm name * @return mixed Cached item value or NULL if the item was not found in cache */ abstract public function get($id, $realm = COT_DEFAULT_REALM); /** * Removes object image from cache * @param string $id Object identifier * @param string $realm Realm name * @return bool */ abstract public function remove($id, $realm = COT_DEFAULT_REALM); } /** * Static cache is used to store large amounts of rarely modified data */ abstract class Static_cache_driver { /** * Stores data as object image in cache * @param string $id Object identifier * @param mixed $data Object value * @param string $realm Realm name * @return bool */ abstract public function store($id, $data, $realm = COT_DEFAULT_REALM); } /** * Dynamic cache is used to store data that is not too large * and is modified more or less frequently */ abstract class Dynamic_cache_driver { /** * Stores data as object image in cache * @param string $id Object identifier * @param mixed $data Object value * @param string $realm Realm name * @param int $ttl Time to live, 0 for unlimited * @return bool */ abstract public function store($id, $data, $realm = COT_DEFAULT_REALM, $ttl = COT_DEFAULT_TTL); } /** * Persistent cache driver that writes all entries back on script termination. * Persistent cache drivers work slower but guarantee long-term data consistency. */ abstract class Writeback_cache_driver extends Dynamic_cache_driver { /** * Values for delayed writeback to persistent cache * @var array */ protected $writeback_data = array(); /** * Keys that are to be removed */ protected $removed_data = array(); /** * Writes modified entries back to persistent storage */ abstract public function flush(); /** * Removes cache image of the object from the database * @param string $id Object identifier * @param string $realm Realm name */ public function remove($id, $realm = COT_DEFAULT_REALM) { $this->removed_data[] = array('id' => $id, 'realm' => $realm); } /** * Removes item immediately, avoiding writeback. * @param string $id Item identifirer * @param string $realm Cache realm * @return bool * @see Cache_driver::remove() */ abstract public function remove_now($id, $realm = COT_DEFAULT_REALM); /** * Stores data as object image in cache * @param string $id Object identifier * @param mixed $data Object value * @param string $realm Realm name * @param int $ttl Time to live, 0 for unlimited * @return bool * @see Cache_driver::store() */ public function store($id, $data, $realm = COT_DEFAULT_REALM, $ttl = 0) { $this->writeback_data[] = array('id' => $id, 'data' => $data, 'realm' => $realm, 'ttl' => $ttl); return true; } /** * Writes item to cache immediately, avoiding writeback. * @param string $id Object identifier * @param mixed $data Object value * @param string $realm Realm name * @param int $ttl Time to live, 0 for unlimited * @return bool * @see Cache_driver::store() */ abstract public function store_now($id, $data, $realm = COT_DEFAULT_REALM, $ttl = COT_DEFAULT_TTL); } /** * Query cache drivers are driven by database */ abstract class Db_cache_driver extends Writeback_cache_driver { /** * Loads all variables from a specified realm(s) into the global scope * @param mixed $realm Realm name or array of realm names * @return int Number of items loaded */ abstract public function get_all($realm = COT_DEFAULT_REALM); } /** * Temporary cache driver is fast in-memory cache. It usually works faster and provides * automatic garbage collection, but it doesn't save data if PHP stops whatsoever. * Use it for individual frequently modified variables. */ abstract class Temporary_cache_driver extends Dynamic_cache_driver { /** * Increments counter value * @param string $id Counter identifier * @param string $realm Realm name * @param int $value Increment value * return int Result value */ public function inc($id, $realm = COT_DEFAULT_REALM, $value = 1) { $res = $this->get($id, $realm); $res += $value; $this->store($id, $res, $realm); return $res; } /** * Decrements counter value * @param string $id Counter identifier * @param string $realm Realm name * @param int $value Increment value * return int Result value */ public function dec($id, $realm = COT_DEFAULT_REALM, $value = 1) { $res = $this->get($id, $realm); $res -= $value; $this->store($id, $res, $realm); return $res; } /** * Returns information about memory usage if available. * Possible keys: available, occupied, max. * If the driver cannot provide a value, it sets it to -1. * @return array Associative array containing information */ abstract public function get_info(); /** * Gets a size limit from php.ini * @param string $name INI setting name * @return int Number of bytes */ protected function get_ini_size($name) { $ini = ini_get($name); $suffix = strtoupper(substr($ini, -1)); $prefix = substr($ini, 0, -1); switch ($suffix) { case 'K': return ((int) $prefix) * 1024; break; case 'M': return ((int) $prefix) * 1048576; break; case 'G': return ((int) $prefix) * 1073741824; break; default: return (int) $ini; } } } /** * A persistent cache using local file system tree. It does not use multilevel structure * or lexicograph search, so it may slow down when your cache grows very big. * But normally it is very fast reads. * @author Cotonti Team */ class File_cache extends Static_cache_driver { /** * Cache root directory * @var string */ private $dir; /** * Cache storage object constructor * @param string $dir Cache root directory. System default will be used if empty. * @throws Exception * @return File_cache */ public function __construct($dir = '') { global $cfg; if (empty($dir)) $dir = $cfg['cache_dir']; if (!empty($dir) && !file_exists($dir)) mkdir($dir, 0755, true); if (file_exists($dir) && is_writeable($dir)) { $this->dir = $dir; } else { throw new Exception('Cache directory '.$dir.' is not writeable!'); // TODO: Need translate } } /** * @see Cache_driver::clear() */ public function clear($realm = COT_DEFAULT_REALM) { if (empty($realm)) { if(is_dir($this->dir)) { $dp = opendir($this->dir); while ($f = readdir($dp)) { $dname = $this->dir.'/'.$f; if ($f[0] != '.' && is_dir($dname)) { $this->clear($f); } } closedir($dp); } } else { if(is_dir($this->dir.'/'.$realm)) { $dp = opendir($this->dir.'/'.$realm); while ($f = readdir($dp)) { $fname = $this->dir.'/'.$realm.'/'.$f; if (is_file($fname)) { unlink($fname); } } closedir($dp); } } return TRUE; } /** * Checks if an object is stored in disk cache * @param string $id Object identifier * @param string $realm Cache realm * @param int $ttl Lifetime in seconds, 0 means unlimited * @return bool */ public function exists($id, $realm = COT_DEFAULT_REALM, $ttl = 0) { $filename = $this->dir.'/'.$realm.'/'.$id; return file_exists($filename) && ($ttl == 0 || time() - filemtime($filename) < $ttl); } /** * Gets an object directly from disk * @param string $id Object identifier * @param string $realm Realm name * @param int $ttl Lifetime in seconds, 0 means unlimited * @return mixed Cached item value or NULL if the item was not found in cache */ public function get($id, $realm = COT_DEFAULT_REALM, $ttl = 0) { if ($this->exists($id, $realm, $ttl)) { return unserialize(file_get_contents($this->dir.'/'.$realm.'/'.$id)); } else { return NULL; } } /** * Removes cache image of the object from disk * @param string $id Object identifier * @param string $realm Realm name */ public function remove($id, $realm = COT_DEFAULT_REALM) { if ($this->exists($id, $realm)) { unlink($this->dir.'/'.$realm.'/'.$id); return true; } else return false; } /** * Stores disk cache entry * @param string $id Object identifier * @param mixed $data Object value * @param string $realm Realm name * @return bool */ public function store($id, $data, $realm = COT_DEFAULT_REALM) { if (!file_exists($this->dir.'/'.$realm)) { mkdir($this->dir.'/'.$realm); } file_put_contents($this->dir.'/'.$realm.'/'.$id, serialize($data)); return true; } } /** * A cache that stores entire page outputs. Disk-based. */ class Page_cache { /** * Cache root */ private $dir; /** * Relative page (item) path */ private $path; /** * Short file name */ private $name; /** * Parameters to exclude */ private $excl; /** * Filename extension */ private $ext; /** * Full path to page cache image */ private $filename; /** * Directory permissions */ private $perms; /** * Constructs controller object and sets basic configuration * @param string $dir Cache directory * @param int $perms Octal permission mask for cache directories */ public function __construct($dir, $perms = 0777) { $this->dir = $dir; $this->perms = $perms; } /** * Removes an item and all contained items and cache files * @param string $path Item path * @return int Number of files removed */ public function clear($path) { return $this->rm_r($this->dir . '/' . $path); } /** * Initializes actual page cache * @param string $path Page path string * @param string $name Short name for the cache file * @param array $exclude A list of GET params to be excluded from consideration * @param string $ext File extension */ public function init($path, $name, $exclude = array(), $ext = '') { $this->path = $path; $this->name = $name; $this->excl = $exclude; $this->ext = $ext; } /** * Reads the page cache object from disk and sends it to output. * If the cache object does not exist, then just calculates the path * for a following write() call. */ public function read() { $filename = $this->dir. '/' . $this->path . '/' . $this->name; $args = array(); foreach ($_GET as $key => $val) { if (!in_array($key, $this->excl)) { $args[$key] = $val; } } ksort($args); if (count($args) > 0) { $hashkey = serialize($args); $filename .= '_' . md5($hashkey) . sha1($hashkey); } if (!empty($this->ext)) { $filename .= '.' . $this->ext; } if (file_exists($filename)) { // Browser cache headers $filemtime = filemtime($filename); $etag = md5($filename . filesize($filename) . $filemtime); if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) { // convert to unix timestamp $if_modified_since = strtotime(preg_replace('#;.*$#', '', stripslashes($_SERVER['HTTP_IF_MODIFIED_SINCE']))); } else { $if_modified_since = false; } $if_none_match = stripslashes($_SERVER['HTTP_IF_NONE_MATCH']); if ($if_none_match == $etag && $if_modified_since >= $filemtime) { $protocol = (isset($_SERVER['SERVER_PROTOCOL'])) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1'; header($protocol . ' 304 Not Modified'); header("Etag: $etag"); exit; } header('Last-Modified: ' . gmdate('D, d M Y H:i:s \G\M\T', $filemtime)); header("ETag: $etag"); header('Expires: Mon, 01 Apr 1974 00:00:00 GMT'); header('Cache-Control: must-revalidate, proxy-revalidate'); // Page output header('Content-Type: text/html; charset=UTF-8'); if (@strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') === FALSE) { readgzfile($filename); } else { header('Content-Encoding: gzip'); echo file_get_contents($filename); } exit; } $this->filename = $filename; } /** * Writes output buffer contents to a cache image file */ public function write() { if (!empty($this->filename)) { if (!file_exists($this->dir . '/' . $this->path)) { mkdir($this->dir . '/' . $this->path, $this->perms, true); } file_put_contents($this->filename, gzencode(cot_outputfilters(ob_get_contents()))); } } /** * Removes a directory with all its contents recursively * @param string $path Directory path * @return int Number of items removed */ private function rm_r($path) { $cnt = 0; if(is_dir($path)) { $dp = opendir($path); while ($f = readdir($dp)) { $fpath = $path . '/' . $f; if (is_dir($fpath) && $f != '.' && $f != '..') { $cnt += $this->rm_r($fpath); } elseif (is_file($fpath)) { unlink($fpath); ++$cnt; } } closedir($dp); rmdir($path); } return ++$cnt; } } /** * A very popular caching solution using MySQL as a storage. It is quite slow compared to * File_cache but may be considered more reliable. * @author Cotonti Team */ class MySQL_cache extends Db_cache_driver { /** * Prefetched data to avoid duplicate queries * @var array */ private $buffer = array(); /** * Performs pre-load actions */ public function __construct() { // 10% GC probability if (mt_rand(1, 10) == 5) { $this->gc(); } } /** * Enforces flush() */ public function __destruct() { $this->flush(); } /** * Saves all modified data with one query */ public function flush() { global $db, $db_cache, $sys; if (count($this->removed_data) > 0) { $q = "DELETE FROM $db_cache WHERE"; $i = 0; foreach ($this->removed_data as $entry) { $c_name = $db->quote($entry['id']); $c_realm = $db->quote($entry['realm']); $or = $i == 0 ? '' : ' OR'; $q .= $or." (c_name = $c_name AND c_realm = $c_realm)"; $i++; } $this->removed_data = array(); $db->query($q); } if (count($this->writeback_data) > 0) { $q = "INSERT INTO $db_cache (c_name, c_realm, c_expire, c_value) VALUES "; $i = 0; foreach ($this->writeback_data as $entry) { $c_name = $db->quote($entry['id']); $c_realm = $db->quote($entry['realm']); $c_expire = $entry['ttl'] > 0 ? $sys['now'] + $entry['ttl'] : 0; $c_value = $db->quote(serialize($entry['data'])); $comma = $i == 0 ? '' : ','; $q .= $comma."($c_name, $c_realm, $c_expire, $c_value)"; $i++; } $this->writeback_data = array(); $q .= " ON DUPLICATE KEY UPDATE c_value=VALUES(c_value), c_expire=VALUES(c_expire)"; $db->query($q); } } /** * @see Cache_driver::clear() */ public function clear($realm = '') { global $db, $db_cache; if (empty($realm)) { $db->query("TRUNCATE $db_cache"); } else { $db->query("DELETE FROM $db_cache WHERE c_realm = " . $db->quote($realm)); } $this->buffer = array(); return TRUE; } /** * @see Cache_driver::exists() */ public function exists($id, $realm = COT_DEFAULT_REALM) { global $db, $db_cache; if (isset($this->buffer[$realm][$id])) { return true; } $sql = $db->query("SELECT c_value FROM $db_cache WHERE c_realm = ".$db->quote($realm)." AND c_name = ".$db->quote($id)); $res = $sql->rowCount() == 1; if ($res) { $this->buffer[$realm][$id] = unserialize($sql->fetchColumn()); } return $res; } /** * Garbage collector function. Removes cache entries which are not valid anymore. * @return int Number of entries removed */ private function gc() { global $db, $db_cache, $sys; $db->query("DELETE FROM $db_cache WHERE c_expire > 0 AND c_expire < ".$sys['now']); return $db->affectedRows; } /** * @see Cache_driver::get() */ public function get($id, $realm = COT_DEFAULT_REALM) { if($this->exists($id, $realm)) { return $this->buffer[$realm][$id]; } else { return null; } } /** * @see Db_cache_driver::get_all() */ public function get_all($realms = COT_DEFAULT_REALM) { global $db, $db_cache; if (is_array($realms)) { $r_where = "c_realm IN("; $i = 0; foreach ($realms as $realm) { $glue = $i == 0 ? "'" : ",'"; $r_where .= $glue.$db->prep($realm)."'"; $i++; } $r_where .= ')'; } else { $r_where = "c_realm = '".$db->prep($realms)."'"; } $sql = $db->query("SELECT c_name, c_value FROM `$db_cache` WHERE c_auto=1 AND $r_where"); $i = 0; while ($row = $sql->fetch()) { global ${$row['c_name']}; ${$row['c_name']} = unserialize($row['c_value']); $i++; } $sql->closeCursor(); return $i; } /** * @see Writeback_cache_driver::remove_now() */ public function remove_now($id, $realm = COT_DEFAULT_REALM) { global $db, $db_cache; $db->query("DELETE FROM $db_cache WHERE c_realm = ".$db->quote($realm)." AND c_name = ".$db->quote($id)); unset($this->buffer[$realm][$id]); return $db->affectedRows == 1; } /** * Stores data as object image in cache * @param string $id Object identifier * @param mixed $data Object value * @param string $realm Realm name * @param int $ttl Time to live, 0 for unlimited * @return bool * @see Cache_driver::store() */ public function store($id, $data, $realm = COT_DEFAULT_REALM, $ttl = 0) { global $db; // Check data length if ($data) { if (strlen($db->prep(serialize($data))) > 16777215) // MySQL max MEDIUMTEXT size { return false; } } return parent::store($id, $data, $realm, $ttl); } /** * Writes item to cache immediately, avoiding writeback. * @param string $id Object identifier * @param mixed $data Object value * @param string $realm Realm name * @param int $ttl Time to live, 0 for unlimited * @return bool * @see Cache_driver::store() */ public function store_now($id, $data, $realm = COT_DEFAULT_REALM, $ttl = COT_DEFAULT_TTL) { global $db, $db_cache, $sys; $c_name = $db->quote($id); $c_realm = $db->quote($realm); $c_expire = $ttl > 0 ? $sys['now'] + $ttl : 0; $c_value = $db->quote(serialize($data)); $db->query("INSERT INTO $db_cache (c_name, c_realm, c_expire, c_value) VALUES ($c_name, $c_realm, $c_expire, $c_value)"); $this->buffer[$realm][$id] = $data; return $db->affectedRows == 1; } } if (extension_loaded('memcache')) { $cot_cache_drivers[] = 'Memcache_driver'; /** * Memcache distributed persistent cache driver implementation. Give it a higher priority * if a cluster of webservers is used and Memcached is running via TCP/IP between them. * In other circumstances this only should be used if no APC/XCache available, * keeping in mind that File_cache might be still faster. * @author Cotonti Team */ class Memcache_driver extends Temporary_cache_driver { /** * PHP Memcache instance * @var Memcache */ protected $memcache = NULL; /** * Creates an object and establishes Memcached server connection * @param string $host Memcached host * @param int $port Memcached port * @param bool $persistent Use persistent connection * @return Memcache_driver */ public function __construct($host = 'localhost', $port = 11211, $persistent = true) { $this->memcache = new Memcache; $this->memcache->addServer($host, $port, $persistent); } /** * Make unique key for one of different sites on one memcache pool * @param $key * @return string */ public static function createKey($key) { if (is_array($key)) $key = serialize($key); return md5(cot::$cfg['site_id'].$key); } /** * @see Cache_driver::clear() */ public function clear($realm = '') { if (empty($realm)) { return $this->memcache->flush(); } else { // FIXME implement exact realm cleanup (not yet provided by Memcache) return $this->memcache->flush(); } } /** * @see Temporary_cache_driver::dec() */ public function dec($id, $realm = COT_DEFAULT_REALM, $value = 1) { $id = self::createKey($id); return $this->memcache->decrement($realm.'/'.$id, $value); } /** * @see Cache_driver::exists() */ public function exists($id, $realm = COT_DEFAULT_REALM) { $id = self::createKey($id); return $this->memcache->get($realm.'/'.$id) !== FALSE; } /** * @see Cache_driver::get() */ public function get($id, $realm = COT_DEFAULT_REALM) { $id = self::createKey($id); return $this->memcache->get($realm.'/'.$id); } /** * @see Temporary_cache_driver::get_info() */ public function get_info() { $info = $this->memcache->getstats(); return array( 'available' => $info['limit_maxbytes'] - $info['bytes'], 'max' => $info['limit_maxbytes'], 'occupied' => $info['bytes'] ); } /** * @see Temporary_cache_driver::inc() */ public function inc($id, $realm = COT_DEFAULT_REALM, $value = 1) { $id = self::createKey($id); return $this->memcache->increment($realm.'/'.$id, $value); } /** * @see Cache_driver::remove() */ public function remove($id, $realm = COT_DEFAULT_REALM) { $id = self::createKey($id); return $this->memcache->delete($realm.'/'.$id); } /** * @see Dynamic_cache_driver::store() */ public function store($id, $data, $realm = COT_DEFAULT_REALM, $ttl = COT_DEFAULT_TTL) { $id = self::createKey($id); return $this->memcache->set($realm.'/'.$id, $data, 0, $ttl); } } } if (extension_loaded('apc')) { $cot_cache_drivers[] = 'APC_driver'; /** * Accelerated PHP Cache driver implementation. This should be used as default cacher * on APC-enabled hosts. * @author Cotonti Team */ class APC_driver extends Temporary_cache_driver { /** * @see Cache_driver::clear() */ public function clear($realm = '') { if (empty($realm)) { return apc_clear_cache(); } else { // TODO implement exact realm cleanup return FALSE; } } /** * @see Cache_driver::exists() */ public function exists($id, $realm = COT_DEFAULT_REALM) { return apc_fetch($realm.'/'.$id) !== FALSE; } /** * @see Cache_driver::get() */ public function get($id, $realm = COT_DEFAULT_REALM) { return unserialize(apc_fetch($realm.'/'.$id)); } /** * @see Temporary_cache_driver::get_info() */ public function get_info() { $info = apc_sma_info(); $max = ini_get('apc.shm_segments') * ini_get('apc.shm_size') * 1024 * 1024; $occupied = $max - $info['avail_mem']; return array( 'available' => $info['avail_mem'], 'max' => $max, 'occupied' => $occupied ); } /** * @see Cache_driver::remove() */ public function remove($id, $realm = COT_DEFAULT_REALM) { return apc_delete($realm.'/'.$id); } /** * @see Dynamic_cache_driver::store() */ public function store($id, $data, $realm = COT_DEFAULT_REALM, $ttl = COT_DEFAULT_TTL) { // Protect from exhausted memory $info = $this->get_info(); if ($info['available'] < $info['max'] * 0.2) { $this->clear(); } return apc_store($realm.'/'.$id, serialize($data), $ttl); } } } if (extension_loaded('xcache')) { $cot_cache_drivers[] = 'Xcache_driver'; /** * XCache variable cache driver. It should be used on hosts that use XCache for * PHP acceleration and variable cache. * @author Cotonti Team */ class Xcache_driver extends Temporary_cache_driver { /** * @see Cache_driver::clear() */ public function clear($realm = '') { if (function_exists('xcache_unset_by_prefix')) { if (empty($realm)) { return xcache_unset_by_prefix(''); } else { return xcache_unset_by_prefix($realm.'/'); } } else { // This does not actually mean success but we can do nothing with it return true; } } /** * @see Cache_driver::exists() */ public function exists($id, $realm = COT_DEFAULT_REALM) { return xcache_isset($realm.'/'.$id); } /** * @see Temporary_cache_driver::dec() */ public function dec($id, $realm = COT_DEFAULT_REALM, $value = 1) { return xcache_dec($realm.'/'.$id, $value); } /** * @see Cache_driver::get() */ public function get($id, $realm = COT_DEFAULT_REALM) { return xcache_get($realm.'/'.$id); } /** * @see Temporary_cache_driver::get_info() */ public function get_info() { return array( 'available' => -1, 'max' => $this->get_ini_size('xcache.var_size'), 'occupied' => -1 ); } /** * @see Temporary_cache_driver::inc() */ public function inc($id, $realm = COT_DEFAULT_REALM, $value = 1) { return xcache_inc($realm.'/'.$id, $value); } /** * @see Cache_driver::remove() */ public function remove($id, $realm = COT_DEFAULT_REALM) { return xcache_unset($realm.'/'.$id); } /** * @see Dynamic_cache_driver::store() */ public function store($id, $data, $realm = COT_DEFAULT_REALM, $ttl = COT_DEFAULT_TTL) { return xcache_set($realm.'/'.$id, $data, $ttl); } } } /** * Multi-layer universal cache controller for Cotonti * * @property-read bool $mem_available Memory storage availability flag */ class Cache { /** * Persistent cache underlayer driver. * Stores disk-only cache entries. Use it for large objects, which you don't want to put * into memory cache. * @var Static_cache_driver */ public $disk; /** * Intermediate database cache driver. * It is recommended to use memory cache for particular objects rather than DB cache. * @var Db_cache_driver */ public $db; /** * Mutable top-layer shared memory driver. * Is FALSE if memory cache is not available * @var Temporary_cache_driver */ public $mem; /** * Page cache driver. * Is FALSE if page cache is disabled * @var Page_cache */ public $page; /** * Event bindings * @var array */ private $bindings; /** * A flag to apply binding changes before termination * @var bool */ private $resync_on_exit = false; /** * Selected memory driver * @var string */ private $selected_drv = ''; /** * Initializes Page cache for early page caching */ public function __construct() { global $cfg; $this->page = new Page_cache($cfg['cache_dir'], $cfg['dir_perms']); } /** * Performs actions before script termination */ public function __destruct() { if ($this->resync_on_exit) { $this->resync_bindings(); } } /** * Property handler * @param string $name Property name * @return mixed Property value */ public function __get($name) { switch ($name) { case 'mem_available': return $this->mem !== FALSE; break; case 'mem_driver': return $this->selected_drv; break; default: return null; break; } } /** * Initializes the rest Cache components when the sources are available */ public function init() { global $cfg, $cot_cache_autoload, $cot_cache_drivers, $cot_cache_bindings, $env; $this->disk = new File_cache($cfg['cache_dir']); $this->db = new MySQL_cache(); $cot_cache_autoload = is_array($cot_cache_autoload) ? array_merge(array('system', 'cot', $env['ext']), $cot_cache_autoload) : array('system', 'cot', $env['ext']); $this->db->get_all($cot_cache_autoload); $cfg['cache_drv'] .= '_driver'; if (in_array($cfg['cache_drv'], $cot_cache_drivers)) { $selected = $cfg['cache_drv']; } if (!empty($selected)) { $mem = new $selected(); // Some drivers may be enabled but without variable cache $info = $mem->get_info(); if ($info['max'] > 1024) { $this->mem = $mem; $this->selected_drv = $selected; } } else { $this->mem = false; } if (!$cot_cache_bindings) { $this->resync_bindings(); } else { unset($cot_cache_bindings); } } /** * Rereads bindings from database */ private function resync_bindings() { // global $db, $db_cache_bindings; $this->bindings = array(); // $sql = $db->query("SELECT * FROM `$db_cache_bindings`"); // while ($row = $sql->fetch()) // { // $this->bindings[$row['c_event']][] = array('id' => $row['c_id'], 'realm' => $row['c_realm']); // } // $sql->closeCursor(); // $this->db->store('cot_cache_bindings', $this->bindings, 'system'); } /** * Binds an event to automatic cache field invalidation * @param string $event Event name * @param string $id Cache entry id * @param string $realm Cache realm name * @param int $type Storage type, one of COT_CACHE_TYPE_* values * @return bool TRUE on success, FALSE on error */ public function bind($event, $id, $realm = COT_DEFAULT_REALM, $type = COT_CACHE_TYPE_DEFAULT) { global $db, $db_cache_bindings; $c_event = $db->quote($event); $c_id = $db->quote($id); $c_realm = $db->quote($realm); $c_type = (int) $type; $db->query("INSERT INTO `$db_cache_bindings` (c_event, c_id, c_realm, c_type) VALUES ($c_event, $c_id, $c_realm, $c_type)"); $res = $db->affectedRows == 1; if ($res) { $this->resync_on_exit = true; } return $res; } /** * Binds multiple cache fields to events, all represented as an associative array * Binding keys: * event - name of the event the field is binded to * id - cache object id * realm - cache realm name * type - cache storage type, one of COT_CACHE_TYPE_* constants * @param array $bindings An indexed array of bindings. * Each binding is an associative array with keys: event, realm, id, type. * @return int Number of bindings added */ public function bind_array($bindings) { global $db, $db_cache_bindings; $q = "INSERT INTO `$db_cache_bindings` (c_event, c_id, c_realm, c_type) VALUES "; $i = 0; foreach ($bindings as $entry) { $c_event = $db->prep($entry['event']); $c_id = $db->prep($entry['id']); $c_realm = $db->prep($entry['realm']); $c_type = (int) $entry['type']; $comma = $i == 0 ? '' : ','; $q .= $comma."('$c_event', '$c_id', '$c_realm', $c_type)"; } $db->query($q); $res = $db->affectedRows; if ($res > 0) { $this->resync_on_exit = true; } return $res; } /** * Clears all cache entries * @param int $type Cache storage type: * COT_CACHE_TYPE_ALL, COT_CACHE_TYPE_DB, COT_CACHE_TYPE_DISK, COT_CACHE_TYPE_MEMORY. * @return bool */ public function clear($type = COT_CACHE_TYPE_ALL) { $res = true; switch ($type) { case COT_CACHE_TYPE_DB: $res = $this->db->clear(); break; case COT_CACHE_TYPE_DISK: $res = $this->disk->clear(); break; case COT_CACHE_TYPE_MEMORY: if ($this->mem) { $res = $this->mem->clear(); } break; case COT_CACHE_TYPE_PAGE: $res = $this->disk->clear(); break; default: if ($this->mem) { $res &= $this->mem->clear(); } $res &= $this->db->clear(); $res &= $this->disk->clear(); } return $res; } /** * Clears cache in specific realm * @param string $realm Realm name * @param int $type Cache storage type: * COT_CACHE_TYPE_ALL, COT_CACHE_TYPE_DB, COT_CACHE_TYPE_DISK, COT_CACHE_TYPE_MEMORY. */ public function clear_realm($realm = COT_DEFAULT_REALM, $type = COT_CACHE_TYPE_ALL) { switch ($type) { case COT_CACHE_TYPE_DB: $this->db->clear($realm); break; case COT_CACHE_TYPE_DISK: $this->disk->clear($realm); break; case COT_CACHE_TYPE_MEMORY: if ($this->mem) { $this->mem->clear($realm); } break; case COT_CACHE_TYPE_PAGE: $this->page->clear($realm); break; default: if ($this->mem) { $this->mem->clear($realm); } $this->db->clear($realm); $this->disk->clear($realm); $this->page->clear($realm); } } /** * Returns information about memory driver usage * @return array Usage information */ public function get_info() { if ($this->mem) { return $this->mem->get_info(); } else { return array(); } } /** * Invalidates cache cells which were binded to the event. * @param string $event Event name * @return int Number of cells cleaned */ public function trigger($event) { $cnt = 0; if (isset($this->bindings[$event]) && count($this->bindings[$event]) > 0) { foreach ($this->bindings[$event] as $cell) { switch ($cell['type']) { case COT_CACHE_TYPE_DISK: $this->disk->remove($cell['id'], $cell['realm']); break; case COT_CACHE_TYPE_DB: $this->db->remove($cell['id'], $cell['realm']); break; case COT_CACHE_TYPE_MEMORY: if ($this->mem) { $this->mem->remove($cell['id'], $cell['realm']); } break; case COT_CACHE_TYPE_PAGE: $this->page->clear($cell['realm'] . '/' . $cell['id']); break; default: if ($this->mem) { $this->mem->remove($cell['id'], $cell['realm']); } $this->disk->remove($cell['id'], $cell['realm']); $this->db->remove($cell['id'], $cell['realm']); $this->page->clear($cell['realm'] . '/' . $cell['id']); } $cnt++; } } return $cnt; } /** * Removes event/cache bindings * @param string $realm Realm name (required) * @param string $id Object identifier. Optional, if not specified, all bindings from the realm are removed. * @return int Number of bindings removed */ public function unbind($realm, $id = '') { global $db, $db_cache_bindings; $c_realm = $db->quote($realm); $q = "DELETE FROM `$db_cache_bindings` WHERE c_realm = $c_realm"; if (!empty($id)) { $c_id = $db->quote($id); $q .= " AND c_id = $c_id"; } $db->query($q); $res = $db->affectedRows; if ($res > 0) { $this->resync_on_exit = true; } return $res; } }
Java
#!/bin/bash set -x # configure tweaks mv /tmp/docker-* /etc/apt/apt.conf.d chown root:root /etc/apt/apt.conf.d/docker-* chmod 644 /etc/apt/apt.conf.d/docker-* # make sure we're fully up-to-date apt-get update && apt-get dist-upgrade -y reboot
Java
/*L * Copyright Ekagra Software Technologies Ltd. * Copyright SAIC * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/cacore-sdk-pre411/LICENSE.txt for details. */ package gov.nih.nci.system.webservice; import gov.nih.nci.system.applicationservice.ApplicationService; import gov.nih.nci.system.client.proxy.ListProxy; import gov.nih.nci.system.query.hibernate.HQLCriteria; import gov.nih.nci.system.query.nestedcriteria.NestedCriteriaPath; import gov.nih.nci.system.util.ClassCache; import gov.nih.nci.system.webservice.util.WSUtils; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.StringTokenizer; import javax.xml.rpc.ServiceException; import org.apache.log4j.Logger; import org.springframework.remoting.jaxrpc.ServletEndpointSupport; public class WSQueryImpl extends ServletEndpointSupport implements WSQuery{ private static Logger log = Logger.getLogger(WSQueryImpl.class); private static ApplicationService applicationService; private static ClassCache classCache; private static int resultCountPerQuery = 1000; public void destroy() { applicationService = null; classCache = null; resultCountPerQuery = 0; } protected void onInit() throws ServiceException { classCache = (ClassCache)getWebApplicationContext().getBean("ClassCache"); applicationService = (ApplicationService)getWebApplicationContext().getBean("ApplicationServiceImpl"); Properties systemProperties = (Properties) getWebApplicationContext().getBean("SystemProperties"); try { String count = systemProperties.getProperty("resultCountPerQuery"); log.debug("resultCountPerQuery: " + count); if (count != null) { resultCountPerQuery = Integer.parseInt(count); } } catch (Exception ex) { log.error("Exception initializing resultCountPerQuery: ", ex); throw new ServiceException("Exception initializing resultCountPerQuery: ", ex); } } public int getTotalNumberOfRecords(String targetClassName, Object criteria) throws Exception{ return getNestedCriteriaResultSet(targetClassName, criteria, 0).size(); } public List queryObject(String targetClassName, Object criteria) throws Exception { return query(targetClassName,criteria,0); } public List query(String targetClassName, Object criteria, int startIndex) throws Exception { List results = new ArrayList(); results = getNestedCriteriaResultSet(targetClassName, criteria, startIndex); List alteredResults = alterResultSet(results); return alteredResults; } private List getNestedCriteriaResultSet(String targetClassName, Object searchCriteria, int startIndex) throws Exception{ List results = new ArrayList(); String searchClassName = getSearchClassName(targetClassName); try { if(searchClassName != null && searchCriteria != null){ List<Object> paramList = new ArrayList<Object>(); paramList.add(searchCriteria); NestedCriteriaPath pathCriteria = new NestedCriteriaPath(targetClassName,paramList); results = applicationService.query(pathCriteria, startIndex, targetClassName); } else{ throw new Exception("Invalid arguments passed over to the server"); } } catch(Exception e) { log.error("WSQuery caught an exception: ", e); throw e; } return results; } public List getAssociation(Object source, String associationName, int startIndex) throws Exception { List results = new ArrayList(); String targetClassName = source.getClass().getName(); log.debug("targetClassName: " + targetClassName); String hql = "select obj."+associationName+" from "+targetClassName+" obj where obj = ?"; log.debug("hql: " + hql); List<Object> params = new ArrayList<Object>(); params.add(source); HQLCriteria criteria = new HQLCriteria(hql,params); results = getHQLResultSet(targetClassName, criteria, startIndex); List alteredResults = alterResultSet(results); return alteredResults; } private List getHQLResultSet(String targetClassName, Object searchCriteria, int startIndex) throws Exception{ List results = new ArrayList(); String searchClassName = getSearchClassName(targetClassName); try { if(searchClassName != null && searchCriteria != null){ results = applicationService.query(searchCriteria, startIndex, targetClassName); } else{ throw new Exception("Invalid arguments passed over to the server"); } } catch(Exception e) { log.error("WSQuery caught an exception: ", e); throw e; } return results; } private String getSearchClassName(String targetClassName)throws Exception { String searchClassName = ""; if(targetClassName.indexOf(",")>0){ StringTokenizer st = new StringTokenizer(targetClassName, ","); while(st.hasMoreTokens()){ String className = st.nextToken(); String validClassName = classCache.getQualifiedClassName(className); log.debug("validClassName: " + validClassName); searchClassName += validClassName + ","; } searchClassName = searchClassName.substring(0,searchClassName.lastIndexOf(",")); } else{ searchClassName = classCache.getQualifiedClassName(targetClassName); } if(searchClassName == null){ throw new Exception("Invalid class name: " + targetClassName); } return searchClassName; } private List alterResultSet(List results) { List objList; if (results instanceof ListProxy) { ListProxy listProxy = (ListProxy)results; objList = listProxy.getListChunk(); } else { objList = results; } WSUtils util = new WSUtils(); objList = (List)util.convertToProxy(null, objList); return objList; } }
Java
ls | `cat` | wc -l | wc -c
Java
package au.gov.ga.geodesy.sitelog.domain.model; import javax.validation.constraints.Size; /** * http://sopac.ucsd.edu/ns/geodesy/doc/igsSiteLog/contact/2004/baseContactLib.xsd:contactType */ public class Contact { private Integer id; @Size(max = 200) protected String name; @Size(max = 200) protected String telephonePrimary; @Size(max = 200) protected String telephoneSecondary; @Size(max = 200) protected String fax; @Size(max = 200) protected String email; @SuppressWarnings("unused") private Integer getId() { return id; } @SuppressWarnings("unused") private void setId(Integer id) { this.id = id; } /** * Return name. */ public String getName() { return name; } /** * Set name. */ public void setName(String value) { this.name = value; } /** * Return primary telephone number. */ public String getTelephonePrimary() { return telephonePrimary; } /** * Set primary telephone number. */ public void setTelephonePrimary(String value) { this.telephonePrimary = value; } /** * Return secondary telephone number. */ public String getTelephoneSecondary() { return telephoneSecondary; } /** * Set secondary telephone number. */ public void setTelephoneSecondary(String value) { this.telephoneSecondary = value; } /** * Return fax number. */ public String getFax() { return fax; } /** * Set fax number. */ public void setFax(String value) { this.fax = value; } /** * Return email address. */ public String getEmail() { return email; } /** * Set email address. */ public void setEmail(String value) { this.email = value; } }
Java
namespace Leaderboard { public enum SortBy { None, Score, Rank } }
Java
#region License Header // /******************************************************************************* // * Open Behavioral Health Information Technology Architecture (OBHITA.org) // * // * Redistribution and use in source and binary forms, with or without // * modification, are permitted provided that the following conditions are met: // * * Redistributions of source code must retain the above copyright // * notice, this list of conditions and the following disclaimer. // * * Redistributions in binary form must reproduce the above copyright // * notice, this list of conditions and the following disclaimer in the // * documentation and/or other materials provided with the distribution. // * * Neither the name of the <organization> nor the // * names of its contributors may be used to endorse or promote products // * derived from this software without specific prior written permission. // * // * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY // * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ******************************************************************************/ #endregion namespace ProCenter.Mvc.Infrastructure.Service.Completeness { #region Using Statements using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using Domain.AssessmentModule.Lookups; using ProCenter.Domain.AssessmentModule.Metadata; using ProCenter.Service.Message.Assessment; using ProCenter.Service.Message.Common.Lookups; using ProCenter.Service.Message.Metadata; #endregion /// <summary>The completeness model validtor provider class.</summary> public class CompletenessModelValidtorProvider : ModelValidatorProvider { #region Public Methods and Operators /// <summary> /// Gets a list of validators. /// </summary> /// <param name="metadata">The metadata.</param> /// <param name="context">The context.</param> /// <returns> /// A list of validators. /// </returns> public override IEnumerable<ModelValidator> GetValidators ( ModelMetadata metadata, ControllerContext context ) { if ( metadata.PropertyName != null && context is ViewContext && (context.Controller.ViewData.Model is IValidateCompleteness || context.Controller.ViewData.Model is SectionDto )) { var viewContext = context as ViewContext; if ( viewContext.ViewData != null ) { if ( ( metadata.ContainerType == typeof(ItemDto) && metadata.PropertyName == "Value" ) || ( metadata.ContainerType == typeof(LookupDto) && metadata.PropertyName == "Code" ) ) { // only care about value var sectionDto = context.Controller.ViewData.Model is IValidateCompleteness ? (context.Controller.ViewData.Model as IValidateCompleteness).CurrentSectionDto : context.Controller.ViewData.Model as SectionDto; if ( sectionDto != null ) { var propertyParts = viewContext.ViewData.TemplateInfo.GetFullHtmlFieldName ( metadata.PropertyName ).Split ( '.' ); if ( propertyParts.Length == 2 ) { var index = propertyParts[0].IndexOf ( "_Value", StringComparison.Ordinal ); if ( index != -1 ) { var code = propertyParts[0].Substring ( 0, index ); var itemDto = GetItemDtoByCode ( sectionDto, code ); if ( itemDto != null ) { var metadataItemDto = itemDto.Metadata.FindMetadataItem<RequiredForCompletenessMetadataItem> (); if ( metadataItemDto != null ) { yield return new CompletenessModelValidator ( metadata, context, metadataItemDto.CompletenessCategory ); } } } } } } } } } #endregion #region Methods private static ItemDto GetItemDtoByCode ( IContainItems sectionDto, string code ) { foreach ( var itemDto in sectionDto.Items ) { if ( itemDto.ItemDefinitionCode == code && itemDto.ItemType == ItemType.Question.CodedConcept.Code ) { return itemDto; } if ( itemDto.Items != null ) { foreach ( var childItemDto in itemDto.Items.Where ( childItemDto => childItemDto.ItemDefinitionCode == code && childItemDto.ItemType == ItemType.Question.CodedConcept.Code ) ) { return childItemDto; } foreach (var containerDto in itemDto.Items.Where(i => i.ItemType != ItemType.Question.CodedConcept.Code).OfType<IContainItems> ()) { var childItem = GetItemDtoByCode ( containerDto, code ); if ( childItem != null ) { return childItem; } } } } return null; } #endregion } }
Java
""" Commands that are available from the connect screen. """ import re import traceback from django.conf import settings from src.players.models import PlayerDB from src.objects.models import ObjectDB from src.server.models import ServerConfig from src.comms.models import Channel from src.utils import create, logger, utils, ansi from src.commands.default.muxcommand import MuxCommand from src.commands.cmdhandler import CMD_LOGINSTART # limit symbol import for API __all__ = ("CmdUnconnectedConnect", "CmdUnconnectedCreate", "CmdUnconnectedQuit", "CmdUnconnectedLook", "CmdUnconnectedHelp", "Magic") CONNECTION_SCREEN_MODULE = settings.CONNECTION_SCREEN_MODULE CONNECTION_SCREEN = "" try: CONNECTION_SCREEN = ansi.parse_ansi(utils.string_from_module(CONNECTION_SCREEN_MODULE)) except Exception: pass if not CONNECTION_SCREEN: CONNECTION_SCREEN = "\nEvennia: Error in CONNECTION_SCREEN MODULE (randomly picked connection screen variable is not a string). \nEnter 'help' for aid." class Magic(MuxCommand): """ Hidden command for the web client's magic cookie authenticator. """ key = "magic" def func(self): session = self.caller player = PlayerDB.objects.player_search(self.lhs) if len(player) != 1: player = None else: player = player[0] if player.name.lower() != self.lhs.lower(): player=None pswd = None if player: pswd = self.rhs == player.db.magic_cookie if not (player and pswd): # No playername or password match session.msg("Could not verify Magic Cookie. Please email the server administrator for assistance.") return # Check IP and/or name bans bans = ServerConfig.objects.conf("server_bans") if bans and (any(tup[0]==player.name for tup in bans) or any(tup[2].match(session.address[0]) for tup in bans if tup[2])): # this is a banned IP or name! string = "{rYou have been banned and cannot continue from here." string += "\nIf you feel this ban is in error, please email an admin.{x" session.msg(string) session.execute_cmd("quit") return session.sessionhandler.login(session, player) class Connect(MuxCommand): """ Connect to the game. Usage (at login screen): connect playername password connect "player name" "pass word" Use the create command to first create an account before logging in. If you have spaces in your name, enclose it in quotes. """ key = "connect" aliases = ["conn", "con", "co"] locks = "cmd:all()" # not really needed def func(self): """ Uses the Django admin api. Note that unlogged-in commands have a unique position in that their func() receives a session object instead of a source_object like all other types of logged-in commands (this is because there is no object yet before the player has logged in) """ session = self.caller args = self.args # extract quoted parts parts = [part.strip() for part in re.split(r"\"|\'", args) if part.strip()] if len(parts) == 1: # this was (hopefully) due to no quotes being found parts = parts[0].split(None, 1) if len(parts) != 2: session.msg("\n\r Usage (without <>): connect <name> <password>") return playername, password = parts # Match account name and check password player = PlayerDB.objects.player_search(playername) if len(player) != 1: player = None else: player = player[0] if player.name.lower() != playername.lower(): player=None pswd = None if player: pswd = player.check_password(password) if not (player and pswd): # No playername or password match string = "Wrong login information given.\nIf you have spaces in your name or " string += "password, don't forget to enclose it in quotes. Also capitalization matters." string += "\nIf you are new you should first create a new account " string += "using the 'create' command." session.msg(string) return # Check IP and/or name bans bans = ServerConfig.objects.conf("server_bans") if bans and (any(tup[0]==player.name for tup in bans) or any(tup[2].match(session.address[0]) for tup in bans if tup[2])): # this is a banned IP or name! string = "{rYou have been banned and cannot continue from here." string += "\nIf you feel this ban is in error, please email an admin.{x" session.msg(string) session.execute_cmd("quit") return # actually do the login. This will call all other hooks: # session.at_init() # if character: # at_first_login() # only once # at_pre_login() # player.at_post_login() - calls look if no character is set # character.at_post_login() - this calls look command by default session.sessionhandler.login(session, player) class Create(MuxCommand): """ Create a new account. Usage (at login screen): create <playername> <password> create "player name" "pass word" This creates a new player account. If you have spaces in your name, enclose it in quotes. """ key = "create" aliases = ["cre", "cr"] locks = "cmd:all()" def func(self): "Do checks and create account" session = self.caller args = self.args.strip() # extract quoted parts parts = [part.strip() for part in re.split(r"\"|\'", args) if part.strip()] if len(parts) == 1: # this was (hopefully) due to no quotes being found parts = parts[0].split(None, 1) if len(parts) != 2: string = "\n Usage (without <>): create <name> <password>" string += "\nIf <name> or <password> contains spaces, enclose it in quotes." session.msg(string) return playername, password = parts print "playername '%s', password: '%s'" % (playername, password) # sanity checks if not re.findall('^[\w. @+-]+$', playername) or not (0 < len(playername) <= 30): # this echoes the restrictions made by django's auth module (except not # allowing spaces, for convenience of logging in). string = "\n\r Playername can max be 30 characters or fewer. Letters, spaces, digits and @/./+/-/_ only." session.msg(string) return # strip excessive spaces in playername playername = re.sub(r"\s+", " ", playername).strip() if PlayerDB.objects.filter(user__username__iexact=playername) or PlayerDB.objects.filter(username__iexact=playername): # player already exists (we also ignore capitalization here) session.msg("Sorry, there is already a player with the name '%s'." % playername) return if not re.findall('^[\w. @+-]+$', password) or not (3 < len(password)): string = "\n\r Password should be longer than 3 characers. Letters, spaces, digits and @\.\+\-\_ only." string += "\nFor best security, make it longer than 8 characters. You can also use a phrase of" string += "\nmany words if you enclose the password in quotes." session.msg(string) return # everything's ok. Create the new player account. try: default_home = ObjectDB.objects.get_id(settings.CHARACTER_DEFAULT_HOME) typeclass = settings.BASE_CHARACTER_TYPECLASS permissions = settings.PERMISSION_PLAYER_DEFAULT try: new_character = create.create_player(playername, None, password, permissions=permissions, character_typeclass=typeclass, character_location=default_home, character_home=default_home) except Exception: session.msg("There was an error creating the default Character/Player:\n%s\n If this problem persists, contact an admin.") return new_player = new_character.player # This needs to be called so the engine knows this player is logging in for the first time. # (so it knows to call the right hooks during login later) utils.init_new_player(new_player) # join the new player to the public channel pchanneldef = settings.CHANNEL_PUBLIC if pchanneldef: pchannel = Channel.objects.get_channel(pchanneldef[0]) if not pchannel.connect_to(new_player): string = "New player '%s' could not connect to public channel!" % new_player.key logger.log_errmsg(string) # allow only the character itself and the player to puppet this character (and Immortals). new_character.locks.add("puppet:id(%i) or pid(%i) or perm(Immortals) or pperm(Immortals)" % (new_character.id, new_player.id)) # If no description is set, set a default description if not new_character.db.desc: new_character.db.desc = "This is a Player." # tell the caller everything went well. string = "A new account '%s' was created. Welcome!" if " " in playername: string += "\n\nYou can now log in with the command 'connect \"%s\" <your password>'." else: string += "\n\nYou can now log with the command 'connect %s <your password>'." session.msg(string % (playername, playername)) except Exception: # We are in the middle between logged in and -not, so we have to handle tracebacks # ourselves at this point. If we don't, we won't see any errors at all. string = "%s\nThis is a bug. Please e-mail an admin if the problem persists." session.msg(string % (traceback.format_exc())) logger.log_errmsg(traceback.format_exc()) class CmdUnconnectedQuit(MuxCommand): """ We maintain a different version of the quit command here for unconnected players for the sake of simplicity. The logged in version is a bit more complicated. """ key = "quit" aliases = ["q", "qu"] locks = "cmd:all()" def func(self): "Simply close the connection." session = self.caller session.msg("Good bye! Disconnecting ...") session.session_disconnect() class CmdUnconnectedLook(MuxCommand): """ This is an unconnected version of the look command for simplicity. This is called by the server and kicks everything in gear. All it does is display the connect screen. """ key = CMD_LOGINSTART aliases = ["look", "l"] locks = "cmd:all()" def func(self): "Show the connect screen." self.caller.msg(CONNECTION_SCREEN) class CmdUnconnectedHelp(MuxCommand): """ This is an unconnected version of the help command, for simplicity. It shows a pane of info. """ key = "help" aliases = ["h", "?"] locks = "cmd:all()" def func(self): "Shows help" string = \ """ You are not yet logged into the game. Commands available at this point: {wcreate, connect, look, help, quit{n To login to the system, you need to do one of the following: {w1){n If you have no previous account, you need to use the 'create' command. {wcreate Anna c67jHL8p{n Note that if you use spaces in your name, you have to enclose in quotes. {wcreate "Anna the Barbarian" c67jHL8p{n It's always a good idea (not only here, but everywhere on the net) to not use a regular word for your password. Make it longer than 6 characters or write a passphrase. {w2){n If you have an account already, either because you just created one in {w1){n above or you are returning, use the 'connect' command: {wconnect Anna c67jHL8p{n (Again, if there are spaces in the name you have to enclose it in quotes). This should log you in. Run {whelp{n again once you're logged in to get more aid. Hope you enjoy your stay! You can use the {wlook{n command if you want to see the connect screen again. """ self.caller.msg(string)
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_14) on Fri Sep 18 14:09:15 BST 2009 --> <TITLE> uk.org.mygrid.cagrid.servicewrapper.service.interproscan.stubs </TITLE> <META NAME="date" CONTENT="2009-09-18"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="uk.org.mygrid.cagrid.servicewrapper.service.interproscan.stubs"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/service/globus/resource/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/stubs/bindings/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../../index.html?uk/org/mygrid/cagrid/servicewrapper/service/interproscan/stubs/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <H2> Package uk.org.mygrid.cagrid.servicewrapper.service.interproscan.stubs </H2> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Interface Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/stubs/InterProScanPortType.html" title="interface in uk.org.mygrid.cagrid.servicewrapper.service.interproscan.stubs">InterProScanPortType</A></B></TD> <TD>&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Class Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/stubs/InterProScanRequest.html" title="class in uk.org.mygrid.cagrid.servicewrapper.service.interproscan.stubs">InterProScanRequest</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/stubs/InterProScanRequestInterProScanInput.html" title="class in uk.org.mygrid.cagrid.servicewrapper.service.interproscan.stubs">InterProScanRequestInterProScanInput</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/stubs/InterProScanResourceProperties.html" title="class in uk.org.mygrid.cagrid.servicewrapper.service.interproscan.stubs">InterProScanResourceProperties</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/stubs/InterProScanResponse.html" title="class in uk.org.mygrid.cagrid.servicewrapper.service.interproscan.stubs">InterProScanResponse</A></B></TD> <TD>&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <DL> </DL> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/service/globus/resource/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/stubs/bindings/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../../index.html?uk/org/mygrid/cagrid/servicewrapper/service/interproscan/stubs/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
Java
package edu.cmu.minorthird.text.gui; import edu.cmu.minorthird.text.FancyLoader; import edu.cmu.minorthird.text.TextLabels; import edu.cmu.minorthird.util.gui.ControlledViewer; import edu.cmu.minorthird.util.gui.VanillaViewer; import edu.cmu.minorthird.util.gui.Viewer; import edu.cmu.minorthird.util.gui.ViewerFrame; import edu.cmu.minorthird.util.gui.ZoomedViewer; /** * View the contents of a bunch of spans, using the util.gui.Viewer framework. * * <p> Hopefully this will evolve into a cleaner version of the * TextBaseViewer, TextBaseEditor, etc suite. It replaces an earlier * attempt, the SpanLooperViewer. * * @author William Cohen */ public class ZoomingTextLabelsViewer extends ZoomedViewer{ static final long serialVersionUID=20080202L; public ZoomingTextLabelsViewer(TextLabels labels){ Viewer zoomedOut=new ControlledViewer(new TextLabelsViewer(labels),new MarkupControls(labels)); Viewer zoomedIn=new VanillaViewer("[Empty TextBase]"); if(labels.getTextBase().size()>0){ zoomedIn=new SpanViewer(labels,labels.getTextBase().documentSpanIterator().next()); } this.setSubViews(zoomedOut,zoomedIn); } // test case public static void main(String[] argv){ try{ final TextLabels labels=FancyLoader.loadTextLabels(argv[0]); new ViewerFrame(argv[0],new ZoomingTextLabelsViewer(labels)); }catch(Exception e){ e.printStackTrace(); System.out.println("Usage: labelKey"); } } }
Java
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE TupleSections #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Test.PGConstant ( TestPGConstant(..) , spec ) where import Data.Proxy (Proxy(..)) import Database.PostgreSQL.Simple.Bind.Parser import Test.Hspec (Spec, describe) import Test.QuickCheck (Arbitrary(..), oneof) import Test.Common (PGSql(..)) import Test.Utils (propParsingWorks) import Test.PGString (TestPGString(..)) data TestPGConstant = TPGCString TestPGString | TPGCNumeric Double deriving (Show, Eq) instance Arbitrary TestPGConstant where arbitrary = oneof [ TPGCString <$> arbitrary , TPGCNumeric <$> arbitrary] instance PGSql TestPGConstant where render (TPGCString s) = render s render (TPGCNumeric c) = show c spec :: Spec spec = do describe "pgConstant" $ do propParsingWorks pgConstant (Proxy :: Proxy TestPGConstant)
Java
<?php $modules["recurringinvoices"]["name"] = "Recurring Invoices"; $modules["recurringinvoices"]["version"] = "1.01"; $modules["recurringinvoices"]["description"] = "This module adds the ability to repeat invoices on a scheduled basis."; $modules["recurringinvoices"]["requirements"] = "phpBMS Core v0.9 or greater; BMS module v0.9 or greater; phpBMS Scheduler activated through cron or other scheduling program."; ?>
Java
/* eslint-disable no-underscore-dangle */ export default function ({ client, filterQuery, mustContain, busy, encodeQueryAsString, }) { return { listUsers(query) { const params = filterQuery( query, 'text', 'limit', 'offset', 'sort', 'sortdir' ); return busy( client._.get('/user', { params, }) ); }, createUser(user) { const expected = [ 'login', 'email', 'firstName', 'lastName', 'password', 'admin', ]; const params = filterQuery(user, ...expected); const { missingKeys, promise } = mustContain(user, ...expected); return missingKeys ? promise : busy(client._.post(`/user${encodeQueryAsString(params)}`)); }, changePassword(old, newPassword) { const params = { old, new: newPassword, }; return busy(client._.put(`/user/password${encodeQueryAsString(params)}`)); }, resetPassword(email) { const params = { email, }; return busy( client._.delete('/user/password', { params, }) ); }, deleteUser(id) { return busy(client._.delete(`/user/${id}`)); }, getUser(id) { return busy(client._.get(`/user/${id}`)); }, updateUser(user) { const expected = ['email', 'firstName', 'lastName', '_id']; const params = filterQuery(user, ...expected.slice(0, 3)); // Remove '_id' const { missingKeys, promise } = mustContain(user, ...expected); return missingKeys ? promise : busy(client._.put(`/user/${user._id}${encodeQueryAsString(params)}`)); }, }; }
Java
<!DOCTYPE HTML> <html> <head> <style> body { margin: 0px; padding: 0px; } </style> </head> <body> <div id="container"></div> <script src="KineticJS/kinetic.js"></script> <script src="kiigame.js"></script> <script src="latkazombit.js"></script> </body> </html>
Java
module.exports = (function () { var TypeChecker = Cactus.Util.TypeChecker; var JSON = Cactus.Util.JSON; var stringify = JSON.stringify; var object = Cactus.Addon.Object; var collection = Cactus.Data.Collection; var gettype = TypeChecker.gettype.bind(TypeChecker); return { "null and undefined" : function () { var o = new TypeChecker({ type : "number" }); exception(/Expected "number", but got undefined \(type "undefined"\)/, o.parse.bind(o, undefined)); exception(/Expected "number", but got null \(type "null"\)/, o.parse.bind(o, null)); }, "required values" : function () { var o = new TypeChecker({ required : false, type : "boolean" }); equal(true, o.parse(true)); o.parse(null); }, "default value" : function () { var o = new TypeChecker({ type : "number", defaultValue : 3 }); assert.eql(3, o.parse(null)); assert.eql(4, o.parse(4)); o = new TypeChecker({ type : { a : { type : "number", defaultValue : 1 } } }); var h = o.parse({ a : 2 }); assert.eql(2, o.parse({ a : 2}).a); assert.eql(1, o.parse({ a : null }).a); assert.eql(1, o.parse({}).a); o = new TypeChecker({ type : { x : { type : "boolean", defaultValue : false } } }); eql({ x : true }, o.parse({ x : true })); eql({ x : false }, o.parse({ x : false })); eql({ x : false }, o.parse({})); // When not passing bool properties. o = new TypeChecker({ type : { b : { type : "boolean", defaultValue : false } } }); eql({ b : false }, o.parse({})); // Default values with incorrect types should have special error message (always throw error) exception(/Expected "boolean", but got 1/, function () { return new TypeChecker({ type : "boolean", defaultValue : 1 }); }); }, defaultValueFunc : function () { var o = new TypeChecker({ defaultValueFunc : function () { return 1; }, type : "number" }); assert.strictEqual(1, o.parse(null)); o = new TypeChecker({ type : { a : { defaultValueFunc : function () { return 2; }, type : "number" } } }); assert.strictEqual(2, o.parse({ a : null }).a); assert.strictEqual(2, o.parse({}).a); // defaultValueFunc return value must match type. exception(/expected "boolean", but got 1/i, function () { return new TypeChecker({ defaultValueFunc : function () { return 1; }, type : "boolean" }).parse(undefined); }); exception(/expected "boolean", but got 1/i, function () { return new TypeChecker({ type : { a : { defaultValueFunc : function () { return 1; }, type : "boolean" } } }).parse({}); }); }, validators : function () { var o = new TypeChecker({ type : "number", validators : [{ func : function (v) { return v > 0; } }] }); o.parse(1); o.parse(0, false); eql({ "" : ["Validation failed: got 0."] }, o.getErrors()); // Validation error message. o = new TypeChecker({ type : "number", validators : [{ func : function (v) { return v > 0; }, message : "Expected positive number." }] }); o.parse(1); exception(/TypeChecker: Error: Expected positive number./, o.parse.bind(o, 0)); eql({ "" : ["Expected positive number."] }, o.getErrors()); // Multiple ordered validators. o = new TypeChecker({ type : "number", validators : [{ func : function (v) { return v > -1; }, message : "Expected number bigger than -1." }, { func : function (v) { return v < 1; }, message : "Expected number smaller than 1." }] }); o.parse(0); exception(/Expected number bigger than -1/i, o.parse.bind(o, -1)); exception(/Expected number smaller than 1/i, o.parse.bind(o, 1)); o = new TypeChecker({ type : "number", validators : [{ func : function (v) { return v > 0; }, message : "Expected number bigger than 0." }, { func : function (v) { return v > 1; }, message : "Expected number bigger than 1." }] }); o.parse(2); exception(/bigger than 0.+ bigger than 1./i, o.parse.bind(o, 0)); }, "simple interface" : function () { var o = TypeChecker.simple("number"); o.parse(1); o = TypeChecker.simple(["number"]); o.parse([1]); o = TypeChecker.simple({ a : "number", b : "boolean" }); o.parse({ a : 1, b : true }); o = TypeChecker.simple({ a : ["number"] }); o.parse({ a : [1] }); o = TypeChecker.simple({ a : { b : "boolean" } }); o.parse({ a : { b : true } }); // Classes. Class("X"); o = TypeChecker.simple({ _type : X }); o.parse(new X()); o = TypeChecker.simple({ a : { _type : X } }); o.parse({ a : new X() }); }, errorHash : function () { var o = TypeChecker.simple("string"); exception(/Nothing parsed/i, o.hasErrors.bind(o)); exception(/Nothing parsed/i, o.getErrors.bind(o)); o.parse("x", false); exception(/No errors exist/, o.getErrors.bind(o)); o.parse(1, false); ok(o.hasErrors()); var errors = o.getErrors(); ok(o.hasErrorsFor("")); not(o.hasErrorsFor("foo")); eql({ "" : ['Expected "string", but got 1 (type "number")'] }, o.getErrors()); o = TypeChecker.simple({ a : "number", b : "number" }); o.parse({ a : "x", b : true }, false); ok(o.hasErrors()); eql({ a : ['Expected "number", but got "x" (type "string")'], b : ['Expected "number", but got true (type "boolean")'] }, o.getErrors()); ok(o.hasErrorsFor("a")); ok(o.hasErrorsFor("b")); eql(['Expected "number", but got "x" (type "string")'], o.getErrorsFor("a")); eql(['Expected "number", but got true (type "boolean")'], o.getErrorsFor("b")); o = new TypeChecker({ type : "number", validators : [{ func : Function.returning(false), message : "false" }] }); o.parse(1, false); eql({ "" : ["false"] }, o.getErrors()); // Errors for array validators. o = new TypeChecker({ type : { p : { type : "string", validators : [{ func : Function.returning(false), message : "Error #1." }, { func : Function.returning(false), message : "Error #2." }] } } }); o.parse({ p : "" }, false); eql({ p : ["Error #1.", "Error #2."] }, o.getErrors()); // When Error is thrown, there should be a hash property with the error // messages as well. o = new TypeChecker({ type : "string" }); o.parse(1, false); assert.throws(o.parse.bind(o, 1), function (e) { assert.ok(/expected "string".+got 1 \(type "number"\)/i.test(e.message)); assert.ok("hash" in e, "Missing hash property"); eql({ "" : ['Expected "string", but got 1 (type "number")'] }, e.hash); return true; }); }, validators2 : function () { // Validators should run only if all other validations pass. var ran = false; var o = new TypeChecker({ type : "number", defaultValue : 0, validators : [{ func : function (v) { ran = true; return v === 0; }, message : "Only way to validate is to send null or 0." }] }); o.parse(0); o.parse("x", false); eql({ "" : [ 'Expected "number", but got "x" (type "string")', 'Only way to validate is to send null or 0.' ] }, o.getErrors()); // Do not run validators if constraints fail. o.parse("x", false); assert.strictEqual(1, object.count(o.getErrors())); o.parse(-1, false); eql({ "" : ["Only way to validate is to send null or 0."] }, o.getErrors()); // Default value should be applied before validation as well. ran = false; assert.strictEqual(0, o.parse(null)); assert.ok(ran, "Validation did not run."); }, "predefined validations" : function () { var o = new TypeChecker({ type : "number", validators : ["natural"] }); o.parse(1); o.parse(0); o.parse(-1, false); eql({ "" : ["Expected natural number."] }, o.getErrors()); o = new TypeChecker({ type : "number", validators : ["positive"] }); o.parse(1); o.parse(0, false); eql({ "" : ["Expected positive number."] }, o.getErrors()); o = new TypeChecker({ type : "number", validators : ["negative"] }); o.parse(-1); o.parse(0, false); eql({ "" : ["Expected negative number."] }, o.getErrors()); o = new TypeChecker({ type : "number", validators : ["x"] }); exception(/Undefined built in validator "x"/i, o.parse.bind(o, 1)); o = new TypeChecker({ type : { a : { type : "number", validators : ["x"] } } }); exception(/Undefined built in validator "x"/i, o.parse.bind(o, { a : 1 })); o = new TypeChecker({ type : "string", validators : ["non empty string"] }); o.parse("x"); o.parse("", false); eql({ "" : ["Expected non-empty string."] }, o.getErrors()); }, T_Array : function () { eql([{ type : "string" }], gettype(new TypeChecker.types.T_Array({ type : "string" }))); var o = new TypeChecker({ type : [{ type : "number" }] }); eql([1, 2], o.parse([1, 2])); eql([], o.parse([])); exception(/Expected \[\{"type":"number"\}\], but got "a" \(type "string"\)/i, o.parse.bind(o, "a")); exception(/error in property "0": expected "number", but got "a" \(type "string"\)/i, o.parse.bind(o, ["a"])); exception(/error in property "1": expected "number", but got true \(type "boolean"\)/i, o.parse.bind(o, [1, true])); exception(/error in property "0": expected "number", but got "a"[\s\S]+error in property "1": expected "number", but got true/i, o.parse.bind(o, ["a", true])); // Nesting of arrays. var o = new TypeChecker({ type : [{ type : [{ type : "number" }] }] }); eql([[1, 2]], o.parse([[1, 2]])); exception(/^TypeChecker: Error in property "0": expected \[\{"type":"number"\}\], but got 1/i, o.parse.bind(o, [1, [2, 3]])); exception(/^TypeChecker: Error in property "1.1": expected "number", but got true/i, o.parse.bind(o, [[1], [2, true]])); eql([[]], o.parse([[]])); eql([], o.parse([])); // Optional arrays. o = new TypeChecker({ type : [{ type : "mixed" }], defaultValue : [] }); o.parse(null); // Optional array in hash. o = new TypeChecker({ type : { a : { type : [{ type : "number" }], defaultValue : [] } } }); o.parse({}); }, T_Primitive : function () { var o = new TypeChecker({ type : "string" }); assert.eql("aoeu", o.parse("aoeu")); exception(/expected "string", but got 1 \(type "number"\)/i, o.parse.bind(o, 1)); exception(/expected "string", but got true \(type "boolean"\)/i, o.parse.bind(o, true)); o = new TypeChecker({ type : "number" }); assert.eql(100, o.parse(100)); exception(/^TypeChecker: Error: Expected "number", but got "1" \(type "string"\)$/, o.parse.bind(o, "1")); // Default values o = new TypeChecker({ type : "boolean", defaultValue : false }); o.parse(true); o.parse(false); not(o.parse(null)); }, T_Enumerable : function () { var o = new TypeChecker({ enumerable : [1,2,3] }); eql(1, o.parse(1)); o.parse(2); o.parse(3); exception(/^TypeChecker: Error: Expected a value in \[1,2,3\], but got 0$/, o.parse.bind(o, 0)); exception(/^TypeChecker: Error: Expected a value in \[1,2,3\], but got 4$/, o.parse.bind(o, 4)); eql({ enumerable : [1,2,3] }, gettype(new TypeChecker.types.T_Enumerable([1, 2, 3]))); }, "T_Union" : function () { var o = new TypeChecker({ union : ["string", "number"] }); eql(1, o.parse(1)); eql("x", o.parse("x")); exception(/Expected a Union/, o.parse.bind(o, true)); eql({ union : [ { type : "string"}, { type : "number" } ]}, gettype(new TypeChecker.types.T_Union([ { type : "string" }, { type : "number" } ]))); }, "T_Instance" : function () { var Foo2 = Class("Foo2", {}); Class("Bar", { isa : Foo2 }); var o = new TypeChecker({ type : Foo2 }); var foo2 = new Foo2(); equal(foo2, o.parse(foo2)); o.parse(new Bar()); exception(/Expected an instance of "Foo2", but got value <1> \(type "number"\)/, o.parse.bind(o, 1)); Class("Baz"); exception(/Expected an instance of "Foo2", but got value <a Baz> \(type "Baz"\)$/, o.parse.bind(o, new Baz())); // Non-Joose classes. function Bax() { } function Qux() { } Qux.extend(Bax); o = new TypeChecker({ type : Bax }); o.parse(new Bax()); o.parse(new Qux()); function Qax() { } Qax.prototype.toString = function () { return "my Qax"; }; exception(/Expected an instance of "Bax", but got value <1> \(type "number"\)/, o.parse.bind(o, 1)); exception(/Expected an instance of "Bax", but got value <my Qax> \(type "Qax"\)$/, o.parse.bind(o, new Qax())); // Anonymous classes. var F = function () {}; var G = function () {}; o = new TypeChecker({ type : F }); G.extend(F); o.parse(new F()); o.parse(new G()); var H = function () {}; H.prototype.toString = Function.returning("my H"); exception(/Expected an instance of "anonymous type", but got value <1>/, o.parse.bind(o, 1)); exception(/Expected an instance of "anonymous type", but got value <my H> \(type "anonymous type"\)/i, o.parse.bind(o, new H())); function I() {} equal(I, gettype(new TypeChecker.types.T_Instance(I)).type); }, T_Hash : function () { var o = new TypeChecker({ x : { type : "boolean" } }); eql({ x : { type : "boolean" } }, gettype(new TypeChecker.types.T_Hash({ x : { type : "boolean" } }))); o = new TypeChecker({ type : { a : { type : "number" }, b : { type : "boolean" } } }); eql({ a : 1, b : true }, o.parse({ a : 1, b : true })); o = new TypeChecker({ type : { a : { type : "number" }, b : { type : "boolean" } } }); exception(/Expected \{"a":\{"type":"number"\},"b":\{"type":"boolean"\}\}, but got 1/i, o.parse.bind(o, 1)); exception(/Error in property "a": expected "number", but got "2"/i, o.parse.bind(o, { a : "2", b : true })); exception(/Error in property "a": expected "number", but got "2"[\s\S]+Error in property "b": expected "boolean", but got "2"/i, o.parse.bind(o, { a : "2", b : "2" })); exception(/Error in property "b": Missing property/, o.parse.bind(o, { a : 1 })); exception(/Error in property "c": Property lacks definition/i, o.parse.bind(o, { a : 1, b : true, c : "1" })); // With required specified. o = new TypeChecker({ type : { name : { type : "string", required : true } } }); assert.throws(o.parse.bind(o, {}), function (e) { assert.ok(/"name": Missing property/.test(e.message)); return true; }); // Non-required properties. o = new TypeChecker({ type : { a : { type : "number", required : false }, b : { type : "boolean", required : false } } }); eql({ a : 1, b : false }, o.parse({ a : 1, b : false })); var h = o.parse({ a : 1, b : undefined }); ok(!("b" in h)); h = o.parse({ a : 1, b : null }); equal(null, h.b); h = o.parse({ a : undefined, b : undefined }); ok(object.isEmpty(h)); h = o.parse({}); ok(object.isEmpty(h)); // Skip properties not in definition. o = new TypeChecker({ allowUndefined : true, type : { a : { type : "number" } } }); o.parse({}, false); eql({ a : ["Missing property"] }, o.getErrors()); o.parse({ a : 1 }); o.parse({ a : 1, b : 2 }); o.parse({ b : 2 }, false); eql({ a : ["Missing property"] }, o.getErrors()); // Remove skipped props that are undefined. eql({ a : 1 }, o.parse({ a : 1 })); }, T_Map : function () { var o = new TypeChecker({ map : true, type : "number" }); eql({ a : 1, b : 1 }, o.parse({ a : 1, b : 1 })); o.parse({ a : 1, b : false }, false); eql({ b : ['Expected "number", but got false (type "boolean")'] }, o.getErrors()); }, "T_Mixed" : function () { var o = new TypeChecker({ type : "mixed" }); equal(true, o.parse(true)); o.parse(""); o.parse({}); eql([], o.parse([])); ok(null === o.parse(null)); ok(undefined === o.parse(undefined)); equal("mixed", gettype(new TypeChecker.types.T_Mixed())); }, "typeof" : function () { var t = TypeChecker.typeof.bind(TypeChecker); equal("number", t(1)); equal("boolean", t(true)); equal("undefined", t(undefined)); equal("null", t(null)); equal("Function", t(function () {})); equal("Object", t({})); equal("Array", t([])); Class("JooseClass"); equal("JooseClass", t(new JooseClass())); function MyClass() {} equal("MyClass", t(new MyClass())); var AnonymousClass = function () {}; equal("anonymous type", t(new AnonymousClass)); }, "BUILD errors" : function () { exception(/Must be a hash/i, function () { return new TypeChecker(); }); exception(/May only specify one of required, defaultValue and defaultValueFunc/i, function () { return new TypeChecker({ required : true, defaultValue : 1 }); }); // required or defaultValue or defaultValueFunc }, helpers : function () { //var tc = new TypeChecker({ // type : "number", // validators : [{ // func : function (o, helpers) { // return !!helpers; // }, // message : "helpers == false" // }] //}); //tc.parse(1, true, true); //tc.parse(1, false, true); //eql({ // "" : ["helpers == false"] //}, tc.getErrors()); }, "recursive definition" : function () { var o = new TypeChecker({ type : { // type type : { required : false, type : "mixed", validators : [{ func : function (v) { if (typeof v === "string") { return collection.hasValue(["string", "number", "object", "function", "boolean", "mixed"], v); } else if (v instanceof Array) { // Flat check only. return v.length === 1; } else if (v instanceof Object) { // Flat check only. return true; } return false; } }] }, required : { type : "boolean", defaultValue : true }, defaultValue : { required : false, type : "mixed" }, defaultValueFunc : { required : false, type : Function }, validators : { type : [{ type : { func : { type : Function }, message : { type : "string" } } }], defaultValue : [] }, enumerable : { required : false, type : Array }, allowUndefined : { defaultValue : false, type : "boolean" } } }); o.parse({ type : "string" }); o.parse({ type : "number" }); o.parse({ required : false, type : "number" }); o.parse({ defaultValue : 3, type : "number" }); o.parse({ defaultValue : true, type : "boolean" }); o.parse({ defaultValue : 4, type : "mixed" }); o.parse({ defaultValue : {}, type : "mixed" }); o.parse({ defaultValueFunc : function () { return 1; }, type : "number" }); o.parse({ type : [{ type : "string" }] }); o.parse({ type : "mixed", validators : [{ func : Function.empty, message : "msg" }] }); o.parse({ type : "number", enumerable : [1,2,3] }); o.parse({ type : {} }); o.parse({ allowUndefined : true, type : {} }); } }; })();
Java
<?php namespace common\models; use Yii; /** * This is the model class for table "mcp_accesslogs". * * @property integer $user_id * @property string $browser * @property string $ip * @property string $session * @property string $intime * @property string $outtime */ class McpAccesslogs extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'mcp_accesslogs'; } /** * @return \yii\db\Connection the database connection used by this AR class. */ public static function getDb() { return Yii::$app->get('oldcmsdb'); } /** * @inheritdoc */ public function rules() { return [ [['user_id'], 'integer'], [['intime', 'outtime'], 'safe'], [['browser'], 'string', 'max' => 255], [['ip'], 'string', 'max' => 30], [['session'], 'string', 'max' => 40] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'user_id' => 'user,s reference', 'browser' => 'Browser', 'ip' => 'Ip', 'session' => 'Session', 'intime' => 'Intime', 'outtime' => 'Outtime', ]; } }
Java
--- title: "Permissions - ACLs" weight: 3 card: name: concept_organization --- There are 3 types of permissions: + Read (as code value: 4) + Read / Execute (as code value: 5) + Read / Write / Execute (as code value: 7) These permissions can be attached to different objects: + Project + Workflow + Workflow node | | Project | Workflow | Workflow node | |---------------------------------------------------------------------------------------|---------|----------|---------------------------------------------| | Create a workflow | RWX | - | - | | Edit a workflow (change run conditions, add nodes, edit payload, notifications, ...) | RO | RWX | - | | Create/edit an environment/pipeline/application | RWX | - | - | | Manage permissions on project | RWX | - | - | | Manage permissions on a workflow | RO | RWX | | | Run a workflow | RO | RX | / - OR RX (if there is some groups on node) | Permissions cannot be attached directly to users, they need to be attached to groups of users. Users inherit their permissions from the groups they are belonging to. Example usage: Enforce a strict separation of duties by allowing a group of people to view/inspect a workflow, a second group will be able to push it to a `deploy-to-staging` node and a third group will be allowed to push it to a `deploy-to-production` node. You can have a fourth group responsible of editing the workflow if needed. A more common scenario consists in giving `Read / Execute` permissions on the node `deploy-to-staging` to everyone in your development team while restricting the `deploy-to-production` node and the project edition to a smaller group of users. **Warning:** when you add a new group permission on a workflow node, **only the groups linked on the node will be taken in account**.
Java
/** * Swedish translation for bootstrap-wysihtml5 */ (function($){ $.fn.wysihtml5.locale["sv-SE"] = { font_styles: { normal: "Normal Text", h1: "Rubrik 1", h2: "Rubrik 2", h3: "Rubrik 3" }, emphasis: { bold: "Fet", italic: "Kursiv", underline: "Understruken" }, lists: { unordered: "Osorterad lista", ordered: "Sorterad lista", outdent: "Minska indrag", indent: "Öka indrag" }, link: { insert: "Lägg till länk", cancel: "Avbryt" }, image: { insert: "Lägg till Bild", cancel: "Avbryt" }, html: { edit: "Redigera HTML" }, colours: { black: "Svart", silver: "Silver", gray: "Grå", maroon: "Kastaniebrun", red: "Röd", purple: "Lila", green: "Grön", olive: "Olivgrön", navy: "Marinblå", blue: "Blå", orange: "Orange" } }; }(jQuery));
Java
<?php namespace Tests\Unit; use Tests\TestCase; use Illuminate\Foundation\Testing\RefreshDatabase; class TextPostTest extends TestCase { use RefreshDatabase; protected $textPost; public function setup() { parent::setUp(); $this->authenticate(); $this->textPost = create('Knot\Models\TextPost', ['user_id' => auth()->id()]); } /** @test */ public function a_text_post_belongs_to_a_user() { $this->assertInstanceOf('Knot\Models\User', $this->textPost->user); } /** @test */ public function a_text_has_an_associated_generic_post() { $this->assertInstanceOf('Knot\Models\Post', $this->textPost->post); } }
Java
/////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // This example code is from the book: // // Object-Oriented Programming with C++ and OSF/Motif // by // Douglas Young // Prentice Hall, 1992 // ISBN 0-13-630252-1 // // Copyright 1991 by Prentice Hall // All Rights Reserved // // Permission to use, copy, modify, and distribute this software for // any purpose except publication and without fee is hereby granted, provided // that the above copyright notice appear in all copies of the software. /////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// // DialogManager.h: A base class for cached dialogs ////////////////////////////////////////////////////////// #ifndef DIALOGMANAGER_H #define DIALOGMANAGER_H #include "UIComponent.h" #include "DialogCallbackData.h" class DialogManager : public UIComponent { private: Widget getDialog(); static void destroyTmpDialogCallback ( Widget, XtPointer, XtPointer ); static void okCallback ( Widget, XtPointer, XtPointer ); static void cancelCallback ( Widget, XtPointer, XtPointer ); static void helpCallback ( Widget, XtPointer, XtPointer ); void cleanup ( Widget, DialogCallbackData* ); protected: // Called to get a new dialog virtual Widget createDialog ( Widget ) = 0; public: DialogManager ( const char * ); virtual Widget post ( const char *, void *clientData = NULL, DialogCallback ok = NULL, DialogCallback cancel = NULL, DialogCallback help = NULL ); }; #endif
Java
<?php namespace Users; use Zend\EventManager\EventInterface as Event; use Users\Model\AuthorisationClass as AuthorisationClass; class Module { public function onBootstrap(Event $e) { // This method is called once the MVC bootstrapping is complete $application = $e->getApplication(); $services = $application->getServiceManager(); $e -> getApplication() -> getEventManager() -> getSharedManager() -> attach('Zend\Mvc\Controller\AbstractActionController', 'dispatch', function($e) { $controller = $e -> getTarget(); $full_controller_name = $controller -> params('controller'); $id=0; if ($user = $controller -> identity()) { $role = $user -> getRoleName()->getName(); $id = $user->getId(); } else { $role = 'guest'; } $routeMatch = $e->getRouteMatch(); $checkId = $routeMatch->getParam('param0',0); $controllerClass = $routeMatch->getParam('controller',0); $controllerClassArray = explode('\\', $controllerClass); $controllerName = $controllerClassArray['2']; $moduleName = $controllerClassArray['0']; $role = strtolower($role); $routeCheck = $moduleName.'\\'.$controllerName; $acl = new AuthorisationClass($id,$checkId); if (!$acl->isAuthorised($role,$routeCheck,$routeMatch->getParam('action'))) { $response = $e -> getResponse(); $response -> getHeaders() -> addHeaderLine('Location', '/users/auth/failure/Please log in as an authorised user to view that page'); $response -> setStatusCode(302); $response -> sendHeaders(); exit ; } }, 100); } public function getConfig() { return include __DIR__ . '/config/module.config.php'; } public function getServiceConfig() { return array( 'factories' => array( 'Zend\Authentication\AuthenticationService' => function($serviceManager) { // If you are using DoctrineORMModule: return $serviceManager->get('doctrine.authenticationservice.orm_default'); // If you are using DoctrineODMModule: return $serviceManager->get('doctrine.authenticationservice.odm_default'); } ) ); } public function getAutoloaderConfig() { return array( 'Zend\Loader\StandardAutoloader' => array( 'namespaces' => array( __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__, ), ), ); } }
Java
// RUN: %clang_builtins %s %librt -o %t && %run %t //===-- ctzti2_test.c - Test __ctzti2 -------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file tests __ctzti2 for the compiler_rt library. // //===----------------------------------------------------------------------===// #include "int_lib.h" #include <stdio.h> #ifdef CRT_HAS_128BIT // Returns: the number of trailing 0-bits // Precondition: a != 0 COMPILER_RT_ABI si_int __ctzti2(ti_int a); int test__ctzti2(ti_int a, si_int expected) { si_int x = __ctzti2(a); if (x != expected) { twords at; at.all = a; printf("error in __ctzti2(0x%llX%.16llX) = %d, expected %d\n", at.s.high, at.s.low, x, expected); } return x != expected; } char assumption_1[sizeof(ti_int) == 2*sizeof(di_int)] = {0}; #endif int main() { #ifdef CRT_HAS_128BIT if (test__ctzti2(0x00000001, 0)) return 1; if (test__ctzti2(0x00000002, 1)) return 1; if (test__ctzti2(0x00000003, 0)) return 1; if (test__ctzti2(0x00000004, 2)) return 1; if (test__ctzti2(0x00000005, 0)) return 1; if (test__ctzti2(0x0000000A, 1)) return 1; if (test__ctzti2(0x10000000, 28)) return 1; if (test__ctzti2(0x20000000, 29)) return 1; if (test__ctzti2(0x60000000, 29)) return 1; if (test__ctzti2(0x80000000uLL, 31)) return 1; if (test__ctzti2(0x0000050000000000uLL, 40)) return 1; if (test__ctzti2(0x0200080000000000uLL, 43)) return 1; if (test__ctzti2(0x7200000000000000uLL, 57)) return 1; if (test__ctzti2(0x8000000000000000uLL, 63)) return 1; if (test__ctzti2(make_ti(0x00000000A0000000LL, 0x0000000000000000LL), 93)) return 1; if (test__ctzti2(make_ti(0xF000000000000000LL, 0x0000000000000000LL), 124)) return 1; if (test__ctzti2(make_ti(0x8000000000000000LL, 0x0000000000000000LL), 127)) return 1; #else printf("skipped\n"); #endif return 0; }
Java
CREATE TABLE test_table(column_integer INTEGER, column_smallint SMALLINT, column_numeric_9_2 NUMERIC(9,2), column_char_9 CHAR(9), column_varchar_92 VARCHAR(92), column_date DATE, column_bit BIT(4), column_time TIME, column_timestamp TIMESTAMP, column_datetime datetime, monet monetary, big bigint, float_num float, double_num double, PRIMARY KEY (column_integer) ); INSERT INTO test_table VALUES(1, 11, 1.1, '1', '2/28/2001', '12/31/2002', NULL, '07:00:34 PM', '05:55:31 PM 05/04/2002', '05:55:31 PM 05/04/2000', 123.3, 4444444444444, 44.44, 44.44); select str_to_date(column_varchar_92, '%m/%d/%Y') from test_table where column_integer = 1; select str_to_date(123, '%m/%d/%Y'); select str_to_date('07:00:34 PM', '%r'); select str_to_date('07:00:34 PM', '% r'); select str_to_date('05:55:31 PM 05/04/2002', '%r %m/%d/%Y'); select str_to_date('07:00:34 PM', '0%%%q %r'); select str_to_date('Sat Jan 12 3rd', '%a %b %c %D'), str_to_date('Foo', '%a'), str_to_date('Bar', '%b'), str_to_date('-1', '%c'), str_to_date('-2nd', '%D'); select str_to_date('31 999999 21', '%e %f %H'), str_to_date('-4', '%d'), str_to_date('-3', '%e'), str_to_date('-1', '%f'), str_to_date('-2', '%H'); select str_to_date('11 11 311 11', '%I %i %j %k'), str_to_date('-1', '%i'), str_to_date('-1', '%I'), str_to_date('-1', '%j'), str_to_date('-2', '%k'); select str_to_date('11 am pm', '%l %p %p'), str_to_date('-1', '%l'), str_to_date('genaro', '%M'), str_to_date('-1', '%m'), str_to_date('gm', '%p'); select str_to_date('07 : 00 : 34 PM 07:00:34 AM 88', '%r %r %S'), str_to_date('-07:00:34 PM', '%r'), str_to_date('07:-01:34 PM', '%r'), str_to_date('07:00:-34 PM', '%r'); select str_to_date('07x00:34 PM', '%r'), str_to_date('07:01x34 PM', '%r'), str_to_date('07:00:34 gm', '%r'), str_to_date('-99', '%S'), str_to_date('-14', '%s'); select str_to_date('07 : 00 : 34 88 33', '%T %u %U'), str_to_date('-07:00:34', '%T'), str_to_date('07:-01:34', '%T'), str_to_date('07:00:-34', '%T'); select str_to_date('07x00:34', '%T'), str_to_date('07:01x34', '%T'), str_to_date('-99', '%u'), str_to_date('-14', '%U'); select str_to_date('12 12 Monday 0', '%v %V %W %w'), str_to_date('-1', '%v'), str_to_date('-1', '%V'), str_to_date('mandei', '%W'), str_to_date('-2', '%w'); select str_to_date('12 12 78 30 2000', '%x %X %y %y %Y'), str_to_date('-1', '%x'), str_to_date('-1', '%X'), str_to_date('-99', '%y'), str_to_date('-2', '%Y'); select str_to_date('23 am', '%H %p'); select str_to_date('0000', '%Y'); select str_to_date('13 2002', '%m %Y'); select str_to_date('32 2002', '%d %Y'); select str_to_date('04/2002', '%d/%Y'); select str_to_date('29 02 2001', '%d %m %Y'); select str_to_date('2001 54', '%Y %u'); select str_to_date('2001 54', '%x %v'); select str_to_date('2001 0', '%x %v'); select str_to_date('2001 0', '%X %V'); select str_to_date('2001 999', '%Y %j'); select str_to_date('2001 9', '%Y %w'); select str_to_date('23 am', '%h %p'); select str_to_date('70', '%i'); select str_to_date('70', '%s'); select str_to_date('1999 40 0', '%Y %u %w'); select str_to_date('1999 40 0', '%Y %U %w'); select str_to_date('1999 0 0', '%Y %U %w'); select str_to_date('1999 0 0', '%Y %u %w'); select str_to_date('1999 30 0', '%Y %u %w'); select str_to_date('1998 0 4', '%Y %u %w'); select str_to_date('1998 300', '%Y %j'); select str_to_date('1998 300 23:14:34', '%Y %j %T'); select str_to_date('2000 53 6', '%Y %U %w'); select str_to_date('2001 53 6', '%Y %U %w'); select str_to_date('2007 53 6', '%Y %U %w'); DROP TABLE test_table;
Java
<?php /* @var $this yii\web\View */ $this->title = 'My Yii Application'; ?> <div class="bodyParser"> <?=$this->render('table', [ 'dataHistory' => $dataHistory ])?> </div>
Java
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="lang:clipboard.copy" content="Copy to clipboard"> <meta name="lang:clipboard.copied" content="Copied to clipboard"> <meta name="lang:search.language" content="en"> <meta name="lang:search.pipeline.stopwords" content="True"> <meta name="lang:search.pipeline.trimmer" content="True"> <meta name="lang:search.result.none" content="No matching documents"> <meta name="lang:search.result.one" content="1 matching document"> <meta name="lang:search.result.other" content="# matching documents"> <meta name="lang:search.tokenizer" content="[\s\-]+"> <link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin> <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet"> <style> body, input { font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif } code, kbd, pre { font-family: "Roboto Mono", "Courier New", Courier, monospace } </style> <link rel="stylesheet" href="../_static/stylesheets/application.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/> <link rel="stylesheet" href="../_static/fonts/material-icons.css"/> <meta name="theme-color" content="#3f51b5"> <script src="../_static/javascripts/modernizr.js"></script> <title>statsmodels.sandbox.stats.multicomp.randmvn &#8212; statsmodels</title> <link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png"> <link rel="manifest" href="../_static/icons/site.webmanifest"> <link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191"> <meta name="msapplication-TileColor" content="#2b5797"> <meta name="msapplication-config" content="../_static/icons/browserconfig.xml"> <link rel="stylesheet" href="../_static/stylesheets/examples.css"> <link rel="stylesheet" href="../_static/material.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <script id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script> <script src="../_static/jquery.js"></script> <script src="../_static/underscore.js"></script> <script src="../_static/doctools.js"></script> <script src="../_static/language_data.js"></script> <script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script> <script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script> <script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["$", "$"], ["\\(", "\\)"]], "processEscapes": true, "ignoreClass": "document", "processClass": "math|output_area"}})</script> <link rel="shortcut icon" href="../_static/favicon.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.sandbox.stats.multicomp.rankdata" href="statsmodels.sandbox.stats.multicomp.rankdata.html" /> <link rel="prev" title="statsmodels.sandbox.stats.multicomp.qcrit" href="statsmodels.sandbox.stats.multicomp.qcrit.html" /> <script src="../_static/javascripts/version_dropdown.js"></script> <script> var json_loc = "../_static/versions.json", target_loc = "../../", text = "Versions"; $( document ).ready( add_version_dropdown(json_loc, target_loc, text)); </script> </head> <body dir=ltr data-md-color-primary=indigo data-md-color-accent=blue> <svg class="md-svg"> <defs data-children-count="0"> <svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg> </defs> </svg> <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer"> <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search"> <label class="md-overlay" data-md-component="overlay" for="__drawer"></label> <a href="#generated/statsmodels.sandbox.stats.multicomp.randmvn" tabindex="1" class="md-skip"> Skip to content </a> <header class="md-header" data-md-component="header"> <nav class="md-header-nav md-grid"> <div class="md-flex navheader"> <div class="md-flex__cell md-flex__cell--shrink"> <a href="../index.html" title="statsmodels" class="md-header-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" height="26" alt="statsmodels logo"> </a> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label> </div> <div class="md-flex__cell md-flex__cell--stretch"> <div class="md-flex__ellipsis md-header-nav__title" data-md-component="title"> <span class="md-header-nav__topic">statsmodels v0.11.1</span> <span class="md-header-nav__topic"> statsmodels.sandbox.stats.multicomp.randmvn </span> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--search md-header-nav__button" for="__search"></label> <div class="md-search" data-md-component="search" role="dialog"> <label class="md-search__overlay" for="__search"></label> <div class="md-search__inner" role="search"> <form class="md-search__form" action="../search.html" method="GET" name="search"> <input type="text" class="md-search__input" name="q" placeholder="Search" autocapitalize="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active"> <label class="md-icon md-search__icon" for="__search"></label> <button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1"> &#xE5CD; </button> </form> <div class="md-search__output"> <div class="md-search__scrollwrap" data-md-scrollfix> <div class="md-search-result" data-md-component="result"> <div class="md-search-result__meta"> Type to start searching </div> <ol class="md-search-result__list"></ol> </div> </div> </div> </div> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <div class="md-header-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> </div> </div> </nav> </header> <div class="md-container"> <nav class="md-tabs" data-md-component="tabs"> <div class="md-tabs__inner md-grid"> <ul class="md-tabs__list"> <li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li> <li class="md-tabs__item"><a href="../stats.html" class="md-tabs__link">Statistics <code class="xref py py-mod docutils literal notranslate"><span class="pre">stats</span></code></a></li> </ul> </div> </nav> <main class="md-main"> <div class="md-main__inner md-grid" data-md-component="container"> <div class="md-sidebar md-sidebar--primary" data-md-component="navigation"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--primary" data-md-level="0"> <label class="md-nav__title md-nav__title--site" for="__drawer"> <a href="../index.html" title="statsmodels" class="md-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48"> </a> <a href="../index.html" title="statsmodels">statsmodels v0.11.1</a> </label> <div class="md-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../install.html" class="md-nav__link">Installing statsmodels</a> </li> <li class="md-nav__item"> <a href="../gettingstarted.html" class="md-nav__link">Getting started</a> </li> <li class="md-nav__item"> <a href="../user-guide.html" class="md-nav__link">User Guide</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../user-guide.html#background" class="md-nav__link">Background</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../stats.html" class="md-nav__link">Statistics <code class="xref py py-mod docutils literal notranslate"><span class="pre">stats</span></code></a> </li> <li class="md-nav__item"> <a href="../contingency_tables.html" class="md-nav__link">Contingency tables</a> </li> <li class="md-nav__item"> <a href="../imputation.html" class="md-nav__link">Multiple Imputation with Chained Equations</a> </li> <li class="md-nav__item"> <a href="../emplike.html" class="md-nav__link">Empirical Likelihood <code class="xref py py-mod docutils literal notranslate"><span class="pre">emplike</span></code></a> </li> <li class="md-nav__item"> <a href="../distributions.html" class="md-nav__link">Distributions</a> </li> <li class="md-nav__item"> <a href="../graphics.html" class="md-nav__link">Graphics</a> </li> <li class="md-nav__item"> <a href="../iolib.html" class="md-nav__link">Input-Output <code class="xref py py-mod docutils literal notranslate"><span class="pre">iolib</span></code></a> </li> <li class="md-nav__item"> <a href="../tools.html" class="md-nav__link">Tools</a> </li> <li class="md-nav__item"> <a href="../large_data.html" class="md-nav__link">Working with Large Data Sets</a> </li> <li class="md-nav__item"> <a href="../optimization.html" class="md-nav__link">Optimization</a> </li></ul> </li> <li class="md-nav__item"> <a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a> </li></ul> </li> <li class="md-nav__item"> <a href="../examples/index.html" class="md-nav__link">Examples</a> </li> <li class="md-nav__item"> <a href="../api.html" class="md-nav__link">API Reference</a> </li> <li class="md-nav__item"> <a href="../about.html" class="md-nav__link">About statsmodels</a> </li> <li class="md-nav__item"> <a href="../dev/index.html" class="md-nav__link">Developer Page</a> </li> <li class="md-nav__item"> <a href="../release/index.html" class="md-nav__link">Release Notes</a> </li> </ul> </nav> </div> </div> </div> <div class="md-sidebar md-sidebar--secondary" data-md-component="toc"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--secondary"> <ul class="md-nav__list" data-md-scrollfix=""> <li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.sandbox.stats.multicomp.randmvn.rst.txt">Show Source</a> </li> <li id="searchbox" class="md-nav__item"></li> </ul> </nav> </div> </div> </div> <div class="md-content"> <article class="md-content__inner md-typeset" role="main"> <h1 id="generated-statsmodels-sandbox-stats-multicomp-randmvn--page-root">statsmodels.sandbox.stats.multicomp.randmvn<a class="headerlink" href="#generated-statsmodels-sandbox-stats-multicomp-randmvn--page-root" title="Permalink to this headline">¶</a></h1> <dl class="function"> <dt id="statsmodels.sandbox.stats.multicomp.randmvn"> <code class="sig-prename descclassname">statsmodels.sandbox.stats.multicomp.</code><code class="sig-name descname">randmvn</code><span class="sig-paren">(</span><em class="sig-param">rho</em>, <em class="sig-param">size=(1</em>, <em class="sig-param">2)</em>, <em class="sig-param">standardize=False</em><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/sandbox/stats/multicomp.html#randmvn"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#statsmodels.sandbox.stats.multicomp.randmvn" title="Permalink to this definition">¶</a></dt> <dd><p>create random draws from equi-correlated multivariate normal distribution</p> <dl class="field-list"> <dt class="field-odd">Parameters</dt> <dd class="field-odd"><dl> <dt><strong>rho</strong><span class="classifier"><a class="reference external" href="https://docs.python.org/3/library/functions.html#float" title="(in Python v3.8)"><code class="docutils literal notranslate"><span class="pre">float</span></code></a></span></dt><dd><p>correlation coefficient</p> </dd> <dt><strong>size</strong><span class="classifier"><a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#tuple" title="(in Python v3.8)"><code class="docutils literal notranslate"><span class="pre">tuple</span></code></a> <code class="xref py py-obj docutils literal notranslate"><span class="pre">of</span></code> <a class="reference external" href="https://docs.python.org/3/library/functions.html#int" title="(in Python v3.8)"><code class="docutils literal notranslate"><span class="pre">int</span></code></a></span></dt><dd><p>size is interpreted (nobs, nvars) where each row</p> </dd> </dl> </dd> <dt class="field-even">Returns</dt> <dd class="field-even"><dl> <dt><strong>rvs</strong><span class="classifier"><a class="reference external" href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html#numpy.ndarray" title="(in NumPy v1.17)"><code class="xref py py-obj docutils literal notranslate"><span class="pre">ndarray</span></code></a></span></dt><dd><p>nobs by nvars where each row is a independent random draw of nvars- dimensional correlated rvs</p> </dd> </dl> </dd> </dl> </dd></dl> </article> </div> </div> </main> </div> <footer class="md-footer"> <div class="md-footer-nav"> <nav class="md-footer-nav__inner md-grid"> <a href="statsmodels.sandbox.stats.multicomp.qcrit.html" title="Material" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev"> <div class="md-flex__cell md-flex__cell--shrink"> <i class="md-icon md-icon--arrow-back md-footer-nav__button"></i> </div> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"> <span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Previous </span> statsmodels.sandbox.stats.multicomp.qcrit </span> </div> </a> <a href="statsmodels.sandbox.stats.multicomp.rankdata.html" title="Admonition" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next"> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Next </span> statsmodels.sandbox.stats.multicomp.rankdata </span> </div> <div class="md-flex__cell md-flex__cell--shrink"><i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i> </div> </a> </nav> </div> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class="md-footer-copyright"> <div class="md-footer-copyright__highlight"> &#169; Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. </div> Last updated on Feb 21, 2020. <br/> Created using <a href="http://www.sphinx-doc.org/">Sphinx</a> 2.4.2. and <a href="https://github.com/bashtage/sphinx-material/">Material for Sphinx</a> </div> </div> </div> </footer> <script src="../_static/javascripts/application.js"></script> <script>app.initialize({version: "1.0.4", url: {base: ".."}})</script> </body> </html>
Java
/* * from: FreeBSD: src/sys/tools/fw_stub.awk,v 1.6 2007/03/02 11:42:53 flz */ #include <sys/cdefs.h> __FBSDID("$FreeBSD: releng/9.3/sys/dev/cxgb/cxgb_t3fw.c 189643 2009-03-10 19:22:45Z gnn $"); #include <sys/param.h> #include <sys/errno.h> #include <sys/kernel.h> #include <sys/module.h> #include <sys/linker.h> #include <sys/firmware.h> #include <sys/systm.h> #include <cxgb_t3fw.h> #include <t3b_protocol_sram.h> #include <t3b_tp_eeprom.h> #include <t3c_protocol_sram.h> #include <t3c_tp_eeprom.h> static int cxgb_t3fw_modevent(module_t mod, int type, void *unused) { const struct firmware *fp, *parent; int error; switch (type) { case MOD_LOAD: fp = firmware_register("cxgb_t3fw", t3fw, (size_t)t3fw_length, 0, NULL); if (fp == NULL) goto fail_0; parent = fp; return (0); fail_0: return (ENXIO); case MOD_UNLOAD: error = firmware_unregister("cxgb_t3fw"); return (error); } return (EINVAL); } static moduledata_t cxgb_t3fw_mod = { "cxgb_t3fw", cxgb_t3fw_modevent, 0 }; DECLARE_MODULE(cxgb_t3fw, cxgb_t3fw_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST); MODULE_VERSION(cxgb_t3fw, 1); MODULE_DEPEND(cxgb_t3fw, firmware, 1, 1, 1); static int cxgb_t3b_protocol_sram_modevent(module_t mod, int type, void *unused) { const struct firmware *fp, *parent; int error; switch (type) { case MOD_LOAD: fp = firmware_register("cxgb_t3b_protocol_sram", t3b_protocol_sram, (size_t)t3b_protocol_sram_length, 0, NULL); if (fp == NULL) goto fail_0; parent = fp; return (0); fail_0: return (ENXIO); case MOD_UNLOAD: error = firmware_unregister("cxgb_t3b_protocol_sram"); return (error); } return (EINVAL); } static moduledata_t cxgb_t3b_protocol_sram_mod = { "cxgb_t3b_protocol_sram", cxgb_t3b_protocol_sram_modevent, 0 }; DECLARE_MODULE(cxgb_t3b_protocol_sram, cxgb_t3b_protocol_sram_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST); MODULE_VERSION(cxgb_t3b_protocol_sram, 1); MODULE_DEPEND(cxgb_t3b_protocol_sram, firmware, 1, 1, 1); static int cxgb_t3b_tp_eeprom_modevent(module_t mod, int type, void *unused) { const struct firmware *fp, *parent; int error; switch (type) { case MOD_LOAD: fp = firmware_register("cxgb_t3b_tp_eeprom", t3b_tp_eeprom, (size_t)t3b_tp_eeprom_length, 0, NULL); if (fp == NULL) goto fail_0; parent = fp; return (0); fail_0: return (ENXIO); case MOD_UNLOAD: error = firmware_unregister("cxgb_t3b_tp_eeprom"); return (error); } return (EINVAL); } static moduledata_t cxgb_t3b_tp_eeprom_mod = { "cxgb_t3b_tp_eeprom", cxgb_t3b_tp_eeprom_modevent, 0 }; DECLARE_MODULE(cxgb_t3b_tp_eeprom, cxgb_t3b_tp_eeprom_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST); MODULE_VERSION(cxgb_t3b_tp_eeprom, 1); MODULE_DEPEND(cxgb_t3b_tp_eeprom, firmware, 1, 1, 1); static int cxgb_t3c_protocol_sram_modevent(module_t mod, int type, void *unused) { const struct firmware *fp, *parent; int error; switch (type) { case MOD_LOAD: fp = firmware_register("cxgb_t3c_protocol_sram", t3c_protocol_sram, (size_t)t3c_protocol_sram_length, 0, NULL); if (fp == NULL) goto fail_0; parent = fp; return (0); fail_0: return (ENXIO); case MOD_UNLOAD: error = firmware_unregister("cxgb_t3c_protocol_sram"); return (error); } return (EINVAL); } static moduledata_t cxgb_t3c_protocol_sram_mod = { "cxgb_t3c_protocol_sram", cxgb_t3c_protocol_sram_modevent, 0 }; DECLARE_MODULE(cxgb_t3c_protocol_sram, cxgb_t3c_protocol_sram_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST); MODULE_VERSION(cxgb_t3c_protocol_sram, 1); MODULE_DEPEND(cxgb_t3c_protocol_sram, firmware, 1, 1, 1); static int cxgb_t3c_tp_eeprom_modevent(module_t mod, int type, void *unused) { const struct firmware *fp, *parent; int error; switch (type) { case MOD_LOAD: fp = firmware_register("cxgb_t3c_tp_eeprom", t3c_tp_eeprom, (size_t)t3c_tp_eeprom_length, 0, NULL); if (fp == NULL) goto fail_0; parent = fp; return (0); fail_0: return (ENXIO); case MOD_UNLOAD: error = firmware_unregister("cxgb_t3c_tp_eeprom"); return (error); } return (EINVAL); } static moduledata_t cxgb_t3c_tp_eeprom_mod = { "cxgb_t3c_tp_eeprom", cxgb_t3c_tp_eeprom_modevent, 0 }; DECLARE_MODULE(cxgb_t3c_tp_eeprom, cxgb_t3c_tp_eeprom_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST); MODULE_VERSION(cxgb_t3c_tp_eeprom, 1); MODULE_DEPEND(cxgb_t3c_tp_eeprom, firmware, 1, 1, 1);
Java
#!/usr/bin/python # Copyright (c) 2012 The Native Client Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import json import os import subprocess import sys sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import pynacl.platform python = sys.executable bash = '/bin/bash' echo = 'echo' BOT_ASSIGNMENT = { ###################################################################### # Buildbots. ###################################################################### 'xp-newlib-opt': python + ' buildbot\\buildbot_standard.py opt 32 newlib --no-gyp', 'xp-glibc-opt': python + ' buildbot\\buildbot_standard.py opt 32 glibc --no-gyp', 'xp-bare-newlib-opt': python + ' buildbot\\buildbot_standard.py opt 32 newlib --no-gyp', 'xp-bare-glibc-opt': python + ' buildbot\\buildbot_standard.py opt 32 glibc --no-gyp', 'precise-64-validator-opt': python + ' buildbot/buildbot_standard.py opt 64 glibc --validator', # Clang. 'precise_64-newlib-dbg-clang': python + ' buildbot/buildbot_standard.py dbg 64 newlib --clang', 'mac10.7-newlib-dbg-clang': python + ' buildbot/buildbot_standard.py dbg 32 newlib --clang', # ASan. 'precise_64-newlib-dbg-asan': python + ' buildbot/buildbot_standard.py opt 64 newlib --asan', 'mac10.7-newlib-dbg-asan': python + ' buildbot/buildbot_standard.py opt 32 newlib --asan', # PNaCl. 'oneiric_32-newlib-arm_hw-pnacl-panda-dbg': bash + ' buildbot/buildbot_pnacl.sh mode-buildbot-arm-hw-dbg', 'oneiric_32-newlib-arm_hw-pnacl-panda-opt': bash + ' buildbot/buildbot_pnacl.sh mode-buildbot-arm-hw-opt', 'precise_64-newlib-arm_qemu-pnacl-dbg': bash + ' buildbot/buildbot_pnacl.sh mode-buildbot-arm-dbg', 'precise_64-newlib-arm_qemu-pnacl-opt': bash + ' buildbot/buildbot_pnacl.sh mode-buildbot-arm-opt', 'precise_64-newlib-x86_32-pnacl': python + ' buildbot/buildbot_pnacl.py opt 32 pnacl', 'precise_64-newlib-x86_64-pnacl': python + ' buildbot/buildbot_pnacl.py opt 64 pnacl', 'mac10.8-newlib-opt-pnacl': python + ' buildbot/buildbot_pnacl.py opt 32 pnacl', 'win7-64-newlib-opt-pnacl': python + ' buildbot/buildbot_pnacl.py opt 64 pnacl', 'precise_64-newlib-mips-pnacl': echo + ' "TODO(mseaborn): add mips"', # PNaCl Spec 'precise_64-newlib-arm_qemu-pnacl-buildonly-spec': bash + ' buildbot/buildbot_spec2k.sh pnacl-arm-buildonly', 'oneiric_32-newlib-arm_hw-pnacl-panda-spec': bash + ' buildbot/buildbot_spec2k.sh pnacl-arm-hw', 'lucid_64-newlib-x86_32-pnacl-spec': bash + ' buildbot/buildbot_spec2k.sh pnacl-x8632', 'lucid_64-newlib-x86_64-pnacl-spec': bash + ' buildbot/buildbot_spec2k.sh pnacl-x8664', # NaCl Spec 'lucid_64-newlib-x86_32-spec': bash + ' buildbot/buildbot_spec2k.sh nacl-x8632', 'lucid_64-newlib-x86_64-spec': bash + ' buildbot/buildbot_spec2k.sh nacl-x8664', # Valgrind bots. 'precise-64-newlib-dbg-valgrind': echo + ' "Valgrind bots are disabled: see ' 'https://code.google.com/p/nativeclient/issues/detail?id=3158"', 'precise-64-glibc-dbg-valgrind': echo + ' "Valgrind bots are disabled: see ' 'https://code.google.com/p/nativeclient/issues/detail?id=3158"', # Coverage. 'mac10.6-newlib-coverage': python + (' buildbot/buildbot_standard.py ' 'coverage 64 newlib --coverage'), 'precise-64-32-newlib-coverage': python + (' buildbot/buildbot_standard.py ' 'coverage 32 newlib --coverage'), 'precise-64-64-newlib-coverage': python + (' buildbot/buildbot_standard.py ' 'coverage 64 newlib --coverage'), 'xp-newlib-coverage': python + (' buildbot/buildbot_standard.py ' 'coverage 32 newlib --coverage'), ###################################################################### # Trybots. ###################################################################### 'nacl-precise64_validator_opt': python + ' buildbot/buildbot_standard.py opt 64 glibc --validator', 'nacl-precise64_newlib_dbg_valgrind': bash + ' buildbot/buildbot_valgrind.sh newlib', 'nacl-precise64_glibc_dbg_valgrind': bash + ' buildbot/buildbot_valgrind.sh glibc', # Coverage trybots. 'nacl-mac10.6-newlib-coverage': python + (' buildbot/buildbot_standard.py ' 'coverage 64 newlib --coverage'), 'nacl-precise-64-32-newlib-coverage': python + (' buildbot/buildbot_standard.py ' 'coverage 32 newlib --coverage'), 'nacl-precise-64-64-newlib-coverage': python + (' buildbot/buildbot_standard.py ' 'coverage 64 newlib --coverage'), 'nacl-win32-newlib-coverage': python + (' buildbot/buildbot_standard.py ' 'coverage 32 newlib --coverage'), # Clang trybots. 'nacl-precise_64-newlib-dbg-clang': python + ' buildbot/buildbot_standard.py dbg 64 newlib --clang', 'nacl-mac10.6-newlib-dbg-clang': python + ' buildbot/buildbot_standard.py dbg 32 newlib --clang', # Pnacl main trybots 'nacl-precise_64-newlib-arm_qemu-pnacl': bash + ' buildbot/buildbot_pnacl.sh mode-trybot-qemu', 'nacl-precise_64-newlib-x86_32-pnacl': python + ' buildbot/buildbot_pnacl.py opt 32 pnacl', 'nacl-precise_64-newlib-x86_64-pnacl': python + ' buildbot/buildbot_pnacl.py opt 64 pnacl', 'nacl-precise_64-newlib-mips-pnacl': echo + ' "TODO(mseaborn): add mips"', 'nacl-arm_opt_panda': bash + ' buildbot/buildbot_pnacl.sh mode-buildbot-arm-try', 'nacl-arm_hw_opt_panda': bash + ' buildbot/buildbot_pnacl.sh mode-buildbot-arm-hw-try', 'nacl-mac10.8_newlib_opt_pnacl': python + ' buildbot/buildbot_pnacl.py opt 32 pnacl', 'nacl-win7_64_newlib_opt_pnacl': python + ' buildbot/buildbot_pnacl.py opt 64 pnacl', # Pnacl spec2k trybots 'nacl-precise_64-newlib-x86_32-pnacl-spec': bash + ' buildbot/buildbot_spec2k.sh pnacl-trybot-x8632', 'nacl-precise_64-newlib-x86_64-pnacl-spec': bash + ' buildbot/buildbot_spec2k.sh pnacl-trybot-x8664', 'nacl-arm_perf_panda': bash + ' buildbot/buildbot_spec2k.sh pnacl-trybot-arm-buildonly', 'nacl-arm_hw_perf_panda': bash + ' buildbot/buildbot_spec2k.sh pnacl-trybot-arm-hw', # Toolchain glibc. 'precise64-glibc': bash + ' buildbot/buildbot_linux-glibc-makefile.sh', 'mac-glibc': bash + ' buildbot/buildbot_mac-glibc-makefile.sh', 'win7-glibc': 'buildbot\\buildbot_windows-glibc-makefile.bat', # Toolchain newlib x86. 'win7-toolchain_x86': 'buildbot\\buildbot_toolchain_win.bat', 'mac-toolchain_x86': bash + ' buildbot/buildbot_toolchain.sh mac', 'precise64-toolchain_x86': bash + ' buildbot/buildbot_toolchain.sh linux', # Toolchain newlib arm. 'win7-toolchain_arm': python + ' buildbot/buildbot_toolchain_build.py' ' toolchain_build' ' --buildbot', 'mac-toolchain_arm': python + ' buildbot/buildbot_toolchain_build.py' ' toolchain_build' ' --buildbot', 'precise64-toolchain_arm': python + ' buildbot/buildbot_toolchain_build.py' ' toolchain_build' ' --buildbot', # BIONIC toolchain builders. 'precise64-toolchain_bionic': python + ' buildbot/buildbot_toolchain_build.py' ' toolchain_build_bionic' ' --buildbot', # Pnacl toolchain builders. 'linux-armtools-x86_32': bash + ' buildbot/buildbot_toolchain_arm_trusted.sh', 'linux-pnacl-x86_32': python + ' buildbot/buildbot_pnacl_toolchain.py --buildbot', 'linux-pnacl-x86_64': python + ' buildbot/buildbot_pnacl_toolchain.py --buildbot', 'precise-pnacl-x86_32': python + ' buildbot/buildbot_pnacl_toolchain.py --buildbot', 'precise-pnacl-x86_64': python + ' buildbot/buildbot_pnacl_toolchain.py --buildbot', 'mac-pnacl-x86_32': python + ' buildbot/buildbot_pnacl_toolchain.py --buildbot', # TODO(robertm): Delete this once we are using win-pnacl-x86_64 'win-pnacl-x86_32': python + ' buildbot/buildbot_pnacl_toolchain.py --buildbot', # TODO(robertm): use this in favor or the misnamed win-pnacl-x86_32 'win-pnacl-x86_64': python + ' buildbot/buildbot_pnacl_toolchain.py --buildbot', # Pnacl toolchain testers 'linux-pnacl-x86_64-tests-x86_64': bash + ' buildbot/buildbot_pnacl_toolchain_tests.sh tc-test-bot x86-64', 'linux-pnacl-x86_64-tests-x86_32': bash + ' buildbot/buildbot_pnacl_toolchain_tests.sh tc-test-bot x86-32', 'linux-pnacl-x86_64-tests-arm': bash + ' buildbot/buildbot_pnacl_toolchain_tests.sh tc-test-bot arm', # MIPS toolchain buildbot. 'linux-pnacl-x86_32-tests-mips': bash + ' buildbot/buildbot_toolchain_mips_trusted.sh', # Toolchain trybots. 'nacl-toolchain-precise64-newlib': bash + ' buildbot/buildbot_toolchain.sh linux', 'nacl-toolchain-mac-newlib': bash + ' buildbot/buildbot_toolchain.sh mac', 'nacl-toolchain-win7-newlib': 'buildbot\\buildbot_toolchain_win.bat', 'nacl-toolchain-precise64-newlib-arm': python + ' buildbot/buildbot_toolchain_build.py' ' toolchain_build' ' --trybot', 'nacl-toolchain-mac-newlib-arm': python + ' buildbot/buildbot_toolchain_build.py' ' toolchain_build' ' --trybot', 'nacl-toolchain-win7-newlib-arm': python + ' buildbot/buildbot_toolchain_build.py' ' toolchain_build' ' --trybot', 'nacl-toolchain-precise64-glibc': bash + ' buildbot/buildbot_linux-glibc-makefile.sh', 'nacl-toolchain-mac-glibc': bash + ' buildbot/buildbot_mac-glibc-makefile.sh', 'nacl-toolchain-win7-glibc': 'buildbot\\buildbot_windows-glibc-makefile.bat', # Pnacl toolchain trybots. 'nacl-toolchain-linux-pnacl-x86_32': python + ' buildbot/buildbot_pnacl_toolchain.py --trybot', 'nacl-toolchain-linux-pnacl-x86_64': python + ' buildbot/buildbot_pnacl_toolchain.py --trybot', 'nacl-toolchain-linux-pnacl-mips': echo + ' "TODO(mseaborn)"', 'nacl-toolchain-precise-pnacl-x86_32': python + ' buildbot/buildbot_pnacl_toolchain.py --trybot', 'nacl-toolchain-precise-pnacl-x86_64': python + ' buildbot/buildbot_pnacl_toolchain.py --trybot', 'nacl-toolchain-precise-pnacl-mips': echo + ' "TODO(mseaborn)"', 'nacl-toolchain-mac-pnacl-x86_32': python + ' buildbot/buildbot_pnacl_toolchain.py --trybot', 'nacl-toolchain-win7-pnacl-x86_64': python + ' buildbot/buildbot_pnacl_toolchain.py --trybot', } special_for_arm = [ 'win7_64', 'win7-64', 'lucid-64', 'lucid64', 'precise-64', 'precise64' ] for platform in [ 'vista', 'win7', 'win8', 'win', 'mac10.6', 'mac10.7', 'mac10.8', 'lucid', 'precise'] + special_for_arm: if platform in special_for_arm: arch_variants = ['arm'] else: arch_variants = ['', '32', '64', 'arm'] for arch in arch_variants: arch_flags = '' real_arch = arch arch_part = '-' + arch # Disable GYP build for win32 bots and arm cross-builders. In this case # "win" means Windows XP, not Vista, Windows 7, etc. # # Building via GYP always builds all toolchains by default, but the win32 # XP pnacl builds are pathologically slow (e.g. ~38 seconds per compile on # the nacl-win32_glibc_opt trybot). There are other builders that test # Windows builds via gyp, so the reduced test coverage should be slight. if arch == 'arm' or (platform == 'win' and arch == '32'): arch_flags += ' --no-gyp' if arch == '': arch_part = '' real_arch = '32' # Test with Breakpad tools only on basic Linux builds. if sys.platform.startswith('linux'): arch_flags += ' --use-breakpad-tools' for mode in ['dbg', 'opt']: for libc in ['newlib', 'glibc']: # Buildbots. for bare in ['', '-bare']: name = platform + arch_part + bare + '-' + libc + '-' + mode assert name not in BOT_ASSIGNMENT, name BOT_ASSIGNMENT[name] = ( python + ' buildbot/buildbot_standard.py ' + mode + ' ' + real_arch + ' ' + libc + arch_flags) # Trybots for arch_sep in ['', '-', '_']: name = 'nacl-' + platform + arch_sep + arch + '_' + libc + '_' + mode assert name not in BOT_ASSIGNMENT, name BOT_ASSIGNMENT[name] = ( python + ' buildbot/buildbot_standard.py ' + mode + ' ' + real_arch + ' ' + libc + arch_flags) def EscapeJson(data): return '"' + json.dumps(data).replace('"', r'\"') + '"' def Main(): builder = os.environ.get('BUILDBOT_BUILDERNAME') build_number = os.environ.get('BUILDBOT_BUILDNUMBER') slave_type = os.environ.get('BUILDBOT_SLAVE_TYPE') cmd = BOT_ASSIGNMENT.get(builder) if not cmd: sys.stderr.write('ERROR - unset/invalid builder name\n') sys.exit(1) env = os.environ.copy() # Don't write out .pyc files because in cases in which files move around or # the PYTHONPATH / sys.path change, old .pyc files can be mistakenly used. # This avoids the need for admin changes on the bots in this case. env['PYTHONDONTWRITEBYTECODE'] = '1' # Use .boto file from home-dir instead of buildbot supplied one. if 'AWS_CREDENTIAL_FILE' in env: del env['AWS_CREDENTIAL_FILE'] env['BOTO_CONFIG'] = os.path.expanduser('~/.boto') env['GSUTIL'] = '/b/build/third_party/gsutil/gsutil' # When running from cygwin, we sometimes want to use a native python. # The native python will use the depot_tools version by invoking python.bat. if pynacl.platform.IsWindows(): env['NATIVE_PYTHON'] = 'python.bat' else: env['NATIVE_PYTHON'] = 'python' if sys.platform == 'win32': # If the temp directory is not on the same drive as the working directory, # there can be random failures when cleaning up temp directories, so use # a directory on the current drive. Use __file__ here instead of os.getcwd() # because toolchain_main picks its working directories relative to __file__ filedrive, _ = os.path.splitdrive(__file__) tempdrive, _ = os.path.splitdrive(env['TEMP']) if tempdrive != filedrive: env['TEMP'] = filedrive + '\\temp' env['TMP'] = env['TEMP'] if not os.path.exists(env['TEMP']): os.mkdir(env['TEMP']) # Run through runtest.py to get upload of perf data. build_properties = { 'buildername': builder, 'mastername': 'client.nacl', 'buildnumber': str(build_number), } factory_properties = { 'perf_id': builder, 'show_perf_results': True, 'step_name': 'naclperf', # Seems unused, but is required. 'test_name': 'naclperf', # Really "Test Suite" } # Locate the buildbot build directory by relative path, as it's absolute # location varies by platform and configuration. buildbot_build_dir = os.path.join(* [os.pardir] * 4) runtest = os.path.join(buildbot_build_dir, 'scripts', 'slave', 'runtest.py') # For builds with an actual build number, require that the script is present # (i.e. that we're run from an actual buildbot). if build_number is not None and not os.path.exists(runtest): raise Exception('runtest.py script not found at: %s\n' % runtest) cmd_exe = cmd.split(' ')[0] cmd_exe_ext = os.path.splitext(cmd_exe)[1] # Do not wrap these types of builds with runtest.py: # - tryjobs # - commands beginning with 'echo ' # - batch files # - debug builders if not (slave_type == 'Trybot' or cmd_exe == echo or cmd_exe_ext == '.bat' or '-dbg' in builder): # Perf dashboards are now generated by output scraping that occurs in the # script runtest.py, which lives in the buildbot repository. # Non-trybot builds should be run through runtest, allowing it to upload # perf data if relevant. cmd = ' '.join([ python, runtest, '--build-dir=src/out', '--results-url=https://chromeperf.appspot.com', '--annotate=graphing', '--no-xvfb', # We provide our own xvfb invocation. '--factory-properties', EscapeJson(factory_properties), '--build-properties', EscapeJson(build_properties), cmd, ]) print "%s runs: %s\n" % (builder, cmd) retcode = subprocess.call(cmd, env=env, shell=True) sys.exit(retcode) if __name__ == '__main__': Main()
Java
from contextlib import contextmanager from _pytest.python import FixtureRequest import mock from mock import Mock import pyramid.testing from webob.multidict import MultiDict import pyramid_swagger import pyramid_swagger.tween import pytest import simplejson from pyramid.config import Configurator from pyramid.interfaces import IRoutesMapper from pyramid.registry import Registry from pyramid.response import Response from pyramid.urldispatch import RoutesMapper from webtest import AppError from .request_test import test_app from pyramid_swagger.exceptions import ResponseValidationError from pyramid_swagger.ingest import compile_swagger_schema from pyramid_swagger.ingest import get_resource_listing from pyramid_swagger.tween import validation_tween_factory class CustomResponseValidationException(Exception): pass class EnhancedDummyRequest(pyramid.testing.DummyRequest): """ pyramid.testing.DummyRequest doesn't support MultiDicts like the real pyramid.request.Request so this is the next best thing. """ def __init__(self, **kw): super(EnhancedDummyRequest, self).__init__(**kw) self.GET = MultiDict(self.GET) # Make sure content_type attr exists is not passed in via **kw self.content_type = getattr(self, 'content_type', None) @contextmanager def validation_context(request, response=None): try: yield except Exception: raise CustomResponseValidationException validation_ctx_path = 'tests.acceptance.response_test.validation_context' def get_registry(settings): registry = Registry('testing') config = Configurator(registry=registry) if getattr(registry, 'settings', None) is None: config._set_settings(settings) registry.registerUtility(RoutesMapper(), IRoutesMapper) config.commit() return registry def get_swagger_schema(schema_dir='tests/sample_schemas/good_app/'): return compile_swagger_schema( schema_dir, get_resource_listing(schema_dir, False) ) def _validate_against_tween(request, response=None, **overrides): """ Acceptance testing helper for testing the validation tween with Swagger 1.2 responses. :param request: pytest fixture :param response: standard fixture by default """ def handler(request): return response or Response() settings = dict({ 'pyramid_swagger.swagger_versions': ['1.2'], 'pyramid_swagger.enable_swagger_spec_validation': False, 'pyramid_swagger.schema_directory': 'tests/sample_schemas/good_app/'}, **overrides ) settings['pyramid_swagger.schema12'] = get_swagger_schema() settings['pyramid_swagger.schema20'] = None registry = get_registry(settings) # Let's make request validation a no-op so we can focus our tests. with mock.patch.object(pyramid_swagger.tween, 'validate_request'): validation_tween_factory(handler, registry)(request) def test_response_validation_enabled_by_default(): request = EnhancedDummyRequest( method='GET', path='/sample/path_arg1/resource', params={'required_arg': 'test'}, matchdict={'path_arg': 'path_arg1'}, ) # Omit the logging_info key from the response. If response validation # occurs, we'll fail it. response = Response( body=simplejson.dumps({'raw_response': 'foo'}), headers={'Content-Type': 'application/json; charset=UTF-8'}, ) with pytest.raises(ResponseValidationError) as excinfo: _validate_against_tween(request, response=response) assert "'logging_info' is a required property" in str(excinfo.value) def test_500_when_response_is_missing_required_field(): request = EnhancedDummyRequest( method='GET', path='/sample/path_arg1/resource', params={'required_arg': 'test'}, matchdict={'path_arg': 'path_arg1'}, ) # Omit the logging_info key from the response. response = Response( body=simplejson.dumps({'raw_response': 'foo'}), headers={'Content-Type': 'application/json; charset=UTF-8'}, ) with pytest.raises(ResponseValidationError) as excinfo: _validate_against_tween(request, response=response) assert "'logging_info' is a required property" in str(excinfo.value) def test_200_when_response_is_void_with_none_response(): request = EnhancedDummyRequest( method='GET', path='/sample/nonstring/{int_arg}/{float_arg}/{boolean_arg}', params={'required_arg': 'test'}, matchdict={'int_arg': '1', 'float_arg': '2.0', 'boolean_arg': 'true'}, ) response = Response( body=simplejson.dumps(None), headers={'Content-Type': 'application/json; charset=UTF-8'}, ) _validate_against_tween(request, response=response) def test_200_when_response_is_void_with_empty_response(): request = EnhancedDummyRequest( method='GET', path='/sample/nonstring/{int_arg}/{float_arg}/{boolean_arg}', params={'required_arg': 'test'}, matchdict={'int_arg': '1', 'float_arg': '2.0', 'boolean_arg': 'true'}, ) response = Response(body='{}') _validate_against_tween(request, response=response) def test_500_when_response_arg_is_wrong_type(): request = EnhancedDummyRequest( method='GET', path='/sample/path_arg1/resource', params={'required_arg': 'test'}, matchdict={'path_arg': 'path_arg1'}, ) response = Response( body=simplejson.dumps({ 'raw_response': 1.0, 'logging_info': {'foo': 'bar'} }), headers={'Content-Type': 'application/json; charset=UTF-8'}, ) with pytest.raises(ResponseValidationError) as excinfo: _validate_against_tween(request, response=response) assert "1.0 is not of type 'string'" in str(excinfo.value) def test_500_for_bad_validated_array_response(): request = EnhancedDummyRequest( method='GET', path='/sample_array_response', ) response = Response( body=simplejson.dumps([{"enum_value": "bad_enum_value"}]), headers={'Content-Type': 'application/json; charset=UTF-8'}, ) with pytest.raises(ResponseValidationError) as excinfo: _validate_against_tween(request, response=response) assert "is not one of ['good_enum_value']" in str(excinfo.value) def test_200_for_good_validated_array_response(): request = EnhancedDummyRequest( method='GET', path='/sample_array_response', ) response = Response( body=simplejson.dumps([{"enum_value": "good_enum_value"}]), headers={'Content-Type': 'application/json; charset=UTF-8'}, ) _validate_against_tween(request, response=response) def test_200_for_normal_response_validation(): app = test_app( request=Mock(spec=FixtureRequest, param=['1.2']), **{'pyramid_swagger.enable_response_validation': True} ) response = app.post_json('/sample', {'foo': 'test', 'bar': 'test'}) assert response.status_code == 200 def test_200_skip_validation_for_excluded_path(): # FIXME(#64): This test is broken and doesn't check anything. app = test_app( request=Mock(spec=FixtureRequest, param=['1.2']), **{'pyramid_swagger.exclude_paths': [r'^/sample/?']} ) response = app.get( '/sample/path_arg1/resource', params={'required_arg': 'test'} ) assert response.status_code == 200 def test_app_error_if_path_not_in_spec_and_path_validation_disabled(): """If path missing and validation is disabled we want to let something else handle the error. TestApp throws an AppError, but Pyramid would throw a HTTPNotFound exception. """ with pytest.raises(AppError): app = test_app( request=Mock(spec=FixtureRequest, param=['1.2']), **{'pyramid_swagger.enable_path_validation': False} ) assert app.get('/this/path/doesnt/exist') def test_response_validation_context(): request = EnhancedDummyRequest( method='GET', path='/sample/path_arg1/resource', params={'required_arg': 'test'}, matchdict={'path_arg': 'path_arg1'}, ) # Omit the logging_info key from the response. response = Response( body=simplejson.dumps({'raw_response': 'foo'}), headers={'Content-Type': 'application/json; charset=UTF-8'}, ) with pytest.raises(CustomResponseValidationException): _validate_against_tween( request, response=response, **{'pyramid_swagger.validation_context_path': validation_ctx_path} )
Java
// Benchpress: A collection of micro-benchmarks. var allResults = [ ]; // ----------------------------------------------------------------------------- // F r a m e w o r k // ----------------------------------------------------------------------------- function Benchmark(string, run) { this.string = string; this.run = run; } // Run each benchmark for two seconds and count number of iterations. function time(benchmark) { var elapsed = 0; var start = new Date(); for (var n = 0; elapsed < 2000; n++) { benchmark.run(); elapsed = new Date() - start; } var usec = (elapsed * 1000) / n; allResults.push(usec); print('Time (' + benchmark.string + '): ' + Math.floor(usec) + ' us.'); } function error(string) { print(string); } // ----------------------------------------------------------------------------- // L o o p // ----------------------------------------------------------------------------- function loop() { var sum = 0; for (var i = 0; i < 200; i++) { for (var j = 0; j < 100; j++) { sum++; } } if (sum != 20000) error("Wrong result: " + sum + " should be: 20000"); } var Loop = new Benchmark("Loop", loop); // ----------------------------------------------------------------------------- // M a i n // ----------------------------------------------------------------------------- time(Loop); var logMean = 0; for (var i = 0; i < allResults.length; i++) logMean += Math.log(allResults[i]); logMean /= allResults.length; print("Geometric mean: " + Math.round(Math.pow(Math.E, logMean)) + " us.");
Java
#!/usr/bin/perl # start in the directory with all the files $argc = @ARGV; # get the number of arguments if ($argc == 0 ) { print "msl_Vic2ODL-PDDS-jpg.pl dir multi vic2odl_xsl odl2pds_xsl max \n"; print "prints a set of transcoder (jConvertIIO) commands to test .DAT and .VIC files \n"; print "Output goes to STDOUT. Redirect to a file to keep the output as a script or arg file.\n"; print "There are no command switches, just put the values on the command line. Order is important. \n"; print " dir - the input directory \n"; print " multi - {multi/single] create standalone java commands or a set to be executed from a file \n"; print "vic2odl_xsl - full path to the xsl script to convert vicar files to ODL (VicarToPDSmsl_Blob_ODL2.xsl)\n"; print "odl2pds_xsl - full path to the xsl script to convert ODL files to PDS (PDSToPDSmsl_Blob_ODL2PDS_4.xsl)\n"; print "max - the maximum number fo files to process. \n"; print " (Optional argument) Useful to limit the number of comands generated for a large input directory\n"; print " If the multi option is used, redirect the output to a file. Use this file as the input file for the \n"; print " command: java -Xmx256m jpl.mipl.io.jConvertIIO arg=multi.txt \n"; } $outdir = $ARGV[0]; $multi = $ARGV[1]; $vic2odl_xsl = $ARGV[2]; $odl2pds_xsl = $ARGV[3]; if ($argc > 4) { $max = $ARGV[4]; # maximum number of files used } else { $max = 1000; } # cd /Volumes/bigraid/MSL_data/Sample_EDRS/5-9-2011/clean_data # # cp *.VIC ../out_multi # cp *.VIC ../out_single # cd /Volumes/bigraid/MSL_data/Sample_EDRS/ # ~/bin/msl_Vic2ODL-PDS-jpg.pl /Volumes/bigraid/MSL_data/Sample_EDRS/test-5-11-11 multi 11 > multi11.txt # ~/bin/msl_Vic2ODL-PDS-jpg.pl /Volumes/bigraid/MSL_data/Sample_EDRS/test-5-11-11 single 11 > single11.txt # ~/bin/msl_Vic2ODL-PDS-jpg.pl /Volumes/bigraid/MSL_data/Sample_EDRS/5-9-2011/out_single single 1 > single1.txt # capture output to a file. execute each # # sh single1.txt # sh single.txt # # java -Xmx256m jpl.mipl.io.jConvertIIO arg=multi.txt # time sh single.txt # # time java -Xmx256m jpl.mipl.io.jConvertIIO ARGFILE=multi.txt # 152.015u 30.504s 3:06.07 98.0% 0+0k 236+326io 918pf+0w # # time sh single100.txt # 617.869u 87.299s 15:35.90 75.3% 0+0k 1+1171io 3267pf+0w chdir $outdir; print "#!/bin/sh \n"; $cwd = `pwd`; print "# $cwd \n"; # $debug = " debug=true xml=true "; $debug = " "; if ($multi =~ /^m/) { $java = ""; } else { $java = "java -Xmx256m jpl.mipl.io.jConvertIIO "; } $ct = 0; while (<*.DAT>) { $file = $_; ($base,$ext) = split(/[.]/,$file); $pds = sprintf ( "%s.%s", $base, "LBL"); # java -Xmx256m jpl.mipl.io.jConvertIIO inp=/Volumes/bigraid/MSL_data/Sample_EDRS/test-5-11-11/CC0_353400938EIN_F0000000001036288M1.DAT out=/Volumes/bigraid/MSL_data/Sample_EDRS/test-5-11-11/CC0_353400938EIN_F0000000001036288M1.lbl PDS_DETACHED_ONLY=true format=PDS PDS_LABEL_TYPE=PDS3 xsl=/eclipse_3.6_workspace/MSL_xsl/PDSToPDSmsl_Blob_ODL2PDS_2.xsl $xsl = "/eclipse_3.6_workspace/MSL_xsl/PDSToPDSmsl_Blob_ODL2PDS_4.xsl"; $xsl = $odl2pds_xsl; # other options: RI PDS_FILENAME_IN_LABEL=true $cmd = sprintf("%s inp=%s/%s out=%s/%s %s format=PDS PDS_DETACHED_ONLY=true PDS_LABEL_TYPE=PDS3 xsl=%s ", $java, $outdir, $file, $outdir, $pds, $debug, $xsl); print "$cmd \n"; } $ct=0; while (<*.VIC>) { $file = $_; $vic = $file; ($base,$ext) = split(/[.]/,$file); $odl = sprintf ( "%s.%s", $base, "IMG"); $pds = sprintf ( "%s.%s", $base, "LBL"); $vic_jpg = sprintf ( "%s_vic.%s", $base, "jpg"); $odl_tif = sprintf ( "%s_odl.%s", $base, "tif"); # VIC to ODL # java -Xmx256m jpl.mipl.io.jConvertIIO inp=/Users/slevoe/MSL/Sample_EDRS/RRA_353184709EDR_T0000000001036288M1.VIC out=/Users/slevoe/MSL/Sample_EDRS/out_ODL/RRA_353184709EDR_T0000000001036288M1.ODL format=PDS ADD_BLOB=true RI EMBED PDS_LABEL_TYPE=ODL3 xsl=/eclipse_3.6_workspace/MSL_xsl/VicarToPDSmsl_Blob_ODL1.xsl $xsl = "/eclipse_3.6_workspace/MSL_xsl/VicarToPDSmsl_Blob_ODL2.xsl"; $xsl = $vic2odl_xsl; $cmd = sprintf("%s inp=%s/%s out=%s/%s %s format=PDS ADD_BLOB=true RI EMBED PDS_LABEL_TYPE=ODL3 xsl=%s ", $java, $outdir, $vic, $outdir, $odl, $debug, $xsl); print "$cmd \n"; # system($cmd); # $cmd = sprintf("~/bin/getPdsLabel.pl %s/%s ", $outdir, $odl); # print "$cmd \n"; # ODL - PDS detached # java -Xmx256m jpl.mipl.io.jConvertIIO inp=/Users/slevoe/MSL/Sample_EDRS/out-ODL-PDS_Libs/CC0_353400938EIN_F0000000001036288M1.DAT out=/Users/slevoe/MSL/Sample_EDRS/out-ODL-PDS_Libs/CC0_353400938EIN_F0000000001036288M1.PDS PDS_FILENAME_IN_LABEL=true xml=true debug=true PDS_DETACHED_ONLY=true format=pds PDS_LABEL_TYPE=PDS3 xsl=/eclipse_3.6_workspace/MSL_xsl/PDSToPDSmsl_Blob_ODL2PDS_2.xsl $xsl = "/eclipse_3.6_workspace/MSL_xsl/PDSToPDSmsl_Blob_ODL2PDS_4.xsl"; $xsl = $odl2pds_xsl; # other options: RI PDS_FILENAME_IN_LABEL=true $cmd = sprintf("%s inp=%s/%s out=%s/%s %s format=PDS PDS_DETACHED_ONLY=true PDS_LABEL_TYPE=PDS3 xsl=%s ", $java, $outdir, $odl, $outdir, $pds, $debug, $xsl); print "$cmd \n"; # ODL to tif # java -Xmx256m jpl.mipl.io.jConvertIIO inp=/Users/slevoe/MSL/Sample_EDRS/RRA_353184709EDR_T0000000001036288M1.ODL out=/Users/slevoe/MSL/Sample_EDRS/RRA_353184709EDR_T0000000001036288M1.jpg 2RGB format=jpg RI OFORM=byte $cmd = sprintf("%s inp=%s/%s out=%s/%s %s format=tif RI OFORM=byte ", $java, $outdir, $odl, $outdir, $odl_tif, $debug); print "$cmd \n"; # Vicar to jpg # java -Xmx256m jpl.mipl.io.jConvertIIO inp=/Users/slevoe/MSL/Sample_EDRS/RRA_353184709EDR_T0000000001036288M1.VIC out=/Users/slevoe/MSL/Sample_EDRS/RRA_353184709EDR_T0000000001036288M1.jpg format=tif RI OFORM=byte $cmd = sprintf("%s inp=%s/%s out=%s/%s %s format=jpg RI 2RGB OFORM=byte ", $java, $outdir, $vic, $outdir, $vic_jpg, $debug); print "$cmd \n\n"; $ct++; if($ct >= $max) { exit; } } #
Java
/* copyright(C) 2002 H.Kawai (under KL-01). */ #include <stdio.h> #include <stdlib.h> int GO_fputc(int c, GO_FILE *stream) { if (stream->p >= stream->p1) abort(); *stream->p++ = c; /* GOL_debuglog(1, &c); */ return (unsigned char) c; }
Java
import ghcnpy # Provide introduction ghcnpy.intro() # Print Latest Version ghcnpy.get_ghcnd_version() # Testing Search Capabilities print("\nTESTING SEARCH CAPABILITIES") ghcnpy.find_station("Asheville") # Testing Search Capabilities print("\nTESTING PULL CAPABILITIES") outfile=ghcnpy.get_data_station("USW00003812") print(outfile," has been downloaded")
Java
{% extends 'magicflatpages/base_content.html' %} {% load floppyforms %} {% block js_top %} {{ block.super }} {{ form.media }} {% endblock %} {% block navbar %} {% endblock navbar %} {% block footer_area %} {% endblock footer_area %} {% block content %} <div class="popup-content"> <div class="row"> <div class="col-sm-2"> <div class="side-fix-menus"> <ul class="nav nav-pills nav-stacked" id="nav-elements"> <li role="presentation" class="active"> <a href="#" id="goto-title">Page<br/><i class="fa fa-minus"></i></a> </li> </ul> </div> </div> <div class="col-lg-9"> <h1><small>Page {{ object.title }} details</h1> <form method='post' enctype="multipart/form-data">{% csrf_token %} {{ form }} <div class="bottom-fix-menu" align="center"> <h1> <input type="submit" class="btn btn-lg btn-success" value="Save" /> <a href="{% url 'magiccontent.windows_close' %}?dont_reload=1" class="btn btn-lg btn-danger" role="button" >Cancel</a> </h1> </div> </form> <br/><br/><br/><br/> </div> </div> </div> {% endblock content %} {% block post_content %}{% endblock post_content %} {% block extrajs %} <script type="text/javascript"> // hide the picture filters when there is no picture $(document).ready(function(){ $("#id_url").prop('readonly', true); }); </script> {% endblock extrajs %}
Java
// xml_do_read.h see license.txt for copyright and terms of use #ifndef XML_DO_READ_H #define XML_DO_READ_H class TranslationUnit; class StringTable; TranslationUnit *xmlDoRead(StringTable &strTable, char const *inputFname); #endif // XML_DO_READ_H
Java
'use strict'; myApp.controller('editProfileController', ['$scope', '$state', 'loadingMaskService', 'CONSTANTS', '$uibModal', '$log', '$rootScope', '$http', function ($scope, $state, loadingMaskService, CONSTANTS, $uibModal, $log, $rootScope, $http) { var userInfo = JSON.parse(localStorage.getItem(CONSTANTS.LOCAL_STORAGE_KEY)); $scope.email = userInfo.email; $scope.date = userInfo.birthDate; $scope.firstName = userInfo.firstName; $scope.lastName = userInfo.lastName; $scope.relations = userInfo.relations; $scope.relationOptions = ['Мама', 'Отец', 'Брат']; $scope.submit = function () { if ($scope.editProfileForm.$valid && $scope.editProfileForm.$dirty) { // if form is valid var userInfo = { email: $scope.email, birthDate: $scope.date, firstName: $scope.firstName, lastName: $scope.lastName, relations: $scope.relations }; $http({ method: 'POST', url: '/editRelation', data: { email: userInfo.email, relations: $scope.relations } }).then(function successCallback(response) { localStorage.setItem(CONSTANTS.LOCAL_STORAGE_KEY, JSON.stringify(userInfo)); loadingMaskService.sendRequest(); $state.go('mainPageState.userProfile'); }, function errorCallback(response) { // called asynchronously if an error occurs // or server returns response with an error status. }); } }; $rootScope.$on('relationsUpdated', function(event, relations){ $scope.relations = relations; }); $rootScope.$on('relationRemoved', function(event, relations){ $scope.relations = relations; }); $scope.removeRelation = function(index) { var modalInstance = $uibModal.open({ templateUrl: 'app/pages/src/editProfilePage/src/tpl/removeRelationConfirm.tpl.html', controller: 'removeRelationController', resolve: { index: function () { return index } } }); } $scope.open = function (size) { var modalInstance = $uibModal.open({ templateUrl: 'app/pages/src/editProfilePage/src/tpl/addARelation.tpl.html', controller: 'addRelationController' }); }; }]);
Java
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Service * @subpackage StrikeIron * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Service\StrikeIron; use SoapHeader, SoapClient; /** * @category Zend * @package Zend_Service * @subpackage StrikeIron * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Base { /** * Configuration options * @param array */ protected $options = array( 'username' => null, 'password' => null, 'client' => null, 'options' => null, 'headers' => null, 'wsdl' => null, ); /** * Output headers returned by the last call to SOAPClient->_soapCall() * @param array */ protected $outputHeaders = array(); /** * Class constructor * * @param array $options Key/value pair options * @throws Exception\RuntimeException if soap extension is not loaded */ public function __construct($options = array()) { if (!extension_loaded('soap')) { throw new Exception\RuntimeException('SOAP extension is not enabled'); } $this->options = array_merge($this->options, $options); $this->initSoapHeaders(); $this->initSoapClient(); } /** * Proxy method calls to the SOAPClient instance, transforming method * calls and responses for convenience. * * @param string $method Method name * @param array $params Parameters for method * @return mixed Result * @throws Exception\RuntimeException if error occurs during soap call */ public function __call($method, $params) { // prepare method name and parameters for soap call list($method, $params) = $this->transformCall($method, $params); $params = isset($params[0]) ? array($params[0]) : array(); // make soap call, capturing the result and output headers try { $result = $this->options['client']->__soapCall( $method, $params, $this->options['options'], $this->options['headers'], $this->outputHeaders ); } catch (\Exception $e) { $message = get_class($e) . ': ' . $e->getMessage(); throw new Exception\RuntimeException($message, $e->getCode(), $e); } // transform/decorate the result and return it $result = $this->transformResult($result, $method, $params); return $result; } /** * Initialize the SOAPClient instance * * @return void */ protected function initSoapClient() { if (!isset($this->options['options'])) { $this->options['options'] = array(); } if (!isset($this->options['client'])) { $this->options['client'] = new SoapClient( $this->options['wsdl'], $this->options['options'] ); } } /** * Initialize the headers to pass to SOAPClient->_soapCall() * * @return void * @throws Exception\RuntimeException if invalid headers encountered */ protected function initSoapHeaders() { // validate headers and check if LicenseInfo was given $foundLicenseInfo = false; if (isset($this->options['headers'])) { if (! is_array($this->options['headers'])) { $this->options['headers'] = array($this->options['headers']); } foreach ($this->options['headers'] as $header) { if (!$header instanceof SoapHeader) { throw new Exception\RuntimeException('Header must be instance of SoapHeader'); } elseif ($header->name == 'LicenseInfo') { $foundLicenseInfo = true; break; } } } else { $this->options['headers'] = array(); } // add default LicenseInfo header if a custom one was not supplied if (!$foundLicenseInfo) { $this->options['headers'][] = new SoapHeader( 'http://ws.strikeiron.com', 'LicenseInfo', array( 'RegisteredUser' => array( 'UserID' => $this->options['username'], 'Password' => $this->options['password'], ), ) ); } } /** * Transform a method name or method parameters before sending them * to the remote service. This can be useful for inflection or other * transforms to give the method call a more PHP-like interface. * * @see __call() * @param string $method Method name called from PHP * @param mixed $param Parameters passed from PHP * @return array [$method, $params] for SOAPClient->_soapCall() */ protected function transformCall($method, $params) { return array(ucfirst($method), $params); } /** * Transform the result returned from a method before returning * it to the PHP caller. This can be useful for transforming * the SOAPClient returned result to be more PHP-like. * * The $method name and $params passed to the method are provided to * allow decisions to be made about how to transform the result based * on what was originally called. * * @see __call() * @param $result Raw result returned from SOAPClient_>__soapCall() * @param $method Method name that was passed to SOAPClient->_soapCall() * @param $params Method parameters that were passed to SOAPClient->_soapCall() * @return mixed Transformed result */ protected function transformResult($result, $method, $params) { $resultObjectName = "{$method}Result"; if (isset($result->$resultObjectName)) { $result = $result->$resultObjectName; } if (is_object($result)) { $result = new Decorator($result, $resultObjectName); } return $result; } /** * Get the WSDL URL for this service. * * @return string */ public function getWsdl() { return $this->options['wsdl']; } /** * Get the SOAP Client instance for this service. */ public function getSoapClient() { return $this->options['client']; } /** * Get the StrikeIron output headers returned with the last method response. * * @return array */ public function getLastOutputHeaders() { return $this->outputHeaders; } /** * Get the StrikeIron subscription information for this service. * If any service method was recently called, the subscription info * should have been returned in the SOAP headers so it is cached * and returned from the cache. Otherwise, the getRemainingHits() * method is called as a dummy to get the subscription info headers. * * @param boolean $now Force a call to getRemainingHits instead of cache? * @param string $queryMethod Method that will cause SubscriptionInfo header to be sent * @return Decorator Decorated subscription info * @throws Exception\RuntimeException if no subscription information headers present */ public function getSubscriptionInfo($now = false, $queryMethod = 'GetRemainingHits') { if ($now || empty($this->outputHeaders['SubscriptionInfo'])) { $this->$queryMethod(); } // capture subscription info if returned in output headers if (isset($this->outputHeaders['SubscriptionInfo'])) { $info = (object)$this->outputHeaders['SubscriptionInfo']; $subscriptionInfo = new Decorator($info, 'SubscriptionInfo'); } else { $msg = 'No SubscriptionInfo header found in last output headers'; throw new Exception\RuntimeException($msg); } return $subscriptionInfo; } }
Java
<?php $deleteStyle = isset($this->existing) ? 'inline' : 'none' ?> <?php $addStyle = $deleteStyle == 'inline' ? 'none' : 'inline' ?> <div id="watch-controls"> </div> <h2><?php $this->o($this->notes[0]->title);?></h2> <?php $note = null; ?> <?php foreach ($this->notes as $note): ?> <div class="note"> <div class="note-header"> <form class="inline right" method="post" action="<?php echo build_url('note', 'delete')?>" onsubmit="return confirm('Are you sure?')"> <input type="hidden" value="<?php echo $note->id?>" name="id" /> <input title="Delete" type="image" src="<?php echo resource('images/delete.png')?>" /> </form> <h4><?php $this->o($note->title)?></h4> <span class="note-by">By <?php $this->o($note->userid.' on '.$note->created)?></span> </div> <div class="note-body"><?php $this->bbCode($note->note);?></div> </div> <?php endforeach; ?> <div class="note"> <form method="post" action="<?php echo build_url('note', 'add');?>"> <input type="hidden" value="<?php echo $note->attachedtotype?>" name="attachedtotype"/> <input type="hidden" value="<?php echo $note->attachedtoid?>" name="attachedtoid"/> <input type="hidden" value="<?php echo za()->getUser()->getUsername()?>" name="userid"/> <p> <label for="note-title">Title:</label> <input class="input" type="text" name="title" id="note-title" value="Re: <?php $this->o(str_replace('Re: ', '', $note->title))?>" /> </p> <p> <label for="note-note">Note:</label> <textarea name="note" rows="5" cols="45" id="note-note"></textarea> </p> <p> <input type="submit" class="abutton" value="Add Note" /> <a class="abutton" style="display: <?php echo $deleteStyle?>;" id="delete-watch" href="#" onclick="$.get('<?php echo build_url('note', 'deletewatch')?>', {id:'<?php echo $this->itemid?>', type:'<?php echo $this->itemtype?>'}, function() {$('#delete-watch').hide();$('#add-watch').show(); }); return false;">Remove Watch</a> <a class="abutton" style="display: <?php echo $addStyle?>;" id="add-watch" href="#" onclick="$.get('<?php echo build_url('note', 'addwatch')?>', {id:'<?php echo $this->itemid?>', type:'<?php echo $this->itemtype?>'}, function() {$('#add-watch').hide();$('#delete-watch').show(); }); return false;">Add Watch</a> </p> </form> </div>
Java
/* * Copyright (c) 2011 Yahoo! Inc. All rights reserved. */ YUI.add('master', function(Y, NAME) { /** * The master module. * * @module master */ var DIMENSIONS = { device: 'smartphone', region: 'CA', skin : 'grey' }; /** * Constructor for the Controller class. * * @class Controller * @constructor */ Y.mojito.controllers[NAME] = { init: function(config) { this.config = config; }, /** * Method corresponding to the 'index' action. * * @param ac {Object} The ActionContext that provides access * to the Mojito API. */ index: function(ac) { var dims = ac.params.getFromUrl(), self = this, config = { view: 'index', children: { primary: { type: 'primary', action: 'index' }, secondary: { type: 'secondary', action: 'index' } } }; ac.composite.execute(config, function (data, meta) { data.buttons = self.createButtons(ac, dims); ac.done(data, meta); }); }, createButtons: function (ac, dims) { var buttons = [], className, label, url; Y.each(Y.Object.keys(DIMENSIONS), function (dim) { var params = Y.merge({}, dims); className = 'nav nav-' + dim + (dims[dim] ? ' active' : ''); params[dim] ? delete params[dim] : params[dim] = DIMENSIONS[dim]; url = ac.url.make('htmlframe', 'index', null, 'GET', params); label = dim.substring(0,1).toUpperCase() + dim.substring(1); buttons.push('<a href="'+url+'" class="'+className+'">'+label+'</a>'); }); return buttons.join('\n'); } }; }, '0.0.1', {requires: ['mojito', 'mojito-assets-addon']});
Java
/** * \file PancakeNode.hpp * * * * \author eaburns * \date 18-01-2010 */ #include "search/Node.hpp" #include "pancake/PancakeTypes.hpp" #include "pancake/PancakeState.hpp" #if !defined(_PANCAKE_NODE_H_) #define _PANCAKE_NODE_H_ typedef Node<PancakeState14, PancakeCost> PancakeNode14; #endif // !_PANCAKE_NODE_H_
Java
//----------------------------------------------------------------------------- //Cortex //Copyright (c) 2010-2015, Joshua Scoggins //All rights reserved. // //Redistribution and use in source and binary forms, with or without //modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Cortex nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND //ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE //DISCLAIMED. IN NO EVENT SHALL Joshua Scoggins BE LIABLE FOR ANY //DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES //(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; //LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND //ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT //(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS //SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //----------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Runtime; using System.Text; using System.Text.RegularExpressions; using System.Reflection; using System.IO; using System.Linq; namespace Cortex.Operation { public class GraphVizLink : IGraphLink { private int from, to; private string label; public int From { get { return from; } } public int To { get { return to; } } public string Label { get { return label; } } public GraphVizLink(int from, int to, string label) { this.from = from; this.to = to; this.label = label; } public override string ToString() { if(label.Equals(string.Empty)) return string.Format("node{0} -> node{1};", From, To); else return string.Format("node{0} -> node{1} {2};", From, To, Label); } } public class GraphVizGraphBuilder : GraphBuilder<GraphVizLink> { public GraphVizGraphBuilder() : base() { } public override void Link(int i0, int i1, string label) { Add(new GraphVizLink(i0,i1,label)); } public override string ToString(string graphName) { StringBuilder sb = new StringBuilder(); sb.AppendFormat("digraph {0}\n",graphName); sb.AppendLine("{"); foreach(var v in this) sb.AppendLine(v.ToString()); sb.AppendLine("}"); return sb.ToString(); } } }
Java
/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkPluginActivator.h" #include "DicomEventHandler.h" #include <service/event/ctkEventConstants.h> #include <ctkDictionary.h> #include <mitkLogMacros.h> #include <mitkDataNode.h> #include <mitkIDataStorageService.h> #include <service/event/ctkEventAdmin.h> #include <ctkServiceReference.h> #include <mitkRenderingManager.h> #include <QVector> #include "mitkImage.h" #include <mitkContourModelSet.h> #include <mitkDICOMFileReaderSelector.h> #include <mitkDICOMDCMTKTagScanner.h> #include <mitkDICOMEnums.h> #include <mitkDICOMTagsOfInterestHelper.h> #include <mitkDICOMProperty.h> #include <mitkPropertyNameHelper.h> #include "mitkBaseDICOMReaderService.h" #include <mitkRTDoseReaderService.h> #include <mitkRTPlanReaderService.h> #include <mitkRTStructureSetReaderService.h> #include <mitkRTConstants.h> #include <mitkIsoDoseLevelCollections.h> #include <mitkIsoDoseLevelSetProperty.h> #include <mitkIsoDoseLevelVectorProperty.h> #include <mitkDoseImageVtkMapper2D.h> #include <mitkRTUIConstants.h> #include <mitkIsoLevelsGenerator.h> #include <mitkDoseNodeHelper.h> #include <vtkSmartPointer.h> #include <vtkMath.h> #include <mitkTransferFunction.h> #include <mitkTransferFunctionProperty.h> #include <mitkRenderingModeProperty.h> #include <mitkLocaleSwitch.h> #include <mitkIOUtil.h> #include <berryIPreferencesService.h> #include <berryIPreferences.h> #include <berryPlatform.h> #include <ImporterUtil.h> DicomEventHandler::DicomEventHandler() { } DicomEventHandler::~DicomEventHandler() { } void DicomEventHandler::OnSignalAddSeriesToDataManager(const ctkEvent& ctkEvent) { QStringList listOfFilesForSeries; listOfFilesForSeries = ctkEvent.getProperty("FilesForSeries").toStringList(); if (!listOfFilesForSeries.isEmpty()) { //for rt data, if the modality tag isn't defined or is "CT" the image is handled like before if(ctkEvent.containsProperty("Modality") && (ctkEvent.getProperty("Modality").toString().compare("RTDOSE",Qt::CaseInsensitive) == 0 || ctkEvent.getProperty("Modality").toString().compare("RTSTRUCT",Qt::CaseInsensitive) == 0 || ctkEvent.getProperty("Modality").toString().compare("RTPLAN", Qt::CaseInsensitive) == 0)) { QString modality = ctkEvent.getProperty("Modality").toString(); if(modality.compare("RTDOSE",Qt::CaseInsensitive) == 0) { auto doseReader = mitk::RTDoseReaderService(); doseReader.SetInput(ImporterUtil::getUTF8String(listOfFilesForSeries.front())); std::vector<itk::SmartPointer<mitk::BaseData> > readerOutput = doseReader.Read(); if (!readerOutput.empty()){ mitk::Image::Pointer doseImage = dynamic_cast<mitk::Image*>(readerOutput.at(0).GetPointer()); mitk::DataNode::Pointer doseImageNode = mitk::DataNode::New(); doseImageNode->SetData(doseImage); doseImageNode->SetName("RTDose"); if (doseImage != nullptr) { std::string sopUID; if (mitk::GetBackwardsCompatibleDICOMProperty(0x0008, 0x0016, "dicomseriesreader.SOPClassUID", doseImage->GetPropertyList(), sopUID)) { doseImageNode->SetName(sopUID); }; berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); berry::IPreferences::Pointer prefNode = prefService->GetSystemPreferences()->Node(mitk::RTUIConstants::ROOT_DOSE_VIS_PREFERENCE_NODE_ID.c_str()); if (prefNode.IsNull()) { mitkThrow() << "Error in preference interface. Cannot find preset node under given name. Name: " << prefNode->ToString().toStdString(); } //set some specific colorwash and isoline properties bool showColorWashGlobal = prefNode->GetBool(mitk::RTUIConstants::GLOBAL_VISIBILITY_COLORWASH_ID.c_str(), true); //Set reference dose property double referenceDose = prefNode->GetDouble(mitk::RTUIConstants::REFERENCE_DOSE_ID.c_str(), mitk::RTUIConstants::DEFAULT_REFERENCE_DOSE_VALUE); mitk::ConfigureNodeAsDoseNode(doseImageNode, mitk::GenerateIsoLevels_Virtuos(), referenceDose, showColorWashGlobal); ctkServiceReference serviceReference = mitk::PluginActivator::getContext()->getServiceReference<mitk::IDataStorageService>(); mitk::IDataStorageService* storageService = mitk::PluginActivator::getContext()->getService<mitk::IDataStorageService>(serviceReference); mitk::DataStorage* dataStorage = storageService->GetDefaultDataStorage().GetPointer()->GetDataStorage(); dataStorage->Add(doseImageNode); mitk::RenderingManager::GetInstance()->InitializeViewsByBoundingObjects(dataStorage); } }//END DOSE } else if(modality.compare("RTSTRUCT",Qt::CaseInsensitive) == 0) { auto structReader = mitk::RTStructureSetReaderService(); structReader.SetInput(ImporterUtil::getUTF8String(listOfFilesForSeries.front())); std::vector<itk::SmartPointer<mitk::BaseData> > readerOutput = structReader.Read(); if (readerOutput.empty()){ MITK_ERROR << "No structure sets were created" << endl; } else { std::vector<mitk::DataNode::Pointer> modelVector; ctkServiceReference serviceReference = mitk::PluginActivator::getContext()->getServiceReference<mitk::IDataStorageService>(); mitk::IDataStorageService* storageService = mitk::PluginActivator::getContext()->getService<mitk::IDataStorageService>(serviceReference); mitk::DataStorage* dataStorage = storageService->GetDefaultDataStorage().GetPointer()->GetDataStorage(); for (const auto& aStruct : readerOutput){ mitk::ContourModelSet::Pointer countourModelSet = dynamic_cast<mitk::ContourModelSet*>(aStruct.GetPointer()); mitk::DataNode::Pointer structNode = mitk::DataNode::New(); structNode->SetData(countourModelSet); structNode->SetProperty("name", aStruct->GetProperty("name")); structNode->SetProperty("color", aStruct->GetProperty("contour.color")); structNode->SetProperty("contour.color", aStruct->GetProperty("contour.color")); structNode->SetProperty("includeInBoundingBox", mitk::BoolProperty::New(false)); structNode->SetVisibility(true, mitk::BaseRenderer::GetInstance( mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget0"))); structNode->SetVisibility(false, mitk::BaseRenderer::GetInstance( mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget1"))); structNode->SetVisibility(false, mitk::BaseRenderer::GetInstance( mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget2"))); structNode->SetVisibility(true, mitk::BaseRenderer::GetInstance( mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget3"))); dataStorage->Add(structNode); } mitk::RenderingManager::GetInstance()->InitializeViewsByBoundingObjects(dataStorage); } } else if (modality.compare("RTPLAN", Qt::CaseInsensitive) == 0) { auto planReader = mitk::RTPlanReaderService(); planReader.SetInput(ImporterUtil::getUTF8String(listOfFilesForSeries.front())); std::vector<itk::SmartPointer<mitk::BaseData> > readerOutput = planReader.Read(); if (!readerOutput.empty()){ //there is no image, only the properties are interesting mitk::Image::Pointer planDummyImage = dynamic_cast<mitk::Image*>(readerOutput.at(0).GetPointer()); mitk::DataNode::Pointer planImageNode = mitk::DataNode::New(); planImageNode->SetData(planDummyImage); planImageNode->SetName("RTPlan"); ctkServiceReference serviceReference = mitk::PluginActivator::getContext()->getServiceReference<mitk::IDataStorageService>(); mitk::IDataStorageService* storageService = mitk::PluginActivator::getContext()->getService<mitk::IDataStorageService>(serviceReference); mitk::DataStorage* dataStorage = storageService->GetDefaultDataStorage().GetPointer()->GetDataStorage(); dataStorage->Add(planImageNode); } } } else { mitk::StringList seriesToLoad; QStringListIterator it(listOfFilesForSeries); while (it.hasNext()) { seriesToLoad.push_back(ImporterUtil::getUTF8String(it.next())); } //Get Reference for default data storage. ctkServiceReference serviceReference = mitk::PluginActivator::getContext()->getServiceReference<mitk::IDataStorageService>(); mitk::IDataStorageService* storageService = mitk::PluginActivator::getContext()->getService<mitk::IDataStorageService>(serviceReference); mitk::DataStorage* dataStorage = storageService->GetDefaultDataStorage().GetPointer()->GetDataStorage(); std::vector<mitk::BaseData::Pointer> baseDatas = mitk::IOUtil::Load(seriesToLoad.front()); for (const auto &data : baseDatas) { mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData(data); std::string nodeName = mitk::DataNode::NO_NAME_VALUE(); auto nameDataProp = data->GetProperty("name"); if (nameDataProp.IsNotNull()) { //if data has a name property set by reader, use this name nodeName = nameDataProp->GetValueAsString(); } else { //reader didn't specify a name, generate one. nodeName = mitk::GenerateNameFromDICOMProperties(node); } node->SetName(nodeName); dataStorage->Add(node); } } } else { MITK_INFO << "There are no files for the current series"; } } void DicomEventHandler::OnSignalRemoveSeriesFromStorage(const ctkEvent& /*ctkEvent*/) { } void DicomEventHandler::SubscribeSlots() { ctkServiceReference ref = mitk::PluginActivator::getContext()->getServiceReference<ctkEventAdmin>(); if (ref) { ctkEventAdmin* eventAdmin = mitk::PluginActivator::getContext()->getService<ctkEventAdmin>(ref); ctkDictionary properties; properties[ctkEventConstants::EVENT_TOPIC] = "org/mitk/gui/qt/dicom/ADD"; eventAdmin->subscribeSlot(this, SLOT(OnSignalAddSeriesToDataManager(ctkEvent)), properties); properties[ctkEventConstants::EVENT_TOPIC] = "org/mitk/gui/qt/dicom/DELETED"; eventAdmin->subscribeSlot(this, SLOT(OnSignalRemoveSeriesFromStorage(ctkEvent)), properties); } }
Java
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="generator" content="ApiGen 2.8.0" /> <meta name="robots" content="noindex" /> <title>File widgets/fineuploader/WhFineUploader.php | YiiWheels</title> <script type="text/javascript" src="resources/combined.js?1965618976"></script> <script type="text/javascript" src="elementlist.js?53054354"></script> <link rel="stylesheet" type="text/css" media="all" href="resources/bootstrap.min.css?260161822" /> <link rel="stylesheet" type="text/css" media="all" href="resources/style.css?2015443609" /> </head> <body> <div id="navigation" class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <a href="index.html" class="brand">YiiWheels</a> <div class="nav-collapse"> <ul class="nav"> <li> <a href="package-YiiWheels.widgets.fileuploader.html" title="Summary of YiiWheels\widgets\fileuploader"><span>Package</span></a> </li> <li> <a href="class-WhFineUploader.html" title="Summary of WhFineUploader"><span>Class</span></a> </li> <li class="divider-vertical"></li> <li> <a href="tree.html" title="Tree view of classes, interfaces, traits and exceptions"><span>Tree</span></a> </li> </ul> </div> </div> </div> </div> <div id="left"> <div id="menu"> <form id="search" class="form-search"> <input type="hidden" name="cx" value="" /> <input type="hidden" name="ie" value="UTF-8" /> <input type="text" name="q" class="search-query" placeholder="Search" /> </form> <div id="groups"> <h3>Packages</h3> <ul> <li><a href="package-None.html">None</a> </li> <li><a href="package-yiiwheels.html">yiiwheels<span></span></a> <ul> <li><a href="package-yiiwheels.behaviors.html">behaviors</a> </li> <li><a href="package-yiiwheels.widgets.html">widgets</a> </li> <li class="active"><a href="package-YiiWheels.widgets.html">widgets<span></span></a> <ul> <li><a href="package-YiiWheels.widgets.ace.html">ace</a> </li> <li><a href="package-YiiWheels.widgets.box.html">box</a> </li> <li><a href="package-YiiWheels.widgets.datepicker.html">datepicker</a> </li> <li><a href="package-YiiWheels.widgets.daterangepicker.html">daterangepicker</a> </li> <li><a href="package-YiiWheels.widgets.datetimepicker.html">datetimepicker</a> </li> <li><a href="package-YiiWheels.widgets.detail.html">detail</a> </li> <li><a href="package-YiiWheels.widgets.fileupload.html">fileupload</a> </li> <li class="active"><a href="package-YiiWheels.widgets.fileuploader.html">fileuploader</a> </li> <li><a href="package-YiiWheels.widgets.gallery.html">gallery</a> </li> <li><a href="package-YiiWheels.widgets.google.html">google</a> </li> <li><a href="package-YiiWheels.widgets.grid.html">grid<span></span></a> <ul> <li><a href="package-yiiwheels.widgets.grid.behaviors.html">behaviors</a> </li> <li><a href="package-YiiWheels.widgets.grid.operations.html">operations</a> </li> </ul></li> <li><a href="package-YiiWheels.widgets.highcharts.html">highcharts</a> </li> <li><a href="package-YiiWheels.widgets.maskInput.html">maskInput</a> </li> <li><a href="package-YiiWheels.widgets.maskmoney.html">maskmoney</a> </li> <li><a href="package-YiiWheels.widgets.modal.html">modal</a> </li> <li><a href="package-YiiWheels.widgets.multiselect.html">multiselect</a> </li> <li><a href="package-YiiWheels.widgets.rangeslider.html">rangeslider</a> </li> <li><a href="package-YiiWheels.widgets.redactor.html">redactor</a> </li> <li><a href="package-YiiWheels.widgets.select2.html">select2</a> </li> <li><a href="package-YiiWheels.widgets.sparklines.html">sparklines</a> </li> <li><a href="package-YiiWheels.widgets.switch.html">switch</a> </li> <li><a href="package-YiiWheels.widgets.timeago.html">timeago</a> </li> <li><a href="package-YiiWheels.widgets.timepicker.html">timepicker</a> </li> <li><a href="package-YiiWheels.widgets.toggle.html">toggle</a> </li> <li><a href="package-YiiWheels.widgets.typeahead.html">typeahead</a> </li> </ul></li></ul></li> </ul> </div> <div id="elements"> <h3>Classes</h3> <ul> <li class="active"><a href="class-WhFineUploader.html">WhFineUploader</a></li> </ul> </div> </div> </div> <div id="splitter"></div> <div id="right"> <div id="rightInner"> <pre id="source"><code><span id="1" class="l"><a class="l" href="#1"> 1 </a><span class="xlang">&lt;?php</span> </span><span id="2" class="l"><a class="l" href="#2"> 2 </a><span class="php-comment">/** </span></span><span id="3" class="l"><a class="l" href="#3"> 3 </a><span class="php-comment"> * WhFineUploader widget class </span></span><span id="4" class="l"><a class="l" href="#4"> 4 </a><span class="php-comment"> * Inspired by https://github.com/anggiaj/EFineUploader </span></span><span id="5" class="l"><a class="l" href="#5"> 5 </a><span class="php-comment"> * @author Antonio Ramirez &lt;amigo.cobos@gmail.com&gt; </span></span><span id="6" class="l"><a class="l" href="#6"> 6 </a><span class="php-comment"> * @copyright Copyright &amp;copy; 2amigos.us 2013- </span></span><span id="7" class="l"><a class="l" href="#7"> 7 </a><span class="php-comment"> * @license http://www.opensource.org/licenses/bsd-license.php New BSD License </span></span><span id="8" class="l"><a class="l" href="#8"> 8 </a><span class="php-comment"> * @package YiiWheels.widgets.fileuploader </span></span><span id="9" class="l"><a class="l" href="#9"> 9 </a><span class="php-comment"> * @uses YiiStrap.helpers.TbArray </span></span><span id="10" class="l"><a class="l" href="#10"> 10 </a><span class="php-comment"> */</span> </span><span id="11" class="l"><a class="l" href="#11"> 11 </a>Yii::import(<span class="php-quote">'bootstrap.helpers.TbArray'</span>); </span><span id="12" class="l"><a class="l" href="#12"> 12 </a> </span><span id="13" class="l"><a class="l" href="#13"> 13 </a><span class="php-keyword1">class</span> <a id="WhFineUploader" href="#WhFineUploader">WhFineUploader</a> <span class="php-keyword1">extends</span> CInputWidget </span><span id="14" class="l"><a class="l" href="#14"> 14 </a>{ </span><span id="15" class="l"><a class="l" href="#15"> 15 </a> <span class="php-comment">/** </span></span><span id="16" class="l"><a class="l" href="#16"> 16 </a><span class="php-comment"> * @var string upload action url </span></span><span id="17" class="l"><a class="l" href="#17"> 17 </a><span class="php-comment"> */</span> </span><span id="18" class="l"><a class="l" href="#18"> 18 </a> <span class="php-keyword1">public</span> <span class="php-var"><a id="$uploadAction" href="#$uploadAction">$uploadAction</a></span>; </span><span id="19" class="l"><a class="l" href="#19"> 19 </a> </span><span id="20" class="l"><a class="l" href="#20"> 20 </a> <span class="php-comment">/** </span></span><span id="21" class="l"><a class="l" href="#21"> 21 </a><span class="php-comment"> * @var string the HTML tag to render the uploader to </span></span><span id="22" class="l"><a class="l" href="#22"> 22 </a><span class="php-comment"> */</span> </span><span id="23" class="l"><a class="l" href="#23"> 23 </a> <span class="php-keyword1">public</span> <span class="php-var"><a id="$tagName" href="#$tagName">$tagName</a></span> = <span class="php-quote">'div'</span>; </span><span id="24" class="l"><a class="l" href="#24"> 24 </a> </span><span id="25" class="l"><a class="l" href="#25"> 25 </a> <span class="php-comment">/** </span></span><span id="26" class="l"><a class="l" href="#26"> 26 </a><span class="php-comment"> * @var string text to display if javascript is disabled </span></span><span id="27" class="l"><a class="l" href="#27"> 27 </a><span class="php-comment"> */</span> </span><span id="28" class="l"><a class="l" href="#28"> 28 </a> <span class="php-keyword1">public</span> <span class="php-var"><a id="$noScriptText" href="#$noScriptText">$noScriptText</a></span>; </span><span id="29" class="l"><a class="l" href="#29"> 29 </a> </span><span id="30" class="l"><a class="l" href="#30"> 30 </a> <span class="php-comment">/** </span></span><span id="31" class="l"><a class="l" href="#31"> 31 </a><span class="php-comment"> * @var array the plugin options </span></span><span id="32" class="l"><a class="l" href="#32"> 32 </a><span class="php-comment"> */</span> </span><span id="33" class="l"><a class="l" href="#33"> 33 </a> <span class="php-keyword1">public</span> <span class="php-var"><a id="$pluginOptions" href="#$pluginOptions">$pluginOptions</a></span> = <span class="php-keyword1">array</span>(); </span><span id="34" class="l"><a class="l" href="#34"> 34 </a> </span><span id="35" class="l"><a class="l" href="#35"> 35 </a> <span class="php-comment">/** </span></span><span id="36" class="l"><a class="l" href="#36"> 36 </a><span class="php-comment"> * @var array the events </span></span><span id="37" class="l"><a class="l" href="#37"> 37 </a><span class="php-comment"> */</span> </span><span id="38" class="l"><a class="l" href="#38"> 38 </a> <span class="php-keyword1">public</span> <span class="php-var"><a id="$events" href="#$events">$events</a></span> = <span class="php-keyword1">array</span>(); </span><span id="39" class="l"><a class="l" href="#39"> 39 </a> </span><span id="40" class="l"><a class="l" href="#40"> 40 </a> <span class="php-comment">/** </span></span><span id="41" class="l"><a class="l" href="#41"> 41 </a><span class="php-comment"> * @var string which scenario we get the validation from </span></span><span id="42" class="l"><a class="l" href="#42"> 42 </a><span class="php-comment"> */</span> </span><span id="43" class="l"><a class="l" href="#43"> 43 </a> <span class="php-keyword1">public</span> <span class="php-var"><a id="$scenario" href="#$scenario">$scenario</a></span>; </span><span id="44" class="l"><a class="l" href="#44"> 44 </a> </span><span id="45" class="l"><a class="l" href="#45"> 45 </a> <span class="php-comment">/** </span></span><span id="46" class="l"><a class="l" href="#46"> 46 </a><span class="php-comment"> * @var array d </span></span><span id="47" class="l"><a class="l" href="#47"> 47 </a><span class="php-comment"> */</span> </span><span id="48" class="l"><a class="l" href="#48"> 48 </a> <span class="php-keyword1">protected</span> <span class="php-var"><a id="$defaultOptions" href="#$defaultOptions">$defaultOptions</a></span> = <span class="php-keyword1">array</span>(); </span><span id="49" class="l"><a class="l" href="#49"> 49 </a> </span><span id="50" class="l"><a class="l" href="#50"> 50 </a> <span class="php-comment">/** </span></span><span id="51" class="l"><a class="l" href="#51"> 51 </a><span class="php-comment"> * @throws CException </span></span><span id="52" class="l"><a class="l" href="#52"> 52 </a><span class="php-comment"> */</span> </span><span id="53" class="l"><a class="l" href="#53"> 53 </a> <span class="php-keyword1">public</span> <span class="php-keyword1">function</span> <a id="_init" href="#_init">init</a>() </span><span id="54" class="l"><a class="l" href="#54"> 54 </a> { </span><span id="55" class="l"><a class="l" href="#55"> 55 </a> <span class="php-keyword1">if</span> (<span class="php-var">$this</span>-&gt;uploadAction === <span class="php-keyword1">null</span>) { </span><span id="56" class="l"><a class="l" href="#56"> 56 </a> <span class="php-keyword1">throw</span> <span class="php-keyword1">new</span> CException(Yii::t(<span class="php-quote">'zii'</span>, <span class="php-quote">'&quot;uploadAction&quot; attribute cannot be blank'</span>)); </span><span id="57" class="l"><a class="l" href="#57"> 57 </a> } </span><span id="58" class="l"><a class="l" href="#58"> 58 </a> <span class="php-keyword1">if</span> (<span class="php-var">$this</span>-&gt;noScriptText === <span class="php-keyword1">null</span>) { </span><span id="59" class="l"><a class="l" href="#59"> 59 </a> <span class="php-var">$this</span>-&gt;noScriptText = Yii::t(<span class="php-quote">'zii'</span>, <span class="php-quote">&quot;Please enable JavaScript to use file uploader.&quot;</span>); </span><span id="60" class="l"><a class="l" href="#60"> 60 </a> } </span><span id="61" class="l"><a class="l" href="#61"> 61 </a> </span><span id="62" class="l"><a class="l" href="#62"> 62 </a> <span class="php-var">$this</span>-&gt;attachBehavior(<span class="php-quote">'ywplugin'</span>, <span class="php-keyword1">array</span>(<span class="php-quote">'class'</span> =&gt; <span class="php-quote">'yiiwheels.behaviors.WhPlugin'</span>)); </span><span id="63" class="l"><a class="l" href="#63"> 63 </a> </span><span id="64" class="l"><a class="l" href="#64"> 64 </a> <span class="php-var">$this</span>-&gt;initDefaultOptions(); </span><span id="65" class="l"><a class="l" href="#65"> 65 </a> } </span><span id="66" class="l"><a class="l" href="#66"> 66 </a> </span><span id="67" class="l"><a class="l" href="#67"> 67 </a> <span class="php-comment">/** </span></span><span id="68" class="l"><a class="l" href="#68"> 68 </a><span class="php-comment"> * Widget's run method </span></span><span id="69" class="l"><a class="l" href="#69"> 69 </a><span class="php-comment"> */</span> </span><span id="70" class="l"><a class="l" href="#70"> 70 </a> <span class="php-keyword1">public</span> <span class="php-keyword1">function</span> <a id="_run" href="#_run">run</a>() </span><span id="71" class="l"><a class="l" href="#71"> 71 </a> { </span><span id="72" class="l"><a class="l" href="#72"> 72 </a> <span class="php-var">$this</span>-&gt;renderTag(); </span><span id="73" class="l"><a class="l" href="#73"> 73 </a> <span class="php-var">$this</span>-&gt;registerClientScript(); </span><span id="74" class="l"><a class="l" href="#74"> 74 </a> } </span><span id="75" class="l"><a class="l" href="#75"> 75 </a> </span><span id="76" class="l"><a class="l" href="#76"> 76 </a> <span class="php-comment">/** </span></span><span id="77" class="l"><a class="l" href="#77"> 77 </a><span class="php-comment"> * Renders the tag where the button is going to be rendered </span></span><span id="78" class="l"><a class="l" href="#78"> 78 </a><span class="php-comment"> */</span> </span><span id="79" class="l"><a class="l" href="#79"> 79 </a> <span class="php-keyword1">public</span> <span class="php-keyword1">function</span> <a id="_renderTag" href="#_renderTag">renderTag</a>() </span><span id="80" class="l"><a class="l" href="#80"> 80 </a> { </span><span id="81" class="l"><a class="l" href="#81"> 81 </a> <span class="php-keyword1">echo</span> CHtml::tag(<span class="php-var">$this</span>-&gt;tagName, <span class="php-var">$this</span>-&gt;htmlOptions, <span class="php-quote">'&lt;noscript&gt;'</span> . <span class="php-var">$this</span>-&gt;noScriptText . <span class="php-quote">'&lt;/noscript&gt;'</span>, <span class="php-keyword1">true</span>); </span><span id="82" class="l"><a class="l" href="#82"> 82 </a> } </span><span id="83" class="l"><a class="l" href="#83"> 83 </a> </span><span id="84" class="l"><a class="l" href="#84"> 84 </a> <span class="php-comment">/** </span></span><span id="85" class="l"><a class="l" href="#85"> 85 </a><span class="php-comment"> * Registers required client script for finuploader </span></span><span id="86" class="l"><a class="l" href="#86"> 86 </a><span class="php-comment"> */</span> </span><span id="87" class="l"><a class="l" href="#87"> 87 </a> <span class="php-keyword1">public</span> <span class="php-keyword1">function</span> <a id="_registerClientScript" href="#_registerClientScript">registerClientScript</a>() </span><span id="88" class="l"><a class="l" href="#88"> 88 </a> { </span><span id="89" class="l"><a class="l" href="#89"> 89 </a> <span class="php-comment">/* publish assets dir */</span> </span><span id="90" class="l"><a class="l" href="#90"> 90 </a> <span class="php-var">$path</span> = <span class="php-keyword2">dirname</span>(__FILE__) . DIRECTORY_SEPARATOR . <span class="php-quote">'assets'</span>; </span><span id="91" class="l"><a class="l" href="#91"> 91 </a> <span class="php-var">$assetsUrl</span> = <span class="php-var">$this</span>-&gt;getAssetsUrl(<span class="php-var">$path</span>); </span><span id="92" class="l"><a class="l" href="#92"> 92 </a> </span><span id="93" class="l"><a class="l" href="#93"> 93 </a> <span class="php-comment">/* @var $cs CClientScript */</span> </span><span id="94" class="l"><a class="l" href="#94"> 94 </a> <span class="php-var">$cs</span> = Yii::app()-&gt;getClientScript(); </span><span id="95" class="l"><a class="l" href="#95"> 95 </a> </span><span id="96" class="l"><a class="l" href="#96"> 96 </a> <span class="php-var">$script</span> = YII_DEBUG ? <span class="php-quote">'jquery.fineuploader-3.2.js'</span> : <span class="php-quote">'jquery.fineuploader-3.2.min.js'</span>; </span><span id="97" class="l"><a class="l" href="#97"> 97 </a> </span><span id="98" class="l"><a class="l" href="#98"> 98 </a> <span class="php-var">$cs</span>-&gt;registerCssFile(<span class="php-var">$assetsUrl</span> . <span class="php-quote">'/css/fineuploader.css'</span>); </span><span id="99" class="l"><a class="l" href="#99"> 99 </a> <span class="php-var">$cs</span>-&gt;registerScriptFile(<span class="php-var">$assetsUrl</span> . <span class="php-quote">'/js/'</span> . <span class="php-var">$script</span>); </span><span id="100" class="l"><a class="l" href="#100">100 </a> </span><span id="101" class="l"><a class="l" href="#101">101 </a> <span class="php-comment">/* initialize plugin */</span> </span><span id="102" class="l"><a class="l" href="#102">102 </a> <span class="php-var">$selector</span> = <span class="php-quote">'#'</span> . TbArray::getValue(<span class="php-quote">'id'</span>, <span class="php-var">$this</span>-&gt;htmlOptions, <span class="php-var">$this</span>-&gt;getId()); </span><span id="103" class="l"><a class="l" href="#103">103 </a> </span><span id="104" class="l"><a class="l" href="#104">104 </a> <span class="php-var">$this</span>-&gt;getApi()-&gt;registerPlugin( </span><span id="105" class="l"><a class="l" href="#105">105 </a> <span class="php-quote">'fineUploader'</span>, </span><span id="106" class="l"><a class="l" href="#106">106 </a> <span class="php-var">$selector</span>, </span><span id="107" class="l"><a class="l" href="#107">107 </a> CMap::mergeArray(<span class="php-var">$this</span>-&gt;defaultOptions, <span class="php-var">$this</span>-&gt;pluginOptions) </span><span id="108" class="l"><a class="l" href="#108">108 </a> ); </span><span id="109" class="l"><a class="l" href="#109">109 </a> <span class="php-var">$this</span>-&gt;getApi()-&gt;registerEvents(<span class="php-var">$selector</span>, <span class="php-var">$this</span>-&gt;events); </span><span id="110" class="l"><a class="l" href="#110">110 </a> } </span><span id="111" class="l"><a class="l" href="#111">111 </a> </span><span id="112" class="l"><a class="l" href="#112">112 </a> <span class="php-comment">/** </span></span><span id="113" class="l"><a class="l" href="#113">113 </a><span class="php-comment"> * Sets up default options for the plugin </span></span><span id="114" class="l"><a class="l" href="#114">114 </a><span class="php-comment"> * - thanks https://github.com/anggiaj </span></span><span id="115" class="l"><a class="l" href="#115">115 </a><span class="php-comment"> */</span> </span><span id="116" class="l"><a class="l" href="#116">116 </a> <span class="php-keyword1">protected</span> <span class="php-keyword1">function</span> <a id="_initDefaultOptions" href="#_initDefaultOptions">initDefaultOptions</a>() </span><span id="117" class="l"><a class="l" href="#117">117 </a> { </span><span id="118" class="l"><a class="l" href="#118">118 </a> <span class="php-keyword1">list</span>(<span class="php-var">$name</span>, <span class="php-var">$id</span>) = <span class="php-var">$this</span>-&gt;resolveNameID(); </span><span id="119" class="l"><a class="l" href="#119">119 </a> </span><span id="120" class="l"><a class="l" href="#120">120 </a> TbArray::defaultValue(<span class="php-quote">'id'</span>, <span class="php-var">$id</span>, <span class="php-var">$this</span>-&gt;htmlOptions); </span><span id="121" class="l"><a class="l" href="#121">121 </a> TbArray::defaultValue(<span class="php-quote">'name'</span>, <span class="php-var">$name</span>, <span class="php-var">$this</span>-&gt;htmlOptions); </span><span id="122" class="l"><a class="l" href="#122">122 </a> </span><span id="123" class="l"><a class="l" href="#123">123 </a> </span><span id="124" class="l"><a class="l" href="#124">124 </a> <span class="php-var">$this</span>-&gt;defaultOptions = <span class="php-keyword1">array</span>( </span><span id="125" class="l"><a class="l" href="#125">125 </a> <span class="php-quote">'request'</span> =&gt; <span class="php-keyword1">array</span>( </span><span id="126" class="l"><a class="l" href="#126">126 </a> <span class="php-quote">'endpoint'</span> =&gt; <span class="php-var">$this</span>-&gt;uploadAction, </span><span id="127" class="l"><a class="l" href="#127">127 </a> <span class="php-quote">'inputName'</span> =&gt; <span class="php-var">$name</span>, </span><span id="128" class="l"><a class="l" href="#128">128 </a> ), </span><span id="129" class="l"><a class="l" href="#129">129 </a> <span class="php-quote">'validation'</span> =&gt; <span class="php-var">$this</span>-&gt;getValidator(), </span><span id="130" class="l"><a class="l" href="#130">130 </a> <span class="php-quote">'messages'</span> =&gt; <span class="php-keyword1">array</span>( </span><span id="131" class="l"><a class="l" href="#131">131 </a> <span class="php-quote">'typeError'</span> =&gt; Yii::t(<span class="php-quote">'zii'</span>, <span class="php-quote">'{file} has an invalid extension. Valid extension(s): {extensions}.'</span>), </span><span id="132" class="l"><a class="l" href="#132">132 </a> <span class="php-quote">'sizeError'</span> =&gt; Yii::t(<span class="php-quote">'zii'</span>, <span class="php-quote">'{file} is too large, maximum file size is {sizeLimit}.'</span>), </span><span id="133" class="l"><a class="l" href="#133">133 </a> <span class="php-quote">'minSizeError'</span> =&gt; Yii::t(<span class="php-quote">'zii'</span>, <span class="php-quote">'{file} is too small, minimum file size is {minSizeLimit}.'</span>), </span><span id="134" class="l"><a class="l" href="#134">134 </a> <span class="php-quote">'emptyError:'</span> =&gt; Yii::t(<span class="php-quote">'zii'</span>, <span class="php-quote">'{file} is empty, please select files again without it.'</span>), </span><span id="135" class="l"><a class="l" href="#135">135 </a> <span class="php-quote">'noFilesError'</span> =&gt; Yii::t(<span class="php-quote">'zii'</span>, <span class="php-quote">'No files to upload.'</span>), </span><span id="136" class="l"><a class="l" href="#136">136 </a> <span class="php-quote">'onLeave'</span> =&gt; Yii::t( </span><span id="137" class="l"><a class="l" href="#137">137 </a> <span class="php-quote">'zii'</span>, </span><span id="138" class="l"><a class="l" href="#138">138 </a> <span class="php-quote">'The files are being uploaded, if you leave now the upload will be cancelled.'</span> </span><span id="139" class="l"><a class="l" href="#139">139 </a> ) </span><span id="140" class="l"><a class="l" href="#140">140 </a> ), </span><span id="141" class="l"><a class="l" href="#141">141 </a> ); </span><span id="142" class="l"><a class="l" href="#142">142 </a> } </span><span id="143" class="l"><a class="l" href="#143">143 </a> </span><span id="144" class="l"><a class="l" href="#144">144 </a> <span class="php-comment">/** </span></span><span id="145" class="l"><a class="l" href="#145">145 </a><span class="php-comment"> * @return array </span></span><span id="146" class="l"><a class="l" href="#146">146 </a><span class="php-comment"> */</span> </span><span id="147" class="l"><a class="l" href="#147">147 </a> <span class="php-keyword1">protected</span> <span class="php-keyword1">function</span> <a id="_getValidator" href="#_getValidator">getValidator</a>() </span><span id="148" class="l"><a class="l" href="#148">148 </a> { </span><span id="149" class="l"><a class="l" href="#149">149 </a> <span class="php-var">$ret</span> = <span class="php-keyword1">array</span>(); </span><span id="150" class="l"><a class="l" href="#150">150 </a> <span class="php-keyword1">if</span> (<span class="php-var">$this</span>-&gt;hasModel()) { </span><span id="151" class="l"><a class="l" href="#151">151 </a> <span class="php-keyword1">if</span> (<span class="php-var">$this</span>-&gt;scenario !== <span class="php-keyword1">null</span>) { </span><span id="152" class="l"><a class="l" href="#152">152 </a> <span class="php-var">$originalScenario</span> = <span class="php-var">$this</span>-&gt;model-&gt;getScenario(); </span><span id="153" class="l"><a class="l" href="#153">153 </a> <span class="php-var">$this</span>-&gt;model-&gt;setScenario(<span class="php-var">$this</span>-&gt;scenario); </span><span id="154" class="l"><a class="l" href="#154">154 </a> <span class="php-var">$validators</span> = <span class="php-var">$this</span>-&gt;model-&gt;getValidators(<span class="php-var">$this</span>-&gt;attribute); </span><span id="155" class="l"><a class="l" href="#155">155 </a> <span class="php-var">$this</span>-&gt;model-&gt;setScenario(<span class="php-var">$originalScenario</span>); </span><span id="156" class="l"><a class="l" href="#156">156 </a> </span><span id="157" class="l"><a class="l" href="#157">157 </a> } <span class="php-keyword1">else</span> { </span><span id="158" class="l"><a class="l" href="#158">158 </a> <span class="php-var">$validators</span> = <span class="php-var">$this</span>-&gt;model-&gt;getValidators(<span class="php-var">$this</span>-&gt;attribute); </span><span id="159" class="l"><a class="l" href="#159">159 </a> } </span><span id="160" class="l"><a class="l" href="#160">160 </a> </span><span id="161" class="l"><a class="l" href="#161">161 </a> <span class="php-comment">// we are just looking for the first founded CFileValidator</span> </span><span id="162" class="l"><a class="l" href="#162">162 </a> <span class="php-keyword1">foreach</span> (<span class="php-var">$validators</span> <span class="php-keyword1">as</span> <span class="php-var">$validator</span>) { </span><span id="163" class="l"><a class="l" href="#163">163 </a> <span class="php-keyword1">if</span> (<span class="php-keyword2">is_a</span>(<span class="php-var">$validator</span>, <span class="php-quote">'CFileValidator'</span>)) { </span><span id="164" class="l"><a class="l" href="#164">164 </a> <span class="php-var">$ret</span> = <span class="php-keyword1">array</span>( </span><span id="165" class="l"><a class="l" href="#165">165 </a> <span class="php-quote">'allowedExtensions'</span> =&gt; <span class="php-keyword2">explode</span>(<span class="php-quote">','</span>, <span class="php-keyword2">str_replace</span>(<span class="php-quote">' '</span>, <span class="php-quote">''</span>, <span class="php-var">$validator</span>-&gt;types)), </span><span id="166" class="l"><a class="l" href="#166">166 </a> <span class="php-quote">'sizeLimit'</span> =&gt; <span class="php-var">$validator</span>-&gt;maxSize, </span><span id="167" class="l"><a class="l" href="#167">167 </a> <span class="php-quote">'minSizeLimit'</span> =&gt; <span class="php-var">$validator</span>-&gt;minSize, </span><span id="168" class="l"><a class="l" href="#168">168 </a> ); </span><span id="169" class="l"><a class="l" href="#169">169 </a> <span class="php-keyword1">break</span>; </span><span id="170" class="l"><a class="l" href="#170">170 </a> } </span><span id="171" class="l"><a class="l" href="#171">171 </a> } </span><span id="172" class="l"><a class="l" href="#172">172 </a> } </span><span id="173" class="l"><a class="l" href="#173">173 </a> <span class="php-keyword1">return</span> <span class="php-var">$ret</span>; </span><span id="174" class="l"><a class="l" href="#174">174 </a> } </span><span id="175" class="l"><a class="l" href="#175">175 </a></span>}</code></pre> </div> <div id="footer"> YiiWheels API documentation generated by <a href="http://apigen.org">ApiGen 2.8.0</a> </div> </div> </body> </html>
Java
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // godoc: Go Documentation Server // Web server tree: // // http://godoc/ main landing page // http://godoc/doc/ serve from $GOROOT/doc - spec, mem, etc. // http://godoc/src/ serve files from $GOROOT/src; .go gets pretty-printed // http://godoc/cmd/ serve documentation about commands // http://godoc/pkg/ serve documentation about packages // (idea is if you say import "compress/zlib", you go to // http://godoc/pkg/compress/zlib) // // Command-line interface: // // godoc packagepath [name ...] // // godoc compress/zlib // - prints doc for package compress/zlib // godoc crypto/block Cipher NewCMAC // - prints doc for Cipher and NewCMAC in package crypto/block // +build !appengine package main import ( "archive/zip" _ "expvar" // to serve /debug/vars "flag" "fmt" "go/build" "log" "net/http" "net/http/httptest" _ "net/http/pprof" // to serve /debug/pprof/* "net/url" "os" "path/filepath" "regexp" "runtime" "strings" "golang.org/x/tools/godoc" "golang.org/x/tools/godoc/analysis" "golang.org/x/tools/godoc/static" "golang.org/x/tools/godoc/vfs" "golang.org/x/tools/godoc/vfs/gatefs" "golang.org/x/tools/godoc/vfs/mapfs" "golang.org/x/tools/godoc/vfs/zipfs" ) const defaultAddr = ":6060" // default webserver address var ( // file system to serve // (with e.g.: zip -r go.zip $GOROOT -i \*.go -i \*.html -i \*.css -i \*.js -i \*.txt -i \*.c -i \*.h -i \*.s -i \*.png -i \*.jpg -i \*.sh -i favicon.ico) zipfile = flag.String("zip", "", "zip file providing the file system to serve; disabled if empty") // file-based index writeIndex = flag.Bool("write_index", false, "write index to a file; the file name must be specified with -index_files") analysisFlag = flag.String("analysis", "", `comma-separated list of analyses to perform (supported: type, pointer). See http://golang.org/lib/godoc/analysis/help.html`) // network httpAddr = flag.String("http", "", "HTTP service address (e.g., '"+defaultAddr+"')") serverAddr = flag.String("server", "", "webserver address for command line searches") // layout control html = flag.Bool("html", false, "print HTML in command-line mode") srcMode = flag.Bool("src", false, "print (exported) source in command-line mode") allMode = flag.Bool("all", false, "include unexported identifiers in command-line mode") urlFlag = flag.String("url", "", "print HTML for named URL") // command-line searches query = flag.Bool("q", false, "arguments are considered search queries") verbose = flag.Bool("v", false, "verbose mode") // file system roots // TODO(gri) consider the invariant that goroot always end in '/' goroot = flag.String("goroot", runtime.GOROOT(), "Go root directory") // layout control tabWidth = flag.Int("tabwidth", 4, "tab width") showTimestamps = flag.Bool("timestamps", false, "show timestamps with directory listings") templateDir = flag.String("templates", "", "load templates/JS/CSS from disk in this directory") showPlayground = flag.Bool("play", false, "enable playground in web interface") showExamples = flag.Bool("ex", false, "show examples in command line mode") declLinks = flag.Bool("links", true, "link identifiers to their declarations") // search index indexEnabled = flag.Bool("index", false, "enable search index") indexFiles = flag.String("index_files", "", "glob pattern specifying index files; if not empty, the index is read from these files in sorted order") indexInterval = flag.Duration("index_interval", 0, "interval of indexing; 0 for default (5m), negative to only index once at startup") maxResults = flag.Int("maxresults", 10000, "maximum number of full text search results shown") indexThrottle = flag.Float64("index_throttle", 0.75, "index throttle value; 0.0 = no time allocated, 1.0 = full throttle") // source code notes notesRx = flag.String("notes", "BUG", "regular expression matching note markers to show") ) func usage() { fmt.Fprintf(os.Stderr, "usage: godoc package [name ...]\n"+ " godoc -http="+defaultAddr+"\n") flag.PrintDefaults() os.Exit(2) } func loggingHandler(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { log.Printf("%s\t%s", req.RemoteAddr, req.URL) h.ServeHTTP(w, req) }) } func handleURLFlag() { // Try up to 10 fetches, following redirects. urlstr := *urlFlag for i := 0; i < 10; i++ { // Prepare request. u, err := url.Parse(urlstr) if err != nil { log.Fatal(err) } req := &http.Request{ URL: u, } // Invoke default HTTP handler to serve request // to our buffering httpWriter. w := httptest.NewRecorder() http.DefaultServeMux.ServeHTTP(w, req) // Return data, error, or follow redirect. switch w.Code { case 200: // ok os.Stdout.Write(w.Body.Bytes()) return case 301, 302, 303, 307: // redirect redirect := w.HeaderMap.Get("Location") if redirect == "" { log.Fatalf("HTTP %d without Location header", w.Code) } urlstr = redirect default: log.Fatalf("HTTP error %d", w.Code) } } log.Fatalf("too many redirects") } func initCorpus(corpus *godoc.Corpus) { err := corpus.Init() if err != nil { log.Fatal(err) } } func main() { flag.Usage = usage flag.Parse() if certInit != nil { certInit() } playEnabled = *showPlayground // Check usage: server and no args. if (*httpAddr != "" || *urlFlag != "") && (flag.NArg() > 0) { fmt.Fprintln(os.Stderr, "can't use -http with args.") usage() } // Check usage: command line args or index creation mode. if (*httpAddr != "" || *urlFlag != "") != (flag.NArg() == 0) && !*writeIndex { fmt.Fprintln(os.Stderr, "missing args.") usage() } var fsGate chan bool fsGate = make(chan bool, 20) // Determine file system to use. if *zipfile == "" { // use file system of underlying OS rootfs := gatefs.New(vfs.OS(*goroot), fsGate) fs.Bind("/", rootfs, "/", vfs.BindReplace) } else { // use file system specified via .zip file (path separator must be '/') rc, err := zip.OpenReader(*zipfile) if err != nil { log.Fatalf("%s: %s\n", *zipfile, err) } defer rc.Close() // be nice (e.g., -writeIndex mode) fs.Bind("/", zipfs.New(rc, *zipfile), *goroot, vfs.BindReplace) } if *templateDir != "" { fs.Bind("/lib/godoc", vfs.OS(*templateDir), "/", vfs.BindBefore) } else { fs.Bind("/lib/godoc", mapfs.New(static.Files), "/", vfs.BindReplace) } // Bind $GOPATH trees into Go root. for _, p := range filepath.SplitList(build.Default.GOPATH) { fs.Bind("/src", gatefs.New(vfs.OS(p), fsGate), "/src", vfs.BindAfter) } httpMode := *httpAddr != "" var typeAnalysis, pointerAnalysis bool if *analysisFlag != "" { for _, a := range strings.Split(*analysisFlag, ",") { switch a { case "type": typeAnalysis = true case "pointer": pointerAnalysis = true default: log.Fatalf("unknown analysis: %s", a) } } } corpus := godoc.NewCorpus(fs) corpus.Verbose = *verbose corpus.MaxResults = *maxResults corpus.IndexEnabled = *indexEnabled && httpMode if *maxResults == 0 { corpus.IndexFullText = false } corpus.IndexFiles = *indexFiles corpus.IndexDirectory = indexDirectoryDefault corpus.IndexThrottle = *indexThrottle corpus.IndexInterval = *indexInterval if *writeIndex { corpus.IndexThrottle = 1.0 corpus.IndexEnabled = true } if *writeIndex || httpMode || *urlFlag != "" { if httpMode { go initCorpus(corpus) } else { initCorpus(corpus) } } pres = godoc.NewPresentation(corpus) pres.TabWidth = *tabWidth pres.ShowTimestamps = *showTimestamps pres.ShowPlayground = *showPlayground pres.ShowExamples = *showExamples pres.DeclLinks = *declLinks pres.SrcMode = *srcMode pres.HTMLMode = *html pres.AllMode = *allMode if *notesRx != "" { pres.NotesRx = regexp.MustCompile(*notesRx) } readTemplates(pres, httpMode || *urlFlag != "") registerHandlers(pres) if *writeIndex { // Write search index and exit. if *indexFiles == "" { log.Fatal("no index file specified") } log.Println("initialize file systems") *verbose = true // want to see what happens corpus.UpdateIndex() log.Println("writing index file", *indexFiles) f, err := os.Create(*indexFiles) if err != nil { log.Fatal(err) } index, _ := corpus.CurrentIndex() _, err = index.WriteTo(f) if err != nil { log.Fatal(err) } log.Println("done") return } // Print content that would be served at the URL *urlFlag. if *urlFlag != "" { handleURLFlag() return } if httpMode { // HTTP server mode. var handler http.Handler = http.DefaultServeMux if *verbose { log.Printf("Go Documentation Server") log.Printf("version = %s", runtime.Version()) log.Printf("address = %s", *httpAddr) log.Printf("goroot = %s", *goroot) log.Printf("tabwidth = %d", *tabWidth) switch { case !*indexEnabled: log.Print("search index disabled") case *maxResults > 0: log.Printf("full text index enabled (maxresults = %d)", *maxResults) default: log.Print("identifier search index enabled") } fs.Fprint(os.Stderr) handler = loggingHandler(handler) } // Initialize search index. if *indexEnabled { go corpus.RunIndexer() } // Start type/pointer analysis. if typeAnalysis || pointerAnalysis { go analysis.Run(pointerAnalysis, &corpus.Analysis) } if runHTTPS != nil { go func() { if err := runHTTPS(handler); err != nil { log.Fatalf("ListenAndServe TLS: %v", err) } }() } // Start http server. if *verbose { log.Println("starting HTTP server") } if wrapHTTPMux != nil { handler = wrapHTTPMux(handler) } if err := http.ListenAndServe(*httpAddr, handler); err != nil { log.Fatalf("ListenAndServe %s: %v", *httpAddr, err) } return } if *query { handleRemoteSearch() return } if err := godoc.CommandLine(os.Stdout, fs, pres, flag.Args()); err != nil { log.Print(err) } } // Hooks that are set non-nil in autocert.go if the "autocert" build tag // is used. var ( certInit func() runHTTPS func(http.Handler) error wrapHTTPMux func(http.Handler) http.Handler )
Java
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>QGeoCodingManager &mdash; PyQt 5.5.1 Reference Guide</title> <link rel="stylesheet" href="../_static/classic.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../', VERSION: '5.5.1', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <link rel="shortcut icon" href="../_static/logo_tn.ico"/> <link rel="top" title="PyQt 5.5.1 Reference Guide" href="../index.html" /> <link rel="up" title="PyQt5 Class Reference" href="../class_reference.html" /> <link rel="next" title="QGeoCodingManagerEngine" href="qgeocodingmanagerengine.html" /> <link rel="prev" title="QGeoCodeReply" href="qgeocodereply.html" /> </head> <body role="document"> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="qgeocodingmanagerengine.html" title="QGeoCodingManagerEngine" accesskey="N">next</a> |</li> <li class="right" > <a href="qgeocodereply.html" title="QGeoCodeReply" accesskey="P">previous</a> |</li> <li class="nav-item nav-item-0"><a href="../index.html">PyQt 5.5.1 Reference Guide</a> &raquo;</li> <li class="nav-item nav-item-1"><a href="../class_reference.html" accesskey="U">PyQt5 Class Reference</a> &raquo;</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <div class="section" id="qgeocodingmanager"> <h1>QGeoCodingManager<a class="headerlink" href="#qgeocodingmanager" title="Permalink to this headline">¶</a></h1> <dl class="class"> <dt id="PyQt5.QtLocation.QGeoCodingManager"> <em class="property">class </em><code class="descclassname">PyQt5.QtLocation.</code><code class="descname">QGeoCodingManager</code><a class="headerlink" href="#PyQt5.QtLocation.QGeoCodingManager" title="Permalink to this definition">¶</a></dt> <dd><p><a class="reference external" href="http://doc.qt.io/qt-5/qgeocodingmanager.html">C++ documentation</a></p> </dd></dl> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <p class="logo"><a href="../index.html"> <img class="logo" src="../_static/logo.png" alt="Logo"/> </a></p> <h4>Previous topic</h4> <p class="topless"><a href="qgeocodereply.html" title="previous chapter">QGeoCodeReply</a></p> <h4>Next topic</h4> <p class="topless"><a href="qgeocodingmanagerengine.html" title="next chapter">QGeoCodingManagerEngine</a></p> <div id="searchbox" style="display: none" role="search"> <h3>Quick search</h3> <form class="search" action="../search.html" method="get"> <input type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> <p class="searchtip" style="font-size: 90%"> Enter search terms or a module, class or function name. </p> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="qgeocodingmanagerengine.html" title="QGeoCodingManagerEngine" >next</a> |</li> <li class="right" > <a href="qgeocodereply.html" title="QGeoCodeReply" >previous</a> |</li> <li class="nav-item nav-item-0"><a href="../index.html">PyQt 5.5.1 Reference Guide</a> &raquo;</li> <li class="nav-item nav-item-1"><a href="../class_reference.html" >PyQt5 Class Reference</a> &raquo;</li> </ul> </div> <div class="footer" role="contentinfo"> &copy; Copyright 2015 Riverbank Computing Limited. Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.3.1. </div> </body> </html>
Java
{-# LANGUAGE OverloadedStrings #-} module WildBind.SeqSpec (main,spec) where import Control.Applicative ((<*>)) import Control.Monad (forM_) import Control.Monad.IO.Class (liftIO) import qualified Control.Monad.Trans.State as State import Data.Monoid ((<>)) import Data.IORef (modifyIORef, newIORef, readIORef) import Test.Hspec import WildBind.Binding ( binds, on, run, as, boundActions, actDescription, boundInputs, Binding, justBefore ) import WildBind.Description (ActionDescription) import WildBind.Seq ( prefix, toSeq, fromSeq, withPrefix, withCancel, reviseSeq ) import WildBind.ForTest ( SampleInput(..), SampleState(..), evalStateEmpty, execAll, boundDescs, curBoundInputs, curBoundDescs, curBoundDesc, checkBoundInputs, checkBoundDescs, checkBoundDesc, withRefChecker ) main :: IO () main = hspec spec spec :: Spec spec = do spec_prefix spec_SeqBinding spec_reviseSeq spec_prefix :: Spec spec_prefix = describe "prefix" $ do let base_b = binds $ do on SIa `as` "a" `run` return () on SIb `as` "b" `run` return () specify "no prefix" $ do let b = prefix [] [] base_b boundDescs b (SS "") `shouldMatchList` [ (SIa, "a"), (SIb, "b") ] specify "one prefix" $ evalStateEmpty $ do State.put $ prefix [] [SIc] base_b checkBoundInputs (SS "") [SIc] execAll (SS "") [SIc] checkBoundDescs (SS "") [(SIa, "a"), (SIb, "b")] execAll (SS "") [SIc] checkBoundDescs (SS "") [(SIa, "a"), (SIb, "b")] execAll (SS "") [SIa] checkBoundInputs (SS "") [SIc] specify "two prefixes" $ evalStateEmpty $ do State.put $ prefix [] [SIc, SIb] base_b checkBoundInputs (SS "") [SIc] execAll (SS "") [SIc] checkBoundInputs (SS "") [SIb] execAll (SS "") [SIb] checkBoundDescs (SS "") [(SIa, "a"), (SIb, "b")] execAll (SS "") [SIa] checkBoundInputs (SS "") [SIc] specify "cancel binding" $ evalStateEmpty $ do State.put $ prefix [SIa] [SIc, SIb] base_b checkBoundInputs (SS "") [SIc] execAll (SS "") [SIc] -- there is no cancel binding at the top level. checkBoundInputs (SS "") [SIa, SIb] checkBoundDesc (SS "") SIa "cancel" execAll (SS "") [SIa] checkBoundInputs (SS "") [SIc] execAll (SS "") [SIc, SIb] checkBoundDescs (SS "") [(SIa, "a"), (SIb, "b")] -- cancel binding should be weak and overridden. execAll (SS "") [SIb] checkBoundInputs (SS "") [SIc] execAll (SS "") [SIc, SIb] checkBoundDescs (SS "") [(SIa, "a"), (SIb, "b")] execAll (SS "") [SIa] checkBoundInputs (SS "") [SIc] spec_SeqBinding :: Spec spec_SeqBinding = describe "SeqBinding" $ do let b_a = binds $ on SIa `as` "a" `run` return () b_b = binds $ on SIb `as` "b" `run` return () describe "withPrefix" $ do it "should allow nesting" $ evalStateEmpty $ do State.put $ fromSeq $ withPrefix [SIb] $ withPrefix [SIc] $ withPrefix [SIa] $ toSeq (b_a <> b_b) checkBoundInputs (SS "") [SIb] execAll (SS "") [SIb] checkBoundInputs (SS "") [SIc] execAll (SS "") [SIc] checkBoundInputs (SS "") [SIa] execAll (SS "") [SIa] checkBoundDescs (SS "") [(SIa, "a"), (SIb, "b")] execAll (SS "") [SIa] checkBoundInputs (SS "") [SIb] describe "mappend" $ do it "should be able to combine SeqBindings with different prefixes." $ evalStateEmpty $ do State.put $ fromSeq $ withPrefix [SIc] $ ( (withPrefix [SIa, SIc] $ toSeq $ b_a) <> (withPrefix [SIa] $ toSeq $ b_b) ) checkBoundInputs (SS "") [SIc] execAll (SS "") [SIc] checkBoundInputs (SS "") [SIa] execAll (SS "") [SIa] checkBoundInputs (SS "") [SIc, SIb] checkBoundDesc (SS "") SIb "b" execAll (SS "") [SIb] checkBoundInputs (SS "") [SIc] execAll (SS "") [SIc, SIa] checkBoundInputs (SS "") [SIc, SIb] execAll (SS "") [SIc] checkBoundDescs (SS "") [(SIa, "a")] execAll (SS "") [SIa] checkBoundInputs (SS "") [SIc] describe "withCancel" $ do it "should weakly add 'cancel' binding when at least one prefix is kept in the state." $ evalStateEmpty $ do State.put $ fromSeq $ withPrefix [SIa, SIc] $ withCancel [SIa, SIb, SIc] $ ( toSeq b_a <> (withPrefix [SIc] $ toSeq b_b) ) let checkPrefixOne = do checkBoundInputs (SS "") [SIa] execAll (SS "") [SIa] checkBoundInputs (SS "") [SIa, SIb, SIc] forM_ [SIa, SIb] $ \c -> checkBoundDesc (SS "") c "cancel" checkPrefixOne execAll (SS "") [SIa] checkPrefixOne execAll (SS "") [SIc] checkBoundInputs (SS "") [SIa, SIb, SIc] checkBoundDesc (SS "") SIa "a" checkBoundDesc (SS "") SIb "cancel" execAll (SS "") [SIa] checkPrefixOne execAll (SS "") [SIc, SIb] checkPrefixOne execAll (SS "") [SIc, SIc] checkBoundDescs (SS "") [(SIa, "cancel"), (SIb, "b"), (SIc, "cancel")] execAll (SS "") [SIb] checkPrefixOne spec_reviseSeq :: Spec spec_reviseSeq = describe "reviseSeq" $ do it "should allow access to prefix keys input so far" $ evalStateEmpty $ withRefChecker [] $ \out checkOut -> do act_out <- liftIO $ newIORef ("" :: String) let sb = withCancel [SIa] $ withPrefix [SIa, SIb, SIc] $ toSeq $ base_b base_b = binds $ on SIb `as` "B" `run` modifyIORef act_out (++ "B executed") rev ps _ _ = justBefore $ modifyIORef out (++ [ps]) State.put $ fromSeq $ reviseSeq rev sb execAll (SS "") [SIa, SIa] checkOut [[], [SIa]] execAll (SS "") [SIa, SIb, SIc] checkOut [[], [SIa], [], [SIa], [SIa, SIb]] liftIO $ readIORef act_out `shouldReturn` "" execAll (SS "") [SIb] checkOut [[], [SIa], [], [SIa], [SIa, SIb], [SIa, SIb, SIc]] liftIO $ readIORef act_out `shouldReturn` "B executed" it "should allow unbinding" $ evalStateEmpty $ do let sb = withPrefix [SIa] ( toSeq ba <> (withPrefix [SIb] $ toSeq bab) <> (withPrefix [SIa] $ toSeq baa) ) ba = binds $ on SIc `as` "c on a" `run` return () bab = binds $ on SIc `as` "c on ab" `run` return () baa = binds $ do on SIc `as` "c on aa" `run` return () on SIb `as` "b on aa" `run` return () rev ps _ i act = if (ps == [SIa] && i == SIb) || (ps == [SIa,SIa] && i == SIc) then Nothing else Just act State.put $ fromSeq $ reviseSeq rev sb checkBoundInputs (SS "") [SIa] execAll (SS "") [SIa] checkBoundInputs (SS "") [SIa, SIc] -- SIb should be canceled execAll (SS "") [SIa] checkBoundDescs (SS "") [(SIb, "b on aa")] -- SIc should be canceled execAll (SS "") [SIb] checkBoundInputs (SS "") [SIa]
Java
Foursquare Archiver =================== Archive your Foursquare checkin data locally. This is a Python script for saving the json data from Foursuare's `checkins` resource https://developer.foursquare.com/docs/users/checkins . If you want to generate a heatmap of checkins, see [`csv.py`](./csv.py) and http://crccheck.github.io/foursquare-archiver/ Getting started --------------- In a virtualenv, install requirements: make install Get yourself a Foursquare Oauth token. See https://developer.foursquare.com/docs/explore Set the `FOURSQUARE_OAUTH_TOKEN` environment variable export FOURSQUARE_OAUTH_TOKEN=AAAABBBBBCCCCDDDD Usage ----- Run `main.py`. A `data` directory will be created if it does not already exist. ./main.py ### With Docker You can also run this via Docker with something like: docker run --rm -e FOURSQUARE_OAUTH_TOKEN=AAAABBBBBCCCCDDDD -v /tmp/data:/app/data:rw crccheck/foursquare-archiver --data=/app/data
Java
.filebrowser table td { font-size: 10px; } .filebrowser table a { font-size: 11px; } .filebrowser thead th.sorted a { padding-right: 13px; } .filebrowser td { padding: 9px 10px 7px 10px !important; } .filebrowser td.fb_icon { padding: 6px 5px 5px 5px !important; } table a.fb_deletelink, table a.fb_renamelink, table a.fb_selectlink, table a.fb_makethumblink, table a.fb_imagegeneratorlink { cursor: pointer; display: block; padding: 0; margin: 0; width: 23px; height: 17px; background-color: transparent; background-position: 0 center; background-repeat: no-repeat; } table .fb_deletelink:link, table .fb_deletelink:visited { width: 15px; background-image: url('../img/filebrowser_icon_delete.gif'); } table .fb_deletelink:hover, table .fb_deletelink:active { background-image: url('../img/filebrowser_icon_delete_hover.gif'); } table .fb_renamelink:link, table .fb_renamelink:visited { width: 14px; background-image: url('../img/filebrowser_icon_rename.gif'); } table .fb_renamelink:hover, table .fb_renamelink:active { background-image: url('../img/filebrowser_icon_rename_hover.gif'); } table .fb_selectlink:link, table .fb_selectlink:visited { background-image: url('../img/filebrowser_icon_select.gif'); } table .fb_selectlink:hover, table .fb_selectlink:active { background-image: url('../img/filebrowser_icon_select_hover.gif'); } table .fb_makethumblink:link, table .fb_makethumblink:visited { width: 50px; height: 29px; background-image: url('../img/filebrowser_icon_makethumb.gif'); } table .fb_makethumblink:hover, table .fb_makethumblink:active { background-image: url('../img/filebrowser_icon_makethumb_hover.gif'); } table .fb_imagegeneratorlink:link, table .fb_imagegeneratorlink:visited { background-image: url('../img/filebrowser_icon_imagegenerator.gif'); } table .fb_imagegeneratorlink:hover, table .fb_imagegeneratorlink:active { background-image: url('../img/filebrowser_icon_imagegenerator_hover.gif'); } /* Object Tools Basics (For Filebrowser without Grappelli) ----------------------------------------------------------------------- */ .object-tools { position:relative; float:right; font-weight:bold; font-family:Arial,Helvetica,sans-serif; text-transform: none; margin-top: -23px; margin-bottom:-10px; padding:0; } .form-row .object-tools { margin-top:5px; margin-bottom:5px; float:none; } .object-tools li { display:block; float:left; color: #ccc; font-size: 12px !important; line-height: 12px !important; padding: 0; background: none !important; } .object-tools li:hover { background:none !important; } .object-tools a { display: block; float: left; margin: -3px 0 0 15px; padding: 3px 0 2px 22px !important; font-size: 12px !important; line-height: 12px !important; background-color: #fff !important; background-position: 0 0 !important; background-repeat: no-repeat; } .object-tools a:link, .object-tools a:visited { color: #659DC2 !important; } .object-tools a:hover, .object-tools a:active { color: #555 !important; } /* Object Tools - Links ----------------------------------------------------------------------- */ .object-tools .fb_makedirectorylink:link, .object-tools .fb_makedirectorylink:visited { padding-left: 28px !important; background-image: url('../img/filebrowser_object-tools_icon_makedirectory.gif') !important; } .object-tools .fb_makedirectorylink:hover, .object-tools .fb_makedirectorylink:active { background-image: url('../img/filebrowser_object-tools_icon_makedirectory_hover.gif') !important; } .object-tools .fb_multipleuploadlink:link, .object-tools .fb_multipleuploadlink:visited { padding-left: 24px !important; background-image: url('../img/filebrowser_object-tools_icon_multipleupload.gif') !important; } .object-tools .fb_multipleuploadlink:hover, .object-tools .fb_multipleuploadlink:active { background-image: url('../img/filebrowser_object-tools_icon_multipleupload_hover.gif') !important; } .object-tools .fb_imagegeneratorlink:link, .object-tools .fb_imagegeneratorlink:visited { padding-left: 26px !important; background-image: url('../img/filebrowser_object-tools_icon_imagegenerator.gif') !important; } .object-tools .fb_imagegeneratorlink:hover, .object-tools .fb_imagegeneratorlink:active { background-image: url('../img/filebrowser_object-tools_icon_imagegenerator_hover.gif') !important; } .object-tools .fb_makethumbslink:link, .object-tools .fb_makethumbslink:visited { padding-left: 28px !important; background-image: url('../img/filebrowser_object-tools_icon_makethumb.gif') !important; } .object-tools .fb_makethumbslink:hover, .object-tools .fb_makethumbslink:active { background-image: url('../img/filebrowser_object-tools_icon_makethumb_hover.gif') !important; }
Java
<?php return array( 'Status\\V1\\Rpc\\Ping\\Controller' => array( 'GET' => array( 'description' => 'Ping the API for availability and receive a timestamp for acknowledgement.', 'request' => null, 'response' => '{ "ack": "Acknowledge the request with a timestamp" }', ), 'description' => 'Ping the API for availability.', ), 'Status\\V1\\Rest\\Status\\Controller' => array( 'collection' => array( 'GET' => array( 'description' => 'Retrieve a paginated list of status messages.', 'request' => null, 'response' => null, ), 'POST' => array( 'description' => 'Create a new status messages.', 'request' => null, 'response' => null, ), 'description' => 'Manipulate lists of status messages.', ), 'entity' => array( 'GET' => array( 'description' => 'Retrieve a status message.', 'request' => null, 'response' => '{ "_links": { "self": { "href": "/status[/:status_id]" } } "message": "A status message of no more than 140 characters.", "user": "The user submitting the status message.", "timestamp": "The timestamp when the status message was last modified." }', ), 'PATCH' => array( 'description' => 'Update a status message.', 'request' => '{ "message": "A status message of no more than 140 characters.", "user": "The user submitting the status message.", "timestamp": "The timestamp when the status message was last modified." }', 'response' => '{ "_links": { "self": { "href": "/status[/:status_id]" } } "message": "A status message of no more than 140 characters.", "user": "The user submitting the status message.", "timestamp": "The timestamp when the status message was last modified." }', ), 'PUT' => array( 'description' => 'Replace a status message.', 'request' => '{ "message": "A status message of no more than 140 characters.", "user": "The user submitting the status message.", "timestamp": "The timestamp when the status message was last modified." }', 'response' => '{ "_links": { "self": { "href": "/status[/:status_id]" } } "message": "A status message of no more than 140 characters.", "user": "The user submitting the status message.", "timestamp": "The timestamp when the status message was last modified." }', ), 'DELETE' => array( 'description' => 'Delete a status message.', 'request' => null, 'response' => null, ), 'description' => 'Manipulate and retrieve individual status messages.', ), 'description' => 'Create, manipulate, and retrieve status messages.', ), );
Java
#include <pulsar/testing/CppTester.hpp> #include <pulsar/system/Atom.hpp> using namespace pulsar; TEST_SIMPLE(TestAtom){ CppTester tester("Testing the Atom class"); Atom H=create_atom({0.0,0.0,0.0},1); Atom H2=create_atom({0.0,0.0,0.0},1,1); tester.test_equal("create_atom works",H,H2); tester.test_equal("correct Z",1,H.Z); tester.test_equal("correct isotope",1,H.isotope); tester.test_equal("correct mass",1.007975,H.mass); tester.test_equal("correct isotope mass",1.0078250322,H.isotope_mass); tester.test_equal("correct charge",0,H.charge); tester.test_equal("correct multiplicity",2,H.multiplicity); tester.test_equal("correct nelectrons",1,H.nelectrons); tester.test_equal("correct covalent radius",0.5858150988919267,H.cov_radius); tester.test_equal("correct vDW radius",2.267671350549394,H.vdw_radius); Atom H3(H2); tester.test_equal("copy constructor works",H,H3); Atom H4(std::move(H3)); tester.test_equal("move constructor works",H,H4); Atom D=create_atom({0.0,0.0,0.0},1,2); tester.test_equal("Isotopes work",2,D.isotope); tester.test_equal("Isotopes are different",true,D!=H); D=H4; tester.test_equal("assignment works",D,H); Atom U=create_atom({0.0,0.0,0.0},92); U=std::move(H4); tester.test_equal("move assignment works",U,H); tester.test_equal("hash works",H.my_hash(),U.my_hash()); tester.test_equal("hash works 1",H.my_hash(),H2.my_hash()); tester.test_equal("hash works 2",H.my_hash(),D.my_hash()); Atom GH=make_ghost_atom(H2); tester.test_equal("ghost works",true,is_ghost_atom(GH)); Atom q=make_point_charge(H2,3.3),q2=make_point_charge(H2.get_coords(),3.3); tester.test_equal("point charges work",true,is_point_charge(q)); tester.test_equal("point charges work 2",true,is_point_charge(q2)); tester.test_equal("is same point charge",q,q2); Atom Dm=make_dummy_atom(H),Dm2=make_dummy_atom(H.get_coords()); tester.test_equal("is dummy atom",true,is_dummy_atom(Dm)); tester.test_equal("is dummy atom 2",true,is_dummy_atom(Dm2)); tester.test_equal("is same dummy atom",Dm,Dm2); tester.print_results(); return tester.nfailed(); }
Java
<?php /** * Created by PhpStorm. * User: bill * Date: 13.04.15 * Time: 17:13 */ namespace app\tests\codeception\unit\modules\mobile\models; use app\modules\mobile\models\Trip; use app\tests\codeception\unit\fixtures\TripFixture; use Codeception\Specify; use yii\codeception\TestCase; use MongoDate; class TripTest extends TestCase{ use Specify; /** * @var \UnitTester */ protected $tester; public function fixtures() { return [ 'reports' => [ 'class' => TripFixture::className(), ], ]; } public function testGetStatus() { $this->specify("Status must be correct", function($duration, $possession, $complete, $expected) { $model = new Trip(); $model['duration'] = $duration; $model['numberPossession'] = $possession; $model['complete'] = $complete; expect($model->getStatus())->equals($expected); },[ 'examples' => [ [ 'duration' => ['to' => new MongoDate(strtotime('08.03.2015'))], 'possession' => ['to' => new MongoDate(strtotime('07.03.2015'))], 'complete' => true, 'expected' => Trip::STATUS_COMPLETE ], [ 'duration' => ['to' => new MongoDate(strtotime('08.03.2015'))], 'possession' => ['to' => new MongoDate(strtotime('11.03.2015'))], 'complete' => true, 'expected' => Trip::STATUS_COMPLETE ], [ 'duration' => ['to' => new MongoDate(strtotime('08.03.2015'))], 'possession' => ['to' => new MongoDate(strtotime('12.03.2015'))], 'complete' => true, 'expected' => Trip::STATUS_EXPIRED ], [ 'duration' => ['to' => new MongoDate()], 'possession' => ['to' => null], 'complete' => false, 'expected' => Trip::STATUS_INCOMPLETE ], [ 'duration' => ['to' => new MongoDate(time()-Trip::TIME_TO_RETURN_NUMBER - 1)], 'possession' => ['to' => null], 'complete' => false, 'expected' => Trip::STATUS_EXPIRED ], ] ]); } }
Java
<?php class ReCopyWidget extends CWidget { public $targetClass='clone'; //Target CSS class target for duplicate public $limit=0; //The number of allowed copies. Default: 0 is unlimited public $addButtonId; // Add button id. Set id differently if this widget is called multiple times per page. public $addButtonLabel='Add more'; //Add button text. public $addButtonCssClass=''; //Add button CSS class. public $removeButtonLabel='Remove'; //Remove button text public $removeButtonCssClass='recopy-remove'; //Remove button CSS class. public $excludeSelector; //A jQuery selector used to exclude an element and its children public $copyClass; //A class to attach to each copy public $clearInputs; //Boolean Option to clear each copies text input fields or textarea private $_assetsUrl; /** * Initializes the widgets */ public function init() { parent::init(); if ($this->_assetsUrl === null) { $assetsDir = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'assets'; $this->_assetsUrl = Yii::app()->assetManager->publish($assetsDir); } $this->addButtonId=trim($this->addButtonId); if(empty($this->addButtonId)) $this->addButtonId='recopy-add'; if($this->limit) $this->limit= (is_numeric($this->limit) && $this->limit > 0)? (int)ceil($this->limit):0; } /** * Execute the widgets */ public function run() { if($this->limit==1) return ; Yii::app()->clientScript ->registerScriptFile($this->_assetsUrl . '/reCopy.js', CClientScript::POS_HEAD) ->registerScript(__CLASS__.$this->addButtonId, ' $(function(){ var removeLink = \' <a class="'.$this->removeButtonCssClass.'" href="#" onclick="$(this).parent().slideUp(function(){ $(this).remove() }); return false">'.$this->removeButtonLabel.'</a>\'; $("a#'.$this->addButtonId.'").relCopy({'.implode(', ', array_filter(array( empty($this->excludeSelector)?'':'excludeSelector: "'.$this->excludeSelector.'"', empty($this->limit)? '': 'limit: '.$this->limit, empty($this->copyClass)? '': 'copyClass: "'.$this->copyClass.'"', $this->clearInputs===true? 'clearInputs: true':'', $this->clearInputs===false? 'clearInputs: false':'', 'append: removeLink', ))).'}); }); ', CClientScript::POS_END); echo CHtml::link($this->addButtonLabel, '#', array( 'id'=>$this->addButtonId, 'rel'=>'.'.$this->targetClass, 'class'=>$this->addButtonCssClass) ); } }//end class
Java
/** *============================================================================ * The Ohio State University Research Foundation, The University of Chicago - * Argonne National Laboratory, Emory University, SemanticBits LLC, * and Ekagra Software Technologies Ltd. * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/cagrid-workflow/LICENSE.txt for details. *============================================================================ **/ package gov.nih.nci.cagrid.portal.portlet.workflow.mvc; import gov.nih.nci.cagrid.portal.portlet.workflow.WorkflowExecutionService; import gov.nih.nci.cagrid.portal.portlet.workflow.WorkflowRegistryService; import gov.nih.nci.cagrid.portal.portlet.workflow.domain.SessionEprs; import gov.nih.nci.cagrid.portal.portlet.workflow.domain.SubmitWorkflowCommand; import gov.nih.nci.cagrid.portal.portlet.workflow.domain.WorkflowDescription; import gov.nih.nci.cagrid.portal.portlet.workflow.domain.WorkflowSubmitted; import gov.nih.nci.cagrid.portal.portlet.workflow.util.Utils; import java.io.File; import java.io.IOException; import java.util.Map; import java.util.UUID; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; import org.apache.axis.message.addressing.EndpointReferenceType; import org.apache.commons.httpclient.HttpException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.validation.BindException; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.portlet.ModelAndView; import org.springframework.web.portlet.bind.PortletRequestUtils; import org.springframework.web.portlet.mvc.SimpleFormController; @Controller @RequestMapping(params={"action=newInstance"}) @SuppressWarnings("deprecation") public class NewInstanceFormController extends SimpleFormController { protected final Log log = LogFactory.getLog(getClass()); @Autowired private WorkflowExecutionService workflowService; @Autowired @Qualifier("MyExperiment") private WorkflowRegistryService registry; @Autowired private SessionEprs eprs; @Autowired private Utils utilities; /* @see org.springframework.web.portlet.mvc.SimpleFormController#processFormSubmission(javax.portlet.ActionRequest, javax.portlet.ActionResponse, java.lang.Object, org.springframework.validation.BindException) */ @Override protected void processFormSubmission(ActionRequest request, ActionResponse response, Object command, BindException errors) throws Exception { String id = PortletRequestUtils.getStringParameter(request, "id", "NaN"); log.debug("processFormSubmission. action: " + PortletRequestUtils.getStringParameter(request, "action", "NaN") + " | id - " + id); SubmitWorkflowCommand cmd = (SubmitWorkflowCommand)command; log.debug("Command Object: " + cmd.getTheWorkflow()); try { WorkflowDescription selectedWorkflow = registry.getWorkflow(id); log.info("Submitting the selected workflow.. #" + id); String tempFilePath = saveWorkflowDefinition(selectedWorkflow); EndpointReferenceType epr = workflowService.submitWorkflow(selectedWorkflow.getName(), tempFilePath, cmd.getInputValues()); UUID uuid = UUID.randomUUID(); log.debug("Will submit UUID : " + uuid.toString()); eprs.put(uuid.toString(), new WorkflowSubmitted(epr, selectedWorkflow, "Submitted")); cmd.setResult("The Workflow was submitted successfully."); log.info("The Workflow was submitted successfully."); } catch(Throwable e) { log.error("Error submitting workflow", e); Throwable ex = e.getCause(); while(ex.getCause() !=null ) { ex = ex.getCause(); } cmd.setResult(e.getClass().getSimpleName() + " submitting workflow: " + e.getMessage()); } } /* @see org.springframework.web.portlet.mvc.SimpleFormController#renderFormSubmission(javax.portlet.RenderRequest, javax.portlet.RenderResponse, java.lang.Object, org.springframework.validation.BindException) */ @Override protected ModelAndView renderFormSubmission(RenderRequest request, RenderResponse response, Object cmd, BindException errors) throws Exception { log.debug("renderFormSubmission. action: " + PortletRequestUtils.getStringParameter(request, "action", "NaN")); return new ModelAndView("json", "contents", ((SubmitWorkflowCommand)cmd).getResult()); } /* @see org.springframework.web.portlet.mvc.SimpleFormController#showForm(javax.portlet.RenderRequest, javax.portlet.RenderResponse, org.springframework.validation.BindException) */ @Override protected ModelAndView showForm(RenderRequest request, RenderResponse response, BindException errors) throws Exception { String id = PortletRequestUtils.getStringParameter(request, "id", "NaN"); log.info("showForm. Action: " + PortletRequestUtils.getStringParameter(request, "action", "NaN") + " | id: " + id); SubmitWorkflowCommand cmd = new SubmitWorkflowCommand(); cmd.setTheWorkflow(registry.getWorkflow(id)); return new ModelAndView("newInstance", "cmd", cmd); } /** * Download the workflow definition to local filesystem * @param wd Workflow Definition * @return path of temporary file * @throws IOException * @throws HttpException */ private String saveWorkflowDefinition(WorkflowDescription wd) throws HttpException, IOException { File tmpPath = new File( System.getProperty("java.io.tmpdir")+"/taverna" ); tmpPath.mkdirs(); String defPath = tmpPath.getAbsolutePath()+"/myexperiment_"+wd.getId()+"_v"+wd.getVersion()+".t2flow"; if(new File(defPath).exists()) { log.debug("Definition temporary file already exists so not downloading again."); return defPath; } getUtilities().saveFile(defPath, getUtilities().download(wd.getContentURI()) ); return defPath; } public SessionEprs getSessionEprs() {return eprs;} public void setSessionEprs(SessionEprs sessionEprs) {this.eprs = sessionEprs;} public WorkflowExecutionService getWorkflowService() {return workflowService;} public void setWorkflowService(WorkflowExecutionService workflowService) {this.workflowService = workflowService;} public WorkflowRegistryService getRegistry() {return registry;} public void setRegistry(WorkflowRegistryService registry) {this.registry = registry;} public Utils getUtilities() {return utilities;} public void setUtilities(Utils utilities) {this.utilities = utilities;} }
Java
<?php namespace PayrollCalculator; use Zend\ModuleManager\Feature\ConsoleUsageProviderInterface; use Zend\Console\Adapter\AdapterInterface as Console; class Module { public function getConfig() { return include __DIR__ . '/config/module.config.php'; } public function getAutoloaderConfig() { return array( 'Zend\Loader\StandardAutoloader' => array( 'namespaces' => array( __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__, ), ), ); } public function getConsoleUsage(Console $console) { return array( // Describe available commands 'outputpaydays FileName.csv' => 'Show pay days for the remainder of the year', // Describe expected parameters array( 'FileName.csv', 'A file where you would like your output saved' ), ); } }
Java
# -*- coding: utf-8 -*- """ eve.io.media ~~~~~~~~~~~~ Media storage for Eve-powered APIs. :copyright: (c) 2014 by Nicola Iarocci. :license: BSD, see LICENSE for more details. """ class MediaStorage(object): """ The MediaStorage class provides a standardized API for storing files, along with a set of default behaviors that all other storage systems can inherit or override as necessary. ..versioneadded:: 0.3 """ def __init__(self, app=None): """ :param app: the flask application (eve itself). This can be used by the class to access, amongst other things, the app.config object to retrieve class-specific settings. """ self.app = app def get(self, id_or_filename): """ Opens the file given by name or unique id. Note that although the returned file is guaranteed to be a File object, it might actually be some subclass. Returns None if no file was found. """ raise NotImplementedError def put(self, content, filename=None, content_type=None): """ Saves a new file using the storage system, preferably with the name specified. If there already exists a file with this name name, the storage system may modify the filename as necessary to get a unique name. Depending on the storage system, a unique id or the actual name of the stored file will be returned. The content type argument is used to appropriately identify the file when it is retrieved. .. versionchanged:: 0.5 Allow filename to be optional (#414). """ raise NotImplementedError def delete(self, id_or_filename): """ Deletes the file referenced by name or unique id. If deletion is not supported on the target storage system this will raise NotImplementedError instead """ raise NotImplementedError def exists(self, id_or_filename): """ Returns True if a file referenced by the given name or unique id already exists in the storage system, or False if the name is available for a new file. """ raise NotImplementedError
Java
<!-- %BD_HTML%/SearchResult.htm --> <HTML> <HEAD> <meta http-equiv="Content-Type" content="text/html; charset=windows-1255"> <TITLE>úåöàú àéðèøðè - Takanot File</TITLE> </HEAD> <style> <!-- TR.A_Table {font-color:#3e6ea6; background-color: #f7f9fb; font-size:11;font-family: Arial,} TR.B_Table {font-color:#3e6ea6; background-color: #ecf1f6; font-size:11;font-family: Arial,} TR.C {font-color:#1e4a7a; background-color: #A9CAEF;font-weight:bold; font-size:11;font-family: Arial,} TR.clear { font-color:#1e4a7a; background-color: #FFFFFF;} H5 { font-family:Arial, Helvetica, sans-serif; font-size: 14px;} H3 { font-family:Arial, Helvetica, sans-serif; font-size: 16px;} TD.A_Row { font-family: Arial, Helvetica, sans-serif; font-weight:bold; font-style: normal; color: #093300; font-size: 10px} .defaultFont { color:#1f4a7b;font-family: Arial, Helvetica, sans-serif; font-size: 12px} --> </style> <BODY dir=rtl class="defaultFont"> <CENTER> <IMG src="/budget/Images/title1.jpg" align=bottom alt="ú÷öéá äîãéðä"> <TABLE align="center" border=0 cellspacing=0 cellpadding=0> <TR align="center"> <TD><H3>úåöàú çéôåù ìùðú 2007</H3></TD> </TR> <TR align="center"> <!--<TD><H3>ðúåðé áéöåò ðëåðéí ìñåó çåãù 04/2008</H3></TD>--> <TD><H3>ðúåðé áéöåò ëôé ùðøùîå áñôøé äðäìú äçùáåðåú ùì äîùøãéí - 04/2008<br></H3></TD> </TR> </TR align="center"> <TD><H3>àéï àçéãåú áéï äñòéôéí ìâáé îåòã òãëåï äðúåðéí</H3></TD> </TR> </TABLE> <H5>äñëåîéí äéðí ùì çå÷ äú÷öéá äî÷åøé åáàìôé ù÷ìéí <BR> </H5> </CENTER> <table width="100%" border="0" cellspacing="1" cellpadding="1" bgcolor="#8fbcee"> <TR class="C" align="center"> <TD valign=top width=50>ñòéó</TD> <TD valign=top align="right" width=120>ùí ñòéó</TD> <TD valign=top width=65>äåöàä ðèå</TD> <TD valign=top width=65>äåöàä îåúðéú áäëðñä</TD> <TD valign=top width=65>ñä"ë äåöàä</TD> <TD valign=top width=65>äøùàä ìäúçééá</TD> <TD valign=top width=65>ùéà ë"à</TD> <TD valign=top width=40>ñä"ë ðåöì</TD> <TD valign=top width=40>àçåæ ðåöì</TD> </TR> </TABLE> <table width="100%" border="0" cellspacing="1" cellpadding="1" bgcolor="#8fbcee"> <TR class="B_Table" align="center"> <TD valign=top width=50>&nbsp;60</TD> <TD valign=top align="right" width=120>&nbsp;çéðåê</TD> <TD valign=top width=65>&nbsp; 543,226</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 543,226</TD> <TD valign=top width=65>&nbsp; 453,365</TD> <TD valign=top width=65>&nbsp; 0.0</TD> <TD valign=top width=40>&nbsp; 461,148</TD> <TD valign=top width=40>&nbsp; 84.89</TD> </TR> <TR class="A_Table" align="center"> <TD valign=top width=50>&nbsp;6002</TD> <TD valign=top align="right" width=120>&nbsp;úëðéú ôéúåç çéðåê</TD> <TD valign=top width=65>&nbsp; 454,800</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 454,800</TD> <TD valign=top width=65>&nbsp; 384,339</TD> <TD valign=top width=65>&nbsp; 0.0</TD> <TD valign=top width=40>&nbsp; 364,590</TD> <TD valign=top width=40>&nbsp; 80.16</TD> </TR> <TR class="B_Table" align="center"> <TD valign=top width=50>&nbsp;600210</TD> <TD valign=top align="right" width=120>&nbsp;áðééú ëéúåú ìéîåã</TD> <TD valign=top width=65>&nbsp; 440,316</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 440,316</TD> <TD valign=top width=65>&nbsp; 369,855</TD> <TD valign=top width=65>&nbsp; 0.0</TD> <TD valign=top width=40>&nbsp; 350,527</TD> <TD valign=top width=40>&nbsp; 79.61</TD> </TR> <TR class="A_Table" align="center"> <TD valign=top width=50>&nbsp;600215</TD> <TD valign=top align="right" width=120>&nbsp;úùúéåú äé÷ôéåú ìîáðé çéðåê</TD> <TD valign=top width=65>&nbsp; 14,484</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 14,484</TD> <TD valign=top width=65>&nbsp; 14,484</TD> <TD valign=top width=65>&nbsp; 0.0</TD> <TD valign=top width=40>&nbsp; 14,063</TD> <TD valign=top width=40>&nbsp; 97.09</TD> </TR> <TR class="B_Table" align="center"> <TD valign=top width=50>&nbsp;6003</TD> <TD valign=top align="right" width=120>&nbsp;äöèéãåú îáðé çéðåê</TD> <TD valign=top width=65>&nbsp; 10,505</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 10,505</TD> <TD valign=top width=65>&nbsp; 10,505</TD> <TD valign=top width=65>&nbsp; 0.0</TD> <TD valign=top width=40>&nbsp; 10,336</TD> <TD valign=top width=40>&nbsp; 98.39</TD> </TR> <TR class="A_Table" align="center"> <TD valign=top width=50>&nbsp;600301</TD> <TD valign=top align="right" width=120>&nbsp;îòð÷éí ìäöèéãåú</TD> <TD valign=top width=65>&nbsp; 10,505</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 10,505</TD> <TD valign=top width=65>&nbsp; 10,505</TD> <TD valign=top width=65>&nbsp; 0.0</TD> <TD valign=top width=40>&nbsp; 10,336</TD> <TD valign=top width=40>&nbsp; 98.39</TD> </TR> <TR class="B_Table" align="center"> <TD valign=top width=50>&nbsp;6006</TD> <TD valign=top align="right" width=120>&nbsp;çéãåù îáðéí</TD> <TD valign=top width=65>&nbsp; 61,624</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 61,624</TD> <TD valign=top width=65>&nbsp; 42,224</TD> <TD valign=top width=65>&nbsp; 0.0</TD> <TD valign=top width=40>&nbsp; 63,558</TD> <TD valign=top width=40>&nbsp;103.14</TD> </TR> <TR class="A_Table" align="center"> <TD valign=top width=50>&nbsp;600601</TD> <TD valign=top align="right" width=120>&nbsp;çéãåù îáðéí áîòøëú</TD> <TD valign=top width=65>&nbsp; 61,624</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 61,624</TD> <TD valign=top width=65>&nbsp; 42,224</TD> <TD valign=top width=65>&nbsp; 0.0</TD> <TD valign=top width=40>&nbsp; 63,558</TD> <TD valign=top width=40>&nbsp;103.14</TD> </TR> <TR class="B_Table" align="center"> <TD valign=top width=50>&nbsp;6007</TD> <TD valign=top align="right" width=120>&nbsp;ôéúåç îëììåú ìäëùøú îåøéí</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 0.0</TD> <TD valign=top width=40>&nbsp; 193</TD> <TD valign=top width=40>&nbsp; 0.00</TD> </TR> <TR class="A_Table" align="center"> <TD valign=top width=50>&nbsp;600701</TD> <TD valign=top align="right" width=120>&nbsp;ôéúåç îëììåú ìäëùøú îåøéí</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 0.0</TD> <TD valign=top width=40>&nbsp; 193</TD> <TD valign=top width=40>&nbsp; 0.00</TD> </TR> <TR class="B_Table" align="center"> <TD valign=top width=50>&nbsp;6008</TD> <TD valign=top align="right" width=120>&nbsp;øæøáä</TD> <TD valign=top width=65>&nbsp; 16,297</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 16,297</TD> <TD valign=top width=65>&nbsp; 16,297</TD> <TD valign=top width=65>&nbsp; 0.0</TD> <TD valign=top width=40>&nbsp; 16,297</TD> <TD valign=top width=40>&nbsp;100.00</TD> </TR> <TR class="A_Table" align="center"> <TD valign=top width=50>&nbsp;600801</TD> <TD valign=top align="right" width=120>&nbsp;øæøáä ìòîéãä áéòãéí</TD> <TD valign=top width=65>&nbsp; 16,297</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 16,297</TD> <TD valign=top width=65>&nbsp; 16,297</TD> <TD valign=top width=65>&nbsp; 0.0</TD> <TD valign=top width=40>&nbsp; 16,297</TD> <TD valign=top width=40>&nbsp;100.00</TD> </TR> <TR class="B_Table" align="center"> <TD valign=top width=50>&nbsp;6009</TD> <TD valign=top align="right" width=120>&nbsp;øæøáä ìééùåí îñ÷ðåú ëç</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 0.0</TD> <TD valign=top width=40>&nbsp; 6,174</TD> <TD valign=top width=40>&nbsp; 0.00</TD> </TR> <TR class="A_Table" align="center"> <TD valign=top width=50>&nbsp;600901</TD> <TD valign=top align="right" width=120>&nbsp;øæøáä ìééùåí îñ÷ðåú ëç</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 0.0</TD> <TD valign=top width=40>&nbsp; 6,174</TD> <TD valign=top width=40>&nbsp; 0.00</TD> </TR> </TABLE> </CENTER> <BR> <CENTER> <table border="0" cellspacing="1" cellpadding="3" bgcolor="#8fbcee" dir="rtl"> <TR class="C" align="center"> <TD class="A_Row" valign=top width=80>ñéëåí ãå"ç</TD> <TD class="A_Row" valign=top width=60>äåöàä ðèå</TD> <TD class="A_Row" valign=top width=60>äåöàä îåúðéú áäëðñä</TD> <TD class="A_Row" valign=top width=60>ñä"ë äåöàä</TD> <TD class="A_Row" valign=top width=60>äøùàä ìäúçééá</TD> <TD class="A_Row" valign=top width=60>ùéà ë"à</TD> <TD class="A_Row" valign=top width=50>ñä"ë ðåöì</TD> <TD class="A_Row" valign=top width=50>àçåæ ðåöì</TD> </TR> <TR class="clear" align="center"> <TD class="A_Row" valign=top width=80>&nbsp;ú÷öéá î÷åøé</TD> <TD class="A_Row" valign=top width=60>&nbsp; 543,226</TD> <TD class="A_Row" valign=top width=60>&nbsp; 0</TD> <TD class="A_Row" valign=top width=60>&nbsp; 543,226</TD> <TD class="A_Row" valign=top width=60>&nbsp; 453,365</TD> <TD class="A_Row" valign=top width=60>&nbsp; 0</TD> <TD class="A_Row" valign=top width=50>&nbsp;</TD> <TD class="A_Row" valign=top width=50>&nbsp;</TD> </TR> <!--<TR class="clear" align="center"> <TD class="A_Row" valign=top width=80>&nbsp;ú÷öéá òì ùéðåééå</TD> <TD class="A_Row" valign=top width=60>&nbsp; 792,146</TD> <TD class="A_Row" valign=top width=60>&nbsp; 0</TD> <TD class="A_Row" valign=top width=60>&nbsp; 792,146</TD> <TD class="A_Row" valign=top width=60>&nbsp; 563,518</TD> <TD class="A_Row" valign=top width=60>&nbsp; 0</TD> <TD class="A_Row" valign=top width=50>&nbsp; 461,148</TD> <TD class="A_Row" valign=top width=50>&nbsp; 84.89</TD> </TR>--> </TABLE> <CENTER> <TABLE WIDTH="100" > <TR> <TD align="center" nowrap> <IMG SRC="/budget/Images/semel.gif" HEIGHT=37 WIDTH=30 border = "0"><BR> <FONT SIZE=-2> <A HREF="http://www.mof.gov.il/rights.htm"> ëì äæëåéåú &copy; .ùîåøåú,2005,îãéðú éùøàì<BR></A> ðùîç ì÷áì àú äòøåúéëí åäöòåúéëí ìëúåáú: </FONT> <FONT SIZE=-2 dir=ltr> <A HREF="mailto:Webmaster@mof.gov.il">Webmaster@mof.gov.il</A><BR> </FONT> </TD> </TR> </TABLE> </CENTER> </CENTER> </BODY> </HTML>
Java
from django.utils.translation import ugettext as _ from django.db import models from jmbo.models import ModelBase class Superhero(ModelBase): name = models.CharField(max_length=256, editable=False) class Meta: verbose_name_plural = _("Superheroes")
Java
/* Copyright (c) 2015-present, salesforce.com, inc. All rights reserved */ /* Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license */ export default {"viewBox":"0 0 100 100","xmlns":"http://www.w3.org/2000/svg","path":{"d":"M50.6 52.9c2.6-3.7 5.3-5.6 7.1-8.4 3.2-4.8 3.9-11.6 1.8-16.8-2.1-5.3-7-8.4-12.7-8.3S36.5 23 34.7 28.3c-2.1 5.8-1.2 12.8 3.5 17.2 1.9 1.8 3.7 4.7 2.7 7.4-.9 2.6-4 3.7-6.2 4.8-5 2.2-11.1 5.3-12.1 11.2-1 4.9 2.3 10 7.6 10h23.3c1 0 1.9-1.2 1.3-1.9-3.2-3.7-6.6-8.7-6.6-13.6-.3-3.5.7-7.4 2.4-10.5zm14.2 13.5c-2.7 0-5-2.2-5-4.9s2.2-4.9 5-4.9c2.7 0 5 2.2 5 4.9.1 2.7-2.3 4.9-5 4.9zm0-16.8c-6.6 0-11.9 5.3-11.9 11.9 0 8.1 8.5 15.8 11.1 17.7.4.4 1 .4 1.6 0 2.6-2.1 11.1-9.6 11.1-17.7 0-6.6-5.3-11.9-11.9-11.9z"}};
Java
<?php namespace common\widgets; use yii\helpers\VarDumper; /** * Created by PhpStorm. * User: Александр Чернявенко * Date: 25.11.2014 * Time: 14:09 */ class PredictionAsset extends \yii\web\AssetBundle { public $depends = [ 'yii\web\JqueryAsset', ]; public $css = [ ]; public $js = [ ]; public function init() { $this->setSourcePath(__DIR__ . '/assets/prediction'); parent::init(); } /** * Sets the source path if empty * * @param string $path the path to be set */ protected function setSourcePath($path) { if (empty($this->sourcePath)) { $this->sourcePath = $path; } } }
Java
/*@author gihan tharanga*/ #include <iostream> #include <string> //video capturing methods int videoCapturing(); int videoCapOriginal(); /*detect the faces display the frames and number of face*/ int FaceDetector(std::string&);
Java
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: ''' Processor functions for images ''' import numpy as np def squeeze_image(img): ''' Return image, remove axes length 1 at end of image shape For example, an image may have shape (10,20,30,1,1). In this case squeeze will result in an image with shape (10,20,30). See doctests for further description of behavior. Parameters ---------- img : ``SpatialImage`` Returns ------- squeezed_img : ``SpatialImage`` Copy of img, such that data, and data shape have been squeezed, for dimensions > 3rd, and at the end of the shape list Examples -------- >>> import nipype.externals.pynifti as nf >>> shape = (10,20,30,1,1) >>> data = np.arange(np.prod(shape)).reshape(shape) >>> affine = np.eye(4) >>> img = nf.Nifti1Image(data, affine) >>> img.get_shape() (10, 20, 30, 1, 1) >>> img2 = squeeze_image(img) >>> img2.get_shape() (10, 20, 30) If the data are 3D then last dimensions of 1 are ignored >>> shape = (10,1,1) >>> data = np.arange(np.prod(shape)).reshape(shape) >>> img = nf.ni1.Nifti1Image(data, affine) >>> img.get_shape() (10, 1, 1) >>> img2 = squeeze_image(img) >>> img2.get_shape() (10, 1, 1) Only *final* dimensions of 1 are squeezed >>> shape = (1, 1, 5, 1, 2, 1, 1) >>> data = data.reshape(shape) >>> img = nf.ni1.Nifti1Image(data, affine) >>> img.get_shape() (1, 1, 5, 1, 2, 1, 1) >>> img2 = squeeze_image(img) >>> img2.get_shape() (1, 1, 5, 1, 2) ''' klass = img.__class__ shape = img.get_shape() slen = len(shape) if slen < 4: return klass.from_image(img) for bdim in shape[3::][::-1]: if bdim == 1: slen-=1 else: break if slen == len(shape): return klass.from_image(img) shape = shape[:slen] data = img.get_data() data = data.reshape(shape) return klass(data, img.get_affine(), img.get_header(), img.extra) def concat_images(images): ''' Concatenate images in list to single image, along last dimension ''' n_imgs = len(images) img0 = images[0] i0shape = img0.get_shape() affine = img0.get_affine() header = img0.get_header() out_shape = (n_imgs, ) + i0shape out_data = np.empty(out_shape) for i, img in enumerate(images): if not np.all(img.get_affine() == affine): raise ValueError('Affines do not match') out_data[i] = img.get_data() out_data = np.rollaxis(out_data, 0, len(i0shape)+1) klass = img0.__class__ return klass(out_data, affine, header)
Java
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE191_Integer_Underflow__short_rand_postdec_07.c Label Definition File: CWE191_Integer_Underflow.label.xml Template File: sources-sinks-07.tmpl.c */ /* * @description * CWE: 191 Integer Underflow * BadSource: rand Set data to result of rand() * GoodSource: Set data to a small, non-zero number (negative two) * Sinks: decrement * GoodSink: Ensure there will not be an underflow before decrementing data * BadSink : Decrement data, which can cause an Underflow * Flow Variant: 07 Control flow: if(staticFive==5) and if(staticFive!=5) * * */ #include "std_testcase.h" /* The variable below is not declared "const", but is never assigned any other value so a tool should be able to identify that reads of this will always give its initialized value. */ static int staticFive = 5; #ifndef OMITBAD void CWE191_Integer_Underflow__short_rand_postdec_07_bad() { short data; data = 0; if(staticFive==5) { /* POTENTIAL FLAW: Use a random value */ data = (short)RAND32(); } if(staticFive==5) { { /* POTENTIAL FLAW: Decrementing data could cause an underflow */ data--; short result = data; printIntLine(result); } } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodB2G1() - use badsource and goodsink by changing the second staticFive==5 to staticFive!=5 */ static void goodB2G1() { short data; data = 0; if(staticFive==5) { /* POTENTIAL FLAW: Use a random value */ data = (short)RAND32(); } if(staticFive!=5) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Add a check to prevent an underflow from occurring */ if (data > SHRT_MIN) { data--; short result = data; printIntLine(result); } else { printLine("data value is too large to perform arithmetic safely."); } } } /* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */ static void goodB2G2() { short data; data = 0; if(staticFive==5) { /* POTENTIAL FLAW: Use a random value */ data = (short)RAND32(); } if(staticFive==5) { /* FIX: Add a check to prevent an underflow from occurring */ if (data > SHRT_MIN) { data--; short result = data; printIntLine(result); } else { printLine("data value is too large to perform arithmetic safely."); } } } /* goodG2B1() - use goodsource and badsink by changing the first staticFive==5 to staticFive!=5 */ static void goodG2B1() { short data; data = 0; if(staticFive!=5) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Use a small, non-zero value that will not cause an underflow in the sinks */ data = -2; } if(staticFive==5) { { /* POTENTIAL FLAW: Decrementing data could cause an underflow */ data--; short result = data; printIntLine(result); } } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */ static void goodG2B2() { short data; data = 0; if(staticFive==5) { /* FIX: Use a small, non-zero value that will not cause an underflow in the sinks */ data = -2; } if(staticFive==5) { { /* POTENTIAL FLAW: Decrementing data could cause an underflow */ data--; short result = data; printIntLine(result); } } } void CWE191_Integer_Underflow__short_rand_postdec_07_good() { goodB2G1(); goodB2G2(); goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE191_Integer_Underflow__short_rand_postdec_07_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE191_Integer_Underflow__short_rand_postdec_07_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
Java
<?php namespace VKBansal\Test\Spectrum\Plugin; class PlugTest extends \PHPUnit_Framework_TestCase{ protected $plugin; protected $plug; public function setUp() { $this->plugin = $this->getMockForAbstractClass('VKBansal\Spectrum\Plugin\AbstractPlugin'); $this->plugin ->method('getName')->will($this->returnValue('test-plugin')); $this->plugin ->method('add')->will($this->returnValue(true)); $this->plugin ->method('remove')->will($this->returnValue(true)); $this->plug = $this->getMockForTrait('VKBansal\Spectrum\Plugin\PluggableTrait', [], 'Spectrum'); } /** * @expectedException \VKBansal\Spectrum\Plugin\PluginNotFoundException */ public function testRemoveException() { $this->markTestSkipped(); $this->plug->addPlugin($this->plugin); $this->plug->removePlugin('test-plugin'); $this->plug->removePlugin('test-plugin'); } }
Java
<div> <div class="os-page-commands"> <div class="left" os-imaging> <button show-if-allowed="specimenResource.updateOpts" class="default" ui-sref="specimen-addedit" ng-if="!!visit.id && !specimen.reserved && (!specimen.activityStatus || specimen.activityStatus == 'Active')" ng-switch on="!!specimen.id"> <span ng-switch-when="true"> <span class="fa fa-pencil"></span> <span translate="common.buttons.edit">Edit</span> </span> <span ng-switch-default> <span class="fa fa-plus"></span> <span translate="specimens.buttons.collect">Collect</span> </span> </button> <span ng-if="!!specimen.id"> <div ng-if="!specimen.reserved && specimen.activityStatus == 'Active' && specimen.status == 'Collected'" show-if-allowed="specimenResource.allUpdateOpts" dropdown class="os-inline-btn"> <button class="btn btn-default dropdown-toggle default"> <span class="fa fa-plus"></span> <span translate="common.buttons.create">Create</span> <span class="fa fa-caret-down"></span> </button> <ul class="dropdown-menu"> <li> <a ui-sref="specimen-create-derivative( {eventId: visit.eventId, visitId: visit.id, specimenId: specimen.id, srId: specimen.reqId})"> <span class="fa fa-flask"></span> <span translate="specimens.ctx_menu.create_derivative">Create Derivative</span> </a> </li> <li> <a ui-sref="specimen-create-aliquots( {eventId: visit.eventId, visitId: visit.id, specimenId: specimen.id, srId: specimen.reqId})"> <span class="fa fa-share-alt"></span> <span translate="specimens.ctx_menu.create_aliquots">Create Aliquots</span> </a> </li> </ul> </div> <os-assign-to-spmn-list menu-align="left" on-add-to-list="addSpecimensToSpecimenList(list)"> </os-assign-to-spmn-list> <button show-if-allowed="specimenResource.updateOpts" class="default" ng-if="!cpViewCtx.isCoordinator && specimen.activityStatus == 'Active' && specimen.status == 'Collected'" ng-click="printSpecimenLabels()"> <span class="fa fa-print"></span> <span translate="specimens.buttons.print">Print</span> </button> <button show-if-allowed="specimenResource.deleteOpts" class="default" ng-click="deleteSpecimen()"> <span class="fa fa-trash"></span> <span translate="common.buttons.delete">Delete</span> </button> <div dropdown os-show-if-menu-items-present class="os-inline-btn"> <button class="btn btn-default dropdown-toggle default"> <span translate="common.buttons.more">More</span> <span class="fa fa-caret-down"></span> </button> <ul class="dropdown-menu dropdown-menu-right"> <li ng-if="!!specimen.imageId"> <os-view-image image-id="specimen.imageId" show-text="true"></os-view-image> </li> <li show-if-allowed="specimenResource.updateOpts" ng-if="!cpViewCtx.isCoordinator && !specimen.reserved && specimen.activityStatus == 'Active' && specimen.status == 'Collected'"> <a ui-sref="specimen-detail.events( {eventId: visit.eventId, visitId: visit.id, specimenId: specimen.id, srId: specimen.reqId})"> <span class="fa fa-calendar-o"></span> <span translate="specimens.ctx_menu.add_event">Add Event</span> </a> </li> <li show-if-allowed="specimenResource.updateOpts" ng-if="!cpViewCtx.isCoordinator && !specimen.reserved && specimen.activityStatus == 'Active' && specimen.status == 'Collected'"> <a ng-click="closeSpecimen()"> <span class="fa fa-remove"></span> <span translate="common.buttons.close">Close</span> </a> </li> <li show-if-allowed="specimenResource.updateOpts" ng-if="!cpViewCtx.isCoordinator && specimen.activityStatus == 'Closed'"> <a ng-click="reopen()"> <span class="fa fa-check"></span> <span translate="specimens.buttons.reopen">Reopen</span> </a> </li> </ul> </div> </span> </div> <div class="right"> <button class="default" os-right-drawer-toggle ng-switch on="spmnCtx.showActivity" ng-click="toggleShowActivity()"> <span ng-switch-when="true" translate="common.buttons.hide_activity">Hide Events</span> <span ng-switch-when="false" translate="common.buttons.show_activity">Show Events</span> </button> </div> </div> <div class="clearfix os-container-wrapper"> <div class="container os-col" style="width: 100%;"> <div ng-switch on="fieldsCtx.hasDict"> <div ng-switch-when="true"> <sde-fields-overview base-fields="fieldsCtx.sysDict" fields="fieldsCtx.cpDict" obj="spmnCtx.obj" in-objs="spmnCtx.inObjs" ex-objs="spmnCtx.exObjs" watcher="spmnCtx.watcher"> </sde-fields-overview> </div> <div ng-switch-default> <div ng-include="'modules/biospecimen/participant/specimen/static-fields.html'"></div> </div> </div> <span show-if-allowed="specimenResource.allReadOpts" style="display: inline-block; width: 100%;"> <os-specimen-tree cp="cp" cpr="cpr" visit="visit" specimens="treeSpecimens" allowed-ops="specimenAllowedOps" reload="reload()" pending-spmns-disp-interval="pendingSpmnsDispInterval"> </os-specimen-tree> </span> </div> <div class="os-col os-no-border" os-right-drawer open-width="34" style="position: static;"> <div ng-if="!!specimen.id"> <os-audit-overview class="os-no-top-margin" object-name="'specimen'" object-id="specimen.id"></os-audit-overview> </div> <div ng-include="'modules/biospecimen/participant/specimen/activities.html'"></div> </div> </div> </div> <script type="text/ng-template" id="modules/biospecimen/participant/specimen/static-fields.html"> <div> <ul class="os-key-values os-two-cols"> <li class="item"> <strong class="key key-sm" translate="specimens.lineage">Lineage</strong> <span class="value value-md">{{specimen.lineage | osNoValue}}</span> </li> <li class="item"> <strong class="key key-sm" translate="specimens.collection_status">Status</strong> <ng-switch on="!specimen.distributionStatus"> <ng-switch ng-switch-when="true" on="specimen.status"> <span ng-switch-when="Collected" class="value value-md os-status-collected">Collected</span> <span ng-switch-when="Missed Collection" class="value value-md os-status-missed">Missed Collection</span> <span ng-switch-when="Not Collected" class="value value-md os-status-missed">Not Collected</span> <span ng-switch-default class="value value-md os-status-pending">Pending</span> </ng-switch> <ng-switch ng-switch-when="false" on="specimen.distributionStatus"> <span ng-switch-when="Distributed"> <span class="value value-md" ng-class="specimen.availableQty > 0 ? 'os-status-part-distributed' : 'os-status-distributed'"> Distributed </span> </span> <span ng-switch-when="Returned" class="value value-md os-status-returned">Returned</span> </ng-switch> </ng-switch> </li> <li class="item" ng-if="barcodingEnabled"> <strong class="key key-sm" translate="specimens.barcode">Barcode</strong> <span class="value value-md">{{specimen.barcode | osNoValue}}</span> </li> <li class="item"> <strong class="key key-sm" translate="specimens.type">Specimen Type</strong> <span class="value value-md"> <span>{{specimen.type | osNoValue}}</span> <span ng-if="specimen.specimenClass">({{specimen.specimenClass}})</span> </span> </li> <li class="item"> <strong class="key key-sm" translate="specimens.anatomic_site">Anatomic Site</strong> <span class="value value-md">{{specimen.anatomicSite | osNoValue}}</span> </li> <li class="item"> <strong class="key key-sm" translate="specimens.laterality">Laterality</strong> <span class="value value-md">{{specimen.laterality | osNoValue}}</span> </li> <li class="item"> <strong class="key key-sm" translate="specimens.initial_qty">Initial Quantity</strong> <os-spmn-measure-val value="specimen.initialQty" specimen="specimen"></os-spmn-measure-val> </li> <li class="item"> <strong class="key key-sm" translate="specimens.available_qty">Available Quantity</strong> <os-spmn-measure-val value="specimen.availableQty" specimen="specimen"></os-spmn-measure-val> </li> <li class="item"> <strong class="key key-sm" translate="specimens.concentration">Concentration</strong> <os-spmn-measure-val value="specimen.concentration" measure="'concentration'" specimen="specimen"> </os-spmn-measure-val> </li> <li class="item" ng-if="!!specimen.parentId"> <strong class="key key-sm" translate="specimens.parent_specimen">Parent Specimen</strong> <span class="value value-md"> <a ui-sref="specimen-detail.overview( {eventId: visit.eventId, visitId: visit.id, specimenId: specimen.parentId, srId: specimen.reqId})"> <span ng-if="!!specimen.parentLabel">{{specimen.parentLabel}}</span> <span ng-if="!specimen.parentLabel" translate="specimens.parent_specimen">Parent Specimen</span> </a> </span> </li> <li class="item"> <strong class="key key-sm" translate="specimens.pathology">Pathology Status</strong> <span class="value value-md">{{specimen.pathology | osNoValue}}</span> </li> <li class="item"> <strong class="key key-sm" translate="specimens.storage_location">Storage Location</strong> <ng-switch on="!!specimen.storageLocation.id && specimen.storageLocation.id != -1"> <span class="value value-md" ng-switch-when="true"> <a ui-sref="container-detail.locations({containerId: specimen.storageLocation.id})"> <os-disp-storage-position position="specimen.storageLocation"></os-disp-storage-position> </a> </span> <span class="value value-md" ng-switch-default translate="specimens.virtually_located"> Virtual </span> </ng-switch> </li> <li class="item"> <strong class="key key-sm" translate="specimens.biohazards">Biohazards</strong> <span class="value value-md">{{specimen.biohazards | osArrayJoin | osNoValue}}</span> </li> <li class="item"> <strong class="key key-sm" translate="specimens.created_on">Created On</strong> <span class="value value-md">{{specimen.createdOn | date: global.dateTimeFmt | osNoValue}}</span> </li> <li class="item" ng-if="specimen.lineage != 'New'"> <strong class="key key-sm" translate="specimens.created_by">Created By</strong> <span class="value value-md">{{specimen.createdBy | osUserDisplayName | osNoValue}}</span> </li> <li class="item"> <strong class="key key-sm" translate="specimens.freeze_thaw_cycles">Freeze/Thaw Cycles</strong> <span class="value value-md">{{specimen.freezeThawCycles | osNoValue}}</span> </li> </ul> <div ng-if="!!specimen.extensionDetail"> <div os-extension-overview ext-object="specimen.extensionDetail" show-column="2"></div> </div> <div class="os-section os-line-section" ng-if="!!specimen.comments"> <strong class="key key-sm"> <span translate="specimens.comments">Comments</span> <span>&nbsp;</span> </strong> <span class="value value-md">{{specimen.comments}}</span> </div> <div ng-include="'modules/biospecimen/participant/specimen/external-ids.html'"></div> <div class="os-section" ng-init="opCollapsed=false" ng-if="specimen.specimensPool.length >= 1"> <button class="os-btn-section-collapse os-btn-transparent" ng-click="opCollapsed=!opCollapsed"> <span ng-if="!opCollapsed" class="fa fa-chevron-circle-down"></span> <span ng-if="opCollapsed" class="fa fa-chevron-circle-right"></span> </button> <h3 class="os-sub-section-title"> <span translate="specimens.pooled_from">Pooled From</span> </h3> <div collapse="opCollapsed"> <span ng-repeat="p in specimen.specimensPool"> <a ui-sref="specimen-detail.overview({cpId: p.cpId, cprId: p.cprId, visitId: p.visitId, specimenId: p.id})"> <span>{{p.label}}{{$last ? '' : ','}}</span> </a> </span> </div> </div> <div class="os-section" ng-init="opCollapsed=false" ng-if="specimen.pooledSpecimens.length >= 1"> <button class="os-btn-section-collapse os-btn-transparent" ng-click="opCollapsed=!opCollapsed"> <span ng-if="!opCollapsed" class="fa fa-chevron-circle-down"></span> <span ng-if="opCollapsed" class="fa fa-chevron-circle-right"></span> </button> <h3 class="os-sub-section-title"> <span translate="specimens.pooled_in">Pooled In</span> </h3> <div collapse="opCollapsed"> <span ng-repeat="p in specimen.pooledSpecimens"> <a ui-sref="specimen-detail.overview({cpId: p.cpId, cprId: p.cprId, visitId: p.visitId, specimenId: p.id})"> <span>{{p.label}}{{$last ? '' : ','}}</span> </a> </span> </div> </div> </div> </script> <script type="text/ng-template" id="modules/biospecimen/participant/specimen/activities.html"> <div> <h3 class="os-sub-section-title" translate="specimens.recent_events"> Recent Activity </h3> <span ng-if="activities.length == 0" translate="common.none">None</span> <ul class="os-activity-list" ng-if="activities.length > 0"> <li class="os-activity" ng-repeat="activity in activities"> <div class="title" ng-switch on="activity.isEditable"> <a ui-sref="specimen-detail.event-overview({recordId: activity.id, formId: activity.formId})"> <ng-include src="'modules/biospecimen/participant/specimen/activity-info.html'"></ng-include> </a> </div> <div class="info"> <span> {{activity.updatedBy | osUserDisplayName}} - {{activity.updateTime | date: global.dateTimeFmt}} </span> </div> </li> </ul> </div> </script> <script type="text/ng-template" id="modules/biospecimen/participant/specimen/activity-info.html"> <span> <span ng-if="!!activity.user && !!activity.time"> {{'specimens.activity_full_info' | translate: activity}} </span> <span ng-if="!!activity.user && !activity.time"> {{'specimens.activity_user_info' | translate: activity}} </span> <span ng-if="!activity.user && !!activity.time"> {{'specimens.activity_time_info' | translate: activity}} </span> <span ng-if="!activity.user && !activity.time"> {{'specimens.activity_info' | translate: activity}} </span> </span> </script> <script type="text/ng-template" id="modules/biospecimen/participant/specimen/confirm-print.html"> <div class="os-modal"> <div class="os-modal-header"> <span translate="specimens.confirm_print">Confirm Print</span> </div> <div class="os-modal-body"> <span translate="specimens.confirm_print_q">Do you want to print child specimen labels as well?</span> </div> <div class="os-modal-footer"> <button class="btn os-btn-text" ng-click="cancel()"> <span translate="common.buttons.discard">Cancel</span> </button> <button class="btn os-btn-secondary" ng-click="printSpecimenLabels(false)"> <span translate="specimens.buttons.print_current">No, only current specimen</span> </button> <button class="btn btn-primary" ng-click="printSpecimenLabels(true)"> <span translate="common.yes">Yes</span> </button> </div> </div> </script> <script type="text/ng-template" id="modules/biospecimen/participant/specimen/external-ids.html"> <div class="os-section" ng-init="extIdsCollapsed=false" ng-if="specimen.externalIds.length > 0"> <button class="os-btn-section-collapse os-btn-transparent" ng-click="extIdsCollapsed=!extIdsCollapsed"> <span class="fa" ng-class="{true: 'fa-chevron-circle-right', false: 'fa-chevron-circle-down'}[extIdsCollapsed]"></span> </button> <h3 class="os-sub-section-title" translate="specimens.external_ids">External IDs</h3> <div collapse="extIdsCollapsed"> <table class="os-table os-table-muted-hdr os-border"> <thead class="os-table-head"> <tr class="row"> <th class="col col-xs-6"> <span translate="common.name">Name</span> </th> <th class="col col-xs-6"> <span translate="common.value">Value</span> </th> </tr> </thead> <tbody class="os-table-body"> <tr class="row" ng-repeat="extId in specimen.externalIds"> <td class="col col-xs-6"> <span>{{extId.name | osNoValue}}</span> </td> <td class="col col-xs-6"> <span>{{extId.value | osNoValue}}</span> </td> </tr> </tbody> </table> </div> </div> </script>
Java
/* Copyright (C) 2009-2010 ProFUSION embedded systems Copyright (C) 2009-2010 Samsung Electronics This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "config.h" #include "ewk_history.h" #include "BackForwardList.h" #include "CairoUtilitiesEfl.h" #include "HistoryItem.h" #include "IconDatabaseBase.h" #include "Image.h" #include "IntSize.h" #include "Page.h" #include "PageGroup.h" #include "ewk_history_private.h" #include "ewk_private.h" #include <Eina.h> #include <eina_safety_checks.h> #include <wtf/text/CString.h> struct _Ewk_History { WebCore::BackForwardList* core; }; #define EWK_HISTORY_CORE_GET_OR_RETURN(history, core_, ...) \ if (!(history)) { \ CRITICAL("history is NULL."); \ return __VA_ARGS__; \ } \ if (!(history)->core) { \ CRITICAL("history->core is NULL."); \ return __VA_ARGS__; \ } \ if (!(history)->core->enabled()) { \ ERR("history->core is disabled!."); \ return __VA_ARGS__; \ } \ WebCore::BackForwardList* core_ = (history)->core struct _Ewk_History_Item { WebCore::HistoryItem* core; const char* title; const char* alternateTitle; const char* uri; const char* originalUri; }; #define EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core_, ...) \ if (!(item)) { \ CRITICAL("item is NULL."); \ return __VA_ARGS__; \ } \ if (!(item)->core) { \ CRITICAL("item->core is NULL."); \ return __VA_ARGS__; \ } \ WebCore::HistoryItem* core_ = (item)->core static inline Eina_List* _ewk_history_item_list_get(const WebCore::HistoryItemVector& coreItems) { Eina_List* result = 0; unsigned int size; size = coreItems.size(); for (unsigned int i = 0; i < size; i++) { Ewk_History_Item* item = ewk_history_item_new_from_core(coreItems[i].get()); if (item) result = eina_list_append(result, item); } return result; } Eina_Bool ewk_history_clear(Ewk_History* history) { EWK_HISTORY_CORE_GET_OR_RETURN(history, core, false); WebCore::Page* page = core->page(); if (page && page->groupPtr()) page->groupPtr()->removeVisitedLinks(); const int limit = ewk_history_limit_get(history); ewk_history_limit_set(history, 0); ewk_history_limit_set(history, limit); return true; } Eina_Bool ewk_history_forward(Ewk_History* history) { EWK_HISTORY_CORE_GET_OR_RETURN(history, core, false); if (core->forwardListCount() < 1) return false; core->goForward(); return true; } Eina_Bool ewk_history_back(Ewk_History* history) { EWK_HISTORY_CORE_GET_OR_RETURN(history, core, false); if (core->backListCount() < 1) return false; core->goBack(); return true; } Eina_Bool ewk_history_history_item_add(Ewk_History* history, const Ewk_History_Item* item) { EWK_HISTORY_CORE_GET_OR_RETURN(history, history_core, false); EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, item_core, false); history_core->addItem(item_core); return true; } Eina_Bool ewk_history_history_item_set(Ewk_History* history, const Ewk_History_Item* item) { EWK_HISTORY_CORE_GET_OR_RETURN(history, history_core, false); EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, item_core, false); history_core->goToItem(item_core); return true; } Ewk_History_Item* ewk_history_history_item_back_get(const Ewk_History* history) { EWK_HISTORY_CORE_GET_OR_RETURN(history, core, 0); return ewk_history_item_new_from_core(core->backItem()); } Ewk_History_Item* ewk_history_history_item_current_get(const Ewk_History* history) { EWK_HISTORY_CORE_GET_OR_RETURN(history, core, 0); WebCore::HistoryItem* currentItem = core->currentItem(); if (currentItem) return ewk_history_item_new_from_core(currentItem); return 0; } Ewk_History_Item* ewk_history_history_item_forward_get(const Ewk_History* history) { EWK_HISTORY_CORE_GET_OR_RETURN(history, core, 0); return ewk_history_item_new_from_core(core->forwardItem()); } Ewk_History_Item* ewk_history_history_item_nth_get(const Ewk_History* history, int index) { EWK_HISTORY_CORE_GET_OR_RETURN(history, core, 0); return ewk_history_item_new_from_core(core->itemAtIndex(index)); } Eina_Bool ewk_history_history_item_contains(const Ewk_History* history, const Ewk_History_Item* item) { EWK_HISTORY_CORE_GET_OR_RETURN(history, history_core, false); EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, item_core, false); return history_core->containsItem(item_core); } Eina_List* ewk_history_forward_list_get(const Ewk_History* history) { EWK_HISTORY_CORE_GET_OR_RETURN(history, core, 0); WebCore::HistoryItemVector items; int limit = core->forwardListCount(); core->forwardListWithLimit(limit, items); return _ewk_history_item_list_get(items); } Eina_List* ewk_history_forward_list_get_with_limit(const Ewk_History* history, int limit) { EWK_HISTORY_CORE_GET_OR_RETURN(history, core, 0); WebCore::HistoryItemVector items; core->forwardListWithLimit(limit, items); return _ewk_history_item_list_get(items); } int ewk_history_forward_list_length(const Ewk_History* history) { EWK_HISTORY_CORE_GET_OR_RETURN(history, core, 0); return core->forwardListCount(); } Eina_List* ewk_history_back_list_get(const Ewk_History* history) { EWK_HISTORY_CORE_GET_OR_RETURN(history, core, 0); WebCore::HistoryItemVector items; int limit = core->backListCount(); core->backListWithLimit(limit, items); return _ewk_history_item_list_get(items); } Eina_List* ewk_history_back_list_get_with_limit(const Ewk_History* history, int limit) { EWK_HISTORY_CORE_GET_OR_RETURN(history, core, 0); WebCore::HistoryItemVector items; core->backListWithLimit(limit, items); return _ewk_history_item_list_get(items); } int ewk_history_back_list_length(const Ewk_History* history) { EWK_HISTORY_CORE_GET_OR_RETURN(history, core, 0); return core->backListCount(); } int ewk_history_limit_get(Ewk_History* history) { EWK_HISTORY_CORE_GET_OR_RETURN(history, core, 0); return core->capacity(); } Eina_Bool ewk_history_limit_set(const Ewk_History* history, int limit) { EWK_HISTORY_CORE_GET_OR_RETURN(history, core, false); core->setCapacity(limit); return true; } Ewk_History_Item* ewk_history_item_new_from_core(WebCore::HistoryItem* core) { Ewk_History_Item* item; if (!core) { ERR("WebCore::HistoryItem is NULL."); return 0; } core->ref(); item = new Ewk_History_Item; memset(item, 0, sizeof(*item)); item->core = core; return item; } Ewk_History_Item* ewk_history_item_new(const char* uri, const char* title) { WTF::String historyUri = WTF::String::fromUTF8(uri); WTF::String historyTitle = WTF::String::fromUTF8(title); WTF::RefPtr<WebCore::HistoryItem> core = WebCore::HistoryItem::create(historyUri, historyTitle, 0); Ewk_History_Item* item = ewk_history_item_new_from_core(core.release().leakRef()); return item; } static inline void _ewk_history_item_free(Ewk_History_Item* item, WebCore::HistoryItem* core) { core->deref(); delete item; } void ewk_history_item_free(Ewk_History_Item* item) { EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core); _ewk_history_item_free(item, core); } void ewk_history_item_list_free(Eina_List* history_items) { void* deleteItem; EINA_LIST_FREE(history_items, deleteItem) { Ewk_History_Item* item = (Ewk_History_Item*)deleteItem; _ewk_history_item_free(item, item->core); } } const char* ewk_history_item_title_get(const Ewk_History_Item* item) { EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core, 0); // hide the following optimzation from outside Ewk_History_Item* historyItem = const_cast<Ewk_History_Item*>(item); eina_stringshare_replace(&historyItem->title, core->title().utf8().data()); return historyItem->title; } const char* ewk_history_item_title_alternate_get(const Ewk_History_Item* item) { EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core, 0); // hide the following optimzation from outside Ewk_History_Item* historyItem = const_cast<Ewk_History_Item*>(item); eina_stringshare_replace(&historyItem->alternateTitle, core->alternateTitle().utf8().data()); return historyItem->alternateTitle; } void ewk_history_item_title_alternate_set(Ewk_History_Item* item, const char* title) { EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core); if (!eina_stringshare_replace(&item->alternateTitle, title)) return; core->setAlternateTitle(WTF::String::fromUTF8(title)); } const char* ewk_history_item_uri_get(const Ewk_History_Item* item) { EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core, 0); // hide the following optimzation from outside Ewk_History_Item* historyItem = const_cast<Ewk_History_Item*>((item)); eina_stringshare_replace(&historyItem->uri, core->urlString().utf8().data()); return historyItem->uri; } const char* ewk_history_item_uri_original_get(const Ewk_History_Item* item) { EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core, 0); // hide the following optimzation from outside Ewk_History_Item* historyItem = const_cast<Ewk_History_Item*>(item); eina_stringshare_replace(&historyItem->originalUri, core->originalURLString().utf8().data()); return historyItem->originalUri; } double ewk_history_item_time_last_visited_get(const Ewk_History_Item* item) { EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core, 0.0); return core->lastVisitedTime(); } cairo_surface_t* ewk_history_item_icon_surface_get(const Ewk_History_Item* item) { EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core, 0); RefPtr<cairo_surface_t> icon = WebCore::iconDatabase().synchronousNativeIconForPageURL(core->url(), WebCore::IntSize(16, 16)); if (!icon) ERR("icon is NULL."); return icon.get(); } Evas_Object* ewk_history_item_icon_object_add(const Ewk_History_Item* item, Evas* canvas) { EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core, 0); EINA_SAFETY_ON_NULL_RETURN_VAL(canvas, 0); RefPtr<cairo_surface_t> surface = WebCore::iconDatabase().synchronousNativeIconForPageURL(core->url(), WebCore::IntSize(16, 16)); if (!surface) { ERR("icon is NULL."); return 0; } return surface ? WebCore::evasObjectFromCairoImageSurface(canvas, surface.get()).leakRef() : 0; } Eina_Bool ewk_history_item_page_cache_exists(const Ewk_History_Item* item) { EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core, false); return core->isInPageCache(); } int ewk_history_item_visit_count(const Ewk_History_Item* item) { EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core, 0); return core->visitCount(); } Eina_Bool ewk_history_item_visit_last_failed(const Ewk_History_Item* item) { EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core, true); return core->lastVisitWasFailure(); } /* internal methods ****************************************************/ /** * @internal * * Creates history for given view. Called internally by ewk_view and * should never be called from outside. * * @param core WebCore::BackForwardList instance to use internally. * * @return newly allocated history instance or @c NULL on errors. */ Ewk_History* ewk_history_new(WebCore::BackForwardList* core) { Ewk_History* history; EINA_SAFETY_ON_NULL_RETURN_VAL(core, 0); DBG("core=%p", core); history = new Ewk_History; history->core = core; core->ref(); return history; } /** * @internal * * Destroys previously allocated history instance. This is called * automatically by ewk_view and should never be called from outside. * * @param history instance to free */ void ewk_history_free(Ewk_History* history) { DBG("history=%p", history); history->core->deref(); delete history; } namespace EWKPrivate { WebCore::HistoryItem* coreHistoryItem(const Ewk_History_Item* ewkHistoryItem) { EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(ewkHistoryItem, core, 0); return core; } } // namespace EWKPrivate
Java
<?php /** * Yasc. * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE. * It is also available through the world-wide-web at this URL: * http://github.com/nebiros/yasc/raw/master/LICENSE * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to mail@jfalvarez.com so we can send you a copy immediately. * * @category Yasc * @package Yasc * @subpackage Yasc_App * @copyright Copyright (c) 2010 - 2014 Juan Felipe Alvarez Sadarriaga. (http://juan.im) * @version $Id$ * @license http://github.com/nebiros/yasc/raw/master/LICENSE New BSD License */ /** * Configuration. * * @package Yasc * @subpackage Yasc_App * @copyright Copyright (c) 2010 - 2014 Juan Felipe Alvarez Sadarriaga. (http://juan.im) * @license http://github.com/nebiros/yasc/raw/master/LICENSE New BSD License * @author nebiros */ class Yasc_App_Config { /** * * @var array */ protected $_options = array(); /** * * @var bool */ protected $_useViewStream = false; /** * Layout. * * @var string */ protected $_layoutScript = null; /** * */ public function __construct() { $this->_addDefaultPaths(); } /** * * @param array $options * @return Yasc_App_Config */ public function setOptions(Array $options) { $this->_options = $options; return $this; } /** * * @return array */ public function getOptions() { return $this->_options; } /** * * @param mixed $key * @param mixed $default * @return mixed|null */ public function getOption($key, $default = null) { if (true === isset($this->_options[$key])) { return $this->_options[$key]; } return $default; } /** * * @param array $options * @return Yasc_App_Config */ public function addOptions(Array $options) { $this->_options = array_merge($this->_options, $options); return $this; } /** * * @param mixed $key * @param mixed $value * @return Yasc_App_Config */ public function addOption($key, $value = null) { $this->_options[$key] = $value; return $this; } /** * * @param bool $flag * @return Yasc_App_Config */ public function setViewStream($flag = false) { $this->_useViewStream = $flag; return $this; } /** * * @return bool */ public function useViewStream() { return $this->_useViewStream; } /** * * @return array */ public function getViewsPaths() { return Yasc_Autoloader_Manager::getInstance()->getPaths( Yasc_Autoloader_Manager::PATH_TYPE_VIEW); } /** * * @param string $path * @return Yasc_App_Config */ public function setViewsPath($path) { Yasc_Autoloader_Manager::getInstance()->addPath( Yasc_Autoloader_Manager::PATH_TYPE_VIEW_HELPER, $path); return $this; } /** * * @param string $path * @return Yasc_App_Config */ public function addViewsPath($path) { Yasc_Autoloader_Manager::getInstance()->addPath( Yasc_Autoloader_Manager::PATH_TYPE_VIEW, $path); return $this; } /** * * @return string */ public function getLayoutScript() { return $this->_layoutScript; } /** * * @param string $layout * @return Yasc_App_Config */ public function setLayoutScript($layout) { if (false === is_string($layout)) { return false; } $layout = realpath($layout); if (false === is_file($layout)) { throw new Yasc_App_Exception("Layout file '{$layout}' not found"); } $this->_layoutScript = $layout; // Cause a layout is a view too, we going to add layout script folder // to the views folders. $this->addViewsPath(dirname($this->_layoutScript)); return $this; } /** * * @return array */ public function getViewHelperPaths() { return Yasc_Autoloader_Manager::getInstance()->getPaths( Yasc_Autoloader_Manager::PATH_TYPE_VIEW_HELPER); } /** * * @param string $classPrefix * @return string */ public function getViewHelpersPath($classPrefix = null) { return Yasc_Autoloader_Manager::getInstance()->getPath( Yasc_Autoloader_Manager::PATH_TYPE_VIEW_HELPER, $classPrefix); } /** * * @param string $path * @param string $classPrefix * @return Yasc_App_Config */ public function setViewHelpersPath($path, $classPrefix = null) { Yasc_Autoloader_Manager::getInstance()->setPath( Yasc_Autoloader_Manager::PATH_TYPE_VIEW_HELPER, $path, $classPrefix); return $this; } /** * * @param string $path * @param string $classPrefix * @return Yasc_App_Config */ public function addViewHelpersPath($path, $classPrefix = null) { Yasc_Autoloader_Manager::getInstance()->addPath( Yasc_Autoloader_Manager::PATH_TYPE_VIEW_HELPER, $path, $classPrefix); return $this; } /** * * @return array */ public function getFunctionHelperPaths() { return Yasc_Autoloader_Manager::getInstance()->getPaths( Yasc_Autoloader_Manager::PATH_TYPE_FUNCTION_HELPER); } /** * * @param string $classPrefix * @return string */ public function getFunctionHelpersPath($classPrefix = null) { return Yasc_Autoloader_Manager::getInstance()->getPath( Yasc_Autoloader_Manager::PATH_TYPE_FUNCTION_HELPER, $classPrefix); } /** * * @param string $path * @param string $classPrefix * @return Yasc_App_Config */ public function setFunctionHelpersPath($path, $classPrefix = null) { Yasc_Autoloader_Manager::getInstance()->setPath( Yasc_Autoloader_Manager::PATH_TYPE_FUNCTION_HELPER, $path, $classPrefix); return $this; } /** * * @param string $path * @param string $classPrefix * @return Yasc_App_Config */ public function addFunctionHelpersPath($path, $classPrefix = null) { Yasc_Autoloader_Manager::getInstance()->addPath( Yasc_Autoloader_Manager::PATH_TYPE_FUNCTION_HELPER, $path, $classPrefix); return $this; } /** * * @return array */ public function getModelPaths() { return Yasc_Autoloader_Manager::getInstance()->getPaths( Yasc_Autoloader_Manager::PATH_TYPE_MODEL); } /** * * @param string $path * @param string $classPrefix * @return Yasc_App_Config */ public function setModelsPath($path, $classPrefix = null) { Yasc_Autoloader_Manager::getInstance()->setPath( Yasc_Autoloader_Manager::PATH_TYPE_MODEL, $path, $classPrefix); return $this; } /** * * @param string $path * @param string $classPrefix * @return Yasc_App_Config */ public function addModelsPath($path, $classPrefix = null) { Yasc_Autoloader_Manager::getInstance()->addPath( Yasc_Autoloader_Manager::PATH_TYPE_MODEL, $path, $classPrefix); return $this; } /** * * @return void */ protected function _addDefaultPaths() { $views = realpath(APPLICATION_PATH . "/views"); $helpers = realpath(APPLICATION_PATH . "/views/helpers"); $models = realpath(APPLICATION_PATH . "/models"); // default paths, if they exist. if (true === is_dir($views)) { Yasc_Autoloader_Manager::getInstance()->addPath( Yasc_Autoloader_Manager::PATH_TYPE_VIEW, $views); } if (true === is_dir($helpers)) { Yasc_Autoloader_Manager::getInstance()->addPath( Yasc_Autoloader_Manager::PATH_TYPE_VIEW_HELPER, $helpers, "Helper"); } if (true === is_dir($models)) { Yasc_Autoloader_Manager::getInstance()->addPath( Yasc_Autoloader_Manager::PATH_TYPE_MODEL, $models, "Model"); } } }
Java
//===-- lib/Evaluate/fold-real.cpp ----------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "fold-implementation.h" namespace Fortran::evaluate { template <int KIND> Expr<Type<TypeCategory::Real, KIND>> FoldIntrinsicFunction( FoldingContext &context, FunctionRef<Type<TypeCategory::Real, KIND>> &&funcRef) { using T = Type<TypeCategory::Real, KIND>; using ComplexT = Type<TypeCategory::Complex, KIND>; ActualArguments &args{funcRef.arguments()}; auto *intrinsic{std::get_if<SpecificIntrinsic>(&funcRef.proc().u)}; CHECK(intrinsic); std::string name{intrinsic->name}; if (name == "acos" || name == "acosh" || name == "asin" || name == "asinh" || (name == "atan" && args.size() == 1) || name == "atanh" || name == "bessel_j0" || name == "bessel_j1" || name == "bessel_y0" || name == "bessel_y1" || name == "cos" || name == "cosh" || name == "erf" || name == "erfc" || name == "erfc_scaled" || name == "exp" || name == "gamma" || name == "log" || name == "log10" || name == "log_gamma" || name == "sin" || name == "sinh" || name == "sqrt" || name == "tan" || name == "tanh") { CHECK(args.size() == 1); if (auto callable{context.hostIntrinsicsLibrary() .GetHostProcedureWrapper<Scalar, T, T>(name)}) { return FoldElementalIntrinsic<T, T>( context, std::move(funcRef), *callable); } else { context.messages().Say( "%s(real(kind=%d)) cannot be folded on host"_en_US, name, KIND); } } else if (name == "atan" || name == "atan2" || name == "hypot" || name == "mod") { std::string localName{name == "atan2" ? "atan" : name}; CHECK(args.size() == 2); if (auto callable{ context.hostIntrinsicsLibrary() .GetHostProcedureWrapper<Scalar, T, T, T>(localName)}) { return FoldElementalIntrinsic<T, T, T>( context, std::move(funcRef), *callable); } else { context.messages().Say( "%s(real(kind=%d), real(kind%d)) cannot be folded on host"_en_US, name, KIND, KIND); } } else if (name == "bessel_jn" || name == "bessel_yn") { if (args.size() == 2) { // elemental // runtime functions use int arg using Int4 = Type<TypeCategory::Integer, 4>; if (auto callable{ context.hostIntrinsicsLibrary() .GetHostProcedureWrapper<Scalar, T, Int4, T>(name)}) { return FoldElementalIntrinsic<T, Int4, T>( context, std::move(funcRef), *callable); } else { context.messages().Say( "%s(integer(kind=4), real(kind=%d)) cannot be folded on host"_en_US, name, KIND); } } } else if (name == "abs") { // Argument can be complex or real if (auto *x{UnwrapExpr<Expr<SomeReal>>(args[0])}) { return FoldElementalIntrinsic<T, T>( context, std::move(funcRef), &Scalar<T>::ABS); } else if (auto *z{UnwrapExpr<Expr<SomeComplex>>(args[0])}) { if (auto callable{ context.hostIntrinsicsLibrary() .GetHostProcedureWrapper<Scalar, T, ComplexT>("abs")}) { return FoldElementalIntrinsic<T, ComplexT>( context, std::move(funcRef), *callable); } else { context.messages().Say( "abs(complex(kind=%d)) cannot be folded on host"_en_US, KIND); } } else { common::die(" unexpected argument type inside abs"); } } else if (name == "aimag") { return FoldElementalIntrinsic<T, ComplexT>( context, std::move(funcRef), &Scalar<ComplexT>::AIMAG); } else if (name == "aint" || name == "anint") { // ANINT rounds ties away from zero, not to even common::RoundingMode mode{name == "aint" ? common::RoundingMode::ToZero : common::RoundingMode::TiesAwayFromZero}; return FoldElementalIntrinsic<T, T>(context, std::move(funcRef), ScalarFunc<T, T>([&name, &context, mode]( const Scalar<T> &x) -> Scalar<T> { ValueWithRealFlags<Scalar<T>> y{x.ToWholeNumber(mode)}; if (y.flags.test(RealFlag::Overflow)) { context.messages().Say("%s intrinsic folding overflow"_en_US, name); } return y.value; })); } else if (name == "dprod") { if (auto scalars{GetScalarConstantArguments<T, T>(context, args)}) { return Fold(context, Expr<T>{Multiply<T>{ Expr<T>{std::get<0>(*scalars)}, Expr<T>{std::get<1>(*scalars)}}}); } } else if (name == "epsilon") { return Expr<T>{Scalar<T>::EPSILON()}; } else if (name == "huge") { return Expr<T>{Scalar<T>::HUGE()}; } else if (name == "max") { return FoldMINorMAX(context, std::move(funcRef), Ordering::Greater); } else if (name == "merge") { return FoldMerge<T>(context, std::move(funcRef)); } else if (name == "min") { return FoldMINorMAX(context, std::move(funcRef), Ordering::Less); } else if (name == "real") { if (auto *expr{args[0].value().UnwrapExpr()}) { return ToReal<KIND>(context, std::move(*expr)); } } else if (name == "sign") { return FoldElementalIntrinsic<T, T, T>( context, std::move(funcRef), &Scalar<T>::SIGN); } else if (name == "tiny") { return Expr<T>{Scalar<T>::TINY()}; } // TODO: cshift, dim, dot_product, eoshift, fraction, matmul, // maxval, minval, modulo, nearest, norm2, pack, product, // reduce, rrspacing, scale, set_exponent, spacing, spread, // sum, transfer, transpose, unpack, bessel_jn (transformational) and // bessel_yn (transformational) return Expr<T>{std::move(funcRef)}; } template <int KIND> Expr<Type<TypeCategory::Real, KIND>> FoldOperation( FoldingContext &context, ComplexComponent<KIND> &&x) { using Operand = Type<TypeCategory::Complex, KIND>; using Result = Type<TypeCategory::Real, KIND>; if (auto array{ApplyElementwise(context, x, std::function<Expr<Result>(Expr<Operand> &&)>{ [=](Expr<Operand> &&operand) { return Expr<Result>{ComplexComponent<KIND>{ x.isImaginaryPart, std::move(operand)}}; }})}) { return *array; } using Part = Type<TypeCategory::Real, KIND>; auto &operand{x.left()}; if (auto value{GetScalarConstantValue<Operand>(operand)}) { if (x.isImaginaryPart) { return Expr<Part>{Constant<Part>{value->AIMAG()}}; } else { return Expr<Part>{Constant<Part>{value->REAL()}}; } } return Expr<Part>{std::move(x)}; } FOR_EACH_REAL_KIND(template class ExpressionBase, ) template class ExpressionBase<SomeReal>; } // namespace Fortran::evaluate
Java
<?php namespace app\models; use Yii; use yii\base\Model; /** * LoginForm is the model behind the login form. */ class LoginForm extends Model { public $login; public $password; public $rememberMe = true; private $_user = false; /** * @return array the validation rules. */ public function rules() { return [ [['login', 'password'], 'required'], ['login', 'exist', 'targetClass' => '\app\models\UserModel', 'message' => Yii::t('app', 'A specified login does not exist')], ['rememberMe', 'boolean'], ['password', 'validatePassword'], ]; } /** * Validates the password. * This method serves as the inline validation for password. * * @param string $attribute the attribute currently being validated * @param array $params the additional name-value pairs given in the rule */ public function validatePassword($attribute, $params) { if (!$this->hasErrors()) { $user = $this->getUser(); if (!$user || !$user->validatePassword($this->password)) { $this->addError($attribute, Yii::t('app', 'Incorrect password')); } } } /** * Logs in a user using the provided username and password. * @return boolean whether the user is logged in successfully */ public function login() { if ($this->validate()) { return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0); } return false; } /** * Finds user by [[username]] * * @return User|null */ public function getUser() { if ($this->_user === false) { $this->_user = UserModel::findByLogin($this->login); } return $this->_user; } }
Java
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Test.h" #if SK_SUPPORT_GPU #include "GrReducedClip.h" #endif #include "SkClipStack.h" #include "SkPath.h" #include "SkRandom.h" #include "SkRect.h" #include "SkRegion.h" static void test_assign_and_comparison(skiatest::Reporter* reporter) { SkClipStack s; bool doAA = false; REPORTER_ASSERT(reporter, 0 == s.getSaveCount()); // Build up a clip stack with a path, an empty clip, and a rect. s.save(); REPORTER_ASSERT(reporter, 1 == s.getSaveCount()); SkPath p; p.moveTo(5, 6); p.lineTo(7, 8); p.lineTo(5, 9); p.close(); s.clipDevPath(p, SkRegion::kIntersect_Op, doAA); s.save(); REPORTER_ASSERT(reporter, 2 == s.getSaveCount()); SkRect r = SkRect::MakeLTRB(1, 2, 3, 4); s.clipDevRect(r, SkRegion::kIntersect_Op, doAA); r = SkRect::MakeLTRB(10, 11, 12, 13); s.clipDevRect(r, SkRegion::kIntersect_Op, doAA); s.save(); REPORTER_ASSERT(reporter, 3 == s.getSaveCount()); r = SkRect::MakeLTRB(14, 15, 16, 17); s.clipDevRect(r, SkRegion::kUnion_Op, doAA); // Test that assignment works. SkClipStack copy = s; REPORTER_ASSERT(reporter, s == copy); // Test that different save levels triggers not equal. s.restore(); REPORTER_ASSERT(reporter, 2 == s.getSaveCount()); REPORTER_ASSERT(reporter, s != copy); // Test that an equal, but not copied version is equal. s.save(); REPORTER_ASSERT(reporter, 3 == s.getSaveCount()); r = SkRect::MakeLTRB(14, 15, 16, 17); s.clipDevRect(r, SkRegion::kUnion_Op, doAA); REPORTER_ASSERT(reporter, s == copy); // Test that a different op on one level triggers not equal. s.restore(); REPORTER_ASSERT(reporter, 2 == s.getSaveCount()); s.save(); REPORTER_ASSERT(reporter, 3 == s.getSaveCount()); r = SkRect::MakeLTRB(14, 15, 16, 17); s.clipDevRect(r, SkRegion::kIntersect_Op, doAA); REPORTER_ASSERT(reporter, s != copy); // Test that different state (clip type) triggers not equal. // NO LONGER VALID: if a path contains only a rect, we turn // it into a bare rect for performance reasons (working // around Chromium/JavaScript bad pattern). /* s.restore(); s.save(); SkPath rp; rp.addRect(r); s.clipDevPath(rp, SkRegion::kUnion_Op, doAA); REPORTER_ASSERT(reporter, s != copy); */ // Test that different rects triggers not equal. s.restore(); REPORTER_ASSERT(reporter, 2 == s.getSaveCount()); s.save(); REPORTER_ASSERT(reporter, 3 == s.getSaveCount()); r = SkRect::MakeLTRB(24, 25, 26, 27); s.clipDevRect(r, SkRegion::kUnion_Op, doAA); REPORTER_ASSERT(reporter, s != copy); // Sanity check s.restore(); REPORTER_ASSERT(reporter, 2 == s.getSaveCount()); copy.restore(); REPORTER_ASSERT(reporter, 2 == copy.getSaveCount()); REPORTER_ASSERT(reporter, s == copy); s.restore(); REPORTER_ASSERT(reporter, 1 == s.getSaveCount()); copy.restore(); REPORTER_ASSERT(reporter, 1 == copy.getSaveCount()); REPORTER_ASSERT(reporter, s == copy); // Test that different paths triggers not equal. s.restore(); REPORTER_ASSERT(reporter, 0 == s.getSaveCount()); s.save(); REPORTER_ASSERT(reporter, 1 == s.getSaveCount()); p.addRect(r); s.clipDevPath(p, SkRegion::kIntersect_Op, doAA); REPORTER_ASSERT(reporter, s != copy); } static void assert_count(skiatest::Reporter* reporter, const SkClipStack& stack, int count) { SkClipStack::B2TIter iter(stack); int counter = 0; while (iter.next()) { counter += 1; } REPORTER_ASSERT(reporter, count == counter); } // Exercise the SkClipStack's bottom to top and bidirectional iterators // (including the skipToTopmost functionality) static void test_iterators(skiatest::Reporter* reporter) { SkClipStack stack; static const SkRect gRects[] = { { 0, 0, 40, 40 }, { 60, 0, 100, 40 }, { 0, 60, 40, 100 }, { 60, 60, 100, 100 } }; for (size_t i = 0; i < SK_ARRAY_COUNT(gRects); i++) { // the union op will prevent these from being fused together stack.clipDevRect(gRects[i], SkRegion::kUnion_Op, false); } assert_count(reporter, stack, 4); // bottom to top iteration { const SkClipStack::Element* element = NULL; SkClipStack::B2TIter iter(stack); int i; for (i = 0, element = iter.next(); element; ++i, element = iter.next()) { REPORTER_ASSERT(reporter, SkClipStack::Element::kRect_Type == element->getType()); REPORTER_ASSERT(reporter, element->getRect() == gRects[i]); } SkASSERT(i == 4); } // top to bottom iteration { const SkClipStack::Element* element = NULL; SkClipStack::Iter iter(stack, SkClipStack::Iter::kTop_IterStart); int i; for (i = 3, element = iter.prev(); element; --i, element = iter.prev()) { REPORTER_ASSERT(reporter, SkClipStack::Element::kRect_Type == element->getType()); REPORTER_ASSERT(reporter, element->getRect() == gRects[i]); } SkASSERT(i == -1); } // skipToTopmost { const SkClipStack::Element* element = NULL; SkClipStack::Iter iter(stack, SkClipStack::Iter::kBottom_IterStart); element = iter.skipToTopmost(SkRegion::kUnion_Op); REPORTER_ASSERT(reporter, SkClipStack::Element::kRect_Type == element->getType()); REPORTER_ASSERT(reporter, element->getRect() == gRects[3]); } } // Exercise the SkClipStack's getConservativeBounds computation static void test_bounds(skiatest::Reporter* reporter, bool useRects) { static const int gNumCases = 20; static const SkRect gAnswerRectsBW[gNumCases] = { // A op B { 40, 40, 50, 50 }, { 10, 10, 50, 50 }, { 10, 10, 80, 80 }, { 10, 10, 80, 80 }, { 40, 40, 80, 80 }, // invA op B { 40, 40, 80, 80 }, { 0, 0, 100, 100 }, { 0, 0, 100, 100 }, { 0, 0, 100, 100 }, { 40, 40, 50, 50 }, // A op invB { 10, 10, 50, 50 }, { 40, 40, 50, 50 }, { 0, 0, 100, 100 }, { 0, 0, 100, 100 }, { 0, 0, 100, 100 }, // invA op invB { 0, 0, 100, 100 }, { 40, 40, 80, 80 }, { 0, 0, 100, 100 }, { 10, 10, 80, 80 }, { 10, 10, 50, 50 }, }; static const SkRegion::Op gOps[] = { SkRegion::kIntersect_Op, SkRegion::kDifference_Op, SkRegion::kUnion_Op, SkRegion::kXOR_Op, SkRegion::kReverseDifference_Op }; SkRect rectA, rectB; rectA.iset(10, 10, 50, 50); rectB.iset(40, 40, 80, 80); SkPath clipA, clipB; clipA.addRoundRect(rectA, SkIntToScalar(5), SkIntToScalar(5)); clipB.addRoundRect(rectB, SkIntToScalar(5), SkIntToScalar(5)); SkClipStack stack; SkRect devClipBound; bool isIntersectionOfRects = false; int testCase = 0; int numBitTests = useRects ? 1 : 4; for (int invBits = 0; invBits < numBitTests; ++invBits) { for (size_t op = 0; op < SK_ARRAY_COUNT(gOps); ++op) { stack.save(); bool doInvA = SkToBool(invBits & 1); bool doInvB = SkToBool(invBits & 2); clipA.setFillType(doInvA ? SkPath::kInverseEvenOdd_FillType : SkPath::kEvenOdd_FillType); clipB.setFillType(doInvB ? SkPath::kInverseEvenOdd_FillType : SkPath::kEvenOdd_FillType); if (useRects) { stack.clipDevRect(rectA, SkRegion::kIntersect_Op, false); stack.clipDevRect(rectB, gOps[op], false); } else { stack.clipDevPath(clipA, SkRegion::kIntersect_Op, false); stack.clipDevPath(clipB, gOps[op], false); } REPORTER_ASSERT(reporter, !stack.isWideOpen()); REPORTER_ASSERT(reporter, SkClipStack::kWideOpenGenID != stack.getTopmostGenID()); stack.getConservativeBounds(0, 0, 100, 100, &devClipBound, &isIntersectionOfRects); if (useRects) { REPORTER_ASSERT(reporter, isIntersectionOfRects == (gOps[op] == SkRegion::kIntersect_Op)); } else { REPORTER_ASSERT(reporter, !isIntersectionOfRects); } SkASSERT(testCase < gNumCases); REPORTER_ASSERT(reporter, devClipBound == gAnswerRectsBW[testCase]); ++testCase; stack.restore(); } } } // Test out 'isWideOpen' entry point static void test_isWideOpen(skiatest::Reporter* reporter) { { // Empty stack is wide open. Wide open stack means that gen id is wide open. SkClipStack stack; REPORTER_ASSERT(reporter, stack.isWideOpen()); REPORTER_ASSERT(reporter, SkClipStack::kWideOpenGenID == stack.getTopmostGenID()); } SkRect rectA, rectB; rectA.iset(10, 10, 40, 40); rectB.iset(50, 50, 80, 80); // Stack should initially be wide open { SkClipStack stack; REPORTER_ASSERT(reporter, stack.isWideOpen()); REPORTER_ASSERT(reporter, SkClipStack::kWideOpenGenID == stack.getTopmostGenID()); } // Test out case where the user specifies a union that includes everything { SkClipStack stack; SkPath clipA, clipB; clipA.addRoundRect(rectA, SkIntToScalar(5), SkIntToScalar(5)); clipA.setFillType(SkPath::kInverseEvenOdd_FillType); clipB.addRoundRect(rectB, SkIntToScalar(5), SkIntToScalar(5)); clipB.setFillType(SkPath::kInverseEvenOdd_FillType); stack.clipDevPath(clipA, SkRegion::kReplace_Op, false); stack.clipDevPath(clipB, SkRegion::kUnion_Op, false); REPORTER_ASSERT(reporter, stack.isWideOpen()); REPORTER_ASSERT(reporter, SkClipStack::kWideOpenGenID == stack.getTopmostGenID()); } // Test out union w/ a wide open clip { SkClipStack stack; stack.clipDevRect(rectA, SkRegion::kUnion_Op, false); REPORTER_ASSERT(reporter, stack.isWideOpen()); REPORTER_ASSERT(reporter, SkClipStack::kWideOpenGenID == stack.getTopmostGenID()); } // Test out empty difference from a wide open clip { SkClipStack stack; SkRect emptyRect; emptyRect.setEmpty(); stack.clipDevRect(emptyRect, SkRegion::kDifference_Op, false); REPORTER_ASSERT(reporter, stack.isWideOpen()); REPORTER_ASSERT(reporter, SkClipStack::kWideOpenGenID == stack.getTopmostGenID()); } // Test out return to wide open { SkClipStack stack; stack.save(); stack.clipDevRect(rectA, SkRegion::kReplace_Op, false); REPORTER_ASSERT(reporter, !stack.isWideOpen()); REPORTER_ASSERT(reporter, SkClipStack::kWideOpenGenID != stack.getTopmostGenID()); stack.restore(); REPORTER_ASSERT(reporter, stack.isWideOpen()); REPORTER_ASSERT(reporter, SkClipStack::kWideOpenGenID == stack.getTopmostGenID()); } } static int count(const SkClipStack& stack) { SkClipStack::Iter iter(stack, SkClipStack::Iter::kTop_IterStart); const SkClipStack::Element* element = NULL; int count = 0; for (element = iter.prev(); element; element = iter.prev(), ++count) { ; } return count; } static void test_rect_inverse_fill(skiatest::Reporter* reporter) { // non-intersecting rectangles SkRect rect = SkRect::MakeLTRB(0, 0, 10, 10); SkPath path; path.addRect(rect); path.toggleInverseFillType(); SkClipStack stack; stack.clipDevPath(path, SkRegion::kIntersect_Op, false); SkRect bounds; SkClipStack::BoundsType boundsType; stack.getBounds(&bounds, &boundsType); REPORTER_ASSERT(reporter, SkClipStack::kInsideOut_BoundsType == boundsType); REPORTER_ASSERT(reporter, bounds == rect); } static void test_rect_replace(skiatest::Reporter* reporter) { SkRect rect = SkRect::MakeWH(100, 100); SkRect rect2 = SkRect::MakeXYWH(50, 50, 100, 100); SkRect bound; SkClipStack::BoundsType type; bool isIntersectionOfRects; // Adding a new rect with the replace operator should not increase // the stack depth. BW replacing BW. { SkClipStack stack; REPORTER_ASSERT(reporter, 0 == count(stack)); stack.clipDevRect(rect, SkRegion::kReplace_Op, false); REPORTER_ASSERT(reporter, 1 == count(stack)); stack.clipDevRect(rect, SkRegion::kReplace_Op, false); REPORTER_ASSERT(reporter, 1 == count(stack)); } // Adding a new rect with the replace operator should not increase // the stack depth. AA replacing AA. { SkClipStack stack; REPORTER_ASSERT(reporter, 0 == count(stack)); stack.clipDevRect(rect, SkRegion::kReplace_Op, true); REPORTER_ASSERT(reporter, 1 == count(stack)); stack.clipDevRect(rect, SkRegion::kReplace_Op, true); REPORTER_ASSERT(reporter, 1 == count(stack)); } // Adding a new rect with the replace operator should not increase // the stack depth. BW replacing AA replacing BW. { SkClipStack stack; REPORTER_ASSERT(reporter, 0 == count(stack)); stack.clipDevRect(rect, SkRegion::kReplace_Op, false); REPORTER_ASSERT(reporter, 1 == count(stack)); stack.clipDevRect(rect, SkRegion::kReplace_Op, true); REPORTER_ASSERT(reporter, 1 == count(stack)); stack.clipDevRect(rect, SkRegion::kReplace_Op, false); REPORTER_ASSERT(reporter, 1 == count(stack)); } // Make sure replace clip rects don't collapse too much. { SkClipStack stack; stack.clipDevRect(rect, SkRegion::kReplace_Op, false); stack.clipDevRect(rect2, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, 1 == count(stack)); stack.save(); stack.clipDevRect(rect, SkRegion::kReplace_Op, false); REPORTER_ASSERT(reporter, 2 == count(stack)); stack.getBounds(&bound, &type, &isIntersectionOfRects); REPORTER_ASSERT(reporter, bound == rect); stack.restore(); REPORTER_ASSERT(reporter, 1 == count(stack)); stack.save(); stack.clipDevRect(rect, SkRegion::kReplace_Op, false); stack.clipDevRect(rect, SkRegion::kReplace_Op, false); REPORTER_ASSERT(reporter, 2 == count(stack)); stack.restore(); REPORTER_ASSERT(reporter, 1 == count(stack)); stack.save(); stack.clipDevRect(rect, SkRegion::kReplace_Op, false); stack.clipDevRect(rect2, SkRegion::kIntersect_Op, false); stack.clipDevRect(rect, SkRegion::kReplace_Op, false); REPORTER_ASSERT(reporter, 2 == count(stack)); stack.restore(); REPORTER_ASSERT(reporter, 1 == count(stack)); } } // Simplified path-based version of test_rect_replace. static void test_path_replace(skiatest::Reporter* reporter) { SkRect rect = SkRect::MakeWH(100, 100); SkPath path; path.addCircle(50, 50, 50); // Replace operation doesn't grow the stack. { SkClipStack stack; REPORTER_ASSERT(reporter, 0 == count(stack)); stack.clipDevPath(path, SkRegion::kReplace_Op, false); REPORTER_ASSERT(reporter, 1 == count(stack)); stack.clipDevPath(path, SkRegion::kReplace_Op, false); REPORTER_ASSERT(reporter, 1 == count(stack)); } // Replacing rect with path. { SkClipStack stack; stack.clipDevRect(rect, SkRegion::kReplace_Op, true); REPORTER_ASSERT(reporter, 1 == count(stack)); stack.clipDevPath(path, SkRegion::kReplace_Op, true); REPORTER_ASSERT(reporter, 1 == count(stack)); } } // Test out SkClipStack's merging of rect clips. In particular exercise // merging of aa vs. bw rects. static void test_rect_merging(skiatest::Reporter* reporter) { SkRect overlapLeft = SkRect::MakeLTRB(10, 10, 50, 50); SkRect overlapRight = SkRect::MakeLTRB(40, 40, 80, 80); SkRect nestedParent = SkRect::MakeLTRB(10, 10, 90, 90); SkRect nestedChild = SkRect::MakeLTRB(40, 40, 60, 60); SkRect bound; SkClipStack::BoundsType type; bool isIntersectionOfRects; // all bw overlapping - should merge { SkClipStack stack; stack.clipDevRect(overlapLeft, SkRegion::kReplace_Op, false); stack.clipDevRect(overlapRight, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, 1 == count(stack)); stack.getBounds(&bound, &type, &isIntersectionOfRects); REPORTER_ASSERT(reporter, isIntersectionOfRects); } // all aa overlapping - should merge { SkClipStack stack; stack.clipDevRect(overlapLeft, SkRegion::kReplace_Op, true); stack.clipDevRect(overlapRight, SkRegion::kIntersect_Op, true); REPORTER_ASSERT(reporter, 1 == count(stack)); stack.getBounds(&bound, &type, &isIntersectionOfRects); REPORTER_ASSERT(reporter, isIntersectionOfRects); } // mixed overlapping - should _not_ merge { SkClipStack stack; stack.clipDevRect(overlapLeft, SkRegion::kReplace_Op, true); stack.clipDevRect(overlapRight, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, 2 == count(stack)); stack.getBounds(&bound, &type, &isIntersectionOfRects); REPORTER_ASSERT(reporter, !isIntersectionOfRects); } // mixed nested (bw inside aa) - should merge { SkClipStack stack; stack.clipDevRect(nestedParent, SkRegion::kReplace_Op, true); stack.clipDevRect(nestedChild, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, 1 == count(stack)); stack.getBounds(&bound, &type, &isIntersectionOfRects); REPORTER_ASSERT(reporter, isIntersectionOfRects); } // mixed nested (aa inside bw) - should merge { SkClipStack stack; stack.clipDevRect(nestedParent, SkRegion::kReplace_Op, false); stack.clipDevRect(nestedChild, SkRegion::kIntersect_Op, true); REPORTER_ASSERT(reporter, 1 == count(stack)); stack.getBounds(&bound, &type, &isIntersectionOfRects); REPORTER_ASSERT(reporter, isIntersectionOfRects); } // reverse nested (aa inside bw) - should _not_ merge { SkClipStack stack; stack.clipDevRect(nestedChild, SkRegion::kReplace_Op, false); stack.clipDevRect(nestedParent, SkRegion::kIntersect_Op, true); REPORTER_ASSERT(reporter, 2 == count(stack)); stack.getBounds(&bound, &type, &isIntersectionOfRects); REPORTER_ASSERT(reporter, !isIntersectionOfRects); } } static void test_quickContains(skiatest::Reporter* reporter) { SkRect testRect = SkRect::MakeLTRB(10, 10, 40, 40); SkRect insideRect = SkRect::MakeLTRB(20, 20, 30, 30); SkRect intersectingRect = SkRect::MakeLTRB(25, 25, 50, 50); SkRect outsideRect = SkRect::MakeLTRB(0, 0, 50, 50); SkRect nonIntersectingRect = SkRect::MakeLTRB(100, 100, 110, 110); SkPath insideCircle; insideCircle.addCircle(25, 25, 5); SkPath intersectingCircle; intersectingCircle.addCircle(25, 40, 10); SkPath outsideCircle; outsideCircle.addCircle(25, 25, 50); SkPath nonIntersectingCircle; nonIntersectingCircle.addCircle(100, 100, 5); { SkClipStack stack; stack.clipDevRect(outsideRect, SkRegion::kDifference_Op, false); // return false because quickContains currently does not care for kDifference_Op REPORTER_ASSERT(reporter, false == stack.quickContains(testRect)); } // Replace Op tests { SkClipStack stack; stack.clipDevRect(outsideRect, SkRegion::kReplace_Op, false); REPORTER_ASSERT(reporter, true == stack.quickContains(testRect)); } { SkClipStack stack; stack.clipDevRect(insideRect, SkRegion::kIntersect_Op, false); stack.save(); // To prevent in-place substitution by replace OP stack.clipDevRect(outsideRect, SkRegion::kReplace_Op, false); REPORTER_ASSERT(reporter, true == stack.quickContains(testRect)); stack.restore(); } { SkClipStack stack; stack.clipDevRect(outsideRect, SkRegion::kIntersect_Op, false); stack.save(); // To prevent in-place substitution by replace OP stack.clipDevRect(insideRect, SkRegion::kReplace_Op, false); REPORTER_ASSERT(reporter, false == stack.quickContains(testRect)); stack.restore(); } // Verify proper traversal of multi-element clip { SkClipStack stack; stack.clipDevRect(insideRect, SkRegion::kIntersect_Op, false); // Use a path for second clip to prevent in-place intersection stack.clipDevPath(outsideCircle, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, false == stack.quickContains(testRect)); } // Intersect Op tests with rectangles { SkClipStack stack; stack.clipDevRect(outsideRect, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, true == stack.quickContains(testRect)); } { SkClipStack stack; stack.clipDevRect(insideRect, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, false == stack.quickContains(testRect)); } { SkClipStack stack; stack.clipDevRect(intersectingRect, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, false == stack.quickContains(testRect)); } { SkClipStack stack; stack.clipDevRect(nonIntersectingRect, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, false == stack.quickContains(testRect)); } // Intersect Op tests with circle paths { SkClipStack stack; stack.clipDevPath(outsideCircle, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, true == stack.quickContains(testRect)); } { SkClipStack stack; stack.clipDevPath(insideCircle, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, false == stack.quickContains(testRect)); } { SkClipStack stack; stack.clipDevPath(intersectingCircle, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, false == stack.quickContains(testRect)); } { SkClipStack stack; stack.clipDevPath(nonIntersectingCircle, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, false == stack.quickContains(testRect)); } // Intersect Op tests with inverse filled rectangles { SkClipStack stack; SkPath path; path.addRect(outsideRect); path.toggleInverseFillType(); stack.clipDevPath(path, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, false == stack.quickContains(testRect)); } { SkClipStack stack; SkPath path; path.addRect(insideRect); path.toggleInverseFillType(); stack.clipDevPath(path, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, false == stack.quickContains(testRect)); } { SkClipStack stack; SkPath path; path.addRect(intersectingRect); path.toggleInverseFillType(); stack.clipDevPath(path, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, false == stack.quickContains(testRect)); } { SkClipStack stack; SkPath path; path.addRect(nonIntersectingRect); path.toggleInverseFillType(); stack.clipDevPath(path, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, true == stack.quickContains(testRect)); } // Intersect Op tests with inverse filled circles { SkClipStack stack; SkPath path = outsideCircle; path.toggleInverseFillType(); stack.clipDevPath(path, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, false == stack.quickContains(testRect)); } { SkClipStack stack; SkPath path = insideCircle; path.toggleInverseFillType(); stack.clipDevPath(path, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, false == stack.quickContains(testRect)); } { SkClipStack stack; SkPath path = intersectingCircle; path.toggleInverseFillType(); stack.clipDevPath(path, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, false == stack.quickContains(testRect)); } { SkClipStack stack; SkPath path = nonIntersectingCircle; path.toggleInverseFillType(); stack.clipDevPath(path, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, true == stack.quickContains(testRect)); } } /////////////////////////////////////////////////////////////////////////////////////////////////// #if SK_SUPPORT_GPU // Functions that add a shape to the clip stack. The shape is computed from a rectangle. // AA is always disabled since the clip stack reducer can cause changes in aa rasterization of the // stack. A fractional edge repeated in different elements may be rasterized fewer times using the // reduced stack. typedef void (*AddElementFunc) (const SkRect& rect, bool invert, SkRegion::Op op, SkClipStack* stack); static void add_round_rect(const SkRect& rect, bool invert, SkRegion::Op op, SkClipStack* stack) { SkPath path; SkScalar rx = rect.width() / 10; SkScalar ry = rect.height() / 20; path.addRoundRect(rect, rx, ry); if (invert) { path.setFillType(SkPath::kInverseWinding_FillType); } stack->clipDevPath(path, op, false); }; static void add_rect(const SkRect& rect, bool invert, SkRegion::Op op, SkClipStack* stack) { if (invert) { SkPath path; path.addRect(rect); path.setFillType(SkPath::kInverseWinding_FillType); stack->clipDevPath(path, op, false); } else { stack->clipDevRect(rect, op, false); } }; static void add_oval(const SkRect& rect, bool invert, SkRegion::Op op, SkClipStack* stack) { SkPath path; path.addOval(rect); if (invert) { path.setFillType(SkPath::kInverseWinding_FillType); } stack->clipDevPath(path, op, false); }; static void add_elem_to_stack(const SkClipStack::Element& element, SkClipStack* stack) { switch (element.getType()) { case SkClipStack::Element::kRect_Type: stack->clipDevRect(element.getRect(), element.getOp(), element.isAA()); break; case SkClipStack::Element::kPath_Type: stack->clipDevPath(element.getPath(), element.getOp(), element.isAA()); break; case SkClipStack::Element::kEmpty_Type: SkDEBUGFAIL("Why did the reducer produce an explicit empty."); stack->clipEmpty(); break; } } static void add_elem_to_region(const SkClipStack::Element& element, const SkIRect& bounds, SkRegion* region) { SkRegion elemRegion; SkRegion boundsRgn(bounds); switch (element.getType()) { case SkClipStack::Element::kRect_Type: { SkPath path; path.addRect(element.getRect()); elemRegion.setPath(path, boundsRgn); break; } case SkClipStack::Element::kPath_Type: elemRegion.setPath(element.getPath(), boundsRgn); break; case SkClipStack::Element::kEmpty_Type: // region->setEmpty(); return; } region->op(elemRegion, element.getOp()); } static void test_reduced_clip_stack(skiatest::Reporter* reporter) { // We construct random clip stacks, reduce them, and then rasterize both versions to verify that // they are equal. // All the clip elements will be contained within these bounds. static const SkRect kBounds = SkRect::MakeWH(100, 100); enum { kNumTests = 200, kMinElemsPerTest = 1, kMaxElemsPerTest = 50, }; // min/max size of a clip element as a fraction of kBounds. static const SkScalar kMinElemSizeFrac = SK_Scalar1 / 5; static const SkScalar kMaxElemSizeFrac = SK_Scalar1; static const SkRegion::Op kOps[] = { SkRegion::kDifference_Op, SkRegion::kIntersect_Op, SkRegion::kUnion_Op, SkRegion::kXOR_Op, SkRegion::kReverseDifference_Op, SkRegion::kReplace_Op, }; // Replace operations short-circuit the optimizer. We want to make sure that we test this code // path a little bit but we don't want it to prevent us from testing many longer traversals in // the optimizer. static const int kReplaceDiv = 4 * kMaxElemsPerTest; // We want to test inverse fills. However, they are quite rare in practice so don't over do it. static const SkScalar kFractionInverted = SK_Scalar1 / kMaxElemsPerTest; static const AddElementFunc kElementFuncs[] = { add_rect, add_round_rect, add_oval, }; SkRandom r; for (int i = 0; i < kNumTests; ++i) { // Randomly generate a clip stack. SkClipStack stack; int numElems = r.nextRangeU(kMinElemsPerTest, kMaxElemsPerTest); for (int e = 0; e < numElems; ++e) { SkRegion::Op op = kOps[r.nextULessThan(SK_ARRAY_COUNT(kOps))]; if (op == SkRegion::kReplace_Op) { if (r.nextU() % kReplaceDiv) { --e; continue; } } // saves can change the clip stack behavior when an element is added. bool doSave = r.nextBool(); SkSize size = SkSize::Make( SkScalarFloorToScalar(SkScalarMul(kBounds.width(), r.nextRangeScalar(kMinElemSizeFrac, kMaxElemSizeFrac))), SkScalarFloorToScalar(SkScalarMul(kBounds.height(), r.nextRangeScalar(kMinElemSizeFrac, kMaxElemSizeFrac)))); SkPoint xy = {SkScalarFloorToScalar(r.nextRangeScalar(kBounds.fLeft, kBounds.fRight - size.fWidth)), SkScalarFloorToScalar(r.nextRangeScalar(kBounds.fTop, kBounds.fBottom - size.fHeight))}; SkRect rect = SkRect::MakeXYWH(xy.fX, xy.fY, size.fWidth, size.fHeight); bool invert = r.nextBiasedBool(kFractionInverted); kElementFuncs[r.nextULessThan(SK_ARRAY_COUNT(kElementFuncs))](rect, invert, op, &stack); if (doSave) { stack.save(); } } SkRect inflatedBounds = kBounds; inflatedBounds.outset(kBounds.width() / 2, kBounds.height() / 2); SkIRect inflatedIBounds; inflatedBounds.roundOut(&inflatedIBounds); typedef GrReducedClip::ElementList ElementList; // Get the reduced version of the stack. ElementList reducedClips; int32_t reducedGenID; GrReducedClip::InitialState initial; SkIRect tBounds(inflatedIBounds); SkIRect* tightBounds = r.nextBool() ? &tBounds : NULL; GrReducedClip::ReduceClipStack(stack, inflatedIBounds, &reducedClips, &reducedGenID, &initial, tightBounds); REPORTER_ASSERT(reporter, SkClipStack::kInvalidGenID != reducedGenID); // Build a new clip stack based on the reduced clip elements SkClipStack reducedStack; if (GrReducedClip::kAllOut_InitialState == initial) { // whether the result is bounded or not, the whole plane should start outside the clip. reducedStack.clipEmpty(); } for (ElementList::Iter iter = reducedClips.headIter(); NULL != iter.get(); iter.next()) { add_elem_to_stack(*iter.get(), &reducedStack); } // GrReducedClipStack assumes that the final result is clipped to the returned bounds if (NULL != tightBounds) { reducedStack.clipDevRect(*tightBounds, SkRegion::kIntersect_Op); } // convert both the original stack and reduced stack to SkRegions and see if they're equal SkRegion region; SkRegion reducedRegion; region.setRect(inflatedIBounds); const SkClipStack::Element* element; SkClipStack::Iter iter(stack, SkClipStack::Iter::kBottom_IterStart); while ((element = iter.next())) { add_elem_to_region(*element, inflatedIBounds, &region); } reducedRegion.setRect(inflatedIBounds); iter.reset(reducedStack, SkClipStack::Iter::kBottom_IterStart); while ((element = iter.next())) { add_elem_to_region(*element, inflatedIBounds, &reducedRegion); } REPORTER_ASSERT(reporter, region == reducedRegion); } } #if defined(WIN32) #define SUPPRESS_VISIBILITY_WARNING #else #define SUPPRESS_VISIBILITY_WARNING __attribute__((visibility("hidden"))) #endif static void test_reduced_clip_stack_genid(skiatest::Reporter* reporter) { { SkClipStack stack; stack.clipDevRect(SkRect::MakeXYWH(0, 0, 100, 100), SkRegion::kReplace_Op, true); stack.clipDevRect(SkRect::MakeXYWH(0, 0, SkScalar(50.3), SkScalar(50.3)), SkRegion::kReplace_Op, true); SkIRect inflatedIBounds = SkIRect::MakeXYWH(0, 0, 100, 100); GrReducedClip::ElementList reducedClips; int32_t reducedGenID; GrReducedClip::InitialState initial; SkIRect tightBounds; GrReducedClip::ReduceClipStack(stack, inflatedIBounds, &reducedClips, &reducedGenID, &initial, &tightBounds); REPORTER_ASSERT(reporter, reducedClips.count() == 1); // Clips will be cached based on the generation id. Make sure the gen id is valid. REPORTER_ASSERT(reporter, SkClipStack::kInvalidGenID != reducedGenID); } { SkClipStack stack; // Create a clip with following 25.3, 25.3 boxes which are 25 apart: // A B // C D stack.clipDevRect(SkRect::MakeXYWH(0, 0, SkScalar(25.3), SkScalar(25.3)), SkRegion::kReplace_Op, true); int32_t genIDA = stack.getTopmostGenID(); stack.clipDevRect(SkRect::MakeXYWH(50, 0, SkScalar(25.3), SkScalar(25.3)), SkRegion::kUnion_Op, true); int32_t genIDB = stack.getTopmostGenID(); stack.clipDevRect(SkRect::MakeXYWH(0, 50, SkScalar(25.3), SkScalar(25.3)), SkRegion::kUnion_Op, true); int32_t genIDC = stack.getTopmostGenID(); stack.clipDevRect(SkRect::MakeXYWH(50, 50, SkScalar(25.3), SkScalar(25.3)), SkRegion::kUnion_Op, true); int32_t genIDD = stack.getTopmostGenID(); #define XYWH SkIRect::MakeXYWH SkIRect unused; unused.setEmpty(); SkIRect stackBounds = XYWH(0, 0, 76, 76); // The base test is to test each rect in two ways: // 1) The box dimensions. (Should reduce to "all in", no elements). // 2) A bit over the box dimensions. // In the case 2, test that the generation id is what is expected. // The rects are of fractional size so that case 2 never gets optimized to an empty element // list. // Not passing in tighter bounds is tested for consistency. static const struct SUPPRESS_VISIBILITY_WARNING { SkIRect testBounds; int reducedClipCount; int32_t reducedGenID; GrReducedClip::InitialState initialState; SkIRect tighterBounds; // If this is empty, the query will not pass tighter bounds // parameter. } testCases[] = { // Rect A. { XYWH(0, 0, 25, 25), 0, SkClipStack::kWideOpenGenID, GrReducedClip::kAllIn_InitialState, XYWH(0, 0, 25, 25) }, { XYWH(0, 0, 25, 25), 0, SkClipStack::kWideOpenGenID, GrReducedClip::kAllIn_InitialState, unused }, { XYWH(0, 0, 27, 27), 1, genIDA, GrReducedClip::kAllOut_InitialState, XYWH(0, 0, 27, 27)}, { XYWH(0, 0, 27, 27), 1, genIDA, GrReducedClip::kAllOut_InitialState, unused }, // Rect B. { XYWH(50, 0, 25, 25), 0, SkClipStack::kWideOpenGenID, GrReducedClip::kAllIn_InitialState, XYWH(50, 0, 25, 25) }, { XYWH(50, 0, 25, 25), 0, SkClipStack::kWideOpenGenID, GrReducedClip::kAllIn_InitialState, unused }, { XYWH(50, 0, 27, 27), 1, genIDB, GrReducedClip::kAllOut_InitialState, XYWH(50, 0, 26, 27) }, { XYWH(50, 0, 27, 27), 1, genIDB, GrReducedClip::kAllOut_InitialState, unused }, // Rect C. { XYWH(0, 50, 25, 25), 0, SkClipStack::kWideOpenGenID, GrReducedClip::kAllIn_InitialState, XYWH(0, 50, 25, 25) }, { XYWH(0, 50, 25, 25), 0, SkClipStack::kWideOpenGenID, GrReducedClip::kAllIn_InitialState, unused }, { XYWH(0, 50, 27, 27), 1, genIDC, GrReducedClip::kAllOut_InitialState, XYWH(0, 50, 27, 26) }, { XYWH(0, 50, 27, 27), 1, genIDC, GrReducedClip::kAllOut_InitialState, unused }, // Rect D. { XYWH(50, 50, 25, 25), 0, SkClipStack::kWideOpenGenID, GrReducedClip::kAllIn_InitialState, unused }, { XYWH(50, 50, 25, 25), 0, SkClipStack::kWideOpenGenID, GrReducedClip::kAllIn_InitialState, XYWH(50, 50, 25, 25)}, { XYWH(50, 50, 27, 27), 1, genIDD, GrReducedClip::kAllOut_InitialState, unused }, { XYWH(50, 50, 27, 27), 1, genIDD, GrReducedClip::kAllOut_InitialState, XYWH(50, 50, 26, 26)}, // Other tests: { XYWH(0, 0, 100, 100), 4, genIDD, GrReducedClip::kAllOut_InitialState, unused }, { XYWH(0, 0, 100, 100), 4, genIDD, GrReducedClip::kAllOut_InitialState, stackBounds }, // Rect in the middle, touches none. { XYWH(26, 26, 24, 24), 0, SkClipStack::kEmptyGenID, GrReducedClip::kAllOut_InitialState, unused }, { XYWH(26, 26, 24, 24), 0, SkClipStack::kEmptyGenID, GrReducedClip::kAllOut_InitialState, XYWH(26, 26, 24, 24) }, // Rect in the middle, touches all the rects. GenID is the last rect. { XYWH(24, 24, 27, 27), 4, genIDD, GrReducedClip::kAllOut_InitialState, unused }, { XYWH(24, 24, 27, 27), 4, genIDD, GrReducedClip::kAllOut_InitialState, XYWH(24, 24, 27, 27) }, }; #undef XYWH for (size_t i = 0; i < SK_ARRAY_COUNT(testCases); ++i) { GrReducedClip::ElementList reducedClips; int32_t reducedGenID; GrReducedClip::InitialState initial; SkIRect tightBounds; GrReducedClip::ReduceClipStack(stack, testCases[i].testBounds, &reducedClips, &reducedGenID, &initial, testCases[i].tighterBounds.isEmpty() ? NULL : &tightBounds); REPORTER_ASSERT(reporter, reducedClips.count() == testCases[i].reducedClipCount); SkASSERT(reducedClips.count() == testCases[i].reducedClipCount); REPORTER_ASSERT(reporter, reducedGenID == testCases[i].reducedGenID); SkASSERT(reducedGenID == testCases[i].reducedGenID); REPORTER_ASSERT(reporter, initial == testCases[i].initialState); SkASSERT(initial == testCases[i].initialState); if (!testCases[i].tighterBounds.isEmpty()) { REPORTER_ASSERT(reporter, tightBounds == testCases[i].tighterBounds); SkASSERT(tightBounds == testCases[i].tighterBounds); } } } } static void test_reduced_clip_stack_no_aa_crash(skiatest::Reporter* reporter) { SkClipStack stack; stack.clipDevRect(SkIRect::MakeXYWH(0, 0, 100, 100), SkRegion::kReplace_Op); stack.clipDevRect(SkIRect::MakeXYWH(0, 0, 50, 50), SkRegion::kReplace_Op); SkIRect inflatedIBounds = SkIRect::MakeXYWH(0, 0, 100, 100); GrReducedClip::ElementList reducedClips; int32_t reducedGenID; GrReducedClip::InitialState initial; SkIRect tightBounds; // At the time, this would crash. GrReducedClip::ReduceClipStack(stack, inflatedIBounds, &reducedClips, &reducedGenID, &initial, &tightBounds); REPORTER_ASSERT(reporter, 0 == reducedClips.count()); } #endif DEF_TEST(ClipStack, reporter) { SkClipStack stack; REPORTER_ASSERT(reporter, 0 == stack.getSaveCount()); assert_count(reporter, stack, 0); static const SkIRect gRects[] = { { 0, 0, 100, 100 }, { 25, 25, 125, 125 }, { 0, 0, 1000, 1000 }, { 0, 0, 75, 75 } }; for (size_t i = 0; i < SK_ARRAY_COUNT(gRects); i++) { stack.clipDevRect(gRects[i], SkRegion::kIntersect_Op); } // all of the above rects should have been intersected, leaving only 1 rect SkClipStack::B2TIter iter(stack); const SkClipStack::Element* element = iter.next(); SkRect answer; answer.iset(25, 25, 75, 75); REPORTER_ASSERT(reporter, NULL != element); REPORTER_ASSERT(reporter, SkClipStack::Element::kRect_Type == element->getType()); REPORTER_ASSERT(reporter, SkRegion::kIntersect_Op == element->getOp()); REPORTER_ASSERT(reporter, element->getRect() == answer); // now check that we only had one in our iterator REPORTER_ASSERT(reporter, !iter.next()); stack.reset(); REPORTER_ASSERT(reporter, 0 == stack.getSaveCount()); assert_count(reporter, stack, 0); test_assign_and_comparison(reporter); test_iterators(reporter); test_bounds(reporter, true); // once with rects test_bounds(reporter, false); // once with paths test_isWideOpen(reporter); test_rect_merging(reporter); test_rect_replace(reporter); test_rect_inverse_fill(reporter); test_path_replace(reporter); test_quickContains(reporter); #if SK_SUPPORT_GPU test_reduced_clip_stack(reporter); test_reduced_clip_stack_genid(reporter); test_reduced_clip_stack_no_aa_crash(reporter); #endif }
Java
<?php namespace app\models; use Yii; use app\models\general\GeneralLabel; use app\models\general\GeneralMessage; /** * This is the model class for table "tbl_six_step". * * @property integer $six_step_id * @property integer $atlet_id * @property string $stage * @property string $status */ class SixStepBiomekanik extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'tbl_six_step_biomekanik'; } public function behaviors() { return [ 'bedezign\yii2\audit\AuditTrailBehavior', [ 'class' => \yii\behaviors\BlameableBehavior::className(), 'createdByAttribute' => 'created_by', 'updatedByAttribute' => 'updated_by', ], [ 'class' => \yii\behaviors\TimestampBehavior::className(), 'createdAtAttribute' => 'created', 'updatedAtAttribute' => 'updated', 'value' => new \yii\db\Expression('NOW()'), ], ]; } /** * @inheritdoc */ public function rules() { return [ [['atlet_id', 'stage', 'status', 'tarikh'], 'required', 'skipOnEmpty' => true, 'message' => GeneralMessage::yii_validation_required], [['atlet_id', 'kategori_atlet', 'sukan', 'acara'], 'integer', 'message' => GeneralMessage::yii_validation_integer], [['stage', 'status'], 'string', 'max' => 30, 'tooLong' => GeneralMessage::yii_validation_string_max], [['stage', 'status'], function ($attribute, $params) { if (!\common\models\general\GeneralFunction::validateXSS($this->$attribute)) { $this->addError($attribute, GeneralMessage::yii_validation_xss); } }], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'six_step_id' => GeneralLabel::six_step_id, 'atlet_id' => GeneralLabel::atlet_id, 'kategori_atlet' => GeneralLabel::kategori_atlet, 'sukan' => GeneralLabel::sukan, 'acara' => GeneralLabel::acara, 'stage' => GeneralLabel::stage, 'status' => GeneralLabel::status, 'tarikh' => GeneralLabel::tarikh, ]; } /** * @return \yii\db\ActiveQuery */ public function getAtlet(){ return $this->hasOne(Atlet::className(), ['atlet_id' => 'atlet_id']); } /** * @return \yii\db\ActiveQuery */ public function getRefSixstepBiomekanikStage(){ return $this->hasOne(RefSixstepBiomekanikStage::className(), ['id' => 'stage']); } /** * @return \yii\db\ActiveQuery */ public function getRefSixstepBiomekanikStatus(){ return $this->hasOne(RefSixstepBiomekanikStatus::className(), ['id' => 'status']); } }
Java
# ---------------------------------------------------------------------------- # Copyright (c) 2016-2021, QIIME 2 development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ---------------------------------------------------------------------------- from qiime2.plugin import SemanticType from ..plugin_setup import plugin from . import AlphaDiversityDirectoryFormat SampleData = SemanticType('SampleData', field_names='type') AlphaDiversity = SemanticType('AlphaDiversity', variant_of=SampleData.field['type']) plugin.register_semantic_types(SampleData, AlphaDiversity) plugin.register_semantic_type_to_format( SampleData[AlphaDiversity], artifact_format=AlphaDiversityDirectoryFormat )
Java
using System; using System.Data; using System.Data.SqlClient; using System.IO; using System.Xml.Serialization; using JetBat.Client.Entities; using JetBat.Client.Metadata.Abstract; using JetBat.Client.Metadata.Definitions; using JetBat.Client.Metadata.Misc; using JetBat.Client.Metadata.Simple; namespace JetBat.Client.SqlServer.Concrete { public class PlainObjectListViewDefinitionSqlLoader : IObjectDefinitionSqlLoader { private const int PlainObjectListViewObjectTypeID = 2; private readonly string _connectionString; private readonly bool _enableCaching; public PlainObjectListViewDefinitionSqlLoader(string connectionString, bool enableCaching) { _connectionString = connectionString; _enableCaching = enableCaching; } #region IObjectDefinitionSqlLoader Members public Type TargetObjectType { get { return typeof(PlainObjectListViewDefinition); } } public int TargetObjectID { get { return PlainObjectListViewObjectTypeID; } } public ObjectDefinition LoadImmutable(string objectNamespace, string objectName) { return new PlainObjectListViewDefinition((PlainObjectListView)Load(objectNamespace, objectName)); } #endregion public BusinessObject Load(string objectNamespace, string objectName) { #region Load from cache string cacheDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, StaticHelper.MetadataCacheDirectoryName + @"\PlainObjectListView"); string cacheFileName = string.Format(@"{0}\{1}.{2}.xml", cacheDirectory, objectNamespace, objectName); if (_enableCaching) { if (File.Exists(cacheFileName)) { XmlSerializer serializer = new XmlSerializer(typeof(PlainObjectListView)); using (FileStream stream = new FileStream(cacheFileName, FileMode.Open, FileAccess.Read)) return (PlainObjectListView)serializer.Deserialize(stream); } } #endregion string uiListCaption; string basicObjectNamespace; string basicObjectName; string objectActionNameLoadList; string objectMethodNameLoadList; string namespaceName; string name; int objectType; string friendlyName; string description; NamedObjectCollection<ObjectAttribute> attributes; NamedObjectCollection<ObjectComplexAttribute> complexAttributes; NamedObjectCollection<ObjectAction> actions; NamedObjectCollection<ObjectMethod> methods; using (SqlConnection sqlConnection = new SqlConnection(_connectionString)) { sqlConnection.Open(); SqlCommand command = new SqlCommand("MetadataEngine_LoadPlainObjectListViewDescriptor", sqlConnection) { CommandType = CommandType.StoredProcedure }; command.Parameters.AddWithValue("@Namespace", objectNamespace); command.Parameters.AddWithValue("@Name", objectName); SqlDataReader reader = command.ExecuteReader(); if (reader == null) throw new NullReferenceException("DataReader is null while must not be."); using (reader) { reader.Read(); uiListCaption = reader["UIListCaption"].ToString(); basicObjectNamespace = Convert.ToString(reader["EntityNamespaceName"]); basicObjectName = Convert.ToString(reader["EntityName"]); objectActionNameLoadList = reader["ObjectActionNameLoadList"].Equals(DBNull.Value) ? "" : Convert.ToString(reader["ObjectActionNameLoadList"]); objectMethodNameLoadList = reader["ObjectMethodNameLoadList"].Equals(DBNull.Value) ? "" : Convert.ToString(reader["ObjectMethodNameLoadList"]); objectType = Convert.ToInt32(reader["ObjectTypeID"]); namespaceName = Convert.ToString(reader["NamespaceName"]); name = Convert.ToString(reader["Name"]); friendlyName = Convert.ToString(reader["FriendlyName"]); description = Convert.ToString(reader["Description"]); reader.NextResult(); attributes = StaticHelper.getAttributesFormReader(reader); reader.NextResult(); complexAttributes = StaticHelper.getComplexAttributesFromReader(reader); reader.NextResult(); StaticHelper.getComplexAttributeAttributePairsFromReader(reader, complexAttributes); reader.NextResult(); actions = StaticHelper.getActionsFormReader(reader); reader.NextResult(); methods = StaticHelper.getMethodsFromReader(reader); reader.NextResult(); StaticHelper.getMethodParametersFromReader(reader, methods); } } BusinessObject definition = new PlainObjectListView { UIListCaption = uiListCaption, BasicObjectNamespace = basicObjectNamespace, BasicObjectName = basicObjectName, ObjectActionNameLoadList = objectActionNameLoadList, ObjectMethodNameLoadList = objectMethodNameLoadList, ObjectNamespace = namespaceName, ObjectName = name, ObjectType = objectType, FriendlyName = friendlyName, Description = description, Attributes = attributes, ComplexAttributes = complexAttributes, Actions = actions, Methods = methods }; #region Save to cache if (_enableCaching) { if (!Directory.Exists(cacheDirectory)) Directory.CreateDirectory(cacheDirectory); XmlSerializer serializer = new XmlSerializer(typeof(PlainObjectListView)); using (FileStream stream = new FileStream(cacheFileName, FileMode.OpenOrCreate, FileAccess.Write)) serializer.Serialize(stream, definition); } #endregion return definition; } } }
Java
from ..base import BaseTopazTest class TestMarshal(BaseTopazTest): def test_version_constants(self, space): w_res = space.execute("return Marshal::MAJOR_VERSION") assert space.int_w(w_res) == 4 w_res = space.execute("return Marshal::MINOR_VERSION") assert space.int_w(w_res) == 8 w_res = space.execute("return Marshal.dump('test')[0].ord") assert space.int_w(w_res) == 4 w_res = space.execute("return Marshal.dump('test')[1].ord") assert space.int_w(w_res) == 8 def test_dump_constants(self, space): w_res = space.execute("return Marshal.dump(nil)") assert space.str_w(w_res) == "\x04\b0" w_res = space.execute("return Marshal.dump(true)") assert space.str_w(w_res) == "\x04\bT" w_res = space.execute("return Marshal.dump(false)") assert space.str_w(w_res) == "\x04\bF" def test_load_constants(self, space): w_res = space.execute("return Marshal.load('\x04\b0')") assert w_res == space.w_nil w_res = space.execute("return Marshal.load('\x04\bT')") assert w_res == space.w_true w_res = space.execute("return Marshal.load('\x04\bF')") assert w_res == space.w_false def test_constants(self, space): w_res = space.execute("return Marshal.load(Marshal.dump(nil))") assert w_res == space.w_nil w_res = space.execute("return Marshal.load(Marshal.dump(true))") assert w_res == space.w_true w_res = space.execute("return Marshal.load(Marshal.dump(false))") assert w_res == space.w_false def test_dump_tiny_integer(self, space): w_res = space.execute("return Marshal.dump(5)") assert space.str_w(w_res) == "\x04\bi\n" w_res = space.execute("return Marshal.dump(100)") assert space.str_w(w_res) == "\x04\bii" w_res = space.execute("return Marshal.dump(0)") assert space.str_w(w_res) == "\x04\bi\x00" w_res = space.execute("return Marshal.dump(-1)") assert space.str_w(w_res) == "\x04\bi\xFA" w_res = space.execute("return Marshal.dump(-123)") assert space.str_w(w_res) == "\x04\bi\x80" w_res = space.execute("return Marshal.dump(122)") assert space.str_w(w_res) == "\x04\bi\x7F" def test_load_tiny_integer(self, space): w_res = space.execute("return Marshal.load('\x04\bi\n')") assert space.int_w(w_res) == 5 w_res = space.execute("return Marshal.load('\x04\bii')") assert space.int_w(w_res) == 100 #w_res = space.execute('return Marshal.load("\x04\bi\x00")') w_res = space.execute('return Marshal.load(Marshal.dump(0))') assert space.int_w(w_res) == 0 w_res = space.execute("return Marshal.load('\x04\bi\xFA')") assert space.int_w(w_res) == -1 w_res = space.execute("return Marshal.load('\x04\bi\x80')") assert space.int_w(w_res) == -123 w_res = space.execute("return Marshal.load('\x04\bi\x7F')") assert space.int_w(w_res) == 122 def test_dump_array(self, space): w_res = space.execute("return Marshal.dump([])") assert space.str_w(w_res) == "\x04\b[\x00" w_res = space.execute("return Marshal.dump([nil])") assert space.str_w(w_res) == "\x04\b[\x060" w_res = space.execute("return Marshal.dump([nil, true, false])") assert space.str_w(w_res) == "\x04\b[\b0TF" w_res = space.execute("return Marshal.dump([1, 2, 3])") assert space.str_w(w_res) == "\x04\b[\x08i\x06i\x07i\x08" w_res = space.execute("return Marshal.dump([1, [2, 3], 4])") assert space.str_w(w_res) == "\x04\b[\bi\x06[\ai\ai\bi\t" w_res = space.execute("return Marshal.dump([:foo, :bar])") assert space.str_w(w_res) == "\x04\b[\a:\bfoo:\bbar" def test_load_array(self, space): #w_res = space.execute("return Marshal.load('\x04\b[\x00')") w_res = space.execute("return Marshal.load(Marshal.dump([]))") assert self.unwrap(space, w_res) == [] w_res = space.execute("return Marshal.load('\x04\b[\x060')") assert self.unwrap(space, w_res) == [None] w_res = space.execute("return Marshal.load('\x04\b[\b0TF')") assert self.unwrap(space, w_res) == [None, True, False] w_res = space.execute("return Marshal.load('\x04\b[\x08i\x06i\x07i\x08')") assert self.unwrap(space, w_res) == [1, 2, 3] w_res = space.execute("return Marshal.load('\x04\b[\bi\x06[\ai\ai\bi\t')") assert self.unwrap(space, w_res) == [1, [2, 3], 4] w_res = space.execute("return Marshal.load('\x04\b[\a:\bfoo:\bbar')") assert self.unwrap(space, w_res) == ["foo", "bar"] def test_dump_symbol(self, space): w_res = space.execute("return Marshal.dump(:abc)") assert space.str_w(w_res) == "\x04\b:\babc" w_res = space.execute("return Marshal.dump(('hello' * 25).to_sym)") assert space.str_w(w_res) == "\x04\b:\x01}" + "hello" * 25 w_res = space.execute("return Marshal.dump(('hello' * 100).to_sym)") assert space.str_w(w_res) == "\x04\b:\x02\xF4\x01" + "hello" * 100 def test_load_symbol(self, space): w_res = space.execute("return Marshal.load('\x04\b:\babc')") assert space.symbol_w(w_res) == "abc" w_res = space.execute("return Marshal.load('\x04\b:\x01}' + 'hello' * 25)") assert space.symbol_w(w_res) == "hello" * 25 def test_dump_hash(self, space): w_res = space.execute("return Marshal.dump({})") assert space.str_w(w_res) == "\x04\b{\x00" w_res = space.execute("return Marshal.dump({1 => 2, 3 => 4})") assert self.unwrap(space, w_res) == "\x04\b{\ai\x06i\ai\bi\t" w_res = space.execute("return Marshal.dump({1 => {2 => 3}, 4 => 5})") assert self.unwrap(space, w_res) == "\x04\b{\ai\x06{\x06i\ai\bi\ti\n" w_res = space.execute("return Marshal.dump({1234 => {23456 => 3456789}, 4 => 5})") assert self.unwrap(space, w_res) == "\x04\b{\ai\x02\xD2\x04{\x06i\x02\xA0[i\x03\x15\xBF4i\ti\n" def test_load_hash(self, space): #w_res = space.execute("return Marshal.load('\x04\b{\x00')") w_res = space.execute("return Marshal.load(Marshal.dump({}))") assert self.unwrap(space, w_res) == {} w_res = space.execute("return Marshal.load('\x04\b{\ai\x06i\ai\bi\t')") assert self.unwrap(space, w_res) == {1: 2, 3: 4} w_res = space.execute("return Marshal.load('\x04\b{\ai\x06{\x06i\ai\bi\ti\n')") assert self.unwrap(space, w_res) == {1: {2: 3}, 4: 5} w_res = space.execute("return Marshal.load('\x04\b{\ai\x02\xD2\x04{\x06i\x02\xA0[i\x03\x15\xBF4i\ti\n')") assert self.unwrap(space, w_res) == {1234: {23456: 3456789}, 4: 5} def test_dump_integer(self, space): w_res = space.execute("return Marshal.dump(123)") assert space.str_w(w_res) == "\x04\bi\x01{" w_res = space.execute("return Marshal.dump(255)") assert space.str_w(w_res) == "\x04\bi\x01\xFF" w_res = space.execute("return Marshal.dump(256)") assert space.str_w(w_res) == "\x04\bi\x02\x00\x01" w_res = space.execute("return Marshal.dump(2 ** 16 - 2)") assert space.str_w(w_res) == "\x04\bi\x02\xFE\xFF" w_res = space.execute("return Marshal.dump(2 ** 16 - 1)") assert space.str_w(w_res) == "\x04\bi\x02\xFF\xFF" w_res = space.execute("return Marshal.dump(2 ** 16)") assert space.str_w(w_res) == "\x04\bi\x03\x00\x00\x01" w_res = space.execute("return Marshal.dump(2 ** 16 + 1)") assert space.str_w(w_res) == "\x04\bi\x03\x01\x00\x01" w_res = space.execute("return Marshal.dump(2 ** 30 - 1)") assert space.str_w(w_res) == "\x04\bi\x04\xFF\xFF\xFF?" # TODO: test tooo big numbers (they give a warning and inf) def test_load_integer(self, space): w_res = space.execute("return Marshal.load('\x04\bi\x01{')") assert space.int_w(w_res) == 123 w_res = space.execute("return Marshal.load('\x04\bi\x01\xFF')") assert space.int_w(w_res) == 255 #w_res = space.execute("return Marshal.load('\x04\bi\x02\x00\x01')") w_res = space.execute("return Marshal.load(Marshal.dump(256))") assert space.int_w(w_res) == 256 w_res = space.execute("return Marshal.load('\x04\bi\x02\xFE\xFF')") assert space.int_w(w_res) == 2 ** 16 - 2 w_res = space.execute("return Marshal.load('\x04\bi\x02\xFF\xFF')") assert space.int_w(w_res) == 2 ** 16 - 1 #w_res = space.execute("return Marshal.load('\x04\bi\x03\x00\x00\x01')") w_res = space.execute("return Marshal.load(Marshal.dump(2 ** 16))") assert space.int_w(w_res) == 2 ** 16 #w_res = space.execute("return Marshal.load('\x04\bi\x03\x01\x00\x01')") w_res = space.execute("return Marshal.load(Marshal.dump(2 ** 16 + 1))") assert space.int_w(w_res) == 2 ** 16 + 1 w_res = space.execute("return Marshal.load('\x04\bi\x04\xFF\xFF\xFF?')") assert space.int_w(w_res) == 2 ** 30 - 1 def test_dump_negative_integer(self, space): w_res = space.execute("return Marshal.dump(-1)") assert space.str_w(w_res) == "\x04\bi\xFA" w_res = space.execute("return Marshal.dump(-123)") assert space.str_w(w_res) == "\x04\bi\x80" w_res = space.execute("return Marshal.dump(-124)") assert space.str_w(w_res) == "\x04\bi\xFF\x84" w_res = space.execute("return Marshal.dump(-256)") assert space.str_w(w_res) == "\x04\bi\xFF\x00" w_res = space.execute("return Marshal.dump(-257)") assert space.str_w(w_res) == "\x04\bi\xFE\xFF\xFE" w_res = space.execute("return Marshal.dump(-(2 ** 30))") assert space.str_w(w_res) == "\x04\bi\xFC\x00\x00\x00\xC0" def test_load_negative_integer(self, space): w_res = space.execute("return Marshal.load('\x04\bi\xFA')") assert space.int_w(w_res) == -1 w_res = space.execute("return Marshal.load('\x04\bi\x80')") assert space.int_w(w_res) == -123 w_res = space.execute("return Marshal.load('\x04\bi\xFF\x84')") assert space.int_w(w_res) == -124 #w_res = space.execute("return Marshal.load('\x04\bi\xFF\x00')") w_res = space.execute("return Marshal.load(Marshal.dump(-256))") assert space.int_w(w_res) == -256 w_res = space.execute("return Marshal.load('\x04\bi\xFE\xFF\xFE')") assert space.int_w(w_res) == -257 #w_res = space.execute("return Marshal.load('\x04\bi\xFE\x00\x00')") w_res = space.execute("return Marshal.load(Marshal.dump(-(2 ** 16)))") assert space.int_w(w_res) == -(2 ** 16) w_res = space.execute("return Marshal.load('\x04\bi\xFD\xFF\xFF\xFE')") assert space.int_w(w_res) == -(2 ** 16 + 1) #w_res = space.execute("return Marshal.load('\x04\bi\xFC\x00\x00\x00')") w_res = space.execute("return Marshal.load(Marshal.dump(-(2 ** 24)))") assert space.int_w(w_res) == -(2 ** 24) w_res = space.execute("return Marshal.load('\x04\bi\xFC\xFF\xFF\xFF\xFE')") assert space.int_w(w_res) == -(2 ** 24 + 1) #w_res = space.execute("return Marshal.load('\x04\bi\xFC\x00\x00\x00\xC0')") w_res = space.execute("return Marshal.load(Marshal.dump(-(2 ** 30)))") assert space.int_w(w_res) == -(2 ** 30) def test_dump_float(self, space): w_res = space.execute("return Marshal.dump(0.0)") assert space.str_w(w_res) == "\x04\bf\x060" w_res = space.execute("return Marshal.dump(0.1)") assert space.str_w(w_res) == "\x04\bf\b0.1" w_res = space.execute("return Marshal.dump(1.0)") assert space.str_w(w_res) == "\x04\bf\x061" w_res = space.execute("return Marshal.dump(1.1)") assert space.str_w(w_res) == "\x04\bf\b1.1" w_res = space.execute("return Marshal.dump(1.001)") assert space.str_w(w_res) == "\x04\bf\n1.001" #w_res = space.execute("return Marshal.dump(123456789.123456789)") #assert space.str_w(w_res) == "\x04\bf\x17123456789.12345679" #w_res = space.execute("return Marshal.dump(-123456789.123456789)") #assert space.str_w(w_res) == "\x04\bf\x18-123456789.12345679" #w_res = space.execute("return Marshal.dump(-0.0)") #assert space.str_w(w_res) == "\x04\bf\a-0" def test_load_float(self, space): w_res = space.execute("return Marshal.load('\x04\bf\x060')") assert space.float_w(w_res) == 0.0 w_res = space.execute("return Marshal.load('\x04\bf\b0.1')") assert space.float_w(w_res) == 0.1 w_res = space.execute("return Marshal.load('\x04\bf\x061')") assert space.float_w(w_res) == 1.0 w_res = space.execute("return Marshal.load('\x04\bf\b1.1')") assert space.float_w(w_res) == 1.1 w_res = space.execute("return Marshal.load('\x04\bf\n1.001')") assert space.float_w(w_res) == 1.001 #w_res = space.execute("return Marshal.load('\x04\bf\x17123456789.12345679')") #assert space.float_w(w_res) == 123456789.123456789 #w_res = space.execute("return Marshal.load('\x04\bf\x18-123456789.12345679')") #assert space.float_w(w_res) == -123456789.123456789 #w_res = space.execute("return Marshal.load('\x04\bf\a-0')") #assert repr(space.float_w(w_res)) == repr(-0.0) def test_dump_string(self, space): w_res = space.execute("return Marshal.dump('')") assert space.str_w(w_res) == "\x04\bI\"\x00\x06:\x06ET" w_res = space.execute("return Marshal.dump('abc')") assert space.str_w(w_res) == "\x04\bI\"\babc\x06:\x06ET" w_res = space.execute("return Marshal.dump('i am a longer string')") assert space.str_w(w_res) == "\x04\bI\"\x19i am a longer string\x06:\x06ET" def test_load_string(self, space): #w_res = space.execute("return Marshal.load('\x04\bI\"\x00\x06:\x06ET')") w_res = space.execute("return Marshal.load(Marshal.dump(''))") assert space.str_w(w_res) == "" w_res = space.execute("return Marshal.load('\x04\bI\"\babc\x06:\x06ET')") assert space.str_w(w_res) == "abc" w_res = space.execute("return Marshal.load('\x04\bI\"\x19i am a longer string\x06:\x06ET')") assert space.str_w(w_res) == "i am a longer string" def test_array(self, space): w_res = space.execute("return Marshal.load(Marshal.dump([1, 2, 3]))") assert self.unwrap(space, w_res) == [1, 2, 3] w_res = space.execute("return Marshal.load(Marshal.dump([1, [2, 3], 4]))") assert self.unwrap(space, w_res) == [1, [2, 3], 4] w_res = space.execute("return Marshal.load(Marshal.dump([130, [2, 3], 4]))") assert self.unwrap(space, w_res) == [130, [2, 3], 4] w_res = space.execute("return Marshal.load(Marshal.dump([-10000, [2, 123456], -9000]))") assert self.unwrap(space, w_res) == [-10000, [2, 123456], -9000] w_res = space.execute("return Marshal.load(Marshal.dump([:foo, :bar]))") assert self.unwrap(space, w_res) == ["foo", "bar"] w_res = space.execute("return Marshal.load(Marshal.dump(['foo', 'bar']))") assert self.unwrap(space, w_res) == ["foo", "bar"] def test_incompatible_format(self, space): with self.raises( space, "TypeError", "incompatible marshal file format (can't be read)\n" "format version 4.8 required; 97.115 given" ): space.execute("Marshal.load('asd')") def test_short_data(self, space): with self.raises(space, "ArgumentError", "marshal data too short"): space.execute("Marshal.load('')") def test_parameters(self, space): with self.raises(space, "TypeError", "instance of IO needed"): space.execute("Marshal.load(4)") def test_io(self, space, tmpdir): f = tmpdir.join("testfile") w_res = space.execute(""" Marshal.dump('hallo', File.new('%s', 'wb')) file = File.open('%s', 'rb') return Marshal.load(file.read) """ % (f, f)) assert space.str_w(w_res) == "hallo" w_res = space.execute(""" Marshal.dump('hallo', File.new('%s', 'wb')) file = File.open('%s', 'rb') return Marshal.load(file) """ % (f, f)) assert space.str_w(w_res) == "hallo"
Java
/* * Copyright (c) 2007 BUSINESS OBJECTS SOFTWARE LIMITED * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of Business Objects nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * IntellicutList.java * Creation date: Dec 10th 2002 * By: Ken Wong */ package org.openquark.gems.client; import java.awt.Container; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.MouseEvent; import javax.swing.JList; import javax.swing.JViewport; import javax.swing.ListSelectionModel; import org.openquark.gems.client.IntellicutListModel.FilterLevel; import org.openquark.gems.client.IntellicutListModelAdapter.IntellicutListEntry; import org.openquark.gems.client.IntellicutManager.IntellicutMode; /** * A list that encapsulates all the details associated with populating * a list with the unqualified names of gems. * @author Ken Wong * @author Frank Worsley */ public class IntellicutList extends JList { private static final long serialVersionUID = -8515575227984050475L; /** The last list index that was visible when the state was saved. */ private int savedVisibleIndex = -1; /** The last list entry that was visible when the state was saved. */ private IntellicutListEntry savedVisibleEntry = null; /** The list entry that was selected when the state was saved. */ private IntellicutListEntry savedSelectedEntry = null; /** Whether or not this list should be drawn transparently. */ private boolean transparent = false; /** * Constructor for IntellicutList. */ public IntellicutList(IntellicutMode mode) { setName("MatchingGemsList"); setCellRenderer(new IntellicutListRenderer(mode)); setSelectionMode(ListSelectionModel.SINGLE_SELECTION); } /** * Enables the list to be transparent. If the list is transparent non selected list items * will let the components below them show through. Selected list items will draw a blue * semi-transparent tint as their background. * @param value whether or not the list should be transparent */ void setTransparent(boolean value) { this.transparent = value; updateUI(); } /** * @return whether or not the intellicut list is transparent */ public boolean isTransparent() { return transparent; } /** * Saves the currently selected list item and the scroll position of the * list so that the list state can be restored later. */ private void saveListState() { IntellicutListModel listModel = (IntellicutListModel) getModel(); savedVisibleEntry = null; savedSelectedEntry = null; savedVisibleIndex = getLastVisibleIndex(); int selectedIndex = getSelectedIndex(); try { savedVisibleEntry = listModel.get(savedVisibleIndex); savedSelectedEntry = listModel.get(selectedIndex); // We only want to make the selected entry visible again after refreshing // the list if it was visible before. if (selectedIndex > getLastVisibleIndex() || selectedIndex < getFirstVisibleIndex()) { savedSelectedEntry = null; } } catch (Exception ex) { // This might throw a NullPointerException or ArrayIndexOutOfBoundsException // if the model is not initialized. In that case there is no index we can restore. } } /** * Restores the previously saved list state as closely as possible. */ private void restoreListState() { IntellicutListModel listModel = (IntellicutListModel) getModel(); int newSelectedIndex = listModel.indexOf(savedSelectedEntry); int newVisibleIndex = listModel.indexOf(savedVisibleEntry); if (newVisibleIndex == -1) { newVisibleIndex = savedVisibleIndex; } // We have to add one cell height, otherwise the cell will be just // outside of the visible range of the list. ensureIndexIsVisible doesn't // work here since we want the index to appear at the very bottom. Point newLocation = indexToLocation(newVisibleIndex); if (newLocation != null) { newLocation.y += getCellBounds(0, 0).height; scrollRectToVisible(new Rectangle(newLocation)); } if (newSelectedIndex != -1) { setSelectedIndex(newSelectedIndex); ensureIndexIsVisible(newSelectedIndex); } else { setSelectedIndex(0); } } /** * Refreshes the list while remembering the selected item and scroll position * as closely as possible. Simply refreshing the list model will not remember * the list state. * @param prefix the new prefix for values in the list */ public void refreshList(String prefix) { IntellicutListModel listModel = (IntellicutListModel) getModel(); saveListState(); listModel.refreshList(prefix); restoreListState(); } /** * Finds the JViewport this list is embedded in. * @return the viewport or null if there is no viewport */ private JViewport getViewport() { Container parent = getParent(); while (parent != null && !(parent instanceof JViewport)) { parent = parent.getParent (); } return (JViewport) parent; } /** * Scrolls the given index as close as possible to the top of the list's viewport. * @param index index of the item to scroll to the top */ void scrollToTop(int index) { Point location = indexToLocation(index); if (location == null) { return; } JViewport viewport = getViewport(); // Scroll this element as close to the top as possible. if (viewport.getViewSize().height - location.y < viewport.getSize().height) { location.y -= viewport.getSize().height - viewport.getViewSize().height + location.y; } viewport.setViewPosition(location); } /** * Sets the current gem filtering level. * * The list is automatically refreshed after doing this. This method also saves * the list's displayed state as opposed to just setting the filter level which * will not remember the list state. * @param filterLevel the new level to filter at */ void setFilterLevel(FilterLevel filterLevel) { if (filterLevel == null) { throw new NullPointerException("filterLevel must not be null in IntellicutList.setFilterLevel"); } IntellicutListModel listModel = (IntellicutListModel) getModel(); saveListState(); listModel.setFilterLevel(filterLevel); restoreListState(); } /** * Returns the user selected IntellicutListEntry * @return IntellicutListEntry */ IntellicutListEntry getSelected(){ return getModel().getSize() > 0 ? (IntellicutListEntry) getSelectedValue() : null; } /** * We want tooltips to be displayed to the right of an item. * If there is no item at the coordinates it returns null. * @param e the mouse event for which to determine the location * @return the tooltip location for the list item at the coordinates of the mouse event */ @Override public Point getToolTipLocation(MouseEvent e) { int index = locationToIndex(e.getPoint()); if (index == -1) { return null; } Rectangle cellBounds = getCellBounds(index, index); // take off 50 and add 5 for good looks return new Point (cellBounds.x + cellBounds.width - 50, cellBounds.y + 5); } /** * @param e the MouseEvent for which to get the tooltip text * @return the tooltip text for the list item at the coordinates or null if there is no * item at the coordinates */ @Override public String getToolTipText(MouseEvent e) { int index = locationToIndex(e.getPoint()); if (index == -1) { return null; } IntellicutListEntry listEntry = (IntellicutListEntry) getModel().getElementAt(index); if (listEntry == null) { return null; } IntellicutListModel listModel = (IntellicutListModel) getModel(); return listModel.getAdapter().getToolTipTextForEntry(listEntry, this); } }
Java
########################################################################## # # Copyright (c) 2013-2015, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above # copyright notice, this list of conditions and the following # disclaimer. # # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided with # the distribution. # # * Neither the name of John Haddon nor the names of # any other contributors to this software may be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ########################################################################## import os import unittest import IECore import Gaffer import GafferImage import GafferImageTest class ObjectToImageTest( GafferImageTest.ImageTestCase ) : fileName = os.path.expandvars( "$GAFFER_ROOT/python/GafferImageTest/images/checker.exr" ) negFileName = os.path.expandvars( "$GAFFER_ROOT/python/GafferImageTest/images/checkerWithNegativeDataWindow.200x150.exr" ) def test( self ) : i = IECore.Reader.create( self.fileName ).read() n = GafferImage.ObjectToImage() n["object"].setValue( i ) self.assertEqual( n["out"].image(), i ) def testImageWithANegativeDataWindow( self ) : i = IECore.Reader.create( self.negFileName ).read() n = GafferImage.ObjectToImage() n["object"].setValue( i ) self.assertEqual( n["out"].image(), i ) def testHashVariesPerTileAndChannel( self ) : n = GafferImage.ObjectToImage() n["object"].setValue( IECore.Reader.create( self.fileName ).read() ) self.assertNotEqual( n["out"].channelDataHash( "R", IECore.V2i( 0 ) ), n["out"].channelDataHash( "G", IECore.V2i( 0 ) ) ) self.assertNotEqual( n["out"].channelDataHash( "R", IECore.V2i( 0 ) ), n["out"].channelDataHash( "R", IECore.V2i( GafferImage.ImagePlug.tileSize() ) ) ) if __name__ == "__main__": unittest.main()
Java
import React from 'react'; import 'isomorphic-fetch'; import {RouteHandler} from 'react-router'; import Transmit from 'react-transmit'; import {createStore, combineReducers} from 'redux'; import {Provider} from 'react-redux'; import * as reducers from '../reducers/index'; class AppContainer extends React.Component { static propTypes = { initialState: React.PropTypes.object.isRequired } render() { const reducer = combineReducers(reducers); const store = createStore(reducer, this.props.initialState); return ( <Provider store={store}> {() => <RouteHandler /> } </Provider> ); } } export default Transmit.createContainer(AppContainer, { queries: {} });
Java
require("../pc.v0"); require("util").puts(JSON.stringify({ "name": "pc", "version": pc.version, "description": "property creation for reusable d3.js code.", "keywords": ["d3", "visualization"], "homepage": "http://milroc.github.com/pc/", "author": {"name": "Miles McCrocklin", "url": "http://www.milesmccrocklin.com" }, "repository": {"type": "git", "url": "http://github.com/milroc/pc.git"}, "devDependencies": { "uglify-js": "1.2.6", "vows": "0.6.0" } }, null, 2));
Java
.title { margin-top: 30px; vertical-align: top; } .title button { margin-top: 20px; } .contents { margin-top: 100px; } .contetns span { margin-top: 20px; }
Java
package immortal import ( "os/exec" "syscall" "testing" "time" ) func TestWatchPidGetpid(t *testing.T) { ch := make(chan error, 1) d := &Daemon{} cmd := exec.Command("go", "version") cmd.Start() pid := cmd.Process.Pid go func() { d.WatchPid(pid, ch) ch <- cmd.Wait() }() select { case <-time.After(time.Millisecond): syscall.Kill(pid, syscall.SIGTERM) case err := <-ch: if err != nil { if err.Error() != "EXIT" { t.Error(err) } } } } func TestWatchPidGetpidKill(t *testing.T) { d := &Daemon{} ch := make(chan error, 1) cmd := exec.Command("sleep", "100") cmd.Start() pid := cmd.Process.Pid go func() { d.WatchPid(pid, ch) ch <- cmd.Wait() }() select { case err := <-ch: if err != nil { if err.Error() != "EXIT" { t.Error(err) } } case <-time.After(1 * time.Millisecond): if err := cmd.Process.Kill(); err != nil { t.Errorf("failed to kill: %s", err) } } }
Java
/* * Author: Kiveisha Yevgeniy * Copyright (c) 2015 Intel Corporation. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Utilities.h" #include <string.h> char Utilities::toHEX (char code) { return m_hex[code & 15]; } long Utilities::Escaping (char * src, char * dest) { char *pstr = src; char *pbuf = dest; long count = 0; while (*pstr) { if (isalnum(*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.' || *pstr == '~') { *pbuf++ = *pstr; count++; } else if (*pstr == ' ') { *pbuf++ = '+'; count++; } else if (*pstr == '=') { *pbuf++ = *pstr; count++; } else { *pbuf++ = '%', *pbuf++ = toHEX(*pstr >> 4), *pbuf++ = toHEX(*pstr & 15); count += 3; } pstr++; } *pbuf = '\0'; return count; } std::string Utilities::EncodeBase64 (unsigned char const* bytes_to_encode, unsigned int in_len) { std::string ret; int i = 0; int j = 0; unsigned char char_array_3[3]; unsigned char char_array_4[4]; while (in_len--) { char_array_3[i++] = *(bytes_to_encode++); if (i == 3) { char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for(i = 0; (i <4) ; i++) { ret += m_base64_chars[char_array_4[i]]; } i = 0; } } if (i) { for(j = i; j < 3; j++) { char_array_3[j] = '\0'; } char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for (j = 0; (j < i + 1); j++) { ret += m_base64_chars[char_array_4[j]]; } while((i++ < 3)) ret += '='; } return ret; }
Java
<!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 (version 1.7.0_51) on Tue May 19 11:04:42 CEST 2015 --> <title>Uses of Interface com.mxgraph.util.svg.ShapeProducer (JGraph X 3.3.0.1 API Specification)</title> <meta name="date" content="2015-05-19"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Interface com.mxgraph.util.svg.ShapeProducer (JGraph X 3.3.0.1 API Specification)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><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><a href="../../../../../com/mxgraph/util/svg/ShapeProducer.html" title="interface in com.mxgraph.util.svg">Class</a></li> <li class="navBarCell1Rev">Use</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 class="aboutLanguage"><em><p><b>JGraph X 3.3.0.1</b></p></em></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/mxgraph/util/svg/class-use/ShapeProducer.html" target="_top">Frames</a></li> <li><a href="ShapeProducer.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All 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> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Interface com.mxgraph.util.svg.ShapeProducer" class="title">Uses of Interface<br>com.mxgraph.util.svg.ShapeProducer</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../com/mxgraph/util/svg/ShapeProducer.html" title="interface in com.mxgraph.util.svg">ShapeProducer</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#com.mxgraph.util.svg">com.mxgraph.util.svg</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="com.mxgraph.util.svg"> <!-- --> </a> <h3>Uses of <a href="../../../../../com/mxgraph/util/svg/ShapeProducer.html" title="interface in com.mxgraph.util.svg">ShapeProducer</a> in <a href="../../../../../com/mxgraph/util/svg/package-summary.html">com.mxgraph.util.svg</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../com/mxgraph/util/svg/package-summary.html">com.mxgraph.util.svg</a> that implement <a href="../../../../../com/mxgraph/util/svg/ShapeProducer.html" title="interface in com.mxgraph.util.svg">ShapeProducer</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../com/mxgraph/util/svg/AWTPathProducer.html" title="class in com.mxgraph.util.svg">AWTPathProducer</a></strong></code> <div class="block">This class provides an implementation of the PathHandler that initializes a Shape from the value of a path's 'd' attribute.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../com/mxgraph/util/svg/AWTPolygonProducer.html" title="class in com.mxgraph.util.svg">AWTPolygonProducer</a></strong></code> <div class="block">This class produces a polygon shape from a reader.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../com/mxgraph/util/svg/AWTPolylineProducer.html" title="class in com.mxgraph.util.svg">AWTPolylineProducer</a></strong></code> <div class="block">This class produces a polyline shape from a reader.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><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><a href="../../../../../com/mxgraph/util/svg/ShapeProducer.html" title="interface in com.mxgraph.util.svg">Class</a></li> <li class="navBarCell1Rev">Use</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 class="aboutLanguage"><em><p><b>JGraph X 3.3.0.1</b></p></em></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/mxgraph/util/svg/class-use/ShapeProducer.html" target="_top">Frames</a></li> <li><a href="ShapeProducer.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All 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> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small><font size=1>Copyright (c) 2010 <a href="http://www.mxgraph.com/" target="_blank">Gaudenz Alder</a>. All rights reserved.</font></small></p> </body> </html>
Java
SEEK::Application.configure do #This holds a secret phrase, used for encrypting private information in the database #GLOBAL_PASSPHRASE="" Seek::Config.default :solr_enabled, true end
Java
#pragma once #include "boxFilter.hpp" class boxFilter_Separable_VHI_nonVec : public cp::BoxFilterBase { protected: int ksize; void filter_naive_impl() override; void filter_omp_impl() override; void operator()(const cv::Range& range) const override; public: boxFilter_Separable_VHI_nonVec(cv::Mat& _src, cv::Mat& _dest, int _r, int _parallelType); virtual void init(); }; class boxFilter_Separable_VHI_SSE : public boxFilter_Separable_VHI_nonVec { private: __m128 mDiv; void filter_naive_impl() override; void filter_omp_impl() override; void operator()(const cv::Range& range) const override; public: boxFilter_Separable_VHI_SSE(cv::Mat& _src, cv::Mat& _dest, int _r, int _parallelType); void init() override; }; class boxFilter_Separable_VHI_AVX : public boxFilter_Separable_VHI_nonVec { private: __m256 mDiv; void filter_naive_impl() override; void filter_omp_impl() override; void operator()(const cv::Range& range) const override; public: boxFilter_Separable_VHI_AVX(cv::Mat& _src, cv::Mat& _dest, int _r, int _parallelType); void init() override; };
Java
<!DOCTYPE html> <!-- | Generated by Apache Maven Doxia at 2014-11-25 | Rendered using Apache Maven Fluido Skin 1.3.0 --> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="Date-Revision-yyyymmdd" content="20141125" /> <meta http-equiv="Content-Language" content="en" /> <title>TrAP Transport WebSocket by Netty - Continuous Integration</title> <link rel="stylesheet" href="./css/apache-maven-fluido-1.3.0.min.css" /> <link rel="stylesheet" href="./css/site.css" /> <link rel="stylesheet" href="./css/print.css" media="print" /> <script type="text/javascript" src="./js/apache-maven-fluido-1.3.0.min.js"></script> </head> <body class="topBarDisabled"> <div class="container-fluid"> <div id="banner"> <div class="pull-left"> <div id="bannerLeft"> <h2>TrAP Transport WebSocket by Netty</h2> </div> </div> <div class="pull-right"> </div> <div class="clear"><hr/></div> </div> <div id="breadcrumbs"> <ul class="breadcrumb"> <li id="publishDate">Last Published: 2014-11-25</li> <li class="divider">|</li> <li id="projectVersion">Version: 1.3</li> <li class="divider">|</li> <li class=""> <a href="../../../index.html" title="Trap"> Trap</a> </li> <li class="divider ">/</li> <li class=""> <a href="../../" title="TrAP Transports"> TrAP Transports</a> </li> <li class="divider ">/</li> <li class=""> <a href="../" title="WebSocket Transport Parent"> WebSocket Transport Parent</a> </li> <li class="divider ">/</li> <li class=""> <a href="./" title="TrAP Transport WebSocket by Netty"> TrAP Transport WebSocket by Netty</a> </li> <li class="divider ">/</li> <li class="">Continuous Integration</li> </ul> </div> <div class="row-fluid"> <div id="leftColumn" class="span3"> <div class="well sidebar-nav"> <ul class="nav nav-list"> <li class="nav-header">Trap 1.3</li> <li> <a href="../../../index.html" title="Introduction"> <i class="none"></i> Introduction</a> </li> <li> <a href="../../../trap-api/quickstart.html" title="Java Quickstart"> <i class="none"></i> Java Quickstart</a> </li> <li> <a href="../../../trap-js/index.html" title="JavaScript Quickstart"> <i class="none"></i> JavaScript Quickstart</a> </li> <li> <a href="../../../channels.html" title="Channels"> <i class="none"></i> Channels</a> </li> <li> <a href="../../../configuration.html" title="Configuration"> <i class="none"></i> Configuration</a> </li> <li class="nav-header">Language Specific Documentation</li> <li> <a href="../../../trap-api/index.html" title="Java"> <i class="none"></i> Java</a> </li> <li> <a href="../../../trap-js/index.html" title="JavaScript"> <i class="none"></i> JavaScript</a> </li> <li class="nav-header">Project Documentation</li> <li> <a href="project-info.html" title="Project Information"> <i class="icon-chevron-down"></i> Project Information</a> <ul class="nav nav-list"> <li> <a href="index.html" title="About"> <i class="none"></i> About</a> </li> <li> <a href="plugin-management.html" title="Plugin Management"> <i class="none"></i> Plugin Management</a> </li> <li> <a href="distribution-management.html" title="Distribution Management"> <i class="none"></i> Distribution Management</a> </li> <li> <a href="dependency-info.html" title="Dependency Information"> <i class="none"></i> Dependency Information</a> </li> <li> <a href="dependency-convergence.html" title="Dependency Convergence"> <i class="none"></i> Dependency Convergence</a> </li> <li> <a href="source-repository.html" title="Source Repository"> <i class="none"></i> Source Repository</a> </li> <li> <a href="mail-lists.html" title="Mailing Lists"> <i class="none"></i> Mailing Lists</a> </li> <li> <a href="issue-tracking.html" title="Issue Tracking"> <i class="none"></i> Issue Tracking</a> </li> <li class="active"> <a href="#"><i class="none"></i>Continuous Integration</a> </li> <li> <a href="plugins.html" title="Project Plugins"> <i class="none"></i> Project Plugins</a> </li> <li> <a href="license.html" title="Project License"> <i class="none"></i> Project License</a> </li> <li> <a href="dependency-management.html" title="Dependency Management"> <i class="none"></i> Dependency Management</a> </li> <li> <a href="team-list.html" title="Project Team"> <i class="none"></i> Project Team</a> </li> <li> <a href="project-summary.html" title="Project Summary"> <i class="none"></i> Project Summary</a> </li> <li> <a href="dependencies.html" title="Dependencies"> <i class="none"></i> Dependencies</a> </li> </ul> </li> <li> <a href="project-reports.html" title="Project Reports"> <i class="icon-chevron-right"></i> Project Reports</a> </li> </ul> <form id="search-form" action="http://www.google.com/search" method="get" > <input value="ericssonresearch.github.io/trap/transports/websocket/websocket-netty/" name="sitesearch" type="hidden"/> <input class="search-query" name="q" id="query" type="text" /> </form> <script type="text/javascript" src="http://www.google.com/coop/cse/brand?form=search-form"></script> <hr class="divider" /> <div id="poweredBy"> <div class="clear"></div> <div class="clear"></div> <div class="clear"></div> <a href="http://maven.apache.org/" title="Built by Maven" class="poweredBy"> <img class="builtBy" alt="Built by Maven" src="./images/logos/maven-feather.png" /> </a> </div> </div> </div> <div id="bodyColumn" class="span9" > <div class="section"> <h2>Continuous Integration<a name="Continuous_Integration"></a></h2><a name="Continuous_Integration"></a> <p>No continuous integration management system is defined. Please check back at a later date.</p></div> </div> </div> </div> <hr/> <footer> <div class="container-fluid"> <div class="row span12">Copyright &copy; 2014 <a href="https://www.ericsson.com">Ericsson AB</a>. All Rights Reserved. </div> </div> </footer> </body> </html>
Java
/** * Created on: Mar 13, 2013 */ package com.tubros.constraints.core.spi.solver package runtime import org.junit.runner.RunWith import org.scalamock.scalatest.MockFactory import org.scalatest._ import org.scalatest.junit.JUnitRunner import com.tubros.constraints.api._ /** * The '''SymbolTableSpec''' type defines the unit tests responsible for * certifying the [[com.tubros.constraints.core.spi.solver.runtime.SymbolTable]] * abstraction for use in CSP implementations. * * @author svickers * */ @RunWith (classOf[JUnitRunner]) class SymbolTableSpec extends ProjectSpec { "A SymbolTable" should "be able to be constructed with nothing in it" in { val table = SymbolTable.empty; table shouldNot be (null); table ('unknown) should be ('empty); table.contains ('anyName) shouldBe (false); } it should "support symbol name addition" in { val entry = VariableName ('aName); val oneEntry = SymbolTable.empty addSymbol (entry); oneEntry.contains (entry) shouldBe (true); oneEntry (entry) shouldBe (Set (entry)); } it should "support dependant definitions" in { val dependant = ( SymbolTable.empty addSymbol ('a) addSymbol ('b) addDerivedSymbol ('c, Set ('a, 'b)) ); dependant ('c) should not be ('empty); dependant.contains ('c) shouldBe (true); dependant ('c) shouldBe ( Set (VariableName ('a), VariableName ('b)) ); } it should "support nested dependant definitions" in { val nested = ( SymbolTable.empty addDerivedSymbol ('d, Set ('c)) addDerivedSymbol ('c, Set ('a, 'b)) addSymbol ('b) addSymbol ('a) ); nested.contains ('d) shouldBe (true); nested ('d) should not be ('empty); nested ('d) shouldBe ( Set (VariableName ('a), VariableName ('b)) ); } it should "be able to determine what symbols are dependants" in { val dependant = ( SymbolTable.empty addSymbol ('a) addSymbol ('b) addDerivedSymbol ('c, Set ('a, 'b)) ); dependant.isDerived ('a) shouldBe (false); dependant.isDerived ('c) shouldBe (true); } it should "be able to resolve dependants available when expected" in { val dependant = ( SymbolTable.empty addSymbol ('a) addSymbol ('b) addDerivedSymbol ('c, Set ('a, 'b)) ); dependant.derivedFrom (Set[VariableName] ('a, 'b)) shouldBe ( Set (VariableName ('c)) ); } it should "not resolve a dependant unless all roots are available" in { val dependant = ( SymbolTable.empty addSymbol ('a) addSymbol ('b) addDerivedSymbol ('c, Set ('a, 'b)) ); dependant.derivedFrom (Set[VariableName] ('a)) should be ('empty); } it should "not resolve a dependant unless all participants are available" in { val dependant = ( SymbolTable.empty addSymbol ('a) addSymbol ('b) addSymbol ('d) addDerivedSymbol ('c, Set ('a, 'e)) addDerivedSymbol ('e, Set ('d)) ); dependant.derivedFrom (Set[VariableName] ('a, 'b)) should be ('empty); } }
Java
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="lang:clipboard.copy" content="Copy to clipboard"> <meta name="lang:clipboard.copied" content="Copied to clipboard"> <meta name="lang:search.language" content="en"> <meta name="lang:search.pipeline.stopwords" content="True"> <meta name="lang:search.pipeline.trimmer" content="True"> <meta name="lang:search.result.none" content="No matching documents"> <meta name="lang:search.result.one" content="1 matching document"> <meta name="lang:search.result.other" content="# matching documents"> <meta name="lang:search.tokenizer" content="[\s\-]+"> <link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin> <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet"> <style> body, input { font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif } code, kbd, pre { font-family: "Roboto Mono", "Courier New", Courier, monospace } </style> <link rel="stylesheet" href="../_static/stylesheets/application.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/> <link rel="stylesheet" href="../_static/fonts/material-icons.css"/> <meta name="theme-color" content="#3f51b5"> <script src="../_static/javascripts/modernizr.js"></script> <title>statsmodels.genmod.cov_struct.Exchangeable.update &#8212; statsmodels</title> <link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png"> <link rel="manifest" href="../_static/icons/site.webmanifest"> <link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191"> <meta name="msapplication-TileColor" content="#2b5797"> <meta name="msapplication-config" content="../_static/icons/browserconfig.xml"> <link rel="stylesheet" href="../_static/stylesheets/examples.css"> <link rel="stylesheet" href="../_static/stylesheets/deprecation.css"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css" /> <link rel="stylesheet" type="text/css" href="../_static/material.css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <link rel="stylesheet" type="text/css" href="../_static/plot_directive.css" /> <script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script> <script src="../_static/jquery.js"></script> <script src="../_static/underscore.js"></script> <script src="../_static/doctools.js"></script> <script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script> <link rel="shortcut icon" href="../_static/favicon.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.genmod.cov_struct.GlobalOddsRatio" href="statsmodels.genmod.cov_struct.GlobalOddsRatio.html" /> <link rel="prev" title="statsmodels.genmod.cov_struct.Exchangeable.summary" href="statsmodels.genmod.cov_struct.Exchangeable.summary.html" /> </head> <body dir=ltr data-md-color-primary=indigo data-md-color-accent=blue> <svg class="md-svg"> <defs data-children-count="0"> <svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg> </defs> </svg> <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer"> <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search"> <label class="md-overlay" data-md-component="overlay" for="__drawer"></label> <a href="#generated/statsmodels.genmod.cov_struct.Exchangeable.update" tabindex="1" class="md-skip"> Skip to content </a> <header class="md-header" data-md-component="header"> <nav class="md-header-nav md-grid"> <div class="md-flex navheader"> <div class="md-flex__cell md-flex__cell--shrink"> <a href="../index.html" title="statsmodels" class="md-header-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" height="26" alt="statsmodels logo"> </a> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label> </div> <div class="md-flex__cell md-flex__cell--stretch"> <div class="md-flex__ellipsis md-header-nav__title" data-md-component="title"> <span class="md-header-nav__topic">statsmodels v0.13.0</span> <span class="md-header-nav__topic"> statsmodels.genmod.cov_struct.Exchangeable.update </span> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--search md-header-nav__button" for="__search"></label> <div class="md-search" data-md-component="search" role="dialog"> <label class="md-search__overlay" for="__search"></label> <div class="md-search__inner" role="search"> <form class="md-search__form" action="../search.html" method="get" name="search"> <input type="text" class="md-search__input" name="q" placeholder="Search" autocapitalize="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active"> <label class="md-icon md-search__icon" for="__search"></label> <button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1"> &#xE5CD; </button> </form> <div class="md-search__output"> <div class="md-search__scrollwrap" data-md-scrollfix> <div class="md-search-result" data-md-component="result"> <div class="md-search-result__meta"> Type to start searching </div> <ol class="md-search-result__list"></ol> </div> </div> </div> </div> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <div class="md-header-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> </div> <script src="../_static/javascripts/version_dropdown.js"></script> <script> var json_loc = "../../versions-v2.json", target_loc = "../../", text = "Versions"; $( document ).ready( add_version_dropdown(json_loc, target_loc, text)); </script> </div> </nav> </header> <div class="md-container"> <nav class="md-tabs" data-md-component="tabs"> <div class="md-tabs__inner md-grid"> <ul class="md-tabs__list"> <li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li> <li class="md-tabs__item"><a href="../gee.html" class="md-tabs__link">Generalized Estimating Equations</a></li> <li class="md-tabs__item"><a href="statsmodels.genmod.cov_struct.Exchangeable.html" class="md-tabs__link">statsmodels.genmod.cov_struct.Exchangeable</a></li> </ul> </div> </nav> <main class="md-main"> <div class="md-main__inner md-grid" data-md-component="container"> <div class="md-sidebar md-sidebar--primary" data-md-component="navigation"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--primary" data-md-level="0"> <label class="md-nav__title md-nav__title--site" for="__drawer"> <a href="../index.html" title="statsmodels" class="md-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48"> </a> <a href="../index.html" title="statsmodels">statsmodels v0.13.0</a> </label> <div class="md-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../install.html" class="md-nav__link">Installing statsmodels</a> </li> <li class="md-nav__item"> <a href="../gettingstarted.html" class="md-nav__link">Getting started</a> </li> <li class="md-nav__item"> <a href="../user-guide.html" class="md-nav__link">User Guide</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../user-guide.html#background" class="md-nav__link">Background</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../regression.html" class="md-nav__link">Linear Regression</a> </li> <li class="md-nav__item"> <a href="../glm.html" class="md-nav__link">Generalized Linear Models</a> </li> <li class="md-nav__item"> <a href="../gee.html" class="md-nav__link">Generalized Estimating Equations</a> </li> <li class="md-nav__item"> <a href="../gam.html" class="md-nav__link">Generalized Additive Models (GAM)</a> </li> <li class="md-nav__item"> <a href="../rlm.html" class="md-nav__link">Robust Linear Models</a> </li> <li class="md-nav__item"> <a href="../mixed_linear.html" class="md-nav__link">Linear Mixed Effects Models</a> </li> <li class="md-nav__item"> <a href="../discretemod.html" class="md-nav__link">Regression with Discrete Dependent Variable</a> </li> <li class="md-nav__item"> <a href="../mixed_glm.html" class="md-nav__link">Generalized Linear Mixed Effects Models</a> </li> <li class="md-nav__item"> <a href="../anova.html" class="md-nav__link">ANOVA</a> </li> <li class="md-nav__item"> <a href="../other_models.html" class="md-nav__link">Other Models <code class="xref py py-mod docutils literal notranslate"><span class="pre">othermod</span></code></a> </li></ul> </li> <li class="md-nav__item"> <a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a> </li></ul> </li> <li class="md-nav__item"> <a href="../examples/index.html" class="md-nav__link">Examples</a> </li> <li class="md-nav__item"> <a href="../api.html" class="md-nav__link">API Reference</a> </li> <li class="md-nav__item"> <a href="../about.html" class="md-nav__link">About statsmodels</a> </li> <li class="md-nav__item"> <a href="../dev/index.html" class="md-nav__link">Developer Page</a> </li> <li class="md-nav__item"> <a href="../release/index.html" class="md-nav__link">Release Notes</a> </li> </ul> </nav> </div> </div> </div> <div class="md-sidebar md-sidebar--secondary" data-md-component="toc"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--secondary"> <ul class="md-nav__list" data-md-scrollfix=""> <li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.genmod.cov_struct.Exchangeable.update.rst.txt">Show Source</a> </li> <li id="searchbox" class="md-nav__item"></li> </ul> </nav> </div> </div> </div> <div class="md-content"> <article class="md-content__inner md-typeset" role="main"> <h1 id="generated-statsmodels-genmod-cov-struct-exchangeable-update--page-root">statsmodels.genmod.cov_struct.Exchangeable.update<a class="headerlink" href="#generated-statsmodels-genmod-cov-struct-exchangeable-update--page-root" title="Permalink to this headline">¶</a></h1> <dl class="py method"> <dt class="sig sig-object py" id="statsmodels.genmod.cov_struct.Exchangeable.update"> <span class="sig-prename descclassname"><span class="pre">Exchangeable.</span></span><span class="sig-name descname"><span class="pre">update</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">params</span></span></em><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/genmod/cov_struct.html#Exchangeable.update"><span class="viewcode-link"><span class="pre">[source]</span></span></a><a class="headerlink" href="#statsmodels.genmod.cov_struct.Exchangeable.update" title="Permalink to this definition">¶</a></dt> <dd><p>Update the association parameter values based on the current regression coefficients.</p> <dl class="field-list"> <dt class="field-odd">Parameters</dt> <dd class="field-odd"><dl> <dt><strong>params</strong><span class="classifier"><a class="reference external" href="https://numpy.org/doc/stable/glossary.html#term-array_like" title="(in NumPy v1.21)"><span>array_like</span></a></span></dt><dd><p>Working values for the regression parameters.</p> </dd> </dl> </dd> </dl> </dd></dl> </article> </div> </div> </main> </div> <footer class="md-footer"> <div class="md-footer-nav"> <nav class="md-footer-nav__inner md-grid"> <a href="statsmodels.genmod.cov_struct.Exchangeable.summary.html" title="statsmodels.genmod.cov_struct.Exchangeable.summary" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev"> <div class="md-flex__cell md-flex__cell--shrink"> <i class="md-icon md-icon--arrow-back md-footer-nav__button"></i> </div> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"> <span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Previous </span> statsmodels.genmod.cov_struct.Exchangeable.summary </span> </div> </a> <a href="statsmodels.genmod.cov_struct.GlobalOddsRatio.html" title="statsmodels.genmod.cov_struct.GlobalOddsRatio" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next"> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Next </span> statsmodels.genmod.cov_struct.GlobalOddsRatio </span> </div> <div class="md-flex__cell md-flex__cell--shrink"><i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i> </div> </a> </nav> </div> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class="md-footer-copyright"> <div class="md-footer-copyright__highlight"> &#169; Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. </div> Last updated on Oct 06, 2021. <br/> Created using <a href="http://www.sphinx-doc.org/">Sphinx</a> 4.0.3. and <a href="https://github.com/bashtage/sphinx-material/">Material for Sphinx</a> </div> </div> </div> </footer> <script src="../_static/javascripts/application.js"></script> <script>app.initialize({version: "1.0.4", url: {base: ".."}})</script> </body> </html>
Java
#include "synchronization/Communicator.hpp" namespace Synchronization { Communicator::Communicator() : _numManagedCons(0), _numManagedFmus(0) { } size_type Synchronization::Communicator::addFmu(FMI::AbstractFmu* in, vector<FMI::InputMapping> & valuePacking) { vector<ConnectionSPtr>& connList = in->getConnections(); size_type numNewCons = 0; for (auto & con : connList) { con->initialize(in->getFmuName()); size_type conId; auto it = _knownConIds.find(con->getStartTag()); if (it == _knownConIds.end()) { valuePacking.push_back(con->getPacking()); conId = _numManagedCons++; _knownConIds[con->getStartTag()] = conId; ++numNewCons; } else { conId = it->second; if (con->isShared()) { ++numNewCons; valuePacking.push_back(con->getPacking()); } } con->setLocalId(conId); } in->setSharedId(_numManagedFmus++); for (auto & con : connList) { if (con->getLocalId() + 1 > _connections.size()) { _connections.resize(con->getLocalId() + 1); _connections[con->getLocalId()] = con; } } if (_outConnectionIds.size() < in->getSharedId() + 1) { _outConnectionIds.resize(in->getSharedId() + 1); } if (_inConnectionIds.size() < in->getSharedId() + 1) { _inConnectionIds.resize(in->getSharedId() + 1); } for (auto & i : connList) { if (i->isOutgoing(in->getFmuName())) { _outConnectionIds[in->getSharedId()].push_back(i->getLocalId()); } else { _inConnectionIds[in->getSharedId()].push_back(i->getLocalId()); } } return numNewCons; } bool_type Communicator::send(HistoryEntry const & in, size_type communicationId) { return static_cast<bool_type>(_connections[communicationId]->send(in)); } HistoryEntry Communicator::recv(size_type communicationId) { return _connections[communicationId]->recv(); } int_type Communicator::connectionIsFree(size_type communicationId) { return _connections[communicationId]->hasFreeBuffer(); } const vector<size_type> & Communicator::getInConnectionIds(const FMI::AbstractFmu * in) const { return _inConnectionIds[in->getSharedId()]; } const vector<size_type> & Communicator::getOutConnectionIds(const FMI::AbstractFmu * in) const { return _outConnectionIds[in->getSharedId()]; } size_type Communicator::getNumInConnections() const { size_type sum = 0; for (const auto & _inConnectionId : _inConnectionIds) { sum += _inConnectionId.size(); } return sum; } size_type Communicator::getNumOutConnections() const { size_type sum = 0; for (const auto & _outConnectionId : _outConnectionIds) { sum += _outConnectionId.size(); } return sum; } } /* namespace Synchronization */
Java
{% load url from future %} <div class="well"> <h3 class="title">Violence</h3> <table class="table tabulated-data"> <thead> <tr> <th>Group</th> <th>Monthly Numbers</th> </tr> </thead> <tbody> <tr> <td>Girls Cases</td> <td>{{ violence_numbers_girls|floatformat:0 }}</td> </tr> <tr> <td>Boys Cases</td> <td>{{ violence_numbers_boys|floatformat:0 }}</td> </tr> <tr> <td>Cases Referred to Police</td> <td>{{ violence_numbers_reported|floatformat:0 }}</td> </tr> </tbody> </table> <div class="actions"> <a href="{% url 'violence-admin-details' %}" class="btn btn-secondary"><i class="icon-th-list"></i> View Details</a> </div> </div>
Java
#!/usr/bin/env python2 from __future__ import print_function import sys import os import urllib import argparse import xml.etree.ElementTree as ET def warn(*msgs): for x in msgs: print('[WARNING]:', x, file=sys.stderr) class PDBTM: def __init__(self, filename): #self.tree = ET.parse(filename) #self.root = self.tree.getroot() def strsum(l): s = '' for x in l: s += x.rstrip() + '\n' return s f = open(filename) s = [] for l in f: s.append(l) #s = strsum(s[1:-1]).strip() s = strsum(s).strip() self.root = ET.fromstring(s) print(root) def get_database(prefix='.'): if not prefix.endswith('/'): prefix += '/' print('Fetching database...', file=sys.stderr) db = urllib.urlopen('http://pdbtm.enzim.hu/data/pdbtmall') print('Saving database...', file=sys.stderr) f = open('%s/pdbtmall' % prefix, 'w') for l in db: f.write(l) #f.write(db.read()) db.close() f.close() def build_database(fn, prefix): print('Unpacking database...', file=sys.stderr) f = open(fn) db = f.read() f.close() firstline = 1 header = '' entries = [] pdbids = [] for l in db.split('\n'): if firstline: header += l firstline -= 1 continue if 'PDBTM>' in l: continue if l.startswith('<?'): continue if l.startswith('<pdbtm'): a = l.find('ID=') + 4 b = a + 4 pdbids.append(l[a:b]) entries.append(header) entries[-1] += '\n' + l if not prefix.endswith('/'): prefix += '/' if not os.path.isdir(prefix): os.mkdir(prefix) for entry in zip(pdbids, entries): f = open(prefix + entry[0] + '.xml', 'w') f.write(entry[1]) f.close() if __name__ == '__main__': parser = argparse.ArgumentParser(description='Manages PDBTM databases. Automatically fetches the PDBTM database if no options are specified. Run without any arguments, dbtool will retrieve the PDBTM database, store it in pdbtm, and unpack it.') parser.add_argument('-d', '--db', default='pdbtmall', help='name of concatenated database file {default:pdbtmall}') parser.add_argument('-b', '--build-db', action='store_true', help='(re)build database from an existing pdbtmsall file (available at http://pdbtm.enzim.hu/data/pdbtmall)') parser.add_argument('directory', nargs='?', default='pdbtm', help='directory to store database in') parser.add_argument('-f', '--force-refresh', action='store_true', help='force overwrite of existing database. Functionally equivalent to removing the old database and rerunning.') #parser.add_argument('-n', metavar='bundle_size', type=int, help='size to cut bundles into') args = parser.parse_args() if args.build_db: build_database(args.db, args.directory) else: #db = PDBTM(args.db) if not os.path.isdir(args.directory): os.mkdir(args.directory) if args.force_refresh or not os.path.isfile('%s/%s' % (args.directory, args.db)): get_database(args.directory) build_database('%s/%s' % (args.directory, args.db), args.directory) #http://pdbtm.enzim.hu/data/pdbtmall
Java
{-# LANGUAGE TemplateHaskell #-} module Data.Comp.Trans.DeriveUntrans ( deriveUntrans ) where import Control.Lens ( view ,(^.)) import Control.Monad ( liftM ) import Control.Monad.Trans ( lift ) import Data.Comp.Multi ( Alg, cata, (:&:)(..) ) import Language.Haskell.TH import Data.Comp.Trans.Util -------------------------------------------------------------------------------- -- | -- Creates an @untranslate@ function inverting the @translate@ function -- created by @deriveTrans@. -- -- @ -- import qualified Foo as F -- type ArithTerm = Term (Arith :+: Atom :+: Lit) -- deriveUntrans [''F.Arith, ''F.Atom, ''F.Lit] (TH.ConT ''ArithTerm) -- @ -- -- will create -- -- @ -- type family Targ l -- newtype T l = T {t :: Targ l} -- -- class Untrans f where -- untrans :: Alg f t -- -- untranslate :: ArithTerm l -> Targ l -- untranslate = t . cata untrans -- -- type instance Targ ArithL = F.Arith -- instance Untrans Arith where -- untrans (Add x y) = T $ F.Add (t x) (t y) -- -- type instance Targ AtomL = F.Atom -- instance Untrans Atom where -- untrans (Var s) = T $ F.Var s -- untrans (Const x) = T $ F.Const (t x) -- -- type instance Targ LitL = F.Lit -- instance Untrans Lit where -- untrans (Lit n) = T $ F.Lit n -- @ -- -- Note that you will need to manually provide an instance @(Untrans f, Untrans g) => Untrans (f :+: g)@ -- due to phase issues. (Or @(Untrans (f :&: p), Untrans (g :&: p)) => Untrans ((f :+: g) :&: p)@, if you -- are propagating annotations.) -- -- With annotation propagation on, it will instead produce -- `untranslate :: Term (Arith :&: Ann) l -> Targ l Ann` deriveUntrans :: [Name] -> Type -> CompTrans [Dec] deriveUntrans names term = do targDec <- mkTarg targNm wrapperDec <- mkWrapper wrapNm unwrapNm targNm fnDec <- mkFn untranslateNm term targNm unwrapNm fnNm classDec <- mkClass classNm fnNm wrapNm instances <- liftM concat $ mapM (mkInstance classNm fnNm wrapNm unwrapNm targNm) names return $ concat [ targDec , wrapperDec , fnDec , classDec , instances ] where targNm = mkName "Targ" wrapNm = mkName "T" unwrapNm = mkName "t" untranslateNm = mkName "untranslate" classNm = mkName "Untrans" fnNm = mkName "untrans" {- type family Targ l -} mkTarg :: Name -> CompTrans [Dec] mkTarg targNm = do i <- lift $ newName "i" return [FamilyD TypeFam targNm [PlainTV i] Nothing] {- newtype T l = T { t :: Targ l } -} mkWrapper :: Name -> Name -> Name -> CompTrans [Dec] mkWrapper tpNm fNm targNm = do i <- lift $ newName "i" let con = RecC tpNm [(fNm, NotStrict, AppT (ConT targNm) (VarT i))] return [NewtypeD [] tpNm [PlainTV i] con []] {- untranslate :: JavaTerm l -> Targ l untranslate = t . cata untrans -} mkFn :: Name -> Type -> Name -> Name -> Name -> CompTrans [Dec] mkFn fnNm term targNm fldNm untransNm = sequence [sig, def] where sig = do i <- lift $ newName "i" lift $ sigD fnNm (forallT [PlainTV i] (return []) (typ $ varT i)) typ :: Q Type -> Q Type typ i = [t| $term' $i -> $targ $i |] term' = return term targ = conT targNm def = lift $ valD (varP fnNm) (normalB body) [] body = [| $fld . cata $untrans |] fld = varE fldNm untrans = varE untransNm {- class Untrans f where untrans :: Alg f T -} mkClass :: Name -> Name -> Name -> CompTrans [Dec] mkClass classNm funNm newtpNm = do f <- lift $ newName "f" let funDec = SigD funNm (AppT (AppT (ConT ''Alg) (VarT f)) (ConT newtpNm)) return [ClassD [] classNm [PlainTV f] [] [funDec]] {- type instance Targ CompilationUnitL = J.CompilationUnit instance Untrans CompilationUnit where untrans (CompilationUnit x y z) = T $ J.CompilationUnit (t x) (t y) (t z) -} mkInstance :: Name -> Name -> Name -> Name -> Name -> Name -> CompTrans [Dec] mkInstance classNm funNm wrap unwrap targNm typNm = do inf <- lift $ reify typNm targTyp <- getFullyAppliedType typNm let nmTyps = simplifyDataInf inf clauses <- mapM (uncurry $ mkClause wrap unwrap) nmTyps let conTyp = ConT (transName typNm) annPropInf <- view annotationProp let instTyp = case annPropInf of Nothing -> conTyp Just api -> foldl AppT (ConT ''(:&:)) [conTyp, api ^. annTyp] return [ famInst targTyp , inst clauses instTyp ] where famInst targTyp = TySynInstD targNm (TySynEqn [ConT $ nameLab typNm] targTyp) inst clauses instTyp = InstanceD [] (AppT (ConT classNm) instTyp) [FunD funNm clauses] mapConditionallyReplacing :: [a] -> (a -> b) -> (a -> Bool) -> [b] -> [b] mapConditionallyReplacing src f p reps = go src reps where go [] _ = [] go (x:xs) (y:ys) | p x = y : go xs ys go (x:xs) l | not (p x) = f x : go xs l go (_:_ ) [] = error "mapConditionallyReplacing: Insufficiently many replacements" mkClause :: Name -> Name -> Name -> [Type] -> CompTrans Clause mkClause wrap unwrap con tps = do isAnn <- getIsAnn nms <- mapM (const $ lift $ newName "x") tps nmAnn <- lift $ newName "a" tps' <- applyCurSubstitutions tps let nmTps = zip nms tps' Clause <$> (sequence [pat isAnn nmTps nmAnn]) <*> (body nmTps nmAnn) <*> pure [] where pat :: (Type -> Bool) -> [(Name, Type)] -> Name -> CompTrans Pat pat isAnn nmTps nmAnn = do isProp <- isPropagatingAnns if isProp then return $ ConP '(:&:) [nodeP, VarP nmAnn] else return nodeP where nonAnnNms = map fst $ filter (not.isAnn.snd) nmTps nodeP = ConP (transName con) (map VarP nonAnnNms) body :: [(Name, Type)] -> Name -> CompTrans Body body nmTps nmAnn = do annPropInf <- view annotationProp args <- case annPropInf of Nothing -> return $ map atom nmTps Just api -> do isAnn <- getIsAnn let unProp = api ^. unpropAnn let annVars = filter (isAnn.snd) nmTps let annExps = unProp (VarE nmAnn) (length annVars) return $ mapConditionallyReplacing nmTps atom (isAnn.snd) annExps return $ makeRhs args where makeRhs :: [Exp] -> Body makeRhs args = NormalB $ AppE (ConE wrap) $ foldl AppE (ConE con) args atom :: (Name, Type) -> Exp atom (x, t) | elem t baseTypes = VarE x atom (x, _) = AppE (VarE unwrap) (VarE x)
Java
from django.template import Library, Node, resolve_variable, TemplateSyntaxError from django.core.urlresolvers import reverse register = Library() @register.simple_tag def active(request, pattern): import re if re.search(pattern, request.get_full_path()): return 'active' return ''
Java
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <memory> #include <utility> #include <vector> #include "base/feature_list.h" #include "base/macros.h" #include "base/optional.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/metrics/user_action_tester.h" #include "base/test/scoped_feature_list.h" #include "base/test/task_environment.h" #include "base/test/test_mock_time_task_runner.h" #include "build/build_config.h" #include "components/autofill/core/common/form_field_data.h" #include "components/password_manager/core/browser/form_fetcher_impl.h" #include "components/password_manager/core/browser/http_auth_manager_impl.h" #include "components/password_manager/core/browser/mock_password_store.h" #include "components/password_manager/core/browser/password_form_manager.h" #include "components/password_manager/core/browser/password_form_manager_for_ui.h" #include "components/password_manager/core/browser/password_manager_driver.h" #include "components/password_manager/core/browser/password_store.h" #include "components/password_manager/core/browser/password_store_consumer.h" #include "components/password_manager/core/browser/stub_password_manager_client.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using autofill::PasswordForm; using base::ASCIIToUTF16; using base::TestMockTimeTaskRunner; using testing::_; using testing::AnyNumber; using testing::Invoke; using testing::Mock; using testing::Return; using testing::ReturnRef; using testing::SaveArg; using testing::WithArg; namespace password_manager { namespace { class MockPasswordManagerClient : public StubPasswordManagerClient { public: MockPasswordManagerClient() {} MOCK_CONST_METHOD1(IsSavingAndFillingEnabled, bool(const GURL&)); MOCK_CONST_METHOD1(IsFillingEnabled, bool(const GURL&)); MOCK_METHOD2(AutofillHttpAuth, void(const autofill::PasswordForm&, const PasswordFormManagerForUI*)); MOCK_CONST_METHOD0(GetProfilePasswordStore, PasswordStore*()); MOCK_METHOD0(PromptUserToSaveOrUpdatePasswordPtr, void()); // Workaround for std::unique_ptr<> lacking a copy constructor. bool PromptUserToSaveOrUpdatePassword( std::unique_ptr<PasswordFormManagerForUI> manager, bool update_password) override { PromptUserToSaveOrUpdatePasswordPtr(); return true; } }; class MockHttpAuthObserver : public HttpAuthObserver { public: MockHttpAuthObserver() = default; ~MockHttpAuthObserver() override = default; MOCK_METHOD0(OnLoginModelDestroying, void()); MOCK_METHOD2(OnAutofillDataAvailable, void(const base::string16&, const base::string16&)); DISALLOW_COPY_AND_ASSIGN(MockHttpAuthObserver); }; // Invokes the password store consumer with a single copy of |form|. ACTION_P(InvokeConsumer, form) { std::vector<std::unique_ptr<PasswordForm>> result; result.push_back(std::make_unique<PasswordForm>(form)); arg0->OnGetPasswordStoreResults(std::move(result)); } ACTION(InvokeEmptyConsumerWithForms) { arg0->OnGetPasswordStoreResults(std::vector<std::unique_ptr<PasswordForm>>()); } } // namespace class HttpAuthManagerTest : public testing::Test { public: HttpAuthManagerTest() = default; ~HttpAuthManagerTest() override = default; protected: void SetUp() override { store_ = new testing::StrictMock<MockPasswordStore>; ASSERT_TRUE(store_->Init(nullptr)); ON_CALL(client_, GetProfilePasswordStore()) .WillByDefault(Return(store_.get())); EXPECT_CALL(*store_, GetSiteStatsImpl(_)).Times(AnyNumber()); httpauth_manager_.reset(new HttpAuthManagerImpl(&client_)); EXPECT_CALL(*store_, IsAbleToSavePasswords()).WillRepeatedly(Return(true)); ON_CALL(client_, AutofillHttpAuth(_, _)) .WillByDefault( Invoke(httpauth_manager_.get(), &HttpAuthManagerImpl::Autofill)); } void TearDown() override { store_->ShutdownOnUIThread(); store_ = nullptr; } HttpAuthManagerImpl* httpauth_manager() { return httpauth_manager_.get(); } base::test::TaskEnvironment task_environment_; scoped_refptr<MockPasswordStore> store_; testing::NiceMock<MockPasswordManagerClient> client_; std::unique_ptr<HttpAuthManagerImpl> httpauth_manager_; }; TEST_F(HttpAuthManagerTest, HttpAuthFilling) { for (bool filling_enabled : {false, true}) { SCOPED_TRACE(testing::Message("filling_enabled=") << filling_enabled); EXPECT_CALL(client_, IsFillingEnabled(_)) .WillRepeatedly(Return(filling_enabled)); PasswordForm observed_form; observed_form.scheme = PasswordForm::Scheme::kBasic; observed_form.origin = GURL("http://proxy.com/"); observed_form.signon_realm = "proxy.com/realm"; PasswordForm stored_form = observed_form; stored_form.username_value = ASCIIToUTF16("user"); stored_form.password_value = ASCIIToUTF16("1234"); MockHttpAuthObserver observer; PasswordStoreConsumer* consumer = nullptr; EXPECT_CALL(*store_, GetLogins(_, _)).WillOnce(SaveArg<1>(&consumer)); httpauth_manager()->SetObserverAndDeliverCredentials(&observer, observed_form); EXPECT_CALL(observer, OnAutofillDataAvailable(ASCIIToUTF16("user"), ASCIIToUTF16("1234"))) .Times(filling_enabled); ASSERT_TRUE(consumer); std::vector<std::unique_ptr<PasswordForm>> result; result.push_back(std::make_unique<PasswordForm>(stored_form)); consumer->OnGetPasswordStoreResults(std::move(result)); testing::Mock::VerifyAndClearExpectations(&store_); httpauth_manager()->DetachObserver(&observer); } } TEST_F(HttpAuthManagerTest, HttpAuthSaving) { for (bool filling_and_saving_enabled : {true, false}) { SCOPED_TRACE(testing::Message("filling_and_saving_enabled=") << filling_and_saving_enabled); EXPECT_CALL(client_, IsSavingAndFillingEnabled(_)) .WillRepeatedly(Return(filling_and_saving_enabled)); PasswordForm observed_form; observed_form.scheme = PasswordForm::Scheme::kBasic; observed_form.origin = GURL("http://proxy.com/"); observed_form.signon_realm = "proxy.com/realm"; MockHttpAuthObserver observer; EXPECT_CALL(*store_, GetLogins(_, _)) .WillRepeatedly(WithArg<1>(InvokeEmptyConsumerWithForms())); // Initiate creating a form manager. httpauth_manager()->SetObserverAndDeliverCredentials(&observer, observed_form); // Emulate that http auth credentials submitted. PasswordForm submitted_form = observed_form; submitted_form.username_value = ASCIIToUTF16("user"); submitted_form.password_value = ASCIIToUTF16("1234"); httpauth_manager()->OnPasswordFormSubmitted(submitted_form); httpauth_manager()->OnPasswordFormDismissed(); // Expect save prompt on successful submission. std::unique_ptr<PasswordFormManagerForUI> form_manager_to_save; EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr()) .Times(filling_and_saving_enabled ? 1 : 0); httpauth_manager()->OnDidFinishMainFrameNavigation(); testing::Mock::VerifyAndClearExpectations(&client_); httpauth_manager()->DetachObserver(&observer); } } TEST_F(HttpAuthManagerTest, NavigationWithoutSubmission) { EXPECT_CALL(client_, IsSavingAndFillingEnabled(_)) .WillRepeatedly(Return(true)); PasswordForm observed_form; observed_form.scheme = PasswordForm::Scheme::kBasic; observed_form.origin = GURL("http://proxy.com/"); observed_form.signon_realm = "proxy.com/realm"; MockHttpAuthObserver observer; EXPECT_CALL(*store_, GetLogins(_, _)) .WillRepeatedly(WithArg<1>(InvokeEmptyConsumerWithForms())); // Initiate creating a form manager. httpauth_manager()->SetObserverAndDeliverCredentials(&observer, observed_form); // Expect no prompt, since no submission was happened. EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr()).Times(0); httpauth_manager()->OnDidFinishMainFrameNavigation(); httpauth_manager()->DetachObserver(&observer); } TEST_F(HttpAuthManagerTest, NavigationWhenMatchingNotReady) { EXPECT_CALL(client_, IsSavingAndFillingEnabled).WillRepeatedly(Return(true)); PasswordForm observed_form; observed_form.scheme = PasswordForm::Scheme::kBasic; observed_form.origin = GURL("http://proxy.com/"); observed_form.signon_realm = "proxy.com/realm"; MockHttpAuthObserver observer; // The password store is queried but it's slow and won't respond. EXPECT_CALL(*store_, GetLogins); // Initiate creating a form manager. httpauth_manager()->SetObserverAndDeliverCredentials(&observer, observed_form); PasswordForm submitted_form = observed_form; submitted_form.username_value = ASCIIToUTF16("user"); submitted_form.password_value = ASCIIToUTF16("1234"); httpauth_manager()->OnPasswordFormSubmitted(submitted_form); httpauth_manager()->OnPasswordFormDismissed(); // Expect no prompt as the password store didn't reply. EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr()).Times(0); httpauth_manager()->OnDidFinishMainFrameNavigation(); httpauth_manager()->DetachObserver(&observer); } } // namespace password_manager
Java
# VIVO: Connect, Share, Discover [![Build](https://github.com/vivo-project/VIVO/workflows/Build/badge.svg)](https://github.com/vivo-project/VIVO/actions?query=workflow%3ABuild) [![Deploy](https://github.com/vivo-project/VIVO/workflows/Deploy/badge.svg)](https://github.com/vivo-project/VIVO/actions?query=workflow%3ADeploy) [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.2639714.svg)](https://doi.org/10.5281/zenodo.2639713) VIVO is an open source semantic web tool for research discovery -- finding people and the research they do. VIVO supports editing, searching, browsing and visualizing research activity in order to discover people, programs, facilities, funding, scholarly works and events. VIVO's search returns results faceted by type for rapid retrieval of desired information across disciplines. ## Resources ### VIVO Project web site http://vivoweb.org/ ### VIVO Project Wiki https://wiki.lyrasis.org/display/VIVO/ ### Installation Instructions Installation instructions for the latest release can be found at this location on the wiki: https://wiki.lyrasis.org/display/VIVODOC112x/Installing+VIVO ### Docker VIVO docker container is available at [vivoweb/vivo](https://hub.docker.com/repository/docker/vivoweb/vivo) with accompanying [vivoweb/vivo-solr](https://hub.docker.com/repository/docker/vivoweb/vivo-solr). These can be used independently or with docker-compose. ### Docker Compose Docker Compose environment variables: .env defaults ``` LOCAL_VIVO_HOME=./vivo-home RESET_HOME=false RESET_CORE=false ``` - `LOCAL_VIVO_HOME`: VIVO home directory on your host machine which will mount to volume in docker container. Set this environment variable to persist your VIVO data on your host machine. - `RESET_HOME`: Convenience to reset VIVO home when starting container. **Caution**, will delete local configuration, content, and configuration model. - `RESET_CORE`: Convenience to reset VIVO Solr core when starting container. **Caution**, will require complete reindex. Before building VIVO, you will also need to clone (and switch to the same branch, if other than main) of [Vitro](https://github.com/vivo-project/Vitro). The Vitro project must be cloned to a sibling directory next to VIVO so that it can be found during the build. You will also need to clone (and switch to the appropriate branch) of [Vitro-languages](https://github.com/vivo-project/Vitro-languages) and [VIVO-languages](https://github.com/vivo-project/VIVO-languages). Build and start VIVO. 1. In Vitro-languages, run: ``` mvn install ``` 2. In VIVO-languages, run: ``` mvn install ``` 3. In VIVO (with Vitro cloned alongside it), run: ``` mvn clean package -s installer/example-settings.xml docker-compose up ``` ### Docker Image To build and run local Docker image. ``` docker build -t vivoweb/vivo:development . docker run -p 8080:8080 vivoweb/vivo:development ``` ## Contact us There are several ways to contact the VIVO community. Whatever your interest, we would be pleased to hear from you. ### Contact form http://vivoweb.org/support/user-feedback ### Mailing lists #### [vivo-all](https://groups.google.com/forum/#!forum/vivo-all) This updates list provides news to the VIVO community of interest to all. #### [vivo-community](https://groups.google.com/forum/#!forum/vivo-community) Join the VIVO community! Here you'll find non-technical discussion regarding participation, the VIVO conference, policy, project management, outreach, and engagement. #### [vivo-tech](https://groups.google.com/forum/#!forum/vivo-tech) The best place to get your hands dirty in the VIVO Project. Developers and implementers frequent this list to get the latest on feature design, development, implementation, and testing. ## Contributing Code If you would like to contribute code to the VIVO project, please open a ticket in our [JIRA](https://jira.lyrasis.org/projects/VIVO), and prepare a pull request that references your ticket. Contributors welcome! ## Citing VIVO If you are using VIVO in your publications or projects, please cite the software paper in the Journal of Open Source Software: * Conlon et al., (2019). VIVO: a system for research discovery. Journal of Open Source Software, 4(39), 1182, https://doi.org/10.21105/joss.01182 ### BibTeX ```tex @article{Conlon2019, doi = {10.21105/joss.01182}, url = {https://doi.org/10.21105/joss.01182}, year = {2019}, publisher = {The Open Journal}, volume = {4}, number = {39}, pages = {1182}, author = {Michael Conlon and Andrew Woods and Graham Triggs and Ralph O'Flinn and Muhammad Javed and Jim Blake and Benjamin Gross and Qazi Asim Ijaz Ahmad and Sabih Ali and Martin Barber and Don Elsborg and Kitio Fofack and Christian Hauschke and Violeta Ilik and Huda Khan and Ted Lawless and Jacob Levernier and Brian Lowe and Jose Martin and Steve McKay and Simon Porter and Tatiana Walther and Marijane White and Stefan Wolff and Rebecca Younes}, title = {{VIVO}: a system for research discovery}, journal = {Journal of Open Source Software} }
Java
#!/bin/bash # define helpers source_dir=~/.osx-bootstrap if [[ ! -f ~/.ssh/id_rsa ]]; then echo '' echo '##### Please enter your github username: ' read github_user echo '##### Please enter your github email address: ' read github_email # setup github if [[ $github_user && $github_email ]]; then # setup config git config --global user.name $github_user git config --global user.email $github_email git config --global github.user $github_user git config --global github.token your_token_here git config --global color.ui true git config --global push.default current # sublime support # git config --global core.editor "subl -w" # set rsa key curl -s -O http://github-media-downloads.s3.amazonaws.com/osx/git-credential-osxkeychain chmod u+x git-credential-osxkeychain sudo mv git-credential-osxkeychain "$(dirname $(which git))/git-credential-osxkeychain" git config --global credential.helper osxkeychain # generate ssh key cd ~/.ssh ssh-keygen -t rsa -C $github_email pbcopy < ~/.ssh/id_rsa.pub echo '' echo '##### The following rsa key has been copied to your clipboard: ' cat ~/.ssh/id_rsa.pub echo '##### Follow step 4 to complete: https://help.github.com/articles/generating-ssh-keys' ssh -T git@github.com fi fi
Java
#if !(NET35 || NET20 || WINDOWS_PHONE) using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace Newtonsoft.Json.Utilities { internal sealed class DynamicProxyMetaObject<T> : DynamicMetaObject { private readonly DynamicProxy<T> _proxy; private readonly bool _dontFallbackFirst; internal DynamicProxyMetaObject(Expression expression, T value, DynamicProxy<T> proxy, bool dontFallbackFirst) : base(expression, BindingRestrictions.Empty, value) { _proxy = proxy; _dontFallbackFirst = dontFallbackFirst; } private new T Value { get { return (T)base.Value; } } private bool IsOverridden(string method) { return _proxy.GetType().GetMember(method, MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance).Cast<MethodInfo>() .Any(info => // check that the method overrides the original on DynamicObjectProxy info.DeclaringType != typeof(DynamicProxy<T>) && info.GetBaseDefinition().DeclaringType == typeof(DynamicProxy<T>)); } public override DynamicMetaObject BindGetMember(GetMemberBinder binder) { return IsOverridden("TryGetMember") ? CallMethodWithResult("TryGetMember", binder, NoArgs, e => binder.FallbackGetMember(this, e)) : base.BindGetMember(binder); } public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) { return IsOverridden("TrySetMember") ? CallMethodReturnLast("TrySetMember", binder, GetArgs(value), e => binder.FallbackSetMember(this, value, e)) : base.BindSetMember(binder, value); } public override DynamicMetaObject BindDeleteMember(DeleteMemberBinder binder) { return IsOverridden("TryDeleteMember") ? CallMethodNoResult("TryDeleteMember", binder, NoArgs, e => binder.FallbackDeleteMember(this, e)) : base.BindDeleteMember(binder); } public override DynamicMetaObject BindConvert(ConvertBinder binder) { return IsOverridden("TryConvert") ? CallMethodWithResult("TryConvert", binder, NoArgs, e => binder.FallbackConvert(this, e)) : base.BindConvert(binder); } public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) { if (!IsOverridden("TryInvokeMember")) return base.BindInvokeMember(binder, args); // // Generate a tree like: // // { // object result; // TryInvokeMember(payload, out result) // ? result // : TryGetMember(payload, out result) // ? FallbackInvoke(result) // : fallbackResult // } // // Then it calls FallbackInvokeMember with this tree as the // "error", giving the language the option of using this // tree or doing .NET binding. // Fallback fallback = e => binder.FallbackInvokeMember(this, args, e); DynamicMetaObject call = BuildCallMethodWithResult( "TryInvokeMember", binder, GetArgArray(args), BuildCallMethodWithResult( "TryGetMember", new GetBinderAdapter(binder), NoArgs, fallback(null), e => binder.FallbackInvoke(e, args, null) ), null ); return _dontFallbackFirst ? call : fallback(call); } public override DynamicMetaObject BindCreateInstance(CreateInstanceBinder binder, DynamicMetaObject[] args) { return IsOverridden("TryCreateInstance") ? CallMethodWithResult("TryCreateInstance", binder, GetArgArray(args), e => binder.FallbackCreateInstance(this, args, e)) : base.BindCreateInstance(binder, args); } public override DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args) { return IsOverridden("TryInvoke") ? CallMethodWithResult("TryInvoke", binder, GetArgArray(args), e => binder.FallbackInvoke(this, args, e)) : base.BindInvoke(binder, args); } public override DynamicMetaObject BindBinaryOperation(BinaryOperationBinder binder, DynamicMetaObject arg) { return IsOverridden("TryBinaryOperation") ? CallMethodWithResult("TryBinaryOperation", binder, GetArgs(arg), e => binder.FallbackBinaryOperation(this, arg, e)) : base.BindBinaryOperation(binder, arg); } public override DynamicMetaObject BindUnaryOperation(UnaryOperationBinder binder) { return IsOverridden("TryUnaryOperation") ? CallMethodWithResult("TryUnaryOperation", binder, NoArgs, e => binder.FallbackUnaryOperation(this, e)) : base.BindUnaryOperation(binder); } public override DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes) { return IsOverridden("TryGetIndex") ? CallMethodWithResult("TryGetIndex", binder, GetArgArray(indexes), e => binder.FallbackGetIndex(this, indexes, e)) : base.BindGetIndex(binder, indexes); } public override DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value) { return IsOverridden("TrySetIndex") ? CallMethodReturnLast("TrySetIndex", binder, GetArgArray(indexes, value), e => binder.FallbackSetIndex(this, indexes, value, e)) : base.BindSetIndex(binder, indexes, value); } public override DynamicMetaObject BindDeleteIndex(DeleteIndexBinder binder, DynamicMetaObject[] indexes) { return IsOverridden("TryDeleteIndex") ? CallMethodNoResult("TryDeleteIndex", binder, GetArgArray(indexes), e => binder.FallbackDeleteIndex(this, indexes, e)) : base.BindDeleteIndex(binder, indexes); } private delegate DynamicMetaObject Fallback(DynamicMetaObject errorSuggestion); private readonly static Expression[] NoArgs = new Expression[0]; private static Expression[] GetArgs(params DynamicMetaObject[] args) { return args.Select(arg => Expression.Convert(arg.Expression, typeof(object))).ToArray(); } private static Expression[] GetArgArray(DynamicMetaObject[] args) { return new[] { Expression.NewArrayInit(typeof(object), GetArgs(args)) }; } private static Expression[] GetArgArray(DynamicMetaObject[] args, DynamicMetaObject value) { return new Expression[] { Expression.NewArrayInit(typeof(object), GetArgs(args)), Expression.Convert(value.Expression, typeof(object)) }; } private static ConstantExpression Constant(DynamicMetaObjectBinder binder) { Type t = binder.GetType(); while (!t.IsVisible) t = t.BaseType; return Expression.Constant(binder, t); } /// <summary> /// Helper method for generating a MetaObject which calls a /// specific method on Dynamic that returns a result /// </summary> private DynamicMetaObject CallMethodWithResult(string methodName, DynamicMetaObjectBinder binder, Expression[] args, Fallback fallback, Fallback fallbackInvoke = null) { // // First, call fallback to do default binding // This produces either an error or a call to a .NET member // DynamicMetaObject fallbackResult = fallback(null); DynamicMetaObject callDynamic = BuildCallMethodWithResult(methodName, binder, args, fallbackResult, fallbackInvoke); // // Now, call fallback again using our new MO as the error // When we do this, one of two things can happen: // 1. Binding will succeed, and it will ignore our call to // the dynamic method, OR // 2. Binding will fail, and it will use the MO we created // above. // return _dontFallbackFirst ? callDynamic : fallback(callDynamic); } private DynamicMetaObject BuildCallMethodWithResult(string methodName, DynamicMetaObjectBinder binder, Expression[] args, DynamicMetaObject fallbackResult, Fallback fallbackInvoke) { // // Build a new expression like: // { // object result; // TryGetMember(payload, out result) ? fallbackInvoke(result) : fallbackResult // } // ParameterExpression result = Expression.Parameter(typeof(object), null); IList<Expression> callArgs = new List<Expression>(); callArgs.Add(Expression.Convert(Expression, typeof(T))); callArgs.Add(Constant(binder)); callArgs.AddRange(args); callArgs.Add(result); DynamicMetaObject resultMetaObject = new DynamicMetaObject(result, BindingRestrictions.Empty); // Need to add a conversion if calling TryConvert if (binder.ReturnType != typeof (object)) { UnaryExpression convert = Expression.Convert(resultMetaObject.Expression, binder.ReturnType); // will always be a cast or unbox resultMetaObject = new DynamicMetaObject(convert, resultMetaObject.Restrictions); } if (fallbackInvoke != null) resultMetaObject = fallbackInvoke(resultMetaObject); DynamicMetaObject callDynamic = new DynamicMetaObject( Expression.Block( new[] {result}, Expression.Condition( Expression.Call( Expression.Constant(_proxy), typeof(DynamicProxy<T>).GetMethod(methodName), callArgs ), resultMetaObject.Expression, fallbackResult.Expression, binder.ReturnType ) ), GetRestrictions().Merge(resultMetaObject.Restrictions).Merge(fallbackResult.Restrictions) ); return callDynamic; } /// <summary> /// Helper method for generating a MetaObject which calls a /// specific method on Dynamic, but uses one of the arguments for /// the result. /// </summary> private DynamicMetaObject CallMethodReturnLast(string methodName, DynamicMetaObjectBinder binder, Expression[] args, Fallback fallback) { // // First, call fallback to do default binding // This produces either an error or a call to a .NET member // DynamicMetaObject fallbackResult = fallback(null); // // Build a new expression like: // { // object result; // TrySetMember(payload, result = value) ? result : fallbackResult // } // ParameterExpression result = Expression.Parameter(typeof(object), null); IList<Expression> callArgs = new List<Expression>(); callArgs.Add(Expression.Convert(Expression, typeof (T))); callArgs.Add(Constant(binder)); callArgs.AddRange(args); callArgs[args.Length + 1] = Expression.Assign(result, callArgs[args.Length + 1]); DynamicMetaObject callDynamic = new DynamicMetaObject( Expression.Block( new[] { result }, Expression.Condition( Expression.Call( Expression.Constant(_proxy), typeof(DynamicProxy<T>).GetMethod(methodName), callArgs ), result, fallbackResult.Expression, typeof(object) ) ), GetRestrictions().Merge(fallbackResult.Restrictions) ); // // Now, call fallback again using our new MO as the error // When we do this, one of two things can happen: // 1. Binding will succeed, and it will ignore our call to // the dynamic method, OR // 2. Binding will fail, and it will use the MO we created // above. // return _dontFallbackFirst ? callDynamic : fallback(callDynamic); } /// <summary> /// Helper method for generating a MetaObject which calls a /// specific method on Dynamic, but uses one of the arguments for /// the result. /// </summary> private DynamicMetaObject CallMethodNoResult(string methodName, DynamicMetaObjectBinder binder, Expression[] args, Fallback fallback) { // // First, call fallback to do default binding // This produces either an error or a call to a .NET member // DynamicMetaObject fallbackResult = fallback(null); IList<Expression> callArgs = new List<Expression>(); callArgs.Add(Expression.Convert(Expression, typeof(T))); callArgs.Add(Constant(binder)); callArgs.AddRange(args); // // Build a new expression like: // if (TryDeleteMember(payload)) { } else { fallbackResult } // DynamicMetaObject callDynamic = new DynamicMetaObject( Expression.Condition( Expression.Call( Expression.Constant(_proxy), typeof(DynamicProxy<T>).GetMethod(methodName), callArgs ), Expression.Empty(), fallbackResult.Expression, typeof (void) ), GetRestrictions().Merge(fallbackResult.Restrictions) ); // // Now, call fallback again using our new MO as the error // When we do this, one of two things can happen: // 1. Binding will succeed, and it will ignore our call to // the dynamic method, OR // 2. Binding will fail, and it will use the MO we created // above. // return _dontFallbackFirst ? callDynamic : fallback(callDynamic); } /// <summary> /// Returns a Restrictions object which includes our current restrictions merged /// with a restriction limiting our type /// </summary> private BindingRestrictions GetRestrictions() { return (Value == null && HasValue) ? BindingRestrictions.GetInstanceRestriction(Expression, null) : BindingRestrictions.GetTypeRestriction(Expression, LimitType); } public override IEnumerable<string> GetDynamicMemberNames() { return _proxy.GetDynamicMemberNames(Value); } // It is okay to throw NotSupported from this binder. This object // is only used by DynamicObject.GetMember--it is not expected to // (and cannot) implement binding semantics. It is just so the DO // can use the Name and IgnoreCase properties. private sealed class GetBinderAdapter : GetMemberBinder { internal GetBinderAdapter(InvokeMemberBinder binder) : base(binder.Name, binder.IgnoreCase) { } public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion) { throw new NotSupportedException(); } } } } #endif
Java
/* config.h. Generated from config.h.in by configure. */ /* config.h.in. Generated from configure.in by autoheader. */ /* Whether to build xhprof as dynamic module */ #define COMPILE_DL_XHPROF 1 /* Define to 1 if you have the <dlfcn.h> header file. */ #define HAVE_DLFCN_H 1 /* Define to 1 if you have the <inttypes.h> header file. */ #define HAVE_INTTYPES_H 1 /* Define to 1 if you have the <memory.h> header file. */ #define HAVE_MEMORY_H 1 /* Define to 1 if you have the <stdint.h> header file. */ #define HAVE_STDINT_H 1 /* Define to 1 if you have the <stdlib.h> header file. */ #define HAVE_STDLIB_H 1 /* Define to 1 if you have the <strings.h> header file. */ #define HAVE_STRINGS_H 1 /* Define to 1 if you have the <string.h> header file. */ #define HAVE_STRING_H 1 /* Define to 1 if you have the <sys/stat.h> header file. */ #define HAVE_SYS_STAT_H 1 /* Define to 1 if you have the <sys/types.h> header file. */ #define HAVE_SYS_TYPES_H 1 /* Define to 1 if you have the <unistd.h> header file. */ #define HAVE_UNISTD_H 1 /* Define to 1 if your C compiler doesn't accept -c and -o together. */ /* #undef NO_MINUS_C_MINUS_O */ /* Define to the address where bug reports for this package should be sent. */ #define PACKAGE_BUGREPORT "" /* Define to the full name of this package. */ #define PACKAGE_NAME "" /* Define to the full name and version of this package. */ #define PACKAGE_STRING "" /* Define to the one symbol short name of this package. */ #define PACKAGE_TARNAME "" /* Define to the version of this package. */ #define PACKAGE_VERSION "" /* Define to 1 if you have the ANSI C header files. */ #define STDC_HEADERS 1
Java
''' Given a number, find the next higher number using only the digits in the given number. For example if the given number is 1234, next higher number with same digits is 1243 ''' def FindNext(num): number = str(num) length = len(number) for i in range(length-2,-1,-1): current = number[i] right = number[i+1] if current < right: temp = sorted(number[i:]) Next = temp[temp.index(current)+1] temp.remove(Next) temp = ''.join(temp) return int(number[:i]+Next+temp) return num
Java
package manifest import ( "encoding/json" "fmt" "log" "reflect" "regexp" "strconv" "strings" "github.com/fatih/color" "github.com/servehub/serve/manifest/processor" "github.com/servehub/utils" "github.com/servehub/utils/gabs" ) type Manifest struct { tree *gabs.Container } func (m Manifest) String() string { return m.tree.StringIndent("", " ") } func (m Manifest) Unwrap() interface{} { return m.tree.Data() } func (m Manifest) Has(path string) bool { v := m.tree.Path(path).Data() return v != nil && v != "" } func (m Manifest) GetString(path string) string { return fmt.Sprintf("%v", m.tree.Path(path).Data()) } func (m Manifest) GetStringOr(path string, defaultVal string) string { if m.tree.ExistsP(path) { return m.GetString(path) } return defaultVal } func (m Manifest) GetFloat(path string) float64 { f, err := strconv.ParseFloat(m.GetString(path), 64) if err != nil { log.Fatalf("Error on parse float64 '%v' from: %v", path, m.GetString(path)) } return f } func (m Manifest) GetInt(path string) int { i, err := strconv.Atoi(m.GetString(path)) if err != nil { log.Fatalf("Error on parse integer '%v' from: %v", path, m.GetString(path)) } return i } func (m Manifest) GetIntOr(path string, defaultVal int) int { if m.tree.ExistsP(path) { return m.GetInt(path) } return defaultVal } func (m Manifest) GetBool(path string) bool { return strings.ToLower(m.GetString(path)) == "true" } func (m Manifest) GetMap(path string) map[string]Manifest { out := make(map[string]Manifest) tree := m.tree if len(path) > 0 && path != "." && path != "/" { tree = m.tree.Path(path) } mmap, err := tree.ChildrenMap() if err != nil { log.Fatalf("Error get map '%v' from: %v. Error: %s", path, m.tree.Path(path).Data(), err) } for k, v := range mmap { out[k] = Manifest{v} } return out } func (m Manifest) GetArray(path string) []Manifest { out := make([]Manifest, 0) arr, err := m.tree.Path(path).Children() if err != nil { log.Fatalf("Error get array `%v` from: %v", path, m.tree.Path(path).Data()) } for _, v := range arr { out = append(out, Manifest{v}) } return out } func (m Manifest) GetArrayForce(path string) []interface{} { out := make([]interface{}, 0) arr, err := m.tree.Path(path).Children() if err != nil && m.tree.ExistsP(path) { arr = append(arr, m.tree.Path(path)) } for _, v := range arr { out = append(out, v.Data()) } return out } func (m Manifest) GetTree(path string) Manifest { return Manifest{m.tree.Path(path)} } func (m Manifest) Set(path string, value interface{}) { m.tree.SetP(value, path) } func (m Manifest) ArrayAppend(path string, value interface{}) { m.tree.ArrayAppendP(value, path) } func (m Manifest) FindPlugins(plugin string) ([]PluginData, error) { tree := m.tree.Path(plugin) result := make([]PluginData, 0) if tree.Data() == nil { return nil, fmt.Errorf("Plugin `%s` not found in manifest!", plugin) } if _, ok := tree.Data().([]interface{}); ok { arr, _ := tree.Children() for _, item := range arr { if _, ok := item.Data().(string); ok { result = append(result, makePluginPair(plugin, item)) } else if res, err := item.ChildrenMap(); err == nil { if len(res) == 1 { for subplugin, data := range res { result = append(result, makePluginPair(plugin+"."+subplugin, data)) break } } else if len(res) == 0 && !PluginRegestry.Has(plugin) { // skip subplugin with empty data } else { result = append(result, makePluginPair(plugin, item)) } } } } else if PluginRegestry.Has(plugin) { result = append(result, makePluginPair(plugin, tree)) } else { log.Println(color.YellowString("Plugins for `%s` section not specified, skip...", plugin)) } return result, nil } func (m Manifest) DelTree(path string) error { return m.tree.DeleteP(path) } func (m Manifest) GetPluginWithData(plugin string) PluginData { return makePluginPair(plugin, m.tree) } var envNameRegex = regexp.MustCompile("\\W") func (m Manifest) ToEnvMap(prefix string) map[string]string { result := make(map[string]string) if children, err := m.tree.ChildrenMap(); err == nil { for k, child := range children { result = utils.MergeMaps(result, Manifest{child}.ToEnvMap(prefix+strings.ToUpper(envNameRegex.ReplaceAllString(k, "_"))+"_")) } } else if children, err := m.tree.Children(); err == nil { for i, child := range children { result = utils.MergeMaps(result, Manifest{child}.ToEnvMap(prefix+strconv.Itoa(i)+"_")) } } else if m.tree.Data() != nil { result[prefix[:len(prefix)-1]] = fmt.Sprintf("%v", m.tree.Data()) } return result } func Load(path string, vars map[string]string) *Manifest { tree, err := gabs.LoadYamlFile(path) if err != nil { log.Fatalln("Error on load file:", err) } for k, v := range vars { tree.Set(v, "vars", k) } for _, proc := range processor.GetAll() { if err := proc.Process(tree); err != nil { log.Fatalf("Error in processor '%v': %v. \n\nManifest: %s", reflect.ValueOf(proc).Type().Name(), err, tree.StringIndent("", " ")) } } return &Manifest{tree} } func LoadJSON(path string) *Manifest { tree, err := gabs.ParseJSONFile(path) if err != nil { log.Fatalf("Error on load json file '%s': %v\n", path, err) } return &Manifest{tree} } func ParseJSON(json string) *Manifest { tree, err := gabs.ParseJSON([]byte(json)) if err != nil { log.Fatalf("Error on parse json '%s': %v\n", json, err) } return &Manifest{tree} } func makePluginPair(plugin string, data *gabs.Container) PluginData { if s, ok := data.Data().(string); ok { obj := gabs.New() ns := strings.Split(plugin, ".") obj.Set(s, ns[len(ns)-1]) data = obj } else { var cpy interface{} bs, _ := json.Marshal(data.Data()) json.Unmarshal(bs, &cpy) data.Set(cpy) } return PluginData{plugin, PluginRegestry.Get(plugin), Manifest{data}} }
Java