code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
<?php $array = new SplDoublyLinkedList( ); $get = $array->offsetGet( 'fail' ); ?>
JSchwehn/php
testdata/fuzzdir/corpus/ext_spl_tests_SplDoublyLinkedList_offsetGet_param_string.php
PHP
bsd-3-clause
85
""" exec_command Implements exec_command function that is (almost) equivalent to commands.getstatusoutput function but on NT, DOS systems the returned status is actually correct (though, the returned status values may be different by a factor). In addition, exec_command takes keyword arguments for (re-)defining environment variables. Provides functions: exec_command --- execute command in a specified directory and in the modified environment. find_executable --- locate a command using info from environment variable PATH. Equivalent to posix `which` command. Author: Pearu Peterson <pearu@cens.ioc.ee> Created: 11 January 2003 Requires: Python 2.x Successfully tested on: ======== ============ ================================================= os.name sys.platform comments ======== ============ ================================================= posix linux2 Debian (sid) Linux, Python 2.1.3+, 2.2.3+, 2.3.3 PyCrust 0.9.3, Idle 1.0.2 posix linux2 Red Hat 9 Linux, Python 2.1.3, 2.2.2, 2.3.2 posix sunos5 SunOS 5.9, Python 2.2, 2.3.2 posix darwin Darwin 7.2.0, Python 2.3 nt win32 Windows Me Python 2.3(EE), Idle 1.0, PyCrust 0.7.2 Python 2.1.1 Idle 0.8 nt win32 Windows 98, Python 2.1.1. Idle 0.8 nt win32 Cygwin 98-4.10, Python 2.1.1(MSC) - echo tests fail i.e. redefining environment variables may not work. FIXED: don't use cygwin echo! Comment: also `cmd /c echo` will not work but redefining environment variables do work. posix cygwin Cygwin 98-4.10, Python 2.3.3(cygming special) nt win32 Windows XP, Python 2.3.3 ======== ============ ================================================= Known bugs: * Tests, that send messages to stderr, fail when executed from MSYS prompt because the messages are lost at some point. """ from __future__ import division, absolute_import, print_function __all__ = ['exec_command', 'find_executable'] import os import sys import subprocess import locale import warnings from numpy.distutils.misc_util import is_sequence, make_temp_file from numpy.distutils import log def filepath_from_subprocess_output(output): """ Convert `bytes` in the encoding used by a subprocess into a filesystem-appropriate `str`. Inherited from `exec_command`, and possibly incorrect. """ mylocale = locale.getpreferredencoding(False) if mylocale is None: mylocale = 'ascii' output = output.decode(mylocale, errors='replace') output = output.replace('\r\n', '\n') # Another historical oddity if output[-1:] == '\n': output = output[:-1] # stdio uses bytes in python 2, so to avoid issues, we simply # remove all non-ascii characters if sys.version_info < (3, 0): output = output.encode('ascii', errors='replace') return output def forward_bytes_to_stdout(val): """ Forward bytes from a subprocess call to the console, without attempting to decode them. The assumption is that the subprocess call already returned bytes in a suitable encoding. """ if sys.version_info.major < 3: # python 2 has binary output anyway sys.stdout.write(val) elif hasattr(sys.stdout, 'buffer'): # use the underlying binary output if there is one sys.stdout.buffer.write(val) elif hasattr(sys.stdout, 'encoding'): # round-trip the encoding if necessary sys.stdout.write(val.decode(sys.stdout.encoding)) else: # make a best-guess at the encoding sys.stdout.write(val.decode('utf8', errors='replace')) def temp_file_name(): # 2019-01-30, 1.17 warnings.warn('temp_file_name is deprecated since NumPy v1.17, use ' 'tempfile.mkstemp instead', DeprecationWarning, stacklevel=1) fo, name = make_temp_file() fo.close() return name def get_pythonexe(): pythonexe = sys.executable if os.name in ['nt', 'dos']: fdir, fn = os.path.split(pythonexe) fn = fn.upper().replace('PYTHONW', 'PYTHON') pythonexe = os.path.join(fdir, fn) assert os.path.isfile(pythonexe), '%r is not a file' % (pythonexe,) return pythonexe def find_executable(exe, path=None, _cache={}): """Return full path of a executable or None. Symbolic links are not followed. """ key = exe, path try: return _cache[key] except KeyError: pass log.debug('find_executable(%r)' % exe) orig_exe = exe if path is None: path = os.environ.get('PATH', os.defpath) if os.name=='posix': realpath = os.path.realpath else: realpath = lambda a:a if exe.startswith('"'): exe = exe[1:-1] suffixes = [''] if os.name in ['nt', 'dos', 'os2']: fn, ext = os.path.splitext(exe) extra_suffixes = ['.exe', '.com', '.bat'] if ext.lower() not in extra_suffixes: suffixes = extra_suffixes if os.path.isabs(exe): paths = [''] else: paths = [ os.path.abspath(p) for p in path.split(os.pathsep) ] for path in paths: fn = os.path.join(path, exe) for s in suffixes: f_ext = fn+s if not os.path.islink(f_ext): f_ext = realpath(f_ext) if os.path.isfile(f_ext) and os.access(f_ext, os.X_OK): log.info('Found executable %s' % f_ext) _cache[key] = f_ext return f_ext log.warn('Could not locate executable %s' % orig_exe) return None ############################################################ def _preserve_environment( names ): log.debug('_preserve_environment(%r)' % (names)) env = {name: os.environ.get(name) for name in names} return env def _update_environment( **env ): log.debug('_update_environment(...)') for name, value in env.items(): os.environ[name] = value or '' def exec_command(command, execute_in='', use_shell=None, use_tee=None, _with_python = 1, **env ): """ Return (status,output) of executed command. .. deprecated:: 1.17 Use subprocess.Popen instead Parameters ---------- command : str A concatenated string of executable and arguments. execute_in : str Before running command ``cd execute_in`` and after ``cd -``. use_shell : {bool, None}, optional If True, execute ``sh -c command``. Default None (True) use_tee : {bool, None}, optional If True use tee. Default None (True) Returns ------- res : str Both stdout and stderr messages. Notes ----- On NT, DOS systems the returned status is correct for external commands. Wild cards will not work for non-posix systems or when use_shell=0. """ # 2019-01-30, 1.17 warnings.warn('exec_command is deprecated since NumPy v1.17, use ' 'subprocess.Popen instead', DeprecationWarning, stacklevel=1) log.debug('exec_command(%r,%s)' % (command,\ ','.join(['%s=%r'%kv for kv in env.items()]))) if use_tee is None: use_tee = os.name=='posix' if use_shell is None: use_shell = os.name=='posix' execute_in = os.path.abspath(execute_in) oldcwd = os.path.abspath(os.getcwd()) if __name__[-12:] == 'exec_command': exec_dir = os.path.dirname(os.path.abspath(__file__)) elif os.path.isfile('exec_command.py'): exec_dir = os.path.abspath('.') else: exec_dir = os.path.abspath(sys.argv[0]) if os.path.isfile(exec_dir): exec_dir = os.path.dirname(exec_dir) if oldcwd!=execute_in: os.chdir(execute_in) log.debug('New cwd: %s' % execute_in) else: log.debug('Retaining cwd: %s' % oldcwd) oldenv = _preserve_environment( list(env.keys()) ) _update_environment( **env ) try: st = _exec_command(command, use_shell=use_shell, use_tee=use_tee, **env) finally: if oldcwd!=execute_in: os.chdir(oldcwd) log.debug('Restored cwd to %s' % oldcwd) _update_environment(**oldenv) return st def _exec_command(command, use_shell=None, use_tee = None, **env): """ Internal workhorse for exec_command(). """ if use_shell is None: use_shell = os.name=='posix' if use_tee is None: use_tee = os.name=='posix' if os.name == 'posix' and use_shell: # On POSIX, subprocess always uses /bin/sh, override sh = os.environ.get('SHELL', '/bin/sh') if is_sequence(command): command = [sh, '-c', ' '.join(command)] else: command = [sh, '-c', command] use_shell = False elif os.name == 'nt' and is_sequence(command): # On Windows, join the string for CreateProcess() ourselves as # subprocess does it a bit differently command = ' '.join(_quote_arg(arg) for arg in command) # Inherit environment by default env = env or None try: # universal_newlines is set to False so that communicate() # will return bytes. We need to decode the output ourselves # so that Python will not raise a UnicodeDecodeError when # it encounters an invalid character; rather, we simply replace it proc = subprocess.Popen(command, shell=use_shell, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=False) except EnvironmentError: # Return 127, as os.spawn*() and /bin/sh do return 127, '' text, err = proc.communicate() mylocale = locale.getpreferredencoding(False) if mylocale is None: mylocale = 'ascii' text = text.decode(mylocale, errors='replace') text = text.replace('\r\n', '\n') # Another historical oddity if text[-1:] == '\n': text = text[:-1] # stdio uses bytes in python 2, so to avoid issues, we simply # remove all non-ascii characters if sys.version_info < (3, 0): text = text.encode('ascii', errors='replace') if use_tee and text: print(text) return proc.returncode, text def _quote_arg(arg): """ Quote the argument for safe use in a shell command line. """ # If there is a quote in the string, assume relevants parts of the # string are already quoted (e.g. '-I"C:\\Program Files\\..."') if '"' not in arg and ' ' in arg: return '"%s"' % arg return arg ############################################################
shoyer/numpy
numpy/distutils/exec_command.py
Python
bsd-3-clause
10,919
// ========================================================================== // Project: SproutCore - JavaScript Application Framework // Copyright: ©2006-2011 Strobe Inc. and contributors. // Portions ©2008-2011 Apple Inc. All rights reserved. // License: Licensed under MIT license (see license.js) // ==========================================================================
darkrsw/safe
tests/clone_detector_tests/sproutcore/frameworks/bootstrap/core.js
JavaScript
bsd-3-clause
398
# -*- coding: utf-8 -*- """ wakatime.dependencies.haxe ~~~~~~~~~~~~~~~~~~~~~~~~~~ Parse dependencies from Haxe code. :copyright: (c) 2018 Alan Hamlett. :license: BSD, see LICENSE for more details. """ from . import TokenParser class HaxeParser(TokenParser): exclude = [ r'^haxe$', ] state = None def parse(self): for index, token, content in self.tokens: self._process_token(token, content) return self.dependencies def _process_token(self, token, content): if self.partial(token) == 'Namespace': self._process_namespace(token, content) elif self.partial(token) == 'Text': self._process_text(token, content) else: self._process_other(token, content) def _process_namespace(self, token, content): if self.state == 'import': self.append(self._format(content)) self.state = None else: self.state = content def _process_text(self, token, content): pass def _process_other(self, token, content): self.state = None def _format(self, content): return content.strip()
wakatime/wakatime
wakatime/dependencies/haxe.py
Python
bsd-3-clause
1,199
// 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 "media/video/capture/linux/video_capture_device_linux.h" #if defined(OS_OPENBSD) #include <sys/videoio.h> #else #include <linux/videodev2.h> #endif #include <list> #include "base/bind.h" #include "base/strings/stringprintf.h" #include "media/video/capture/linux/v4l2_capture_delegate.h" namespace media { // USB VID and PID are both 4 bytes long. static const size_t kVidPidSize = 4; // /sys/class/video4linux/video{N}/device is a symlink to the corresponding // USB device info directory. static const char kVidPathTemplate[] = "/sys/class/video4linux/%s/device/../idVendor"; static const char kPidPathTemplate[] = "/sys/class/video4linux/%s/device/../idProduct"; static bool ReadIdFile(const std::string path, std::string* id) { char id_buf[kVidPidSize]; FILE* file = fopen(path.c_str(), "rb"); if (!file) return false; const bool success = fread(id_buf, kVidPidSize, 1, file) == 1; fclose(file); if (!success) return false; id->append(id_buf, kVidPidSize); return true; } // Translates Video4Linux pixel formats to Chromium pixel formats. // static VideoPixelFormat VideoCaptureDeviceLinux::V4l2FourCcToChromiumPixelFormat( uint32 v4l2_fourcc) { return V4L2CaptureDelegate::V4l2FourCcToChromiumPixelFormat(v4l2_fourcc); } // Gets a list of usable Four CC formats prioritised. // static std::list<uint32_t> VideoCaptureDeviceLinux::GetListOfUsableFourCCs( bool favour_mjpeg) { return V4L2CaptureDelegate::GetListOfUsableFourCcs(favour_mjpeg); } const std::string VideoCaptureDevice::Name::GetModel() const { // |unique_id| is of the form "/dev/video2". |file_name| is "video2". const std::string dev_dir = "/dev/"; DCHECK_EQ(0, unique_id_.compare(0, dev_dir.length(), dev_dir)); const std::string file_name = unique_id_.substr(dev_dir.length(), unique_id_.length()); const std::string vidPath = base::StringPrintf(kVidPathTemplate, file_name.c_str()); const std::string pidPath = base::StringPrintf(kPidPathTemplate, file_name.c_str()); std::string usb_id; if (!ReadIdFile(vidPath, &usb_id)) return ""; usb_id.append(":"); if (!ReadIdFile(pidPath, &usb_id)) return ""; return usb_id; } VideoCaptureDeviceLinux::VideoCaptureDeviceLinux(const Name& device_name) : v4l2_thread_("V4L2CaptureThread"), device_name_(device_name) { } VideoCaptureDeviceLinux::~VideoCaptureDeviceLinux() { // Check if the thread is running. // This means that the device has not been StopAndDeAllocate()d properly. DCHECK(!v4l2_thread_.IsRunning()); v4l2_thread_.Stop(); } void VideoCaptureDeviceLinux::AllocateAndStart( const VideoCaptureParams& params, scoped_ptr<VideoCaptureDevice::Client> client) { DCHECK(!capture_impl_); if (v4l2_thread_.IsRunning()) return; // Wrong state. v4l2_thread_.Start(); const int line_frequency = TranslatePowerLineFrequencyToV4L2(GetPowerLineFrequencyForLocation()); capture_impl_ = V4L2CaptureDelegate::CreateV4L2CaptureDelegate( device_name_, v4l2_thread_.message_loop_proxy(), line_frequency); if (!capture_impl_) { client->OnError("Failed to create VideoCaptureDelegate"); return; } v4l2_thread_.message_loop()->PostTask( FROM_HERE, base::Bind(&V4L2CaptureDelegate::AllocateAndStart, capture_impl_, params.requested_format.frame_size.width(), params.requested_format.frame_size.height(), params.requested_format.frame_rate, base::Passed(&client))); } void VideoCaptureDeviceLinux::StopAndDeAllocate() { if (!v4l2_thread_.IsRunning()) return; // Wrong state. v4l2_thread_.message_loop()->PostTask( FROM_HERE, base::Bind(&V4L2CaptureDelegate::StopAndDeAllocate, capture_impl_)); v4l2_thread_.Stop(); capture_impl_ = NULL; } void VideoCaptureDeviceLinux::SetRotation(int rotation) { if (v4l2_thread_.IsRunning()) { v4l2_thread_.message_loop()->PostTask( FROM_HERE, base::Bind(&V4L2CaptureDelegate::SetRotation, capture_impl_, rotation)); } } // static int VideoCaptureDeviceLinux::TranslatePowerLineFrequencyToV4L2(int frequency) { switch (frequency) { case kPowerLine50Hz: return V4L2_CID_POWER_LINE_FREQUENCY_50HZ; case kPowerLine60Hz: return V4L2_CID_POWER_LINE_FREQUENCY_60HZ; default: // If we have no idea of the frequency, at least try and set it to AUTO. return V4L2_CID_POWER_LINE_FREQUENCY_AUTO; } } } // namespace media
guorendong/iridium-browser-ubuntu
media/video/capture/linux/video_capture_device_linux.cc
C++
bsd-3-clause
4,680
<?php /* * 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. * * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. For more information, see * <http://www.doctrine-project.org>. */ namespace Doctrine\ORM; use Exception; use Doctrine\Common\EventManager; use Doctrine\Common\Persistence\ObjectManager; use Doctrine\DBAL\Connection; use Doctrine\DBAL\LockMode; use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\Mapping\ClassMetadataFactory; use Doctrine\ORM\Query\ResultSetMapping; use Doctrine\ORM\Proxy\ProxyFactory; use Doctrine\ORM\Query\FilterCollection; use Doctrine\Common\Util\ClassUtils; /** * The EntityManager is the central access point to ORM functionality. * * It is a facade to all different ORM subsystems such as UnitOfWork, * Query Language and Repository API. Instantiation is done through * the static create() method. The quickest way to obtain a fully * configured EntityManager is: * * use Doctrine\ORM\Tools\Setup; * use Doctrine\ORM\EntityManager; * * $paths = array('/path/to/entity/mapping/files'); * * $config = Setup::createAnnotationMetadataConfiguration($paths); * $dbParams = array('driver' => 'pdo_sqlite', 'memory' => true); * $entityManager = EntityManager::create($dbParams, $config); * * For more information see * {@link http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/configuration.html} * * You should never attempt to inherit from the EntityManager: Inheritance * is not a valid extension point for the EntityManager. Instead you * should take a look at the {@see \Doctrine\ORM\Decorator\EntityManagerDecorator} * and wrap your entity manager in a decorator. * * @since 2.0 * @author Benjamin Eberlei <kontakt@beberlei.de> * @author Guilherme Blanco <guilhermeblanco@hotmail.com> * @author Jonathan Wage <jonwage@gmail.com> * @author Roman Borschel <roman@code-factory.org> */ /* final */class EntityManager implements EntityManagerInterface { /** * The used Configuration. * * @var \Doctrine\ORM\Configuration */ private $config; /** * The database connection used by the EntityManager. * * @var \Doctrine\DBAL\Connection */ private $conn; /** * The metadata factory, used to retrieve the ORM metadata of entity classes. * * @var \Doctrine\ORM\Mapping\ClassMetadataFactory */ private $metadataFactory; /** * The UnitOfWork used to coordinate object-level transactions. * * @var \Doctrine\ORM\UnitOfWork */ private $unitOfWork; /** * The event manager that is the central point of the event system. * * @var \Doctrine\Common\EventManager */ private $eventManager; /** * The proxy factory used to create dynamic proxies. * * @var \Doctrine\ORM\Proxy\ProxyFactory */ private $proxyFactory; /** * The repository factory used to create dynamic repositories. * * @var \Doctrine\ORM\Repository\RepositoryFactory */ private $repositoryFactory; /** * The expression builder instance used to generate query expressions. * * @var \Doctrine\ORM\Query\Expr */ private $expressionBuilder; /** * Whether the EntityManager is closed or not. * * @var bool */ private $closed = false; /** * Collection of query filters. * * @var \Doctrine\ORM\Query\FilterCollection */ private $filterCollection; /** * Creates a new EntityManager that operates on the given database connection * and uses the given Configuration and EventManager implementations. * * @param \Doctrine\DBAL\Connection $conn * @param \Doctrine\ORM\Configuration $config * @param \Doctrine\Common\EventManager $eventManager */ protected function __construct(Connection $conn, Configuration $config, EventManager $eventManager) { $this->conn = $conn; $this->config = $config; $this->eventManager = $eventManager; $metadataFactoryClassName = $config->getClassMetadataFactoryName(); $this->metadataFactory = new $metadataFactoryClassName; $this->metadataFactory->setEntityManager($this); $this->metadataFactory->setCacheDriver($this->config->getMetadataCacheImpl()); $this->repositoryFactory = $config->getRepositoryFactory(); $this->unitOfWork = new UnitOfWork($this); $this->proxyFactory = new ProxyFactory( $this, $config->getProxyDir(), $config->getProxyNamespace(), $config->getAutoGenerateProxyClasses() ); } /** * {@inheritDoc} */ public function getConnection() { return $this->conn; } /** * Gets the metadata factory used to gather the metadata of classes. * * @return \Doctrine\ORM\Mapping\ClassMetadataFactory */ public function getMetadataFactory() { return $this->metadataFactory; } /** * {@inheritDoc} */ public function getExpressionBuilder() { if ($this->expressionBuilder === null) { $this->expressionBuilder = new Query\Expr; } return $this->expressionBuilder; } /** * {@inheritDoc} */ public function beginTransaction() { $this->conn->beginTransaction(); } /** * {@inheritDoc} */ public function transactional($func) { if (!is_callable($func)) { throw new \InvalidArgumentException('Expected argument of type "callable", got "' . gettype($func) . '"'); } $this->conn->beginTransaction(); try { $return = call_user_func($func, $this); $this->flush(); $this->conn->commit(); return $return ?: true; } catch (Exception $e) { $this->close(); $this->conn->rollback(); throw $e; } } /** * {@inheritDoc} */ public function commit() { $this->conn->commit(); } /** * {@inheritDoc} */ public function rollback() { $this->conn->rollback(); } /** * Returns the ORM metadata descriptor for a class. * * The class name must be the fully-qualified class name without a leading backslash * (as it is returned by get_class($obj)) or an aliased class name. * * Examples: * MyProject\Domain\User * sales:PriceRequest * * @param string $className * * @return \Doctrine\ORM\Mapping\ClassMetadata * * @internal Performance-sensitive method. */ public function getClassMetadata($className) { return $this->metadataFactory->getMetadataFor($className); } /** * {@inheritDoc} */ public function createQuery($dql = '') { $query = new Query($this); if ( ! empty($dql)) { $query->setDql($dql); } return $query; } /** * {@inheritDoc} */ public function createNamedQuery($name) { return $this->createQuery($this->config->getNamedQuery($name)); } /** * {@inheritDoc} */ public function createNativeQuery($sql, ResultSetMapping $rsm) { $query = new NativeQuery($this); $query->setSql($sql); $query->setResultSetMapping($rsm); return $query; } /** * {@inheritDoc} */ public function createNamedNativeQuery($name) { list($sql, $rsm) = $this->config->getNamedNativeQuery($name); return $this->createNativeQuery($sql, $rsm); } /** * {@inheritDoc} */ public function createQueryBuilder() { return new QueryBuilder($this); } /** * Flushes all changes to objects that have been queued up to now to the database. * This effectively synchronizes the in-memory state of managed objects with the * database. * * If an entity is explicitly passed to this method only this entity and * the cascade-persist semantics + scheduled inserts/removals are synchronized. * * @param null|object|array $entity * * @return void * * @throws \Doctrine\ORM\OptimisticLockException If a version check on an entity that * makes use of optimistic locking fails. */ public function flush($entity = null) { $this->errorIfClosed(); $this->unitOfWork->commit($entity); } /** * Finds an Entity by its identifier. * * @param string $entityName * @param mixed $id * @param integer $lockMode * @param integer|null $lockVersion * * @return object|null The entity instance or NULL if the entity can not be found. * * @throws OptimisticLockException * @throws ORMInvalidArgumentException * @throws TransactionRequiredException * @throws ORMException */ public function find($entityName, $id, $lockMode = LockMode::NONE, $lockVersion = null) { $class = $this->metadataFactory->getMetadataFor(ltrim($entityName, '\\')); if (is_object($id) && $this->metadataFactory->hasMetadataFor(ClassUtils::getClass($id))) { $id = $this->unitOfWork->getSingleIdentifierValue($id); if ($id === null) { throw ORMInvalidArgumentException::invalidIdentifierBindingEntity(); } } if ( ! is_array($id)) { $id = array($class->identifier[0] => $id); } $sortedId = array(); foreach ($class->identifier as $identifier) { if ( ! isset($id[$identifier])) { throw ORMException::missingIdentifierField($class->name, $identifier); } $sortedId[$identifier] = $id[$identifier]; } $unitOfWork = $this->getUnitOfWork(); // Check identity map first if (($entity = $unitOfWork->tryGetById($sortedId, $class->rootEntityName)) !== false) { if ( ! ($entity instanceof $class->name)) { return null; } switch ($lockMode) { case LockMode::OPTIMISTIC: $this->lock($entity, $lockMode, $lockVersion); break; case LockMode::PESSIMISTIC_READ: case LockMode::PESSIMISTIC_WRITE: $persister = $unitOfWork->getEntityPersister($class->name); $persister->refresh($sortedId, $entity, $lockMode); break; } return $entity; // Hit! } $persister = $unitOfWork->getEntityPersister($class->name); switch ($lockMode) { case LockMode::NONE: return $persister->load($sortedId); case LockMode::OPTIMISTIC: if ( ! $class->isVersioned) { throw OptimisticLockException::notVersioned($class->name); } $entity = $persister->load($sortedId); $unitOfWork->lock($entity, $lockMode, $lockVersion); return $entity; default: if ( ! $this->getConnection()->isTransactionActive()) { throw TransactionRequiredException::transactionRequired(); } return $persister->load($sortedId, null, null, array(), $lockMode); } } /** * {@inheritDoc} */ public function getReference($entityName, $id) { $class = $this->metadataFactory->getMetadataFor(ltrim($entityName, '\\')); if ( ! is_array($id)) { $id = array($class->identifier[0] => $id); } $sortedId = array(); foreach ($class->identifier as $identifier) { if ( ! isset($id[$identifier])) { throw ORMException::missingIdentifierField($class->name, $identifier); } $sortedId[$identifier] = $id[$identifier]; } // Check identity map first, if its already in there just return it. if (($entity = $this->unitOfWork->tryGetById($sortedId, $class->rootEntityName)) !== false) { return ($entity instanceof $class->name) ? $entity : null; } if ($class->subClasses) { return $this->find($entityName, $sortedId); } if ( ! is_array($sortedId)) { $sortedId = array($class->identifier[0] => $sortedId); } $entity = $this->proxyFactory->getProxy($class->name, $sortedId); $this->unitOfWork->registerManaged($entity, $sortedId, array()); return $entity; } /** * {@inheritDoc} */ public function getPartialReference($entityName, $identifier) { $class = $this->metadataFactory->getMetadataFor(ltrim($entityName, '\\')); // Check identity map first, if its already in there just return it. if (($entity = $this->unitOfWork->tryGetById($identifier, $class->rootEntityName)) !== false) { return ($entity instanceof $class->name) ? $entity : null; } if ( ! is_array($identifier)) { $identifier = array($class->identifier[0] => $identifier); } $entity = $class->newInstance(); $class->setIdentifierValues($entity, $identifier); $this->unitOfWork->registerManaged($entity, $identifier, array()); $this->unitOfWork->markReadOnly($entity); return $entity; } /** * Clears the EntityManager. All entities that are currently managed * by this EntityManager become detached. * * @param string|null $entityName if given, only entities of this type will get detached * * @return void */ public function clear($entityName = null) { $this->unitOfWork->clear($entityName); } /** * {@inheritDoc} */ public function close() { $this->clear(); $this->closed = true; } /** * Tells the EntityManager to make an instance managed and persistent. * * The entity will be entered into the database at or before transaction * commit or as a result of the flush operation. * * NOTE: The persist operation always considers entities that are not yet known to * this EntityManager as NEW. Do not pass detached entities to the persist operation. * * @param object $entity The instance to make managed and persistent. * * @return void * * @throws ORMInvalidArgumentException */ public function persist($entity) { if ( ! is_object($entity)) { throw ORMInvalidArgumentException::invalidObject('EntityManager#persist()' , $entity); } $this->errorIfClosed(); $this->unitOfWork->persist($entity); } /** * Removes an entity instance. * * A removed entity will be removed from the database at or before transaction commit * or as a result of the flush operation. * * @param object $entity The entity instance to remove. * * @return void * * @throws ORMInvalidArgumentException */ public function remove($entity) { if ( ! is_object($entity)) { throw ORMInvalidArgumentException::invalidObject('EntityManager#remove()' , $entity); } $this->errorIfClosed(); $this->unitOfWork->remove($entity); } /** * Refreshes the persistent state of an entity from the database, * overriding any local changes that have not yet been persisted. * * @param object $entity The entity to refresh. * * @return void * * @throws ORMInvalidArgumentException */ public function refresh($entity) { if ( ! is_object($entity)) { throw ORMInvalidArgumentException::invalidObject('EntityManager#refresh()' , $entity); } $this->errorIfClosed(); $this->unitOfWork->refresh($entity); } /** * Detaches an entity from the EntityManager, causing a managed entity to * become detached. Unflushed changes made to the entity if any * (including removal of the entity), will not be synchronized to the database. * Entities which previously referenced the detached entity will continue to * reference it. * * @param object $entity The entity to detach. * * @return void * * @throws ORMInvalidArgumentException */ public function detach($entity) { if ( ! is_object($entity)) { throw ORMInvalidArgumentException::invalidObject('EntityManager#detach()' , $entity); } $this->unitOfWork->detach($entity); } /** * Merges the state of a detached entity into the persistence context * of this EntityManager and returns the managed copy of the entity. * The entity passed to merge will not become associated/managed with this EntityManager. * * @param object $entity The detached entity to merge into the persistence context. * * @return object The managed copy of the entity. * * @throws ORMInvalidArgumentException */ public function merge($entity) { if ( ! is_object($entity)) { throw ORMInvalidArgumentException::invalidObject('EntityManager#merge()' , $entity); } $this->errorIfClosed(); return $this->unitOfWork->merge($entity); } /** * {@inheritDoc} * * @todo Implementation need. This is necessary since $e2 = clone $e1; throws an E_FATAL when access anything on $e: * Fatal error: Maximum function nesting level of '100' reached, aborting! */ public function copy($entity, $deep = false) { throw new \BadMethodCallException("Not implemented."); } /** * {@inheritDoc} */ public function lock($entity, $lockMode, $lockVersion = null) { $this->unitOfWork->lock($entity, $lockMode, $lockVersion); } /** * Gets the repository for an entity class. * * @param string $entityName The name of the entity. * * @return \Doctrine\ORM\EntityRepository The repository class. */ public function getRepository($entityName) { return $this->repositoryFactory->getRepository($this, $entityName); } /** * Determines whether an entity instance is managed in this EntityManager. * * @param object $entity * * @return boolean TRUE if this EntityManager currently manages the given entity, FALSE otherwise. */ public function contains($entity) { return $this->unitOfWork->isScheduledForInsert($entity) || $this->unitOfWork->isInIdentityMap($entity) && ! $this->unitOfWork->isScheduledForDelete($entity); } /** * {@inheritDoc} */ public function getEventManager() { return $this->eventManager; } /** * {@inheritDoc} */ public function getConfiguration() { return $this->config; } /** * Throws an exception if the EntityManager is closed or currently not active. * * @return void * * @throws ORMException If the EntityManager is closed. */ private function errorIfClosed() { if ($this->closed) { throw ORMException::entityManagerClosed(); } } /** * {@inheritDoc} */ public function isOpen() { return (!$this->closed); } /** * {@inheritDoc} */ public function getUnitOfWork() { return $this->unitOfWork; } /** * {@inheritDoc} */ public function getHydrator($hydrationMode) { return $this->newHydrator($hydrationMode); } /** * {@inheritDoc} */ public function newHydrator($hydrationMode) { switch ($hydrationMode) { case Query::HYDRATE_OBJECT: return new Internal\Hydration\ObjectHydrator($this); case Query::HYDRATE_ARRAY: return new Internal\Hydration\ArrayHydrator($this); case Query::HYDRATE_SCALAR: return new Internal\Hydration\ScalarHydrator($this); case Query::HYDRATE_SINGLE_SCALAR: return new Internal\Hydration\SingleScalarHydrator($this); case Query::HYDRATE_SIMPLEOBJECT: return new Internal\Hydration\SimpleObjectHydrator($this); default: if (($class = $this->config->getCustomHydrationMode($hydrationMode)) !== null) { return new $class($this); } } throw ORMException::invalidHydrationMode($hydrationMode); } /** * {@inheritDoc} */ public function getProxyFactory() { return $this->proxyFactory; } /** * {@inheritDoc} */ public function initializeObject($obj) { $this->unitOfWork->initializeObject($obj); } /** * Factory method to create EntityManager instances. * * @param mixed $conn An array with the connection parameters or an existing Connection instance. * @param Configuration $config The Configuration instance to use. * @param EventManager $eventManager The EventManager instance to use. * * @return EntityManager The created EntityManager. * * @throws \InvalidArgumentException * @throws ORMException */ public static function create($conn, Configuration $config, EventManager $eventManager = null) { if ( ! $config->getMetadataDriverImpl()) { throw ORMException::missingMappingDriverImpl(); } switch (true) { case (is_array($conn)): $conn = \Doctrine\DBAL\DriverManager::getConnection( $conn, $config, ($eventManager ?: new EventManager()) ); break; case ($conn instanceof Connection): if ($eventManager !== null && $conn->getEventManager() !== $eventManager) { throw ORMException::mismatchedEventManager(); } break; default: throw new \InvalidArgumentException("Invalid argument: " . $conn); } return new EntityManager($conn, $config, $conn->getEventManager()); } /** * {@inheritDoc} */ public function getFilters() { if (null === $this->filterCollection) { $this->filterCollection = new FilterCollection($this); } return $this->filterCollection; } /** * {@inheritDoc} */ public function isFiltersStateClean() { return null === $this->filterCollection || $this->filterCollection->isClean(); } /** * {@inheritDoc} */ public function hasFilters() { return null !== $this->filterCollection; } }
351784144/DhtvWeiXin
vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php
PHP
bsd-3-clause
24,823
""" Oracle database backend for Django. Requires cx_Oracle: http://cx-oracle.sourceforge.net/ """ from __future__ import unicode_literals import decimal import re import sys import warnings def _setup_environment(environ): import platform # Cygwin requires some special voodoo to set the environment variables # properly so that Oracle will see them. if platform.system().upper().startswith('CYGWIN'): try: import ctypes except ImportError as e: from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured("Error loading ctypes: %s; " "the Oracle backend requires ctypes to " "operate correctly under Cygwin." % e) kernel32 = ctypes.CDLL('kernel32') for name, value in environ: kernel32.SetEnvironmentVariableA(name, value) else: import os os.environ.update(environ) _setup_environment([ # Oracle takes client-side character set encoding from the environment. ('NLS_LANG', '.UTF8'), # This prevents unicode from getting mangled by getting encoded into the # potentially non-unicode database character set. ('ORA_NCHAR_LITERAL_REPLACE', 'TRUE'), ]) try: import cx_Oracle as Database except ImportError as e: from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured("Error loading cx_Oracle module: %s" % e) try: import pytz except ImportError: pytz = None from django.db import utils from django.db.backends import * from django.db.backends.oracle.client import DatabaseClient from django.db.backends.oracle.creation import DatabaseCreation from django.db.backends.oracle.introspection import DatabaseIntrospection from django.utils.encoding import force_bytes, force_text DatabaseError = Database.DatabaseError IntegrityError = Database.IntegrityError # Check whether cx_Oracle was compiled with the WITH_UNICODE option if cx_Oracle is pre-5.1. This will # also be True for cx_Oracle 5.1 and in Python 3.0. See #19606 if int(Database.version.split('.', 1)[0]) >= 5 and \ (int(Database.version.split('.', 2)[1]) >= 1 or not hasattr(Database, 'UNICODE')): convert_unicode = force_text else: convert_unicode = force_bytes class DatabaseFeatures(BaseDatabaseFeatures): empty_fetchmany_value = () needs_datetime_string_cast = False interprets_empty_strings_as_nulls = True uses_savepoints = True has_select_for_update = True has_select_for_update_nowait = True can_return_id_from_insert = True allow_sliced_subqueries = False supports_subqueries_in_group_by = False supports_transactions = True supports_timezones = False has_zoneinfo_database = pytz is not None supports_bitwise_or = False can_defer_constraint_checks = True ignores_nulls_in_unique_constraints = False has_bulk_insert = True supports_tablespaces = True supports_sequence_reset = False atomic_transactions = False class DatabaseOperations(BaseDatabaseOperations): compiler_module = "django.db.backends.oracle.compiler" def autoinc_sql(self, table, column): # To simulate auto-incrementing primary keys in Oracle, we have to # create a sequence and a trigger. sq_name = self._get_sequence_name(table) tr_name = self._get_trigger_name(table) tbl_name = self.quote_name(table) col_name = self.quote_name(column) sequence_sql = """ DECLARE i INTEGER; BEGIN SELECT COUNT(*) INTO i FROM USER_CATALOG WHERE TABLE_NAME = '%(sq_name)s' AND TABLE_TYPE = 'SEQUENCE'; IF i = 0 THEN EXECUTE IMMEDIATE 'CREATE SEQUENCE "%(sq_name)s"'; END IF; END; /""" % locals() trigger_sql = """ CREATE OR REPLACE TRIGGER "%(tr_name)s" BEFORE INSERT ON %(tbl_name)s FOR EACH ROW WHEN (new.%(col_name)s IS NULL) BEGIN SELECT "%(sq_name)s".nextval INTO :new.%(col_name)s FROM dual; END; /""" % locals() return sequence_sql, trigger_sql def cache_key_culling_sql(self): return """ SELECT cache_key FROM (SELECT cache_key, rank() OVER (ORDER BY cache_key) AS rank FROM %s) WHERE rank = %%s + 1 """ def date_extract_sql(self, lookup_type, field_name): if lookup_type == 'week_day': # TO_CHAR(field, 'D') returns an integer from 1-7, where 1=Sunday. return "TO_CHAR(%s, 'D')" % field_name else: # http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions050.htm return "EXTRACT(%s FROM %s)" % (lookup_type.upper(), field_name) def date_interval_sql(self, sql, connector, timedelta): """ Implements the interval functionality for expressions format for Oracle: (datefield + INTERVAL '3 00:03:20.000000' DAY(1) TO SECOND(6)) """ minutes, seconds = divmod(timedelta.seconds, 60) hours, minutes = divmod(minutes, 60) days = str(timedelta.days) day_precision = len(days) fmt = "(%s %s INTERVAL '%s %02d:%02d:%02d.%06d' DAY(%d) TO SECOND(6))" return fmt % (sql, connector, days, hours, minutes, seconds, timedelta.microseconds, day_precision) def date_trunc_sql(self, lookup_type, field_name): # http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions230.htm#i1002084 if lookup_type in ('year', 'month'): return "TRUNC(%s, '%s')" % (field_name, lookup_type.upper()) else: return "TRUNC(%s)" % field_name # Oracle crashes with "ORA-03113: end-of-file on communication channel" # if the time zone name is passed in parameter. Use interpolation instead. # https://groups.google.com/forum/#!msg/django-developers/zwQju7hbG78/9l934yelwfsJ # This regexp matches all time zone names from the zoneinfo database. _tzname_re = re.compile(r'^[\w/:+-]+$') def _convert_field_to_tz(self, field_name, tzname): if not self._tzname_re.match(tzname): raise ValueError("Invalid time zone name: %s" % tzname) # Convert from UTC to local time, returning TIMESTAMP WITH TIME ZONE. result = "(FROM_TZ(%s, '0:00') AT TIME ZONE '%s')" % (field_name, tzname) # Extracting from a TIMESTAMP WITH TIME ZONE ignore the time zone. # Convert to a DATETIME, which is called DATE by Oracle. There's no # built-in function to do that; the easiest is to go through a string. result = "TO_CHAR(%s, 'YYYY-MM-DD HH24:MI:SS')" % result result = "TO_DATE(%s, 'YYYY-MM-DD HH24:MI:SS')" % result # Re-convert to a TIMESTAMP because EXTRACT only handles the date part # on DATE values, even though they actually store the time part. return "CAST(%s AS TIMESTAMP)" % result def datetime_extract_sql(self, lookup_type, field_name, tzname): if settings.USE_TZ: field_name = self._convert_field_to_tz(field_name, tzname) if lookup_type == 'week_day': # TO_CHAR(field, 'D') returns an integer from 1-7, where 1=Sunday. sql = "TO_CHAR(%s, 'D')" % field_name else: # http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions050.htm sql = "EXTRACT(%s FROM %s)" % (lookup_type.upper(), field_name) return sql, [] def datetime_trunc_sql(self, lookup_type, field_name, tzname): if settings.USE_TZ: field_name = self._convert_field_to_tz(field_name, tzname) # http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions230.htm#i1002084 if lookup_type in ('year', 'month'): sql = "TRUNC(%s, '%s')" % (field_name, lookup_type.upper()) elif lookup_type == 'day': sql = "TRUNC(%s)" % field_name elif lookup_type == 'hour': sql = "TRUNC(%s, 'HH24')" % field_name elif lookup_type == 'minute': sql = "TRUNC(%s, 'MI')" % field_name else: sql = field_name # Cast to DATE removes sub-second precision. return sql, [] def convert_values(self, value, field): if isinstance(value, Database.LOB): value = value.read() if field and field.get_internal_type() == 'TextField': value = force_text(value) # Oracle stores empty strings as null. We need to undo this in # order to adhere to the Django convention of using the empty # string instead of null, but only if the field accepts the # empty string. if value is None and field and field.empty_strings_allowed: value = '' # Convert 1 or 0 to True or False elif value in (1, 0) and field and field.get_internal_type() in ('BooleanField', 'NullBooleanField'): value = bool(value) # Force floats to the correct type elif value is not None and field and field.get_internal_type() == 'FloatField': value = float(value) # Convert floats to decimals elif value is not None and field and field.get_internal_type() == 'DecimalField': value = util.typecast_decimal(field.format_number(value)) # cx_Oracle always returns datetime.datetime objects for # DATE and TIMESTAMP columns, but Django wants to see a # python datetime.date, .time, or .datetime. We use the type # of the Field to determine which to cast to, but it's not # always available. # As a workaround, we cast to date if all the time-related # values are 0, or to time if the date is 1/1/1900. # This could be cleaned a bit by adding a method to the Field # classes to normalize values from the database (the to_python # method is used for validation and isn't what we want here). elif isinstance(value, Database.Timestamp): if field and field.get_internal_type() == 'DateTimeField': pass elif field and field.get_internal_type() == 'DateField': value = value.date() elif field and field.get_internal_type() == 'TimeField' or (value.year == 1900 and value.month == value.day == 1): value = value.time() elif value.hour == value.minute == value.second == value.microsecond == 0: value = value.date() return value def deferrable_sql(self): return " DEFERRABLE INITIALLY DEFERRED" def drop_sequence_sql(self, table): return "DROP SEQUENCE %s;" % self.quote_name(self._get_sequence_name(table)) def fetch_returned_insert_id(self, cursor): return int(cursor._insert_id_var.getvalue()) def field_cast_sql(self, db_type, internal_type): if db_type and db_type.endswith('LOB'): return "DBMS_LOB.SUBSTR(%s)" else: return "%s" def last_executed_query(self, cursor, sql, params): # http://cx-oracle.sourceforge.net/html/cursor.html#Cursor.statement # The DB API definition does not define this attribute. statement = cursor.statement if statement and six.PY2 and not isinstance(statement, unicode): statement = statement.decode('utf-8') # Unlike Psycopg's `query` and MySQLdb`'s `_last_executed`, CxOracle's # `statement` doesn't contain the query parameters. refs #20010. return super(DatabaseOperations, self).last_executed_query(cursor, statement, params) def last_insert_id(self, cursor, table_name, pk_name): sq_name = self._get_sequence_name(table_name) cursor.execute('SELECT "%s".currval FROM dual' % sq_name) return cursor.fetchone()[0] def lookup_cast(self, lookup_type): if lookup_type in ('iexact', 'icontains', 'istartswith', 'iendswith'): return "UPPER(%s)" return "%s" def max_in_list_size(self): return 1000 def max_name_length(self): return 30 def prep_for_iexact_query(self, x): return x def process_clob(self, value): if value is None: return '' return force_text(value.read()) def quote_name(self, name): # SQL92 requires delimited (quoted) names to be case-sensitive. When # not quoted, Oracle has case-insensitive behavior for identifiers, but # always defaults to uppercase. # We simplify things by making Oracle identifiers always uppercase. if not name.startswith('"') and not name.endswith('"'): name = '"%s"' % util.truncate_name(name.upper(), self.max_name_length()) # Oracle puts the query text into a (query % args) construct, so % signs # in names need to be escaped. The '%%' will be collapsed back to '%' at # that stage so we aren't really making the name longer here. name = name.replace('%','%%') return name.upper() def random_function_sql(self): return "DBMS_RANDOM.RANDOM" def regex_lookup_9(self, lookup_type): raise NotImplementedError("Regexes are not supported in Oracle before version 10g.") def regex_lookup_10(self, lookup_type): if lookup_type == 'regex': match_option = "'c'" else: match_option = "'i'" return 'REGEXP_LIKE(%%s, %%s, %s)' % match_option def regex_lookup(self, lookup_type): # If regex_lookup is called before it's been initialized, then create # a cursor to initialize it and recur. self.connection.cursor() return self.connection.ops.regex_lookup(lookup_type) def return_insert_id(self): return "RETURNING %s INTO %%s", (InsertIdVar(),) def savepoint_create_sql(self, sid): return convert_unicode("SAVEPOINT " + self.quote_name(sid)) def savepoint_rollback_sql(self, sid): return convert_unicode("ROLLBACK TO SAVEPOINT " + self.quote_name(sid)) def sql_flush(self, style, tables, sequences, allow_cascade=False): # Return a list of 'TRUNCATE x;', 'TRUNCATE y;', # 'TRUNCATE z;'... style SQL statements if tables: # Oracle does support TRUNCATE, but it seems to get us into # FK referential trouble, whereas DELETE FROM table works. sql = ['%s %s %s;' % ( style.SQL_KEYWORD('DELETE'), style.SQL_KEYWORD('FROM'), style.SQL_FIELD(self.quote_name(table)) ) for table in tables] # Since we've just deleted all the rows, running our sequence # ALTER code will reset the sequence to 0. sql.extend(self.sequence_reset_by_name_sql(style, sequences)) return sql else: return [] def sequence_reset_by_name_sql(self, style, sequences): sql = [] for sequence_info in sequences: sequence_name = self._get_sequence_name(sequence_info['table']) table_name = self.quote_name(sequence_info['table']) column_name = self.quote_name(sequence_info['column'] or 'id') query = _get_sequence_reset_sql() % {'sequence': sequence_name, 'table': table_name, 'column': column_name} sql.append(query) return sql def sequence_reset_sql(self, style, model_list): from django.db import models output = [] query = _get_sequence_reset_sql() for model in model_list: for f in model._meta.local_fields: if isinstance(f, models.AutoField): table_name = self.quote_name(model._meta.db_table) sequence_name = self._get_sequence_name(model._meta.db_table) column_name = self.quote_name(f.column) output.append(query % {'sequence': sequence_name, 'table': table_name, 'column': column_name}) # Only one AutoField is allowed per model, so don't # continue to loop break for f in model._meta.many_to_many: if not f.rel.through: table_name = self.quote_name(f.m2m_db_table()) sequence_name = self._get_sequence_name(f.m2m_db_table()) column_name = self.quote_name('id') output.append(query % {'sequence': sequence_name, 'table': table_name, 'column': column_name}) return output def start_transaction_sql(self): return '' def tablespace_sql(self, tablespace, inline=False): if inline: return "USING INDEX TABLESPACE %s" % self.quote_name(tablespace) else: return "TABLESPACE %s" % self.quote_name(tablespace) def value_to_db_datetime(self, value): if value is None: return None # Oracle doesn't support tz-aware datetimes if timezone.is_aware(value): if settings.USE_TZ: value = value.astimezone(timezone.utc).replace(tzinfo=None) else: raise ValueError("Oracle backend does not support timezone-aware datetimes when USE_TZ is False.") return six.text_type(value) def value_to_db_time(self, value): if value is None: return None if isinstance(value, six.string_types): return datetime.datetime.strptime(value, '%H:%M:%S') # Oracle doesn't support tz-aware times if timezone.is_aware(value): raise ValueError("Oracle backend does not support timezone-aware times.") return datetime.datetime(1900, 1, 1, value.hour, value.minute, value.second, value.microsecond) def year_lookup_bounds_for_date_field(self, value): first = '%s-01-01' second = '%s-12-31' return [first % value, second % value] def year_lookup_bounds_for_datetime_field(self, value): # The default implementation uses datetime objects for the bounds. # This must be overridden here, to use a formatted date (string) as # 'second' instead -- cx_Oracle chops the fraction-of-second part # off of datetime objects, leaving almost an entire second out of # the year under the default implementation. bounds = super(DatabaseOperations, self).year_lookup_bounds_for_datetime_field(value) if settings.USE_TZ: bounds = [b.astimezone(timezone.utc).replace(tzinfo=None) for b in bounds] return [b.isoformat(b' ') for b in bounds] def combine_expression(self, connector, sub_expressions): "Oracle requires special cases for %% and & operators in query expressions" if connector == '%%': return 'MOD(%s)' % ','.join(sub_expressions) elif connector == '&': return 'BITAND(%s)' % ','.join(sub_expressions) elif connector == '|': raise NotImplementedError("Bit-wise or is not supported in Oracle.") return super(DatabaseOperations, self).combine_expression(connector, sub_expressions) def _get_sequence_name(self, table): name_length = self.max_name_length() - 3 return '%s_SQ' % util.truncate_name(table, name_length).upper() def _get_trigger_name(self, table): name_length = self.max_name_length() - 3 return '%s_TR' % util.truncate_name(table, name_length).upper() def bulk_insert_sql(self, fields, num_values): items_sql = "SELECT %s FROM DUAL" % ", ".join(["%s"] * len(fields)) return " UNION ALL ".join([items_sql] * num_values) class _UninitializedOperatorsDescriptor(object): def __get__(self, instance, owner): # If connection.operators is looked up before a connection has been # created, transparently initialize connection.operators to avert an # AttributeError. if instance is None: raise AttributeError("operators not available as class attribute") # Creating a cursor will initialize the operators. instance.cursor().close() return instance.__dict__['operators'] class DatabaseWrapper(BaseDatabaseWrapper): vendor = 'oracle' operators = _UninitializedOperatorsDescriptor() _standard_operators = { 'exact': '= %s', 'iexact': '= UPPER(%s)', 'contains': "LIKE TRANSLATE(%s USING NCHAR_CS) ESCAPE TRANSLATE('\\' USING NCHAR_CS)", 'icontains': "LIKE UPPER(TRANSLATE(%s USING NCHAR_CS)) ESCAPE TRANSLATE('\\' USING NCHAR_CS)", 'gt': '> %s', 'gte': '>= %s', 'lt': '< %s', 'lte': '<= %s', 'startswith': "LIKE TRANSLATE(%s USING NCHAR_CS) ESCAPE TRANSLATE('\\' USING NCHAR_CS)", 'endswith': "LIKE TRANSLATE(%s USING NCHAR_CS) ESCAPE TRANSLATE('\\' USING NCHAR_CS)", 'istartswith': "LIKE UPPER(TRANSLATE(%s USING NCHAR_CS)) ESCAPE TRANSLATE('\\' USING NCHAR_CS)", 'iendswith': "LIKE UPPER(TRANSLATE(%s USING NCHAR_CS)) ESCAPE TRANSLATE('\\' USING NCHAR_CS)", } _likec_operators = _standard_operators.copy() _likec_operators.update({ 'contains': "LIKEC %s ESCAPE '\\'", 'icontains': "LIKEC UPPER(%s) ESCAPE '\\'", 'startswith': "LIKEC %s ESCAPE '\\'", 'endswith': "LIKEC %s ESCAPE '\\'", 'istartswith': "LIKEC UPPER(%s) ESCAPE '\\'", 'iendswith': "LIKEC UPPER(%s) ESCAPE '\\'", }) Database = Database def __init__(self, *args, **kwargs): super(DatabaseWrapper, self).__init__(*args, **kwargs) self.features = DatabaseFeatures(self) use_returning_into = self.settings_dict["OPTIONS"].get('use_returning_into', True) self.features.can_return_id_from_insert = use_returning_into self.ops = DatabaseOperations(self) self.client = DatabaseClient(self) self.creation = DatabaseCreation(self) self.introspection = DatabaseIntrospection(self) self.validation = BaseDatabaseValidation(self) def _connect_string(self): settings_dict = self.settings_dict if not settings_dict['HOST'].strip(): settings_dict['HOST'] = 'localhost' if settings_dict['PORT'].strip(): dsn = Database.makedsn(settings_dict['HOST'], int(settings_dict['PORT']), settings_dict['NAME']) else: dsn = settings_dict['NAME'] return "%s/%s@%s" % (settings_dict['USER'], settings_dict['PASSWORD'], dsn) def get_connection_params(self): conn_params = self.settings_dict['OPTIONS'].copy() if 'use_returning_into' in conn_params: del conn_params['use_returning_into'] return conn_params def get_new_connection(self, conn_params): conn_string = convert_unicode(self._connect_string()) return Database.connect(conn_string, **conn_params) def init_connection_state(self): cursor = self.create_cursor() # Set the territory first. The territory overrides NLS_DATE_FORMAT # and NLS_TIMESTAMP_FORMAT to the territory default. When all of # these are set in single statement it isn't clear what is supposed # to happen. cursor.execute("ALTER SESSION SET NLS_TERRITORY = 'AMERICA'") # Set oracle date to ansi date format. This only needs to execute # once when we create a new connection. We also set the Territory # to 'AMERICA' which forces Sunday to evaluate to a '1' in # TO_CHAR(). cursor.execute( "ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS'" " NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS.FF'" + (" TIME_ZONE = 'UTC'" if settings.USE_TZ else '')) cursor.close() if 'operators' not in self.__dict__: # Ticket #14149: Check whether our LIKE implementation will # work for this connection or we need to fall back on LIKEC. # This check is performed only once per DatabaseWrapper # instance per thread, since subsequent connections will use # the same settings. cursor = self.create_cursor() try: cursor.execute("SELECT 1 FROM DUAL WHERE DUMMY %s" % self._standard_operators['contains'], ['X']) except DatabaseError: self.operators = self._likec_operators else: self.operators = self._standard_operators cursor.close() # There's no way for the DatabaseOperations class to know the # currently active Oracle version, so we do some setups here. # TODO: Multi-db support will need a better solution (a way to # communicate the current version). if self.oracle_version is not None and self.oracle_version <= 9: self.ops.regex_lookup = self.ops.regex_lookup_9 else: self.ops.regex_lookup = self.ops.regex_lookup_10 try: self.connection.stmtcachesize = 20 except: # Django docs specify cx_Oracle version 4.3.1 or higher, but # stmtcachesize is available only in 4.3.2 and up. pass def create_cursor(self): return FormatStylePlaceholderCursor(self.connection) def _commit(self): if self.connection is not None: try: return self.connection.commit() except Database.DatabaseError as e: # cx_Oracle 5.0.4 raises a cx_Oracle.DatabaseError exception # with the following attributes and values: # code = 2091 # message = 'ORA-02091: transaction rolled back # 'ORA-02291: integrity constraint (TEST_DJANGOTEST.SYS # _C00102056) violated - parent key not found' # We convert that particular case to our IntegrityError exception x = e.args[0] if hasattr(x, 'code') and hasattr(x, 'message') \ and x.code == 2091 and 'ORA-02291' in x.message: six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2]) raise # Oracle doesn't support savepoint commits. Ignore them. def _savepoint_commit(self, sid): pass def _set_autocommit(self, autocommit): with self.wrap_database_errors: self.connection.autocommit = autocommit def check_constraints(self, table_names=None): """ To check constraints, we set constraints to immediate. Then, when, we're done we must ensure they are returned to deferred. """ self.cursor().execute('SET CONSTRAINTS ALL IMMEDIATE') self.cursor().execute('SET CONSTRAINTS ALL DEFERRED') def is_usable(self): try: if hasattr(self.connection, 'ping'): # Oracle 10g R2 and higher self.connection.ping() else: # Use a cx_Oracle cursor directly, bypassing Django's utilities. self.connection.cursor().execute("SELECT 1 FROM DUAL") except Database.Error: return False else: return True @cached_property def oracle_version(self): with self.temporary_connection(): version = self.connection.version try: return int(version.split('.')[0]) except ValueError: return None class OracleParam(object): """ Wrapper object for formatting parameters for Oracle. If the string representation of the value is large enough (greater than 4000 characters) the input size needs to be set as CLOB. Alternatively, if the parameter has an `input_size` attribute, then the value of the `input_size` attribute will be used instead. Otherwise, no input size will be set for the parameter when executing the query. """ def __init__(self, param, cursor, strings_only=False): # With raw SQL queries, datetimes can reach this function # without being converted by DateTimeField.get_db_prep_value. if settings.USE_TZ and isinstance(param, datetime.datetime): if timezone.is_naive(param): warnings.warn("Oracle received a naive datetime (%s)" " while time zone support is active." % param, RuntimeWarning) default_timezone = timezone.get_default_timezone() param = timezone.make_aware(param, default_timezone) param = param.astimezone(timezone.utc).replace(tzinfo=None) # Oracle doesn't recognize True and False correctly in Python 3. # The conversion done below works both in 2 and 3. if param is True: param = "1" elif param is False: param = "0" if hasattr(param, 'bind_parameter'): self.force_bytes = param.bind_parameter(cursor) elif isinstance(param, six.memoryview): self.force_bytes = param else: self.force_bytes = convert_unicode(param, cursor.charset, strings_only) if hasattr(param, 'input_size'): # If parameter has `input_size` attribute, use that. self.input_size = param.input_size elif isinstance(param, six.string_types) and len(param) > 4000: # Mark any string param greater than 4000 characters as a CLOB. self.input_size = Database.CLOB else: self.input_size = None class VariableWrapper(object): """ An adapter class for cursor variables that prevents the wrapped object from being converted into a string when used to instanciate an OracleParam. This can be used generally for any other object that should be passed into Cursor.execute as-is. """ def __init__(self, var): self.var = var def bind_parameter(self, cursor): return self.var def __getattr__(self, key): return getattr(self.var, key) def __setattr__(self, key, value): if key == 'var': self.__dict__[key] = value else: setattr(self.var, key, value) class InsertIdVar(object): """ A late-binding cursor variable that can be passed to Cursor.execute as a parameter, in order to receive the id of the row created by an insert statement. """ def bind_parameter(self, cursor): param = cursor.cursor.var(Database.NUMBER) cursor._insert_id_var = param return param class FormatStylePlaceholderCursor(object): """ Django uses "format" (e.g. '%s') style placeholders, but Oracle uses ":var" style. This fixes it -- but note that if you want to use a literal "%s" in a query, you'll need to use "%%s". We also do automatic conversion between Unicode on the Python side and UTF-8 -- for talking to Oracle -- in here. """ charset = 'utf-8' def __init__(self, connection): self.cursor = connection.cursor() # Necessary to retrieve decimal values without rounding error. self.cursor.numbersAsStrings = True # Default arraysize of 1 is highly sub-optimal. self.cursor.arraysize = 100 def _format_params(self, params): try: return dict((k,OracleParam(v, self, True)) for k,v in params.items()) except AttributeError: return tuple([OracleParam(p, self, True) for p in params]) def _guess_input_sizes(self, params_list): # Try dict handling; if that fails, treat as sequence if hasattr(params_list[0], 'keys'): sizes = {} for params in params_list: for k, value in params.items(): if value.input_size: sizes[k] = value.input_size self.setinputsizes(**sizes) else: # It's not a list of dicts; it's a list of sequences sizes = [None] * len(params_list[0]) for params in params_list: for i, value in enumerate(params): if value.input_size: sizes[i] = value.input_size self.setinputsizes(*sizes) def _param_generator(self, params): # Try dict handling; if that fails, treat as sequence if hasattr(params, 'items'): return dict((k, v.force_bytes) for k,v in params.items()) else: return [p.force_bytes for p in params] def _fix_for_params(self, query, params): # cx_Oracle wants no trailing ';' for SQL statements. For PL/SQL, it # it does want a trailing ';' but not a trailing '/'. However, these # characters must be included in the original query in case the query # is being passed to SQL*Plus. if query.endswith(';') or query.endswith('/'): query = query[:-1] if params is None: params = [] query = convert_unicode(query, self.charset) elif hasattr(params, 'keys'): # Handle params as dict args = dict((k, ":%s"%k) for k in params.keys()) query = convert_unicode(query % args, self.charset) else: # Handle params as sequence args = [(':arg%d' % i) for i in range(len(params))] query = convert_unicode(query % tuple(args), self.charset) return query, self._format_params(params) def execute(self, query, params=None): query, params = self._fix_for_params(query, params) self._guess_input_sizes([params]) try: return self.cursor.execute(query, self._param_generator(params)) except Database.DatabaseError as e: # cx_Oracle <= 4.4.0 wrongly raises a DatabaseError for ORA-01400. if hasattr(e.args[0], 'code') and e.args[0].code == 1400 and not isinstance(e, IntegrityError): six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2]) raise def executemany(self, query, params=None): if not params: # No params given, nothing to do return None # uniform treatment for sequences and iterables params_iter = iter(params) query, firstparams = self._fix_for_params(query, next(params_iter)) # we build a list of formatted params; as we're going to traverse it # more than once, we can't make it lazy by using a generator formatted = [firstparams]+[self._format_params(p) for p in params_iter] self._guess_input_sizes(formatted) try: return self.cursor.executemany(query, [self._param_generator(p) for p in formatted]) except Database.DatabaseError as e: # cx_Oracle <= 4.4.0 wrongly raises a DatabaseError for ORA-01400. if hasattr(e.args[0], 'code') and e.args[0].code == 1400 and not isinstance(e, IntegrityError): six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2]) raise def fetchone(self): row = self.cursor.fetchone() if row is None: return row return _rowfactory(row, self.cursor) def fetchmany(self, size=None): if size is None: size = self.arraysize return tuple([_rowfactory(r, self.cursor) for r in self.cursor.fetchmany(size)]) def fetchall(self): return tuple([_rowfactory(r, self.cursor) for r in self.cursor.fetchall()]) def var(self, *args): return VariableWrapper(self.cursor.var(*args)) def arrayvar(self, *args): return VariableWrapper(self.cursor.arrayvar(*args)) def __getattr__(self, attr): if attr in self.__dict__: return self.__dict__[attr] else: return getattr(self.cursor, attr) def __iter__(self): return CursorIterator(self.cursor) class CursorIterator(six.Iterator): """Cursor iterator wrapper that invokes our custom row factory.""" def __init__(self, cursor): self.cursor = cursor self.iter = iter(cursor) def __iter__(self): return self def __next__(self): return _rowfactory(next(self.iter), self.cursor) def _rowfactory(row, cursor): # Cast numeric values as the appropriate Python type based upon the # cursor description, and convert strings to unicode. casted = [] for value, desc in zip(row, cursor.description): if value is not None and desc[1] is Database.NUMBER: precision, scale = desc[4:6] if scale == -127: if precision == 0: # NUMBER column: decimal-precision floating point # This will normally be an integer from a sequence, # but it could be a decimal value. if '.' in value: value = decimal.Decimal(value) else: value = int(value) else: # FLOAT column: binary-precision floating point. # This comes from FloatField columns. value = float(value) elif precision > 0: # NUMBER(p,s) column: decimal-precision fixed point. # This comes from IntField and DecimalField columns. if scale == 0: value = int(value) else: value = decimal.Decimal(value) elif '.' in value: # No type information. This normally comes from a # mathematical expression in the SELECT list. Guess int # or Decimal based on whether it has a decimal point. value = decimal.Decimal(value) else: value = int(value) # datetimes are returned as TIMESTAMP, except the results # of "dates" queries, which are returned as DATETIME. elif desc[1] in (Database.TIMESTAMP, Database.DATETIME): # Confirm that dt is naive before overwriting its tzinfo. if settings.USE_TZ and value is not None and timezone.is_naive(value): value = value.replace(tzinfo=timezone.utc) elif desc[1] in (Database.STRING, Database.FIXED_CHAR, Database.LONG_STRING): value = to_unicode(value) casted.append(value) return tuple(casted) def to_unicode(s): """ Convert strings to Unicode objects (and return all other data types unchanged). """ if isinstance(s, six.string_types): return force_text(s) return s def _get_sequence_reset_sql(): # TODO: colorize this SQL code with style.SQL_KEYWORD(), etc. return """ DECLARE table_value integer; seq_value integer; BEGIN SELECT NVL(MAX(%(column)s), 0) INTO table_value FROM %(table)s; SELECT NVL(last_number - cache_size, 0) INTO seq_value FROM user_sequences WHERE sequence_name = '%(sequence)s'; WHILE table_value > seq_value LOOP SELECT "%(sequence)s".nextval INTO seq_value FROM dual; END LOOP; END; /"""
atruberg/django-custom
django/db/backends/oracle/base.py
Python
bsd-3-clause
39,830
/* * Copyright (c) 2012, United States Government, as represented by the Secretary of Health and Human Services. * 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 the United States Government 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 UNITED STATES GOVERNMENT 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. */ package gov.hhs.fha.nhinc.gateway.executorservice; import gov.hhs.fha.nhinc.orchestration.OutboundOrchestratableMessage; import gov.hhs.fha.nhinc.orchestration.OutboundResponseProcessor; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.Future; import org.apache.log4j.Logger; import com.google.common.base.Optional; /** * Main unit of execution Executes a DQ or PD request currently, but could be used to execute any of the Nhin * transaction requests (such as DR or DeferredPD) * * Uses generics for CumulativeResponse (which represents final object that is returned). Each IndividualResponse * returned from executed NhinCallableRequest contains the OutboundResponseProcessor for the IndividualResponse * * Constructs with the java.util.concurrent.ExecutorService to use to execute the requests and a List of * NhinCallableRequest to be submitted to ExecutorService * * Uses an ExecutorCompletionService, and executeTask will return only when all CallableRequest have completed/returned. * Once executeTask has returned, call getFinalResponse to get the final cumulative/aggregated/processed response which * contains all the responses from the individual NhinCallableRequest * * @author paul.eftis */ public class NhinTaskExecutor<CumulativeResponse extends OutboundOrchestratableMessage, IndividualResponse extends OutboundOrchestratableMessage> { private static final Logger LOG = Logger.getLogger(NhinTaskExecutor.class); private CumulativeResponse cumulativeResponse = null; private Executor executor = null; private String transactionId = null; private List<NhinCallableRequest<IndividualResponse>> callableList = new ArrayList<NhinCallableRequest<IndividualResponse>>(); /** * */ public NhinTaskExecutor(Executor e, List<NhinCallableRequest<IndividualResponse>> list, String id) { transactionId = id; executor = e; callableList = list; } /** * Called when TaskExecutor is complete to retrieve the final result * * @return Response which contains all the responses from the individual CallableRequest aggregated into a single * response */ public CumulativeResponse getFinalResponse() { return cumulativeResponse; } @SuppressWarnings("static-access") public void executeTask() throws InterruptedException, ExecutionException { LOG.debug("NhinTaskExecutor::executeTask begin"); try { CompletionService<IndividualResponse> executorCompletionService = new ExecutorCompletionService<IndividualResponse>( executor); // loop through the callableList and submit the callable requests for execution for (NhinCallableRequest<IndividualResponse> c : callableList) { executorCompletionService.submit(c); } // the executor completion service puts the callable responses on a // blocking queue where you retrieve <Future> responses off queue using // take(), when they become available int count = 0; for (NhinCallableRequest<IndividualResponse> c : callableList) { Future<IndividualResponse> future = executorCompletionService.take(); // for debug count++; LOG.debug("NhinTaskExecutor::executeTask::take received response count=" + count); if (future != null) { try { IndividualResponse r = (IndividualResponse) future.get(); if (r != null) { // process response Optional<OutboundResponseProcessor> optionalProcessor = r.getResponseProcessor(); if (!optionalProcessor.isPresent()) { throw new IllegalArgumentException( "IndividualResponse.getResponseProcessor returned null"); } OutboundResponseProcessor processor = optionalProcessor.get(); cumulativeResponse = (CumulativeResponse) processor.processNhinResponse(r, cumulativeResponse); } else { // shouldn't ever get here, but if we do all we can do is log and skip it LOG.error("NhinTaskExecutor::executeTask (count=" + count + ") received null response!!!!!"); } } catch (Exception e) { // shouldn't ever get here LOG.error("NhinTaskExecutor processResponse EXCEPTION!!!"); ExecutorServiceHelper.getInstance().outputCompleteException(e); } } else { // shouldn't ever get here LOG.error("NhinTaskExecutor::executeTask received null future from queue (i.e. take)!!!!!"); } } LOG.debug("NhinTaskExecutor::executeTask done"); } catch (Exception e) { // shouldn't ever get here LOG.error("NhinTaskExecutor EXCEPTION!!!"); ExecutorServiceHelper.getInstance().outputCompleteException(e); } } }
sailajaa/CONNECT
Product/Production/Common/CONNECTCoreLib/src/main/java/gov/hhs/fha/nhinc/gateway/executorservice/NhinTaskExecutor.java
Java
bsd-3-clause
7,263
# -*- coding: utf-8 -*- # pylint: disable=E265 """ lantz.drivers.andor.ccd ~~~~~~~~~~~~~~~~~~~~~~~ Low level driver wrapping library for CCD and Intensified CCD cameras. Only functions for iXon EMCCD cameras were tested. Only tested in Windows OS. The driver was written for the single-camera scenario. If more than one camera is present, some 'read_once=True' should be erased but it shouldn't be necessary to make any more changes. Sources:: - Andor SDK 2.96 Manual :copyright: 2015 by Lantz Authors, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import numpy as np import ctypes as ct from collections import namedtuple from lantz import Driver, Feat, Action, DictFeat from lantz.errors import InstrumentError from lantz.foreign import LibraryDriver from lantz import Q_ degC = Q_(1, 'degC') us = Q_(1, 'us') MHz = Q_(1, 'MHz') seg = Q_(1, 's') _ERRORS = { 20002: 'DRV_SUCCESS', 20003: 'DRV_VXDNOTINSTALLED', 20004: 'DRV_ERROR_SCAN', 20005: 'DRV_ERROR_CHECK_SUM', 20006: 'DRV_ERROR_FILELOAD', 20007: 'DRV_UNKNOWN_FUNCTION', 20008: 'DRV_ERROR_VXD_INIT', 20009: 'DRV_ERROR_ADDRESS', 20010: 'DRV_ERROR_PAGELOCK', 20011: 'DRV_ERROR_PAGE_UNLOCK', 20012: 'DRV_ERROR_BOARDTEST', 20013: 'Unable to communicate with card.', 20014: 'DRV_ERROR_UP_FIFO', 20015: 'DRV_ERROR_PATTERN', 20017: 'DRV_ACQUISITION_ERRORS', 20018: 'Computer unable to read the data via the ISA slot at the required rate.', 20019: 'DRV_ACQ_DOWNFIFO_FULL', 20020: 'RV_PROC_UNKNOWN_INSTRUCTION', 20021: 'DRV_ILLEGAL_OP_CODE', 20022: 'Unable to meet Kinetic cycle time.', 20023: 'Unable to meet Accumulate cycle time.', 20024: 'No acquisition has taken place', 20026: 'Overflow of the spool buffer.', 20027: 'DRV_SPOOLSETUPERROR', 20033: 'DRV_TEMPERATURE_CODES', 20034: 'Temperature is OFF.', 20035: 'Temperature reached but not stabilized.', 20036: 'Temperature has stabilized at set point.', 20037: 'Temperature has not reached set point.', 20038: 'DRV_TEMPERATURE_OUT_RANGE', 20039: 'DRV_TEMPERATURE_NOT_SUPPORTED', 20040: 'Temperature had stabilized but has since drifted.', 20049: 'DRV_GENERAL_ERRORS', 20050: 'DRV_INVALID_AUX', 20051: 'DRV_COF_NOTLOADED', 20052: 'DRV_FPGAPROG', 20053: 'DRV_FLEXERROR', 20054: 'DRV_GPIBERROR', 20064: 'DRV_DATATYPE', 20065: 'DRV_DRIVER_ERRORS', 20066: 'Invalid parameter 1', 20067: 'Invalid parameter 2', 20068: 'Invalid parameter 3', 20069: 'Invalid parameter 4', 20070: 'DRV_INIERROR', 20071: 'DRV_COFERROR', 20072: 'Acquisition in progress', 20073: 'The system is not currently acquiring', 20074: 'DRV_TEMPCYCLE', 20075: 'System not initialized', 20076: 'DRV_P5INVALID', 20077: 'DRV_P6INVALID', 20078: 'Not a valid mode', 20079: 'DRV_INVALID_FILTER', 20080: 'DRV_I2CERRORS', 20081: 'DRV_DRV_I2CDEVNOTFOUND', 20082: 'DRV_I2CTIMEOUT', 20083: 'DRV_P7INVALID', 20089: 'DRV_USBERROR', 20090: 'DRV_IOCERROR', 20091: 'DRV_VRMVERSIONERROR', 20093: 'DRV_USB_INTERRUPT_ENDPOINT_ERROR', 20094: 'DRV_RANDOM_TRACK_ERROR', 20095: 'DRV_INVALID_TRIGGER_MODE', 20096: 'DRV_LOAD_FIRMWARE_ERROR', 20097: 'DRV_DIVIDE_BY_ZERO_ERROR', 20098: 'DRV_INVALID_RINGEXPOSURES', 20099: 'DRV_BINNING_ERROR', 20990: 'No camera present', 20991: 'Feature not supported on this camera.', 20992: 'Feature is not available at the moment.', 20115: 'DRV_ERROR_MAP', 20116: 'DRV_ERROR_UNMAP', 20117: 'DRV_ERROR_MDL', 20118: 'DRV_ERROR_UNMDL', 20119: 'DRV_ERROR_BUFFSIZE', 20121: 'DRV_ERROR_NOHANDLE', 20130: 'DRV_GATING_NOT_AVAILABLE', 20131: 'DRV_FPGA_VOLTAGE_ERROR', 20100: 'DRV_INVALID_AMPLIFIER', 20101: 'DRV_INVALID_COUNTCONVERT_MODE' } class CCD(LibraryDriver): LIBRARY_NAME = 'atmcd64d.dll' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.cameraIndex = ct.c_int(0) def _patch_functions(self): internal = self.lib.internal internal.GetCameraSerialNumber.argtypes = [ct.pointer(ct.c_uint)] internal.Filter_SetAveragingFactor.argtypes = [ct.c_int] internal.Filter_SetThreshold.argtypes = ct.c_float internal.Filter_GetThreshold.argtypes = ct.c_float def _return_handler(self, func_name, ret_value): excl_func = ['GetTemperatureF', 'IsCountConvertModeAvailable', 'IsAmplifierAvailable', 'IsTriggerModeAvailable'] if ret_value != 20002 and func_name not in excl_func: raise InstrumentError('{}'.format(_ERRORS[ret_value])) return ret_value def initialize(self): """ This function will initialize the Andor SDK System. As part of the initialization procedure on some cameras (i.e. Classic, iStar and earlier iXion) the DLL will need access to a DETECTOR.INI which contains information relating to the detector head, number pixels, readout speeds etc. If your system has multiple cameras then see the section Controlling multiple cameras. """ self.lib.Initialize() self.triggers = {'Internal': 0, 'External': 1, 'External Start': 6, 'External Exposure': 7, 'External FVB EM': 9, 'Software Trigger': 10, 'External Charge Shifting': 12} self.savetypes = {'Signed16bits': 1, 'Signed32bits': 2, 'Float': 3} # Initial values self.readout_packing_state = False self.readout_packing = self.readout_packing_state self.readout_mode_mode = 'Image' self.readout_mode = self.readout_mode_mode self.photon_counting_mode_state = False self.photon_counting_mode = self.photon_counting_mode_state self.frame_transfer_mode_state = False self.frame_transfer_mode = self.frame_transfer_mode_state self.fan_mode_index = 'onfull' self.fan_mode = self.fan_mode_index self.EM_gain_mode_index = 'RealGain' self.EM_gain_mode = self.EM_gain_mode_index self.cooled_on_shutdown_value = False self.cooled_on_shutdown = self.cooled_on_shutdown_value self.baseline_offset_value = 100 self.baseline_offset = self.baseline_offset_value self.adv_trigger_mode_state = True self.adv_trigger_mode = self.adv_trigger_mode_state self.acq_mode = 'Single Scan' self.acquisition_mode = self.acq_mode self.amp_typ = 0 self.horiz_shift_speed_index = 0 self.horiz_shift_speed = self.horiz_shift_speed_index self.vert_shift_speed_index = 0 self.vert_shift_speed = self.vert_shift_speed_index self.preamp_index = 0 self.preamp = self.preamp_index self.temperature_sp = 0 * degC self.temperature_setpoint = self.temperature_sp self.auxout = np.zeros(4, dtype=bool) for i in np.arange(1, 5): self.out_aux_port[i] = False self.trigger_mode_index = 'Internal' self.trigger_mode = self.trigger_mode_index def finalize(self): """Finalize Library. Concluding function. """ if self.status != 'Camera is idle, waiting for instructions.': self.abort_acquisition() self.cooler_on = False self.free_int_mem() self.lib.ShutDown() ### SYSTEM INFORMATION @Feat(read_once=True) def ncameras(self): """This function returns the total number of Andor cameras currently installed. It is possible to call this function before any of the cameras are initialized. """ n = ct.c_long() self.lib.GetAvailableCameras(ct.pointer(n)) return n.value def camera_handle(self, index): """This function returns the handle for the camera specified by cameraIndex. When multiple Andor cameras are installed the handle of each camera must be retrieved in order to select a camera using the SetCurrentCamera function. The number of cameras can be obtained using the GetAvailableCameras function. :param index: index of any of the installed cameras. Valid values: 0 to NumberCameras-1 where NumberCameras is the value returned by the GetAvailableCameras function. """ index = ct.c_long(index) handle = ct.c_long() self.lib.GetCameraHandle(index, ct.pointer(handle)) return handle.value @Feat() def current_camera(self): """When multiple Andor cameras are installed this function allows the user to select which camera is currently active. Once a camera has been selected the other functions can be called as normal but they will only apply to the selected camera. If only 1 camera is installed calling this function is not required since that camera will be selected by default. """ n = ct.c_long() # current camera handler self.lib.GetCurrentCamera(ct.pointer(n)) return n.value @current_camera.setter def current_camera(self, value): value = ct.c_long(value) self.lib.SetCurrentCamera(value.value) # needs camera handler @Feat(read_once=True) def idn(self): """Identification of the device """ hname = (ct.c_char * 100)() self.lib.GetHeadModel(ct.pointer(hname)) hname = str(hname.value)[2:-1] sn = ct.c_uint() self.lib.GetCameraSerialNumber(ct.pointer(sn)) return 'Andor ' + hname + ', serial number ' + str(sn.value) @Feat(read_once=True) def hardware_version(self): pcb, decode = ct.c_uint(), ct.c_uint() dummy1, dummy2 = ct.c_uint(), ct.c_uint() firmware_ver, firmware_build = ct.c_uint(), ct.c_uint() self.lib.GetHardwareVersion(ct.pointer(pcb), ct.pointer(decode), ct.pointer(dummy1), ct.pointer(dummy2), ct.pointer(firmware_ver), ct.pointer(firmware_build)) results = namedtuple('hardware_versions', 'PCB Flex10K CameraFirmware CameraFirmwareBuild') return results(pcb.value, decode.value, firmware_ver.value, firmware_build.value) @Feat(read_once=True) def software_version(self): eprom, coffile, vxdrev = ct.c_uint(), ct.c_uint(), ct.c_uint() vxdver, dllrev, dllver = ct.c_uint(), ct.c_uint(), ct.c_uint() self.lib.GetSoftwareVersion(ct.pointer(eprom), ct.pointer(coffile), ct.pointer(vxdrev), ct.pointer(vxdver), ct.pointer(dllrev), ct.pointer(dllver)) results = namedtuple('software_versions', 'EPROM COF DriverRev DriverVer DLLRev DLLVer') return results(eprom.value, coffile.value, vxdrev.value, vxdver.value, dllrev.value, dllver.value) # TODO: Make sense of this: @Feat(read_once=True) def capabilities(self): """This function will fill in an AndorCapabilities structure with the capabilities associated with the connected camera. Individual capabilities are determined by examining certain bits and combinations of bits in the member variables of the AndorCapabilites structure. """ class Capabilities(ct.Structure): _fields_ = [("Size", ct.c_ulong), ("AcqModes", ct.c_ulong), ("ReadModes", ct.c_ulong), ("FTReadModes", ct.c_ulong), ("TriggerModes", ct.c_ulong), ("CameraType", ct.c_ulong), ("PixelModes", ct.c_ulong), ("SetFunctions", ct.c_ulong), ("GetFunctions", ct.c_ulong), ("Features", ct.c_ulong), ("PCICard", ct.c_ulong), ("EMGainCapability", ct.c_ulong)] stru = Capabilities() stru.Size = ct.sizeof(stru) self.lib.GetCapabilities(ct.pointer(stru)) return stru @Feat(read_once=True) def controller_card(self): """This function will retrieve the type of PCI controller card included in your system. This function is not applicable for USB systems. The maximum number of characters that can be returned from this function is 10. """ model = ct.c_wchar_p() self.lib.GetControllerCardModel(ct.pointer(model)) return model.value @Feat(read_once=True) def count_convert_wavelength_range(self): """This function returns the valid wavelength range available in Count Convert mode.""" mini = ct.c_float() maxi = ct.c_float() self.lib.GetCountConvertWavelengthRange(ct.pointer(mini), ct.pointer(maxi)) return (mini.value, maxi.value) @Feat(read_once=True) def detector_shape(self): xp, yp = ct.c_int(), ct.c_int() self.lib.GetDetector(ct.pointer(xp), ct.pointer(yp)) return (xp.value, yp.value) @Feat(read_once=True) def px_size(self): """This function returns the dimension of the pixels in the detector in microns. """ xp, yp = ct.c_float(), ct.c_float() self.lib.GetPixelSize(ct.pointer(xp), ct.pointer(yp)) return (xp.value, yp.value) def QE(self, wl): """Returns the percentage QE for a particular head model at a user specified wavelength. """ hname = (ct.c_char * 100)() self.lib.GetHeadModel(ct.pointer(hname)) wl = ct.c_float(wl) qe = ct.c_float() self.lib.GetQE(ct.pointer(hname), wl, ct.c_uint(0), ct.pointer(qe)) return qe.value def sensitivity(self, ad, amp, i, pa): """This function returns the sensitivity for a particular speed. """ sens = ct.c_float() ad, amp, i, pa = ct.c_int(ad), ct.c_int(amp), ct.c_int(i), ct.c_int(pa) self.lib.GetSensitivity(ad, amp, i, pa, ct.pointer(sens)) return sens.value def count_convert_available(self, mode): """This function checks if the hardware and current settings permit the use of the specified Count Convert mode. """ mode = ct.c_int(mode) ans = self.lib.IsCountConvertModeAvailable(mode) if ans == 20002: return True else: return False ### SHUTTER # I couldn't find a better way to do this... sorry @Action() def shutter(self, typ, mode, ext_closing, ext_opening, ext_mode): """This function expands the control offered by SetShutter to allow an external shutter and internal shutter to be controlled independently (only available on some cameras – please consult your Camera User Guide). The typ parameter allows the user to control the TTL signal output to an external shutter. The opening and closing times specify the length of time required to open and close the shutter (this information is required for calculating acquisition timings – see SHUTTER TRANSFER TIME). The mode and extmode parameters control the behaviour of the internal and external shutters. To have an external shutter open and close automatically in an experiment, set the mode parameter to “Open” and set the extmode parameter to “Auto”. To have an internal shutter open and close automatically in an experiment, set the extmode parameter to “Open” and set the mode parameter to “Auto”. To not use any shutter in the experiment, set both shutter modes to permanently open. :param typ: 0 (or 1) Output TTL low (or high) signal to open shutter. :param mode: Internal shutter: 0 Fully Auto, 1 Permanently Open, 2 Permanently Closed, 4 Open for FVB series, 5 Open for any series. :param ext_closing: Time shutter takes to close (milliseconds) :param ext_opening: Time shutter takes to open (milliseconds) :param ext_mode: External shutter: 0 Fully Auto, 1 Permanently Open, 2 Permanently Closed, 4 Open for FVB series, 5 Open for any series. """ self.lib.SetShutterEx(ct.c_int(typ), ct.c_int(mode), ct.c_int(ext_closing), ct.c_int(ext_opening), ct.c_int(ext_mode)) @Feat(read_once=True) def shutter_min_times(self): """ This function will return the minimum opening and closing times in milliseconds for the shutter on the current camera. """ otime, ctime = ct.c_int(), ct.c_int() self.lib.GetShutterMinTimes(ct.pointer(ctime), ct.pointer(otime)) return (otime.value, ctime.value) @Feat(read_once=True) def has_mechanical_shutter(self): state = ct.c_int() self.lib.IsInternalMechanicalShutter(ct.pointer(state)) return bool(state.value) ### TEMPERATURE @Feat(read_once=True, units='degC') def min_temperature(self): """This function returns the valid range of temperatures in centigrads to which the detector can be cooled. """ mini, maxi = ct.c_int(), ct.c_int() self.lib.GetTemperatureRange(ct.pointer(mini), ct.pointer(maxi)) return mini.value @Feat(read_once=True, units='degC') def max_temperature(self): """This function returns the valid range of temperatures in centigrads to which the detector can be cooled. """ mini, maxi = ct.c_int(), ct.c_int() self.lib.GetTemperatureRange(ct.pointer(mini), ct.pointer(maxi)) return maxi.value @Feat() def temperature_status(self): """This function returns the temperature of the detector to the nearest degree. It also gives the status of cooling process. """ temp = ct.c_float() ans = self.lib.GetTemperatureF(ct.pointer(temp)) return _ERRORS[ans] @Feat(units='degC') def temperature(self): """This function returns the temperature of the detector to the nearest degree. It also gives the status of cooling process. """ temp = ct.c_float() self.lib.GetTemperatureF(ct.pointer(temp)) return temp.value @Feat(units='degC') def temperature_setpoint(self): return self.temperature_sp @temperature_setpoint.setter def temperature_setpoint(self, value): self.temperature_sp = value value = ct.c_int(int(value)) self.lib.SetTemperature(value) @Feat(values={True: 1, False: 0}) def cooler_on(self): state = ct.c_int() self.lib.IsCoolerOn(ct.pointer(state)) return state.value @cooler_on.setter def cooler_on(self, value): if value: self.lib.CoolerON() else: self.lib.CoolerOFF() @Feat(values={True: 1, False: 0}) def cooled_on_shutdown(self): """This function determines whether the cooler is switched off when the camera is shut down. """ return self.cooled_on_shutdown_value @cooled_on_shutdown.setter def cooled_on_shutdown(self, state): ans = self.lib.SetCoolerMode(ct.c_int(state)) if ans == 20002: self.cooled_on_shutdown_value = state @Feat(values={'onfull': 0, 'onlow': 1, 'off': 2}) def fan_mode(self): """Allows the user to control the mode of the camera fan. If the system is cooled, the fan should only be turned off for short periods of time. During this time the body of the camera will warm up which could compromise cooling capabilities. If the camera body reaches too high a temperature, depends on camera, the buzzer will sound. If this happens, turn off the external power supply and allow the system to stabilize before continuing. """ return self.fan_mode_index @fan_mode.setter def fan_mode(self, mode): ans = self.lib.SetFanMode(ct.c_int(mode)) if ans == 20002: self.fan_mode_index = mode ### FILTERS @Feat() def averaging_factor(self): """Averaging factor to be used with the recursive filter. For information on the various data averaging filters available see DATA AVERAGING FILTERS in the Special Guides section of the manual. """ af = ct.c_uint() self.lib.Filter_GetAveragingFactor(ct.pointer(af)) return af.value @averaging_factor.setter def averaging_factor(self, value): self.lib.Filter_SetAveragingFactor(ct.c_uint(value)) @Feat() def averaging_frame_count(self): """Number of frames to be used when using the frame averaging filter. """ fc = ct.c_uint() self.lib.Filter_GetAveragingFrameCount(ct.pointer(fc)) return fc.value @averaging_frame_count.setter def averaging_frame_count(self, value): self.lib.Filter_SetAveragingFrameCount(ct.c_uint(value)) @Feat(values={'NAF': 0, 'RAF': 5, 'FAF': 6}) def averaging_mode(self): """Current averaging mode. Valid options are: 0 – No Averaging Filter 5 – Recursive Averaging Filter 6 – Frame Averaging Filter """ i = ct.c_int() self.lib.Filter_GetDataAveragingMode(ct.pointer(i)) return i.value @averaging_mode.setter def averaging_mode(self, value): self.lib.Filter_SetDataAveragingMode(ct.c_int(value)) @Feat(values={'NF': 0, 'MF': 1, 'LAF': 2, 'IRF': 3, 'NTF': 4}) def noise_filter_mode(self): """Set the Noise Filter to use; For information on the various spurious noise filters available see SPURIOUS NOISE FILTERS in the Special Guides section of the manual. Valid options are: 0 – No Averaging Filter 1 – Median Filter 2 – Level Above Filter 3 – Interquartile Range Filter 4 – Noise Threshold Filter """ i = ct.c_uint() self.lib.Filter_GetMode(ct.pointer(i)) return i.value @noise_filter_mode.setter def noise_filter_mode(self, value): self.lib.Filter_SetMode(ct.c_uint(value)) @Feat() def filter_threshold(self): """Sets the threshold value for the Noise Filter. For information on the various spurious noise filters available see SPURIOUS NOISE FILTERS in the Special Guides section of the manual. Valid values are: 0 – 65535 for Level Above filte 0 – 10 for all other filters. """ f = ct.c_float() self.lib.Filter_GetThreshold(ct.pointer(f)) return f.value @filter_threshold.setter def filter_threshold(self, value): self.lib.Filter_SetThreshold(ct.c_float(value)) @Feat(values={True: 2, False: 0}) def cr_filter_enabled(self): """This function will set the state of the cosmic ray filter mode for future acquisitions. If the filter mode is on, consecutive scans in an accumulation will be compared and any cosmic ray-like features that are only present in one scan will be replaced with a scaled version of the corresponding pixel value in the correct scan. """ i = ct.c_int() self.lib.GetFilterMode(ct.pointer(i)) return i.value @cr_filter_enabled.setter def cr_filter_enabled(self, value): self.lib.SetFilterMode(ct.c_int(value)) ### PHOTON COUNTING MODE @Feat(values={True: 1, False: 0}) # FIXME: untested def photon_counting_mode(self): """This function activates the photon counting option. """ return self.photon_counting_mode_state @photon_counting_mode.setter def photon_counting_mode(self, state): ans = self.lib.SetPhotonCounting(ct.c_int(state)) if ans == 20002: self.photon_counting_mode_state = state @Feat(read_once=True) def n_photon_counting_div(self): """Available in some systems is photon counting mode. This function gets the number of photon counting divisions available. The functions SetPhotonCounting and SetPhotonCountingThreshold can be used to specify which of these divisions is to be used. """ inti = ct.c_ulong() self.lib.GetNumberPhotonCountingDivisions(ct.pointer(inti)) return inti.value @Action() # untested def set_photon_counting_divs(self, n, thres): """This function sets the thresholds for the photon counting option. """ thres = ct.c_long(thres) self.lib.SetPhotonCountingDivisions(ct.c_ulong(n), ct.pointer(thres)) @Action() def set_photon_counting_thres(self, mini, maxi): """This function sets the minimum and maximum threshold in counts (1-65535) for the photon counting option. """ self.lib.SetPhotonCountingThreshold(ct.c_long(mini), ct.c_long(maxi)) ### FAST KINETICS MODE @Feat(units='s') def FK_exposure_time(self): """This function will return the current “valid” exposure time for a fast kinetics acquisition. This function should be used after all the acquisitions settings have been set, i.e. SetFastKinetics and SetFKVShiftSpeed. The value returned is the actual time used in subsequent acquisitions. """ f = ct.c_float() self.lib.GetFKExposureTime(ct.pointer(f)) return f.value ### ACQUISITION HANDLING @Feat(values={'Single Scan': 1, 'Accumulate': 2, 'Kinetics': 3, 'Fast Kinetics': 4, 'Run till abort': 5}) def acquisition_mode(self): """This function will set the acquisition mode to be used on the next StartAcquisition. NOTE: In Mode 5 the system uses a “Run Till Abort” acquisition mode. In Mode 5 only, the camera continually acquires data until the AbortAcquisition function is called. By using the SetDriverEvent function you will be notified as each acquisition is completed. """ return self.acq_mode @acquisition_mode.setter def acquisition_mode(self, mode): ans = self.lib.SetAcquisitionMode(ct.c_int(mode)) if ans == 20002: self.acq_mode = mode @Action() def prepare_acquisition(self): """This function reads the current acquisition setup and allocates and configures any memory that will be used during the acquisition. The function call is not required as it will be called automatically by the StartAcquisition function if it has not already been called externally. However for long kinetic series acquisitions the time to allocate and configure any memory can be quite long which can result in a long delay between calling StartAcquisition and the acquisition actually commencing. For iDus, there is an additional delay caused by the camera being set-up with any new acquisition parameters. Calling PrepareAcquisition first will reduce this delay in the StartAcquisition call. """ self.lib.PrepareAcquisition() @Action() def start_acquisition(self): """This function starts an acquisition. The status of the acquisition can be monitored via GetStatus(). """ self.lib.StartAcquisition() @Action() def abort_acquisition(self): """This function aborts the current acquisition if one is active """ self.lib.AbortAcquisition() @Action() def wait_for_acquisition(self): """WaitForAcquisition can be called after an acquisition is started using StartAcquisition to put the calling thread to sleep until an Acquisition Event occurs. This can be used as a simple alternative to the functionality provided by the SetDriverEvent function, as all Event creation and handling is performed internally by the SDK library. Like the SetDriverEvent functionality it will use less processor resources than continuously polling with the GetStatus function. If you wish to restart the calling thread without waiting for an Acquisition event, call the function CancelWait. An Acquisition Event occurs each time a new image is acquired during an Accumulation, Kinetic Series or Run-Till-Abort acquisition or at the end of a Single Scan Acquisition. If a second event occurs before the first one has been acknowledged, the first one will be ignored. Care should be taken in this case, as you may have to use CancelWait to exit the function. """ self.lib.WaitForAcquisition() @Action() def cancel_wait(self): """This function restarts a thread which is sleeping within the WaitForAcquisition function. The sleeping thread will return from WaitForAcquisition with a value not equal to DRV_SUCCESS. """ self.lib.CancelWait() @Feat() def acquisition_progress(self): """This function will return information on the progress of the current acquisition. It can be called at any time but is best used in conjunction with SetDriverEvent. The values returned show the number of completed scans in the current acquisition. If 0 is returned for both accum and series then either: - No acquisition is currently running - The acquisition has just completed - The very first scan of an acquisition has just started and not yet completed. GetStatus can be used to confirm if the first scan has just started, returning DRV_ACQUIRING, otherwise it will return DRV_IDLE. For example, if accum=2 and series=3 then the acquisition has completed 3 in the series and 2 accumulations in the 4 scan of the series """ acc = ct.c_long() series = ct.c_long() self.lib.GetAcquisitionProgress(ct.pointer(acc), ct.pointer(series)) return acc.value, series.value @Feat() def status(self): """This function will return the current status of the Andor SDK system. This function should be called before an acquisition is started to ensure that it is IDLE and during an acquisition to monitor the process. """ st = ct.c_int() self.lib.GetStatus(ct.pointer(st)) if st.value == 20073: return 'Camera is idle, waiting for instructions.' elif st.value == 20074: return 'Camera is executing the temperature cycle.' elif st.value == 20072: return 'Acquisition in progress.' elif st.value == 20023: return 'Unable to meet accumulate cycle time.' elif st.value == 20022: return 'Unable to meet kinetic cycle time.' elif st.value == 20013: return 'Unable to communicate with card.' elif st.value == 20018: return ('Computer unable to read the data via the ISA slot at the ' 'required rate.') elif st.value == 20026: return 'Overflow of the spool buffer.' @Feat() def n_exposures_in_ring(self): """Gets the number of exposures in the ring at this moment.""" n = ct.c_int() self.lib.GetNumberRingExposureTimes(ct.pointer(n)) return n.value @Feat() def buffer_size(self): """This function will return the maximum number of images the circular buffer can store based on the current acquisition settings. """ n = ct.c_long() self.lib.GetSizeOfCircularBuffer(ct.pointer(n)) return n.value @Feat(values={True: 1, False: 0}) def exposing(self): """This function will return if the system is exposing or not. The status of the firepulse will be returned. NOTE This is only supported by the CCI23 card. """ i = ct.c_int() self.lib.GetCameraEventStatus(ct.pointer(i)) return i.value @Feat() def n_images_acquired(self): """This function will return the total number of images acquired since the current acquisition started. If the camera is idle the value returned is the number of images acquired during the last acquisition. """ n = ct.c_long() self.lib.GetTotalNumberImagesAcquired(ct.pointer(n)) return n.value @Action() def set_image(self, shape=None, binned=(1, 1), p_0=(1, 1)): """This function will set the horizontal and vertical binning to be used when taking a full resolution image. :param hbin: number of pixels to bin horizontally. :param vbin: number of pixels to bin vertically. :param hstart: Start column (inclusive). :param hend: End column (inclusive). :param vstart: Start row (inclusive). :param vend: End row (inclusive). """ if shape is None: shape = self.detector_shape (hbin, vbin) = binned (hstart, vstart) = p_0 (hend, vend) = (p_0[0] + shape[0] - 1, p_0[1] + shape[1] - 1) self.lib.SetImage(ct.c_int(hbin), ct.c_int(vbin), ct.c_int(hstart), ct.c_int(hend), ct.c_int(vstart), ct.c_int(vend)) @Feat(values={'FVB': 0, 'Multi-Track': 1, 'Random-Track': 2, 'Single-Track': 3, 'Image': 4}) def readout_mode(self): """This function will set the readout mode to be used on the subsequent acquisitions. """ return self.readout_mode_mode @readout_mode.setter def readout_mode(self, mode): ans = self.lib.SetReadMode(ct.c_int(mode)) if ans == 20002: self.readout_mode_mode = mode @Feat(values={True: 1, False: 0}) def readout_packing(self): """This function will configure whether data is packed into the readout register to improve frame rates for sub-images. Note: It is important to ensure that no light falls outside of the sub-image area otherwise the acquired data will be corrupted. Only currently available on iXon+ and iXon3. """ return self.readout_packing_state @readout_packing.setter def readout_packing(self, state): ans = self.lib.SetReadoutRegisterPacking(ct.c_int(state)) if ans == 20002: self.readout_packing_state = state ### DATA HANDLING @Feat(read_once=True) def min_image_length(self): """This function will return the minimum number of pixels that can be read out from the chip at each exposure. This minimum value arises due the way in which the chip is read out and will limit the possible sub image dimensions and binning sizes that can be applied. """ # Will contain the minimum number of super pixels on return. px = ct.c_int() self.lib.GetMinimumImageLength(ct.pointer(px)) return px.value @Action() def free_int_mem(self): """The FreeInternalMemory function will deallocate any memory used internally to store the previously acquired data. Note that once this function has been called, data from last acquisition cannot be retrived. """ self.lib.FreeInternalMemory() def acquired_data(self, shape): """This function will return the data from the last acquisition. The data are returned as long integers (32-bit signed integers). The “array” must be large enough to hold the complete data set. """ size = np.array(shape).prod() arr = np.ascontiguousarray(np.zeros(size, dtype=np.int32)) self.lib.GetAcquiredData(arr.ctypes.data_as(ct.POINTER(ct.c_int32)), ct.c_ulong(size)) arr = arr.reshape(shape) return arr def acquired_data16(self, shape): """16-bit version of the GetAcquiredData function. The “array” must be large enough to hold the complete data set. """ size = np.array(shape).prod() arr = np.ascontiguousarray(np.zeros(size, dtype=np.int16)) self.lib.GetAcquiredData16(arr.ctypes.data_as(ct.POINTER(ct.c_int16)), ct.c_ulong(size)) return arr.reshape(shape) def oldest_image(self, shape): """This function will update the data array with the oldest image in the circular buffer. Once the oldest image has been retrieved it no longer is available. The data are returned as long integers (32-bit signed integers). The "array" must be exactly the same size as the full image. """ size = np.array(shape).prod() array = np.ascontiguousarray(np.zeros(size, dtype=np.int32)) self.lib.GetOldestImage(array.ctypes.data_as(ct.POINTER(ct.c_int32)), ct.c_ulong(size)) return array.reshape(shape) def oldest_image16(self, shape): """16-bit version of the GetOldestImage function. """ size = np.array(shape).prod() array = np.ascontiguousarray(np.zeros(size, dtype=np.int16)) self.lib.GetOldestImage16(array.ctypes.data_as(ct.POINTER(ct.c_int16)), ct.c_ulong(size)) return array.reshape(shape) def most_recent_image(self, shape): """This function will update the data array with the most recently acquired image in any acquisition mode. The data are returned as long integers (32-bit signed integers). The "array" must be exactly the same size as the complete image. """ size = np.array(shape).prod() arr = np.ascontiguousarray(np.zeros(size, dtype=np.int32)) self.lib.GetMostRecentImage(arr.ctypes.data_as(ct.POINTER(ct.c_int32)), ct.c_ulong(size)) return arr.reshape(shape) def most_recent_image16(self, shape): """16-bit version of the GetMostRecentImage function. """ size = np.array(shape).prod() arr = np.ascontiguousarray(np.zeros(size, dtype=np.int16)) pt = ct.POINTER(ct.c_int16) self.lib.GetMostRecentImage16(arr.ctypes.data_as(pt), ct.c_ulong(size)) return arr.reshape(shape) def images(self, first, last, shape, validfirst, validlast): """This function will update the data array with the specified series of images from the circular buffer. If the specified series is out of range (i.e. the images have been overwritten or have not yet been acquired) then an error will be returned. :param first: index of first image in buffer to retrieve. :param flast: index of last image in buffer to retrieve. :param farr: pointer to data storage allocated by the user. :param size: total number of pixels. :param fvalidfirst: index of the first valid image. :param fvalidlast: index of the last valid image. """ size = shape[0] * shape[1] * (1 + last - first) array = np.ascontiguousarray(np.zeros(size, dtype=np.int32)) self.lib.GetImages(ct.c_long(first), ct.c_long(last), array.ctypes.data_as(ct.POINTER(ct.c_int32)), ct.c_ulong(size), ct.pointer(ct.c_long(validfirst)), ct.pointer(ct.c_long(validlast))) return array.reshape(-1, shape[0], shape[1]) def images16(self, first, last, shape, validfirst, validlast): """16-bit version of the GetImages function. """ size = shape[0] * shape[1] * (1 + last - first) array = np.ascontiguousarray(np.zeros(size, dtype=np.int16)) self.lib.GetImages16(ct.c_long(first), ct.c_long(last), array.ctypes.data_as(ct.POINTER(ct.c_int16)), ct.c_ulong(size), ct.pointer(ct.c_long(validfirst)), ct.pointer(ct.c_long(validlast))) return array.reshape(-1, shape[0], shape[1]) @Feat() def new_images_index(self): """This function will return information on the number of new images (i.e. images which have not yet been retrieved) in the circular buffer. This information can be used with GetImages to retrieve a series of the latest images. If any images are overwritten in the circular buffer they can no longer be retrieved and the information returned will treat overwritten images as having been retrieved. """ first = ct.c_long() last = ct.c_long() self.lib.GetNumberNewImages(ct.pointer(first), ct.pointer(last)) return (first.value, last.value) @Feat() # TODO: test this def available_images_index(self): """This function will return information on the number of available images in the circular buffer. This information can be used with GetImages to retrieve a series of images. If any images are overwritten in the circular buffer they no longer can be retrieved and the information returned will treat overwritten images as not available. """ first = ct.c_long() last = ct.c_long() self.lib.GetNumberAvailableImages(ct.pointer(first), ct.pointer(last)) return (first.value, last.value) def set_dma_parameters(self, n_max_images, s_per_dma): """In order to facilitate high image readout rates the controller card may wait for multiple images to be acquired before notifying the SDK that new data is available. Without this facility, there is a chance that hardware interrupts may be lost as the operating system does not have enough time to respond to each interrupt. The drawback to this is that you will not get the data for an image until all images for that interrupt have been acquired. There are 3 settings involved in determining how many images will be acquired for each notification (DMA Interrupt) of the controller card and they are as follows: 1. The size of the DMA buffer gives an upper limit on the number of images that can be stored within it and is usually set to the size of one full image when installing the software. This will usually mean that if you acquire full frames there will never be more than one image per DMA. 2. A second setting that is used is the minimum amount of time (SecondsPerDMA) that should expire between interrupts. This can be used to give an indication of the reponsiveness of the operating system to interrupts. Decreasing this value will allow more interrupts per second and should only be done for faster pcs. The default value is 0.03s (30ms), finding the optimal value for your pc can only be done through experimentation. 3. The third setting is an overide to the number of images calculated using the previous settings. If the number of images per dma is calculated to be greater than MaxImagesPerDMA then it will be reduced to MaxImagesPerDMA. This can be used to, for example, ensure that there is never more than 1 image per DMA by setting MaxImagesPerDMA to 1. Setting MaxImagesPerDMA to zero removes this limit. Care should be taken when modifying these parameters as missed interrupts may prevent the acquisition from completing. """ self.lib.SetDMAParameters(ct.c_int(n_max_images), ct.c_float(s_per_dma)) @Feat() def max_images_per_dma(self): """This function will return the maximum number of images that can be transferred during a single DMA transaction. """ n = ct.c_ulong() self.lib.GetImagesPerDMA(ct.pointer(n)) return n.value @Action() def save_raw(self, filename, typ): """This function saves the last acquisition as a raw data file. See self.savetypes for the file type keys. """ self.lib.SaveAsRaw(ct.c_char_p(str.encode(filename)), ct.c_int(self.savetypes[typ])) ### EXPOSURE SETTINGS @Feat() def acquisition_timings(self): """This function will return the current “valid” acquisition timing information. This function should be used after all the acquisitions settings have been set, e.g. SetExposureTime, SetKineticCycleTime and SetReadMode etc. The values returned are the actual times used in subsequent acquisitions. This function is required as it is possible to set the exposure time to 20ms, accumulate cycle time to 30ms and then set the readout mode to full image. As it can take 250ms to read out an image it is not possible to have a cycle time of 30ms. All data is measured in seconds. """ exp = ct.c_float() accum = ct.c_float() kine = ct.c_float() self.lib.GetAcquisitionTimings(ct.pointer(exp), ct.pointer(accum), ct.pointer(kine)) return exp.value * seg, accum.value * seg, kine.value * seg @Action() def set_exposure_time(self, time): """This function will set the exposure time to the nearest valid value not less than the given value, in seconds. The actual exposure time used is obtained by GetAcquisitionTimings. Please refer to SECTION 5 – ACQUISITION MODES for further information. """ try: time.magnitude except AttributeError: time = time * seg self.lib.SetExposureTime(ct.c_float(time.magnitude)) @Action() def set_accum_time(self, time): """This function will set the accumulation cycle time to the nearest valid value not less than the given value. The actual cycle time used is obtained by GetAcquisitionTimings. Please refer to SECTION 5 – ACQUISITION MODES for further information. """ try: time.magnitude except AttributeError: time = time * seg self.lib.SetAccumulationCycleTime(ct.c_float(time.magnitude)) @Action() def set_kinetic_cycle_time(self, time): """This function will set the kinetic cycle time to the nearest valid value not less than the given value. The actual time used is obtained by GetAcquisitionTimings. . Please refer to SECTION 5 – ACQUISITION MODES for further information. float time: the kinetic cycle time in seconds. """ try: time.magnitude except AttributeError: time = time * seg self.lib.SetKineticCycleTime(ct.c_float(time.magnitude)) @Action() def set_n_kinetics(self, n): """This function will set the number of scans (possibly accumulated scans) to be taken during a single acquisition sequence. This will only take effect if the acquisition mode is Kinetic Series. """ self.lib.SetNumberKinetics(ct.c_int(n)) @Action() def set_n_accum(self, n): """This function will set the number of scans accumulated in memory. This will only take effect if the acquisition mode is either Accumulate or Kinetic Series. """ self.lib.SetNumberAccumulations(ct.c_int(n)) @Feat(units='s') def keep_clean_time(self): """This function will return the time to perform a keep clean cycle. This function should be used after all the acquisitions settings have been set, e.g. SetExposureTime, SetKineticCycleTime and SetReadMode etc. The value returned is the actual times used in subsequent acquisitions. """ time = ct.c_float() self.lib.GetKeepCleanTime(ct.pointer(time)) return time.value @Feat(units='s') def readout_time(self): """This function will return the time to readout data from a sensor. This function should be used after all the acquisitions settings have been set, e.g. SetExposureTime, SetKineticCycleTime and SetReadMode etc. The value returned is the actual times used in subsequent acquisitions. """ time = ct.c_float() self.lib.GetReadOutTime(ct.pointer(time)) return time.value @Feat(read_once=True, units='s') def max_exposure(self): """This function will return the maximum Exposure Time in seconds that is settable by the SetExposureTime function. """ exp = ct.c_float() self.lib.GetMaximumExposure(ct.pointer(exp)) return exp.value @Feat(read_once=True) def n_max_nexposure(self): """This function will return the maximum number of exposures that can be configured in the SetRingExposureTimes SDK function. """ n = ct.c_int() self.lib.GetMaximumNumberRingExposureTimes(ct.pointer(n)) return n.value def true_exposure_times(self, n): # FIXME: bit order? something """This function will return the actual exposure times that the camera will use. There may be differences between requested exposures and the actual exposures. ntimes: Numbers of times requested. """ times = np.ascontiguousarray(np.zeros(n, dtype=np.float)) outtimes = times.ctypes.data_as(ct.POINTER(ct.c_float)) self.lib.GetAdjustedRingExposureTimes(ct.c_int(n), outtimes) return times def exposure_times(self, value): n = ct.c_int(len(value)) value = np.ascontiguousarray(value.astype(np.float)) outvalue = value.ctypes.data_as(ct.POINTER(ct.c_float)) self.lib.SetRingExposureTimes(n, outvalue) @Feat(values={True: 1, False: 0}) def frame_transfer_mode(self): """This function will set whether an acquisition will readout in Frame Transfer Mode. If the acquisition mode is Single Scan or Fast Kinetics this call will have no affect. """ return self.frame_transfer_mode_state @frame_transfer_mode.setter def frame_transfer_mode(self, state): ans = self.lib.SetFrameTransferMode(ct.c_int(state)) if ans == 20002: self.frame_transfer_mode_state = state ### AMPLIFIERS, GAIN, SPEEDS @Feat(read_once=True) def n_preamps(self): """Available in some systems are a number of pre amp gains that can be applied to the data as it is read out. This function gets the number of these pre amp gains available. The functions GetPreAmpGain and SetPreAmpGain can be used to specify which of these gains is to be used. """ n = ct.c_int() self.lib.GetNumberPreAmpGains(ct.pointer(n)) return n.value def preamp_available(self, channel, amp, index, preamp): """This function checks that the AD channel exists, and that the amplifier, speed and gain are available for the AD channel. """ channel = ct.c_int(channel) amp = ct.c_int(amp) index = ct.c_int(index) preamp = ct.c_int(preamp) status = ct.c_int() self.lib.IsPreAmpGainAvailable(channel, amp, index, preamp, ct.pointer(status)) return bool(status.value) def preamp_descr(self, index): """This function will return a string with a pre amp gain description. The pre amp gain is selected using the index. The SDK has a string associated with each of its pre amp gains. The maximum number of characters needed to store the pre amp gain descriptions is 30. The user has to specify the number of characters they wish to have returned to them from this function. """ index = ct.c_int(index) descr = (ct.c_char * 30)() leng = ct.c_int(30) self.lib.GetAmpDesc(index, ct.pointer(descr), leng) return str(descr.value)[2:-1] def true_preamp(self, index): """For those systems that provide a number of pre amp gains to apply to the data as it is read out; this function retrieves the amount of gain that is stored for a particular index. The number of gains available can be obtained by calling the GetNumberPreAmpGains function and a specific Gain can be selected using the function SetPreAmpGain. """ index = ct.c_int(index) gain = ct.c_float() self.lib.GetPreAmpGain(index, ct.pointer(gain)) return gain.value @Feat() def preamp(self): """This function will set the pre amp gain to be used for subsequent acquisitions. The actual gain factor that will be applied can be found through a call to the GetPreAmpGain function. The number of Pre Amp Gains available is found by calling the GetNumberPreAmpGains function. """ return self.preamp_index @preamp.setter def preamp(self, index): self.preamp_index = index self.lib.SetPreAmpGain(ct.c_int(index)) @Feat(values={True: 1, False: 0}) def EM_advanced_enabled(self): """This function turns on and off access to higher EM gain levels within the SDK. Typically, optimal signal to noise ratio and dynamic range is achieved between x1 to x300 EM Gain. Higher gains of > x300 are recommended for single photon counting only. Before using higher levels, you should ensure that light levels do not exceed the regime of tens of photons per pixel, otherwise accelerated ageing of the sensor can occur. This is set to False upon initialization of the camera. """ state = ct.c_int() self.lib.GetEMAdvanced(ct.pointer(state)) return state.value @EM_advanced_enabled.setter def EM_advanced_enabled(self, value): self.lib.SetEMAdvanced(ct.c_int(value)) @Feat(values={'DAC255': 0, 'DAC4095': 1, 'Linear': 2, 'RealGain': 3}) def EM_gain_mode(self): """Set the EM Gain mode to one of the following possible settings. Mode 0: The EM Gain is controlled by DAC settings in the range 0-255. Default mode. 1: The EM Gain is controlled by DAC settings in the range 0-4095. 2: Linear mode. 3: Real EM gain """ return self.EM_gain_mode_index @EM_gain_mode.setter def EM_gain_mode(self, mode): ans = self.lib.SetEMGainMode(ct.c_int(mode)) if ans == 20002: self.EM_gain_mode_index = mode @Feat() def EM_gain(self): """Allows the user to change the gain value. The valid range for the gain depends on what gain mode the camera is operating in. See SetEMGainMode to set the mode and GetEMGainRange to get the valid range to work with. To access higher gain values (>x300) see SetEMAdvanced. """ gain = ct.c_int() self.lib.GetEMCCDGain(ct.pointer(gain)) return gain.value @EM_gain.setter def EM_gain(self, value): self.lib.SetEMCCDGain(ct.c_int(value)) @Feat() def EM_gain_range(self): """Returns the minimum and maximum values of the current selected EM Gain mode and temperature of the sensor. """ mini, maxi = ct.c_int(), ct.c_int() self.lib.GetEMGainRange(ct.pointer(mini), ct.pointer(maxi)) return (mini.value, maxi.value) @Feat(read_once=True) def n_ad_channels(self): n = ct.c_int() self.lib.GetNumberADChannels(ct.pointer(n)) return n.value @Feat(read_once=True) def n_amps(self): n = ct.c_int() self.lib.GetNumberAmp(ct.pointer(n)) return n.value def amp_available(self, iamp): """This function checks if the hardware and current settings permit the use of the specified amplifier.""" ans = self.lib.IsAmplifierAvailable(ct.c_int(iamp)) if ans == 20002: return True else: return False def amp_descr(self, index): """This function will return a string with an amplifier description. The amplifier is selected using the index. The SDK has a string associated with each of its amplifiers. The maximum number of characters needed to store the amplifier descriptions is 21. The user has to specify the number of characters they wish to have returned to them from this function. """ index = ct.c_int(index) descr = (ct.c_char * 21)() leng = ct.c_int(21) self.lib.GetAmpDesc(index, ct.pointer(descr), leng) return str(descr.value)[2:-1] def readout_flipped(self, iamp): """On cameras with multiple amplifiers the frame readout may be flipped. This function can be used to determine if this is the case. """ flipped = ct.c_int() self.lib.IsReadoutFlippedByAmplifier(ct.c_int(iamp), ct.pointer(flipped)) return bool(flipped.value) def amp_max_hspeed(self, index): """This function will return the maximum available horizontal shift speed for the amplifier selected by the index parameter. """ hspeed = ct.c_float() self.lib.GetAmpMaxSpeed(ct.c_int(index), ct.pointer(hspeed)) return hspeed.value def n_horiz_shift_speeds(self, channel=0, typ=None): """As your Andor SDK system is capable of operating at more than one horizontal shift speed this function will return the actual number of speeds available. :param channel: the AD channel. :param typ: output amplification. 0 electron multiplication. 1 conventional. """ if typ is None: typ = self.amp_typ n = ct.c_int() self.lib.GetNumberHSSpeeds(ct.c_int(channel), ct.c_int(typ), ct.pointer(n)) return n.value def true_horiz_shift_speed(self, index=0, typ=None, ad=0): """As your Andor system is capable of operating at more than one horizontal shift speed this function will return the actual speeds available. The value returned is in MHz. GetHSSpeed(int channel, int typ, int index, float* speed) :param typ: output amplification. 0 electron multiplication/Conventional(clara) 1 conventional/Extended NIR Mode(clara). :param index: speed required 0 to NumberSpeeds-1 where NumberSpeeds is value returned in first parameter after a call to GetNumberHSSpeeds(). :param ad: the AD channel. """ if typ is None: typ = self.amp_typ speed = ct.c_float() self.lib.GetHSSpeed(ct.c_int(ad), ct.c_int(typ), ct.c_int(index), ct.pointer(speed)) return speed.value * MHz @Feat() def horiz_shift_speed(self): return self.horiz_shift_speed_index @horiz_shift_speed.setter def horiz_shift_speed(self, index): """This function will set the speed at which the pixels are shifted into the output node during the readout phase of an acquisition. Typically your camera will be capable of operating at several horizontal shift speeds. To get the actual speed that an index corresponds to use the GetHSSpeed function. :param typ: output amplification. 0 electron multiplication/Conventional(clara). 1 conventional/Extended NIR mode(clara). :param index: the horizontal speed to be used 0 to GetNumberHSSpeeds() - 1 """ ans = self.lib.SetHSSpeed(ct.c_int(self.amp_typ), ct.c_int(index)) if ans == 20002: self.horiz_shift_speed_index = index @Feat() def fastest_recommended_vsspeed(self): """As your Andor SDK system may be capable of operating at more than one vertical shift speed this function will return the fastest recommended speed available. The very high readout speeds, may require an increase in the amplitude of the Vertical Clock Voltage using SetVSAmplitude. This function returns the fastest speed which does not require the Vertical Clock Voltage to be adjusted. The values returned are the vertical shift speed index and the actual speed in microseconds per pixel shift. """ inti, f2 = ct.c_int(), ct.c_float() self.lib.GetFastestRecommendedVSSpeed(ct.pointer(inti), ct.pointer(f2)) return (inti.value, f2.value) @Feat(read_once=True) def n_vert_clock_amps(self): """This function will normally return the number of vertical clock voltage amplitudes that the camera has. """ n = ct.c_int() self.lib.GetNumberVSAmplitudes(ct.pointer(n)) return n.value def vert_amp_index(self, string): """This Function is used to get the index of the Vertical Clock Amplitude that corresponds to the string passed in. :param string: "Normal" , "+1" , "+2" , "+3" , "+4" """ index = ct.c_int() string = ct.c_char_p(str.encode(string)) self.lib.GetVSAmplitudeFromString(string, ct.pointer(index)) return index.value def vert_amp_string(self, index): """This Function is used to get the Vertical Clock Amplitude string that corresponds to the index passed in. :param index: Index of VS amplitude required Valid values 0 to GetNumberVSAmplitudes() - 1 """ index = ct.c_int(index) string = (ct.c_char * 6)() self.lib.GetVSAmplitudeString(index, ct.pointer(string)) return str(string.value)[2:-1] def true_vert_amp(self, index): """This Function is used to get the value of the Vertical Clock Amplitude found at the index passed in. :param index: Index of VS amplitude required Valid values 0 to GetNumberVSAmplitudes() - 1 """ index = ct.c_int(index) amp = ct.c_int() self.lib.GetVSAmplitudeValue(index, ct.pointer(amp)) return amp.value @Action() def set_vert_clock(self, index): """If you choose a high readout speed (a low readout time), then you should also consider increasing the amplitude of the Vertical Clock Voltage. There are five levels of amplitude available for you to choose from: - Normal, +1, +2, +3, +4 Exercise caution when increasing the amplitude of the vertical clock voltage, since higher clocking voltages may result in increased clock-induced charge (noise) in your signal. In general, only the very highest vertical clocking speeds are likely to benefit from an increased vertical clock voltage amplitude. """ self.lib.SetVSAmplitude(ct.c_int(index)) @Feat(read_once=True) def n_vert_shift_speeds(self): """As your Andor system may be capable of operating at more than one vertical shift speed this function will return the actual number of speeds available. """ n = ct.c_int() self.lib.GetNumberVSSpeeds(ct.pointer(n)) return n.value def true_vert_shift_speed(self, index=0): """As your Andor SDK system may be capable of operating at more than one vertical shift speed this function will return the actual speeds available. The value returned is in microseconds. """ speed = ct.c_float() self.lib.GetVSSpeed(ct.c_int(index), ct.pointer(speed)) return speed.value * us @Feat() def vert_shift_speed(self): return self.vert_shift_speed_index @vert_shift_speed.setter def vert_shift_speed(self, index): """This function will set the vertical speed to be used for subsequent acquisitions. """ self.vert_shift_speed_index = index self.lib.SetVSSpeed(ct.c_int(index)) ### BASELINE @Feat(values={True: 1, False: 0}) def baseline_clamp(self): """This function returns the status of the baseline clamp functionality. With this feature enabled the baseline level of each scan in a kinetic series will be more consistent across the sequence. """ i = ct.c_int() self.lib.GetBaselineClamp(ct.pointer(i)) return i.value @baseline_clamp.setter def baseline_clamp(self, value): value = ct.c_int(value) self.lib.SetBaselineClamp(value) @Feat(limits=(-1000, 1100, 100)) def baseline_offset(self): """This function allows the user to move the baseline level by the amount selected. For example “+100” will add approximately 100 counts to the default baseline value. The value entered should be a multiple of 100 between -1000 and +1000 inclusively. """ return self.baseline_offset_value @baseline_offset.setter def baseline_offset(self, value): ans = self.lib.SetBaselineOffset(ct.c_int(value)) if ans == 20002: self.baseline_offset_value = value ### BIT DEPTH def bit_depth(self, ch): """This function will retrieve the size in bits of the dynamic range for any available AD channel. """ ch = ct.c_int(ch) depth = ct.c_uint() self.lib.GetBitDepth(ch, ct.pointer(depth)) return depth.value ### TRIGGER @Feat(values={True: 1, False: 0}) def adv_trigger_mode(self): """This function will set the state for the iCam functionality that some cameras are capable of. There may be some cases where we wish to prevent the software using the new functionality and just do it the way it was previously done. """ return self.adv_trigger_mode_state @adv_trigger_mode.setter def adv_trigger_mode(self, state): ans = self.lib.SetAdvancedTriggerModeState(ct.c_int(state)) if ans == 20002: self.adv_trigger_mode_state = state def trigger_mode_available(self, modestr): """This function checks if the hardware and current settings permit the use of the specified trigger mode. """ index = self.triggers[modestr] ans = self.lib.IsTriggerModeAvailable(ct.c_int(index)) if ans == 20002: return True else: return False @Feat(values={'Internal': 0, 'External': 1, 'External Start': 6, 'External Exposure': 7, 'External FVB EM': 9, 'Software Trigger': 10, 'External Charge Shifting': 12}) def trigger_mode(self): """This function will set the trigger mode that the camera will operate in. """ return self.trigger_mode_index @trigger_mode.setter def trigger_mode(self, mode): ans = self.lib.SetTriggerMode(ct.c_int(mode)) if ans == 20002: self.trigger_mode_index = mode @Action() def send_software_trigger(self): """This function sends an event to the camera to take an acquisition when in Software Trigger mode. Not all cameras have this mode available to them. To check if your camera can operate in this mode check the GetCapabilities function for the Trigger Mode AC_TRIGGERMODE_CONTINUOUS. If this mode is physically possible and other settings are suitable (IsTriggerModeAvailable) and the camera is acquiring then this command will take an acquisition. NOTES: The settings of the camera must be as follows: - ReadOut mode is full image - RunMode is Run Till Abort - TriggerMode is 10 """ self.lib.SendSoftwareTrigger() @Action() def trigger_level(self, value): """This function sets the trigger voltage which the system will use. """ self.lib.SetTriggerLevel(ct.c_float(value)) ### AUXPORT @DictFeat(values={True: not(0), False: 0}, keys=list(range(1, 5))) def in_aux_port(self, port): """This function returns the state of the TTL Auxiliary Input Port on the Andor plug-in card. """ port = ct.c_int(port) state = ct.c_int() self.lib.InAuxPort(port, ct.pointer(state)) return state.value @DictFeat(values={True: 1, False: 0}, keys=list(range(1, 5))) def out_aux_port(self, port): """This function sets the TTL Auxiliary Output port (P) on the Andor plug-in card to either ON/HIGH or OFF/LOW. """ return self.auxout[port - 1] @out_aux_port.setter def out_aux_port(self, port, state): self.auxout[port - 1] = bool(state) port = ct.c_int(port) state = ct.c_int(state) self.lib.OutAuxPort(port, ct.pointer(state)) def is_implemented(self, strcommand): """Checks if command is implemented. """ result = ct.c_bool() command = ct.c_wchar_p(strcommand) self.lib.AT_IsImplemented(self.AT_H, command, ct.addressof(result)) return result.value def is_writable(self, strcommand): """Checks if command is writable. """ result = ct.c_bool() command = ct.c_wchar_p(strcommand) self.lib.AT_IsWritable(self.AT_H, command, ct.addressof(result)) return result.value def queuebuffer(self, bufptr, value): """Put buffer in queue. """ value = ct.c_int(value) self.lib.AT_QueueBuffer(self.AT_H, ct.byref(bufptr), value) def waitbuffer(self, ptr, bufsize): """Wait for next buffer ready. """ timeout = ct.c_int(20000) self.lib.AT_WaitBuffer(self.AT_H, ct.byref(ptr), ct.byref(bufsize), timeout) def command(self, strcommand): """Run command. """ command = ct.c_wchar_p(strcommand) self.lib.AT_Command(self.AT_H, command) def getint(self, strcommand): """Run command and get Int return value. """ result = ct.c_longlong() command = ct.c_wchar_p(strcommand) self.lib.AT_GetInt(self.AT_H, command, ct.addressof(result)) return result.value def setint(self, strcommand, value): """SetInt function. """ command = ct.c_wchar_p(strcommand) value = ct.c_longlong(value) self.lib.AT_SetInt(self.AT_H, command, value) def getfloat(self, strcommand): """Run command and get Int return value. """ result = ct.c_double() command = ct.c_wchar_p(strcommand) self.lib.AT_GetFloat(self.AT_H, command, ct.addressof(result)) return result.value def setfloat(self, strcommand, value): """Set command with Float value parameter. """ command = ct.c_wchar_p(strcommand) value = ct.c_double(value) self.lib.AT_SetFloat(self.AT_H, command, value) def getbool(self, strcommand): """Run command and get Bool return value. """ result = ct.c_bool() command = ct.c_wchar_p(strcommand) self.lib.AT_GetBool(self.AT_H, command, ct.addressof(result)) return result.value def setbool(self, strcommand, value): """Set command with Bool value parameter. """ command = ct.c_wchar_p(strcommand) value = ct.c_bool(value) self.lib.AT_SetBool(self.AT_H, command, value) def getenumerated(self, strcommand): """Run command and set Enumerated return value. """ result = ct.c_int() command = ct.c_wchar_p(strcommand) self.lib.AT_GetEnumerated(self.AT_H, command, ct.addressof(result)) def setenumerated(self, strcommand, value): """Set command with Enumerated value parameter. """ command = ct.c_wchar_p(strcommand) value = ct.c_bool(value) self.lib.AT_SetEnumerated(self.AT_H, command, value) def setenumstring(self, strcommand, item): """Set command with EnumeratedString value parameter. """ command = ct.c_wchar_p(strcommand) item = ct.c_wchar_p(item) self.lib.AT_SetEnumString(self.AT_H, command, item) def flush(self): self.lib.AT_Flush(self.AT_H) if __name__ == '__main__': from matplotlib import pyplot as plt from lantz import Q_ import time degC = Q_(1, 'degC') us = Q_(1, 'us') MHz = Q_(1, 'MHz') s = Q_(1, 's') with CCD() as andor: print(andor.idn) andor.free_int_mem() # Acquisition settings andor.readout_mode = 'Image' andor.set_image() # andor.acquisition_mode = 'Single Scan' andor.acquisition_mode = 'Run till abort' andor.set_exposure_time(0.03 * s) andor.trigger_mode = 'Internal' andor.amp_typ = 0 andor.horiz_shift_speed = 0 andor.vert_shift_speed = 0 andor.shutter(0, 0, 0, 0, 0) # # Temperature stabilization # andor.temperature_setpoint = -30 * degC # andor.cooler_on = True # stable = 'Temperature has stabilized at set point.' # print('Temperature set point =', andor.temperature_setpoint) # while andor.temperature_status != stable: # print("Current temperature:", np.round(andor.temperature, 1)) # time.sleep(30) # print('Temperature has stabilized at set point') # Acquisition andor.start_acquisition() time.sleep(2) data = andor.most_recent_image(shape=andor.detector_shape) andor.abort_acquisition() plt.imshow(data, cmap='gray', interpolation='None') plt.colorbar() plt.show() print(data.min(), data.max(), data.mean())
varses/awsch
lantz/drivers/andor/ccd.py
Python
bsd-3-clause
74,992
import datetime import httplib2 import itertools import json from django.conf import settings from django.db import connection, transaction from django.db.models import Sum, Max import commonware.log from apiclient.discovery import build from celeryutils import task from oauth2client.client import OAuth2Credentials import amo import amo.search from addons.models import Addon, AddonUser from bandwagon.models import Collection from lib.es.utils import get_indices from reviews.models import Review from stats.models import Contribution from users.models import UserProfile from versions.models import Version from mkt.constants.regions import REGIONS_CHOICES_SLUG from mkt.monolith.models import MonolithRecord from mkt.webapps.models import Webapp from . import search from .models import (AddonCollectionCount, CollectionCount, CollectionStats, DownloadCount, ThemeUserCount, UpdateCount) log = commonware.log.getLogger('z.task') @task def addon_total_contributions(*addons, **kw): "Updates the total contributions for a given addon." log.info('[%s@%s] Updating total contributions.' % (len(addons), addon_total_contributions.rate_limit)) # Only count uuid=None; those are verified transactions. stats = (Contribution.objects.filter(addon__in=addons, uuid=None) .values_list('addon').annotate(Sum('amount'))) for addon, total in stats: Addon.objects.filter(id=addon).update(total_contributions=total) @task def update_addons_collections_downloads(data, **kw): log.info("[%s] Updating addons+collections download totals." % (len(data))) cursor = connection.cursor() q = ("UPDATE addons_collections SET downloads=%s WHERE addon_id=%s " "AND collection_id=%s;" * len(data)) cursor.execute(q, list(itertools.chain.from_iterable( [var['sum'], var['addon'], var['collection']] for var in data))) transaction.commit_unless_managed() @task def update_collections_total(data, **kw): log.info("[%s] Updating collections' download totals." % (len(data))) for var in data: (Collection.objects.filter(pk=var['collection_id']) .update(downloads=var['sum'])) def get_profile_id(service, domain): """ Fetch the profile ID for the given domain. """ accounts = service.management().accounts().list().execute() account_ids = [a['id'] for a in accounts.get('items', ())] for account_id in account_ids: webproperties = service.management().webproperties().list( accountId=account_id).execute() webproperty_ids = [p['id'] for p in webproperties.get('items', ())] for webproperty_id in webproperty_ids: profiles = service.management().profiles().list( accountId=account_id, webPropertyId=webproperty_id).execute() for p in profiles.get('items', ()): # sometimes GA includes "http://", sometimes it doesn't. if '://' in p['websiteUrl']: name = p['websiteUrl'].partition('://')[-1] else: name = p['websiteUrl'] if name == domain: return p['id'] @task def update_google_analytics(date, **kw): creds_data = getattr(settings, 'GOOGLE_ANALYTICS_CREDENTIALS', None) if not creds_data: log.critical('Failed to update global stats: ' 'GOOGLE_ANALYTICS_CREDENTIALS not set') return creds = OAuth2Credentials( *[creds_data[k] for k in ('access_token', 'client_id', 'client_secret', 'refresh_token', 'token_expiry', 'token_uri', 'user_agent')]) h = httplib2.Http() creds.authorize(h) service = build('analytics', 'v3', http=h) domain = getattr(settings, 'GOOGLE_ANALYTICS_DOMAIN', None) or settings.DOMAIN profile_id = get_profile_id(service, domain) if profile_id is None: log.critical('Failed to update global stats: could not access a Google' ' Analytics profile for ' + domain) return datestr = date.strftime('%Y-%m-%d') try: data = service.data().ga().get(ids='ga:' + profile_id, start_date=datestr, end_date=datestr, metrics='ga:visits').execute() # Storing this under the webtrends stat name so it goes on the # same graph as the old webtrends data. p = ['webtrends_DailyVisitors', data['rows'][0][0], date] except Exception, e: log.critical( 'Fetching stats data for %s from Google Analytics failed: %s' % e) return try: cursor = connection.cursor() cursor.execute('REPLACE INTO global_stats (name, count, date) ' 'values (%s, %s, %s)', p) transaction.commit_unless_managed() except Exception, e: log.critical('Failed to update global stats: (%s): %s' % (p, e)) return log.debug('Committed global stats details: (%s) has (%s) for (%s)' % tuple(p)) @task def update_global_totals(job, date, **kw): log.info('Updating global statistics totals (%s) for (%s)' % (job, date)) jobs = _get_daily_jobs(date) jobs.update(_get_metrics_jobs(date)) num = jobs[job]() q = """REPLACE INTO global_stats (`name`, `count`, `date`) VALUES (%s, %s, %s)""" p = [job, num or 0, date] try: cursor = connection.cursor() cursor.execute(q, p) transaction.commit_unless_managed() except Exception, e: log.critical('Failed to update global stats: (%s): %s' % (p, e)) log.debug('Committed global stats details: (%s) has (%s) for (%s)' % tuple(p)) def _get_daily_jobs(date=None): """Return a dictionary of statistics queries. If a date is specified and applies to the job it will be used. Otherwise the date will default to today(). """ if not date: date = datetime.date.today() # Passing through a datetime would not generate an error, # but would pass and give incorrect values. if isinstance(date, datetime.datetime): raise ValueError('This requires a valid date, not a datetime') # Testing on lte created date doesn't get you todays date, you need to do # less than next date. That's because 2012-1-1 becomes 2012-1-1 00:00 next_date = date + datetime.timedelta(days=1) date_str = date.strftime('%Y-%m-%d') extra = dict(where=['DATE(created)=%s'], params=[date_str]) # If you're editing these, note that you are returning a function! This # cheesy hackery was done so that we could pass the queries to celery # lazily and not hammer the db with a ton of these all at once. stats = { # Add-on Downloads 'addon_total_downloads': lambda: DownloadCount.objects.filter( date__lt=next_date).aggregate(sum=Sum('count'))['sum'], 'addon_downloads_new': lambda: DownloadCount.objects.filter( date=date).aggregate(sum=Sum('count'))['sum'], # Add-on counts 'addon_count_new': Addon.objects.extra(**extra).count, # Version counts 'version_count_new': Version.objects.extra(**extra).count, # User counts 'user_count_total': UserProfile.objects.filter( created__lt=next_date).count, 'user_count_new': UserProfile.objects.extra(**extra).count, # Review counts 'review_count_total': Review.objects.filter(created__lte=date, editorreview=0).count, 'review_count_new': Review.objects.filter(editorreview=0).extra( **extra).count, # Collection counts 'collection_count_total': Collection.objects.filter( created__lt=next_date).count, 'collection_count_new': Collection.objects.extra(**extra).count, 'collection_count_autopublishers': Collection.objects.filter( created__lt=next_date, type=amo.COLLECTION_SYNCHRONIZED).count, 'collection_addon_downloads': (lambda: AddonCollectionCount.objects.filter(date__lte=date).aggregate( sum=Sum('count'))['sum']), } # If we're processing today's stats, we'll do some extras. We don't do # these for re-processed stats because they change over time (eg. add-ons # move from sandbox -> public if date == datetime.date.today(): stats.update({ 'addon_count_experimental': Addon.objects.filter( created__lte=date, status=amo.STATUS_UNREVIEWED, disabled_by_user=0).count, 'addon_count_nominated': Addon.objects.filter( created__lte=date, status=amo.STATUS_NOMINATED, disabled_by_user=0).count, 'addon_count_public': Addon.objects.filter( created__lte=date, status=amo.STATUS_PUBLIC, disabled_by_user=0).count, 'addon_count_pending': Version.objects.filter( created__lte=date, files__status=amo.STATUS_PENDING).count, 'collection_count_private': Collection.objects.filter( created__lte=date, listed=0).count, 'collection_count_public': Collection.objects.filter( created__lte=date, listed=1).count, 'collection_count_editorspicks': Collection.objects.filter( created__lte=date, type=amo.COLLECTION_FEATURED).count, 'collection_count_normal': Collection.objects.filter( created__lte=date, type=amo.COLLECTION_NORMAL).count, }) return stats def _get_metrics_jobs(date=None): """Return a dictionary of statistics queries. If a date is specified and applies to the job it will be used. Otherwise the date will default to the last date metrics put something in the db. """ if not date: date = UpdateCount.objects.aggregate(max=Max('date'))['max'] # If you're editing these, note that you are returning a function! stats = { 'addon_total_updatepings': lambda: UpdateCount.objects.filter( date=date).aggregate(sum=Sum('count'))['sum'], 'collector_updatepings': lambda: UpdateCount.objects.get( addon=11950, date=date).count, } return stats @task def index_update_counts(ids, **kw): index = kw.pop('index', None) indices = get_indices(index) es = amo.search.get_es() qs = UpdateCount.objects.filter(id__in=ids) if qs: log.info('Indexing %s updates for %s.' % (qs.count(), qs[0].date)) try: for update in qs: key = '%s-%s' % (update.addon_id, update.date) data = search.extract_update_count(update) for index in indices: UpdateCount.index(data, bulk=True, id=key, index=index) es.flush_bulk(forced=True) except Exception, exc: index_update_counts.retry(args=[ids], exc=exc, **kw) raise @task def index_download_counts(ids, **kw): index = kw.pop('index', None) indices = get_indices(index) es = amo.search.get_es() qs = DownloadCount.objects.filter(id__in=ids) if qs: log.info('Indexing %s downloads for %s.' % (qs.count(), qs[0].date)) try: for dl in qs: key = '%s-%s' % (dl.addon_id, dl.date) data = search.extract_download_count(dl) for index in indices: DownloadCount.index(data, bulk=True, id=key, index=index) es.flush_bulk(forced=True) except Exception, exc: index_download_counts.retry(args=[ids], exc=exc) raise @task def index_collection_counts(ids, **kw): index = kw.pop('index', None) indices = get_indices(index) es = amo.search.get_es() qs = CollectionCount.objects.filter(collection__in=ids) if qs: log.info('Indexing %s addon collection counts: %s' % (qs.count(), qs[0].date)) try: for collection_count in qs: collection = collection_count.collection_id key = '%s-%s' % (collection, collection_count.date) filters = dict(collection=collection, date=collection_count.date) data = search.extract_addon_collection( collection_count, AddonCollectionCount.objects.filter(**filters), CollectionStats.objects.filter(**filters)) for index in indices: CollectionCount.index(data, bulk=True, id=key, index=index) es.flush_bulk(forced=True) except Exception, exc: index_collection_counts.retry(args=[ids], exc=exc) raise @task def index_theme_user_counts(ids, **kw): index = kw.pop('index', None) indices = get_indices(index) es = amo.search.get_es() qs = ThemeUserCount.objects.filter(id__in=ids) if qs: log.info('Indexing %s theme user counts for %s.' % (qs.count(), qs[0].date)) try: for user_count in qs: key = '%s-%s' % (user_count.addon_id, user_count.date) data = search.extract_theme_user_count(user_count) for index in indices: ThemeUserCount.index(data, bulk=True, id=key, index=index) es.flush_bulk(forced=True) except Exception, exc: index_theme_user_counts.retry(args=[ids], exc=exc) raise @task def update_monolith_stats(metric, date, **kw): log.info('Updating monolith statistics (%s) for (%s)' % (metric, date)) jobs = _get_monolith_jobs(date)[metric] for job in jobs: try: # Only record if count is greater than zero. count = job['count']() if count: value = {'count': count} if 'dimensions' in job: value.update(job['dimensions']) MonolithRecord.objects.create(recorded=date, key=metric, value=json.dumps(value)) log.debug('Monolith stats details: (%s) has (%s) for (%s). ' 'Value: %s' % (metric, count, date, value)) except Exception as e: log.critical('Update of monolith table failed: (%s): %s' % ([metric, date], e)) def _get_monolith_jobs(date=None): """ Return a dict of Monolith based statistics queries. The dict is of the form:: {'<metric_name>': [{'count': <callable>, 'dimensions': <dimensions>}]} Where `dimensions` is an optional dict of dimensions we expect to filter on via Monolith. If a date is specified and applies to the job it will be used. Otherwise the date will default to today(). """ if not date: date = datetime.date.today() # If we have a datetime make it a date so H/M/S isn't used. if isinstance(date, datetime.datetime): date = date.date() next_date = date + datetime.timedelta(days=1) stats = { # Marketplace reviews. 'apps_review_count_new': [{ 'count': Review.objects.filter( created__range=(date, next_date), editorreview=0, addon__type=amo.ADDON_WEBAPP).count, }], # New users 'mmo_user_count_total': [{ 'count': UserProfile.objects.filter( created__lt=next_date, source=amo.LOGIN_SOURCE_MMO_BROWSERID).count, }], 'mmo_user_count_new': [{ 'count': UserProfile.objects.filter( created__range=(date, next_date), source=amo.LOGIN_SOURCE_MMO_BROWSERID).count, }], # New developers. 'mmo_developer_count_total': [{ 'count': AddonUser.objects.filter( addon__type=amo.ADDON_WEBAPP).values('user').distinct().count, }], # App counts. 'apps_count_new': [{ 'count': Webapp.objects.filter( created__range=(date, next_date)).count, }], } # Add various "Apps Added" for all the dimensions we need. apps = Webapp.objects.filter(created__range=(date, next_date)) package_counts = [] premium_counts = [] # privileged==packaged for our consideration. package_types = amo.ADDON_WEBAPP_TYPES.copy() package_types.pop(amo.ADDON_WEBAPP_PRIVILEGED) for region_slug, region in REGIONS_CHOICES_SLUG: # Apps added by package type and region. for package_type in package_types.values(): package_counts.append({ 'count': apps.filter( is_packaged=package_type == 'packaged').exclude( addonexcludedregion__region=region.id).count, 'dimensions': {'region': region_slug, 'package_type': package_type}, }) # Apps added by premium type and region. for premium_type, pt_name in amo.ADDON_PREMIUM_API.items(): premium_counts.append({ 'count': apps.filter( premium_type=premium_type).exclude( addonexcludedregion__region=region.id).count, 'dimensions': {'region': region_slug, 'premium_type': pt_name}, }) stats.update({'apps_added_by_package_type': package_counts}) stats.update({'apps_added_by_premium_type': premium_counts}) # Add various "Apps Available" for all the dimensions we need. apps = Webapp.objects.filter(status=amo.STATUS_PUBLIC, disabled_by_user=False) package_counts = [] premium_counts = [] for region_slug, region in REGIONS_CHOICES_SLUG: # Apps available by package type and region. for package_type in package_types.values(): package_counts.append({ 'count': apps.filter( is_packaged=package_type == 'packaged').exclude( addonexcludedregion__region=region.id).count, 'dimensions': {'region': region_slug, 'package_type': package_type}, }) # Apps available by premium type and region. for premium_type, pt_name in amo.ADDON_PREMIUM_API.items(): premium_counts.append({ 'count': apps.filter( premium_type=premium_type).exclude( addonexcludedregion__region=region.id).count, 'dimensions': {'region': region_slug, 'premium_type': pt_name}, }) stats.update({'apps_available_by_package_type': package_counts}) stats.update({'apps_available_by_premium_type': premium_counts}) return stats
wagnerand/zamboni
apps/stats/tasks.py
Python
bsd-3-clause
19,050
import hashlib import logging import os from django.conf import settings from django.core.files.storage import default_storage as storage from django.db import transaction from PIL import Image from olympia import amo from olympia.addons.models import ( Addon, attach_tags, attach_translations, AppSupport, CompatOverride, IncompatibleVersions, Persona, Preview) from olympia.addons.indexers import AddonIndexer from olympia.amo.celery import task from olympia.amo.decorators import set_modified_on, write from olympia.amo.helpers import user_media_path from olympia.amo.storage_utils import rm_stored_dir from olympia.amo.utils import cache_ns_key, ImageCheck, LocalFileStorage from olympia.editors.models import RereviewQueueTheme from olympia.lib.es.utils import index_objects from olympia.versions.models import Version # pulling tasks from cron from . import cron # noqa log = logging.getLogger('z.task') @task @write def version_changed(addon_id, **kw): update_last_updated(addon_id) update_appsupport([addon_id]) def update_last_updated(addon_id): queries = Addon._last_updated_queries() try: addon = Addon.objects.get(pk=addon_id) except Addon.DoesNotExist: log.info('[1@None] Updating last updated for %s failed, no addon found' % addon_id) return log.info('[1@None] Updating last updated for %s.' % addon_id) if addon.is_persona(): q = 'personas' elif addon.status == amo.STATUS_PUBLIC: q = 'public' else: q = 'exp' qs = queries[q].filter(pk=addon_id).using('default') res = qs.values_list('id', 'last_updated') if res: pk, t = res[0] Addon.objects.filter(pk=pk).update(last_updated=t) @write def update_appsupport(ids): log.info("[%s@None] Updating appsupport for %s." % (len(ids), ids)) addons = Addon.objects.no_cache().filter(id__in=ids).no_transforms() support = [] for addon in addons: for app, appver in addon.compatible_apps.items(): if appver is None: # Fake support for all version ranges. min_, max_ = 0, 999999999999999999 else: min_, max_ = appver.min.version_int, appver.max.version_int support.append(AppSupport(addon=addon, app=app.id, min=min_, max=max_)) if not support: return with transaction.atomic(): AppSupport.objects.filter(addon__id__in=ids).delete() AppSupport.objects.bulk_create(support) # All our updates were sql, so invalidate manually. Addon.objects.invalidate(*addons) @task def delete_preview_files(id, **kw): log.info('[1@None] Removing preview with id of %s.' % id) p = Preview(id=id) for f in (p.thumbnail_path, p.image_path): try: storage.delete(f) except Exception, e: log.error('Error deleting preview file (%s): %s' % (f, e)) @task(acks_late=True) def index_addons(ids, **kw): log.info('Indexing addons %s-%s. [%s]' % (ids[0], ids[-1], len(ids))) transforms = (attach_tags, attach_translations) index_objects(ids, Addon, AddonIndexer.extract_document, kw.pop('index', None), transforms, Addon.unfiltered) @task def unindex_addons(ids, **kw): for addon in ids: log.info('Removing addon [%s] from search index.' % addon) Addon.unindex(addon) @task def delete_persona_image(dst, **kw): log.info('[1@None] Deleting persona image: %s.' % dst) if not dst.startswith(user_media_path('addons')): log.error("Someone tried deleting something they shouldn't: %s" % dst) return try: storage.delete(dst) except Exception, e: log.error('Error deleting persona image: %s' % e) @set_modified_on def create_persona_preview_images(src, full_dst, **kw): """ Creates a 680x100 thumbnail used for the Persona preview and a 32x32 thumbnail used for search suggestions/detail pages. """ log.info('[1@None] Resizing persona images: %s' % full_dst) preview, full = amo.PERSONA_IMAGE_SIZES['header'] preview_w, preview_h = preview orig_w, orig_h = full with storage.open(src) as fp: i_orig = i = Image.open(fp) # Crop image from the right. i = i.crop((orig_w - (preview_w * 2), 0, orig_w, orig_h)) # Resize preview. i = i.resize(preview, Image.ANTIALIAS) i.load() with storage.open(full_dst[0], 'wb') as fp: i.save(fp, 'png') _, icon_size = amo.PERSONA_IMAGE_SIZES['icon'] icon_w, icon_h = icon_size # Resize icon. i = i_orig i.load() i = i.crop((orig_w - (preview_h * 2), 0, orig_w, orig_h)) i = i.resize(icon_size, Image.ANTIALIAS) i.load() with storage.open(full_dst[1], 'wb') as fp: i.save(fp, 'png') return True @set_modified_on def save_persona_image(src, full_dst, **kw): """Creates a PNG of a Persona header/footer image.""" log.info('[1@None] Saving persona image: %s' % full_dst) img = ImageCheck(storage.open(src)) if not img.is_image(): log.error('Not an image: %s' % src, exc_info=True) return with storage.open(src, 'rb') as fp: i = Image.open(fp) with storage.open(full_dst, 'wb') as fp: i.save(fp, 'png') return True @task def update_incompatible_appversions(data, **kw): """Updates the incompatible_versions table for this version.""" log.info('Updating incompatible_versions for %s versions.' % len(data)) addon_ids = set() for version_id in data: # This is here to handle both post_save and post_delete hooks. IncompatibleVersions.objects.filter(version=version_id).delete() try: version = Version.objects.get(pk=version_id) except Version.DoesNotExist: log.info('Version ID [%d] not found. Incompatible versions were ' 'cleared.' % version_id) return addon_ids.add(version.addon_id) try: compat = CompatOverride.objects.get(addon=version.addon) except CompatOverride.DoesNotExist: log.info('Compat override for addon with version ID [%d] not ' 'found. Incompatible versions were cleared.' % version_id) return app_ranges = [] ranges = compat.collapsed_ranges() for range in ranges: if range.min == '0' and range.max == '*': # Wildcard range, add all app ranges app_ranges.extend(range.apps) else: # Since we can't rely on add-on version numbers, get the min # and max ID values and find versions whose ID is within those # ranges, being careful with wildcards. min_id = max_id = None if range.min == '0': versions = (Version.objects.filter(addon=version.addon_id) .order_by('id') .values_list('id', flat=True)[:1]) if versions: min_id = versions[0] else: try: min_id = Version.objects.get(addon=version.addon_id, version=range.min).id except Version.DoesNotExist: pass if range.max == '*': versions = (Version.objects.filter(addon=version.addon_id) .order_by('-id') .values_list('id', flat=True)[:1]) if versions: max_id = versions[0] else: try: max_id = Version.objects.get(addon=version.addon_id, version=range.max).id except Version.DoesNotExist: pass if min_id and max_id: if min_id <= version.id <= max_id: app_ranges.extend(range.apps) for app_range in app_ranges: IncompatibleVersions.objects.create(version=version, app=app_range.app.id, min_app_version=app_range.min, max_app_version=app_range.max) log.info('Added incompatible version for version ID [%d]: ' 'app:%d, %s -> %s' % (version_id, app_range.app.id, app_range.min, app_range.max)) # Increment namespace cache of compat versions. for addon_id in addon_ids: cache_ns_key('d2c-versions:%s' % addon_id, increment=True) def make_checksum(header_path, footer_path): ls = LocalFileStorage() footer = footer_path and ls._open(footer_path).read() or '' raw_checksum = ls._open(header_path).read() + footer return hashlib.sha224(raw_checksum).hexdigest() def theme_checksum(theme, **kw): theme.checksum = make_checksum(theme.header_path, theme.footer_path) dupe_personas = Persona.objects.filter(checksum=theme.checksum) if dupe_personas.exists(): theme.dupe_persona = dupe_personas[0] theme.save() def rereviewqueuetheme_checksum(rqt, **kw): """Check for possible duplicate theme images.""" dupe_personas = Persona.objects.filter( checksum=make_checksum(rqt.header_path or rqt.theme.header_path, rqt.footer_path or rqt.theme.footer_path)) if dupe_personas.exists(): rqt.dupe_persona = dupe_personas[0] rqt.save() @task @write def save_theme(header, footer, addon, **kw): """Save theme image and calculates checksum after theme save.""" dst_root = os.path.join(user_media_path('addons'), str(addon.id)) header = os.path.join(settings.TMP_PATH, 'persona_header', header) header_dst = os.path.join(dst_root, 'header.png') if footer: footer = os.path.join(settings.TMP_PATH, 'persona_footer', footer) footer_dst = os.path.join(dst_root, 'footer.png') try: save_persona_image(src=header, full_dst=header_dst) if footer: save_persona_image(src=footer, full_dst=footer_dst) create_persona_preview_images( src=header, full_dst=[os.path.join(dst_root, 'preview.png'), os.path.join(dst_root, 'icon.png')], set_modified_on=[addon]) theme_checksum(addon.persona) except IOError: addon.delete() raise @task @write def save_theme_reupload(header, footer, addon, **kw): header_dst = None footer_dst = None dst_root = os.path.join(user_media_path('addons'), str(addon.id)) try: if header: header = os.path.join(settings.TMP_PATH, 'persona_header', header) header_dst = os.path.join(dst_root, 'pending_header.png') save_persona_image(src=header, full_dst=header_dst) if footer: footer = os.path.join(settings.TMP_PATH, 'persona_footer', footer) footer_dst = os.path.join(dst_root, 'pending_footer.png') save_persona_image(src=footer, full_dst=footer_dst) except IOError as e: log.error(str(e)) raise if header_dst or footer_dst: theme = addon.persona header = 'pending_header.png' if header_dst else theme.header # Theme footer is optional, but can't be None. footer = theme.footer or '' if footer_dst: footer = 'pending_footer.png' # Store pending header and/or footer file paths for review. RereviewQueueTheme.objects.filter(theme=theme).delete() rqt = RereviewQueueTheme(theme=theme, header=header, footer=footer) rereviewqueuetheme_checksum(rqt=rqt) rqt.save() @task @write def calc_checksum(theme_id, **kw): """For migration 596.""" lfs = LocalFileStorage() theme = Persona.objects.get(id=theme_id) header = theme.header_path footer = theme.footer_path # Delete invalid themes that are not images (e.g. PDF, EXE). try: Image.open(header) Image.open(footer) except IOError: log.info('Deleting invalid theme [%s] (header: %s) (footer: %s)' % (theme.addon.id, header, footer)) theme.addon.delete() theme.delete() rm_stored_dir(header.replace('header.png', ''), storage=lfs) return # Calculate checksum and save. try: theme.checksum = make_checksum(header, footer) theme.save() except IOError as e: log.error(str(e))
mstriemer/addons-server
src/olympia/addons/tasks.py
Python
bsd-3-clause
12,888
using System; using Polly.CircuitBreaker; namespace Polly { /// <summary> /// Fluent API for defining a Circuit Breaker <see cref="Policy"/>. /// </summary> public static class CircuitBreakerSyntax { /// <summary> /// <para> Builds a <see cref="Policy"/> that will function like a Circuit Breaker.</para> /// <para>The circuit will break after <paramref name="exceptionsAllowedBeforeBreaking"/> /// exceptions that are handled by this policy are raised. The circuit will stay /// broken for the <paramref name="durationOfBreak"/>. Any attempt to execute this policy /// while the circuit is broken, will immediately throw a <see cref="BrokenCircuitException"/> containing the exception /// that broke the cicuit. /// </para> /// <para>If the first action after the break duration period results in an exception, the circuit will break /// again for another <paramref name="durationOfBreak"/>, otherwise it will reset. /// </para> /// </summary> /// <param name="policyBuilder">The policy builder.</param> /// <param name="exceptionsAllowedBeforeBreaking">The number of exceptions that are allowed before opening the circuit.</param> /// <param name="durationOfBreak">The duration the circuit will stay open before resetting.</param> /// <returns>The policy instance.</returns> /// <remarks>(see "Release It!" by Michael T. Nygard fi)</remarks> /// <exception cref="System.ArgumentOutOfRangeException">exceptionsAllowedBeforeBreaking;Value must be greater than zero.</exception> public static Policy CircuitBreaker(this PolicyBuilder policyBuilder, int exceptionsAllowedBeforeBreaking, TimeSpan durationOfBreak) { if (exceptionsAllowedBeforeBreaking <= 0) throw new ArgumentOutOfRangeException("exceptionsAllowedBeforeBreaking", "Value must be greater than zero."); var policyState = new CircuitBreakerState(exceptionsAllowedBeforeBreaking, durationOfBreak); return new Policy(action => CircuitBreakerPolicy.Implementation(action, policyBuilder.ExceptionPredicates, policyState), policyBuilder.ExceptionPredicates); } } }
joelhulen/Polly
src/Polly.Shared/CircuitBreakerSyntax.cs
C#
bsd-3-clause
2,252
//===- AliasSetTracker.cpp - Alias Sets Tracker implementation-------------===// // // 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 // //===----------------------------------------------------------------------===// // // This file implements the AliasSetTracker and AliasSet classes. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/AliasSetTracker.h" #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/GuardUtils.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Analysis/MemoryLocation.h" #include "llvm/Analysis/MemorySSA.h" #include "llvm/Config/llvm-config.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/Function.h" #include "llvm/IR/InstIterator.h" #include "llvm/IR/Instruction.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/Module.h" #include "llvm/IR/PatternMatch.h" #include "llvm/IR/Value.h" #include "llvm/InitializePasses.h" #include "llvm/Pass.h" #include "llvm/Support/AtomicOrdering.h" #include "llvm/Support/Casting.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #include <cassert> #include <cstdint> #include <vector> using namespace llvm; static cl::opt<unsigned> SaturationThreshold("alias-set-saturation-threshold", cl::Hidden, cl::init(250), cl::desc("The maximum number of pointers may-alias " "sets may contain before degradation")); /// mergeSetIn - Merge the specified alias set into this alias set. /// void AliasSet::mergeSetIn(AliasSet &AS, AliasSetTracker &AST) { assert(!AS.Forward && "Alias set is already forwarding!"); assert(!Forward && "This set is a forwarding set!!"); bool WasMustAlias = (Alias == SetMustAlias); // Update the alias and access types of this set... Access |= AS.Access; Alias |= AS.Alias; if (Alias == SetMustAlias) { // Check that these two merged sets really are must aliases. Since both // used to be must-alias sets, we can just check any pointer from each set // for aliasing. AliasAnalysis &AA = AST.getAliasAnalysis(); PointerRec *L = getSomePointer(); PointerRec *R = AS.getSomePointer(); // If the pointers are not a must-alias pair, this set becomes a may alias. if (AA.alias(MemoryLocation(L->getValue(), L->getSize(), L->getAAInfo()), MemoryLocation(R->getValue(), R->getSize(), R->getAAInfo())) != MustAlias) Alias = SetMayAlias; } if (Alias == SetMayAlias) { if (WasMustAlias) AST.TotalMayAliasSetSize += size(); if (AS.Alias == SetMustAlias) AST.TotalMayAliasSetSize += AS.size(); } bool ASHadUnknownInsts = !AS.UnknownInsts.empty(); if (UnknownInsts.empty()) { // Merge call sites... if (ASHadUnknownInsts) { std::swap(UnknownInsts, AS.UnknownInsts); addRef(); } } else if (ASHadUnknownInsts) { UnknownInsts.insert(UnknownInsts.end(), AS.UnknownInsts.begin(), AS.UnknownInsts.end()); AS.UnknownInsts.clear(); } AS.Forward = this; // Forward across AS now... addRef(); // AS is now pointing to us... // Merge the list of constituent pointers... if (AS.PtrList) { SetSize += AS.size(); AS.SetSize = 0; *PtrListEnd = AS.PtrList; AS.PtrList->setPrevInList(PtrListEnd); PtrListEnd = AS.PtrListEnd; AS.PtrList = nullptr; AS.PtrListEnd = &AS.PtrList; assert(*AS.PtrListEnd == nullptr && "End of list is not null?"); } if (ASHadUnknownInsts) AS.dropRef(AST); } void AliasSetTracker::removeAliasSet(AliasSet *AS) { if (AliasSet *Fwd = AS->Forward) { Fwd->dropRef(*this); AS->Forward = nullptr; } else // Update TotalMayAliasSetSize only if not forwarding. if (AS->Alias == AliasSet::SetMayAlias) TotalMayAliasSetSize -= AS->size(); AliasSets.erase(AS); // If we've removed the saturated alias set, set saturated marker back to // nullptr and ensure this tracker is empty. if (AS == AliasAnyAS) { AliasAnyAS = nullptr; assert(AliasSets.empty() && "Tracker not empty"); } } void AliasSet::removeFromTracker(AliasSetTracker &AST) { assert(RefCount == 0 && "Cannot remove non-dead alias set from tracker!"); AST.removeAliasSet(this); } void AliasSet::addPointer(AliasSetTracker &AST, PointerRec &Entry, LocationSize Size, const AAMDNodes &AAInfo, bool KnownMustAlias, bool SkipSizeUpdate) { assert(!Entry.hasAliasSet() && "Entry already in set!"); // Check to see if we have to downgrade to _may_ alias. if (isMustAlias()) if (PointerRec *P = getSomePointer()) { if (!KnownMustAlias) { AliasAnalysis &AA = AST.getAliasAnalysis(); AliasResult Result = AA.alias( MemoryLocation(P->getValue(), P->getSize(), P->getAAInfo()), MemoryLocation(Entry.getValue(), Size, AAInfo)); if (Result != MustAlias) { Alias = SetMayAlias; AST.TotalMayAliasSetSize += size(); } assert(Result != NoAlias && "Cannot be part of must set!"); } else if (!SkipSizeUpdate) P->updateSizeAndAAInfo(Size, AAInfo); } Entry.setAliasSet(this); Entry.updateSizeAndAAInfo(Size, AAInfo); // Add it to the end of the list... ++SetSize; assert(*PtrListEnd == nullptr && "End of list is not null?"); *PtrListEnd = &Entry; PtrListEnd = Entry.setPrevInList(PtrListEnd); assert(*PtrListEnd == nullptr && "End of list is not null?"); // Entry points to alias set. addRef(); if (Alias == SetMayAlias) AST.TotalMayAliasSetSize++; } void AliasSet::addUnknownInst(Instruction *I, AliasAnalysis &AA) { if (UnknownInsts.empty()) addRef(); UnknownInsts.emplace_back(I); // Guards are marked as modifying memory for control flow modelling purposes, // but don't actually modify any specific memory location. using namespace PatternMatch; bool MayWriteMemory = I->mayWriteToMemory() && !isGuard(I) && !(I->use_empty() && match(I, m_Intrinsic<Intrinsic::invariant_start>())); if (!MayWriteMemory) { Alias = SetMayAlias; Access |= RefAccess; return; } // FIXME: This should use mod/ref information to make this not suck so bad Alias = SetMayAlias; Access = ModRefAccess; } /// aliasesPointer - If the specified pointer "may" (or must) alias one of the /// members in the set return the appropriate AliasResult. Otherwise return /// NoAlias. /// AliasResult AliasSet::aliasesPointer(const Value *Ptr, LocationSize Size, const AAMDNodes &AAInfo, AliasAnalysis &AA) const { if (AliasAny) return MayAlias; if (Alias == SetMustAlias) { assert(UnknownInsts.empty() && "Illegal must alias set!"); // If this is a set of MustAliases, only check to see if the pointer aliases // SOME value in the set. PointerRec *SomePtr = getSomePointer(); assert(SomePtr && "Empty must-alias set??"); return AA.alias(MemoryLocation(SomePtr->getValue(), SomePtr->getSize(), SomePtr->getAAInfo()), MemoryLocation(Ptr, Size, AAInfo)); } // If this is a may-alias set, we have to check all of the pointers in the set // to be sure it doesn't alias the set... for (iterator I = begin(), E = end(); I != E; ++I) if (AliasResult AR = AA.alias( MemoryLocation(Ptr, Size, AAInfo), MemoryLocation(I.getPointer(), I.getSize(), I.getAAInfo()))) return AR; // Check the unknown instructions... if (!UnknownInsts.empty()) { for (unsigned i = 0, e = UnknownInsts.size(); i != e; ++i) if (auto *Inst = getUnknownInst(i)) if (isModOrRefSet( AA.getModRefInfo(Inst, MemoryLocation(Ptr, Size, AAInfo)))) return MayAlias; } return NoAlias; } bool AliasSet::aliasesUnknownInst(const Instruction *Inst, AliasAnalysis &AA) const { if (AliasAny) return true; assert(Inst->mayReadOrWriteMemory() && "Instruction must either read or write memory."); for (unsigned i = 0, e = UnknownInsts.size(); i != e; ++i) { if (auto *UnknownInst = getUnknownInst(i)) { const auto *C1 = dyn_cast<CallBase>(UnknownInst); const auto *C2 = dyn_cast<CallBase>(Inst); if (!C1 || !C2 || isModOrRefSet(AA.getModRefInfo(C1, C2)) || isModOrRefSet(AA.getModRefInfo(C2, C1))) return true; } } for (iterator I = begin(), E = end(); I != E; ++I) if (isModOrRefSet(AA.getModRefInfo( Inst, MemoryLocation(I.getPointer(), I.getSize(), I.getAAInfo())))) return true; return false; } Instruction* AliasSet::getUniqueInstruction() { if (AliasAny) // May have collapses alias set return nullptr; if (begin() != end()) { if (!UnknownInsts.empty()) // Another instruction found return nullptr; if (std::next(begin()) != end()) // Another instruction found return nullptr; Value *Addr = begin()->getValue(); assert(!Addr->user_empty() && "where's the instruction which added this pointer?"); if (std::next(Addr->user_begin()) != Addr->user_end()) // Another instruction found -- this is really restrictive // TODO: generalize! return nullptr; return cast<Instruction>(*(Addr->user_begin())); } if (1 != UnknownInsts.size()) return nullptr; return cast<Instruction>(UnknownInsts[0]); } void AliasSetTracker::clear() { // Delete all the PointerRec entries. for (PointerMapType::iterator I = PointerMap.begin(), E = PointerMap.end(); I != E; ++I) I->second->eraseFromList(); PointerMap.clear(); // The alias sets should all be clear now. AliasSets.clear(); } /// mergeAliasSetsForPointer - Given a pointer, merge all alias sets that may /// alias the pointer. Return the unified set, or nullptr if no set that aliases /// the pointer was found. MustAliasAll is updated to true/false if the pointer /// is found to MustAlias all the sets it merged. AliasSet *AliasSetTracker::mergeAliasSetsForPointer(const Value *Ptr, LocationSize Size, const AAMDNodes &AAInfo, bool &MustAliasAll) { AliasSet *FoundSet = nullptr; AliasResult AllAR = MustAlias; for (iterator I = begin(), E = end(); I != E;) { iterator Cur = I++; if (Cur->Forward) continue; AliasResult AR = Cur->aliasesPointer(Ptr, Size, AAInfo, AA); if (AR == NoAlias) continue; AllAR = AliasResult(AllAR & AR); // Possible downgrade to May/Partial, even No if (!FoundSet) { // If this is the first alias set ptr can go into, remember it. FoundSet = &*Cur; } else { // Otherwise, we must merge the sets. FoundSet->mergeSetIn(*Cur, *this); } } MustAliasAll = (AllAR == MustAlias); return FoundSet; } AliasSet *AliasSetTracker::findAliasSetForUnknownInst(Instruction *Inst) { AliasSet *FoundSet = nullptr; for (iterator I = begin(), E = end(); I != E;) { iterator Cur = I++; if (Cur->Forward || !Cur->aliasesUnknownInst(Inst, AA)) continue; if (!FoundSet) { // If this is the first alias set ptr can go into, remember it. FoundSet = &*Cur; } else { // Otherwise, we must merge the sets. FoundSet->mergeSetIn(*Cur, *this); } } return FoundSet; } AliasSet &AliasSetTracker::getAliasSetFor(const MemoryLocation &MemLoc) { Value * const Pointer = const_cast<Value*>(MemLoc.Ptr); const LocationSize Size = MemLoc.Size; const AAMDNodes &AAInfo = MemLoc.AATags; AliasSet::PointerRec &Entry = getEntryFor(Pointer); if (AliasAnyAS) { // At this point, the AST is saturated, so we only have one active alias // set. That means we already know which alias set we want to return, and // just need to add the pointer to that set to keep the data structure // consistent. // This, of course, means that we will never need a merge here. if (Entry.hasAliasSet()) { Entry.updateSizeAndAAInfo(Size, AAInfo); assert(Entry.getAliasSet(*this) == AliasAnyAS && "Entry in saturated AST must belong to only alias set"); } else { AliasAnyAS->addPointer(*this, Entry, Size, AAInfo); } return *AliasAnyAS; } bool MustAliasAll = false; // Check to see if the pointer is already known. if (Entry.hasAliasSet()) { // If the size changed, we may need to merge several alias sets. // Note that we can *not* return the result of mergeAliasSetsForPointer // due to a quirk of alias analysis behavior. Since alias(undef, undef) // is NoAlias, mergeAliasSetsForPointer(undef, ...) will not find the // the right set for undef, even if it exists. if (Entry.updateSizeAndAAInfo(Size, AAInfo)) mergeAliasSetsForPointer(Pointer, Size, AAInfo, MustAliasAll); // Return the set! return *Entry.getAliasSet(*this)->getForwardedTarget(*this); } if (AliasSet *AS = mergeAliasSetsForPointer(Pointer, Size, AAInfo, MustAliasAll)) { // Add it to the alias set it aliases. AS->addPointer(*this, Entry, Size, AAInfo, MustAliasAll); return *AS; } // Otherwise create a new alias set to hold the loaded pointer. AliasSets.push_back(new AliasSet()); AliasSets.back().addPointer(*this, Entry, Size, AAInfo, true); return AliasSets.back(); } void AliasSetTracker::add(Value *Ptr, LocationSize Size, const AAMDNodes &AAInfo) { addPointer(MemoryLocation(Ptr, Size, AAInfo), AliasSet::NoAccess); } void AliasSetTracker::add(LoadInst *LI) { if (isStrongerThanMonotonic(LI->getOrdering())) return addUnknown(LI); addPointer(MemoryLocation::get(LI), AliasSet::RefAccess); } void AliasSetTracker::add(StoreInst *SI) { if (isStrongerThanMonotonic(SI->getOrdering())) return addUnknown(SI); addPointer(MemoryLocation::get(SI), AliasSet::ModAccess); } void AliasSetTracker::add(VAArgInst *VAAI) { addPointer(MemoryLocation::get(VAAI), AliasSet::ModRefAccess); } void AliasSetTracker::add(AnyMemSetInst *MSI) { addPointer(MemoryLocation::getForDest(MSI), AliasSet::ModAccess); } void AliasSetTracker::add(AnyMemTransferInst *MTI) { addPointer(MemoryLocation::getForDest(MTI), AliasSet::ModAccess); addPointer(MemoryLocation::getForSource(MTI), AliasSet::RefAccess); } void AliasSetTracker::addUnknown(Instruction *Inst) { if (isa<DbgInfoIntrinsic>(Inst)) return; // Ignore DbgInfo Intrinsics. if (auto *II = dyn_cast<IntrinsicInst>(Inst)) { // These intrinsics will show up as affecting memory, but they are just // markers. switch (II->getIntrinsicID()) { default: break; // FIXME: Add lifetime/invariant intrinsics (See: PR30807). case Intrinsic::assume: case Intrinsic::sideeffect: return; } } if (!Inst->mayReadOrWriteMemory()) return; // doesn't alias anything if (AliasSet *AS = findAliasSetForUnknownInst(Inst)) { AS->addUnknownInst(Inst, AA); return; } AliasSets.push_back(new AliasSet()); AliasSets.back().addUnknownInst(Inst, AA); } void AliasSetTracker::add(Instruction *I) { // Dispatch to one of the other add methods. if (LoadInst *LI = dyn_cast<LoadInst>(I)) return add(LI); if (StoreInst *SI = dyn_cast<StoreInst>(I)) return add(SI); if (VAArgInst *VAAI = dyn_cast<VAArgInst>(I)) return add(VAAI); if (AnyMemSetInst *MSI = dyn_cast<AnyMemSetInst>(I)) return add(MSI); if (AnyMemTransferInst *MTI = dyn_cast<AnyMemTransferInst>(I)) return add(MTI); // Handle all calls with known mod/ref sets genericall if (auto *Call = dyn_cast<CallBase>(I)) if (Call->onlyAccessesArgMemory()) { auto getAccessFromModRef = [](ModRefInfo MRI) { if (isRefSet(MRI) && isModSet(MRI)) return AliasSet::ModRefAccess; else if (isModSet(MRI)) return AliasSet::ModAccess; else if (isRefSet(MRI)) return AliasSet::RefAccess; else return AliasSet::NoAccess; }; ModRefInfo CallMask = createModRefInfo(AA.getModRefBehavior(Call)); // Some intrinsics are marked as modifying memory for control flow // modelling purposes, but don't actually modify any specific memory // location. using namespace PatternMatch; if (Call->use_empty() && match(Call, m_Intrinsic<Intrinsic::invariant_start>())) CallMask = clearMod(CallMask); for (auto IdxArgPair : enumerate(Call->args())) { int ArgIdx = IdxArgPair.index(); const Value *Arg = IdxArgPair.value(); if (!Arg->getType()->isPointerTy()) continue; MemoryLocation ArgLoc = MemoryLocation::getForArgument(Call, ArgIdx, nullptr); ModRefInfo ArgMask = AA.getArgModRefInfo(Call, ArgIdx); ArgMask = intersectModRef(CallMask, ArgMask); if (!isNoModRef(ArgMask)) addPointer(ArgLoc, getAccessFromModRef(ArgMask)); } return; } return addUnknown(I); } void AliasSetTracker::add(BasicBlock &BB) { for (auto &I : BB) add(&I); } void AliasSetTracker::add(const AliasSetTracker &AST) { assert(&AA == &AST.AA && "Merging AliasSetTracker objects with different Alias Analyses!"); // Loop over all of the alias sets in AST, adding the pointers contained // therein into the current alias sets. This can cause alias sets to be // merged together in the current AST. for (const AliasSet &AS : AST) { if (AS.Forward) continue; // Ignore forwarding alias sets // If there are any call sites in the alias set, add them to this AST. for (unsigned i = 0, e = AS.UnknownInsts.size(); i != e; ++i) if (auto *Inst = AS.getUnknownInst(i)) add(Inst); // Loop over all of the pointers in this alias set. for (AliasSet::iterator ASI = AS.begin(), E = AS.end(); ASI != E; ++ASI) addPointer( MemoryLocation(ASI.getPointer(), ASI.getSize(), ASI.getAAInfo()), (AliasSet::AccessLattice)AS.Access); } } void AliasSetTracker::addAllInstructionsInLoopUsingMSSA() { assert(MSSA && L && "MSSA and L must be available"); for (const BasicBlock *BB : L->blocks()) if (auto *Accesses = MSSA->getBlockAccesses(BB)) for (auto &Access : *Accesses) if (auto *MUD = dyn_cast<MemoryUseOrDef>(&Access)) add(MUD->getMemoryInst()); } // deleteValue method - This method is used to remove a pointer value from the // AliasSetTracker entirely. It should be used when an instruction is deleted // from the program to update the AST. If you don't use this, you would have // dangling pointers to deleted instructions. // void AliasSetTracker::deleteValue(Value *PtrVal) { // First, look up the PointerRec for this pointer. PointerMapType::iterator I = PointerMap.find_as(PtrVal); if (I == PointerMap.end()) return; // Noop // If we found one, remove the pointer from the alias set it is in. AliasSet::PointerRec *PtrValEnt = I->second; AliasSet *AS = PtrValEnt->getAliasSet(*this); // Unlink and delete from the list of values. PtrValEnt->eraseFromList(); if (AS->Alias == AliasSet::SetMayAlias) { AS->SetSize--; TotalMayAliasSetSize--; } // Stop using the alias set. AS->dropRef(*this); PointerMap.erase(I); } // copyValue - This method should be used whenever a preexisting value in the // program is copied or cloned, introducing a new value. Note that it is ok for // clients that use this method to introduce the same value multiple times: if // the tracker already knows about a value, it will ignore the request. // void AliasSetTracker::copyValue(Value *From, Value *To) { // First, look up the PointerRec for this pointer. PointerMapType::iterator I = PointerMap.find_as(From); if (I == PointerMap.end()) return; // Noop assert(I->second->hasAliasSet() && "Dead entry?"); AliasSet::PointerRec &Entry = getEntryFor(To); if (Entry.hasAliasSet()) return; // Already in the tracker! // getEntryFor above may invalidate iterator \c I, so reinitialize it. I = PointerMap.find_as(From); // Add it to the alias set it aliases... AliasSet *AS = I->second->getAliasSet(*this); AS->addPointer(*this, Entry, I->second->getSize(), I->second->getAAInfo(), true, true); } AliasSet &AliasSetTracker::mergeAllAliasSets() { assert(!AliasAnyAS && (TotalMayAliasSetSize > SaturationThreshold) && "Full merge should happen once, when the saturation threshold is " "reached"); // Collect all alias sets, so that we can drop references with impunity // without worrying about iterator invalidation. std::vector<AliasSet *> ASVector; ASVector.reserve(SaturationThreshold); for (iterator I = begin(), E = end(); I != E; I++) ASVector.push_back(&*I); // Copy all instructions and pointers into a new set, and forward all other // sets to it. AliasSets.push_back(new AliasSet()); AliasAnyAS = &AliasSets.back(); AliasAnyAS->Alias = AliasSet::SetMayAlias; AliasAnyAS->Access = AliasSet::ModRefAccess; AliasAnyAS->AliasAny = true; for (auto Cur : ASVector) { // If Cur was already forwarding, just forward to the new AS instead. AliasSet *FwdTo = Cur->Forward; if (FwdTo) { Cur->Forward = AliasAnyAS; AliasAnyAS->addRef(); FwdTo->dropRef(*this); continue; } // Otherwise, perform the actual merge. AliasAnyAS->mergeSetIn(*Cur, *this); } return *AliasAnyAS; } AliasSet &AliasSetTracker::addPointer(MemoryLocation Loc, AliasSet::AccessLattice E) { AliasSet &AS = getAliasSetFor(Loc); AS.Access |= E; if (!AliasAnyAS && (TotalMayAliasSetSize > SaturationThreshold)) { // The AST is now saturated. From here on, we conservatively consider all // pointers to alias each-other. return mergeAllAliasSets(); } return AS; } //===----------------------------------------------------------------------===// // AliasSet/AliasSetTracker Printing Support //===----------------------------------------------------------------------===// void AliasSet::print(raw_ostream &OS) const { OS << " AliasSet[" << (const void*)this << ", " << RefCount << "] "; OS << (Alias == SetMustAlias ? "must" : "may") << " alias, "; switch (Access) { case NoAccess: OS << "No access "; break; case RefAccess: OS << "Ref "; break; case ModAccess: OS << "Mod "; break; case ModRefAccess: OS << "Mod/Ref "; break; default: llvm_unreachable("Bad value for Access!"); } if (Forward) OS << " forwarding to " << (void*)Forward; if (!empty()) { OS << "Pointers: "; for (iterator I = begin(), E = end(); I != E; ++I) { if (I != begin()) OS << ", "; I.getPointer()->printAsOperand(OS << "("); if (I.getSize() == LocationSize::unknown()) OS << ", unknown)"; else OS << ", " << I.getSize() << ")"; } } if (!UnknownInsts.empty()) { OS << "\n " << UnknownInsts.size() << " Unknown instructions: "; for (unsigned i = 0, e = UnknownInsts.size(); i != e; ++i) { if (i) OS << ", "; if (auto *I = getUnknownInst(i)) { if (I->hasName()) I->printAsOperand(OS); else I->print(OS); } } } OS << "\n"; } void AliasSetTracker::print(raw_ostream &OS) const { OS << "Alias Set Tracker: " << AliasSets.size(); if (AliasAnyAS) OS << " (Saturated)"; OS << " alias sets for " << PointerMap.size() << " pointer values.\n"; for (const AliasSet &AS : *this) AS.print(OS); OS << "\n"; } #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) LLVM_DUMP_METHOD void AliasSet::dump() const { print(dbgs()); } LLVM_DUMP_METHOD void AliasSetTracker::dump() const { print(dbgs()); } #endif //===----------------------------------------------------------------------===// // ASTCallbackVH Class Implementation //===----------------------------------------------------------------------===// void AliasSetTracker::ASTCallbackVH::deleted() { assert(AST && "ASTCallbackVH called with a null AliasSetTracker!"); AST->deleteValue(getValPtr()); // this now dangles! } void AliasSetTracker::ASTCallbackVH::allUsesReplacedWith(Value *V) { AST->copyValue(getValPtr(), V); } AliasSetTracker::ASTCallbackVH::ASTCallbackVH(Value *V, AliasSetTracker *ast) : CallbackVH(V), AST(ast) {} AliasSetTracker::ASTCallbackVH & AliasSetTracker::ASTCallbackVH::operator=(Value *V) { return *this = ASTCallbackVH(V, AST); } //===----------------------------------------------------------------------===// // AliasSetPrinter Pass //===----------------------------------------------------------------------===// namespace { class AliasSetPrinter : public FunctionPass { AliasSetTracker *Tracker; public: static char ID; // Pass identification, replacement for typeid AliasSetPrinter() : FunctionPass(ID) { initializeAliasSetPrinterPass(*PassRegistry::getPassRegistry()); } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.setPreservesAll(); AU.addRequired<AAResultsWrapperPass>(); } bool runOnFunction(Function &F) override { auto &AAWP = getAnalysis<AAResultsWrapperPass>(); Tracker = new AliasSetTracker(AAWP.getAAResults()); errs() << "Alias sets for function '" << F.getName() << "':\n"; for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) Tracker->add(&*I); Tracker->print(errs()); delete Tracker; return false; } }; } // end anonymous namespace char AliasSetPrinter::ID = 0; INITIALIZE_PASS_BEGIN(AliasSetPrinter, "print-alias-sets", "Alias Set Printer", false, true) INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) INITIALIZE_PASS_END(AliasSetPrinter, "print-alias-sets", "Alias Set Printer", false, true)
endlessm/chromium-browser
third_party/llvm/llvm/lib/Analysis/AliasSetTracker.cpp
C++
bsd-3-clause
26,484
/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/utility/source/process_thread_impl.h" #include "webrtc/base/checks.h" #include "webrtc/modules/interface/module.h" #include "webrtc/system_wrappers/interface/logging.h" #include "webrtc/system_wrappers/interface/tick_util.h" namespace webrtc { namespace { // We use this constant internally to signal that a module has requested // a callback right away. When this is set, no call to TimeUntilNextProcess // should be made, but Process() should be called directly. const int64_t kCallProcessImmediately = -1; int64_t GetNextCallbackTime(Module* module, int64_t time_now) { int64_t interval = module->TimeUntilNextProcess(); // Currently some implementations erroneously return error codes from // TimeUntilNextProcess(). So, as is, we correct that and log an error. if (interval < 0) { LOG(LS_ERROR) << "TimeUntilNextProcess returned an invalid value " << interval; interval = 0; } return time_now + interval; } } ProcessThread::~ProcessThread() {} // static rtc::scoped_ptr<ProcessThread> ProcessThread::Create() { return rtc::scoped_ptr<ProcessThread>(new ProcessThreadImpl()).Pass(); } ProcessThreadImpl::ProcessThreadImpl() : wake_up_(EventWrapper::Create()), stop_(false) { } ProcessThreadImpl::~ProcessThreadImpl() { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(!thread_.get()); DCHECK(!stop_); while (!queue_.empty()) { delete queue_.front(); queue_.pop(); } } void ProcessThreadImpl::Start() { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(!thread_.get()); if (thread_.get()) return; DCHECK(!stop_); { // TODO(tommi): Since DeRegisterModule is currently being called from // different threads in some cases (ChannelOwner), we need to lock access to // the modules_ collection even on the controller thread. // Once we've cleaned up those places, we can remove this lock. rtc::CritScope lock(&lock_); for (ModuleCallback& m : modules_) m.module->ProcessThreadAttached(this); } thread_ = ThreadWrapper::CreateThread( &ProcessThreadImpl::Run, this, "ProcessThread"); CHECK(thread_->Start()); } void ProcessThreadImpl::Stop() { DCHECK(thread_checker_.CalledOnValidThread()); if(!thread_.get()) return; { rtc::CritScope lock(&lock_); stop_ = true; } wake_up_->Set(); CHECK(thread_->Stop()); stop_ = false; // TODO(tommi): Since DeRegisterModule is currently being called from // different threads in some cases (ChannelOwner), we need to lock access to // the modules_ collection even on the controller thread. // Since DeRegisterModule also checks thread_, we also need to hold the // lock for the .reset() operation. // Once we've cleaned up those places, we can remove this lock. rtc::CritScope lock(&lock_); thread_.reset(); for (ModuleCallback& m : modules_) m.module->ProcessThreadAttached(nullptr); } void ProcessThreadImpl::WakeUp(Module* module) { // Allowed to be called on any thread. { rtc::CritScope lock(&lock_); for (ModuleCallback& m : modules_) { if (m.module == module) m.next_callback = kCallProcessImmediately; } } wake_up_->Set(); } void ProcessThreadImpl::PostTask(rtc::scoped_ptr<ProcessTask> task) { // Allowed to be called on any thread. { rtc::CritScope lock(&lock_); queue_.push(task.release()); } wake_up_->Set(); } void ProcessThreadImpl::RegisterModule(Module* module) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(module); #if (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON)) { // Catch programmer error. rtc::CritScope lock(&lock_); for (const ModuleCallback& mc : modules_) DCHECK(mc.module != module); } #endif // Now that we know the module isn't in the list, we'll call out to notify // the module that it's attached to the worker thread. We don't hold // the lock while we make this call. if (thread_.get()) module->ProcessThreadAttached(this); { rtc::CritScope lock(&lock_); modules_.push_back(ModuleCallback(module)); } // Wake the thread calling ProcessThreadImpl::Process() to update the // waiting time. The waiting time for the just registered module may be // shorter than all other registered modules. wake_up_->Set(); } void ProcessThreadImpl::DeRegisterModule(Module* module) { // Allowed to be called on any thread. // TODO(tommi): Disallow this ^^^ DCHECK(module); { rtc::CritScope lock(&lock_); modules_.remove_if([&module](const ModuleCallback& m) { return m.module == module; }); // TODO(tommi): we currently need to hold the lock while calling out to // ProcessThreadAttached. This is to make sure that the thread hasn't been // destroyed while we attach the module. Once we can make sure // DeRegisterModule isn't being called on arbitrary threads, we can move the // |if (thread_.get())| check and ProcessThreadAttached() call outside the // lock scope. // Notify the module that it's been detached. if (thread_.get()) module->ProcessThreadAttached(nullptr); } } // static bool ProcessThreadImpl::Run(void* obj) { return static_cast<ProcessThreadImpl*>(obj)->Process(); } bool ProcessThreadImpl::Process() { int64_t now = TickTime::MillisecondTimestamp(); int64_t next_checkpoint = now + (1000 * 60); { rtc::CritScope lock(&lock_); if (stop_) return false; for (ModuleCallback& m : modules_) { // TODO(tommi): Would be good to measure the time TimeUntilNextProcess // takes and dcheck if it takes too long (e.g. >=10ms). Ideally this // operation should not require taking a lock, so querying all modules // should run in a matter of nanoseconds. if (m.next_callback == 0) m.next_callback = GetNextCallbackTime(m.module, now); if (m.next_callback <= now || m.next_callback == kCallProcessImmediately) { m.module->Process(); // Use a new 'now' reference to calculate when the next callback // should occur. We'll continue to use 'now' above for the baseline // of calculating how long we should wait, to reduce variance. int64_t new_now = TickTime::MillisecondTimestamp(); m.next_callback = GetNextCallbackTime(m.module, new_now); } if (m.next_callback < next_checkpoint) next_checkpoint = m.next_callback; } while (!queue_.empty()) { ProcessTask* task = queue_.front(); queue_.pop(); lock_.Leave(); task->Run(); delete task; lock_.Enter(); } } int64_t time_to_wait = next_checkpoint - TickTime::MillisecondTimestamp(); if (time_to_wait > 0) wake_up_->Wait(static_cast<unsigned long>(time_to_wait)); return true; } } // namespace webrtc
guorendong/iridium-browser-ubuntu
third_party/webrtc/modules/utility/source/process_thread_impl.cc
C++
bsd-3-clause
7,255
// 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 "media/video/capture/fake_video_capture_device.h" #include <string> #include "base/bind.h" #include "base/memory/scoped_ptr.h" #include "base/strings/stringprintf.h" #include "media/audio/fake_audio_input_stream.h" #include "media/base/video_frame.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkPaint.h" namespace media { static const int kFakeCaptureBeepCycle = 10; // Visual beep every 0.5s. static const int kFakeCaptureCapabilityChangePeriod = 30; FakeVideoCaptureDevice::FakeVideoCaptureDevice() : capture_thread_("CaptureThread"), frame_count_(0), format_roster_index_(0) {} FakeVideoCaptureDevice::~FakeVideoCaptureDevice() { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(!capture_thread_.IsRunning()); } void FakeVideoCaptureDevice::AllocateAndStart( const VideoCaptureParams& params, scoped_ptr<VideoCaptureDevice::Client> client) { DCHECK(thread_checker_.CalledOnValidThread()); if (capture_thread_.IsRunning()) { NOTREACHED(); return; } capture_thread_.Start(); capture_thread_.message_loop()->PostTask( FROM_HERE, base::Bind(&FakeVideoCaptureDevice::OnAllocateAndStart, base::Unretained(this), params, base::Passed(&client))); } void FakeVideoCaptureDevice::StopAndDeAllocate() { DCHECK(thread_checker_.CalledOnValidThread()); if (!capture_thread_.IsRunning()) { NOTREACHED(); return; } capture_thread_.message_loop()->PostTask( FROM_HERE, base::Bind(&FakeVideoCaptureDevice::OnStopAndDeAllocate, base::Unretained(this))); capture_thread_.Stop(); } void FakeVideoCaptureDevice::PopulateVariableFormatsRoster( const VideoCaptureFormats& formats) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(!capture_thread_.IsRunning()); format_roster_ = formats; format_roster_index_ = 0; } void FakeVideoCaptureDevice::OnAllocateAndStart( const VideoCaptureParams& params, scoped_ptr<VideoCaptureDevice::Client> client) { DCHECK_EQ(capture_thread_.message_loop(), base::MessageLoop::current()); client_ = client.Pass(); // Incoming |params| can be none of the supported formats, so we get the // closest thing rounded up. TODO(mcasas): Use the |params|, if they belong to // the supported ones, when http://crbug.com/309554 is verified. DCHECK_EQ(params.requested_format.pixel_format, PIXEL_FORMAT_I420); capture_format_.pixel_format = params.requested_format.pixel_format; capture_format_.frame_rate = 30; if (params.requested_format.frame_size.width() > 1280) capture_format_.frame_size.SetSize(1920, 1080); else if (params.requested_format.frame_size.width() > 640) capture_format_.frame_size.SetSize(1280, 720); else if (params.requested_format.frame_size.width() > 320) capture_format_.frame_size.SetSize(640, 480); else capture_format_.frame_size.SetSize(320, 240); const size_t fake_frame_size = VideoFrame::AllocationSize(VideoFrame::I420, capture_format_.frame_size); fake_frame_.reset(new uint8[fake_frame_size]); capture_thread_.message_loop()->PostTask( FROM_HERE, base::Bind(&FakeVideoCaptureDevice::OnCaptureTask, base::Unretained(this))); } void FakeVideoCaptureDevice::OnStopAndDeAllocate() { DCHECK_EQ(capture_thread_.message_loop(), base::MessageLoop::current()); client_.reset(); } void FakeVideoCaptureDevice::OnCaptureTask() { if (!client_) return; const size_t frame_size = VideoFrame::AllocationSize(VideoFrame::I420, capture_format_.frame_size); memset(fake_frame_.get(), 0, frame_size); SkImageInfo info = SkImageInfo::MakeA8(capture_format_.frame_size.width(), capture_format_.frame_size.height()); SkBitmap bitmap; bitmap.installPixels(info, fake_frame_.get(), info.width()); SkCanvas canvas(bitmap); // Draw a sweeping circle to show an animation. int radius = std::min(capture_format_.frame_size.width(), capture_format_.frame_size.height()) / 4; SkRect rect = SkRect::MakeXYWH(capture_format_.frame_size.width() / 2 - radius, capture_format_.frame_size.height() / 2 - radius, 2 * radius, 2 * radius); SkPaint paint; paint.setStyle(SkPaint::kFill_Style); // Only Y plane is being drawn and this gives 50% grey on the Y // plane. The result is a light green color in RGB space. paint.setAlpha(128); int end_angle = (frame_count_ % kFakeCaptureBeepCycle * 360) / kFakeCaptureBeepCycle; if (!end_angle) end_angle = 360; canvas.drawArc(rect, 0, end_angle, true, paint); // Draw current time. int elapsed_ms = kFakeCaptureTimeoutMs * frame_count_; int milliseconds = elapsed_ms % 1000; int seconds = (elapsed_ms / 1000) % 60; int minutes = (elapsed_ms / 1000 / 60) % 60; int hours = (elapsed_ms / 1000 / 60 / 60) % 60; std::string time_string = base::StringPrintf("%d:%02d:%02d:%03d %d", hours, minutes, seconds, milliseconds, frame_count_); canvas.scale(3, 3); canvas.drawText(time_string.data(), time_string.length(), 30, 20, paint); if (frame_count_ % kFakeCaptureBeepCycle == 0) { // Generate a synchronized beep sound if there is one audio input // stream created. FakeAudioInputStream::BeepOnce(); } frame_count_++; // Give the captured frame to the client. client_->OnIncomingCapturedData(fake_frame_.get(), frame_size, capture_format_, 0, base::TimeTicks::Now()); if (!(frame_count_ % kFakeCaptureCapabilityChangePeriod) && format_roster_.size() > 0U) { Reallocate(); } // Reschedule next CaptureTask. capture_thread_.message_loop()->PostDelayedTask( FROM_HERE, base::Bind(&FakeVideoCaptureDevice::OnCaptureTask, base::Unretained(this)), base::TimeDelta::FromMilliseconds(kFakeCaptureTimeoutMs)); } void FakeVideoCaptureDevice::Reallocate() { DCHECK_EQ(capture_thread_.message_loop(), base::MessageLoop::current()); capture_format_ = format_roster_.at(++format_roster_index_ % format_roster_.size()); DCHECK_EQ(capture_format_.pixel_format, PIXEL_FORMAT_I420); DVLOG(3) << "Reallocating FakeVideoCaptureDevice, new capture resolution " << capture_format_.frame_size.ToString(); const size_t fake_frame_size = VideoFrame::AllocationSize(VideoFrame::I420, capture_format_.frame_size); fake_frame_.reset(new uint8[fake_frame_size]); } } // namespace media
sgraham/nope
media/video/capture/fake_video_capture_device.cc
C++
bsd-3-clause
6,987
// 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 "media/filters/file_data_source.h" #include <algorithm> #include "base/logging.h" namespace media { FileDataSource::FileDataSource() : force_read_errors_(false), force_streaming_(false) { } bool FileDataSource::Initialize(const FilePath& file_path) { DCHECK(!file_.IsValid()); if (!file_.Initialize(file_path)) return false; UpdateHostBytes(); return true; } void FileDataSource::set_host(DataSourceHost* host) { DataSource::set_host(host); UpdateHostBytes(); } void FileDataSource::Stop(const base::Closure& callback) { callback.Run(); } void FileDataSource::Read(int64 position, int size, uint8* data, const DataSource::ReadCB& read_cb) { if (force_read_errors_ || !file_.IsValid()) { read_cb.Run(kReadError); return; } int64 file_size = file_.length(); CHECK_GE(file_size, 0); CHECK_GE(position, 0); CHECK_GE(size, 0); // Cap position and size within bounds. position = std::min(position, file_size); int64 clamped_size = std::min(static_cast<int64>(size), file_size - position); memcpy(data, file_.data() + position, clamped_size); read_cb.Run(clamped_size); } bool FileDataSource::GetSize(int64* size_out) { *size_out = file_.length(); return true; } bool FileDataSource::IsStreaming() { return force_streaming_; } void FileDataSource::SetBitrate(int bitrate) {} FileDataSource::~FileDataSource() {} void FileDataSource::UpdateHostBytes() { if (host() && file_.IsValid()) { host()->SetTotalBytes(file_.length()); host()->AddBufferedByteRange(0, file_.length()); } } } // namespace media
leighpauls/k2cro4
media/filters/file_data_source.cc
C++
bsd-3-clause
1,794
// Copyright 2013 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 "ash/wm/workspace_controller.h" #include <map> #include "ash/root_window_controller.h" #include "ash/screen_util.h" #include "ash/shelf/shelf_layout_manager.h" #include "ash/shelf/shelf_widget.h" #include "ash/shell.h" #include "ash/shell_window_ids.h" #include "ash/system/status_area_widget.h" #include "ash/test/ash_test_base.h" #include "ash/test/shell_test_api.h" #include "ash/test/test_shelf_delegate.h" #include "ash/wm/panels/panel_layout_manager.h" #include "ash/wm/window_state.h" #include "ash/wm/window_util.h" #include "ash/wm/workspace/workspace_window_resizer.h" #include "base/strings/string_number_conversions.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/test/test_window_delegate.h" #include "ui/aura/test/test_windows.h" #include "ui/aura/window.h" #include "ui/aura/window_event_dispatcher.h" #include "ui/base/hit_test.h" #include "ui/base/ui_base_types.h" #include "ui/compositor/layer.h" #include "ui/compositor/scoped_animation_duration_scale_mode.h" #include "ui/events/event_utils.h" #include "ui/events/test/event_generator.h" #include "ui/gfx/screen.h" #include "ui/views/widget/widget.h" #include "ui/wm/core/window_animations.h" #include "ui/wm/core/window_util.h" using aura::Window; namespace ash { // Returns a string containing the names of all the children of |window| (in // order). Each entry is separated by a space. std::string GetWindowNames(const aura::Window* window) { std::string result; for (size_t i = 0; i < window->children().size(); ++i) { if (i != 0) result += " "; result += window->children()[i]->name(); } return result; } // Returns a string containing the names of windows corresponding to each of the // child layers of |window|'s layer. Any layers that don't correspond to a child // Window of |window| are ignored. The result is ordered based on the layer // ordering. std::string GetLayerNames(const aura::Window* window) { typedef std::map<const ui::Layer*, std::string> LayerToWindowNameMap; LayerToWindowNameMap window_names; for (size_t i = 0; i < window->children().size(); ++i) { window_names[window->children()[i]->layer()] = window->children()[i]->name(); } std::string result; const std::vector<ui::Layer*>& layers(window->layer()->children()); for (size_t i = 0; i < layers.size(); ++i) { LayerToWindowNameMap::iterator layer_i = window_names.find(layers[i]); if (layer_i != window_names.end()) { if (!result.empty()) result += " "; result += layer_i->second; } } return result; } class WorkspaceControllerTest : public test::AshTestBase { public: WorkspaceControllerTest() {} ~WorkspaceControllerTest() override {} aura::Window* CreateTestWindowUnparented() { aura::Window* window = new aura::Window(NULL); window->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_NORMAL); window->SetType(ui::wm::WINDOW_TYPE_NORMAL); window->Init(aura::WINDOW_LAYER_TEXTURED); return window; } aura::Window* CreateTestWindow() { aura::Window* window = new aura::Window(NULL); window->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_NORMAL); window->SetType(ui::wm::WINDOW_TYPE_NORMAL); window->Init(aura::WINDOW_LAYER_TEXTURED); ParentWindowInPrimaryRootWindow(window); return window; } aura::Window* CreateBrowserLikeWindow(const gfx::Rect& bounds) { aura::Window* window = CreateTestWindow(); window->SetBounds(bounds); wm::WindowState* window_state = wm::GetWindowState(window); window_state->set_window_position_managed(true); window->Show(); return window; } aura::Window* CreatePopupLikeWindow(const gfx::Rect& bounds) { aura::Window* window = CreateTestWindowInShellWithBounds(bounds); window->Show(); return window; } aura::Window* CreateTestPanel(aura::WindowDelegate* delegate, const gfx::Rect& bounds) { aura::Window* window = CreateTestWindowInShellWithDelegateAndType( delegate, ui::wm::WINDOW_TYPE_PANEL, 0, bounds); test::TestShelfDelegate* shelf_delegate = test::TestShelfDelegate::instance(); shelf_delegate->AddShelfItem(window); PanelLayoutManager* manager = static_cast<PanelLayoutManager*>( Shell::GetContainer(window->GetRootWindow(), kShellWindowId_PanelContainer)->layout_manager()); manager->Relayout(); return window; } aura::Window* GetDesktop() { return Shell::GetContainer(Shell::GetPrimaryRootWindow(), kShellWindowId_DefaultContainer); } gfx::Rect GetFullscreenBounds(aura::Window* window) { return Shell::GetScreen()->GetDisplayNearestWindow(window).bounds(); } ShelfWidget* shelf_widget() { return Shell::GetPrimaryRootWindowController()->shelf(); } ShelfLayoutManager* shelf_layout_manager() { return Shell::GetPrimaryRootWindowController()->GetShelfLayoutManager(); } bool GetWindowOverlapsShelf() { return shelf_layout_manager()->window_overlaps_shelf(); } private: DISALLOW_COPY_AND_ASSIGN(WorkspaceControllerTest); }; // Assertions around adding a normal window. TEST_F(WorkspaceControllerTest, AddNormalWindowWhenEmpty) { scoped_ptr<Window> w1(CreateTestWindow()); w1->SetBounds(gfx::Rect(0, 0, 250, 251)); wm::WindowState* window_state = wm::GetWindowState(w1.get()); EXPECT_FALSE(window_state->HasRestoreBounds()); w1->Show(); EXPECT_FALSE(window_state->HasRestoreBounds()); ASSERT_TRUE(w1->layer() != NULL); EXPECT_TRUE(w1->layer()->visible()); EXPECT_EQ("0,0 250x251", w1->bounds().ToString()); EXPECT_EQ(w1.get(), GetDesktop()->children()[0]); } // Assertions around maximizing/unmaximizing. TEST_F(WorkspaceControllerTest, SingleMaximizeWindow) { scoped_ptr<Window> w1(CreateTestWindow()); w1->SetBounds(gfx::Rect(0, 0, 250, 251)); w1->Show(); wm::ActivateWindow(w1.get()); EXPECT_TRUE(wm::IsActiveWindow(w1.get())); ASSERT_TRUE(w1->layer() != NULL); EXPECT_TRUE(w1->layer()->visible()); EXPECT_EQ("0,0 250x251", w1->bounds().ToString()); // Maximize the window. w1->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MAXIMIZED); EXPECT_TRUE(wm::IsActiveWindow(w1.get())); EXPECT_EQ(w1.get(), GetDesktop()->children()[0]); EXPECT_EQ(ScreenUtil::GetMaximizedWindowBoundsInParent(w1.get()).width(), w1->bounds().width()); EXPECT_EQ(ScreenUtil::GetMaximizedWindowBoundsInParent(w1.get()).height(), w1->bounds().height()); // Restore the window. w1->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_NORMAL); EXPECT_EQ(w1.get(), GetDesktop()->children()[0]); EXPECT_EQ("0,0 250x251", w1->bounds().ToString()); } // Assertions around two windows and toggling one to be fullscreen. TEST_F(WorkspaceControllerTest, FullscreenWithNormalWindow) { scoped_ptr<Window> w1(CreateTestWindow()); scoped_ptr<Window> w2(CreateTestWindow()); w1->SetBounds(gfx::Rect(0, 0, 250, 251)); w1->Show(); ASSERT_TRUE(w1->layer() != NULL); EXPECT_TRUE(w1->layer()->visible()); w2->SetBounds(gfx::Rect(0, 0, 50, 51)); w2->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_FULLSCREEN); w2->Show(); wm::ActivateWindow(w2.get()); // Both windows should be in the same workspace. EXPECT_EQ(w1.get(), GetDesktop()->children()[0]); EXPECT_EQ(w2.get(), GetDesktop()->children()[1]); gfx::Rect work_area( ScreenUtil::GetMaximizedWindowBoundsInParent(w1.get())); EXPECT_EQ(work_area.width(), w2->bounds().width()); EXPECT_EQ(work_area.height(), w2->bounds().height()); // Restore w2, which should then go back to one workspace. w2->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_NORMAL); EXPECT_EQ(50, w2->bounds().width()); EXPECT_EQ(51, w2->bounds().height()); EXPECT_TRUE(wm::IsActiveWindow(w2.get())); } // Makes sure requests to change the bounds of a normal window go through. TEST_F(WorkspaceControllerTest, ChangeBoundsOfNormalWindow) { scoped_ptr<Window> w1(CreateTestWindow()); w1->Show(); // Setting the bounds should go through since the window is in the normal // workspace. w1->SetBounds(gfx::Rect(0, 0, 200, 500)); EXPECT_EQ(200, w1->bounds().width()); EXPECT_EQ(500, w1->bounds().height()); } // Verifies the bounds is not altered when showing and grid is enabled. TEST_F(WorkspaceControllerTest, SnapToGrid) { scoped_ptr<Window> w1(CreateTestWindowUnparented()); w1->SetBounds(gfx::Rect(1, 6, 25, 30)); ParentWindowInPrimaryRootWindow(w1.get()); // We are not aligning this anymore this way. When the window gets shown // the window is expected to be handled differently, but this cannot be // tested with this test. So the result of this test should be that the // bounds are exactly as passed in. EXPECT_EQ("1,6 25x30", w1->bounds().ToString()); } // Assertions around a fullscreen window. TEST_F(WorkspaceControllerTest, SingleFullscreenWindow) { scoped_ptr<Window> w1(CreateTestWindow()); w1->SetBounds(gfx::Rect(0, 0, 250, 251)); // Make the window fullscreen. w1->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_FULLSCREEN); w1->Show(); wm::ActivateWindow(w1.get()); EXPECT_EQ(w1.get(), GetDesktop()->children()[0]); EXPECT_EQ(GetFullscreenBounds(w1.get()).width(), w1->bounds().width()); EXPECT_EQ(GetFullscreenBounds(w1.get()).height(), w1->bounds().height()); // Restore the window. Use SHOW_STATE_DEFAULT as that is what we'll end up // with when using views::Widget. w1->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_DEFAULT); EXPECT_EQ("0,0 250x251", w1->bounds().ToString()); EXPECT_EQ(w1.get(), GetDesktop()->children()[0]); EXPECT_EQ(250, w1->bounds().width()); EXPECT_EQ(251, w1->bounds().height()); // Back to fullscreen. w1->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_FULLSCREEN); EXPECT_EQ(w1.get(), GetDesktop()->children()[0]); EXPECT_EQ(GetFullscreenBounds(w1.get()).width(), w1->bounds().width()); EXPECT_EQ(GetFullscreenBounds(w1.get()).height(), w1->bounds().height()); wm::WindowState* window_state = wm::GetWindowState(w1.get()); ASSERT_TRUE(window_state->HasRestoreBounds()); EXPECT_EQ("0,0 250x251", window_state->GetRestoreBoundsInScreen().ToString()); } // Assertions around minimizing a single window. TEST_F(WorkspaceControllerTest, MinimizeSingleWindow) { scoped_ptr<Window> w1(CreateTestWindow()); w1->Show(); w1->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MINIMIZED); EXPECT_FALSE(w1->layer()->IsDrawn()); EXPECT_TRUE(w1->layer()->GetTargetTransform().IsIdentity()); // Show the window. w1->Show(); EXPECT_TRUE(wm::GetWindowState(w1.get())->IsNormalStateType()); EXPECT_TRUE(w1->layer()->IsDrawn()); } // Assertions around minimizing a fullscreen window. TEST_F(WorkspaceControllerTest, MinimizeFullscreenWindow) { // Two windows, w1 normal, w2 fullscreen. scoped_ptr<Window> w1(CreateTestWindow()); scoped_ptr<Window> w2(CreateTestWindow()); w1->Show(); w2->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_FULLSCREEN); w2->Show(); wm::WindowState* w1_state = wm::GetWindowState(w1.get()); wm::WindowState* w2_state = wm::GetWindowState(w2.get()); w2_state->Activate(); // Minimize w2. w2->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MINIMIZED); EXPECT_TRUE(w1->layer()->IsDrawn()); EXPECT_FALSE(w2->layer()->IsDrawn()); // Show the window, which should trigger unminimizing. w2->Show(); w2_state->Activate(); EXPECT_TRUE(w2_state->IsFullscreen()); EXPECT_TRUE(w1->layer()->IsDrawn()); EXPECT_TRUE(w2->layer()->IsDrawn()); // Minimize the window, which should hide the window. EXPECT_TRUE(w2_state->IsActive()); w2_state->Minimize(); EXPECT_FALSE(w2_state->IsActive()); EXPECT_FALSE(w2->layer()->IsDrawn()); EXPECT_TRUE(w1_state->IsActive()); EXPECT_EQ(w2.get(), GetDesktop()->children()[0]); EXPECT_EQ(w1.get(), GetDesktop()->children()[1]); // Make the window normal. w2->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_NORMAL); // Setting back to normal doesn't change the activation. EXPECT_FALSE(w2_state->IsActive()); EXPECT_TRUE(w1_state->IsActive()); EXPECT_EQ(w2.get(), GetDesktop()->children()[0]); EXPECT_EQ(w1.get(), GetDesktop()->children()[1]); EXPECT_TRUE(w2->layer()->IsDrawn()); } // Verifies ShelfLayoutManager's visibility/auto-hide state is correctly // updated. TEST_F(WorkspaceControllerTest, ShelfStateUpdated) { // Since ShelfLayoutManager queries for mouse location, move the mouse so // it isn't over the shelf. ui::test::EventGenerator generator(Shell::GetPrimaryRootWindow(), gfx::Point()); generator.MoveMouseTo(0, 0); scoped_ptr<Window> w1(CreateTestWindow()); const gfx::Rect w1_bounds(0, 1, 101, 102); ShelfLayoutManager* shelf = shelf_layout_manager(); shelf->SetAutoHideBehavior(ash::SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS); const gfx::Rect touches_shelf_bounds( 0, shelf->GetIdealBounds().y() - 10, 101, 102); // Move |w1| to overlap the shelf. w1->SetBounds(touches_shelf_bounds); EXPECT_FALSE(GetWindowOverlapsShelf()); // A visible ignored window should not trigger the overlap. scoped_ptr<Window> w_ignored(CreateTestWindow()); w_ignored->SetBounds(touches_shelf_bounds); wm::GetWindowState(&(*w_ignored))->set_ignored_by_shelf(true); w_ignored->Show(); EXPECT_FALSE(GetWindowOverlapsShelf()); // Make it visible, since visible shelf overlaps should be true. w1->Show(); EXPECT_TRUE(GetWindowOverlapsShelf()); wm::ActivateWindow(w1.get()); w1->SetBounds(w1_bounds); w1->Show(); wm::ActivateWindow(w1.get()); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->visibility_state()); // Maximize the window. w1->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MAXIMIZED); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->visibility_state()); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->auto_hide_state()); // Restore. w1->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_NORMAL); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->visibility_state()); EXPECT_EQ("0,1 101x102", w1->bounds().ToString()); // Fullscreen. w1->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_FULLSCREEN); EXPECT_EQ(SHELF_HIDDEN, shelf->visibility_state()); // Normal. w1->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_NORMAL); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->visibility_state()); EXPECT_EQ("0,1 101x102", w1->bounds().ToString()); EXPECT_FALSE(GetWindowOverlapsShelf()); // Move window so it obscures shelf. w1->SetBounds(touches_shelf_bounds); EXPECT_TRUE(GetWindowOverlapsShelf()); // Move it back. w1->SetBounds(w1_bounds); EXPECT_FALSE(GetWindowOverlapsShelf()); // Maximize again. w1->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MAXIMIZED); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->visibility_state()); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->auto_hide_state()); // Minimize. w1->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MINIMIZED); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->visibility_state()); // Since the restore from minimize will restore to the pre-minimize // state (tested elsewhere), we abandon the current size and restore // rect and set them to the window. wm::WindowState* window_state = wm::GetWindowState(w1.get()); gfx::Rect restore = window_state->GetRestoreBoundsInScreen(); EXPECT_EQ("0,0 800x597", w1->bounds().ToString()); EXPECT_EQ("0,1 101x102", restore.ToString()); window_state->ClearRestoreBounds(); w1->SetBounds(restore); // Restore. w1->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_NORMAL); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->visibility_state()); EXPECT_EQ("0,1 101x102", w1->bounds().ToString()); // Create another window, maximized. scoped_ptr<Window> w2(CreateTestWindow()); w2->SetBounds(gfx::Rect(10, 11, 250, 251)); w2->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MAXIMIZED); w2->Show(); wm::ActivateWindow(w2.get()); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->visibility_state()); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->auto_hide_state()); EXPECT_EQ("0,1 101x102", w1->bounds().ToString()); EXPECT_EQ(ScreenUtil::GetMaximizedWindowBoundsInParent( w2->parent()).ToString(), w2->bounds().ToString()); // Switch to w1. wm::ActivateWindow(w1.get()); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->visibility_state()); EXPECT_EQ("0,1 101x102", w1->bounds().ToString()); EXPECT_EQ(ScreenUtil::GetMaximizedWindowBoundsInParent( w2->parent()).ToString(), w2->bounds().ToString()); // Switch to w2. wm::ActivateWindow(w2.get()); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->visibility_state()); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->auto_hide_state()); EXPECT_EQ("0,1 101x102", w1->bounds().ToString()); EXPECT_EQ(ScreenUtil::GetMaximizedWindowBoundsInParent(w2.get()).ToString(), w2->bounds().ToString()); // Turn off auto-hide, switch back to w2 (maximized) and verify overlap. shelf->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_NEVER); wm::ActivateWindow(w2.get()); EXPECT_FALSE(GetWindowOverlapsShelf()); // Move w1 to overlap shelf, it shouldn't change window overlaps shelf since // the window isn't in the visible workspace. w1->SetBounds(touches_shelf_bounds); EXPECT_FALSE(GetWindowOverlapsShelf()); // Activate w1. Although w1 is visible, the overlap state is still false since // w2 is maximized. wm::ActivateWindow(w1.get()); EXPECT_FALSE(GetWindowOverlapsShelf()); // Restore w2. w2->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_NORMAL); EXPECT_TRUE(GetWindowOverlapsShelf()); } // Verifies going from maximized to minimized sets the right state for painting // the background of the launcher. TEST_F(WorkspaceControllerTest, MinimizeResetsVisibility) { scoped_ptr<Window> w1(CreateTestWindow()); w1->Show(); wm::ActivateWindow(w1.get()); w1->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MAXIMIZED); EXPECT_EQ(SHELF_BACKGROUND_MAXIMIZED, shelf_widget()->GetBackgroundType()); w1->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MINIMIZED); EXPECT_EQ(SHELF_VISIBLE, shelf_layout_manager()->visibility_state()); EXPECT_EQ(SHELF_BACKGROUND_DEFAULT, shelf_widget()->GetBackgroundType()); } // Verifies window visibility during various workspace changes. TEST_F(WorkspaceControllerTest, VisibilityTests) { scoped_ptr<Window> w1(CreateTestWindow()); w1->Show(); EXPECT_TRUE(w1->IsVisible()); EXPECT_EQ(1.0f, w1->layer()->GetCombinedOpacity()); // Create another window, activate it and make it fullscreen. scoped_ptr<Window> w2(CreateTestWindow()); w2->Show(); wm::ActivateWindow(w2.get()); w2->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_FULLSCREEN); EXPECT_TRUE(w2->IsVisible()); EXPECT_EQ(1.0f, w2->layer()->GetCombinedOpacity()); EXPECT_TRUE(w1->IsVisible()); // Switch to w1. |w1| should be visible on top of |w2|. wm::ActivateWindow(w1.get()); EXPECT_TRUE(w1->IsVisible()); EXPECT_EQ(1.0f, w1->layer()->GetCombinedOpacity()); EXPECT_TRUE(w2->IsVisible()); // Switch back to |w2|. wm::ActivateWindow(w2.get()); EXPECT_TRUE(w2->IsVisible()); EXPECT_EQ(1.0f, w2->layer()->GetCombinedOpacity()); EXPECT_TRUE(w1->IsVisible()); // Restore |w2|, both windows should be visible. w2->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_NORMAL); EXPECT_TRUE(w1->IsVisible()); EXPECT_EQ(1.0f, w1->layer()->GetCombinedOpacity()); EXPECT_TRUE(w2->IsVisible()); EXPECT_EQ(1.0f, w2->layer()->GetCombinedOpacity()); // Make |w2| fullscreen again, then close it. w2->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_FULLSCREEN); w2->Hide(); EXPECT_FALSE(w2->IsVisible()); EXPECT_EQ(1.0f, w1->layer()->GetCombinedOpacity()); EXPECT_TRUE(w1->IsVisible()); // Create |w2| and maximize it. w2.reset(CreateTestWindow()); w2->Show(); wm::ActivateWindow(w2.get()); w2->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MAXIMIZED); EXPECT_TRUE(w2->IsVisible()); EXPECT_EQ(1.0f, w2->layer()->GetCombinedOpacity()); EXPECT_TRUE(w1->IsVisible()); // Close |w2|. w2.reset(); EXPECT_EQ(1.0f, w1->layer()->GetCombinedOpacity()); EXPECT_TRUE(w1->IsVisible()); } // Verifies windows that are offscreen don't move when switching workspaces. TEST_F(WorkspaceControllerTest, DontMoveOnSwitch) { ui::test::EventGenerator generator(Shell::GetPrimaryRootWindow(), gfx::Point()); generator.MoveMouseTo(0, 0); scoped_ptr<Window> w1(CreateTestWindow()); ShelfLayoutManager* shelf = shelf_layout_manager(); const gfx::Rect touches_shelf_bounds( 0, shelf->GetIdealBounds().y() - 10, 101, 102); // Move |w1| to overlap the shelf. w1->SetBounds(touches_shelf_bounds); w1->Show(); wm::ActivateWindow(w1.get()); // Create another window and maximize it. scoped_ptr<Window> w2(CreateTestWindow()); w2->SetBounds(gfx::Rect(10, 11, 250, 251)); w2->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MAXIMIZED); w2->Show(); wm::ActivateWindow(w2.get()); // Switch to w1. wm::ActivateWindow(w1.get()); EXPECT_EQ(touches_shelf_bounds.ToString(), w1->bounds().ToString()); } // Verifies that windows that are completely offscreen move when switching // workspaces. TEST_F(WorkspaceControllerTest, MoveOnSwitch) { ui::test::EventGenerator generator(Shell::GetPrimaryRootWindow(), gfx::Point()); generator.MoveMouseTo(0, 0); scoped_ptr<Window> w1(CreateTestWindow()); ShelfLayoutManager* shelf = shelf_layout_manager(); const gfx::Rect w1_bounds(0, shelf->GetIdealBounds().y(), 100, 200); // Move |w1| so that the top edge is the same as the top edge of the shelf. w1->SetBounds(w1_bounds); w1->Show(); wm::ActivateWindow(w1.get()); EXPECT_EQ(w1_bounds.ToString(), w1->bounds().ToString()); // Create another window and maximize it. scoped_ptr<Window> w2(CreateTestWindow()); w2->SetBounds(gfx::Rect(10, 11, 250, 251)); w2->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MAXIMIZED); w2->Show(); wm::ActivateWindow(w2.get()); // Increase the size of the WorkAreaInsets. This would make |w1| fall // completely out of the display work area. gfx::Insets insets = Shell::GetScreen()->GetPrimaryDisplay().GetWorkAreaInsets(); insets.Set(0, 0, insets.bottom() + 30, 0); Shell::GetInstance()->SetDisplayWorkAreaInsets(w1.get(), insets); // Switch to w1. The window should have moved. wm::ActivateWindow(w1.get()); EXPECT_NE(w1_bounds.ToString(), w1->bounds().ToString()); } namespace { // WindowDelegate used by DontCrashOnChangeAndActivate. class DontCrashOnChangeAndActivateDelegate : public aura::test::TestWindowDelegate { public: DontCrashOnChangeAndActivateDelegate() : window_(NULL) {} void set_window(aura::Window* window) { window_ = window; } // WindowDelegate overrides: void OnBoundsChanged(const gfx::Rect& old_bounds, const gfx::Rect& new_bounds) override { if (window_) { wm::ActivateWindow(window_); window_ = NULL; } } private: aura::Window* window_; DISALLOW_COPY_AND_ASSIGN(DontCrashOnChangeAndActivateDelegate); }; } // namespace // Exercises possible crash in W2. Here's the sequence: // . minimize a maximized window. // . remove the window (which happens when switching displays). // . add the window back. // . show the window and during the bounds change activate it. TEST_F(WorkspaceControllerTest, DontCrashOnChangeAndActivate) { // Force the shelf ShelfLayoutManager* shelf = shelf_layout_manager(); shelf->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_NEVER); DontCrashOnChangeAndActivateDelegate delegate; scoped_ptr<Window> w1(CreateTestWindowInShellWithDelegate( &delegate, 1000, gfx::Rect(10, 11, 250, 251))); w1->Show(); wm::WindowState* w1_state = wm::GetWindowState(w1.get()); w1_state->Activate(); w1_state->Maximize(); w1_state->Minimize(); w1->parent()->RemoveChild(w1.get()); // Do this so that when we Show() the window a resize occurs and we make the // window active. shelf->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS); ParentWindowInPrimaryRootWindow(w1.get()); delegate.set_window(w1.get()); w1->Show(); } // Verifies a window with a transient parent not managed by workspace works. TEST_F(WorkspaceControllerTest, TransientParent) { // Normal window with no transient parent. scoped_ptr<Window> w2(CreateTestWindow()); w2->SetBounds(gfx::Rect(10, 11, 250, 251)); w2->Show(); wm::ActivateWindow(w2.get()); // Window with a transient parent. We set the transient parent to the root, // which would never happen but is enough to exercise the bug. scoped_ptr<Window> w1(CreateTestWindowUnparented()); ::wm::AddTransientChild( Shell::GetInstance()->GetPrimaryRootWindow(), w1.get()); w1->SetBounds(gfx::Rect(10, 11, 250, 251)); ParentWindowInPrimaryRootWindow(w1.get()); w1->Show(); wm::ActivateWindow(w1.get()); // The window with the transient parent should get added to the same parent as // the normal window. EXPECT_EQ(w2->parent(), w1->parent()); } // Test the placement of newly created windows. TEST_F(WorkspaceControllerTest, BasicAutoPlacingOnCreate) { if (!SupportsHostWindowResize()) return; UpdateDisplay("1600x1200"); // Creating a popup handler here to make sure it does not interfere with the // existing windows. gfx::Rect source_browser_bounds(16, 32, 640, 320); scoped_ptr<aura::Window> browser_window(CreateBrowserLikeWindow( source_browser_bounds)); // Creating a popup to make sure it does not interfere with the positioning. scoped_ptr<aura::Window> browser_popup(CreatePopupLikeWindow( gfx::Rect(16, 32, 128, 256))); browser_window->Show(); browser_popup->Show(); { // With a shown window it's size should get returned. scoped_ptr<aura::Window> new_browser_window(CreateBrowserLikeWindow( source_browser_bounds)); // The position should be right flush. EXPECT_EQ("960,32 640x320", new_browser_window->bounds().ToString()); } { // With the window shown - but more on the right side then on the left // side (and partially out of the screen), it should default to the other // side and inside the screen. gfx::Rect source_browser_bounds(gfx::Rect(1000, 600, 640, 320)); browser_window->SetBounds(source_browser_bounds); scoped_ptr<aura::Window> new_browser_window(CreateBrowserLikeWindow( source_browser_bounds)); // The position should be left & bottom flush. EXPECT_EQ("0,600 640x320", new_browser_window->bounds().ToString()); // If the other window was already beyond the point to get right flush // it will remain where it is. EXPECT_EQ("1000,600 640x320", browser_window->bounds().ToString()); } { // Make sure that popups do not get changed. scoped_ptr<aura::Window> new_popup_window(CreatePopupLikeWindow( gfx::Rect(50, 100, 300, 150))); EXPECT_EQ("50,100 300x150", new_popup_window->bounds().ToString()); } browser_window->Hide(); { // If a window is there but not shown the default should be centered. scoped_ptr<aura::Window> new_browser_window(CreateBrowserLikeWindow( gfx::Rect(50, 100, 300, 150))); EXPECT_EQ("650,100 300x150", new_browser_window->bounds().ToString()); } } // Test that adding a second window shifts both the first window and its // transient child. TEST_F(WorkspaceControllerTest, AutoPlacingMovesTransientChild) { // Create an auto-positioned window. scoped_ptr<aura::Window> window1(CreateTestWindowInShellWithId(0)); gfx::Rect desktop_area = window1->parent()->bounds(); wm::GetWindowState(window1.get())->set_window_position_managed(true); // Hide and then show |window1| to trigger auto-positioning logic. window1->Hide(); window1->SetBounds(gfx::Rect(16, 32, 300, 300)); window1->Show(); // |window1| should be horizontally centered. int x_window1 = (desktop_area.width() - 300) / 2; EXPECT_EQ(base::IntToString(x_window1) + ",32 300x300", window1->bounds().ToString()); // Create a |child| window and make it a transient child of |window1|. scoped_ptr<Window> child(CreateTestWindowUnparented()); ::wm::AddTransientChild(window1.get(), child.get()); const int x_child = x_window1 + 50; child->SetBounds(gfx::Rect(x_child, 20, 200, 200)); ParentWindowInPrimaryRootWindow(child.get()); child->Show(); wm::ActivateWindow(child.get()); // The |child| should be where it was created. EXPECT_EQ(base::IntToString(x_child) + ",20 200x200", child->bounds().ToString()); // Create and show a second window forcing the first window and its child to // move. scoped_ptr<aura::Window> window2(CreateTestWindowInShellWithId(1)); wm::GetWindowState(window2.get())->set_window_position_managed(true); // Hide and then show |window2| to trigger auto-positioning logic. window2->Hide(); window2->SetBounds(gfx::Rect(32, 48, 250, 250)); window2->Show(); // Check that both |window1| and |child| have moved left. EXPECT_EQ("0,32 300x300", window1->bounds().ToString()); int x = x_child - x_window1; EXPECT_EQ(base::IntToString(x) + ",20 200x200", child->bounds().ToString()); // Check that |window2| has moved right. x = desktop_area.width() - window2->bounds().width(); EXPECT_EQ(base::IntToString(x) + ",48 250x250", window2->bounds().ToString()); } // Test the basic auto placement of one and or two windows in a "simulated // session" of sequential window operations. TEST_F(WorkspaceControllerTest, BasicAutoPlacingOnShowHide) { // Test 1: In case there is no manageable window, no window should shift. scoped_ptr<aura::Window> window1(CreateTestWindowInShellWithId(0)); window1->SetBounds(gfx::Rect(16, 32, 640, 320)); gfx::Rect desktop_area = window1->parent()->bounds(); scoped_ptr<aura::Window> window2(CreateTestWindowInShellWithId(1)); // Trigger the auto window placement function by making it visible. // Note that the bounds are getting changed while it is invisible. window2->Hide(); window2->SetBounds(gfx::Rect(32, 48, 256, 512)); window2->Show(); // Check the initial position of the windows is unchanged. EXPECT_EQ("16,32 640x320", window1->bounds().ToString()); EXPECT_EQ("32,48 256x512", window2->bounds().ToString()); // Remove the second window and make sure that the first window // does NOT get centered. window2.reset(); EXPECT_EQ("16,32 640x320", window1->bounds().ToString()); wm::WindowState* window1_state = wm::GetWindowState(window1.get()); // Test 2: Set up two managed windows and check their auto positioning. window1_state->set_window_position_managed(true); scoped_ptr<aura::Window> window3(CreateTestWindowInShellWithId(2)); wm::GetWindowState(window3.get())->set_window_position_managed(true); // To avoid any auto window manager changes due to SetBounds, the window // gets first hidden and then shown again. window3->Hide(); window3->SetBounds(gfx::Rect(32, 48, 256, 512)); window3->Show(); // |window1| should be flush left and |window3| flush right. EXPECT_EQ("0,32 640x320", window1->bounds().ToString()); EXPECT_EQ(base::IntToString( desktop_area.width() - window3->bounds().width()) + ",48 256x512", window3->bounds().ToString()); // After removing |window3|, |window1| should be centered again. window3.reset(); EXPECT_EQ( base::IntToString( (desktop_area.width() - window1->bounds().width()) / 2) + ",32 640x320", window1->bounds().ToString()); // Test 3: Set up a manageable and a non manageable window and check // positioning. scoped_ptr<aura::Window> window4(CreateTestWindowInShellWithId(3)); // To avoid any auto window manager changes due to SetBounds, the window // gets first hidden and then shown again. window1->Hide(); window1->SetBounds(gfx::Rect(16, 32, 640, 320)); window4->SetBounds(gfx::Rect(32, 48, 256, 512)); window1->Show(); // |window1| should be centered and |window4| untouched. EXPECT_EQ( base::IntToString( (desktop_area.width() - window1->bounds().width()) / 2) + ",32 640x320", window1->bounds().ToString()); EXPECT_EQ("32,48 256x512", window4->bounds().ToString()); // Test4: A single manageable window should get centered. window4.reset(); window1_state->set_bounds_changed_by_user(false); // Trigger the auto window placement function by showing (and hiding) it. window1->Hide(); window1->Show(); // |window1| should be centered. EXPECT_EQ( base::IntToString( (desktop_area.width() - window1->bounds().width()) / 2) + ",32 640x320", window1->bounds().ToString()); } // Test the proper usage of user window movement interaction. TEST_F(WorkspaceControllerTest, TestUserMovedWindowRepositioning) { scoped_ptr<aura::Window> window1(CreateTestWindowInShellWithId(0)); window1->SetBounds(gfx::Rect(16, 32, 640, 320)); gfx::Rect desktop_area = window1->parent()->bounds(); scoped_ptr<aura::Window> window2(CreateTestWindowInShellWithId(1)); window2->SetBounds(gfx::Rect(32, 48, 256, 512)); window1->Hide(); window2->Hide(); wm::WindowState* window1_state = wm::GetWindowState(window1.get()); wm::WindowState* window2_state = wm::GetWindowState(window2.get()); window1_state->set_window_position_managed(true); window2_state->set_window_position_managed(true); EXPECT_FALSE(window1_state->bounds_changed_by_user()); EXPECT_FALSE(window2_state->bounds_changed_by_user()); // Check that the current location gets preserved if the user has // positioned it previously. window1_state->set_bounds_changed_by_user(true); window1->Show(); EXPECT_EQ("16,32 640x320", window1->bounds().ToString()); // Flag should be still set. EXPECT_TRUE(window1_state->bounds_changed_by_user()); EXPECT_FALSE(window2_state->bounds_changed_by_user()); // Turn on the second window and make sure that both windows are now // positionable again (user movement cleared). window2->Show(); // |window1| should be flush left and |window2| flush right. EXPECT_EQ("0,32 640x320", window1->bounds().ToString()); EXPECT_EQ( base::IntToString(desktop_area.width() - window2->bounds().width()) + ",48 256x512", window2->bounds().ToString()); // FLag should now be reset. EXPECT_FALSE(window1_state->bounds_changed_by_user()); EXPECT_FALSE(window2_state->bounds_changed_by_user()); // Going back to one shown window should keep the state. window1_state->set_bounds_changed_by_user(true); window2->Hide(); EXPECT_EQ("0,32 640x320", window1->bounds().ToString()); EXPECT_TRUE(window1_state->bounds_changed_by_user()); } // Test if the single window will be restored at original position. TEST_F(WorkspaceControllerTest, TestSingleWindowsRestoredBounds) { scoped_ptr<aura::Window> window1( CreateTestWindowInShellWithBounds(gfx::Rect(100, 100, 100, 100))); scoped_ptr<aura::Window> window2( CreateTestWindowInShellWithBounds(gfx::Rect(110, 110, 100, 100))); scoped_ptr<aura::Window> window3( CreateTestWindowInShellWithBounds(gfx::Rect(120, 120, 100, 100))); window1->Hide(); window2->Hide(); window3->Hide(); wm::GetWindowState(window1.get())->set_window_position_managed(true); wm::GetWindowState(window2.get())->set_window_position_managed(true); wm::GetWindowState(window3.get())->set_window_position_managed(true); window1->Show(); wm::ActivateWindow(window1.get()); window2->Show(); wm::ActivateWindow(window2.get()); window3->Show(); wm::ActivateWindow(window3.get()); EXPECT_EQ(0, window1->bounds().x()); EXPECT_EQ(window2->GetRootWindow()->bounds().right(), window2->bounds().right()); EXPECT_EQ(0, window3->bounds().x()); window1->Hide(); EXPECT_EQ(window2->GetRootWindow()->bounds().right(), window2->bounds().right()); EXPECT_EQ(0, window3->bounds().x()); // Being a single window will retore the original location. window3->Hide(); wm::ActivateWindow(window2.get()); EXPECT_EQ("110,110 100x100", window2->bounds().ToString()); // Showing the 3rd will push the 2nd window left. window3->Show(); wm::ActivateWindow(window3.get()); EXPECT_EQ(0, window2->bounds().x()); EXPECT_EQ(window3->GetRootWindow()->bounds().right(), window3->bounds().right()); // Being a single window will retore the original location. window2->Hide(); EXPECT_EQ("120,120 100x100", window3->bounds().ToString()); } // Test that user placed windows go back to their user placement after the user // closes all other windows. TEST_F(WorkspaceControllerTest, TestUserHandledWindowRestore) { scoped_ptr<aura::Window> window1(CreateTestWindowInShellWithId(0)); gfx::Rect user_pos = gfx::Rect(16, 42, 640, 320); window1->SetBounds(user_pos); wm::WindowState* window1_state = wm::GetWindowState(window1.get()); window1_state->SetPreAutoManageWindowBounds(user_pos); gfx::Rect desktop_area = window1->parent()->bounds(); // Create a second window to let the auto manager kick in. scoped_ptr<aura::Window> window2(CreateTestWindowInShellWithId(1)); window2->SetBounds(gfx::Rect(32, 48, 256, 512)); window1->Hide(); window2->Hide(); wm::GetWindowState(window1.get())->set_window_position_managed(true); wm::GetWindowState(window2.get())->set_window_position_managed(true); window1->Show(); EXPECT_EQ(user_pos.ToString(), window1->bounds().ToString()); window2->Show(); // |window1| should be flush left and |window2| flush right. EXPECT_EQ("0," + base::IntToString(user_pos.y()) + " 640x320", window1->bounds().ToString()); EXPECT_EQ( base::IntToString(desktop_area.width() - window2->bounds().width()) + ",48 256x512", window2->bounds().ToString()); window2->Hide(); // After the other window get hidden the window has to move back to the // previous position and the bounds should still be set and unchanged. EXPECT_EQ(user_pos.ToString(), window1->bounds().ToString()); ASSERT_TRUE(window1_state->pre_auto_manage_window_bounds()); EXPECT_EQ(user_pos.ToString(), window1_state->pre_auto_manage_window_bounds()->ToString()); } // Solo window should be restored to the bounds where a user moved to. TEST_F(WorkspaceControllerTest, TestRestoreToUserModifiedBounds) { if (!SupportsHostWindowResize()) return; UpdateDisplay("400x300"); gfx::Rect default_bounds(10, 0, 100, 100); scoped_ptr<aura::Window> window1( CreateTestWindowInShellWithBounds(default_bounds)); wm::WindowState* window1_state = wm::GetWindowState(window1.get()); window1->Hide(); window1_state->set_window_position_managed(true); window1->Show(); // First window is centered. EXPECT_EQ("150,0 100x100", window1->bounds().ToString()); scoped_ptr<aura::Window> window2( CreateTestWindowInShellWithBounds(default_bounds)); wm::WindowState* window2_state = wm::GetWindowState(window2.get()); window2->Hide(); window2_state->set_window_position_managed(true); window2->Show(); // Auto positioning pushes windows to each sides. EXPECT_EQ("0,0 100x100", window1->bounds().ToString()); EXPECT_EQ("300,0 100x100", window2->bounds().ToString()); window2->Hide(); // Restores to the center. EXPECT_EQ("150,0 100x100", window1->bounds().ToString()); // A user moved the window. scoped_ptr<WindowResizer> resizer(CreateWindowResizer( window1.get(), gfx::Point(), HTCAPTION, aura::client::WINDOW_MOVE_SOURCE_MOUSE).release()); gfx::Point location = resizer->GetInitialLocation(); location.Offset(-50, 0); resizer->Drag(location, 0); resizer->CompleteDrag(); window1_state->set_bounds_changed_by_user(true); window1->SetBounds(gfx::Rect(100, 0, 100, 100)); window2->Show(); EXPECT_EQ("0,0 100x100", window1->bounds().ToString()); EXPECT_EQ("300,0 100x100", window2->bounds().ToString()); // Window 1 should be restored to the user modified bounds. window2->Hide(); EXPECT_EQ("100,0 100x100", window1->bounds().ToString()); } // Test that a window from normal to minimize will repos the remaining. TEST_F(WorkspaceControllerTest, ToMinimizeRepositionsRemaining) { scoped_ptr<aura::Window> window1(CreateTestWindowInShellWithId(0)); wm::WindowState* window1_state = wm::GetWindowState(window1.get()); window1_state->set_window_position_managed(true); window1->SetBounds(gfx::Rect(16, 32, 640, 320)); gfx::Rect desktop_area = window1->parent()->bounds(); scoped_ptr<aura::Window> window2(CreateTestWindowInShellWithId(1)); wm::WindowState* window2_state = wm::GetWindowState(window2.get()); window2_state->set_window_position_managed(true); window2->SetBounds(gfx::Rect(32, 48, 256, 512)); window1_state->Minimize(); // |window2| should be centered now. EXPECT_TRUE(window2->IsVisible()); EXPECT_TRUE(window2_state->IsNormalStateType()); EXPECT_EQ(base::IntToString( (desktop_area.width() - window2->bounds().width()) / 2) + ",48 256x512", window2->bounds().ToString()); window1_state->Restore(); // |window1| should be flush right and |window3| flush left. EXPECT_EQ(base::IntToString( desktop_area.width() - window1->bounds().width()) + ",32 640x320", window1->bounds().ToString()); EXPECT_EQ("0,48 256x512", window2->bounds().ToString()); } // Test that minimizing an initially maximized window will repos the remaining. TEST_F(WorkspaceControllerTest, MaxToMinRepositionsRemaining) { scoped_ptr<aura::Window> window1(CreateTestWindowInShellWithId(0)); wm::WindowState* window1_state = wm::GetWindowState(window1.get()); window1_state->set_window_position_managed(true); gfx::Rect desktop_area = window1->parent()->bounds(); scoped_ptr<aura::Window> window2(CreateTestWindowInShellWithId(1)); wm::WindowState* window2_state = wm::GetWindowState(window2.get()); window2_state->set_window_position_managed(true); window2->SetBounds(gfx::Rect(32, 48, 256, 512)); window1_state->Maximize(); window1_state->Minimize(); // |window2| should be centered now. EXPECT_TRUE(window2->IsVisible()); EXPECT_TRUE(window2_state->IsNormalStateType()); EXPECT_EQ(base::IntToString( (desktop_area.width() - window2->bounds().width()) / 2) + ",48 256x512", window2->bounds().ToString()); } // Test that nomral, maximize, minimizing will repos the remaining. TEST_F(WorkspaceControllerTest, NormToMaxToMinRepositionsRemaining) { scoped_ptr<aura::Window> window1(CreateTestWindowInShellWithId(0)); window1->SetBounds(gfx::Rect(16, 32, 640, 320)); wm::WindowState* window1_state = wm::GetWindowState(window1.get()); window1_state->set_window_position_managed(true); gfx::Rect desktop_area = window1->parent()->bounds(); scoped_ptr<aura::Window> window2(CreateTestWindowInShellWithId(1)); wm::WindowState* window2_state = wm::GetWindowState(window2.get()); window2_state->set_window_position_managed(true); window2->SetBounds(gfx::Rect(32, 40, 256, 512)); // Trigger the auto window placement function by showing (and hiding) it. window1->Hide(); window1->Show(); // |window1| should be flush right and |window3| flush left. EXPECT_EQ(base::IntToString( desktop_area.width() - window1->bounds().width()) + ",32 640x320", window1->bounds().ToString()); EXPECT_EQ("0,40 256x512", window2->bounds().ToString()); window1_state->Maximize(); window1_state->Minimize(); // |window2| should be centered now. EXPECT_TRUE(window2->IsVisible()); EXPECT_TRUE(window2_state->IsNormalStateType()); EXPECT_EQ(base::IntToString( (desktop_area.width() - window2->bounds().width()) / 2) + ",40 256x512", window2->bounds().ToString()); } // Test that nomral, maximize, normal will repos the remaining. TEST_F(WorkspaceControllerTest, NormToMaxToNormRepositionsRemaining) { scoped_ptr<aura::Window> window1(CreateTestWindowInShellWithId(0)); window1->SetBounds(gfx::Rect(16, 32, 640, 320)); wm::WindowState* window1_state = wm::GetWindowState(window1.get()); window1_state->set_window_position_managed(true); gfx::Rect desktop_area = window1->parent()->bounds(); scoped_ptr<aura::Window> window2(CreateTestWindowInShellWithId(1)); wm::GetWindowState(window2.get())->set_window_position_managed(true); window2->SetBounds(gfx::Rect(32, 40, 256, 512)); // Trigger the auto window placement function by showing (and hiding) it. window1->Hide(); window1->Show(); // |window1| should be flush right and |window3| flush left. EXPECT_EQ(base::IntToString( desktop_area.width() - window1->bounds().width()) + ",32 640x320", window1->bounds().ToString()); EXPECT_EQ("0,40 256x512", window2->bounds().ToString()); window1_state->Maximize(); window1_state->Restore(); // |window1| should be flush right and |window2| flush left. EXPECT_EQ(base::IntToString( desktop_area.width() - window1->bounds().width()) + ",32 640x320", window1->bounds().ToString()); EXPECT_EQ("0,40 256x512", window2->bounds().ToString()); } // Test that animations are triggered. TEST_F(WorkspaceControllerTest, AnimatedNormToMaxToNormRepositionsRemaining) { ui::ScopedAnimationDurationScaleMode test_duration_mode( ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION); scoped_ptr<aura::Window> window1(CreateTestWindowInShellWithId(0)); window1->Hide(); window1->SetBounds(gfx::Rect(16, 32, 640, 320)); gfx::Rect desktop_area = window1->parent()->bounds(); scoped_ptr<aura::Window> window2(CreateTestWindowInShellWithId(1)); window2->Hide(); window2->SetBounds(gfx::Rect(32, 48, 256, 512)); wm::GetWindowState(window1.get())->set_window_position_managed(true); wm::GetWindowState(window2.get())->set_window_position_managed(true); // Make sure nothing is animating. window1->layer()->GetAnimator()->StopAnimating(); window2->layer()->GetAnimator()->StopAnimating(); window2->Show(); // The second window should now animate. EXPECT_FALSE(window1->layer()->GetAnimator()->is_animating()); EXPECT_TRUE(window2->layer()->GetAnimator()->is_animating()); window2->layer()->GetAnimator()->StopAnimating(); window1->Show(); EXPECT_TRUE(window1->layer()->GetAnimator()->is_animating()); EXPECT_TRUE(window2->layer()->GetAnimator()->is_animating()); window1->layer()->GetAnimator()->StopAnimating(); window2->layer()->GetAnimator()->StopAnimating(); // |window1| should be flush right and |window2| flush left. EXPECT_EQ(base::IntToString( desktop_area.width() - window1->bounds().width()) + ",32 640x320", window1->bounds().ToString()); EXPECT_EQ("0,48 256x512", window2->bounds().ToString()); } // This tests simulates a browser and an app and verifies the ordering of the // windows and layers doesn't get out of sync as various operations occur. Its // really testing code in FocusController, but easier to simulate here. Just as // with a real browser the browser here has a transient child window // (corresponds to the status bubble). TEST_F(WorkspaceControllerTest, VerifyLayerOrdering) { scoped_ptr<Window> browser(aura::test::CreateTestWindowWithDelegate( NULL, ui::wm::WINDOW_TYPE_NORMAL, gfx::Rect(5, 6, 7, 8), NULL)); browser->SetName("browser"); ParentWindowInPrimaryRootWindow(browser.get()); browser->Show(); wm::ActivateWindow(browser.get()); // |status_bubble| is made a transient child of |browser| and as a result // owned by |browser|. aura::test::TestWindowDelegate* status_bubble_delegate = aura::test::TestWindowDelegate::CreateSelfDestroyingDelegate(); status_bubble_delegate->set_can_focus(false); Window* status_bubble = aura::test::CreateTestWindowWithDelegate(status_bubble_delegate, ui::wm::WINDOW_TYPE_POPUP, gfx::Rect(5, 6, 7, 8), NULL); ::wm::AddTransientChild(browser.get(), status_bubble); ParentWindowInPrimaryRootWindow(status_bubble); status_bubble->SetName("status_bubble"); scoped_ptr<Window> app(aura::test::CreateTestWindowWithDelegate( NULL, ui::wm::WINDOW_TYPE_NORMAL, gfx::Rect(5, 6, 7, 8), NULL)); app->SetName("app"); ParentWindowInPrimaryRootWindow(app.get()); aura::Window* parent = browser->parent(); app->Show(); wm::ActivateWindow(app.get()); EXPECT_EQ(GetWindowNames(parent), GetLayerNames(parent)); // Minimize the app, focus should go the browser. app->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MINIMIZED); EXPECT_TRUE(wm::IsActiveWindow(browser.get())); EXPECT_EQ(GetWindowNames(parent), GetLayerNames(parent)); // Minimize the browser (neither windows are focused). browser->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MINIMIZED); EXPECT_FALSE(wm::IsActiveWindow(browser.get())); EXPECT_FALSE(wm::IsActiveWindow(app.get())); EXPECT_EQ(GetWindowNames(parent), GetLayerNames(parent)); // Show the browser (which should restore it). browser->Show(); EXPECT_EQ(GetWindowNames(parent), GetLayerNames(parent)); // Activate the browser. ash::wm::ActivateWindow(browser.get()); EXPECT_TRUE(wm::IsActiveWindow(browser.get())); EXPECT_EQ(GetWindowNames(parent), GetLayerNames(parent)); // Restore the app. This differs from above code for |browser| as internally // the app code does this. Restoring this way or using Show() should not make // a difference. app->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_NORMAL); EXPECT_EQ(GetWindowNames(parent), GetLayerNames(parent)); // Activate the app. ash::wm::ActivateWindow(app.get()); EXPECT_TRUE(wm::IsActiveWindow(app.get())); EXPECT_EQ(GetWindowNames(parent), GetLayerNames(parent)); } namespace { // Used by DragMaximizedNonTrackedWindow to track how many times the window // hierarchy changes affecting the specified window. class DragMaximizedNonTrackedWindowObserver : public aura::WindowObserver { public: DragMaximizedNonTrackedWindowObserver(aura::Window* window) : change_count_(0), window_(window) { } // Number of times OnWindowHierarchyChanged() has been received. void clear_change_count() { change_count_ = 0; } int change_count() const { return change_count_; } // aura::WindowObserver overrides: // Counts number of times a window is reparented. Ignores reparenting into and // from a docked container which is expected when a tab is dragged. void OnWindowHierarchyChanged(const HierarchyChangeParams& params) override { if (params.target != window_ || (params.old_parent->id() == kShellWindowId_DefaultContainer && params.new_parent->id() == kShellWindowId_DockedContainer) || (params.old_parent->id() == kShellWindowId_DockedContainer && params.new_parent->id() == kShellWindowId_DefaultContainer)) { return; } change_count_++; } private: int change_count_; aura::Window* window_; DISALLOW_COPY_AND_ASSIGN(DragMaximizedNonTrackedWindowObserver); }; } // namespace // Verifies that a new maximized window becomes visible after its activation // is requested, even though it does not become activated because a system // modal window is active. TEST_F(WorkspaceControllerTest, SwitchFromModal) { scoped_ptr<Window> modal_window(CreateTestWindowUnparented()); modal_window->SetBounds(gfx::Rect(10, 11, 21, 22)); modal_window->SetProperty(aura::client::kModalKey, ui::MODAL_TYPE_SYSTEM); ParentWindowInPrimaryRootWindow(modal_window.get()); modal_window->Show(); wm::ActivateWindow(modal_window.get()); scoped_ptr<Window> maximized_window(CreateTestWindow()); maximized_window->SetProperty( aura::client::kShowStateKey, ui::SHOW_STATE_MAXIMIZED); maximized_window->Show(); wm::ActivateWindow(maximized_window.get()); EXPECT_TRUE(maximized_window->IsVisible()); } namespace { // Subclass of WorkspaceControllerTest that runs tests with docked windows // enabled and disabled. class WorkspaceControllerTestDragging : public WorkspaceControllerTest { public: WorkspaceControllerTestDragging() {} ~WorkspaceControllerTestDragging() override {} private: DISALLOW_COPY_AND_ASSIGN(WorkspaceControllerTestDragging); }; } // namespace // Verifies that when dragging a window over the shelf overlap is detected // during and after the drag. TEST_F(WorkspaceControllerTestDragging, DragWindowOverlapShelf) { aura::test::TestWindowDelegate delegate; delegate.set_window_component(HTCAPTION); scoped_ptr<Window> w1(aura::test::CreateTestWindowWithDelegate( &delegate, ui::wm::WINDOW_TYPE_NORMAL, gfx::Rect(5, 5, 100, 50), NULL)); ParentWindowInPrimaryRootWindow(w1.get()); ShelfLayoutManager* shelf = shelf_layout_manager(); shelf->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_NEVER); // Drag near the shelf. ui::test::EventGenerator generator(Shell::GetPrimaryRootWindow(), gfx::Point()); generator.MoveMouseTo(10, 10); generator.PressLeftButton(); generator.MoveMouseTo(100, shelf->GetIdealBounds().y() - 70); // Shelf should not be in overlapped state. EXPECT_FALSE(GetWindowOverlapsShelf()); generator.MoveMouseTo(100, shelf->GetIdealBounds().y() - 20); // Shelf should detect overlap. Overlap state stays after mouse is released. EXPECT_TRUE(GetWindowOverlapsShelf()); generator.ReleaseLeftButton(); EXPECT_TRUE(GetWindowOverlapsShelf()); } // Verifies that when dragging a window autohidden shelf stays hidden during // and after the drag. TEST_F(WorkspaceControllerTestDragging, DragWindowKeepsShelfAutohidden) { aura::test::TestWindowDelegate delegate; delegate.set_window_component(HTCAPTION); scoped_ptr<Window> w1(aura::test::CreateTestWindowWithDelegate( &delegate, ui::wm::WINDOW_TYPE_NORMAL, gfx::Rect(5, 5, 100, 50), NULL)); ParentWindowInPrimaryRootWindow(w1.get()); ShelfLayoutManager* shelf = shelf_layout_manager(); shelf->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->auto_hide_state()); // Drag very little. ui::test::EventGenerator generator(Shell::GetPrimaryRootWindow(), gfx::Point()); generator.MoveMouseTo(10, 10); generator.PressLeftButton(); generator.MoveMouseTo(12, 12); // Shelf should be hidden during and after the drag. EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->auto_hide_state()); generator.ReleaseLeftButton(); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->auto_hide_state()); } // Verifies that events are targeted properly just outside the window edges. TEST_F(WorkspaceControllerTest, WindowEdgeHitTest) { aura::test::TestWindowDelegate d_first, d_second; scoped_ptr<Window> first(aura::test::CreateTestWindowWithDelegate(&d_first, 123, gfx::Rect(20, 10, 100, 50), NULL)); ParentWindowInPrimaryRootWindow(first.get()); first->Show(); scoped_ptr<Window> second(aura::test::CreateTestWindowWithDelegate(&d_second, 234, gfx::Rect(30, 40, 40, 10), NULL)); ParentWindowInPrimaryRootWindow(second.get()); second->Show(); ui::EventTarget* root = first->GetRootWindow(); ui::EventTargeter* targeter = root->GetEventTargeter(); // The windows overlap, and |second| is on top of |first|. Events targeted // slightly outside the edges of the |second| window should still be targeted // to |second| to allow resizing the windows easily. const int kNumPoints = 4; struct { const char* direction; gfx::Point location; } points[kNumPoints] = { { "left", gfx::Point(28, 45) }, // outside the left edge. { "top", gfx::Point(50, 38) }, // outside the top edge. { "right", gfx::Point(72, 45) }, // outside the right edge. { "bottom", gfx::Point(50, 52) }, // outside the bottom edge. }; // Do two iterations, first without any transform on |second|, and the second // time after applying some transform on |second| so that it doesn't get // targeted. for (int times = 0; times < 2; ++times) { SCOPED_TRACE(times == 0 ? "Without transform" : "With transform"); aura::Window* expected_target = times == 0 ? second.get() : first.get(); for (int i = 0; i < kNumPoints; ++i) { SCOPED_TRACE(points[i].direction); const gfx::Point& location = points[i].location; ui::MouseEvent mouse(ui::ET_MOUSE_MOVED, location, location, ui::EventTimeForNow(), ui::EF_NONE, ui::EF_NONE); ui::EventTarget* target = targeter->FindTargetForEvent(root, &mouse); EXPECT_EQ(expected_target, target); ui::TouchEvent touch(ui::ET_TOUCH_PRESSED, location, 0, ui::EventTimeForNow()); target = targeter->FindTargetForEvent(root, &touch); EXPECT_EQ(expected_target, target); } // Apply a transform on |second|. After the transform is applied, the window // should no longer be targeted. gfx::Transform transform; transform.Translate(70, 40); second->SetTransform(transform); } } // Verifies mouse event targeting just outside the window edges for panels. TEST_F(WorkspaceControllerTest, WindowEdgeMouseHitTestPanel) { aura::test::TestWindowDelegate delegate; scoped_ptr<Window> window(CreateTestPanel(&delegate, gfx::Rect(20, 10, 100, 50))); ui::EventTarget* root = window->GetRootWindow(); ui::EventTargeter* targeter = root->GetEventTargeter(); const gfx::Rect bounds = window->bounds(); const int kNumPoints = 5; struct { const char* direction; gfx::Point location; bool is_target_hit; } points[kNumPoints] = { { "left", gfx::Point(bounds.x() - 2, bounds.y() + 10), true }, { "top", gfx::Point(bounds.x() + 10, bounds.y() - 2), true }, { "right", gfx::Point(bounds.right() + 2, bounds.y() + 10), true }, { "bottom", gfx::Point(bounds.x() + 10, bounds.bottom() + 2), true }, { "outside", gfx::Point(bounds.x() + 10, bounds.y() - 31), false }, }; for (int i = 0; i < kNumPoints; ++i) { SCOPED_TRACE(points[i].direction); const gfx::Point& location = points[i].location; ui::MouseEvent mouse(ui::ET_MOUSE_MOVED, location, location, ui::EventTimeForNow(), ui::EF_NONE, ui::EF_NONE); ui::EventTarget* target = targeter->FindTargetForEvent(root, &mouse); if (points[i].is_target_hit) EXPECT_EQ(window.get(), target); else EXPECT_NE(window.get(), target); } } // Verifies touch event targeting just outside the window edges for panels. // The shelf is aligned to the bottom by default, and so touches just below // the bottom edge of the panel should not target the panel itself because // an AttachedPanelWindowTargeter is installed on the panel container. TEST_F(WorkspaceControllerTest, WindowEdgeTouchHitTestPanel) { aura::test::TestWindowDelegate delegate; scoped_ptr<Window> window(CreateTestPanel(&delegate, gfx::Rect(20, 10, 100, 50))); ui::EventTarget* root = window->GetRootWindow(); ui::EventTargeter* targeter = root->GetEventTargeter(); const gfx::Rect bounds = window->bounds(); const int kNumPoints = 5; struct { const char* direction; gfx::Point location; bool is_target_hit; } points[kNumPoints] = { { "left", gfx::Point(bounds.x() - 2, bounds.y() + 10), true }, { "top", gfx::Point(bounds.x() + 10, bounds.y() - 2), true }, { "right", gfx::Point(bounds.right() + 2, bounds.y() + 10), true }, { "bottom", gfx::Point(bounds.x() + 10, bounds.bottom() + 2), false }, { "outside", gfx::Point(bounds.x() + 10, bounds.y() - 31), false }, }; for (int i = 0; i < kNumPoints; ++i) { SCOPED_TRACE(points[i].direction); const gfx::Point& location = points[i].location; ui::TouchEvent touch(ui::ET_TOUCH_PRESSED, location, 0, ui::EventTimeForNow()); ui::EventTarget* target = targeter->FindTargetForEvent(root, &touch); if (points[i].is_target_hit) EXPECT_EQ(window.get(), target); else EXPECT_NE(window.get(), target); } } // Verifies events targeting just outside the window edges for docked windows. TEST_F(WorkspaceControllerTest, WindowEdgeHitTestDocked) { aura::test::TestWindowDelegate delegate; // Make window smaller than the minimum docked area so that the window edges // are exposed. delegate.set_maximum_size(gfx::Size(180, 200)); scoped_ptr<Window> window(aura::test::CreateTestWindowWithDelegate(&delegate, 123, gfx::Rect(20, 10, 100, 50), NULL)); ParentWindowInPrimaryRootWindow(window.get()); aura::Window* docked_container = Shell::GetContainer( window->GetRootWindow(), kShellWindowId_DockedContainer); docked_container->AddChild(window.get()); window->Show(); ui::EventTarget* root = window->GetRootWindow(); ui::EventTargeter* targeter = root->GetEventTargeter(); const gfx::Rect bounds = window->bounds(); const int kNumPoints = 5; struct { const char* direction; gfx::Point location; bool is_target_hit; } points[kNumPoints] = { { "left", gfx::Point(bounds.x() - 2, bounds.y() + 10), true }, { "top", gfx::Point(bounds.x() + 10, bounds.y() - 2), true }, { "right", gfx::Point(bounds.right() + 2, bounds.y() + 10), true }, { "bottom", gfx::Point(bounds.x() + 10, bounds.bottom() + 2), true }, { "outside", gfx::Point(bounds.x() + 10, bounds.y() - 31), false }, }; for (int i = 0; i < kNumPoints; ++i) { SCOPED_TRACE(points[i].direction); const gfx::Point& location = points[i].location; ui::MouseEvent mouse(ui::ET_MOUSE_MOVED, location, location, ui::EventTimeForNow(), ui::EF_NONE, ui::EF_NONE); ui::EventTarget* target = targeter->FindTargetForEvent(root, &mouse); if (points[i].is_target_hit) EXPECT_EQ(window.get(), target); else EXPECT_NE(window.get(), target); ui::TouchEvent touch(ui::ET_TOUCH_PRESSED, location, 0, ui::EventTimeForNow()); target = targeter->FindTargetForEvent(root, &touch); if (points[i].is_target_hit) EXPECT_EQ(window.get(), target); else EXPECT_NE(window.get(), target); } } } // namespace ash
sgraham/nope
ash/wm/workspace_controller_unittest.cc
C++
bsd-3-clause
62,788
//===- RegAllocFast.cpp - A fast register allocator for debug code --------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // /// \file This register allocator allocates registers to a basic block at a /// time, attempting to keep values in registers and reusing registers as /// appropriate. // //===----------------------------------------------------------------------===// #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/IndexedMap.h" #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/SparseSet.h" #include "llvm/ADT/Statistic.h" #include "llvm/CodeGen/MachineBasicBlock.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineOperand.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/RegAllocRegistry.h" #include "llvm/CodeGen/RegisterClassInfo.h" #include "llvm/CodeGen/TargetInstrInfo.h" #include "llvm/CodeGen/TargetOpcodes.h" #include "llvm/CodeGen/TargetRegisterInfo.h" #include "llvm/CodeGen/TargetSubtargetInfo.h" #include "llvm/IR/DebugLoc.h" #include "llvm/IR/Metadata.h" #include "llvm/MC/MCInstrDesc.h" #include "llvm/MC/MCRegisterInfo.h" #include "llvm/Pass.h" #include "llvm/Support/Casting.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #include <cassert> #include <tuple> #include <vector> using namespace llvm; #define DEBUG_TYPE "regalloc" STATISTIC(NumStores, "Number of stores added"); STATISTIC(NumLoads , "Number of loads added"); STATISTIC(NumCopies, "Number of copies coalesced"); static RegisterRegAlloc fastRegAlloc("fast", "fast register allocator", createFastRegisterAllocator); namespace { class RegAllocFast : public MachineFunctionPass { public: static char ID; RegAllocFast() : MachineFunctionPass(ID), StackSlotForVirtReg(-1) {} private: MachineFrameInfo *MFI; MachineRegisterInfo *MRI; const TargetRegisterInfo *TRI; const TargetInstrInfo *TII; RegisterClassInfo RegClassInfo; /// Basic block currently being allocated. MachineBasicBlock *MBB; /// Maps virtual regs to the frame index where these values are spilled. IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg; /// Everything we know about a live virtual register. struct LiveReg { MachineInstr *LastUse = nullptr; ///< Last instr to use reg. unsigned VirtReg; ///< Virtual register number. MCPhysReg PhysReg = 0; ///< Currently held here. unsigned short LastOpNum = 0; ///< OpNum on LastUse. bool Dirty = false; ///< Register needs spill. explicit LiveReg(unsigned v) : VirtReg(v) {} unsigned getSparseSetIndex() const { return TargetRegisterInfo::virtReg2Index(VirtReg); } }; using LiveRegMap = SparseSet<LiveReg>; /// This map contains entries for each virtual register that is currently /// available in a physical register. LiveRegMap LiveVirtRegs; DenseMap<unsigned, SmallVector<MachineInstr *, 4>> LiveDbgValueMap; /// Track the state of a physical register. enum RegState { /// A disabled register is not available for allocation, but an alias may /// be in use. A register can only be moved out of the disabled state if /// all aliases are disabled. regDisabled, /// A free register is not currently in use and can be allocated /// immediately without checking aliases. regFree, /// A reserved register has been assigned explicitly (e.g., setting up a /// call parameter), and it remains reserved until it is used. regReserved /// A register state may also be a virtual register number, indication /// that the physical register is currently allocated to a virtual /// register. In that case, LiveVirtRegs contains the inverse mapping. }; /// One of the RegState enums, or a virtreg. std::vector<unsigned> PhysRegState; SmallVector<unsigned, 16> VirtDead; SmallVector<MachineInstr *, 32> Coalesced; /// Set of register units. using UsedInInstrSet = SparseSet<unsigned>; /// Set of register units that are used in the current instruction, and so /// cannot be allocated. UsedInInstrSet UsedInInstr; /// Mark a physreg as used in this instruction. void markRegUsedInInstr(MCPhysReg PhysReg) { for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) UsedInInstr.insert(*Units); } /// Check if a physreg or any of its aliases are used in this instruction. bool isRegUsedInInstr(MCPhysReg PhysReg) const { for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) if (UsedInInstr.count(*Units)) return true; return false; } /// This flag is set when LiveRegMap will be cleared completely after /// spilling all live registers. LiveRegMap entries should not be erased. bool isBulkSpilling = false; enum : unsigned { spillClean = 1, spillDirty = 100, spillImpossible = ~0u }; public: StringRef getPassName() const override { return "Fast Register Allocator"; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.setPreservesCFG(); MachineFunctionPass::getAnalysisUsage(AU); } MachineFunctionProperties getRequiredProperties() const override { return MachineFunctionProperties().set( MachineFunctionProperties::Property::NoPHIs); } MachineFunctionProperties getSetProperties() const override { return MachineFunctionProperties().set( MachineFunctionProperties::Property::NoVRegs); } private: bool runOnMachineFunction(MachineFunction &MF) override; void allocateBasicBlock(MachineBasicBlock &MBB); void handleThroughOperands(MachineInstr &MI, SmallVectorImpl<unsigned> &VirtDead); int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass &RC); bool isLastUseOfLocalReg(const MachineOperand &MO) const; void addKillFlag(const LiveReg &LRI); void killVirtReg(LiveRegMap::iterator LRI); void killVirtReg(unsigned VirtReg); void spillVirtReg(MachineBasicBlock::iterator MI, LiveRegMap::iterator); void spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg); void usePhysReg(MachineOperand &MO); void definePhysReg(MachineBasicBlock::iterator MI, MCPhysReg PhysReg, RegState NewState); unsigned calcSpillCost(MCPhysReg PhysReg) const; void assignVirtToPhysReg(LiveReg &, MCPhysReg PhysReg); LiveRegMap::iterator findLiveVirtReg(unsigned VirtReg) { return LiveVirtRegs.find(TargetRegisterInfo::virtReg2Index(VirtReg)); } LiveRegMap::const_iterator findLiveVirtReg(unsigned VirtReg) const { return LiveVirtRegs.find(TargetRegisterInfo::virtReg2Index(VirtReg)); } LiveRegMap::iterator assignVirtToPhysReg(unsigned VirtReg, MCPhysReg PhysReg); LiveRegMap::iterator allocVirtReg(MachineInstr &MI, LiveRegMap::iterator, unsigned Hint); LiveRegMap::iterator defineVirtReg(MachineInstr &MI, unsigned OpNum, unsigned VirtReg, unsigned Hint); LiveRegMap::iterator reloadVirtReg(MachineInstr &MI, unsigned OpNum, unsigned VirtReg, unsigned Hint); void spillAll(MachineBasicBlock::iterator MI); bool setPhysReg(MachineInstr &MI, unsigned OpNum, MCPhysReg PhysReg); void dumpState(); }; } // end anonymous namespace char RegAllocFast::ID = 0; INITIALIZE_PASS(RegAllocFast, "regallocfast", "Fast Register Allocator", false, false) /// This allocates space for the specified virtual register to be held on the /// stack. int RegAllocFast::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass &RC) { // Find the location Reg would belong... int SS = StackSlotForVirtReg[VirtReg]; // Already has space allocated? if (SS != -1) return SS; // Allocate a new stack object for this spill location... unsigned Size = TRI->getSpillSize(RC); unsigned Align = TRI->getSpillAlignment(RC); int FrameIdx = MFI->CreateSpillStackObject(Size, Align); // Assign the slot. StackSlotForVirtReg[VirtReg] = FrameIdx; return FrameIdx; } /// Return true if MO is the only remaining reference to its virtual register, /// and it is guaranteed to be a block-local register. bool RegAllocFast::isLastUseOfLocalReg(const MachineOperand &MO) const { // If the register has ever been spilled or reloaded, we conservatively assume // it is a global register used in multiple blocks. if (StackSlotForVirtReg[MO.getReg()] != -1) return false; // Check that the use/def chain has exactly one operand - MO. MachineRegisterInfo::reg_nodbg_iterator I = MRI->reg_nodbg_begin(MO.getReg()); if (&*I != &MO) return false; return ++I == MRI->reg_nodbg_end(); } /// Set kill flags on last use of a virtual register. void RegAllocFast::addKillFlag(const LiveReg &LR) { if (!LR.LastUse) return; MachineOperand &MO = LR.LastUse->getOperand(LR.LastOpNum); if (MO.isUse() && !LR.LastUse->isRegTiedToDefOperand(LR.LastOpNum)) { if (MO.getReg() == LR.PhysReg) MO.setIsKill(); // else, don't do anything we are problably redefining a // subreg of this register and given we don't track which // lanes are actually dead, we cannot insert a kill flag here. // Otherwise we may end up in a situation like this: // ... = (MO) physreg:sub1, implicit killed physreg // ... <== Here we would allow later pass to reuse physreg:sub1 // which is potentially wrong. // LR:sub0 = ... // ... = LR.sub1 <== This is going to use physreg:sub1 } } /// Mark virtreg as no longer available. void RegAllocFast::killVirtReg(LiveRegMap::iterator LRI) { addKillFlag(*LRI); assert(PhysRegState[LRI->PhysReg] == LRI->VirtReg && "Broken RegState mapping"); PhysRegState[LRI->PhysReg] = regFree; // Erase from LiveVirtRegs unless we're spilling in bulk. if (!isBulkSpilling) LiveVirtRegs.erase(LRI); } /// Mark virtreg as no longer available. void RegAllocFast::killVirtReg(unsigned VirtReg) { assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "killVirtReg needs a virtual register"); LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg); if (LRI != LiveVirtRegs.end()) killVirtReg(LRI); } /// This method spills the value specified by VirtReg into the corresponding /// stack slot if needed. void RegAllocFast::spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg) { assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Spilling a physical register is illegal!"); LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg); assert(LRI != LiveVirtRegs.end() && "Spilling unmapped virtual register"); spillVirtReg(MI, LRI); } /// Do the actual work of spilling. void RegAllocFast::spillVirtReg(MachineBasicBlock::iterator MI, LiveRegMap::iterator LRI) { LiveReg &LR = *LRI; assert(PhysRegState[LR.PhysReg] == LRI->VirtReg && "Broken RegState mapping"); if (LR.Dirty) { // If this physreg is used by the instruction, we want to kill it on the // instruction, not on the spill. bool SpillKill = MachineBasicBlock::iterator(LR.LastUse) != MI; LR.Dirty = false; LLVM_DEBUG(dbgs() << "Spilling " << printReg(LRI->VirtReg, TRI) << " in " << printReg(LR.PhysReg, TRI)); const TargetRegisterClass &RC = *MRI->getRegClass(LRI->VirtReg); int FI = getStackSpaceFor(LRI->VirtReg, RC); LLVM_DEBUG(dbgs() << " to stack slot #" << FI << "\n"); TII->storeRegToStackSlot(*MBB, MI, LR.PhysReg, SpillKill, FI, &RC, TRI); ++NumStores; // Update statistics // If this register is used by DBG_VALUE then insert new DBG_VALUE to // identify spilled location as the place to find corresponding variable's // value. SmallVectorImpl<MachineInstr *> &LRIDbgValues = LiveDbgValueMap[LRI->VirtReg]; for (MachineInstr *DBG : LRIDbgValues) { MachineInstr *NewDV = buildDbgValueForSpill(*MBB, MI, *DBG, FI); assert(NewDV->getParent() == MBB && "dangling parent pointer"); (void)NewDV; LLVM_DEBUG(dbgs() << "Inserting debug info due to spill:" << "\n" << *NewDV); } // Now this register is spilled there is should not be any DBG_VALUE // pointing to this register because they are all pointing to spilled value // now. LRIDbgValues.clear(); if (SpillKill) LR.LastUse = nullptr; // Don't kill register again } killVirtReg(LRI); } /// Spill all dirty virtregs without killing them. void RegAllocFast::spillAll(MachineBasicBlock::iterator MI) { if (LiveVirtRegs.empty()) return; isBulkSpilling = true; // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order // of spilling here is deterministic, if arbitrary. for (LiveRegMap::iterator I = LiveVirtRegs.begin(), E = LiveVirtRegs.end(); I != E; ++I) spillVirtReg(MI, I); LiveVirtRegs.clear(); isBulkSpilling = false; } /// Handle the direct use of a physical register. Check that the register is /// not used by a virtreg. Kill the physreg, marking it free. This may add /// implicit kills to MO->getParent() and invalidate MO. void RegAllocFast::usePhysReg(MachineOperand &MO) { // Ignore undef uses. if (MO.isUndef()) return; unsigned PhysReg = MO.getReg(); assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) && "Bad usePhysReg operand"); markRegUsedInInstr(PhysReg); switch (PhysRegState[PhysReg]) { case regDisabled: break; case regReserved: PhysRegState[PhysReg] = regFree; LLVM_FALLTHROUGH; case regFree: MO.setIsKill(); return; default: // The physreg was allocated to a virtual register. That means the value we // wanted has been clobbered. llvm_unreachable("Instruction uses an allocated register"); } // Maybe a superregister is reserved? for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) { MCPhysReg Alias = *AI; switch (PhysRegState[Alias]) { case regDisabled: break; case regReserved: // Either PhysReg is a subregister of Alias and we mark the // whole register as free, or PhysReg is the superregister of // Alias and we mark all the aliases as disabled before freeing // PhysReg. // In the latter case, since PhysReg was disabled, this means that // its value is defined only by physical sub-registers. This check // is performed by the assert of the default case in this loop. // Note: The value of the superregister may only be partial // defined, that is why regDisabled is a valid state for aliases. assert((TRI->isSuperRegister(PhysReg, Alias) || TRI->isSuperRegister(Alias, PhysReg)) && "Instruction is not using a subregister of a reserved register"); LLVM_FALLTHROUGH; case regFree: if (TRI->isSuperRegister(PhysReg, Alias)) { // Leave the superregister in the working set. PhysRegState[Alias] = regFree; MO.getParent()->addRegisterKilled(Alias, TRI, true); return; } // Some other alias was in the working set - clear it. PhysRegState[Alias] = regDisabled; break; default: llvm_unreachable("Instruction uses an alias of an allocated register"); } } // All aliases are disabled, bring register into working set. PhysRegState[PhysReg] = regFree; MO.setIsKill(); } /// Mark PhysReg as reserved or free after spilling any virtregs. This is very /// similar to defineVirtReg except the physreg is reserved instead of /// allocated. void RegAllocFast::definePhysReg(MachineBasicBlock::iterator MI, MCPhysReg PhysReg, RegState NewState) { markRegUsedInInstr(PhysReg); switch (unsigned VirtReg = PhysRegState[PhysReg]) { case regDisabled: break; default: spillVirtReg(MI, VirtReg); LLVM_FALLTHROUGH; case regFree: case regReserved: PhysRegState[PhysReg] = NewState; return; } // This is a disabled register, disable all aliases. PhysRegState[PhysReg] = NewState; for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) { MCPhysReg Alias = *AI; switch (unsigned VirtReg = PhysRegState[Alias]) { case regDisabled: break; default: spillVirtReg(MI, VirtReg); LLVM_FALLTHROUGH; case regFree: case regReserved: PhysRegState[Alias] = regDisabled; if (TRI->isSuperRegister(PhysReg, Alias)) return; break; } } } /// Return the cost of spilling clearing out PhysReg and aliases so it is /// free for allocation. Returns 0 when PhysReg is free or disabled with all /// aliases disabled - it can be allocated directly. /// \returns spillImpossible when PhysReg or an alias can't be spilled. unsigned RegAllocFast::calcSpillCost(MCPhysReg PhysReg) const { if (isRegUsedInInstr(PhysReg)) { LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << " is already used in instr.\n"); return spillImpossible; } switch (unsigned VirtReg = PhysRegState[PhysReg]) { case regDisabled: break; case regFree: return 0; case regReserved: LLVM_DEBUG(dbgs() << printReg(VirtReg, TRI) << " corresponding " << printReg(PhysReg, TRI) << " is reserved already.\n"); return spillImpossible; default: { LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg); assert(I != LiveVirtRegs.end() && "Missing VirtReg entry"); return I->Dirty ? spillDirty : spillClean; } } // This is a disabled register, add up cost of aliases. LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << " is disabled.\n"); unsigned Cost = 0; for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) { MCPhysReg Alias = *AI; switch (unsigned VirtReg = PhysRegState[Alias]) { case regDisabled: break; case regFree: ++Cost; break; case regReserved: return spillImpossible; default: { LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg); assert(I != LiveVirtRegs.end() && "Missing VirtReg entry"); Cost += I->Dirty ? spillDirty : spillClean; break; } } } return Cost; } /// This method updates local state so that we know that PhysReg is the /// proper container for VirtReg now. The physical register must not be used /// for anything else when this is called. void RegAllocFast::assignVirtToPhysReg(LiveReg &LR, MCPhysReg PhysReg) { LLVM_DEBUG(dbgs() << "Assigning " << printReg(LR.VirtReg, TRI) << " to " << printReg(PhysReg, TRI) << "\n"); PhysRegState[PhysReg] = LR.VirtReg; assert(!LR.PhysReg && "Already assigned a physreg"); LR.PhysReg = PhysReg; } RegAllocFast::LiveRegMap::iterator RegAllocFast::assignVirtToPhysReg(unsigned VirtReg, MCPhysReg PhysReg) { LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg); assert(LRI != LiveVirtRegs.end() && "VirtReg disappeared"); assignVirtToPhysReg(*LRI, PhysReg); return LRI; } /// Allocates a physical register for VirtReg. RegAllocFast::LiveRegMap::iterator RegAllocFast::allocVirtReg(MachineInstr &MI, LiveRegMap::iterator LRI, unsigned Hint) { const unsigned VirtReg = LRI->VirtReg; assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Can only allocate virtual registers"); // Take hint when possible. const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg); if (TargetRegisterInfo::isPhysicalRegister(Hint) && MRI->isAllocatable(Hint) && RC.contains(Hint)) { // Ignore the hint if we would have to spill a dirty register. unsigned Cost = calcSpillCost(Hint); if (Cost < spillDirty) { if (Cost) definePhysReg(MI, Hint, regFree); // definePhysReg may kill virtual registers and modify LiveVirtRegs. // That invalidates LRI, so run a new lookup for VirtReg. return assignVirtToPhysReg(VirtReg, Hint); } } // First try to find a completely free register. ArrayRef<MCPhysReg> AO = RegClassInfo.getOrder(&RC); for (MCPhysReg PhysReg : AO) { if (PhysRegState[PhysReg] == regFree && !isRegUsedInInstr(PhysReg)) { assignVirtToPhysReg(*LRI, PhysReg); return LRI; } } LLVM_DEBUG(dbgs() << "Allocating " << printReg(VirtReg) << " from " << TRI->getRegClassName(&RC) << "\n"); unsigned BestReg = 0; unsigned BestCost = spillImpossible; for (MCPhysReg PhysReg : AO) { unsigned Cost = calcSpillCost(PhysReg); LLVM_DEBUG(dbgs() << "\tRegister: " << printReg(PhysReg, TRI) << "\n"); LLVM_DEBUG(dbgs() << "\tCost: " << Cost << "\n"); LLVM_DEBUG(dbgs() << "\tBestCost: " << BestCost << "\n"); // Cost is 0 when all aliases are already disabled. if (Cost == 0) { assignVirtToPhysReg(*LRI, PhysReg); return LRI; } if (Cost < BestCost) BestReg = PhysReg, BestCost = Cost; } if (BestReg) { definePhysReg(MI, BestReg, regFree); // definePhysReg may kill virtual registers and modify LiveVirtRegs. // That invalidates LRI, so run a new lookup for VirtReg. return assignVirtToPhysReg(VirtReg, BestReg); } // Nothing we can do. Report an error and keep going with a bad allocation. if (MI.isInlineAsm()) MI.emitError("inline assembly requires more registers than available"); else MI.emitError("ran out of registers during register allocation"); definePhysReg(MI, *AO.begin(), regFree); return assignVirtToPhysReg(VirtReg, *AO.begin()); } /// Allocates a register for VirtReg and mark it as dirty. RegAllocFast::LiveRegMap::iterator RegAllocFast::defineVirtReg(MachineInstr &MI, unsigned OpNum, unsigned VirtReg, unsigned Hint) { assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Not a virtual register"); LiveRegMap::iterator LRI; bool New; std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg)); if (New) { // If there is no hint, peek at the only use of this register. if ((!Hint || !TargetRegisterInfo::isPhysicalRegister(Hint)) && MRI->hasOneNonDBGUse(VirtReg)) { const MachineInstr &UseMI = *MRI->use_instr_nodbg_begin(VirtReg); // It's a copy, use the destination register as a hint. if (UseMI.isCopyLike()) Hint = UseMI.getOperand(0).getReg(); } LRI = allocVirtReg(MI, LRI, Hint); } else if (LRI->LastUse) { // Redefining a live register - kill at the last use, unless it is this // instruction defining VirtReg multiple times. if (LRI->LastUse != &MI || LRI->LastUse->getOperand(LRI->LastOpNum).isUse()) addKillFlag(*LRI); } assert(LRI->PhysReg && "Register not assigned"); LRI->LastUse = &MI; LRI->LastOpNum = OpNum; LRI->Dirty = true; markRegUsedInInstr(LRI->PhysReg); return LRI; } /// Make sure VirtReg is available in a physreg and return it. RegAllocFast::LiveRegMap::iterator RegAllocFast::reloadVirtReg(MachineInstr &MI, unsigned OpNum, unsigned VirtReg, unsigned Hint) { assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Not a virtual register"); LiveRegMap::iterator LRI; bool New; std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg)); MachineOperand &MO = MI.getOperand(OpNum); if (New) { LRI = allocVirtReg(MI, LRI, Hint); const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg); int FrameIndex = getStackSpaceFor(VirtReg, RC); LLVM_DEBUG(dbgs() << "Reloading " << printReg(VirtReg, TRI) << " into " << printReg(LRI->PhysReg, TRI) << "\n"); TII->loadRegFromStackSlot(*MBB, MI, LRI->PhysReg, FrameIndex, &RC, TRI); ++NumLoads; } else if (LRI->Dirty) { if (isLastUseOfLocalReg(MO)) { LLVM_DEBUG(dbgs() << "Killing last use: " << MO << "\n"); if (MO.isUse()) MO.setIsKill(); else MO.setIsDead(); } else if (MO.isKill()) { LLVM_DEBUG(dbgs() << "Clearing dubious kill: " << MO << "\n"); MO.setIsKill(false); } else if (MO.isDead()) { LLVM_DEBUG(dbgs() << "Clearing dubious dead: " << MO << "\n"); MO.setIsDead(false); } } else if (MO.isKill()) { // We must remove kill flags from uses of reloaded registers because the // register would be killed immediately, and there might be a second use: // %foo = OR killed %x, %x // This would cause a second reload of %x into a different register. LLVM_DEBUG(dbgs() << "Clearing clean kill: " << MO << "\n"); MO.setIsKill(false); } else if (MO.isDead()) { LLVM_DEBUG(dbgs() << "Clearing clean dead: " << MO << "\n"); MO.setIsDead(false); } assert(LRI->PhysReg && "Register not assigned"); LRI->LastUse = &MI; LRI->LastOpNum = OpNum; markRegUsedInInstr(LRI->PhysReg); return LRI; } /// Changes operand OpNum in MI the refer the PhysReg, considering subregs. This /// may invalidate any operand pointers. Return true if the operand kills its /// register. bool RegAllocFast::setPhysReg(MachineInstr &MI, unsigned OpNum, MCPhysReg PhysReg) { MachineOperand &MO = MI.getOperand(OpNum); bool Dead = MO.isDead(); if (!MO.getSubReg()) { MO.setReg(PhysReg); MO.setIsRenamable(true); return MO.isKill() || Dead; } // Handle subregister index. MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, MO.getSubReg()) : 0); MO.setIsRenamable(true); MO.setSubReg(0); // A kill flag implies killing the full register. Add corresponding super // register kill. if (MO.isKill()) { MI.addRegisterKilled(PhysReg, TRI, true); return true; } // A <def,read-undef> of a sub-register requires an implicit def of the full // register. if (MO.isDef() && MO.isUndef()) MI.addRegisterDefined(PhysReg, TRI); return Dead; } // Handles special instruction operand like early clobbers and tied ops when // there are additional physreg defines. void RegAllocFast::handleThroughOperands(MachineInstr &MI, SmallVectorImpl<unsigned> &VirtDead) { LLVM_DEBUG(dbgs() << "Scanning for through registers:"); SmallSet<unsigned, 8> ThroughRegs; for (const MachineOperand &MO : MI.operands()) { if (!MO.isReg()) continue; unsigned Reg = MO.getReg(); if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue; if (MO.isEarlyClobber() || (MO.isUse() && MO.isTied()) || (MO.getSubReg() && MI.readsVirtualRegister(Reg))) { if (ThroughRegs.insert(Reg).second) LLVM_DEBUG(dbgs() << ' ' << printReg(Reg)); } } // If any physreg defines collide with preallocated through registers, // we must spill and reallocate. LLVM_DEBUG(dbgs() << "\nChecking for physdef collisions.\n"); for (const MachineOperand &MO : MI.operands()) { if (!MO.isReg() || !MO.isDef()) continue; unsigned Reg = MO.getReg(); if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue; markRegUsedInInstr(Reg); for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) { if (ThroughRegs.count(PhysRegState[*AI])) definePhysReg(MI, *AI, regFree); } } SmallVector<unsigned, 8> PartialDefs; LLVM_DEBUG(dbgs() << "Allocating tied uses.\n"); for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) { const MachineOperand &MO = MI.getOperand(I); if (!MO.isReg()) continue; unsigned Reg = MO.getReg(); if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue; if (MO.isUse()) { if (!MO.isTied()) continue; LLVM_DEBUG(dbgs() << "Operand " << I << "(" << MO << ") is tied to operand " << MI.findTiedOperandIdx(I) << ".\n"); LiveRegMap::iterator LRI = reloadVirtReg(MI, I, Reg, 0); MCPhysReg PhysReg = LRI->PhysReg; setPhysReg(MI, I, PhysReg); // Note: we don't update the def operand yet. That would cause the normal // def-scan to attempt spilling. } else if (MO.getSubReg() && MI.readsVirtualRegister(Reg)) { LLVM_DEBUG(dbgs() << "Partial redefine: " << MO << "\n"); // Reload the register, but don't assign to the operand just yet. // That would confuse the later phys-def processing pass. LiveRegMap::iterator LRI = reloadVirtReg(MI, I, Reg, 0); PartialDefs.push_back(LRI->PhysReg); } } LLVM_DEBUG(dbgs() << "Allocating early clobbers.\n"); for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) { const MachineOperand &MO = MI.getOperand(I); if (!MO.isReg()) continue; unsigned Reg = MO.getReg(); if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue; if (!MO.isEarlyClobber()) continue; // Note: defineVirtReg may invalidate MO. LiveRegMap::iterator LRI = defineVirtReg(MI, I, Reg, 0); MCPhysReg PhysReg = LRI->PhysReg; if (setPhysReg(MI, I, PhysReg)) VirtDead.push_back(Reg); } // Restore UsedInInstr to a state usable for allocating normal virtual uses. UsedInInstr.clear(); for (const MachineOperand &MO : MI.operands()) { if (!MO.isReg() || (MO.isDef() && !MO.isEarlyClobber())) continue; unsigned Reg = MO.getReg(); if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue; LLVM_DEBUG(dbgs() << "\tSetting " << printReg(Reg, TRI) << " as used in instr\n"); markRegUsedInInstr(Reg); } // Also mark PartialDefs as used to avoid reallocation. for (unsigned PartialDef : PartialDefs) markRegUsedInInstr(PartialDef); } #ifndef NDEBUG void RegAllocFast::dumpState() { for (unsigned Reg = 1, E = TRI->getNumRegs(); Reg != E; ++Reg) { if (PhysRegState[Reg] == regDisabled) continue; dbgs() << " " << printReg(Reg, TRI); switch(PhysRegState[Reg]) { case regFree: break; case regReserved: dbgs() << "*"; break; default: { dbgs() << '=' << printReg(PhysRegState[Reg]); LiveRegMap::iterator I = findLiveVirtReg(PhysRegState[Reg]); assert(I != LiveVirtRegs.end() && "Missing VirtReg entry"); if (I->Dirty) dbgs() << "*"; assert(I->PhysReg == Reg && "Bad inverse map"); break; } } } dbgs() << '\n'; // Check that LiveVirtRegs is the inverse. for (LiveRegMap::iterator i = LiveVirtRegs.begin(), e = LiveVirtRegs.end(); i != e; ++i) { assert(TargetRegisterInfo::isVirtualRegister(i->VirtReg) && "Bad map key"); assert(TargetRegisterInfo::isPhysicalRegister(i->PhysReg) && "Bad map value"); assert(PhysRegState[i->PhysReg] == i->VirtReg && "Bad inverse map"); } } #endif void RegAllocFast::allocateBasicBlock(MachineBasicBlock &MBB) { this->MBB = &MBB; LLVM_DEBUG(dbgs() << "\nAllocating " << MBB); PhysRegState.assign(TRI->getNumRegs(), regDisabled); assert(LiveVirtRegs.empty() && "Mapping not cleared from last block?"); MachineBasicBlock::iterator MII = MBB.begin(); // Add live-in registers as live. for (const MachineBasicBlock::RegisterMaskPair LI : MBB.liveins()) if (MRI->isAllocatable(LI.PhysReg)) definePhysReg(MII, LI.PhysReg, regReserved); VirtDead.clear(); Coalesced.clear(); // Otherwise, sequentially allocate each instruction in the MBB. for (MachineInstr &MI : MBB) { const MCInstrDesc &MCID = MI.getDesc(); LLVM_DEBUG(dbgs() << "\n>> " << MI << "Regs:"; dumpState()); // Debug values are not allowed to change codegen in any way. if (MI.isDebugValue()) { MachineInstr *DebugMI = &MI; MachineOperand &MO = DebugMI->getOperand(0); // Ignore DBG_VALUEs that aren't based on virtual registers. These are // mostly constants and frame indices. if (!MO.isReg()) continue; unsigned Reg = MO.getReg(); if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue; // See if this virtual register has already been allocated to a physical // register or spilled to a stack slot. LiveRegMap::iterator LRI = findLiveVirtReg(Reg); if (LRI != LiveVirtRegs.end()) setPhysReg(*DebugMI, 0, LRI->PhysReg); else { int SS = StackSlotForVirtReg[Reg]; if (SS != -1) { // Modify DBG_VALUE now that the value is in a spill slot. updateDbgValueForSpill(*DebugMI, SS); LLVM_DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *DebugMI); continue; } // We can't allocate a physreg for a DebugValue, sorry! LLVM_DEBUG(dbgs() << "Unable to allocate vreg used by DBG_VALUE"); MO.setReg(0); } // If Reg hasn't been spilled, put this DBG_VALUE in LiveDbgValueMap so // that future spills of Reg will have DBG_VALUEs. LiveDbgValueMap[Reg].push_back(DebugMI); continue; } if (MI.isDebugLabel()) continue; // If this is a copy, we may be able to coalesce. unsigned CopySrcReg = 0; unsigned CopyDstReg = 0; unsigned CopySrcSub = 0; unsigned CopyDstSub = 0; if (MI.isCopy()) { CopyDstReg = MI.getOperand(0).getReg(); CopySrcReg = MI.getOperand(1).getReg(); CopyDstSub = MI.getOperand(0).getSubReg(); CopySrcSub = MI.getOperand(1).getSubReg(); } // Track registers used by instruction. UsedInInstr.clear(); // First scan. // Mark physreg uses and early clobbers as used. // Find the end of the virtreg operands unsigned VirtOpEnd = 0; bool hasTiedOps = false; bool hasEarlyClobbers = false; bool hasPartialRedefs = false; bool hasPhysDefs = false; for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { MachineOperand &MO = MI.getOperand(i); // Make sure MRI knows about registers clobbered by regmasks. if (MO.isRegMask()) { MRI->addPhysRegsUsedFromRegMask(MO.getRegMask()); continue; } if (!MO.isReg()) continue; unsigned Reg = MO.getReg(); if (!Reg) continue; if (TargetRegisterInfo::isVirtualRegister(Reg)) { VirtOpEnd = i+1; if (MO.isUse()) { hasTiedOps = hasTiedOps || MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1; } else { if (MO.isEarlyClobber()) hasEarlyClobbers = true; if (MO.getSubReg() && MI.readsVirtualRegister(Reg)) hasPartialRedefs = true; } continue; } if (!MRI->isAllocatable(Reg)) continue; if (MO.isUse()) { usePhysReg(MO); } else if (MO.isEarlyClobber()) { definePhysReg(MI, Reg, (MO.isImplicit() || MO.isDead()) ? regFree : regReserved); hasEarlyClobbers = true; } else hasPhysDefs = true; } // The instruction may have virtual register operands that must be allocated // the same register at use-time and def-time: early clobbers and tied // operands. If there are also physical defs, these registers must avoid // both physical defs and uses, making them more constrained than normal // operands. // Similarly, if there are multiple defs and tied operands, we must make // sure the same register is allocated to uses and defs. // We didn't detect inline asm tied operands above, so just make this extra // pass for all inline asm. if (MI.isInlineAsm() || hasEarlyClobbers || hasPartialRedefs || (hasTiedOps && (hasPhysDefs || MCID.getNumDefs() > 1))) { handleThroughOperands(MI, VirtDead); // Don't attempt coalescing when we have funny stuff going on. CopyDstReg = 0; // Pretend we have early clobbers so the use operands get marked below. // This is not necessary for the common case of a single tied use. hasEarlyClobbers = true; } // Second scan. // Allocate virtreg uses. for (unsigned I = 0; I != VirtOpEnd; ++I) { const MachineOperand &MO = MI.getOperand(I); if (!MO.isReg()) continue; unsigned Reg = MO.getReg(); if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue; if (MO.isUse()) { LiveRegMap::iterator LRI = reloadVirtReg(MI, I, Reg, CopyDstReg); MCPhysReg PhysReg = LRI->PhysReg; CopySrcReg = (CopySrcReg == Reg || CopySrcReg == PhysReg) ? PhysReg : 0; if (setPhysReg(MI, I, PhysReg)) killVirtReg(LRI); } } // Track registers defined by instruction - early clobbers and tied uses at // this point. UsedInInstr.clear(); if (hasEarlyClobbers) { for (const MachineOperand &MO : MI.operands()) { if (!MO.isReg()) continue; unsigned Reg = MO.getReg(); if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue; // Look for physreg defs and tied uses. if (!MO.isDef() && !MO.isTied()) continue; markRegUsedInInstr(Reg); } } unsigned DefOpEnd = MI.getNumOperands(); if (MI.isCall()) { // Spill all virtregs before a call. This serves one purpose: If an // exception is thrown, the landing pad is going to expect to find // registers in their spill slots. // Note: although this is appealing to just consider all definitions // as call-clobbered, this is not correct because some of those // definitions may be used later on and we do not want to reuse // those for virtual registers in between. LLVM_DEBUG(dbgs() << " Spilling remaining registers before call.\n"); spillAll(MI); } // Third scan. // Allocate defs and collect dead defs. for (unsigned I = 0; I != DefOpEnd; ++I) { const MachineOperand &MO = MI.getOperand(I); if (!MO.isReg() || !MO.isDef() || !MO.getReg() || MO.isEarlyClobber()) continue; unsigned Reg = MO.getReg(); if (TargetRegisterInfo::isPhysicalRegister(Reg)) { if (!MRI->isAllocatable(Reg)) continue; definePhysReg(MI, Reg, MO.isDead() ? regFree : regReserved); continue; } LiveRegMap::iterator LRI = defineVirtReg(MI, I, Reg, CopySrcReg); MCPhysReg PhysReg = LRI->PhysReg; if (setPhysReg(MI, I, PhysReg)) { VirtDead.push_back(Reg); CopyDstReg = 0; // cancel coalescing; } else CopyDstReg = (CopyDstReg == Reg || CopyDstReg == PhysReg) ? PhysReg : 0; } // Kill dead defs after the scan to ensure that multiple defs of the same // register are allocated identically. We didn't need to do this for uses // because we are crerating our own kill flags, and they are always at the // last use. for (unsigned VirtReg : VirtDead) killVirtReg(VirtReg); VirtDead.clear(); if (CopyDstReg && CopyDstReg == CopySrcReg && CopyDstSub == CopySrcSub) { LLVM_DEBUG(dbgs() << "-- coalescing: " << MI); Coalesced.push_back(&MI); } else { LLVM_DEBUG(dbgs() << "<< " << MI); } } // Spill all physical registers holding virtual registers now. LLVM_DEBUG(dbgs() << "Spilling live registers at end of block.\n"); spillAll(MBB.getFirstTerminator()); // Erase all the coalesced copies. We are delaying it until now because // LiveVirtRegs might refer to the instrs. for (MachineInstr *MI : Coalesced) MBB.erase(MI); NumCopies += Coalesced.size(); LLVM_DEBUG(MBB.dump()); } /// Allocates registers for a function. bool RegAllocFast::runOnMachineFunction(MachineFunction &MF) { LLVM_DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n" << "********** Function: " << MF.getName() << '\n'); MRI = &MF.getRegInfo(); const TargetSubtargetInfo &STI = MF.getSubtarget(); TRI = STI.getRegisterInfo(); TII = STI.getInstrInfo(); MFI = &MF.getFrameInfo(); MRI->freezeReservedRegs(MF); RegClassInfo.runOnMachineFunction(MF); UsedInInstr.clear(); UsedInInstr.setUniverse(TRI->getNumRegUnits()); // initialize the virtual->physical register map to have a 'null' // mapping for all virtual registers unsigned NumVirtRegs = MRI->getNumVirtRegs(); StackSlotForVirtReg.resize(NumVirtRegs); LiveVirtRegs.setUniverse(NumVirtRegs); // Loop over all of the basic blocks, eliminating virtual register references for (MachineBasicBlock &MBB : MF) allocateBasicBlock(MBB); // All machine operands and other references to virtual registers have been // replaced. Remove the virtual registers. MRI->clearVirtRegs(); StackSlotForVirtReg.clear(); LiveDbgValueMap.clear(); return true; } FunctionPass *llvm::createFastRegisterAllocator() { return new RegAllocFast(); }
endlessm/chromium-browser
third_party/swiftshader/third_party/llvm-7.0/llvm/lib/CodeGen/RegAllocFast.cpp
C++
bsd-3-clause
41,634
package org.hisp.dhis.system.util; /* * Copyright (c) 2004-2016, University of Oslo * 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 the HISP project 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. */ import org.hisp.dhis.common.IdentifiableObject; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Collection; import java.util.function.Predicate; /** * @author Morten Olav Hansen <mortenoh@gmail.com> */ public class PredicateUtils { public static final Predicate<Field> idObjectCollections = new CollectionWithTypePredicate( IdentifiableObject.class ); private static class CollectionPredicate implements Predicate<Field> { @Override public boolean test( Field field ) { return Collection.class.isAssignableFrom( field.getType() ); } } private static class CollectionWithTypePredicate implements Predicate<Field> { private CollectionPredicate collectionPredicate = new CollectionPredicate(); private Class<?> type; CollectionWithTypePredicate( Class<?> type ) { this.type = type; } @Override public boolean test( Field field ) { if ( collectionPredicate.test( field ) ) { ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); if ( actualTypeArguments.length > 0 ) { if ( type.isAssignableFrom( (Class<?>) actualTypeArguments[0] ) ) { return true; } } } return false; } } }
mortenoh/dhis2-core
dhis-2/dhis-support/dhis-support-system/src/main/java/org/hisp/dhis/system/util/PredicateUtils.java
Java
bsd-3-clause
3,238
/**************************************************************************** * * Copyright (C) 2018-2019 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name PX4 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. * ****************************************************************************/ /** * @file test_microbench_uorb.cpp * Tests for microbench uORB functionality. */ #include <unit_test.h> #include <time.h> #include <stdlib.h> #include <unistd.h> #include <drivers/drv_hrt.h> #include <perf/perf_counter.h> #include <px4_platform_common/px4_config.h> #include <px4_platform_common/micro_hal.h> #include <uORB/Subscription.hpp> #include <uORB/topics/sensor_accel.h> #include <uORB/topics/sensor_gyro.h> #include <uORB/topics/sensor_gyro_fifo.h> #include <uORB/topics/vehicle_local_position.h> #include <uORB/topics/vehicle_status.h> namespace MicroBenchORB { #ifdef __PX4_NUTTX #include <nuttx/irq.h> static irqstate_t flags; #endif void lock() { #ifdef __PX4_NUTTX flags = px4_enter_critical_section(); #endif } void unlock() { #ifdef __PX4_NUTTX px4_leave_critical_section(flags); #endif } #define PERF(name, op, count) do { \ px4_usleep(1000); \ reset(); \ perf_counter_t p = perf_alloc(PC_ELAPSED, name); \ for (int i = 0; i < count; i++) { \ px4_usleep(1); \ lock(); \ perf_begin(p); \ op; \ perf_end(p); \ unlock(); \ reset(); \ } \ perf_print_counter(p); \ perf_free(p); \ } while (0) class MicroBenchORB : public UnitTest { public: virtual bool run_tests(); private: bool time_px4_uorb(); bool time_px4_uorb_direct(); void reset(); vehicle_status_s status; vehicle_local_position_s lpos; sensor_gyro_s gyro; sensor_gyro_fifo_s gyro_fifo; }; bool MicroBenchORB::run_tests() { ut_run_test(time_px4_uorb); ut_run_test(time_px4_uorb_direct); return (_tests_failed == 0); } template<typename T> T random(T min, T max) { const T scale = rand() / (T) RAND_MAX; /* [0, 1.0] */ return min + scale * (max - min); /* [min, max] */ } void MicroBenchORB::reset() { srand(time(nullptr)); // initialize with random data status.timestamp = rand(); status.mission_failure = rand(); lpos.timestamp = rand(); lpos.dist_bottom_valid = rand(); gyro.timestamp = rand(); gyro_fifo.timestamp = rand(); } ut_declare_test_c(test_microbench_uorb, MicroBenchORB) bool MicroBenchORB::time_px4_uorb() { int fd_status = orb_subscribe(ORB_ID(vehicle_status)); int fd_lpos = orb_subscribe(ORB_ID(vehicle_local_position)); int fd_gyro = orb_subscribe(ORB_ID(sensor_gyro)); int fd_gyro_fifo = orb_subscribe(ORB_ID(sensor_gyro_fifo)); int ret = 0; bool updated = false; uint64_t time = 0; PERF("orb_check vehicle_status", ret = orb_check(fd_status, &updated), 100); PERF("orb_copy vehicle_status", ret = orb_copy(ORB_ID(vehicle_status), fd_status, &status), 100); printf("\n"); PERF("orb_check vehicle_local_position", ret = orb_check(fd_lpos, &updated), 100); PERF("orb_copy vehicle_local_position", ret = orb_copy(ORB_ID(vehicle_local_position), fd_lpos, &lpos), 100); printf("\n"); PERF("orb_check sensor_gyro", ret = orb_check(fd_gyro, &updated), 100); PERF("orb_copy sensor_gyro", ret = orb_copy(ORB_ID(sensor_gyro), fd_gyro, &gyro), 100); printf("\n"); PERF("orb_check sensor_gyro_fifo", ret = orb_check(fd_gyro_fifo, &updated), 100); PERF("orb_copy sensor_gyro_fifo", ret = orb_copy(ORB_ID(sensor_gyro_fifo), fd_gyro_fifo, &gyro_fifo), 100); printf("\n"); PERF("orb_exists sensor_accel 0", ret = orb_exists(ORB_ID(sensor_accel), 0), 100); PERF("orb_exists sensor_accel 1", ret = orb_exists(ORB_ID(sensor_accel), 1), 100); PERF("orb_exists sensor_accel 2", ret = orb_exists(ORB_ID(sensor_accel), 2), 100); PERF("orb_exists sensor_accel 3", ret = orb_exists(ORB_ID(sensor_accel), 3), 100); PERF("orb_exists sensor_accel 4", ret = orb_exists(ORB_ID(sensor_accel), 4), 100); PERF("orb_exists sensor_accel 5", ret = orb_exists(ORB_ID(sensor_accel), 5), 100); PERF("orb_exists sensor_accel 6", ret = orb_exists(ORB_ID(sensor_accel), 6), 100); PERF("orb_exists sensor_accel 7", ret = orb_exists(ORB_ID(sensor_accel), 7), 100); PERF("orb_exists sensor_accel 8", ret = orb_exists(ORB_ID(sensor_accel), 8), 100); PERF("orb_exists sensor_accel 9", ret = orb_exists(ORB_ID(sensor_accel), 9), 100); PERF("orb_exists sensor_accel 10", ret = orb_exists(ORB_ID(sensor_accel), 10), 100); orb_unsubscribe(fd_status); orb_unsubscribe(fd_lpos); orb_unsubscribe(fd_gyro); orb_unsubscribe(fd_gyro_fifo); return true; } bool MicroBenchORB::time_px4_uorb_direct() { bool ret = false; bool updated = false; uint64_t time = 0; uORB::Subscription vstatus{ORB_ID(vehicle_status)}; PERF("uORB::Subscription orb_check vehicle_status", ret = vstatus.updated(), 100); PERF("uORB::Subscription orb_copy vehicle_status", ret = vstatus.copy(&status), 100); printf("\n"); uORB::Subscription local_pos{ORB_ID(vehicle_local_position)}; PERF("uORB::Subscription orb_check vehicle_local_position", ret = local_pos.updated(), 100); PERF("uORB::Subscription orb_copy vehicle_local_position", ret = local_pos.copy(&lpos), 100); { printf("\n"); uORB::Subscription sens_gyro0{ORB_ID(sensor_gyro), 0}; PERF("uORB::Subscription orb_check sensor_gyro:0", ret = sens_gyro0.updated(), 100); PERF("uORB::Subscription orb_copy sensor_gyro:0", ret = sens_gyro0.copy(&gyro), 100); } { printf("\n"); uORB::Subscription sens_gyro1{ORB_ID(sensor_gyro), 1}; PERF("uORB::Subscription orb_check sensor_gyro:1", ret = sens_gyro1.updated(), 100); PERF("uORB::Subscription orb_copy sensor_gyro:1", ret = sens_gyro1.copy(&gyro), 100); } { printf("\n"); uORB::Subscription sens_gyro2{ORB_ID(sensor_gyro), 2}; PERF("uORB::Subscription orb_check sensor_gyro:2", ret = sens_gyro2.updated(), 100); PERF("uORB::Subscription orb_copy sensor_gyro:2", ret = sens_gyro2.copy(&gyro), 100); } { printf("\n"); uORB::Subscription sens_gyro3{ORB_ID(sensor_gyro), 3}; PERF("uORB::Subscription orb_check sensor_gyro:3", ret = sens_gyro3.updated(), 100); PERF("uORB::Subscription orb_copy sensor_gyro:3", ret = sens_gyro3.copy(&gyro), 100); } { printf("\n"); uORB::Subscription sens_gyro_fifo0{ORB_ID(sensor_gyro_fifo), 0}; PERF("uORB::Subscription orb_check sensor_gyro_fifo:0", ret = sens_gyro_fifo0.updated(), 100); PERF("uORB::Subscription orb_copy sensor_gyro_fifo:0", ret = sens_gyro_fifo0.copy(&gyro_fifo), 100); } return true; } } // namespace MicroBenchORB
PX4/Firmware
src/systemcmds/tests/test_microbench_uorb.cpp
C++
bsd-3-clause
7,926
// Copyright (c) 2015 The WebM project authors. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. #include "encoder/capture_source_list.h" #include <sstream> #include "glog/logging.h" #include "encoder/win/media_source_dshow.h" #include "encoder/win/string_util_win.h" class AutoComInit { public: AutoComInit() { CoInitialize(NULL); } ~AutoComInit() { CoUninitialize(); } }; namespace webmlive { std::string GetAudioSourceList() { AutoComInit com_init; CaptureSourceLoader loader; const int status = loader.Init(CLSID_AudioInputDeviceCategory); if (status) { LOG(ERROR) << "no video source!"; return ""; } std::ostringstream aud_list; for (int i = 0; i < loader.GetNumSources(); ++i) { const std::string dev_name = WStringToString(loader.GetSourceName(i).c_str()); LOG(INFO) << "adev" << i << ": " << dev_name; aud_list << i << ": " << dev_name << "\n"; } return aud_list.str(); } std::string GetVideoSourceList() { AutoComInit com_init; CaptureSourceLoader loader; const int status = loader.Init(CLSID_VideoInputDeviceCategory); if (status) { LOG(ERROR) << "no video source!"; return ""; } std::ostringstream vid_list; for (int i = 0; i < loader.GetNumSources(); ++i) { const std::string dev_name = WStringToString(loader.GetSourceName(i).c_str()); LOG(INFO) << "vdev" << i << ": " << dev_name; vid_list << i << ": " << dev_name << "\n"; } return vid_list.str(); } } // namespace webmlive
felipebetancur/webmlive
encoder/win/capture_source_list_dshow.cc
C++
bsd-3-clause
1,799
// 210-Evt-EventListeners.cpp // Contents: // 1. Printing of listener data // 2. My listener and registration // 3. Test cases // main() provided in 000-CatchMain.cpp // Let Catch provide the required interfaces: #define CATCH_CONFIG_EXTERNAL_INTERFACES #include <catch2/catch.hpp> #include <iostream> // ----------------------------------------------------------------------- // 1. Printing of listener data: // std::string ws(int const level) { return std::string( 2 * level, ' ' ); } template< typename T > std::ostream& operator<<( std::ostream& os, std::vector<T> const& v ) { os << "{ "; for ( const auto& x : v ) os << x << ", "; return os << "}"; } // struct SourceLineInfo { // char const* file; // std::size_t line; // }; void print( std::ostream& os, int const level, std::string const& title, Catch::SourceLineInfo const& info ) { os << ws(level ) << title << ":\n" << ws(level+1) << "- file: " << info.file << "\n" << ws(level+1) << "- line: " << info.line << "\n"; } //struct MessageInfo { // std::string macroName; // std::string message; // SourceLineInfo lineInfo; // ResultWas::OfType type; // unsigned int sequence; //}; void print( std::ostream& os, int const level, Catch::MessageInfo const& info ) { os << ws(level+1) << "- macroName: '" << info.macroName << "'\n" << ws(level+1) << "- message '" << info.message << "'\n"; print( os,level+1 , "- lineInfo", info.lineInfo ); os << ws(level+1) << "- sequence " << info.sequence << "\n"; } void print( std::ostream& os, int const level, std::string const& title, std::vector<Catch::MessageInfo> const& v ) { os << ws(level ) << title << ":\n"; for ( const auto& x : v ) { os << ws(level+1) << "{\n"; print( os, level+2, x ); os << ws(level+1) << "}\n"; } // os << ws(level+1) << "\n"; } // struct TestRunInfo { // std::string name; // }; void print( std::ostream& os, int const level, std::string const& title, Catch::TestRunInfo const& info ) { os << ws(level ) << title << ":\n" << ws(level+1) << "- name: " << info.name << "\n"; } // struct Counts { // std::size_t total() const; // bool allPassed() const; // bool allOk() const; // // std::size_t passed = 0; // std::size_t failed = 0; // std::size_t failedButOk = 0; // }; void print( std::ostream& os, int const level, std::string const& title, Catch::Counts const& info ) { os << ws(level ) << title << ":\n" << ws(level+1) << "- total(): " << info.total() << "\n" << ws(level+1) << "- allPassed(): " << info.allPassed() << "\n" << ws(level+1) << "- allOk(): " << info.allOk() << "\n" << ws(level+1) << "- passed: " << info.passed << "\n" << ws(level+1) << "- failed: " << info.failed << "\n" << ws(level+1) << "- failedButOk: " << info.failedButOk << "\n"; } // struct Totals { // Counts assertions; // Counts testCases; // }; void print( std::ostream& os, int const level, std::string const& title, Catch::Totals const& info ) { os << ws(level) << title << ":\n"; print( os, level+1, "- assertions", info.assertions ); print( os, level+1, "- testCases" , info.testCases ); } // struct TestRunStats { // TestRunInfo runInfo; // Totals totals; // bool aborting; // }; void print( std::ostream& os, int const level, std::string const& title, Catch::TestRunStats const& info ) { os << ws(level) << title << ":\n"; print( os, level+1 , "- runInfo", info.runInfo ); print( os, level+1 , "- totals" , info.totals ); os << ws(level+1) << "- aborting: " << info.aborting << "\n"; } // struct TestCaseInfo { // enum SpecialProperties{ // None = 0, // IsHidden = 1 << 1, // ShouldFail = 1 << 2, // MayFail = 1 << 3, // Throws = 1 << 4, // NonPortable = 1 << 5, // Benchmark = 1 << 6 // }; // // bool isHidden() const; // bool throws() const; // bool okToFail() const; // bool expectedToFail() const; // // std::string tagsAsString() const; // // std::string name; // std::string className; // std::string description; // std::vector<std::string> tags; // std::vector<std::string> lcaseTags; // SourceLineInfo lineInfo; // SpecialProperties properties; // }; void print( std::ostream& os, int const level, std::string const& title, Catch::TestCaseInfo const& info ) { os << ws(level ) << title << ":\n" << ws(level+1) << "- isHidden(): " << info.isHidden() << "\n" << ws(level+1) << "- throws(): " << info.throws() << "\n" << ws(level+1) << "- okToFail(): " << info.okToFail() << "\n" << ws(level+1) << "- expectedToFail(): " << info.expectedToFail() << "\n" << ws(level+1) << "- tagsAsString(): '" << info.tagsAsString() << "'\n" << ws(level+1) << "- name: '" << info.name << "'\n" << ws(level+1) << "- className: '" << info.className << "'\n" << ws(level+1) << "- description: '" << info.description << "'\n" << ws(level+1) << "- tags: " << info.tags << "\n" << ws(level+1) << "- lcaseTags: " << info.lcaseTags << "\n"; print( os, level+1 , "- lineInfo", info.lineInfo ); os << ws(level+1) << "- properties (flags): 0x" << std::hex << info.properties << std::dec << "\n"; } // struct TestCaseStats { // TestCaseInfo testInfo; // Totals totals; // std::string stdOut; // std::string stdErr; // bool aborting; // }; void print( std::ostream& os, int const level, std::string const& title, Catch::TestCaseStats const& info ) { os << ws(level ) << title << ":\n"; print( os, level+1 , "- testInfo", info.testInfo ); print( os, level+1 , "- totals" , info.totals ); os << ws(level+1) << "- stdOut: " << info.stdOut << "\n" << ws(level+1) << "- stdErr: " << info.stdErr << "\n" << ws(level+1) << "- aborting: " << info.aborting << "\n"; } // struct SectionInfo { // std::string name; // std::string description; // SourceLineInfo lineInfo; // }; void print( std::ostream& os, int const level, std::string const& title, Catch::SectionInfo const& info ) { os << ws(level ) << title << ":\n" << ws(level+1) << "- name: " << info.name << "\n"; print( os, level+1 , "- lineInfo", info.lineInfo ); } // struct SectionStats { // SectionInfo sectionInfo; // Counts assertions; // double durationInSeconds; // bool missingAssertions; // }; void print( std::ostream& os, int const level, std::string const& title, Catch::SectionStats const& info ) { os << ws(level ) << title << ":\n"; print( os, level+1 , "- sectionInfo", info.sectionInfo ); print( os, level+1 , "- assertions" , info.assertions ); os << ws(level+1) << "- durationInSeconds: " << info.durationInSeconds << "\n" << ws(level+1) << "- missingAssertions: " << info.missingAssertions << "\n"; } // struct AssertionInfo // { // StringRef macroName; // SourceLineInfo lineInfo; // StringRef capturedExpression; // ResultDisposition::Flags resultDisposition; // }; void print( std::ostream& os, int const level, std::string const& title, Catch::AssertionInfo const& info ) { os << ws(level ) << title << ":\n" << ws(level+1) << "- macroName: '" << info.macroName << "'\n"; print( os, level+1 , "- lineInfo" , info.lineInfo ); os << ws(level+1) << "- capturedExpression: '" << info.capturedExpression << "'\n" << ws(level+1) << "- resultDisposition (flags): 0x" << std::hex << info.resultDisposition << std::dec << "\n"; } //struct AssertionResultData //{ // std::string reconstructExpression() const; // // std::string message; // mutable std::string reconstructedExpression; // LazyExpression lazyExpression; // ResultWas::OfType resultType; //}; void print( std::ostream& os, int const level, std::string const& title, Catch::AssertionResultData const& info ) { os << ws(level ) << title << ":\n" << ws(level+1) << "- reconstructExpression(): '" << info.reconstructExpression() << "'\n" << ws(level+1) << "- message: '" << info.message << "'\n" << ws(level+1) << "- lazyExpression: '" << "(info.lazyExpression)" << "'\n" << ws(level+1) << "- resultType: '" << info.resultType << "'\n"; } //class AssertionResult { // bool isOk() const; // bool succeeded() const; // ResultWas::OfType getResultType() const; // bool hasExpression() const; // bool hasMessage() const; // std::string getExpression() const; // std::string getExpressionInMacro() const; // bool hasExpandedExpression() const; // std::string getExpandedExpression() const; // std::string getMessage() const; // SourceLineInfo getSourceInfo() const; // std::string getTestMacroName() const; // // AssertionInfo m_info; // AssertionResultData m_resultData; //}; void print( std::ostream& os, int const level, std::string const& title, Catch::AssertionResult const& info ) { os << ws(level ) << title << ":\n" << ws(level+1) << "- isOk(): " << info.isOk() << "\n" << ws(level+1) << "- succeeded(): " << info.succeeded() << "\n" << ws(level+1) << "- getResultType(): " << info.getResultType() << "\n" << ws(level+1) << "- hasExpression(): " << info.hasExpression() << "\n" << ws(level+1) << "- hasMessage(): " << info.hasMessage() << "\n" << ws(level+1) << "- getExpression(): '" << info.getExpression() << "'\n" << ws(level+1) << "- getExpressionInMacro(): '" << info.getExpressionInMacro() << "'\n" << ws(level+1) << "- hasExpandedExpression(): " << info.hasExpandedExpression() << "\n" << ws(level+1) << "- getExpandedExpression(): " << info.getExpandedExpression() << "'\n" << ws(level+1) << "- getMessage(): '" << info.getMessage() << "'\n"; print( os, level+1 , "- getSourceInfo(): ", info.getSourceInfo() ); os << ws(level+1) << "- getTestMacroName(): '" << info.getTestMacroName() << "'\n"; // print( os, level+1 , "- *** m_info (AssertionInfo)", info.m_info ); // print( os, level+1 , "- *** m_resultData (AssertionResultData)", info.m_resultData ); } // struct AssertionStats { // AssertionResult assertionResult; // std::vector<MessageInfo> infoMessages; // Totals totals; // }; void print( std::ostream& os, int const level, std::string const& title, Catch::AssertionStats const& info ) { os << ws(level ) << title << ":\n"; print( os, level+1 , "- assertionResult", info.assertionResult ); print( os, level+1 , "- infoMessages", info.infoMessages ); print( os, level+1 , "- totals", info.totals ); } // ----------------------------------------------------------------------- // 2. My listener and registration: // char const * dashed_line = "--------------------------------------------------------------------------"; struct MyListener : Catch::TestEventListenerBase { using TestEventListenerBase::TestEventListenerBase; // inherit constructor // Get rid of Wweak-tables ~MyListener(); // The whole test run starting void testRunStarting( Catch::TestRunInfo const& testRunInfo ) override { std::cout << std::boolalpha << "\nEvent: testRunStarting:\n"; print( std::cout, 1, "- testRunInfo", testRunInfo ); } // The whole test run ending void testRunEnded( Catch::TestRunStats const& testRunStats ) override { std::cout << dashed_line << "\nEvent: testRunEnded:\n"; print( std::cout, 1, "- testRunStats", testRunStats ); } // A test is being skipped (because it is "hidden") void skipTest( Catch::TestCaseInfo const& testInfo ) override { std::cout << dashed_line << "\nEvent: skipTest:\n"; print( std::cout, 1, "- testInfo", testInfo ); } // Test cases starting void testCaseStarting( Catch::TestCaseInfo const& testInfo ) override { std::cout << dashed_line << "\nEvent: testCaseStarting:\n"; print( std::cout, 1, "- testInfo", testInfo ); } // Test cases ending void testCaseEnded( Catch::TestCaseStats const& testCaseStats ) override { std::cout << "\nEvent: testCaseEnded:\n"; print( std::cout, 1, "testCaseStats", testCaseStats ); } // Sections starting void sectionStarting( Catch::SectionInfo const& sectionInfo ) override { std::cout << "\nEvent: sectionStarting:\n"; print( std::cout, 1, "- sectionInfo", sectionInfo ); } // Sections ending void sectionEnded( Catch::SectionStats const& sectionStats ) override { std::cout << "\nEvent: sectionEnded:\n"; print( std::cout, 1, "- sectionStats", sectionStats ); } // Assertions before/ after void assertionStarting( Catch::AssertionInfo const& assertionInfo ) override { std::cout << "\nEvent: assertionStarting:\n"; print( std::cout, 1, "- assertionInfo", assertionInfo ); } bool assertionEnded( Catch::AssertionStats const& assertionStats ) override { std::cout << "\nEvent: assertionEnded:\n"; print( std::cout, 1, "- assertionStats", assertionStats ); return true; } }; CATCH_REGISTER_LISTENER( MyListener ) // Get rid of Wweak-tables MyListener::~MyListener() {} // ----------------------------------------------------------------------- // 3. Test cases: // TEST_CASE( "1: Hidden testcase", "[.hidden]" ) { } TEST_CASE( "2: Testcase with sections", "[tag-A][tag-B]" ) { int i = 42; REQUIRE( i == 42 ); SECTION("Section 1") { INFO("Section 1"); i = 7; SECTION("Section 1.1") { INFO("Section 1.1"); REQUIRE( i == 42 ); } } SECTION("Section 2") { INFO("Section 2"); REQUIRE( i == 42 ); } WARN("At end of test case"); } struct Fixture { int fortytwo() const { return 42; } }; TEST_CASE_METHOD( Fixture, "3: Testcase with class-based fixture", "[tag-C][tag-D]" ) { REQUIRE( fortytwo() == 42 ); } // Compile & run: // - g++ -std=c++11 -Wall -I$(CATCH_SINGLE_INCLUDE) -o 210-Evt-EventListeners 210-Evt-EventListeners.cpp 000-CatchMain.o && 210-Evt-EventListeners --success // - cl -EHsc -I%CATCH_SINGLE_INCLUDE% 210-Evt-EventListeners.cpp 000-CatchMain.obj && 210-Evt-EventListeners --success // Expected compact output (all assertions): // // prompt> 210-Evt-EventListeners --reporter compact --success // result omitted for brevity.
ibc/MediaSoup
worker/deps/catch/examples/210-Evt-EventListeners.cpp
C++
isc
14,789
/* ########################################################################### GLOBAL ASSETS RELEASE v6.0.2 BUILD DATE: 20100224 ########################################################################### */ // init values hele = new Array(); newspause = 4; // time to pause news items in seconds fx = op = ni = 0; tp = ns = 1; nop = .1; nextf = -1; mout = "mout"; done = false; newspause = newspause * 1000; function featurefade(selectedf){ if (is.docom){ if (done){ done = false; if (selectedf != 0){ hele['subhover'+selectedf].style.visibility = "visible"; hele['mout'].style.visibility = "visible"; if (fx != 0){ hele['feature'+fx].style.zIndex = 10; hele['subhover'+fx].style.visibility = "hidden"; } hele['feature'+selectedf].style.zIndex = 20; hele['feature'+selectedf].style.visibility = "visible"; fc = fx; fx = selectedf; setTimeout('fadein();',1); }else{ hele['mout'].style.visibility = "hidden"; hele['subhover'+fx].style.visibility = "hidden"; fc = fx; fx = selectedf; op = 1; setTimeout('fadeout();',1); } }else{ nextf = selectedf; } } } function fadein(){ if (!is.op && !is.iemac && !is.oldmoz){ setopacity('feature'+fx,.99); }else{ setopacity('feature'+fx,1); } if (fc != 0){ hele['feature'+fc].style.visibility = "hidden"; } op = 0; done = true; if (nextf != -1){ featurefade(nextf); nextf = -1; } } function fadeout(){ if (!is.op && !is.iemac && !is.oldmoz){ op = op - .5; if (op <= 0){ op = 0; hele['feature'+fc].style.visibility = "hidden"; setopacity('feature'+fc,.99); done = true; }else{ setopacity('feature'+fc,op); setTimeout('fadeout();',50); } }else{ hele['feature'+fc].style.visibility = "hidden"; done = true; } } function fadenews(){ if (nop == .1){ nx = ns + 1; if(nx > tp){ nx = 1; } if (!is.safari && !is.oldmoz && !is.ns6 && !is.iemac){ setopacity('newsitem'+nx,.1); }else{ var nn = 1; while (hele['newsitem'+nn]){ if (nn != nx){ hele['newsitem'+nn].style.visibility = "hidden"; }else{ if (!is.oldmoz){ setopacity('newsitem'+nn,.99); } hele['newsitem'+nn].style.visibility = "visible"; } nn++; } } hele['newsitem'+nx].style.visibility = "visible"; hele['newsitem'+ns].style.zIndex = 3; hele['newsitem'+nx].style.zIndex = 5; } if (!is.safari && !is.oldmoz && !is.ns6){ nop = nop + .2; if (nop >= .99){ nop = .1; hele['newsitem'+ns].style.visibility = "hidden"; setopacity('newsitem'+ns,.99); ns++; if(ns > tp){ ns = 1; } setTimeout('fadenews();',newspause); }else{ setopacity('newsitem'+nx,nop); setTimeout('fadenews();',130); } }else{ ns++; if(ns > tp){ ns = 1; } setTimeout('fadenews();',newspause); } } function setopacity(cobj,opac){ if (document.all && !is.op && !is.iemac){ //ie hele[cobj].filters.alpha.opacity = opac * 100; }else{ hele[cobj].style.MozOpacity = opac; hele[cobj].style.opacity = opac; } } var rollNames=["",""]; function prephome(){ if (is.docom && !hele['newsitem1']){ while (document.getElementById('newsitem'+tp)){ hele['newsitem'+tp] = document.getElementById('newsitem'+tp); hele['newsitem'+tp].style.left='10px'; if (is.oldmoz){ setopacity('newsitem'+tp,1); hele['newsitem'+tp].style.visibility = "hidden"; } if (is.iewin){ hele['newsitem'+tp].style.backgroundImage = 'url(/im/bg_home_b3_iewin.gif)'; } if (tp == 1){ hele['newsitem1'].style.zIndex = 3; } if (is.oldmoz && tp == 1){ hele['newsitem'+tp].style.visibility = "visible"; } tp++; } tp--; // get names for omniture if(rollNames[0] == "" && document.getElementById('ipfeature')){ rollNames[0] = document.getElementById('ipfeature').src.replace(/.*\/b1_([^\/.]+_d).jpg/,"$1");; rollNames[1] = document.getElementById('ipsub1').src.replace(/.*\/b1_([^\/.]+)_p1.gif/,"$1_s");; rollNames[2] = document.getElementById('ipsub2').src.replace(/.*\/b1_([^\/.]+)_p2.gif/,"$1_s");; rollNames[3] = document.getElementById('ipsub3').src.replace(/.*\/b1_([^\/.]+)_p3.gif/,"$1_s");; } var sf = 1; while (document.getElementById('subhover'+sf)){ hele['subhover'+sf] = document.getElementById('subhover'+sf); hele['feature'+sf] = document.getElementById('feature'+sf); if (!is.op && !is.iemac && !is.oldmoz){ setopacity('feature'+sf,1); } sf++; } hele['mout'] = document.getElementById('mout'); if (tp > 0){ setTimeout('fadenews();',newspause); } } // for old code with new page if (!document.getElementById('mtopics')){ movin(); } } // omniture code function customlink(thisfeature) { if(window.s_account){ s_linkType='o'; s_linkName=thisfeature; s_lnk=s_co(this); s_gs(s_account); } } // legacy function var rollCount=[0,0,0,0]; function sendRollData() {}
fbiville/annotation-processing-ftw
doc/javac/8/windows/javac_files/developer.js
JavaScript
mit
4,902
module Fastlane module Notification class Slack def initialize(webhook_url) @webhook_url = webhook_url @client = Faraday.new do |conn| conn.use(Faraday::Response::RaiseError) end end # Overriding channel, icon_url and username is only supported in legacy incoming webhook. # Also note that the use of attachments has been discouraged by Slack, in favor of Block Kit. # https://api.slack.com/legacy/custom-integrations/messaging/webhooks def post_to_legacy_incoming_webhook(channel:, username:, attachments:, link_names:, icon_url:) @client.post(@webhook_url) do |request| request.headers['Content-Type'] = 'application/json' request.body = { channel: channel, username: username, icon_url: icon_url, attachments: attachments, link_names: link_names }.to_json end end # This class was inspired by `LinkFormatter` in `slack-notifier` gem # https://github.com/stevenosloan/slack-notifier/blob/4bf6582663dc9e5070afe3fdc42d67c14a513354/lib/slack-notifier/util/link_formatter.rb class LinkConverter HTML_PATTERN = %r{<a.*?href=['"](?<link>#{URI.regexp})['"].*?>(?<label>.+?)<\/a>} MARKDOWN_PATTERN = /\[(?<label>[^\[\]]*?)\]\((?<link>#{URI.regexp}|mailto:#{URI::MailTo::EMAIL_REGEXP})\)/ def self.convert(string) convert_markdown_to_slack_link(convert_html_to_slack_link(string.scrub)) end def self.convert_html_to_slack_link(string) string.gsub(HTML_PATTERN) do |match| slack_link(Regexp.last_match[:link], Regexp.last_match[:label]) end end def self.convert_markdown_to_slack_link(string) string.gsub(MARKDOWN_PATTERN) do |match| slack_link(Regexp.last_match[:link], Regexp.last_match[:label]) end end def self.slack_link(href, text) return "<#{href}>" if text.nil? || text.empty? "<#{href}|#{text}>" end end end end end
fastlane/fastlane
fastlane/lib/fastlane/notification/slack.rb
Ruby
mit
2,115
#!/usr/bin/env python # Copyright (c) 2014-2015 Daniel Kraft # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # CLI to solve an auxpow (or not) in regtest difficulty. import binascii import hashlib import sys def computeAuxpow (block, target, ok): """ Build an auxpow object (serialised as hex string) that solves (ok = True) or doesn't solve (ok = False) the block. """ # Start by building the merge-mining coinbase. The merkle tree # consists only of the block hash as root. coinbase = "fabe" + binascii.hexlify ("m" * 2) coinbase += block coinbase += "01000000" + ("00" * 4) # Construct "vector" of transaction inputs. vin = "01" vin += ("00" * 32) + ("ff" * 4) vin += ("%02x" % (len (coinbase) / 2)) + coinbase vin += ("ff" * 4) # Build up the full coinbase transaction. It consists only # of the input and has no outputs. tx = "01000000" + vin + "00" + ("00" * 4) txHash = doubleHashHex (tx) # Construct the parent block header. It need not be valid, just good # enough for auxpow purposes. header = "01000000" header += "00" * 32 header += reverseHex (txHash) header += "00" * 4 header += "00" * 4 header += "00" * 4 # Mine the block. (header, blockhash) = mineBlock (header, target, ok) # Build the MerkleTx part of the auxpow. auxpow = tx auxpow += blockhash auxpow += "00" auxpow += "00" * 4 # Extend to full auxpow. auxpow += "00" auxpow += "00" * 4 auxpow += header return auxpow def mineBlock (header, target, ok): """ Given a block header, update the nonce until it is ok (or not) for the given target. """ data = bytearray (binascii.unhexlify (header)) while True: assert data[79] < 255 data[79] += 1 hexData = binascii.hexlify (data) blockhash = doubleHashHex (hexData) if (ok and blockhash < target) or ((not ok) and blockhash > target): break return (hexData, blockhash) def doubleHashHex (data): """ Perform Crowncoin's Double-SHA256 hash on the given hex string. """ hasher = hashlib.sha256 () hasher.update (binascii.unhexlify (data)) data = hasher.digest () hasher = hashlib.sha256 () hasher.update (data) return reverseHex (hasher.hexdigest ()) def reverseHex (data): """ Flip byte order in the given data (hex string). """ b = bytearray (binascii.unhexlify (data)) b.reverse () return binascii.hexlify (b) ################################################################################ if len (sys.argv) != 4: print "Usage: solveauxpow.py HASH _TARGET OK" sys.exit () blockHash = sys.argv[1] revTarget = sys.argv[2] ok = sys.argv[3] if ok not in ["true", "false"]: print "expected 'true' or 'false' as OK value" sys.exit () target = reverseHex (revTarget) ok = (ok == "true") res = computeAuxpow (blockHash, target, ok) print res
cerebrus29301/crowncoin
contrib/solveauxpow.py
Python
mit
3,047
/* * C# Version Ported by Matt Bettcher and Ian Qvist 2009-2010 * * Original C++ Version Copyright (c) 2007 Eric Jordan * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.Xna.Framework; namespace FarseerPhysics.Common.Decomposition { /// <summary> /// Convex decomposition algorithm using ear clipping /// /// Properties: /// - Only works on simple polygons. /// - Does not support holes. /// - Running time is O(n^2), n = number of vertices. /// /// Source: http://www.ewjordan.com/earClip/ /// </summary> internal static class EarclipDecomposer { //box2D rev 32 - for details, see http://www.box2d.org/forum/viewtopic.php?f=4&t=83&start=50 /// <summary> /// Decompose the polygon into several smaller non-concave polygon. /// Each resulting polygon will have no more than Settings.MaxPolygonVertices vertices. /// </summary> /// <param name="vertices">The vertices.</param> /// <param name="tolerance">The tolerance.</param> public static List<Vertices> convexPartition( Vertices vertices, float tolerance = 0.001f ) { Debug.Assert( vertices.Count > 3 ); Debug.Assert( !vertices.isCounterClockWise() ); return triangulatePolygon( vertices, tolerance ); } /// <summary> /// Triangulates a polygon using simple ear-clipping algorithm. Returns /// size of Triangle array unless the polygon can't be triangulated. /// This should only happen if the polygon self-intersects, /// though it will not _always_ return null for a bad polygon - it is the /// caller's responsibility to check for self-intersection, and if it /// doesn't, it should at least check that the return value is non-null /// before using. You're warned! /// /// Triangles may be degenerate, especially if you have identical points /// in the input to the algorithm. Check this before you use them. /// /// This is totally unoptimized, so for large polygons it should not be part /// of the simulation loop. /// </summary> /// <remarks> /// Only works on simple polygons. /// </remarks> static List<Vertices> triangulatePolygon( Vertices vertices, float tolerance ) { //FPE note: Check is needed as invalid triangles can be returned in recursive calls. if( vertices.Count < 3 ) return new List<Vertices>(); var results = new List<Vertices>(); //Recurse and split on pinch points Vertices pA, pB; var pin = new Vertices( vertices ); if( resolvePinchPoint( pin, out pA, out pB, tolerance ) ) { var mergeA = triangulatePolygon( pA, tolerance ); var mergeB = triangulatePolygon( pB, tolerance ); if( mergeA.Count == -1 || mergeB.Count == -1 ) throw new Exception( "Can't triangulate your polygon." ); for( int i = 0; i < mergeA.Count; ++i ) results.Add( new Vertices( mergeA[i] ) ); for( int i = 0; i < mergeB.Count; ++i ) results.Add( new Vertices( mergeB[i] ) ); return results; } var buffer = new Vertices[vertices.Count - 2]; var bufferSize = 0; var xrem = new float[vertices.Count]; var yrem = new float[vertices.Count]; for( int i = 0; i < vertices.Count; ++i ) { xrem[i] = vertices[i].X; yrem[i] = vertices[i].Y; } var vNum = vertices.Count; while( vNum > 3 ) { // Find an ear var earIndex = -1; var earMaxMinCross = -10.0f; for( int i = 0; i < vNum; ++i ) { if( isEar( i, xrem, yrem, vNum ) ) { var lower = remainder( i - 1, vNum ); var upper = remainder( i + 1, vNum ); var d1 = new Vector2( xrem[upper] - xrem[i], yrem[upper] - yrem[i] ); var d2 = new Vector2( xrem[i] - xrem[lower], yrem[i] - yrem[lower] ); var d3 = new Vector2( xrem[lower] - xrem[upper], yrem[lower] - yrem[upper] ); Nez.Vector2Ext.normalize( ref d1 ); Nez.Vector2Ext.normalize( ref d2 ); Nez.Vector2Ext.normalize( ref d3 ); float cross12; MathUtils.cross( ref d1, ref d2, out cross12 ); cross12 = Math.Abs( cross12 ); float cross23; MathUtils.cross( ref d2, ref d3, out cross23 ); cross23 = Math.Abs( cross23 ); float cross31; MathUtils.cross( ref d3, ref d1, out cross31 ); cross31 = Math.Abs( cross31 ); //Find the maximum minimum angle float minCross = Math.Min( cross12, Math.Min( cross23, cross31 ) ); if( minCross > earMaxMinCross ) { earIndex = i; earMaxMinCross = minCross; } } } // If we still haven't found an ear, we're screwed. // Note: sometimes this is happening because the // remaining points are collinear. Really these // should just be thrown out without halting triangulation. if( earIndex == -1 ) { for( int i = 0; i < bufferSize; i++ ) results.Add( buffer[i] ); return results; } // Clip off the ear: // - remove the ear tip from the list --vNum; float[] newx = new float[vNum]; float[] newy = new float[vNum]; int currDest = 0; for( int i = 0; i < vNum; ++i ) { if( currDest == earIndex ) ++currDest; newx[i] = xrem[currDest]; newy[i] = yrem[currDest]; ++currDest; } // - add the clipped triangle to the triangle list int under = ( earIndex == 0 ) ? ( vNum ) : ( earIndex - 1 ); int over = ( earIndex == vNum ) ? 0 : ( earIndex + 1 ); var toAdd = new Triangle( xrem[earIndex], yrem[earIndex], xrem[over], yrem[over], xrem[under], yrem[under] ); buffer[bufferSize] = toAdd; ++bufferSize; // - replace the old list with the new one xrem = newx; yrem = newy; } var tooAdd = new Triangle( xrem[1], yrem[1], xrem[2], yrem[2], xrem[0], yrem[0] ); buffer[bufferSize] = tooAdd; ++bufferSize; for( int i = 0; i < bufferSize; i++ ) results.Add( new Vertices( buffer[i] ) ); return results; } /// <summary> /// Finds and fixes "pinch points," points where two polygon /// vertices are at the same point. /// /// If a pinch point is found, pin is broken up into poutA and poutB /// and true is returned; otherwise, returns false. /// /// Mostly for internal use. /// /// O(N^2) time, which sucks... /// </summary> /// <param name="pin">The pin.</param> /// <param name="poutA">The pout A.</param> /// <param name="poutB">The pout B.</param> /// <param name="tolerance"></param> static bool resolvePinchPoint( Vertices pin, out Vertices poutA, out Vertices poutB, float tolerance ) { poutA = new Vertices(); poutB = new Vertices(); if( pin.Count < 3 ) return false; bool hasPinchPoint = false; int pinchIndexA = -1; int pinchIndexB = -1; for( int i = 0; i < pin.Count; ++i ) { for( int j = i + 1; j < pin.Count; ++j ) { //Don't worry about pinch points where the points //are actually just dupe neighbors if( Math.Abs( pin[i].X - pin[j].X ) < tolerance && Math.Abs( pin[i].Y - pin[j].Y ) < tolerance && j != i + 1 ) { pinchIndexA = i; pinchIndexB = j; hasPinchPoint = true; break; } } if( hasPinchPoint ) break; } if( hasPinchPoint ) { int sizeA = pinchIndexB - pinchIndexA; if( sizeA == pin.Count ) return false; //has dupe points at wraparound, not a problem here for( int i = 0; i < sizeA; ++i ) { int ind = remainder( pinchIndexA + i, pin.Count ); // is this right poutA.Add( pin[ind] ); } int sizeB = pin.Count - sizeA; for( int i = 0; i < sizeB; ++i ) { int ind = remainder( pinchIndexB + i, pin.Count ); // is this right poutB.Add( pin[ind] ); } } return hasPinchPoint; } /// <summary> /// Fix for obnoxious behavior for the % operator for negative numbers... /// </summary> /// <param name="x">The x.</param> /// <param name="modulus">The modulus.</param> /// <returns></returns> static int remainder( int x, int modulus ) { int rem = x % modulus; while( rem < 0 ) { rem += modulus; } return rem; } /// <summary> /// Checks if vertex i is the tip of an ear in polygon defined by xv[] and yv[]. /// </summary> /// <param name="i">The i.</param> /// <param name="xv">The xv.</param> /// <param name="yv">The yv.</param> /// <param name="xvLength">Length of the xv.</param> /// <remarks> /// Assumes clockwise orientation of polygon. /// </remarks> /// <returns> /// <c>true</c> if the specified i is ear; otherwise, <c>false</c>. /// </returns> static bool isEar( int i, float[] xv, float[] yv, int xvLength ) { float dx0, dy0, dx1, dy1; if( i >= xvLength || i < 0 || xvLength < 3 ) { return false; } int upper = i + 1; int lower = i - 1; if( i == 0 ) { dx0 = xv[0] - xv[xvLength - 1]; dy0 = yv[0] - yv[xvLength - 1]; dx1 = xv[1] - xv[0]; dy1 = yv[1] - yv[0]; lower = xvLength - 1; } else if( i == xvLength - 1 ) { dx0 = xv[i] - xv[i - 1]; dy0 = yv[i] - yv[i - 1]; dx1 = xv[0] - xv[i]; dy1 = yv[0] - yv[i]; upper = 0; } else { dx0 = xv[i] - xv[i - 1]; dy0 = yv[i] - yv[i - 1]; dx1 = xv[i + 1] - xv[i]; dy1 = yv[i + 1] - yv[i]; } float cross = dx0 * dy1 - dx1 * dy0; if( cross > 0 ) return false; var myTri = new Triangle( xv[i], yv[i], xv[upper], yv[upper], xv[lower], yv[lower] ); for( int j = 0; j < xvLength; ++j ) { if( j == i || j == lower || j == upper ) continue; if( myTri.isInside( xv[j], yv[j] ) ) return false; } return true; } class Triangle : Vertices { //Constructor automatically fixes orientation to ccw public Triangle( float x1, float y1, float x2, float y2, float x3, float y3 ) { float cross = ( x2 - x1 ) * ( y3 - y1 ) - ( x3 - x1 ) * ( y2 - y1 ); if( cross > 0 ) { Add( new Vector2( x1, y1 ) ); Add( new Vector2( x2, y2 ) ); Add( new Vector2( x3, y3 ) ); } else { Add( new Vector2( x1, y1 ) ); Add( new Vector2( x3, y3 ) ); Add( new Vector2( x2, y2 ) ); } } public bool isInside( float x, float y ) { Vector2 a = this[0]; Vector2 b = this[1]; Vector2 c = this[2]; if( x < a.X && x < b.X && x < c.X ) return false; if( x > a.X && x > b.X && x > c.X ) return false; if( y < a.Y && y < b.Y && y < c.Y ) return false; if( y > a.Y && y > b.Y && y > c.Y ) return false; float vx2 = x - a.X; float vy2 = y - a.Y; float vx1 = b.X - a.X; float vy1 = b.Y - a.Y; float vx0 = c.X - a.X; float vy0 = c.Y - a.Y; float dot00 = vx0 * vx0 + vy0 * vy0; float dot01 = vx0 * vx1 + vy0 * vy1; float dot02 = vx0 * vx2 + vy0 * vy2; float dot11 = vx1 * vx1 + vy1 * vy1; float dot12 = vx1 * vx2 + vy1 * vy2; float invDenom = 1.0f / ( dot00 * dot11 - dot01 * dot01 ); float u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom; float v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom; return ( ( u > 0 ) && ( v > 0 ) && ( u + v < 1 ) ); } } } }
Blucky87/Nez
Nez.FarseerPhysics/Farseer/Common/Decomposition/EarclipDecomposer.cs
C#
mit
11,877
import * as React from 'react'; import Select, { Props as SelectProps } from './Select'; import { handleInputChange } from './utils'; import manageState from './stateManager'; import { GroupedOptionsType, OptionsType, InputActionMeta, OptionTypeBase } from './types'; export interface AsyncProps<OptionType extends OptionTypeBase> { /* The default set of options to show before the user starts searching. When set to `true`, the results for loadOptions('') will be autoloaded. Default: false. */ defaultOptions?: GroupedOptionsType<OptionType> | OptionsType<OptionType> | boolean; /* Function that returns a promise, which is the set of options to be used once the promise resolves. */ loadOptions: (inputValue: string, callback: ((options: OptionsType<OptionType>) => void)) => Promise<any> | void; /* If cacheOptions is truthy, then the loaded data will be cached. The cache will remain until `cacheOptions` changes value. Default: false. */ cacheOptions?: any; } export type Props<OptionType extends OptionTypeBase> = SelectProps<OptionType> & AsyncProps<OptionType>; export const defaultProps: Props<any>; export interface State<OptionType extends OptionTypeBase> { defaultOptions?: OptionsType<OptionType>; inputValue: string; isLoading: boolean; loadedInputValue?: string; loadedOptions: OptionsType<OptionType>; passEmptyOptions: boolean; } export class Async<OptionType extends OptionTypeBase> extends React.Component<Props<OptionType>, State<OptionType>> { static defaultProps: Props<any>; select: React.Ref<any>; lastRequest: {}; mounted: boolean; optionsCache: { [key: string]: OptionsType<OptionType> }; focus(): void; blur(): void; loadOptions(inputValue: string, callback: (options: OptionsType<OptionType>) => void): void; handleInputChange: (newValue: string, actionMeta: InputActionMeta) => string; } type ClassProps<T> = T extends new (props: infer P) => any ? P : never; type FunctionProps<T> = T extends (props: infer P) => any ? P : never; type SelectComponentProps<T> = T extends React.FunctionComponent<any> ? FunctionProps<T> : T extends React.ComponentClass<any> ? ClassProps<T> : never; type AsyncComponentProps<T extends React.ComponentType<any> = React.ComponentType<any>> = SelectComponentProps<T> & AsyncProps<any>; export function makeAsyncSelect<T extends React.ComponentType<any> = React.ComponentType<any>>( SelectComponent: T, ): React.ComponentClass<AsyncComponentProps<T>>; export default Async;
mcliment/DefinitelyTyped
types/react-select/src/Async.d.ts
TypeScript
mit
2,527
package org.knowm.xchange.ccex.dto.trade; import java.math.BigDecimal; import com.fasterxml.jackson.annotation.JsonProperty; public class CCEXOpenorder { private String OrderUuid; private String Exchange; private String OrderType; private BigDecimal Quantity; private BigDecimal QuantityRemaining; private BigDecimal Limit; private BigDecimal CommissionPaid; private BigDecimal Price; private BigDecimal PricePerUnit; private String Opened; private String Closed; private boolean CancelInitiated; private boolean ImmediateOrCancel; private boolean IsConditional; private String Condition; private String ConditionTarget; public CCEXOpenorder( @JsonProperty("OrderUuid") String orderUuid, @JsonProperty("Exchange") String exchange, @JsonProperty("OrderType") String orderType, @JsonProperty("Quantity") BigDecimal quantity, @JsonProperty("QuantityRemaining") BigDecimal quantityRemaining, @JsonProperty("Limit") BigDecimal limit, @JsonProperty("CommissionPaid") BigDecimal commissionPaid, @JsonProperty("Price") BigDecimal price, @JsonProperty("PricePerUnit") BigDecimal pricePerUnit, @JsonProperty("Opened") String opened, @JsonProperty("Closed") String closed, @JsonProperty("CancelInitiated") boolean cancelInitiated, @JsonProperty("ImmediateOrCancel") boolean immediateOrCancel, @JsonProperty("IsConditional") boolean isConditional, @JsonProperty("Condition") String condition, @JsonProperty("ConditionTarget") String conditionTarget) { super(); OrderUuid = orderUuid; Exchange = exchange; OrderType = orderType; Quantity = quantity; QuantityRemaining = quantityRemaining; Limit = limit; CommissionPaid = commissionPaid; Price = price; PricePerUnit = pricePerUnit; Opened = opened; Closed = closed; CancelInitiated = cancelInitiated; ImmediateOrCancel = immediateOrCancel; IsConditional = isConditional; Condition = condition; ConditionTarget = conditionTarget; } public String getOrderUuid() { return OrderUuid; } public void setOrderUuid(String orderUuid) { OrderUuid = orderUuid; } public String getExchange() { return Exchange; } public void setExchange(String exchange) { Exchange = exchange; } public String getOrderType() { return OrderType; } public void setOrderType(String orderType) { OrderType = orderType; } public BigDecimal getQuantity() { return Quantity; } public void setQuantity(BigDecimal quantity) { Quantity = quantity; } public BigDecimal getQuantityRemaining() { return QuantityRemaining; } public void setQuantityRemaining(BigDecimal quantityRemaining) { QuantityRemaining = quantityRemaining; } public BigDecimal getLimit() { return Limit; } public void setLimit(BigDecimal limit) { Limit = limit; } public BigDecimal getCommissionPaid() { return CommissionPaid; } public void setCommissionPaid(BigDecimal commissionPaid) { CommissionPaid = commissionPaid; } public BigDecimal getPrice() { return Price; } public void setPrice(BigDecimal price) { Price = price; } public BigDecimal getPricePerUnit() { return PricePerUnit; } public void setPricePerUnit(BigDecimal pricePerUnit) { PricePerUnit = pricePerUnit; } public String getOpened() { return Opened; } public void setOpened(String opened) { Opened = opened; } public String getClosed() { return Closed; } public void setClosed(String closed) { Closed = closed; } public boolean isCancelInitiated() { return CancelInitiated; } public void setCancelInitiated(boolean cancelInitiated) { CancelInitiated = cancelInitiated; } public boolean isImmediateOrCancel() { return ImmediateOrCancel; } public void setImmediateOrCancel(boolean immediateOrCancel) { ImmediateOrCancel = immediateOrCancel; } public boolean isIsConditional() { return IsConditional; } public void setIsConditional(boolean isConditional) { IsConditional = isConditional; } public String getCondition() { return Condition; } public void setCondition(String condition) { Condition = condition; } public String getConditionTarget() { return ConditionTarget; } public void setConditionTarget(String conditionTarget) { ConditionTarget = conditionTarget; } @Override public String toString() { return "CCEXOpenorder [OrderUuid=" + OrderUuid + ", Exchange=" + Exchange + ", OrderType=" + OrderType + ", Quantity=" + Quantity + ", QuantityRemaining=" + QuantityRemaining + ", Limit=" + Limit + ", CommissionPaid=" + CommissionPaid + ", Price=" + Price + ", PricePerUnit=" + PricePerUnit + ", Opened=" + Opened + ", Closed=" + Closed + ", CancelInitiated=" + CancelInitiated + ", ImmediateOrCancel=" + ImmediateOrCancel + ", IsConditional=" + IsConditional + ", Condition=" + Condition + ", ConditionTarget=" + ConditionTarget + "]"; } }
stevenuray/XChange
xchange-ccex/src/main/java/org/knowm/xchange/ccex/dto/trade/CCEXOpenorder.java
Java
mit
4,881
module Pod class Command class IPC < Command class List < IPC self.summary = 'Lists the specifications known to CocoaPods' self.description = <<-DESC Prints to STDOUT a YAML dictionary where the keys are the name of the specifications and each corresponding value is a dictionary with the following keys: - defined_in_file - version - authors - summary - description - platforms DESC def run require 'yaml' sets = config.sources_manager.aggregate.all_sets result = {} sets.each do |set| begin spec = set.specification result[spec.name] = { 'authors' => spec.authors.keys, 'summary' => spec.summary, 'description' => spec.description, 'platforms' => spec.available_platforms.map { |p| p.name.to_s }, } rescue DSLError next end end output_pipe.puts result.to_yaml end end end end end
morizotter/SwiftyDrop
vendor/bundle/gems/cocoapods-1.5.3/lib/cocoapods/command/ipc/list.rb
Ruby
mit
1,153
package buildpack import ( "fmt" "strconv" "code.cloudfoundry.org/cli/cf/flags" . "code.cloudfoundry.org/cli/cf/i18n" "code.cloudfoundry.org/cli/cf" "code.cloudfoundry.org/cli/cf/api" "code.cloudfoundry.org/cli/cf/commandregistry" "code.cloudfoundry.org/cli/cf/errors" "code.cloudfoundry.org/cli/cf/models" "code.cloudfoundry.org/cli/cf/requirements" "code.cloudfoundry.org/cli/cf/terminal" ) type CreateBuildpack struct { ui terminal.UI buildpackRepo api.BuildpackRepository buildpackBitsRepo api.BuildpackBitsRepository } func init() { commandregistry.Register(&CreateBuildpack{}) } func (cmd *CreateBuildpack) MetaData() commandregistry.CommandMetadata { fs := make(map[string]flags.FlagSet) fs["enable"] = &flags.BoolFlag{Name: "enable", Usage: T("Enable the buildpack to be used for staging")} fs["disable"] = &flags.BoolFlag{Name: "disable", Usage: T("Disable the buildpack from being used for staging")} return commandregistry.CommandMetadata{ Name: "create-buildpack", Description: T("Create a buildpack"), Usage: []string{ T("CF_NAME create-buildpack BUILDPACK PATH POSITION [--enable|--disable]"), T("\n\nTIP:\n"), T(" Path should be a zip file, a url to a zip file, or a local directory. Position is a positive integer, sets priority, and is sorted from lowest to highest."), }, Flags: fs, TotalArgs: 3, } } func (cmd *CreateBuildpack) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) ([]requirements.Requirement, error) { if len(fc.Args()) != 3 { cmd.ui.Failed(T("Incorrect Usage. Requires buildpack_name, path and position as arguments\n\n") + commandregistry.Commands.CommandUsage("create-buildpack")) return nil, fmt.Errorf("Incorrect usage: %d arguments of %d required", len(fc.Args()), 3) } reqs := []requirements.Requirement{ requirementsFactory.NewLoginRequirement(), } return reqs, nil } func (cmd *CreateBuildpack) SetDependency(deps commandregistry.Dependency, pluginCall bool) commandregistry.Command { cmd.ui = deps.UI cmd.buildpackRepo = deps.RepoLocator.GetBuildpackRepository() cmd.buildpackBitsRepo = deps.RepoLocator.GetBuildpackBitsRepository() return cmd } func (cmd *CreateBuildpack) Execute(c flags.FlagContext) error { buildpackName := c.Args()[0] buildpackFile, buildpackFileName, err := cmd.buildpackBitsRepo.CreateBuildpackZipFile(c.Args()[1]) if err != nil { cmd.ui.Warn(T("Failed to create a local temporary zip file for the buildpack")) return err } cmd.ui.Say(T("Creating buildpack {{.BuildpackName}}...", map[string]interface{}{"BuildpackName": terminal.EntityNameColor(buildpackName)})) buildpack, err := cmd.createBuildpack(buildpackName, c) if err != nil { if httpErr, ok := err.(errors.HTTPError); ok && httpErr.ErrorCode() == errors.BuildpackNameTaken { cmd.ui.Ok() cmd.ui.Warn(T("Buildpack {{.BuildpackName}} already exists", map[string]interface{}{"BuildpackName": buildpackName})) cmd.ui.Say(T("TIP: use '{{.CfUpdateBuildpackCommand}}' to update this buildpack", map[string]interface{}{"CfUpdateBuildpackCommand": terminal.CommandColor(cf.Name + " " + "update-buildpack")})) } else if httpErr, ok := err.(errors.HTTPError); ok && httpErr.ErrorCode() == errors.StackUnique { cmd.ui.Ok() cmd.ui.Warn(T("Buildpack {{.BuildpackName}} already exists without a stack", map[string]interface{}{"BuildpackName": buildpackName})) cmd.ui.Say(T("TIP: use '{{.CfDeleteBuildpackCommand}}' to delete buildpack {{.BuildpackName}} without a stack", map[string]interface{}{"CfDeleteBuildpackCommand": terminal.CommandColor(cf.Name + " " + "delete-buildpack"), "BuildpackName": buildpackName})) } else { return err } return nil } cmd.ui.Ok() cmd.ui.Say("") cmd.ui.Say(T("Uploading buildpack {{.BuildpackName}}...", map[string]interface{}{"BuildpackName": terminal.EntityNameColor(buildpackName)})) err = cmd.buildpackBitsRepo.UploadBuildpack(buildpack, buildpackFile, buildpackFileName) if err != nil { if httpErr, ok := err.(errors.HTTPError); ok && httpErr.ErrorCode() == errors.BuildpackNameStackTaken { cmd.ui.Ok() cmd.ui.Warn(httpErr.Error()) cmd.ui.Say(T("TIP: use '{{.CfUpdateBuildpackCommand}}' to update this buildpack", map[string]interface{}{"CfUpdateBuildpackCommand": terminal.CommandColor(cf.Name + " " + "update-buildpack")})) } else { return err } return nil } cmd.ui.Ok() return nil } func (cmd CreateBuildpack) createBuildpack(buildpackName string, c flags.FlagContext) (buildpack models.Buildpack, apiErr error) { position, err := strconv.Atoi(c.Args()[2]) if err != nil { apiErr = fmt.Errorf(T("Error {{.ErrorDescription}} is being passed in as the argument for 'Position' but 'Position' requires an integer. For more syntax help, see `cf create-buildpack -h`.", map[string]interface{}{"ErrorDescription": c.Args()[2]})) return } enabled := c.Bool("enable") disabled := c.Bool("disable") if enabled && disabled { apiErr = errors.New(T("Cannot specify both {{.Enabled}} and {{.Disabled}}.", map[string]interface{}{ "Enabled": "enabled", "Disabled": "disabled", })) return } var enableOption *bool if enabled { enableOption = &enabled } if disabled { disabled = false enableOption = &disabled } buildpack, apiErr = cmd.buildpackRepo.Create(buildpackName, &position, enableOption, nil) return }
odlp/antifreeze
vendor/github.com/cloudfoundry/cli/cf/commands/buildpack/create_buildpack.go
GO
mit
5,392
import * as chai from 'chai'; const expect = chai.expect; const chaiAsPromised = require('chai-as-promised'); import * as sinon from 'sinon'; import * as sinonAsPromised from 'sinon-as-promised'; import { ClickReport } from '../src/models/click_report'; chai.use(chaiAsPromised); describe('ClickReport', () => { const tableName = 'ClickReports-table'; const campaignId = 'thatCampaignId'; let tNameStub; const clickReportHashKey = 'campaignId'; const clickReportRangeKey = 'timestamp'; before(() => { sinon.stub(ClickReport, '_client').resolves(true); tNameStub = sinon.stub(ClickReport, 'tableName', { get: () => tableName}); }); describe('#get', () => { it('calls the DynamoDB get method with correct params', (done) => { ClickReport.get(campaignId, clickReportRangeKey).then(() => { const args = ClickReport._client.lastCall.args; expect(args[0]).to.equal('get'); expect(args[1]).to.have.deep.property(`Key.${clickReportHashKey}`, campaignId); expect(args[1]).to.have.deep.property(`Key.${clickReportRangeKey}`, clickReportRangeKey); expect(args[1]).to.have.property('TableName', tableName); done(); }); }); }); describe('#hashKey', () => { it('returns the hash key name', () => { expect(ClickReport.hashKey).to.equal(clickReportHashKey); }); }); describe('#rangeKey', () => { it('returns the range key name', () => { expect(ClickReport.rangeKey).to.equal(clickReportRangeKey); }); }); after(() => { ClickReport._client.restore(); tNameStub.restore(); }); });
davidgf/moonmail-models
tests/click_report.test.js
JavaScript
mit
1,612
package collectors import ( "encoding/json" "fmt" "strconv" "strings" "time" "bosun.org/metadata" "bosun.org/opentsdb" "bosun.org/slog" "bosun.org/util" ) func init() { const interval = time.Minute * 5 collectors = append(collectors, &IntervalCollector{F: c_omreport_chassis, Interval: interval}, &IntervalCollector{F: c_omreport_fans, Interval: interval}, &IntervalCollector{F: c_omreport_memory, Interval: interval}, &IntervalCollector{F: c_omreport_processors, Interval: interval}, &IntervalCollector{F: c_omreport_ps, Interval: interval}, &IntervalCollector{F: c_omreport_ps_amps_sysboard_pwr, Interval: interval}, &IntervalCollector{F: c_omreport_storage_battery, Interval: interval}, &IntervalCollector{F: c_omreport_storage_controller, Interval: interval}, &IntervalCollector{F: c_omreport_storage_enclosure, Interval: interval}, &IntervalCollector{F: c_omreport_storage_vdisk, Interval: interval}, &IntervalCollector{F: c_omreport_system, Interval: interval}, &IntervalCollector{F: c_omreport_temps, Interval: interval}, &IntervalCollector{F: c_omreport_volts, Interval: interval}, ) } func c_omreport_chassis() (opentsdb.MultiDataPoint, error) { var md opentsdb.MultiDataPoint readOmreport(func(fields []string) { if len(fields) != 2 || fields[0] == "SEVERITY" { return } component := strings.Replace(fields[1], " ", "_", -1) Add(&md, "hw.chassis", severity(fields[0]), opentsdb.TagSet{"component": component}, metadata.Gauge, metadata.Ok, descDellHWChassis) }, "chassis") return md, nil } func c_omreport_system() (opentsdb.MultiDataPoint, error) { var md opentsdb.MultiDataPoint readOmreport(func(fields []string) { if len(fields) != 2 || fields[0] == "SEVERITY" { return } component := strings.Replace(fields[1], " ", "_", -1) Add(&md, "hw.system", severity(fields[0]), opentsdb.TagSet{"component": component}, metadata.Gauge, metadata.Ok, descDellHWSystem) }, "system") return md, nil } func c_omreport_storage_enclosure() (opentsdb.MultiDataPoint, error) { var md opentsdb.MultiDataPoint readOmreport(func(fields []string) { if len(fields) < 3 || fields[0] == "ID" { return } id := strings.Replace(fields[0], ":", "_", -1) Add(&md, "hw.storage.enclosure", severity(fields[1]), opentsdb.TagSet{"id": id}, metadata.Gauge, metadata.Ok, descDellHWStorageEnc) }, "storage", "enclosure") return md, nil } func c_omreport_storage_vdisk() (opentsdb.MultiDataPoint, error) { var md opentsdb.MultiDataPoint readOmreport(func(fields []string) { if len(fields) < 3 || fields[0] == "ID" { return } id := strings.Replace(fields[0], ":", "_", -1) Add(&md, "hw.storage.vdisk", severity(fields[1]), opentsdb.TagSet{"id": id}, metadata.Gauge, metadata.Ok, descDellHWVDisk) }, "storage", "vdisk") return md, nil } func c_omreport_ps() (opentsdb.MultiDataPoint, error) { var md opentsdb.MultiDataPoint readOmreport(func(fields []string) { if len(fields) < 3 || fields[0] == "Index" { return } id := strings.Replace(fields[0], ":", "_", -1) ts := opentsdb.TagSet{"id": id} Add(&md, "hw.ps", severity(fields[1]), ts, metadata.Gauge, metadata.Ok, descDellHWPS) pm := &metadata.HWPowerSupply{} if len(fields) < 6 { return } if fields[4] != "" { pm.RatedInputWattage = fields[4] } if fields[5] != "" { pm.RatedOutputWattage = fields[5] } if j, err := json.Marshal(&pm); err == nil { metadata.AddMeta("", ts, "psMeta", string(j), true) } else { slog.Error(err) } }, "chassis", "pwrsupplies") return md, nil } func c_omreport_ps_amps_sysboard_pwr() (opentsdb.MultiDataPoint, error) { var md opentsdb.MultiDataPoint readOmreport(func(fields []string) { if len(fields) == 2 && strings.Contains(fields[0], "Current") { i_fields := strings.Split(fields[0], "Current") v_fields := strings.Fields(fields[1]) if len(i_fields) < 2 && len(v_fields) < 2 { return } id := strings.Replace(i_fields[0], " ", "", -1) Add(&md, "hw.chassis.current.reading", v_fields[0], opentsdb.TagSet{"id": id}, metadata.Gauge, metadata.A, descDellHWCurrent) } else if len(fields) == 6 && (fields[2] == "System Board Pwr Consumption" || fields[2] == "System Board System Level") { v_fields := strings.Fields(fields[3]) warn_fields := strings.Fields(fields[4]) fail_fields := strings.Fields(fields[5]) if len(v_fields) < 2 || len(warn_fields) < 2 || len(fail_fields) < 2 { return } Add(&md, "hw.chassis.power.reading", v_fields[0], nil, metadata.Gauge, metadata.Watt, descDellHWPower) Add(&md, "hw.chassis.power.warn_level", warn_fields[0], nil, metadata.Gauge, metadata.Watt, descDellHWPowerThreshold) Add(&md, "hw.chassis.power.fail_level", fail_fields[0], nil, metadata.Gauge, metadata.Watt, descDellHWPowerThreshold) } }, "chassis", "pwrmonitoring") return md, nil } func c_omreport_storage_battery() (opentsdb.MultiDataPoint, error) { var md opentsdb.MultiDataPoint readOmreport(func(fields []string) { if len(fields) < 3 || fields[0] == "ID" { return } id := strings.Replace(fields[0], ":", "_", -1) Add(&md, "hw.storage.battery", severity(fields[1]), opentsdb.TagSet{"id": id}, metadata.Gauge, metadata.Ok, descDellHWStorageBattery) }, "storage", "battery") return md, nil } func c_omreport_storage_controller() (opentsdb.MultiDataPoint, error) { var md opentsdb.MultiDataPoint readOmreport(func(fields []string) { if len(fields) < 3 || fields[0] == "ID" { return } c_omreport_storage_pdisk(fields[0], &md) id := strings.Replace(fields[0], ":", "_", -1) ts := opentsdb.TagSet{"id": id} Add(&md, "hw.storage.controller", severity(fields[1]), ts, metadata.Gauge, metadata.Ok, descDellHWStorageCtl) cm := &metadata.HWControllerMeta{} if len(fields) < 8 { return } if fields[2] != "" { cm.Name = fields[2] } if fields[3] != "" { cm.SlotId = fields[3] } if fields[4] != "" { cm.State = fields[4] } if fields[5] != "" { cm.FirmwareVersion = fields[5] } if fields[7] != "" { cm.DriverVersion = fields[7] } if j, err := json.Marshal(&cm); err == nil { metadata.AddMeta("", ts, "controllerMeta", string(j), true) } else { slog.Error(err) } }, "storage", "controller") return md, nil } // c_omreport_storage_pdisk is called from the controller func, since it needs the encapsulating id. func c_omreport_storage_pdisk(id string, md *opentsdb.MultiDataPoint) { readOmreport(func(fields []string) { if len(fields) < 3 || fields[0] == "ID" { return } //Need to find out what the various ID formats might be id := strings.Replace(fields[0], ":", "_", -1) ts := opentsdb.TagSet{"id": id} Add(md, "hw.storage.pdisk", severity(fields[1]), ts, metadata.Gauge, metadata.Ok, descDellHWPDisk) if len(fields) < 32 { return } dm := &metadata.HWDiskMeta{} if fields[2] != "" { dm.Name = fields[2] } if fields[6] != "" { dm.Media = fields[6] } if fields[19] != "" { dm.Capacity = fields[19] } if fields[23] != "" { dm.VendorId = fields[23] } if fields[24] != "" { dm.ProductId = fields[24] } if fields[25] != "" { dm.Serial = fields[25] } if fields[26] != "" { dm.Part = fields[26] } if fields[27] != "" { dm.NegotatiedSpeed = fields[27] } if fields[28] != "" { dm.CapableSpeed = fields[28] } if fields[31] != "" { dm.SectorSize = fields[31] } if j, err := json.Marshal(&dm); err == nil { metadata.AddMeta("", ts, "physicalDiskMeta", string(j), true) } else { slog.Error(err) } }, "storage", "pdisk", "controller="+id) } func c_omreport_processors() (opentsdb.MultiDataPoint, error) { var md opentsdb.MultiDataPoint readOmreport(func(fields []string) { if len(fields) != 8 { return } if _, err := strconv.Atoi(fields[0]); err != nil { return } ts := opentsdb.TagSet{"name": replace(fields[2])} Add(&md, "hw.chassis.processor", severity(fields[1]), ts, metadata.Gauge, metadata.Ok, descDellHWCPU) metadata.AddMeta("", ts, "processor", clean(fields[3], fields[4]), true) }, "chassis", "processors") return md, nil } func c_omreport_fans() (opentsdb.MultiDataPoint, error) { var md opentsdb.MultiDataPoint readOmreport(func(fields []string) { if len(fields) != 8 { return } if _, err := strconv.Atoi(fields[0]); err != nil { return } ts := opentsdb.TagSet{"name": replace(fields[2])} Add(&md, "hw.chassis.fan", severity(fields[1]), ts, metadata.Gauge, metadata.Ok, descDellHWFan) fs := strings.Fields(fields[3]) if len(fs) == 2 && fs[1] == "RPM" { i, err := strconv.Atoi(fs[0]) if err == nil { Add(&md, "hw.chassis.fan.reading", i, ts, metadata.Gauge, metadata.RPM, descDellHWFanSpeed) } } }, "chassis", "fans") return md, nil } func c_omreport_memory() (opentsdb.MultiDataPoint, error) { var md opentsdb.MultiDataPoint readOmreport(func(fields []string) { if len(fields) != 5 { return } if _, err := strconv.Atoi(fields[0]); err != nil { return } ts := opentsdb.TagSet{"name": replace(fields[2])} Add(&md, "hw.chassis.memory", severity(fields[1]), ts, metadata.Gauge, metadata.Ok, descDellHWMemory) metadata.AddMeta("", ts, "memory", clean(fields[4]), true) }, "chassis", "memory") return md, nil } func c_omreport_temps() (opentsdb.MultiDataPoint, error) { var md opentsdb.MultiDataPoint readOmreport(func(fields []string) { if len(fields) != 8 { return } if _, err := strconv.Atoi(fields[0]); err != nil { return } ts := opentsdb.TagSet{"name": replace(fields[2])} Add(&md, "hw.chassis.temps", severity(fields[1]), ts, metadata.Gauge, metadata.Ok, descDellHWTemp) fs := strings.Fields(fields[3]) if len(fs) == 2 && fs[1] == "C" { i, err := strconv.ParseFloat(fs[0], 64) if err == nil { Add(&md, "hw.chassis.temps.reading", i, ts, metadata.Gauge, metadata.C, descDellHWTempReadings) } } }, "chassis", "temps") return md, nil } func c_omreport_volts() (opentsdb.MultiDataPoint, error) { var md opentsdb.MultiDataPoint readOmreport(func(fields []string) { if len(fields) != 8 { return } if _, err := strconv.Atoi(fields[0]); err != nil { return } ts := opentsdb.TagSet{"name": replace(fields[2])} Add(&md, "hw.chassis.volts", severity(fields[1]), ts, metadata.Gauge, metadata.Ok, descDellHWVolt) if i, err := extract(fields[3], "V"); err == nil { Add(&md, "hw.chassis.volts.reading", i, ts, metadata.Gauge, metadata.V, descDellHWVoltReadings) } }, "chassis", "volts") return md, nil } // extract tries to return a parsed number from s with given suffix. A space may // be present between number ond suffix. func extract(s, suffix string) (float64, error) { if !strings.HasSuffix(s, suffix) { return 0, fmt.Errorf("extract: suffix not found") } s = s[:len(s)-len(suffix)] return strconv.ParseFloat(strings.TrimSpace(s), 64) } // severity returns 0 if s is not "Ok" or "Non-Critical", else 1. func severity(s string) int { if s != "Ok" && s != "Non-Critical" { return 1 } return 0 } func readOmreport(f func([]string), args ...string) { args = append(args, "-fmt", "ssv") _ = util.ReadCommand(func(line string) error { sp := strings.Split(line, ";") for i, s := range sp { sp[i] = clean(s) } f(sp) return nil }, "omreport", args...) } // clean concatenates arguments with a space and removes extra whitespace. func clean(ss ...string) string { v := strings.Join(ss, " ") fs := strings.Fields(v) return strings.Join(fs, " ") } func replace(name string) string { r, _ := opentsdb.Replace(name, "_") return r } const ( descDellHWChassis = "Overall status of chassis components." descDellHWSystem = "Overall status of system components." descDellHWStorageEnc = "Overall status of storage enclosures." descDellHWVDisk = "Overall status of virtual disks." descDellHWPS = "Overall status of power supplies." descDellHWCurrent = "Amps used per power supply." descDellHWPower = "System board power usage." descDellHWPowerThreshold = "The warning and failure levels set on the device for system board power usage." descDellHWStorageBattery = "Status of storage controller backup batteries." descDellHWStorageCtl = "Overall status of storage controllers." descDellHWPDisk = "Overall status of physical disks." descDellHWCPU = "Overall status of CPUs." descDellHWFan = "Overall status of system fans." descDellHWFanSpeed = "System fan speed." descDellHWMemory = "System RAM DIMM status." descDellHWTemp = "Overall status of system temperature readings." descDellHWTempReadings = "System temperature readings." descDellHWVolt = "Overall status of power supply volt readings." descDellHWVoltReadings = "Volts used per power supply." )
bosun-sharklasers/bosun
cmd/scollector/collectors/dell_hw.go
GO
mit
12,824
/*! * jQuery JavaScript Library v1.10.2 -wrap,-css,-effects,-offset,-dimensions * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-07-07T17:01Z */ (function( window, undefined ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ //"use strict"; var // The deferred used on DOM ready readyList, // A central reference to the root jQuery(document) rootjQuery, // Support: IE<10 // For `typeof xmlNode.method` instead of `xmlNode.method !== undefined` core_strundefined = typeof undefined, // Use the correct document accordingly with window argument (sandbox) location = window.location, document = window.document, docElem = document.documentElement, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // [[Class]] -> type pairs class2type = {}, // List of deleted data cache ids, so we can reuse them core_deletedIds = [], core_version = "1.10.2 -wrap,-css,-effects,-offset,-dimensions", // Save a reference to some core methods core_concat = core_deletedIds.concat, core_push = core_deletedIds.push, core_slice = core_deletedIds.slice, core_indexOf = core_deletedIds.indexOf, core_toString = class2type.toString, core_hasOwn = class2type.hasOwnProperty, core_trim = core_version.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, // Used for splitting on whitespace core_rnotwhite = /\S+/g, // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }, // The ready event handler completed = function( event ) { // readyState === "complete" is good enough for us to call the dom ready in oldIE if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { detach(); jQuery.ready(); } }, // Clean-up method for dom ready events detach = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); } else { document.detachEvent( "onreadystatechange", completed ); window.detachEvent( "onload", completed ); } }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: core_version, constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { /* jshint eqeqeq: false */ return obj != null && obj == obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { if ( obj == null ) { return String( obj ); } return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }, isPlainObject: function( obj ) { var key; // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !core_hasOwn.call(obj, "constructor") && !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Support: IE<9 // Handle iteration over inherited properties before own properties. if ( jQuery.support.ownLast ) { for ( key in obj ) { return core_hasOwn.call( obj, key ); } } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. for ( key in obj ) {} return key === undefined || core_hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }, parseJSON: function( data ) { // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } if ( data === null ) { return data; } if ( typeof data === "string" ) { // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); if ( data ) { // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } } } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && jQuery.trim( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, // Use native String.trim function wherever possible trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : core_trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { core_push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( core_indexOf ) { return core_indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return core_concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var args, proxy, tmp; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: function() { return ( new Date() ).getTime(); }, // A method for quickly swapping in/out CSS properties to get correct calculations. // Note: this method belongs to the css module but it's needed here for the support module. // If support gets modularized, this method should be moved back to the css module. swap: function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", completed ); // A fallback to window.onload, that will always work window.attachEvent( "onload", completed ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // detach all dom ready events detach(); // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || type !== "function" && ( length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj ); } // All jQuery objects should point back to these rootjQuery = jQuery(document); /*! * Sizzle CSS Selector Engine v1.10.2 * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-07-03 */ (function( window, undefined ) { var i, support, cachedruns, Expr, getText, isXML, compile, outermostContext, sortInput, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), hasDuplicate = false, sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } return 0; }, // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments quoted, // then not containing pseudos/brackets, // then attribute selectors/non-parenthetical expressions, // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rsibling = new RegExp( whitespace + "*[+~]" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : // BMP codepoint high < 0 ? String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( documentIsHTML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && context.parentNode || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key += " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = attrs.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Detect xml * @param {Element|Object} elem An element or a document */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; // Expose support vars for convenience support = Sizzle.support = {}; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsHTML = !isXML( doc ); // Support: IE>8 // If iframe document is assigned to "document" variable and if iframe has been reloaded, // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 // IE6-8 do not support the defaultView property so parent will be undefined if ( parent && parent.attachEvent && parent !== parent.top ) { parent.attachEvent( "onbeforeunload", function() { setDocument(); }); } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if getElementsByClassName can be trusted support.getElementsByClassName = assert(function( div ) { div.innerHTML = "<div class='a'></div><div class='a i'></div>"; // Support: Safari<4 // Catch class over-caching div.firstChild.className = "i"; // Support: Opera<10 // Catch gEBCN failure to find non-leading classes return div.getElementsByClassName("i").length === 2; }); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !doc.getElementsByName || !doc.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && documentIsHTML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Support: Opera 10-12/IE8 // ^= $= *= and empty values // Should not select anything // Support: Windows 8 Native Apps // The type attribute is restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "t", "" ); if ( div.querySelectorAll("[t^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = rnative.test( docElem.contains ) || docElem.compareDocumentPosition ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = docElem.compareDocumentPosition ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); if ( compare ) { // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || contains(preferredDoc, a) ) { return -1; } if ( b === doc || contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } // Not directly comparable, sort on existence of method return a.compareDocumentPosition ? -1 : 1; } : function( a, b ) { var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; // Parentless nodes are either documents or disconnected } else if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return doc; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [elem] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val === undefined ? support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null : val; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[5] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] && match[4] !== undefined ) { match[2] = match[4]; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var data, cache, outerCache, dirkey = dirruns + " " + doneName; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { if ( (data = cache[1]) === true || data === cachedruns ) { return data === true; } } else { cache = outerCache[ dir ] = [ dirkey ]; cache[1] = matcher( elem, context, xml ) || cachedruns; if ( cache[1] === true ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { // A counter to specify which element is currently being matched var matcherCachedRuns = 0, bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); if ( outermost ) { outermostContext = context !== document && context; cachedruns = matcherCachedRuns; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++matcherCachedRuns; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed ) { var i, tokens, token, type, find, match = tokenize( selector ); if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && context.parentNode || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, !documentIsHTML, results, rsibling.test( selector ) ); return results; } // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome<14 // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( document.createElement("div") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( div ) { div.innerHTML = "<input/>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( div ) { return div.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return (val = elem.getAttributeNode( name )) && val.specified ? val.value : elem[ name ] === true ? name.toLowerCase() : null; } }); } jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // First callback to fire (used internally by add and fireWith) firingStart, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( list && ( !fired || stack ) ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function( support ) { var all, a, input, select, fragment, opt, eventName, isSupported, i, div = document.createElement("div"); // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // Finish early in limited (non-browser) environments all = div.getElementsByTagName("*") || []; a = div.getElementsByTagName("a")[ 0 ]; if ( !a || !a.style || !all.length ) { return support; } // First batch of tests select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px;float:left;opacity:.5"; // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) support.getSetAttribute = div.className !== "t"; // IE strips leading whitespace when .innerHTML is used support.leadingWhitespace = div.firstChild.nodeType === 3; // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables support.tbody = !div.getElementsByTagName("tbody").length; // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE support.htmlSerialize = !!div.getElementsByTagName("link").length; // Get the style information from getAttribute // (IE uses .cssText instead) support.style = /top/.test( a.getAttribute("style") ); // Make sure that URLs aren't manipulated // (IE normalizes it by default) support.hrefNormalized = a.getAttribute("href") === "/a"; // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 support.opacity = /^0.5/.test( a.style.opacity ); // Verify style float existence // (IE uses styleFloat instead of cssFloat) support.cssFloat = !!a.style.cssFloat; // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) support.checkOn = !!input.value; // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) support.optSelected = opt.selected; // Tests for enctype support on a form (#6743) support.enctype = !!document.createElement("form").enctype; // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works support.html5Clone = document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>"; // Will be defined later support.inlineBlockNeedsLayout = false; support.shrinkWrapBlocks = false; support.pixelPosition = false; support.deleteExpando = true; support.noCloneEvent = true; support.reliableMarginRight = true; support.boxSizingReliable = true; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Support: IE<9 try { delete div.test; } catch( e ) { support.deleteExpando = false; } // Check if we can trust getAttribute("value") input = document.createElement("input"); input.setAttribute( "value", "" ); support.input = input.getAttribute( "value" ) === ""; // Check if an input maintains its value after becoming a radio input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "checked", "t" ); input.setAttribute( "name", "t" ); fragment = document.createDocumentFragment(); fragment.appendChild( input ); // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE<9 // Opera does not clone events (and typeof div.attachEvent === undefined). // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() if ( div.attachEvent ) { div.attachEvent( "onclick", function() { support.noCloneEvent = false; }); div.cloneNode( true ).click(); } // Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event) // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) for ( i in { submit: true, change: true, focusin: true }) { div.setAttribute( eventName = "on" + i, "t" ); support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false; } div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Support: IE<9 // Iteration over object's inherited properties before its own. for ( i in jQuery( support ) ) { break; } support.ownLast = i !== "0"; // Run tests that need a body at doc ready jQuery(function() { var container, marginDiv, tds, divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;", body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; body.appendChild( container ).appendChild( div ); // Support: IE8 // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; tds = div.getElementsByTagName("td"); tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Support: IE8 // Check if empty table cells still have offsetWidth/Height support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Check box-sizing and margin behavior. div.innerHTML = ""; div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; // Workaround failing boxSizing test due to offsetWidth returning wrong value // with some non-1 values of body zoom, ticket #13543 jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() { support.boxSizing = div.offsetWidth === 4; }); // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = div.appendChild( document.createElement("div") ); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } if ( typeof div.style.zoom !== core_strundefined ) { // Support: IE<8 // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout div.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Support: IE6 // Check if elements with layout shrink-wrap their children div.style.display = "block"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); if ( support.inlineBlockNeedsLayout ) { // Prevent IE 6 from affecting layout for positioned elements #11048 // Prevent IE from shrinking the body in IE 7 mode #12869 // Support: IE<8 body.style.zoom = 1; } } body.removeChild( container ); // Null elements to avoid leaks in IE container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE all = select = fragment = opt = a = input = null; return support; })({}); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; function internalData( elem, name, data, pvt /* Internal Use Only */ ){ if ( !jQuery.acceptData( elem ) ) { return; } var ret, thisCache, internalKey = jQuery.expando, // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { id = elem[ internalKey ] = core_deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { // Avoid exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify cache[ id ] = isNode ? {} : { toJSON: jQuery.noop }; } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( typeof name === "string" ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; } function internalRemoveData( elem, name, pvt ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } else { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = name.concat( jQuery.map( name, jQuery.camelCase ) ); } i = name.length; while ( i-- ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) /* jshint eqeqeq: false */ } else if ( jQuery.support.deleteExpando || cache != cache.window ) { /* jshint eqeqeq: true */ delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } } jQuery.extend({ cache: {}, // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "applet": true, "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data ) { return internalData( elem, name, data ); }, removeData: function( elem, name ) { return internalRemoveData( elem, name ); }, // For internal use only. _data: function( elem, name, data ) { return internalData( elem, name, data, true ); }, _removeData: function( elem, name ) { return internalRemoveData( elem, name, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { // Do not set data on non-element because it will not be cleared (#8335). if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) { return false; } var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; // nodes accept data unless otherwise specified; rejection can be conditional return !noData || noData !== true && elem.getAttribute("classid") === noData; } }); jQuery.fn.extend({ data: function( key, value ) { var attrs, name, data = null, i = 0, elem = this[0]; // Special expections of .data basically thwart jQuery.access, // so implement the relevant behavior ourselves // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { attrs = elem.attributes; for ( ; i < attrs.length; i++ ) { name = attrs[i].name; if ( name.indexOf("data-") === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } return arguments.length > 1 ? // Sets one value this.each(function() { jQuery.data( this, key, value ); }) : // Gets one value // Try to fetch any internally stored data first elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null; }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery._removeData( elem, type + "queue" ); jQuery._removeData( elem, key ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, rclass = /[\t\r\n\f]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button|object)$/i, rclickable = /^(?:a|area)$/i, ruseDefault = /^(?:checked|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute, getSetInput = jQuery.support.input; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } elem.className = jQuery.trim( cur ); } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } elem.className = value ? jQuery.trim( cur ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), classNames = value.match( core_rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( type === core_strundefined || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var ret, hooks, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // Use proper attribute retrieval(#6932, #12072) var val = jQuery.find.attr( elem, "value" ); return val != null ? val : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // oldIE doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) { optionSet = true; } } // force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } }, attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === core_strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( core_rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { elem[ propName ] = false; // Support: IE<9 // Also clear defaultChecked/defaultSelected (if appropriate) } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ propName ] = false; } // See #9699 for explanation of this approach (setting first, then removal) } else { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, propFix: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ // Use proper attribute retrieval(#12072) var tabindex = jQuery.find.attr( elem, "tabindex" ); return tabindex ? parseInt( tabindex, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : -1; } } } }); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { // IE<8 needs the *property* name elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); // Use defaultChecked and defaultSelected for oldIE } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr; jQuery.expr.attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ? function( elem, name, isXML ) { var fn = jQuery.expr.attrHandle[ name ], ret = isXML ? undefined : /* jshint eqeqeq: false */ (jQuery.expr.attrHandle[ name ] = undefined) != getter( elem, name, isXML ) ? name.toLowerCase() : null; jQuery.expr.attrHandle[ name ] = fn; return ret; } : function( elem, name, isXML ) { return isXML ? undefined : elem[ jQuery.camelCase( "default-" + name ) ] ? name.toLowerCase() : null; }; }); // fix oldIE attroperties if ( !getSetInput || !getSetAttribute ) { jQuery.attrHooks.value = { set: function( elem, value, name ) { if ( jQuery.nodeName( elem, "input" ) ) { // Does not return so that setAttribute is also used elem.defaultValue = value; } else { // Use nodeHook if defined (#1954); otherwise setAttribute is fine return nodeHook && nodeHook.set( elem, value, name ); } } }; } // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = { set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { elem.setAttributeNode( (ret = elem.ownerDocument.createAttribute( name )) ); } ret.value = value += ""; // Break association with cloned elements by also using setAttribute (#9646) return name === "value" || value === elem.getAttribute( name ) ? value : undefined; } }; jQuery.expr.attrHandle.id = jQuery.expr.attrHandle.name = jQuery.expr.attrHandle.coords = // Some attributes are constructed with empty-string values when not defined function( elem, name, isXML ) { var ret; return isXML ? undefined : (ret = elem.getAttributeNode( name )) && ret.value !== "" ? ret.value : null; }; jQuery.valHooks.button = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); return ret && ret.specified ? ret.value : undefined; }, set: nodeHook.set }; // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { set: function( elem, value, name ) { nodeHook.set( elem, value === "" ? false : value, name ); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }; }); } // Some attributes require a special call on IE // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !jQuery.support.hrefNormalized ) { // href/src property should get the full normalized URL (#10299/#12915) jQuery.each([ "href", "src" ], function( i, name ) { jQuery.propHooks[ name ] = { get: function( elem ) { return elem.getAttribute( name, 4 ); } }; }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Note: IE uppercases css property names, but if we were to .toLowerCase() // .cssText, that would destroy case senstitivity in URL's, like in "background" return elem.style.cssText || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = value + "" ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !jQuery.support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); var rformElems = /^(?:input|select|textarea)$/i, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var tmp, events, t, handleObjIn, special, eventHandle, handleObj, handlers, type, namespaces, origType, elemData = jQuery._data( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, handleObj, tmp, origCount, t, events, special, handlers, type, namespaces, origType, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery._removeData( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var handle, ontype, cur, bubbleType, special, tmp, i, eventPath = [ elem || document ], type = core_hasOwn.call( event, "type" ) ? event.type : event, namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; try { elem[ type ](); } catch ( e ) { // IE<9 dies on focus/blur to hidden element (#1486,#12518) // only reproducible on winXP IE8 native, not IE9 in IE8 mode } jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, ret, handleObj, matched, j, handlerQueue = [], args = core_slice.call( arguments ), handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var sel, handleObj, matches, i, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { /* jshint eqeqeq: false */ for ( ; cur != this; cur = cur.parentNode || this ) { /* jshint eqeqeq: true */ // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: IE<9 // Fix target property (#1925) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Support: Chrome 23+, Safari? // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Support: IE<9 // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) event.metaKey = !!event.metaKey; return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var body, eventDoc, doc, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { try { this.focus(); return false; } catch ( e ) { // Support: IE<9 // If we error on focus to hidden element (#1486, #12518), // let .trigger() run the handlers } } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Even when returnValue equals to undefined Firefox will still show alert if ( event.result !== undefined ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === core_strundefined ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( !e ) { return; } // If preventDefault exists, run it on the original event if ( e.preventDefault ) { e.preventDefault(); // Support: IE // Otherwise set the returnValue property of the original event to false } else { e.returnValue = false; } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( !e ) { return; } // If stopPropagation exists, run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // Support: IE // Set the cancelBubble property of the original event to true e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "submitBubbles" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "submitBubbles", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "changeBubbles", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var type, origFn; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); var isSimple = /^.[^:#\[\.,]*$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, ret = [], self = this, len = self.length; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, ret = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { cur = ret.push( cur ); break; } } } return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( jQuery.unique(all) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { ret = jQuery.unique( ret ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { ret = ret.reverse(); } } return this.pushStack( ret ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( isSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not; }); } function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, manipulation_rcheckableType = /^(?:checkbox|radio)$/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], area: [ 1, "<map>", "</map>" ], param: [ 1, "<object>", "</object>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. _default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } // If this is a select, ensure that it displays empty (#12336) // Support: IE<9 if ( elem.options && jQuery.nodeName( elem, "select" ) ) { elem.options.length = 0; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[0] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var // Snapshot the DOM in case .domManip sweeps something relevant into its fragment args = jQuery.map( this, function( elem ) { return [ elem.nextSibling, elem.parentNode ]; }), i = 0; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { var next = args[ i++ ], parent = args[ i++ ]; if ( parent ) { // Don't use the snapshot next if it has moved (#13810) if ( next && next.parentNode !== parent ) { next = this.nextSibling; } jQuery( this ).remove(); parent.insertBefore( elem, next ); } // Allow new content to include elements from the context set }, true ); // Force removal if there was no new content (e.g., from empty arguments) return i ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback, allowIntersection ) { // Flatten any nested arrays args = core_concat.apply( [], args ); var first, node, hasScripts, scripts, doc, fragment, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[0], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[0] = value.call( this, index, self.html() ); } self.domManip( args, callback, allowIntersection ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[i], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Hope ajax is available... jQuery._evalUrl( node.src ); } else { jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); // Support: IE<8 // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[1]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var elem, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function fixCloneNodeIssues( src, dest ) { var nodeName, e, data; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) { data = jQuery._data( dest ); for ( e in data.events ) { jQuery.removeEvent( dest, e, data.handle ); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute( jQuery.expando ); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if ( nodeName === "script" && dest.text !== src.text ) { disableScript( dest ).text = src.text; restoreScript( dest ); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if ( nodeName === "object" ) { if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), last = insert.length - 1; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone(true); jQuery( insert[i] )[ original ]( elems ); // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() core_push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) : undefined; if ( !found ) { for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { if ( !tag || jQuery.nodeName( elem, tag ) ) { found.push( elem ); } else { jQuery.merge( found, getAll( elem, tag ) ); } } } return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], found ) : found; } // Used in buildFragment, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( manipulation_rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains( elem.ownerDocument, elem ); if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); // Fix all IE cloning issues for ( i = 0; (node = srcElements[i]) != null; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { fixCloneNodeIssues( node, destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0; (node = srcElements[i]) != null; i++ ) { cloneCopyEvent( node, destElements[i] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } destElements = srcElements = node = null; // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var j, elem, contains, tmp, tag, tbody, wrap, l = elems.length, // Ensure a safe fragment safe = createSafeFragment( context ), nodes = [], i = 0; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || safe.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2]; // Descend through wrappers to the right content j = wrap[0]; while ( j-- ) { tmp = tmp.lastChild; } // Manually add leading whitespace removed by IE if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> elem = tag === "table" && !rtbody.test( elem ) ? tmp.firstChild : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !rtbody.test( elem ) ? tmp : 0; j = elem && elem.childNodes.length; while ( j-- ) { if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { elem.removeChild( tbody ); } } } jQuery.merge( nodes, tmp.childNodes ); // Fix #12392 for WebKit and IE > 9 tmp.textContent = ""; // Fix #12392 for oldIE while ( tmp.firstChild ) { tmp.removeChild( tmp.firstChild ); } // Remember the top-level container for proper cleanup tmp = safe.lastChild; } } } // Fix #11356: Clear elements from fragment if ( tmp ) { safe.removeChild( tmp ); } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !jQuery.support.appendChecked ) { jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); } i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( safe.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } tmp = null; return safe; }, cleanData: function( elems, /* internal */ acceptData ) { var elem, type, id, data, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = jQuery.support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( typeof elem.removeAttribute !== core_strundefined ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } core_deletedIds.push( id ); } } } } }, _evalUrl: function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function(){ var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !manipulation_rcheckableType.test( type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.extend({ hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); } }); var // Document location ajaxLocParts, ajaxLocation, ajax_nonce = jQuery.now(), ajax_rquery = /\?/, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType[0] === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var deep, key, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, response, type, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){ jQuery.fn[ type ] = function( fn ){ return this.on( type, fn ); }; }); jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Cross-domain detection vars parts, // Loop variable i, // URL without anti-cache param cacheURL, // Response headers as string responseHeadersString, // timeout handle timeoutTimer, // To know if global events are to be dispatched fireGlobals, transport, // Response headers responseHeaders, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( (match = rheaders.exec( responseHeadersString )) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !== ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) : // Otherwise add one to the end cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var firstDataType, ct, finalDataType, type, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s[ "throws" ] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || jQuery("head")[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement("script"); script.async = true; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( script.parentNode ) { script.parentNode.removeChild( script ); } // Dereference the script script = null; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending // Use native DOM manipulation to avoid our domManip AJAX trickery head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( undefined, true ); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); var xhrCallbacks, xhrSupported, xhrId = 0, // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject && function() { // Abort all pending requests var key; for ( key in xhrCallbacks ) { xhrCallbacks[ key ]( undefined, true ); } }; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties xhrSupported = jQuery.ajaxSettings.xhr(); jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); xhrSupported = jQuery.support.ajax = !!xhrSupported; // Create transport if the browser can provide an xhr if ( xhrSupported ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var handle, i, xhr = s.xhr(); // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( err ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, responseHeaders, statusText, responses; // Firefox throws exceptions when accessing properties // of an xhr when a network error occurred // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { responses = {}; status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) if ( typeof xhr.responseText === "string" ) { responses.text = xhr.responseText; } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; if ( !s.async ) { // if we're in sync mode we fire the callback callback(); } else if ( xhr.readyState === 4 ) { // (IE6 & IE7) if it's in cache and has been // retrieved directly we need to fire the callback setTimeout( callback ); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback( undefined, true ); } } }; } }); } // Limit scope pollution from any deprecated API // (function() { // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // })(); if ( typeof module === "object" && module && typeof module.exports === "object" ) { // Expose jQuery as module.exports in loaders that implement the Node // module pattern (including browserify). Do not create the global, since // the user will be storing it themselves locally, and globals are frowned // upon in the Node module world. module.exports = jQuery; } else { // Otherwise expose jQuery to the global object as usual window.jQuery = window.$ = jQuery; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd ) { define( "jquery", [], function () { return jQuery; } ); } } })( window );
michael829/jquery-builder
dist/1.10.2/jquery-css-dimensions-effects-offset-wrap.js
JavaScript
mit
226,026
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Management.Automation.Internal; using System.Management.Automation.Language; using System.Management.Automation.Runspaces; using System.Security; using Dbg = System.Management.Automation; namespace System.Management.Automation { /// <summary> /// Holds the state of a Monad Shell session. /// </summary> [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "This is a bridge class between internal classes and a public interface. It requires this much coupling.")] internal sealed partial class SessionStateInternal { #region tracer /// <summary> /// An instance of the PSTraceSource class used for trace output /// using "SessionState" as the category. /// </summary> [Dbg.TraceSourceAttribute( "SessionState", "SessionState Class")] private static readonly Dbg.PSTraceSource s_tracer = Dbg.PSTraceSource.GetTracer("SessionState", "SessionState Class"); #endregion tracer #region Constructor /// <summary> /// Constructor for session state object. /// </summary> /// <param name="context"> /// The context for the runspace to which this session state object belongs. /// </param> /// <exception cref="ArgumentNullException"> /// if <paramref name="context"/> is null. /// </exception> internal SessionStateInternal(ExecutionContext context) : this(null, false, context) { } internal SessionStateInternal(SessionStateInternal parent, bool linkToGlobal, ExecutionContext context) { if (context == null) { throw PSTraceSource.NewArgumentNullException(nameof(context)); } ExecutionContext = context; // Create the working directory stack. This // is used for the pushd and popd commands _workingLocationStack = new Dictionary<string, Stack<PathInfo>>(StringComparer.OrdinalIgnoreCase); // Conservative choice to limit the Set-Location history in order to limit memory impact in case of a regression. const int locationHistoryLimit = 20; _setLocationHistory = new HistoryStack<PathInfo>(locationHistoryLimit); GlobalScope = new SessionStateScope(null); ModuleScope = GlobalScope; _currentScope = GlobalScope; InitializeSessionStateInternalSpecialVariables(false); // Create the push the global scope on as // the starting script scope. That way, if you dot-source a script // that uses variables qualified by script: it works. GlobalScope.ScriptScope = GlobalScope; if (parent != null) { GlobalScope.Parent = parent.GlobalScope; // Copy the drives and providers from the parent... CopyProviders(parent); // During loading of core modules, providers are not populated. // We set the drive information later if (Providers != null && Providers.Count > 0) { CurrentDrive = parent.CurrentDrive; } // Link it to the global scope... if (linkToGlobal) { GlobalScope = parent.GlobalScope; } } else { _currentScope.LocalsTuple = MutableTuple.MakeTuple(Compiler.DottedLocalsTupleType, Compiler.DottedLocalsNameIndexMap); } } /// <summary> /// Add any special variables to the session state variable table. This routine /// must be called at construction time or if the variable table is reset. /// </summary> internal void InitializeSessionStateInternalSpecialVariables(bool clearVariablesTable) { if (clearVariablesTable) { // Clear the variable table GlobalScope.Variables.Clear(); // Add in the per-scope default variables. GlobalScope.AddSessionStateScopeDefaultVariables(); } // Set variable $Error PSVariable errorvariable = new PSVariable("Error", new ArrayList(), ScopedItemOptions.Constant); GlobalScope.SetVariable(errorvariable.Name, errorvariable, false, false, this, fastPath: true); // Set variable $PSDefaultParameterValues Collection<Attribute> attributes = new Collection<Attribute>(); attributes.Add(new ArgumentTypeConverterAttribute(typeof(System.Management.Automation.DefaultParameterDictionary))); PSVariable psDefaultParameterValuesVariable = new PSVariable(SpecialVariables.PSDefaultParameterValues, new DefaultParameterDictionary(), ScopedItemOptions.None, attributes, RunspaceInit.PSDefaultParameterValuesDescription); GlobalScope.SetVariable(psDefaultParameterValuesVariable.Name, psDefaultParameterValuesVariable, false, false, this, fastPath: true); } #endregion Constructor #region Private data /// <summary> /// Provides all the path manipulation and globbing for Monad paths. /// </summary> internal LocationGlobber Globber { get { return _globberPrivate ??= ExecutionContext.LocationGlobber; } } private LocationGlobber _globberPrivate; /// <summary> /// The context of the runspace to which this session state object belongs. /// </summary> internal ExecutionContext ExecutionContext { get; } /// <summary> /// Returns the public session state facade object for this session state instance. /// </summary> internal SessionState PublicSessionState { get { return _publicSessionState ??= new SessionState(this); } set { _publicSessionState = value; } } private SessionState _publicSessionState; /// <summary> /// Gets the engine APIs to access providers. /// </summary> internal ProviderIntrinsics InvokeProvider { get { return _invokeProvider ??= new ProviderIntrinsics(this); } } private ProviderIntrinsics _invokeProvider; /// <summary> /// The module info object associated with this session state. /// </summary> internal PSModuleInfo Module { get; set; } = null; // This is used to maintain the order in which modules were imported. // This is used by Get-Command -All to order by last imported internal List<string> ModuleTableKeys = new List<string>(); /// <summary> /// The private module table for this session state object... /// </summary> internal Dictionary<string, PSModuleInfo> ModuleTable { get; } = new Dictionary<string, PSModuleInfo>(StringComparer.OrdinalIgnoreCase); /// <summary> /// Get/set constraints for this execution environment. /// </summary> internal PSLanguageMode LanguageMode { get { return ExecutionContext.LanguageMode; } set { ExecutionContext.LanguageMode = value; } } /// <summary> /// If true the PowerShell debugger will use FullLanguage mode, otherwise it will use the current language mode. /// </summary> internal bool UseFullLanguageModeInDebugger { get { return ExecutionContext.UseFullLanguageModeInDebugger; } } /// <summary> /// The list of scripts that are allowed to be run. If the name "*" /// is in the list, then all scripts can be run. (This is the default.) /// </summary> public List<string> Scripts { get; } = new List<string>(new string[] { "*" }); /// <summary> /// See if a script is allowed to be run. /// </summary> /// <param name="scriptPath">Path to check.</param> /// <returns>True if script is allowed.</returns> internal SessionStateEntryVisibility CheckScriptVisibility(string scriptPath) { return checkPathVisibility(Scripts, scriptPath); } /// <summary> /// The list of applications that are allowed to be run. If the name "*" /// is in the list, then all applications can be run. (This is the default.) /// </summary> public List<string> Applications { get; } = new List<string>(new string[] { "*" }); /// <summary> /// List of functions/filters to export from this session state object... /// </summary> internal List<CmdletInfo> ExportedCmdlets { get; } = new List<CmdletInfo>(); /// <summary> /// Defines the default command visibility for this session state. Binding an InitialSessionState instance /// with private members will set this to Private. /// </summary> internal SessionStateEntryVisibility DefaultCommandVisibility = SessionStateEntryVisibility.Public; /// <summary> /// Add an new SessionState cmdlet entry to this session state object... /// </summary> /// <param name="entry">The entry to add.</param> internal void AddSessionStateEntry(SessionStateCmdletEntry entry) { AddSessionStateEntry(entry, /*local*/false); } /// <summary> /// Add an new SessionState cmdlet entry to this session state object... /// </summary> /// <param name="entry">The entry to add.</param> /// <param name="local">If local, add cmdlet to current scope. Else, add to module scope.</param> internal void AddSessionStateEntry(SessionStateCmdletEntry entry, bool local) { ExecutionContext.CommandDiscovery.AddSessionStateCmdletEntryToCache(entry, local); } /// <summary> /// Add an new SessionState cmdlet entry to this session state object... /// </summary> /// <param name="entry">The entry to add.</param> internal void AddSessionStateEntry(SessionStateApplicationEntry entry) { this.Applications.Add(entry.Path); } /// <summary> /// Add an new SessionState cmdlet entry to this session state object... /// </summary> /// <param name="entry">The entry to add.</param> internal void AddSessionStateEntry(SessionStateScriptEntry entry) { this.Scripts.Add(entry.Path); } /// <summary> /// Add the variables that must always be present in a SessionState instance... /// </summary> internal void InitializeFixedVariables() { // // BUGBUG // // String resources for aliases are currently associated with Runspace init // // $Host PSVariable v = new PSVariable( SpecialVariables.Host, ExecutionContext.EngineHostInterface, ScopedItemOptions.Constant | ScopedItemOptions.AllScope, RunspaceInit.PSHostDescription); this.GlobalScope.SetVariable(v.Name, v, asValue: false, force: true, this, CommandOrigin.Internal, fastPath: true); // $HOME - indicate where a user's home directory is located in the file system. // -- %USERPROFILE% on windows // -- %HOME% on unix string home = Environment.GetEnvironmentVariable(Platform.CommonEnvVariableNames.Home) ?? string.Empty; v = new PSVariable(SpecialVariables.Home, home, ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope, RunspaceInit.HOMEDescription); this.GlobalScope.SetVariable(v.Name, v, asValue: false, force: true, this, CommandOrigin.Internal, fastPath: true); // $ExecutionContext v = new PSVariable(SpecialVariables.ExecutionContext, ExecutionContext.EngineIntrinsics, ScopedItemOptions.Constant | ScopedItemOptions.AllScope, RunspaceInit.ExecutionContextDescription); this.GlobalScope.SetVariable(v.Name, v, asValue: false, force: true, this, CommandOrigin.Internal, fastPath: true); // $PSVersionTable v = new PSVariable(SpecialVariables.PSVersionTable, PSVersionInfo.GetPSVersionTable(), ScopedItemOptions.Constant | ScopedItemOptions.AllScope, RunspaceInit.PSVersionTableDescription); this.GlobalScope.SetVariable(v.Name, v, asValue: false, force: true, this, CommandOrigin.Internal, fastPath: true); // $PSEdition v = new PSVariable(SpecialVariables.PSEdition, PSVersionInfo.PSEditionValue, ScopedItemOptions.Constant | ScopedItemOptions.AllScope, RunspaceInit.PSEditionDescription); this.GlobalScope.SetVariable(v.Name, v, asValue: false, force: true, this, CommandOrigin.Internal, fastPath: true); // $PID Process currentProcess = Process.GetCurrentProcess(); v = new PSVariable( SpecialVariables.PID, currentProcess.Id, ScopedItemOptions.Constant | ScopedItemOptions.AllScope, RunspaceInit.PIDDescription); this.GlobalScope.SetVariable(v.Name, v, asValue: false, force: true, this, CommandOrigin.Internal, fastPath: true); // $PSCulture v = new PSCultureVariable(); this.GlobalScope.SetVariableForce(v, this); // $PSUICulture v = new PSUICultureVariable(); this.GlobalScope.SetVariableForce(v, this); // $? v = new QuestionMarkVariable(this.ExecutionContext); this.GlobalScope.SetVariableForce(v, this); // $ShellId - if there is no runspace config, use the default string string shellId = ExecutionContext.ShellID; v = new PSVariable(SpecialVariables.ShellId, shellId, ScopedItemOptions.Constant | ScopedItemOptions.AllScope, RunspaceInit.MshShellIdDescription); this.GlobalScope.SetVariable(v.Name, v, asValue: false, force: true, this, CommandOrigin.Internal, fastPath: true); // $PSHOME string applicationBase = Utils.DefaultPowerShellAppBase; v = new PSVariable(SpecialVariables.PSHome, applicationBase, ScopedItemOptions.Constant | ScopedItemOptions.AllScope, RunspaceInit.PSHOMEDescription); this.GlobalScope.SetVariable(v.Name, v, asValue: false, force: true, this, CommandOrigin.Internal, fastPath: true); // $EnabledExperimentalFeatures v = new PSVariable(SpecialVariables.EnabledExperimentalFeatures, ExperimentalFeature.EnabledExperimentalFeatureNames, ScopedItemOptions.Constant | ScopedItemOptions.AllScope, RunspaceInit.EnabledExperimentalFeatures); this.GlobalScope.SetVariable(v.Name, v, asValue: false, force: true, this, CommandOrigin.Internal, fastPath: true); } /// <summary> /// Check to see if an application is allowed to be run. /// </summary> /// <param name="applicationPath">The path to the application to check.</param> /// <returns>True if application is permitted.</returns> internal SessionStateEntryVisibility CheckApplicationVisibility(string applicationPath) { return checkPathVisibility(Applications, applicationPath); } private static SessionStateEntryVisibility checkPathVisibility(List<string> list, string path) { if (list == null || list.Count == 0) return SessionStateEntryVisibility.Private; if (string.IsNullOrEmpty(path)) return SessionStateEntryVisibility.Private; if (list.Contains("*")) return SessionStateEntryVisibility.Public; foreach (string p in list) { if (string.Equals(p, path, StringComparison.OrdinalIgnoreCase)) return SessionStateEntryVisibility.Public; if (WildcardPattern.ContainsWildcardCharacters(p)) { WildcardPattern pattern = WildcardPattern.Get(p, WildcardOptions.IgnoreCase); if (pattern.IsMatch(path)) { return SessionStateEntryVisibility.Public; } } } return SessionStateEntryVisibility.Private; } #endregion Private data /// <summary> /// Notification for SessionState to do cleanup /// before runspace is closed. /// </summary> internal void RunspaceClosingNotification() { if (this != ExecutionContext.TopLevelSessionState && Providers.Count > 0) { // Remove all providers at the top level... CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); foreach (string providerName in Providers.Keys) { // All errors are ignored. RemoveProvider(providerName, true, context); } } } #region Errors /// <summary> /// Constructs a new instance of a ProviderInvocationException /// using the specified data. /// </summary> /// <param name="resourceId"> /// The resource ID to use as the format message for the error. /// </param> /// <param name="resourceStr"> /// This is the message template string. /// </param> /// <param name="provider"> /// The provider information used when formatting the error message. /// </param> /// <param name="path"> /// The path used when formatting the error message. /// </param> /// <param name="e"> /// The exception that was thrown by the provider. This will be set as /// the ProviderInvocationException's InnerException and the message will /// be used when formatting the error message. /// </param> /// <returns> /// A new instance of a ProviderInvocationException. /// </returns> /// <exception cref="ProviderInvocationException"> /// Wraps <paramref name="e"/> in a ProviderInvocationException /// and then throws it. /// </exception> internal ProviderInvocationException NewProviderInvocationException( string resourceId, string resourceStr, ProviderInfo provider, string path, Exception e) { return NewProviderInvocationException(resourceId, resourceStr, provider, path, e, true); } /// <summary> /// Constructs a new instance of a ProviderInvocationException /// using the specified data. /// </summary> /// <param name="resourceId"> /// The resource ID to use as the format message for the error. /// </param> /// <param name="resourceStr"> /// This is the message template string. /// </param> /// <param name="provider"> /// The provider information used when formatting the error message. /// </param> /// <param name="path"> /// The path used when formatting the error message. /// </param> /// <param name="e"> /// The exception that was thrown by the provider. This will be set as /// the ProviderInvocationException's InnerException and the message will /// be used when formatting the error message. /// </param> /// <param name="useInnerExceptionErrorMessage"> /// If true, the error record from the inner exception will be used if it contains one. /// If false, the error message specified by the resourceId will be used. /// </param> /// <returns> /// A new instance of a ProviderInvocationException. /// </returns> /// <exception cref="ProviderInvocationException"> /// Wraps <paramref name="e"/> in a ProviderInvocationException /// and then throws it. /// </exception> internal ProviderInvocationException NewProviderInvocationException( string resourceId, string resourceStr, ProviderInfo provider, string path, Exception e, bool useInnerExceptionErrorMessage) { // If the innerException was itself thrown by // ProviderBase.ThrowTerminatingError, it is already a // ProviderInvocationException, and we don't want to // re-wrap it. ProviderInvocationException pie = e as ProviderInvocationException; if (pie != null) { pie._providerInfo = provider; return pie; } pie = new ProviderInvocationException(resourceId, resourceStr, provider, path, e, useInnerExceptionErrorMessage); // Log a provider health event MshLog.LogProviderHealthEvent( ExecutionContext, provider.Name, pie, Severity.Warning); return pie; } #endregion Errors } }
JamesWTruher/PowerShell-1
src/System.Management.Automation/engine/SessionState.cs
C#
mit
22,530
/* * starter_imagelist.cpp * * Created on: Nov 23, 2010 * Author: Ethan Rublee * * A starter sample for using opencv, load up an imagelist * that was generated with imagelist_creator.cpp * easy as CV_PI right? */ #include "opencv2/imgcodecs.hpp" #include "opencv2/highgui.hpp" #include <iostream> #include <vector> using namespace cv; using namespace std; //hide the local functions in an unnamed namespace namespace { void help(char** av) { cout << "\nThis program gets you started being able to read images from a list in a file\n" "Usage:\n./" << av[0] << " image_list.yaml\n" << "\tThis is a starter sample, to get you up and going in a copy pasta fashion.\n" << "\tThe program reads in an list of images from a yaml or xml file and displays\n" << "one at a time\n" << "\tTry running imagelist_creator to generate a list of images.\n" "Using OpenCV version %s\n" << CV_VERSION << "\n" << endl; } bool readStringList(const string& filename, vector<string>& l) { l.resize(0); FileStorage fs(filename, FileStorage::READ); if (!fs.isOpened()) return false; FileNode n = fs.getFirstTopLevelNode(); if (n.type() != FileNode::SEQ) return false; FileNodeIterator it = n.begin(), it_end = n.end(); for (; it != it_end; ++it) l.push_back((string)*it); return true; } int process(vector<string> images) { namedWindow("image", WINDOW_KEEPRATIO); //resizable window; for (size_t i = 0; i < images.size(); i++) { Mat image = imread(images[i], IMREAD_GRAYSCALE); // do grayscale processing? imshow("image",image); cout << "Press a key to see the next image in the list." << endl; waitKey(); // wait indefinitely for a key to be pressed } return 0; } } int main(int ac, char** av) { cv::CommandLineParser parser(ac, av, "{help h||}{@input||}"); if (parser.has("help")) { help(av); return 0; } std::string arg = parser.get<std::string>("@input"); if (arg.empty()) { help(av); return 1; } vector<string> imagelist; if (!readStringList(arg,imagelist)) { cerr << "Failed to read image list\n" << endl; help(av); return 1; } return process(imagelist); }
zzjkf2009/Midterm_Astar
opencv/samples/cpp/starter_imagelist.cpp
C++
mit
2,246
<?php /** * Check for duplicate class definitions that can be merged into one. * * @author Greg Sherwood <gsherwood@squiz.net> * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence */ namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS; use PHP_CodeSniffer\Sniffs\Sniff; use PHP_CodeSniffer\Files\File; use PHP_CodeSniffer\Util\Tokens; class DuplicateClassDefinitionSniff implements Sniff { /** * A list of tokenizers this sniff supports. * * @var array */ public $supportedTokenizers = array('CSS'); /** * Returns the token types that this sniff is interested in. * * @return int[] */ public function register() { return array(T_OPEN_TAG); }//end register() /** * Processes the tokens that this sniff is interested in. * * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where the token was found. * @param int $stackPtr The position in the stack where * the token was found. * * @return void */ public function process(File $phpcsFile, $stackPtr) { $tokens = $phpcsFile->getTokens(); // Find the content of each class definition name. $classNames = array(); $next = $phpcsFile->findNext(T_OPEN_CURLY_BRACKET, ($stackPtr + 1)); if ($next === false) { // No class definitions in the file. return; } // Save the class names in a "scope", // to prevent false positives with @media blocks. $scope = 'main'; $find = array( T_CLOSE_CURLY_BRACKET, T_OPEN_CURLY_BRACKET, T_COMMENT, T_OPEN_TAG, ); while ($next !== false) { $prev = $phpcsFile->findPrevious($find, ($next - 1)); // Check if an inner block was closed. $beforePrev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($prev - 1), null, true); if ($beforePrev !== false && $tokens[$beforePrev]['code'] === T_CLOSE_CURLY_BRACKET ) { $scope = 'main'; } // Create a sorted name for the class so we can compare classes // even when the individual names are all over the place. $name = ''; for ($i = ($prev + 1); $i < $next; $i++) { $name .= $tokens[$i]['content']; } $name = trim($name); $name = str_replace("\n", ' ', $name); $name = preg_replace('|[\s]+|', ' ', $name); $name = str_replace(', ', ',', $name); $names = explode(',', $name); sort($names); $name = implode(',', $names); if ($name{0} === '@') { // Media block has its own "scope". $scope = $name; } else if (isset($classNames[$scope][$name]) === true) { $first = $classNames[$scope][$name]; $error = 'Duplicate class definition found; first defined on line %s'; $data = array($tokens[$first]['line']); $phpcsFile->addError($error, $next, 'Found', $data); } else { $classNames[$scope][$name] = $next; } $next = $phpcsFile->findNext(T_OPEN_CURLY_BRACKET, ($next + 1)); }//end while }//end process() }//end class
LCabreroG/opensource
vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/DuplicateClassDefinitionSniff.php
PHP
mit
3,605
import { Plugin } from '@ckeditor/ckeditor5-core'; import { DocumentSelection } from '@ckeditor/ckeditor5-engine'; import Selection from '@ckeditor/ckeditor5-engine/src/view/selection'; import EngineView from '@ckeditor/ckeditor5-engine/src/view/view'; import ContextualBalloon from '@ckeditor/ckeditor5-ui/src/panel/balloon/contextualballoon'; import View from '@ckeditor/ckeditor5-ui/src/view'; export default class WidgetToolbarRepository extends Plugin { static readonly requires: [typeof ContextualBalloon]; static readonly pluginName: 'WidgetToolbarRepository'; init(): void; destroy(): void; register( toolbarId: string, options?: { ariaLabel?: string | undefined; items: string[]; getRelatedElement: (el: Selection | DocumentSelection) => EngineView; balloonClassName?: string | undefined; }, ): void; } export interface WidgetRepositoryToolbarDefinition { balloonClassName: string; getRelatedElement: (el: Selection | DocumentSelection) => EngineView; view: View; }
markogresak/DefinitelyTyped
types/ckeditor__ckeditor5-widget/v27/src/widgettoolbarrepository.d.ts
TypeScript
mit
1,085
'''Trains two recurrent neural networks based upon a story and a question. The resulting merged vector is then queried to answer a range of bAbI tasks. The results are comparable to those for an LSTM model provided in Weston et al.: "Towards AI-Complete Question Answering: A Set of Prerequisite Toy Tasks" http://arxiv.org/abs/1502.05698 Task Number | FB LSTM Baseline | Keras QA --- | --- | --- QA1 - Single Supporting Fact | 50 | 100.0 QA2 - Two Supporting Facts | 20 | 50.0 QA3 - Three Supporting Facts | 20 | 20.5 QA4 - Two Arg. Relations | 61 | 62.9 QA5 - Three Arg. Relations | 70 | 61.9 QA6 - Yes/No Questions | 48 | 50.7 QA7 - Counting | 49 | 78.9 QA8 - Lists/Sets | 45 | 77.2 QA9 - Simple Negation | 64 | 64.0 QA10 - Indefinite Knowledge | 44 | 47.7 QA11 - Basic Coreference | 72 | 74.9 QA12 - Conjunction | 74 | 76.4 QA13 - Compound Coreference | 94 | 94.4 QA14 - Time Reasoning | 27 | 34.8 QA15 - Basic Deduction | 21 | 32.4 QA16 - Basic Induction | 23 | 50.6 QA17 - Positional Reasoning | 51 | 49.1 QA18 - Size Reasoning | 52 | 90.8 QA19 - Path Finding | 8 | 9.0 QA20 - Agent's Motivations | 91 | 90.7 For the resources related to the bAbI project, refer to: https://research.facebook.com/researchers/1543934539189348 Notes: - With default word, sentence, and query vector sizes, the GRU model achieves: - 100% test accuracy on QA1 in 20 epochs (2 seconds per epoch on CPU) - 50% test accuracy on QA2 in 20 epochs (16 seconds per epoch on CPU) In comparison, the Facebook paper achieves 50% and 20% for the LSTM baseline. - The task does not traditionally parse the question separately. This likely improves accuracy and is a good example of merging two RNNs. - The word vector embeddings are not shared between the story and question RNNs. - See how the accuracy changes given 10,000 training samples (en-10k) instead of only 1000. 1000 was used in order to be comparable to the original paper. - Experiment with GRU, LSTM, and JZS1-3 as they give subtly different results. - The length and noise (i.e. 'useless' story components) impact the ability for LSTMs / GRUs to provide the correct answer. Given only the supporting facts, these RNNs can achieve 100% accuracy on many tasks. Memory networks and neural networks that use attentional processes can efficiently search through this noise to find the relevant statements, improving performance substantially. This becomes especially obvious on QA2 and QA3, both far longer than QA1. ''' from __future__ import print_function from functools import reduce import re import tarfile import numpy as np np.random.seed(1337) # for reproducibility from keras.utils.data_utils import get_file from keras.layers.embeddings import Embedding from keras.layers import Dense, Merge, Dropout, RepeatVector from keras.layers import recurrent from keras.models import Sequential from keras.preprocessing.sequence import pad_sequences def tokenize(sent): '''Return the tokens of a sentence including punctuation. >>> tokenize('Bob dropped the apple. Where is the apple?') ['Bob', 'dropped', 'the', 'apple', '.', 'Where', 'is', 'the', 'apple', '?'] ''' return [x.strip() for x in re.split('(\W+)?', sent) if x.strip()] def parse_stories(lines, only_supporting=False): '''Parse stories provided in the bAbi tasks format If only_supporting is true, only the sentences that support the answer are kept. ''' data = [] story = [] for line in lines: line = line.decode('utf-8').strip() nid, line = line.split(' ', 1) nid = int(nid) if nid == 1: story = [] if '\t' in line: q, a, supporting = line.split('\t') q = tokenize(q) substory = None if only_supporting: # Only select the related substory supporting = map(int, supporting.split()) substory = [story[i - 1] for i in supporting] else: # Provide all the substories substory = [x for x in story if x] data.append((substory, q, a)) story.append('') else: sent = tokenize(line) story.append(sent) return data def get_stories(f, only_supporting=False, max_length=None): '''Given a file name, read the file, retrieve the stories, and then convert the sentences into a single story. If max_length is supplied, any stories longer than max_length tokens will be discarded. ''' data = parse_stories(f.readlines(), only_supporting=only_supporting) flatten = lambda data: reduce(lambda x, y: x + y, data) data = [(flatten(story), q, answer) for story, q, answer in data if not max_length or len(flatten(story)) < max_length] return data def vectorize_stories(data, word_idx, story_maxlen, query_maxlen): X = [] Xq = [] Y = [] for story, query, answer in data: x = [word_idx[w] for w in story] xq = [word_idx[w] for w in query] y = np.zeros(len(word_idx) + 1) # let's not forget that index 0 is reserved y[word_idx[answer]] = 1 X.append(x) Xq.append(xq) Y.append(y) return pad_sequences(X, maxlen=story_maxlen), pad_sequences(Xq, maxlen=query_maxlen), np.array(Y) RNN = recurrent.LSTM EMBED_HIDDEN_SIZE = 50 SENT_HIDDEN_SIZE = 100 QUERY_HIDDEN_SIZE = 100 BATCH_SIZE = 32 EPOCHS = 40 print('RNN / Embed / Sent / Query = {}, {}, {}, {}'.format(RNN, EMBED_HIDDEN_SIZE, SENT_HIDDEN_SIZE, QUERY_HIDDEN_SIZE)) try: path = get_file('babi-tasks-v1-2.tar.gz', origin='http://www.thespermwhale.com/jaseweston/babi/tasks_1-20_v1-2.tar.gz') except: print('Error downloading dataset, please download it manually:\n' '$ wget http://www.thespermwhale.com/jaseweston/babi/tasks_1-20_v1-2.tar.gz\n' '$ mv tasks_1-20_v1-2.tar.gz ~/.keras/datasets/babi-tasks-v1-2.tar.gz') raise tar = tarfile.open(path) # Default QA1 with 1000 samples # challenge = 'tasks_1-20_v1-2/en/qa1_single-supporting-fact_{}.txt' # QA1 with 10,000 samples # challenge = 'tasks_1-20_v1-2/en-10k/qa1_single-supporting-fact_{}.txt' # QA2 with 1000 samples challenge = 'tasks_1-20_v1-2/en/qa2_two-supporting-facts_{}.txt' # QA2 with 10,000 samples # challenge = 'tasks_1-20_v1-2/en-10k/qa2_two-supporting-facts_{}.txt' train = get_stories(tar.extractfile(challenge.format('train'))) test = get_stories(tar.extractfile(challenge.format('test'))) vocab = sorted(reduce(lambda x, y: x | y, (set(story + q + [answer]) for story, q, answer in train + test))) # Reserve 0 for masking via pad_sequences vocab_size = len(vocab) + 1 word_idx = dict((c, i + 1) for i, c in enumerate(vocab)) story_maxlen = max(map(len, (x for x, _, _ in train + test))) query_maxlen = max(map(len, (x for _, x, _ in train + test))) X, Xq, Y = vectorize_stories(train, word_idx, story_maxlen, query_maxlen) tX, tXq, tY = vectorize_stories(test, word_idx, story_maxlen, query_maxlen) print('vocab = {}'.format(vocab)) print('X.shape = {}'.format(X.shape)) print('Xq.shape = {}'.format(Xq.shape)) print('Y.shape = {}'.format(Y.shape)) print('story_maxlen, query_maxlen = {}, {}'.format(story_maxlen, query_maxlen)) print('Build model...') sentrnn = Sequential() sentrnn.add(Embedding(vocab_size, EMBED_HIDDEN_SIZE, input_length=story_maxlen)) sentrnn.add(Dropout(0.3)) qrnn = Sequential() qrnn.add(Embedding(vocab_size, EMBED_HIDDEN_SIZE, input_length=query_maxlen)) qrnn.add(Dropout(0.3)) qrnn.add(RNN(EMBED_HIDDEN_SIZE, return_sequences=False)) qrnn.add(RepeatVector(story_maxlen)) model = Sequential() model.add(Merge([sentrnn, qrnn], mode='sum')) model.add(RNN(EMBED_HIDDEN_SIZE, return_sequences=False)) model.add(Dropout(0.3)) model.add(Dense(vocab_size, activation='softmax')) model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) print('Training') model.fit([X, Xq], Y, batch_size=BATCH_SIZE, nb_epoch=EPOCHS, validation_split=0.05) loss, acc = model.evaluate([tX, tXq], tY, batch_size=BATCH_SIZE) print('Test loss / test accuracy = {:.4f} / {:.4f}'.format(loss, acc))
kemaswill/keras
examples/babi_rnn.py
Python
mit
8,596
'use strict'; // // Data-forge enumerator for iterating a standard JavaScript array. // var TakeIterator = function (iterator, takeAmount) { var self = this; self._iterator = iterator; self._takeAmount = takeAmount; }; module.exports = TakeIterator; TakeIterator.prototype.moveNext = function () { var self = this; if (--self._takeAmount >= 0) { return self._iterator.moveNext(); } return false; }; TakeIterator.prototype.getCurrent = function () { var self = this; return self._iterator.getCurrent(); };
data-forge/data-forge-js
src/iterators/take.js
JavaScript
mit
524
version_info = (1, 9, 'dev0') __version__ = '.'.join(map(str, version_info))
fevangelista/pyWicked
external/pybind11/pybind11/_version.py
Python
mit
77
define([], function() { /** * A specialized version of `_.map` for arrays without support for callback * shorthands or `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } return arrayMap; });
tomek-f/shittets
require-js-amd/require-zepto-lodash/static/js/lib/lodash-amd/internal/arrayMap.js
JavaScript
mit
609
<?php /** * CPAC_Column_User_Post_Count * * @since 2.0.0 */ class CPAC_Column_User_Post_Count extends CPAC_Column { function __construct( $storage_model ) { // define properties $this->properties['type'] = 'column-user_postcount'; $this->properties['label'] = __( 'Post Count', 'cpac' ); $this->properties['is_cloneable'] = true; // define additional options $this->options['post_type'] = ''; parent::__construct( $storage_model ); } /** * Get count * * @since 2.0.0 */ public function get_count( $user_id ) { if( ! $user_id ) return false; global $wpdb; $sql = " SELECT COUNT(ID) FROM {$wpdb->posts} WHERE post_status = 'publish' AND post_author = %d AND post_type = %s "; return $wpdb->get_var( $wpdb->prepare( $sql, $user_id, $this->options->post_type ) ); } /** * @see CPAC_Column::get_value() * @since 2.0.0 */ function get_value( $user_id ) { $value = '0'; $count = $this->get_raw_value( $user_id ); if ( $count > 0 ) $value = "<a href='edit.php?post_type={$this->options->post_type}&author={$user_id}'>{$count}</a>"; return $value; } /** * @see CPAC_Column::get_raw_value() * @since 2.0.3 */ function get_raw_value( $user_id ) { return $this->get_count( $user_id ); } /** * Display Settings * * @see CPAC_Column::display_settings() * @since 2.0.0 */ function display_settings() { $ptypes = array(); if ( post_type_exists( 'post' ) ) $ptypes['post'] = 'post'; if ( post_type_exists( 'page' ) ) $ptypes['page'] = 'page'; $ptypes = array_merge( $ptypes, get_post_types( array( '_builtin' => false ))); // get posttypes and name $post_types = array(); foreach ( $ptypes as $type ) { $obj = get_post_type_object( $type ); $post_types[ $type ] = $obj->labels->name; } ?> <tr class="<?php $this->properties->type; ?>"> <?php $this->label_view( __( 'Post Type', 'cpac' ), '', 'post_type' ); ?> <td class="input"> <select name="<?php $this->attr_name( 'post_type' ); ?>" id="<?php $this->attr_id( 'post_type' ); ?>"> <?php foreach ( $post_types as $key => $label ) : ?> <option value="<?php echo $key; ?>"<?php selected( $key, $this->options->post_type ) ?>><?php echo $label; ?></option> <?php endforeach; ?> </select> </td> </tr> <?php } }
jake-cooper/wpdfhfh
wp-content/plugins/codepress-admin-columns/classes/column/user/post-count.php
PHP
mit
2,452
# encoding: utf-8 require "mongoid/relations/marshalable" module Mongoid module Relations # This class is the superclass for all relation proxy objects, and contains # common behaviour for all of them. class Proxy alias :extend_proxy :extend # We undefine most methods to get them sent through to the target. instance_methods.each do |method| undef_method(method) unless method =~ /(^__|^send|^object_id|^respond_to|^tap|extend_proxy|extend_proxies)/ end include Threaded::Lifecycle include Marshalable attr_accessor :base, :loaded, :metadata, :target # Backwards compatibility with Mongoid beta releases. delegate :foreign_key, :inverse_foreign_key, to: :metadata delegate :bind_one, :unbind_one, to: :binding delegate :collection_name, to: :base # Convenience for setting the target and the metadata properties since # all proxies will need to do this. # # @example Initialize the proxy. # proxy.init(person, name, metadata) # # @param [ Document ] base The base document on the proxy. # @param [ Document, Array<Document> ] target The target of the proxy. # @param [ Metadata ] metadata The relation's metadata. # # @since 2.0.0.rc.1 def init(base, target, metadata) @base, @target, @metadata = base, target, metadata yield(self) if block_given? extend_proxies(metadata.extension) if metadata.extension? end # Allow extension to be an array and extend each module def extend_proxies(*extension) extension.flatten.each {|ext| extend_proxy(ext) } end # Get the class from the metadata, or return nil if no metadata present. # # @example Get the class. # proxy.klass # # @return [ Class ] The relation class. # # @since 3.0.15 def klass metadata ? metadata.klass : nil end # Resets the criteria inside the relation proxy. Used by many to many # relations to keep the underlying ids array in sync. # # @example Reset the relation criteria. # person.preferences.reset_relation_criteria # # @since 3.0.14 def reset_unloaded target.reset_unloaded(criteria) end # The default substitutable object for a relation proxy is the clone of # the target. # # @example Get the substitutable. # proxy.substitutable # # @return [ Object ] A clone of the target. # # @since 2.1.6 def substitutable target end # Tell the next persistance operation to store in a specific collection, # database or session. # # @example Save the current document to a different collection. # model.with(collection: "secondary").save # # @example Save the current document to a different database. # model.with(database: "secondary").save # # @example Save the current document to a different session. # model.with(session: "replica_set").save # # @example Save with a combination of options. # model.with(session: "sharded", database: "secondary").save # # @param [ Hash ] options The storage options. # # @option options [ String, Symbol ] :collection The collection name. # @option options [ String, Symbol ] :database The database name. # @option options [ String, Symbol ] :session The session name. # # @return [ Document ] The current document. # # @since 3.0.0 def with(options) Threaded.set_persistence_options(klass, options) self end protected # Get the collection from the root of the hierarchy. # # @example Get the collection. # relation.collection # # @return [ Collection ] The root's collection. # # @since 2.0.0 def collection root = base._root root.collection unless root.embedded? end # Takes the supplied document and sets the metadata on it. # # @example Set the metadata. # proxt.characterize_one(name) # # @param [ Document ] document The document to set on. # # @since 2.0.0.rc.4 def characterize_one(document) document.metadata = metadata unless document.metadata end # Default behavior of method missing should be to delegate all calls # to the target of the proxy. This can be overridden in special cases. # # @param [ String, Symbol ] name The name of the method. # @param [ Array ] *args The arguments passed to the method. def method_missing(name, *args, &block) target.send(name, *args, &block) end # When the base document illegally references an embedded document this # error will get raised. # # @example Raise the error. # relation.raise_mixed # # @raise [ Errors::MixedRelations ] The error. # # @since 2.0.0 def raise_mixed raise Errors::MixedRelations.new(base.class, metadata.klass) end # When the base is not yet saved and the user calls create or create! # on the relation, this error will get raised. # # @example Raise the error. # relation.raise_unsaved(post) # # @param [ Document ] doc The child document getting created. # # @raise [ Errors::UnsavedDocument ] The error. # # @since 2.0.0.rc.6 def raise_unsaved(doc) raise Errors::UnsavedDocument.new(base, doc) end # Return the name of defined callback method # # @example returns the before_add callback method name # callback_method(:before_add) # # @param [ Symbol ] which callback # # @return [ Array ] with callback methods to be executed, the array may have symbols and Procs # # @since 3.1.0 def callback_method(callback_name) methods = [] if metadata[callback_name] if metadata[callback_name].is_a? Array methods.concat(metadata[callback_name]) else methods << metadata[callback_name] end end methods end # Executes a callback method # # @example execute the before add callback # execute_callback(:before_add) # # @param [ Symbol ] callback to be executed # # @since 3.1.0 def execute_callback(callback, doc) callback_method = callback_method(callback) if callback_method callback_method.each do |c| if c.is_a? Proc c.call(base, doc) else base.send c, doc end end end end class << self # Apply ordering to the criteria if it was defined on the relation. # # @example Apply the ordering. # Proxy.apply_ordering(criteria, metadata) # # @param [ Criteria ] criteria The criteria to modify. # @param [ Metadata ] metadata The relation metadata. # # @return [ Criteria ] The ordered criteria. # # @since 3.0.6 def apply_ordering(criteria, metadata) metadata.order ? criteria.order_by(metadata.order) : criteria end # Get the criteria that is used to eager load a relation of this # type. # # @example Get the eager load criteria. # Proxy.eager_load(metadata, criteria) # # @param [ Metadata ] metadata The relation metadata. # @param [ Array<Object> ] ids The ids of the base docs. # # @return [ Criteria ] The criteria to eager load the relation. # # @since 2.2.0 def eager_load_ids(metadata, ids) klass, foreign_key = metadata.klass, metadata.foreign_key eager_loaded = klass.any_in(foreign_key => ids).entries ids.each do |id| IdentityMap.clear_many(klass, metadata.type_relation.merge!(foreign_key => id)) end eager_loaded.each do |doc| base_id = doc.__send__(foreign_key) yield(doc, metadata.type_relation.merge!(foreign_key => base_id)) end end end end end end
niedhui/mongoid
lib/mongoid/relations/proxy.rb
Ruby
mit
8,418
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using Azure.Identity; using NUnit.Framework; using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using Azure.Security.KeyVault.Tests; namespace Azure.Security.KeyVault.Secrets.Samples { /// <summary> /// Sample demonstrates how to list secrets and versions of a given secret, /// and list deleted secrets in a soft delete-enabled key vault /// using the synchronous methods of the SecretClient. /// </summary> public partial class GetSecrets { [Test] public void GetSecretsSync() { // Environment variable with the Key Vault endpoint. string keyVaultUrl = TestEnvironment.KeyVaultUrl; #region Snippet:SecretsSample3SecretClient var client = new SecretClient(new Uri(keyVaultUrl), new DefaultAzureCredential()); #endregion #region Snippet:SecretsSample3CreateSecret string bankSecretName = $"BankAccountPassword-{Guid.NewGuid()}"; string storageSecretName = $"StorageAccountPassword{Guid.NewGuid()}"; var bankSecret = new KeyVaultSecret(bankSecretName, "f4G34fMh8v"); bankSecret.Properties.ExpiresOn = DateTimeOffset.Now.AddYears(1); var storageSecret = new KeyVaultSecret(storageSecretName, "f4G34fMh8v547"); storageSecret.Properties.ExpiresOn = DateTimeOffset.Now.AddYears(1); client.SetSecret(bankSecret); client.SetSecret(storageSecret); #endregion #region Snippet:SecretsSample3ListSecrets Dictionary<string, string> secretValues = new Dictionary<string, string>(); IEnumerable<SecretProperties> secrets = client.GetPropertiesOfSecrets(); foreach (SecretProperties secret in secrets) { #if !SNIPPET if (secret.Managed) continue; #endif // Getting a disabled secret will fail, so skip disabled secrets. if (!secret.Enabled.GetValueOrDefault()) { continue; } KeyVaultSecret secretWithValue = client.GetSecret(secret.Name); if (secretValues.ContainsKey(secretWithValue.Value)) { Debug.WriteLine($"Secret {secretWithValue.Name} shares a value with secret {secretValues[secretWithValue.Value]}"); } else { secretValues.Add(secretWithValue.Value, secretWithValue.Name); } } #endregion #region Snippet:SecretsSample3ListSecretVersions string newBankSecretPassword = "sskdjfsdasdjsd"; IEnumerable<SecretProperties> secretVersions = client.GetPropertiesOfSecretVersions(bankSecretName); foreach (SecretProperties secret in secretVersions) { // Secret versions may also be disabled if compromised and new versions generated, so skip disabled versions, too. if (!secret.Enabled.GetValueOrDefault()) { continue; } KeyVaultSecret oldBankSecret = client.GetSecret(secret.Name, secret.Version); if (newBankSecretPassword == oldBankSecret.Value) { Debug.WriteLine($"Secret {secret.Name} reuses a password"); } } client.SetSecret(bankSecretName, newBankSecretPassword); #endregion #region Snippet:SecretsSample3DeleteSecrets DeleteSecretOperation bankSecretOperation = client.StartDeleteSecret(bankSecretName); DeleteSecretOperation storageSecretOperation = client.StartDeleteSecret(storageSecretName); // You only need to wait for completion if you want to purge or recover the secret. while (!bankSecretOperation.HasCompleted || !storageSecretOperation.HasCompleted) { Thread.Sleep(2000); bankSecretOperation.UpdateStatus(); storageSecretOperation.UpdateStatus(); } #endregion #region Snippet:SecretsSample3ListDeletedSecrets IEnumerable<DeletedSecret> secretsDeleted = client.GetDeletedSecrets(); foreach (DeletedSecret secret in secretsDeleted) { Debug.WriteLine($"Deleted secret's recovery Id {secret.RecoveryId}"); } #endregion // If the Key Vault is soft delete-enabled, then for permanent deletion, deleted secret needs to be purged. client.PurgeDeletedSecret(bankSecretName); client.PurgeDeletedSecret(storageSecretName); } } }
ayeletshpigelman/azure-sdk-for-net
sdk/keyvault/Azure.Security.KeyVault.Secrets/tests/samples/Sample3_GetSecrets.cs
C#
mit
4,900
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* SHA-1 implementation in JavaScript (c) Chris Veness 2002-2014 / MIT Licence */ /* */ /* - see http://csrc.nist.gov/groups/ST/toolkit/secure_hashing.html */ /* http://csrc.nist.gov/groups/ST/toolkit/examples.html */ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* jshint node:true *//* global define, escape, unescape */ 'use strict'; /** * SHA-1 hash function reference implementation. * * @namespace */ var Sha1 = {}; /** * Generates SHA-1 hash of string. * * @param {string} msg - (Unicode) string to be hashed. * @returns {string} Hash of msg as hex character string. */ Sha1.hash = function(msg) { // convert string to UTF-8, as SHA only deals with byte-streams msg = msg.utf8Encode(); // constants [§4.2.1] var K = [ 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6 ]; // PREPROCESSING msg += String.fromCharCode(0x80); // add trailing '1' bit (+ 0's padding) to string [§5.1.1] // convert string msg into 512-bit/16-integer blocks arrays of ints [§5.2.1] var l = msg.length/4 + 2; // length (in 32-bit integers) of msg + ‘1’ + appended length var N = Math.ceil(l/16); // number of 16-integer-blocks required to hold 'l' ints var M = new Array(N); for (var i=0; i<N; i++) { M[i] = new Array(16); for (var j=0; j<16; j++) { // encode 4 chars per integer, big-endian encoding M[i][j] = (msg.charCodeAt(i*64+j*4)<<24) | (msg.charCodeAt(i*64+j*4+1)<<16) | (msg.charCodeAt(i*64+j*4+2)<<8) | (msg.charCodeAt(i*64+j*4+3)); } // note running off the end of msg is ok 'cos bitwise ops on NaN return 0 } // add length (in bits) into final pair of 32-bit integers (big-endian) [§5.1.1] // note: most significant word would be (len-1)*8 >>> 32, but since JS converts // bitwise-op args to 32 bits, we need to simulate this by arithmetic operators M[N-1][14] = ((msg.length-1)*8) / Math.pow(2, 32); M[N-1][14] = Math.floor(M[N-1][14]); M[N-1][15] = ((msg.length-1)*8) & 0xffffffff; // set initial hash value [§5.3.1] var H0 = 0x67452301; var H1 = 0xefcdab89; var H2 = 0x98badcfe; var H3 = 0x10325476; var H4 = 0xc3d2e1f0; // HASH COMPUTATION [§6.1.2] var W = new Array(80); var a, b, c, d, e; for (var i=0; i<N; i++) { // 1 - prepare message schedule 'W' for (var t=0; t<16; t++) W[t] = M[i][t]; for (var t=16; t<80; t++) W[t] = Sha1.ROTL(W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16], 1); // 2 - initialise five working variables a, b, c, d, e with previous hash value a = H0; b = H1; c = H2; d = H3; e = H4; // 3 - main loop for (var t=0; t<80; t++) { var s = Math.floor(t/20); // seq for blocks of 'f' functions and 'K' constants var T = (Sha1.ROTL(a,5) + Sha1.f(s,b,c,d) + e + K[s] + W[t]) & 0xffffffff; e = d; d = c; c = Sha1.ROTL(b, 30); b = a; a = T; } // 4 - compute the new intermediate hash value (note 'addition modulo 2^32') H0 = (H0+a) & 0xffffffff; H1 = (H1+b) & 0xffffffff; H2 = (H2+c) & 0xffffffff; H3 = (H3+d) & 0xffffffff; H4 = (H4+e) & 0xffffffff; } return Sha1.toHexStr(H0) + Sha1.toHexStr(H1) + Sha1.toHexStr(H2) + Sha1.toHexStr(H3) + Sha1.toHexStr(H4); }; /** * Function 'f' [§4.1.1]. * @private */ Sha1.f = function(s, x, y, z) { switch (s) { case 0: return (x & y) ^ (~x & z); // Ch() case 1: return x ^ y ^ z; // Parity() case 2: return (x & y) ^ (x & z) ^ (y & z); // Maj() case 3: return x ^ y ^ z; // Parity() } }; /** * Rotates left (circular left shift) value x by n positions [§3.2.5]. * @private */ Sha1.ROTL = function(x, n) { return (x<<n) | (x>>>(32-n)); }; /** * Hexadecimal representation of a number. * @private */ Sha1.toHexStr = function(n) { // note can't use toString(16) as it is implementation-dependant, // and in IE returns signed numbers when used on full words var s="", v; for (var i=7; i>=0; i--) { v = (n>>>(i*4)) & 0xf; s += v.toString(16); } return s; }; /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /** Extend String object with method to encode multi-byte string to utf8 * - monsur.hossa.in/2012/07/20/utf-8-in-javascript.html */ if (typeof String.prototype.utf8Encode == 'undefined') { String.prototype.utf8Encode = function() { return unescape( encodeURIComponent( this ) ); }; } /** Extend String object with method to decode utf8 string to multi-byte */ if (typeof String.prototype.utf8Decode == 'undefined') { String.prototype.utf8Decode = function() { try { return decodeURIComponent( escape( this ) ); } catch (e) { return this; // invalid UTF-8? return as-is } }; } /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ if (typeof module != 'undefined' && module.exports) module.exports = Sha1; // CommonJs export if (typeof define == 'function' && define.amd) define([], function() { return Sha1; }); // AMD
vinaymayar/maygh
src/client/util-sha1.js
JavaScript
mit
5,625
package ratecounter import "time" // A RateCounter is a thread-safe counter which returns the number of times // 'Incr' has been called in the last interval type RateCounter struct { counter Counter interval time.Duration } // Constructs a new RateCounter, for the interval provided func NewRateCounter(intrvl time.Duration) *RateCounter { return &RateCounter{ interval: intrvl, } } // Add an event into the RateCounter func (r *RateCounter) Incr(val int64) { r.counter.Incr(val) go r.scheduleDecrement(val) } func (r *RateCounter) scheduleDecrement(amount int64) { time.Sleep(r.interval) r.counter.Incr(-1 * amount) } // Return the current number of events in the last interval func (r *RateCounter) Rate() int64 { return r.counter.Value() }
eranchetz/ratecounter
ratecounter.go
GO
mit
761
/** @module ember @submodule ember-routing-htmlbars */ import Ember from "ember-metal/core"; // Handlebars, uuid, FEATURES, assert, deprecate import { uuid } from "ember-metal/utils"; import run from "ember-metal/run_loop"; import { readUnwrappedModel } from "ember-views/streams/utils"; import { isSimpleClick } from "ember-views/system/utils"; import ActionManager from "ember-views/system/action_manager"; import { isStream } from "ember-metal/streams/utils"; function actionArgs(parameters, actionName) { var ret, i, l; if (actionName === undefined) { ret = new Array(parameters.length); for (i=0, l=parameters.length;i<l;i++) { ret[i] = readUnwrappedModel(parameters[i]); } } else { ret = new Array(parameters.length + 1); ret[0] = actionName; for (i=0, l=parameters.length;i<l; i++) { ret[i + 1] = readUnwrappedModel(parameters[i]); } } return ret; } var ActionHelper = {}; // registeredActions is re-exported for compatibility with older plugins // that were using this undocumented API. ActionHelper.registeredActions = ActionManager.registeredActions; export { ActionHelper }; var keys = ["alt", "shift", "meta", "ctrl"]; var POINTER_EVENT_TYPE_REGEX = /^click|mouse|touch/; var isAllowedEvent = function(event, allowedKeys) { if (typeof allowedKeys === "undefined") { if (POINTER_EVENT_TYPE_REGEX.test(event.type)) { return isSimpleClick(event); } else { allowedKeys = ''; } } if (allowedKeys.indexOf("any") >= 0) { return true; } for (var i=0, l=keys.length;i<l;i++) { if (event[keys[i] + "Key"] && allowedKeys.indexOf(keys[i]) === -1) { return false; } } return true; }; ActionHelper.registerAction = function(actionNameOrStream, options, allowedKeys) { var actionId = uuid(); var eventName = options.eventName; var parameters = options.parameters; ActionManager.registeredActions[actionId] = { eventName: eventName, handler(event) { if (!isAllowedEvent(event, allowedKeys)) { return true; } if (options.preventDefault !== false) { event.preventDefault(); } if (options.bubbles === false) { event.stopPropagation(); } var target = options.target.value(); var actionName; if (isStream(actionNameOrStream)) { actionName = actionNameOrStream.value(); Ember.assert("You specified a quoteless path to the {{action}} helper " + "which did not resolve to an action name (a string). " + "Perhaps you meant to use a quoted actionName? (e.g. {{action 'save'}}).", typeof actionName === 'string'); } else { actionName = actionNameOrStream; } run(function runRegisteredAction() { if (target.send) { target.send.apply(target, actionArgs(parameters, actionName)); } else { Ember.assert("The action '" + actionName + "' did not exist on " + target, typeof target[actionName] === 'function'); target[actionName].apply(target, actionArgs(parameters)); } }); } }; options.view.on('willClearRender', function() { delete ActionManager.registeredActions[actionId]; }); return actionId; }; /** The `{{action}}` helper provides a useful shortcut for registering an HTML element within a template for a single DOM event and forwarding that interaction to the template's controller or specified `target` option. If the controller does not implement the specified action, the event is sent to the current route, and it bubbles up the route hierarchy from there. For more advanced event handling see [Ember.Component](/api/classes/Ember.Component.html) ### Use Given the following application Handlebars template on the page ```handlebars <div {{action 'anActionName'}}> click me </div> ``` And application code ```javascript App.ApplicationController = Ember.Controller.extend({ actions: { anActionName: function() { } } }); ``` Will result in the following rendered HTML ```html <div class="ember-view"> <div data-ember-action="1"> click me </div> </div> ``` Clicking "click me" will trigger the `anActionName` action of the `App.ApplicationController`. In this case, no additional parameters will be passed. If you provide additional parameters to the helper: ```handlebars <button {{action 'edit' post}}>Edit</button> ``` Those parameters will be passed along as arguments to the JavaScript function implementing the action. ### Event Propagation Events triggered through the action helper will automatically have `.preventDefault()` called on them. You do not need to do so in your event handlers. If you need to allow event propagation (to handle file inputs for example) you can supply the `preventDefault=false` option to the `{{action}}` helper: ```handlebars <div {{action "sayHello" preventDefault=false}}> <input type="file" /> <input type="checkbox" /> </div> ``` To disable bubbling, pass `bubbles=false` to the helper: ```handlebars <button {{action 'edit' post bubbles=false}}>Edit</button> ``` If you need the default handler to trigger you should either register your own event handler, or use event methods on your view class. See [Ember.View](/api/classes/Ember.View.html) 'Responding to Browser Events' for more information. ### Specifying DOM event type By default the `{{action}}` helper registers for DOM `click` events. You can supply an `on` option to the helper to specify a different DOM event name: ```handlebars <div {{action "anActionName" on="doubleClick"}}> click me </div> ``` See `Ember.View` 'Responding to Browser Events' for a list of acceptable DOM event names. ### Specifying whitelisted modifier keys By default the `{{action}}` helper will ignore click event with pressed modifier keys. You can supply an `allowedKeys` option to specify which keys should not be ignored. ```handlebars <div {{action "anActionName" allowedKeys="alt"}}> click me </div> ``` This way the `{{action}}` will fire when clicking with the alt key pressed down. Alternatively, supply "any" to the `allowedKeys` option to accept any combination of modifier keys. ```handlebars <div {{action "anActionName" allowedKeys="any"}}> click me with any key pressed </div> ``` ### Specifying a Target There are several possible target objects for `{{action}}` helpers: In a typical Ember application, where templates are managed through use of the `{{outlet}}` helper, actions will bubble to the current controller, then to the current route, and then up the route hierarchy. Alternatively, a `target` option can be provided to the helper to change which object will receive the method call. This option must be a path to an object, accessible in the current context: ```handlebars {{! the application template }} <div {{action "anActionName" target=view}}> click me </div> ``` ```javascript App.ApplicationView = Ember.View.extend({ actions: { anActionName: function() {} } }); ``` ### Additional Parameters You may specify additional parameters to the `{{action}}` helper. These parameters are passed along as the arguments to the JavaScript function implementing the action. ```handlebars {{#each person in people}} <div {{action "edit" person}}> click me </div> {{/each}} ``` Clicking "click me" will trigger the `edit` method on the current controller with the value of `person` as a parameter. @method action @for Ember.Handlebars.helpers @param {String} actionName @param {Object} [context]* @param {Hash} options */ export function actionHelper(params, hash, options, env) { var view = env.data.view; var target; if (!hash.target) { target = view.getStream('controller'); } else if (isStream(hash.target)) { target = hash.target; } else { target = view.getStream(hash.target); } // Ember.assert("You specified a quoteless path to the {{action}} helper which did not resolve to an action name (a string). Perhaps you meant to use a quoted actionName? (e.g. {{action 'save'}}).", !params[0].isStream); // Ember.deprecate("You specified a quoteless path to the {{action}} helper which did not resolve to an action name (a string). Perhaps you meant to use a quoted actionName? (e.g. {{action 'save'}}).", params[0].isStream); var actionOptions = { eventName: hash.on || "click", parameters: params.slice(1), view: view, bubbles: hash.bubbles, preventDefault: hash.preventDefault, target: target, withKeyCode: hash.withKeyCode }; var actionId = ActionHelper.registerAction(params[0], actionOptions, hash.allowedKeys); env.dom.setAttribute(options.element, 'data-ember-action', actionId); }
dgeb/ember.js
packages/ember-routing-htmlbars/lib/helpers/action.js
JavaScript
mit
8,975
import './polyfills.js'; export { WebGLRenderTargetCube } from './renderers/WebGLRenderTargetCube.js'; export { WebGLRenderTarget } from './renderers/WebGLRenderTarget.js'; export { WebGLRenderer } from './renderers/WebGLRenderer.js'; // export { WebGL2Renderer } from './renderers/WebGL2Renderer.js'; export { ShaderLib } from './renderers/shaders/ShaderLib.js'; export { UniformsLib } from './renderers/shaders/UniformsLib.js'; export { UniformsUtils } from './renderers/shaders/UniformsUtils.js'; export { ShaderChunk } from './renderers/shaders/ShaderChunk.js'; export { FogExp2 } from './scenes/FogExp2.js'; export { Fog } from './scenes/Fog.js'; export { Scene } from './scenes/Scene.js'; export { LensFlare } from './objects/LensFlare.js'; export { Sprite } from './objects/Sprite.js'; export { LOD } from './objects/LOD.js'; export { SkinnedMesh } from './objects/SkinnedMesh.js'; export { Skeleton } from './objects/Skeleton.js'; export { Bone } from './objects/Bone.js'; export { Mesh } from './objects/Mesh.js'; export { LineSegments } from './objects/LineSegments.js'; export { LineLoop } from './objects/LineLoop.js'; export { Line } from './objects/Line.js'; export { Points } from './objects/Points.js'; export { Group } from './objects/Group.js'; export { VideoTexture } from './textures/VideoTexture.js'; export { DataTexture } from './textures/DataTexture.js'; export { CompressedTexture } from './textures/CompressedTexture.js'; export { CubeTexture } from './textures/CubeTexture.js'; export { CanvasTexture } from './textures/CanvasTexture.js'; export { DepthTexture } from './textures/DepthTexture.js'; export { Texture } from './textures/Texture.js'; export * from './geometries/Geometries.js'; export * from './materials/Materials.js'; export { CompressedTextureLoader } from './loaders/CompressedTextureLoader.js'; export { DataTextureLoader } from './loaders/DataTextureLoader.js'; export { CubeTextureLoader } from './loaders/CubeTextureLoader.js'; export { TextureLoader } from './loaders/TextureLoader.js'; export { ObjectLoader } from './loaders/ObjectLoader.js'; export { MaterialLoader } from './loaders/MaterialLoader.js'; export { BufferGeometryLoader } from './loaders/BufferGeometryLoader.js'; export { DefaultLoadingManager, LoadingManager } from './loaders/LoadingManager.js'; export { JSONLoader } from './loaders/JSONLoader.js'; export { ImageLoader } from './loaders/ImageLoader.js'; export { ImageBitmapLoader } from './loaders/ImageBitmapLoader.js'; export { FontLoader } from './loaders/FontLoader.js'; export { FileLoader } from './loaders/FileLoader.js'; export { Loader } from './loaders/Loader.js'; export { LoaderUtils } from './loaders/LoaderUtils.js'; export { Cache } from './loaders/Cache.js'; export { AudioLoader } from './loaders/AudioLoader.js'; export { SpotLightShadow } from './lights/SpotLightShadow.js'; export { SpotLight } from './lights/SpotLight.js'; export { PointLight } from './lights/PointLight.js'; export { RectAreaLight } from './lights/RectAreaLight.js'; export { HemisphereLight } from './lights/HemisphereLight.js'; export { DirectionalLightShadow } from './lights/DirectionalLightShadow.js'; export { DirectionalLight } from './lights/DirectionalLight.js'; export { AmbientLight } from './lights/AmbientLight.js'; export { LightShadow } from './lights/LightShadow.js'; export { Light } from './lights/Light.js'; export { StereoCamera } from './cameras/StereoCamera.js'; export { PerspectiveCamera } from './cameras/PerspectiveCamera.js'; export { OrthographicCamera } from './cameras/OrthographicCamera.js'; export { CubeCamera } from './cameras/CubeCamera.js'; export { ArrayCamera } from './cameras/ArrayCamera.js'; export { Camera } from './cameras/Camera.js'; export { AudioListener } from './audio/AudioListener.js'; export { PositionalAudio } from './audio/PositionalAudio.js'; export { AudioContext } from './audio/AudioContext.js'; export { AudioAnalyser } from './audio/AudioAnalyser.js'; export { Audio } from './audio/Audio.js'; export { VectorKeyframeTrack } from './animation/tracks/VectorKeyframeTrack.js'; export { StringKeyframeTrack } from './animation/tracks/StringKeyframeTrack.js'; export { QuaternionKeyframeTrack } from './animation/tracks/QuaternionKeyframeTrack.js'; export { NumberKeyframeTrack } from './animation/tracks/NumberKeyframeTrack.js'; export { ColorKeyframeTrack } from './animation/tracks/ColorKeyframeTrack.js'; export { BooleanKeyframeTrack } from './animation/tracks/BooleanKeyframeTrack.js'; export { PropertyMixer } from './animation/PropertyMixer.js'; export { PropertyBinding } from './animation/PropertyBinding.js'; export { KeyframeTrack } from './animation/KeyframeTrack.js'; export { AnimationUtils } from './animation/AnimationUtils.js'; export { AnimationObjectGroup } from './animation/AnimationObjectGroup.js'; export { AnimationMixer } from './animation/AnimationMixer.js'; export { AnimationClip } from './animation/AnimationClip.js'; export { Uniform } from './core/Uniform.js'; export { InstancedBufferGeometry } from './core/InstancedBufferGeometry.js'; export { BufferGeometry } from './core/BufferGeometry.js'; export { Geometry } from './core/Geometry.js'; export { InterleavedBufferAttribute } from './core/InterleavedBufferAttribute.js'; export { InstancedInterleavedBuffer } from './core/InstancedInterleavedBuffer.js'; export { InterleavedBuffer } from './core/InterleavedBuffer.js'; export { InstancedBufferAttribute } from './core/InstancedBufferAttribute.js'; export * from './core/BufferAttribute.js'; export { Face3 } from './core/Face3.js'; export { Object3D } from './core/Object3D.js'; export { Raycaster } from './core/Raycaster.js'; export { Layers } from './core/Layers.js'; export { EventDispatcher } from './core/EventDispatcher.js'; export { Clock } from './core/Clock.js'; export { QuaternionLinearInterpolant } from './math/interpolants/QuaternionLinearInterpolant.js'; export { LinearInterpolant } from './math/interpolants/LinearInterpolant.js'; export { DiscreteInterpolant } from './math/interpolants/DiscreteInterpolant.js'; export { CubicInterpolant } from './math/interpolants/CubicInterpolant.js'; export { Interpolant } from './math/Interpolant.js'; export { Triangle } from './math/Triangle.js'; export { _Math as Math } from './math/Math.js'; export { Spherical } from './math/Spherical.js'; export { Cylindrical } from './math/Cylindrical.js'; export { Plane } from './math/Plane.js'; export { Frustum } from './math/Frustum.js'; export { Sphere } from './math/Sphere.js'; export { Ray } from './math/Ray.js'; export { Matrix4 } from './math/Matrix4.js'; export { Matrix3 } from './math/Matrix3.js'; export { Box3 } from './math/Box3.js'; export { Box2 } from './math/Box2.js'; export { Line3 } from './math/Line3.js'; export { Euler } from './math/Euler.js'; export { Vector4 } from './math/Vector4.js'; export { Vector3 } from './math/Vector3.js'; export { Vector2 } from './math/Vector2.js'; export { Quaternion } from './math/Quaternion.js'; export { Color } from './math/Color.js'; export { ImmediateRenderObject } from './extras/objects/ImmediateRenderObject.js'; export { VertexNormalsHelper } from './helpers/VertexNormalsHelper.js'; export { SpotLightHelper } from './helpers/SpotLightHelper.js'; export { SkeletonHelper } from './helpers/SkeletonHelper.js'; export { PointLightHelper } from './helpers/PointLightHelper.js'; export { RectAreaLightHelper } from './helpers/RectAreaLightHelper.js'; export { HemisphereLightHelper } from './helpers/HemisphereLightHelper.js'; export { GridHelper } from './helpers/GridHelper.js'; export { PolarGridHelper } from './helpers/PolarGridHelper.js'; export { FaceNormalsHelper } from './helpers/FaceNormalsHelper.js'; export { DirectionalLightHelper } from './helpers/DirectionalLightHelper.js'; export { CameraHelper } from './helpers/CameraHelper.js'; export { BoxHelper } from './helpers/BoxHelper.js'; export { Box3Helper } from './helpers/Box3Helper.js'; export { PlaneHelper } from './helpers/PlaneHelper.js'; export { ArrowHelper } from './helpers/ArrowHelper.js'; export { AxesHelper } from './helpers/AxesHelper.js'; export * from './extras/curves/Curves.js'; export { Shape } from './extras/core/Shape.js'; export { Path } from './extras/core/Path.js'; export { ShapePath } from './extras/core/ShapePath.js'; export { Font } from './extras/core/Font.js'; export { CurvePath } from './extras/core/CurvePath.js'; export { Curve } from './extras/core/Curve.js'; export { ShapeUtils } from './extras/ShapeUtils.js'; export { SceneUtils } from './extras/SceneUtils.js'; export { WebGLUtils } from './renderers/webgl/WebGLUtils.js'; export * from './constants.js'; export * from './Three.Legacy.js';
RemusMar/three.js
src/Three.js
JavaScript
mit
8,725
<?php /***************************************************************************\ * SPIP, Systeme de publication pour l'internet * * * * Copyright (c) 2001-2011 * * Arnaud Martin, Antoine Pitrou, Philippe Riviere, Emmanuel Saint-James * * * * Ce programme est un logiciel libre distribue sous licence GNU/GPL. * * Pour plus de details voir le fichier COPYING.txt ou l'aide en ligne. * \***************************************************************************/ // if (!defined('_ECRIRE_INC_VERSION')) return; global $tables_images, $tables_sequences, $tables_documents, $tables_mime, $mime_alias; $tables_images = array( // Images reconnues par PHP 'jpg' => 'JPEG', 'png' => 'PNG', 'gif' =>'GIF', // Autres images (peuvent utiliser le tag <img>) 'bmp' => 'BMP', 'tif' => 'TIFF' ); // Multimedia (peuvent utiliser le tag <embed>) $tables_sequences = array( 'aiff' => 'AIFF', 'asf' => 'Windows Media', 'avi' => 'AVI', 'flv' => 'Flash Video', 'mid' => 'Midi', 'mng' => 'MNG', 'mka' => 'Matroska Audio', 'mkv' => 'Matroska Video', 'mov' => 'QuickTime', 'mp3' => 'MP3', 'mp4' => 'MPEG4', 'mpg' => 'MPEG', 'ogg' => 'Ogg', 'qt' => 'QuickTime', 'ra' => 'RealAudio', 'ram' => 'RealAudio', 'rm' => 'RealAudio', 'svg' => 'Scalable Vector Graphics', 'swf' => 'Flash', 'wav' => 'WAV', 'wmv' => 'Windows Media', '3gp' => '3rd Generation Partnership Project' ); // Documents varies $tables_documents = array( 'abw' => 'Abiword', 'ai' => 'Adobe Illustrator', 'bz2' => 'BZip', 'bin' => 'Binary Data', 'blend' => 'Blender', 'c' => 'C source', 'cls' => 'LaTeX Class', 'css' => 'Cascading Style Sheet', 'csv' => 'Comma Separated Values', 'deb' => 'Debian', 'doc' => 'Word', 'djvu' => 'DjVu', 'dvi' => 'LaTeX DVI', 'eps' => 'PostScript', 'gz' => 'GZ', 'h' => 'C header', 'html' => 'HTML', 'kml' => 'Keyhole Markup Language', 'kmz' => 'Google Earth Placemark File', 'pas' => 'Pascal', 'pdf' => 'PDF', 'pgn' => 'Portable Game Notation', 'ppt' => 'PowerPoint', 'ps' => 'PostScript', 'psd' => 'Photoshop', 'rpm' => 'RedHat/Mandrake/SuSE', 'rtf' => 'RTF', 'sdd' => 'StarOffice', 'sdw' => 'StarOffice', 'sit' => 'Stuffit', 'sty' => 'LaTeX Style Sheet', 'sxc' => 'OpenOffice.org Calc', 'sxi' => 'OpenOffice.org Impress', 'sxw' => 'OpenOffice.org', 'tex' => 'LaTeX', 'tgz' => 'TGZ', 'torrent' => 'BitTorrent', 'ttf' => 'TTF Font', 'txt' => 'texte', 'xcf' => 'GIMP multi-layer', 'xls' => 'Excel', 'xml' => 'XML', 'zip' => 'Zip', // open document format 'odt' => 'opendocument text', 'ods' => 'opendocument spreadsheet', 'odp' => 'opendocument presentation', 'odg' => 'opendocument graphics', 'odc' => 'opendocument chart', 'odf' => 'opendocument formula', 'odb' => 'opendocument database', 'odi' => 'opendocument image', 'odm' => 'opendocument text-master', 'ott' => 'opendocument text-template', 'ots' => 'opendocument spreadsheet-template', 'otp' => 'opendocument presentation-template', 'otg' => 'opendocument graphics-template', ); $tables_mime = array( // Images reconnues par PHP 'jpg'=>'image/jpeg', 'png'=>'image/png', 'gif'=>'image/gif', // Autres images (peuvent utiliser le tag <img>) 'bmp'=>'image/x-ms-bmp', // pas enregistre par IANA, variante: image/bmp 'tif'=>'image/tiff', // Multimedia (peuvent utiliser le tag <embed>) 'aiff'=>'audio/x-aiff', 'asf'=>'video/x-ms-asf', 'avi'=>'video/x-msvideo', 'flv' => 'video/x-flv', 'mid'=>'audio/midi', 'mka' => 'audio/mka', 'mkv' => 'video/mkv', 'mng'=>'video/x-mng', 'mov'=>'video/quicktime', 'mp3'=>'audio/mpeg', 'mp4' => 'application/mp4', 'mpg'=>'video/mpeg', 'ogg'=>'application/ogg', 'qt' =>'video/quicktime', 'ra' =>'audio/x-pn-realaudio', 'ram'=>'audio/x-pn-realaudio', 'rm' =>'audio/x-pn-realaudio', 'svg'=>'image/svg+xml', 'swf'=>'application/x-shockwave-flash', 'wav'=>'audio/x-wav', 'wmv'=>'video/x-ms-wmv', '3gp'=>'video/3gpp', // Documents varies 'ai' =>'application/illustrator', 'abw' =>'application/abiword', 'bin' => 'application/octet-stream', # le tout-venant 'blend' => 'application/x-blender', 'bz2'=>'application/x-bzip2', 'c' =>'text/x-csrc', 'css'=>'text/css', 'csv'=>'text/csv', 'deb'=>'application/x-debian-package', 'doc'=>'application/msword', 'djvu'=>'image/vnd.djvu', 'dvi'=>'application/x-dvi', 'eps'=>'application/postscript', 'gz' =>'application/x-gzip', 'h' =>'text/x-chdr', 'html'=>'text/html', 'kml'=>'application/vnd.google-earth.kml+xml', 'kmz'=>'application/vnd.google-earth.kmz', 'pas'=>'text/x-pascal', 'pdf'=>'application/pdf', 'pgn' =>'application/x-chess-pgn', 'ppt'=>'application/vnd.ms-powerpoint', 'ps' =>'application/postscript', 'psd'=>'image/x-photoshop', // pas enregistre par IANA 'rpm'=>'application/x-redhat-package-manager', 'rtf'=>'application/rtf', 'sdd'=>'application/vnd.stardivision.impress', 'sdw'=>'application/vnd.stardivision.writer', 'sit'=>'application/x-stuffit', 'sxc'=>'application/vnd.sun.xml.calc', 'sxi'=>'application/vnd.sun.xml.impress', 'sxw'=>'application/vnd.sun.xml.writer', 'tex'=>'text/x-tex', 'tgz'=>'application/x-gtar', 'torrent' => 'application/x-bittorrent', 'ttf'=>'application/x-font-ttf', 'txt'=>'text/plain', 'xcf'=>'application/x-xcf', 'xls'=>'application/vnd.ms-excel', 'xml'=>'application/xml', 'zip'=>'application/zip', // open document format 'odt' => 'application/vnd.oasis.opendocument.text', 'ods' => 'application/vnd.oasis.opendocument.spreadsheet', 'odp' => 'application/vnd.oasis.opendocument.presentation', 'odg' => 'application/vnd.oasis.opendocument.graphics', 'odc' => 'application/vnd.oasis.opendocument.chart', 'odf' => 'application/vnd.oasis.opendocument.formula', 'odb' => 'application/vnd.oasis.opendocument.database', 'odi' => 'application/vnd.oasis.opendocument.image', 'odm' => 'application/vnd.oasis.opendocument.text-master', 'ott' => 'application/vnd.oasis.opendocument.text-template', 'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template', 'otp' => 'application/vnd.oasis.opendocument.presentation-template', 'otg' => 'application/vnd.oasis.opendocument.graphics-template', 'cls'=>'text/x-tex', 'sty'=>'text/x-tex', ); $mime_alias = array ( 'audio/x-mpeg' => 'audio/mpeg', 'application/x-ogg' => 'application/ogg', 'video/mp4' => 'application/mp4', 'video/flv' => 'video/x-flv', 'audio/3gpp' => 'video/3gpp' ); ?>
eyeswebcrea/espace-couture-sittler.fr
spip/ecrire/maj/vieille_base/13000/typedoc.php
PHP
mit
7,073
require 'rails_helper' RSpec.describe ActiveAdmin::ResourceController do let(:controller) { Admin::PostsController.new } describe "callbacks" do before :all do application = ::ActiveAdmin::Application.new namespace = ActiveAdmin::Namespace.new(application, :admin) namespace.register Post do after_build :call_after_build before_save :call_before_save after_save :call_after_save before_create :call_before_create after_create :call_after_create before_update :call_before_update after_update :call_after_update before_destroy :call_before_destroy after_destroy :call_after_destroy controller do def call_after_build(obj); end def call_before_save(obj); end def call_after_save(obj); end def call_before_create(obj); end def call_after_create(obj); end def call_before_update(obj); end def call_after_update(obj); end def call_before_destroy(obj); end def call_after_destroy(obj); end end end end describe "performing create" do let(:resource){ double("Resource", save: true) } before do expect(resource).to receive(:save) end it "should call the before create callback" do expect(controller).to receive(:call_before_create).with(resource) controller.send :create_resource, resource end it "should call the before save callback" do expect(controller).to receive(:call_before_save).with(resource) controller.send :create_resource, resource end it "should call the after save callback" do expect(controller).to receive(:call_after_save).with(resource) controller.send :create_resource, resource end it "should call the after create callback" do expect(controller).to receive(:call_after_create).with(resource) controller.send :create_resource, resource end end describe "performing update" do let(:resource){ double("Resource", :attributes= => true, save: true) } let(:attributes){ [{}] } before do expect(resource).to receive(:attributes=).with(attributes[0]) expect(resource).to receive(:save) end it "should call the before update callback" do expect(controller).to receive(:call_before_update).with(resource) controller.send :update_resource, resource, attributes end it "should call the before save callback" do expect(controller).to receive(:call_before_save).with(resource) controller.send :update_resource, resource, attributes end it "should call the after save callback" do expect(controller).to receive(:call_after_save).with(resource) controller.send :update_resource, resource, attributes end it "should call the after create callback" do expect(controller).to receive(:call_after_update).with(resource) controller.send :update_resource, resource, attributes end end describe "performing destroy" do let(:resource){ double("Resource", destroy: true) } before do expect(resource).to receive(:destroy) end it "should call the before destroy callback" do expect(controller).to receive(:call_before_destroy).with(resource) controller.send :destroy_resource, resource end it "should call the after destroy callback" do expect(controller).to receive(:call_after_destroy).with(resource) controller.send :destroy_resource, resource end end end end RSpec.describe "A specific resource controller", type: :controller do before do load_resources { ActiveAdmin.register Post } @controller = Admin::PostsController.new end describe "authenticating the user" do it "should do nothing when no authentication_method set" do namespace = controller.class.active_admin_config.namespace expect(namespace).to receive(:authentication_method).once.and_return(nil) controller.send(:authenticate_active_admin_user) end it "should call the authentication_method when set" do namespace = controller.class.active_admin_config.namespace expect(namespace).to receive(:authentication_method).twice. and_return(:authenticate_admin_user!) expect(controller).to receive(:authenticate_admin_user!).and_return(true) controller.send(:authenticate_active_admin_user) end end describe "retrieving the current user" do it "should return nil when no current_user_method set" do namespace = controller.class.active_admin_config.namespace expect(namespace).to receive(:current_user_method).once.and_return(nil) expect(controller.send(:current_active_admin_user)).to eq nil end it "should call the current_user_method when set" do user = double namespace = controller.class.active_admin_config.namespace expect(namespace).to receive(:current_user_method).twice. and_return(:current_admin_user) expect(controller).to receive(:current_admin_user).and_return(user) expect(controller.send(:current_active_admin_user)).to eq user end end describe 'retrieving the resource' do let(:post) { Post.new title: "An incledibly unique Post Title" } let(:http_params){ { id: '1' } } before do allow(Post).to receive(:find).and_return(post) controller.class_eval { public :resource } allow(controller).to receive(:params).and_return(ActionController::Parameters.new(http_params)) end subject { controller.resource } it "returns a Post" do expect(subject).to be_kind_of(Post) end context 'with a decorator' do let(:config) { controller.class.active_admin_config } before { config.decorator_class_name = '::PostDecorator' } it 'returns a PostDecorator' do expect(subject).to be_kind_of(PostDecorator) end it 'returns a PostDecorator that wraps the post' do expect(subject.title).to eq post.title end end end describe 'retrieving the resource collection' do let(:config) { controller.class.active_admin_config } before do Post.create!(title: "An incledibly unique Post Title") if Post.count == 0 config.decorator_class_name = nil request = double 'Request', format: 'application/json' allow(controller).to receive(:params) { {} } allow(controller).to receive(:request){ request } end subject { controller.send :collection } it { is_expected.to be_a ActiveRecord::Relation } it "returns a collection of posts" do expect(subject.first).to be_kind_of(Post) end context 'with a decorator' do before { config.decorator_class_name = 'PostDecorator' } it 'returns a collection decorator using PostDecorator' do expect(subject).to be_a Draper::CollectionDecorator expect(subject.decorator_class).to eq PostDecorator end it 'returns a collection decorator that wraps the post' do expect(subject.first.title).to eq Post.first.title end end end describe "performing batch_action" do let(:batch_action) { ActiveAdmin::BatchAction.new :flag, "Flag", &batch_action_block } let(:batch_action_block) { proc { } } let(:params) { ActionController::Parameters.new(http_params) } before do allow(controller.class.active_admin_config).to receive(:batch_actions).and_return([batch_action]) allow(controller).to receive(:params) { params } end describe "when params batch_action matches existing BatchAction" do let(:http_params) do { batch_action: "flag", collection_selection: ["1"] } end it "should call the block with args" do expect(controller).to receive(:instance_exec).with(["1"], {}) controller.batch_action end it "should call the block in controller scope" do expect(controller).to receive(:render_in_context).with(controller, nil).and_return({}) controller.batch_action end end describe "when params batch_action doesn't match a BatchAction" do let(:http_params) do { batch_action: "derp", collection_selection: ["1"] } end it "should raise an error" do expect { controller.batch_action }.to raise_error("Couldn't find batch action \"derp\"") end end describe "when params batch_action is blank" do let(:http_params) do { collection_selection: ["1"] } end it "should raise an error" do expect { controller.batch_action }.to raise_error("Couldn't find batch action \"\"") end end end end
SoftSwiss/active_admin
spec/unit/resource_controller_spec.rb
Ruby
mit
8,857
import {NgbdAlertBasic} from './basic/alert-basic'; import {NgbdAlertCloseable} from './closeable/alert-closeable'; import {NgbdAlertCustom} from './custom/alert-custom'; import {NgbdAlertSelfclosing} from './selfclosing/alert-selfclosing'; import {NgbdAlertConfig} from './config/alert-config'; export const DEMO_DIRECTIVES = [NgbdAlertBasic, NgbdAlertCloseable, NgbdAlertCustom, NgbdAlertSelfclosing, NgbdAlertConfig]; export const DEMO_SNIPPETS = { basic: { code: require('!!prismjs-loader?lang=typescript!./basic/alert-basic'), markup: require('!!prismjs-loader?lang=markup!./basic/alert-basic.html') }, closeable: { code: require('!!prismjs-loader?lang=typescript!./closeable/alert-closeable'), markup: require('!!prismjs-loader?lang=markup!./closeable/alert-closeable.html') }, custom: { code: require('!!prismjs-loader?lang=typescript!./custom/alert-custom'), markup: require('!!prismjs-loader?lang=markup!./custom/alert-custom.html') }, selfclosing: { code: require('!!prismjs-loader?lang=typescript!./selfclosing/alert-selfclosing'), markup: require('!!prismjs-loader?lang=markup!./selfclosing/alert-selfclosing.html') }, config: { code: require('!!prismjs-loader?lang=typescript!./config/alert-config'), markup: require('!!prismjs-loader?lang=markup!./config/alert-config.html') } };
spongessuck/ng-bootstrap
demo/src/app/components/alert/demos/index.ts
TypeScript
mit
1,360
<?php /** * CodeIgniter * * An open source application development framework for PHP * * This content is released under the MIT License (MIT) * * Copyright (c) 2014 - 2018, British Columbia Institute of Technology * * 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. * * @package CodeIgniter * @author EllisLab Dev Team * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) * @copyright Copyright (c) 2014 - 2018, British Columbia Institute of Technology (https://bcit.ca/) * @license https://opensource.org/licenses/MIT MIT License * @link https://codeigniter.com * @since Version 1.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); /** * CodeIgniter String Helpers * * @package CodeIgniter * @subpackage Helpers * @category Helpers * @author EllisLab Dev Team * @link https://codeigniter.com/user_guide/helpers/string_helper.html */ // ------------------------------------------------------------------------ if ( ! function_exists('strip_slashes')) { /** * Strip Slashes * * Removes slashes contained in a string or in an array * * @param mixed string or array * @return mixed string or array */ function strip_slashes($str) { if ( ! is_array($str)) { return stripslashes($str); } foreach ($str as $key => $val) { $str[$key] = strip_slashes($val); } return $str; } } // ------------------------------------------------------------------------ if ( ! function_exists('strip_quotes')) { /** * Strip Quotes * * Removes single and double quotes from a string * * @param string * @return string */ function strip_quotes($str) { return str_replace(array('"', "'"), '', $str); } } // ------------------------------------------------------------------------ if ( ! function_exists('quotes_to_entities')) { /** * Quotes to Entities * * Converts single and double quotes to entities * * @param string * @return string */ function quotes_to_entities($str) { return str_replace(array("\'","\"","'",'"'), array("&#39;","&quot;","&#39;","&quot;"), $str); } } // ------------------------------------------------------------------------ if ( ! function_exists('reduce_double_slashes')) { /** * Reduce Double Slashes * * Converts double slashes in a string to a single slash, * except those found in http:// * * http://www.some-site.com//index.php * * becomes: * * http://www.some-site.com/index.php * * @param string * @return string */ function reduce_double_slashes($str) { return preg_replace('#(^|[^:])//+#', '\\1/', $str); } } // ------------------------------------------------------------------------ if ( ! function_exists('reduce_multiples')) { /** * Reduce Multiples * * Reduces multiple instances of a particular character. Example: * * Fred, Bill,, Joe, Jimmy * * becomes: * * Fred, Bill, Joe, Jimmy * * @param string * @param string the character you wish to reduce * @param bool TRUE/FALSE - whether to trim the character from the beginning/end * @return string */ function reduce_multiples($str, $character = ',', $trim = FALSE) { $str = preg_replace('#'.preg_quote($character, '#').'{2,}#', $character, $str); return ($trim === TRUE) ? trim($str, $character) : $str; } } // ------------------------------------------------------------------------ if ( ! function_exists('random_string')) { /** * Create a "Random" String * * @param string type of random string. basic, alpha, alnum, numeric, nozero, unique, md5, encrypt and sha1 * @param int number of characters * @return string */ function random_string($type = 'alnum', $len = 8) { switch ($type) { case 'basic': return mt_rand(); case 'alnum': case 'numeric': case 'nozero': case 'alpha': switch ($type) { case 'alpha': $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; break; case 'alnum': $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; break; case 'numeric': $pool = '0123456789'; break; case 'nozero': $pool = '123456789'; break; } return substr(str_shuffle(str_repeat($pool, ceil($len / strlen($pool)))), 0, $len); case 'unique': // todo: remove in 3.1+ case 'md5': return md5(uniqid(mt_rand())); case 'encrypt': // todo: remove in 3.1+ case 'sha1': return sha1(uniqid(mt_rand(), TRUE)); } } } // ------------------------------------------------------------------------ if ( ! function_exists('increment_string')) { /** * Add's _1 to a string or increment the ending number to allow _2, _3, etc * * @param string required * @param string What should the duplicate number be appended with * @param string Which number should be used for the first dupe increment * @return string */ function increment_string($str, $separator = '_', $first = 1) { preg_match('/(.+)'.preg_quote($separator, '/').'([0-9]+)$/', $str, $match); return isset($match[2]) ? $match[1].$separator.($match[2] + 1) : $str.$separator.$first; } } // ------------------------------------------------------------------------ if ( ! function_exists('alternator')) { /** * Alternator * * Allows strings to be alternated. See docs... * * @param string (as many parameters as needed) * @return string */ function alternator() { static $i; if (func_num_args() === 0) { $i = 0; return ''; } $args = func_get_args(); return $args[($i++ % count($args))]; } }
tianhe1986/CodeIgniter
system/helpers/string_helper.php
PHP
mit
6,605
<?php /** * * Description * * @package VirtueMart * @subpackage Paymentmethod * @author Max Milbers * @link https://virtuemart.net * @copyright Copyright (c) 2004 - 2010 VirtueMart Team. All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php * VirtueMart is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * @version $Id: edit_edit.php 9413 2017-01-04 17:20:58Z Milbo $ */ // Check to ensure this file is included in Joomla! defined('_JEXEC') or die('Restricted access'); ?> <div class="col50"> <fieldset> <legend><?php echo vmText::_('COM_VIRTUEMART_PAYMENTMETHOD'); ?></legend> <table class="admintable"> <?php echo VmHTML::row('input','COM_VIRTUEMART_PAYMENTMETHOD_FORM_NAME','payment_name',$this->payment->payment_name,'class="required"'); ?> <?php echo VmHTML::row('input','COM_VIRTUEMART_SLUG','slug',$this->payment->slug); ?> <?php echo VmHTML::row('booleanlist','COM_VIRTUEMART_PUBLISHED','published',$this->payment->published); ?> <?php echo VmHTML::row('textarea','COM_VIRTUEMART_PAYMENT_FORM_DESCRIPTION','payment_desc',$this->payment->payment_desc); ?> <?php echo VmHTML::row('raw','COM_VIRTUEMART_PAYMENT_CLASS_NAME', $this->vmPPaymentList ); ?> <?php echo VmHTML::row('raw','COM_VIRTUEMART_PAYMENTMETHOD_FORM_SHOPPER_GROUP', $this->shopperGroupList ); ?> <?php echo VmHTML::row('input','COM_VIRTUEMART_LIST_ORDER','ordering',$this->payment->ordering,'class="inputbox"','',4,4); ?> <?php echo VmHTML::row('raw', 'COM_VIRTUEMART_CURRENCY', $this->currencyList); ?> <?php if ($this->showVendors()) { echo VmHTML::row('raw', 'COM_VIRTUEMART_VENDOR', $this->vendorList); } if($this->showVendors ){ echo VmHTML::row('checkbox','COM_VIRTUEMART_SHARED', 'shared', $this->payment->shared ); } ?> </table> </fieldset> </div>
yaelduckwen/lo_imaginario
web2/administrator/components/com_virtuemart/views/paymentmethod/tmpl/edit_edit.php
PHP
mit
2,059
<?php header("Content-Type: text/html; charset=utf-8"); if (!$_POST) exit; require dirname(__FILE__)."/validation.php"; require dirname(__FILE__)."/csrf.php"; /************************************************/ /* Your data */ /************************************************/ /* Your email goes here */ $your_email = "your_email@domain.com"; /* Your name or your company name goes here */ $your_name = "Your name"; /* Message subject */ $your_subject = "J-forms: Registration form"; /* Define your data to access MySQL database */ define("REG_USER", "username"); // your username define("REG_SERVER", "host"); // your host define("REG_PASSWORD", "password"); // your password define("REG_DATABASE", "database"); // your database /* Your database table goes here */ $mysql_table = "register"; /************************************************/ /* Settings */ /************************************************/ /* Select validation for fields */ /* If you want to validate field - true, if you don't - false */ $validate_user_name = true; $validate_email = true; $validate_pass = true; $validate_conf_pass = true; $validate_first_name = true; $validate_last_name = true; $validate_gender = true; /* Select the action */ /* If you want to do the action - true, if you don't - false */ $send_letter = true; $duplicate_to_database = true; /************************************************/ /* Variables */ /************************************************/ /* Error variables */ $error_text = array(); $error_message = ''; /* Last row ID */ /* In case, if data will not be duplicated to a database */ $row_id = "No data in a database"; /* POST data */ $user_name = (isset($_POST["username"])) ? strip_tags(trim($_POST["username"])) : false; $email = (isset($_POST["email"])) ? strip_tags(trim($_POST["email"])) : false; $pass = (isset($_POST["password"])) ? strip_tags(trim($_POST["password"])) : false; $conf_pass = (isset($_POST["confirm_password"])) ? strip_tags(trim($_POST["confirm_password"])) : false; $first_name = (isset($_POST["first_name"])) ? strip_tags(trim($_POST["first_name"])) : false; $last_name = (isset($_POST["last_name"])) ? strip_tags(trim($_POST["last_name"])) : false; $gender = (isset($_POST["gender"])) ? strip_tags(trim($_POST["gender"])) : false; $token = (isset($_POST["token_register"])) ? strip_tags(trim($_POST["token_register"])) : false; $user_name = htmlspecialchars($user_name, ENT_QUOTES, 'UTF-8'); $email = htmlspecialchars($email, ENT_QUOTES, 'UTF-8'); $pass = htmlspecialchars($pass, ENT_QUOTES, 'UTF-8'); $conf_pass = htmlspecialchars($conf_pass, ENT_QUOTES, 'UTF-8'); $first_name = htmlspecialchars($first_name, ENT_QUOTES, 'UTF-8'); $last_name = htmlspecialchars($last_name, ENT_QUOTES, 'UTF-8'); $gender = htmlspecialchars($gender, ENT_QUOTES, 'UTF-8'); $token = htmlspecialchars($token, ENT_QUOTES, 'UTF-8'); $user_name = substr($user_name, 0, 30); $email = substr($email, 0, 30); $pass = substr($pass, 0, 30); $conf_pass = substr($conf_pass, 0, 30); $first_name = substr($first_name, 0, 30); $last_name = substr($last_name, 0, 30); $gender = substr($gender, 0, 10); /************************************************/ /* CSRF protection */ /************************************************/ $new_token = new CSRF('register'); if (!$new_token->check_token($token)) { echo '<div class="error-message unit"><i class="fa fa-close"></i>Incorrect token. Please reload this webpage</div>'; exit; } /************************************************/ /* Validation */ /************************************************/ /* Username */ if ($validate_user_name){ $result = validateUsertName($user_name, 1); if ($result !== "valid") { $error_text[] = $result; } } /* Email */ if ($validate_email){ $result = validateEmail($email); if ($result !== "valid") { $error_text[] = $result; } } /* Password */ if ($validate_pass) { $result = validatePass($pass, 6); if ($result !== "valid") { $error_text[] = $result; } } /* Confirm password */ if ($validate_conf_pass) { $result = validateConfPass($pass, $conf_pass); if ($result !== "valid") { $error_text[] = $result; } } /* First name */ if ($validate_first_name){ $result = validateFirstName($first_name, 1); if ($result !== "valid") { $error_text[] = $result; } } /* Last name */ if ($validate_last_name){ $result = validateLastName($last_name, 1); if ($result !== "valid") { $error_text[] = $result; } } /* Gender */ if ($validate_gender){ $result = validateGender($gender); if ($result !== "valid") { $error_text[] = $result; } } /* If validation error occurs */ if ($error_text) { foreach ($error_text as $val) { $error_message .= '<li>' . $val . '</li>'; } echo '<div class="error-message unit"><i class="fa fa-close"></i>Oops! The following errors occurred:<ul>' . $error_message . '</ul></div>'; exit; } /************************************************/ /* Duplicate info to a database */ /************************************************/ if ($duplicate_to_database) { /* Select type of connection to a database */ /* If you want to use connection - true, if you don't - false */ /* For proper work you have to select only one type of connection */ /* Mysqli connection to DB */ $mysqli_connect = true; if ($mysqli_connect) { require dirname(__FILE__)."/mysql.php"; $row_id = queryMysqli($mysql_table, $user_name, $email, $pass, $first_name, $last_name, $gender); } /* PDO connection to DB */ $pdo_connect = false; if ($pdo_connect) { require dirname(__FILE__)."/pdo.php"; $row_id = queryPdo($mysql_table, $user_name, $email, $pass, $first_name, $last_name, $gender); } } /************************************************/ /* Sending email */ /************************************************/ if ($send_letter) { /* Send email using sendmail function */ /* If you want to use sendmail - true, if you don't - false */ /* If you will use sendmail function - do not forget to set '$smtp' variable to 'false' */ $sendmail = true; if ($sendmail) { require dirname(__FILE__)."/phpmailer/PHPMailerAutoload.php"; require dirname(__FILE__)."/message.php"; $mail = new PHPMailer; $mail->isSendmail(); $mail->IsHTML(true); $mail->From = $email; $mail->CharSet = "UTF-8"; $mail->FromName = "J-forms"; $mail->Encoding = "base64"; $mail->ContentType = "text/html"; $mail->addAddress($your_email, $your_name); $mail->Subject = $your_subject; $mail->Body = $letter; $mail->AltBody = "Use an HTML compatible email client"; } /* Send email using smtp function */ /* If you want to use smtp - true, if you don't - false */ /* If you will use smtp function - do not forget to set '$sendmail' variable to 'false' */ $smtp = false; if ($smtp) { require dirname(__FILE__)."/phpmailer/PHPMailerAutoload.php"; require dirname(__FILE__)."/message.php"; $mail = new PHPMailer; $mail->isSMTP(); // Set mailer to use SMTP $mail->Host = "smtp1.example.com;smtp2.example.com"; // Specify main and backup server $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = "your-username"; // SMTP username $mail->Password = "your-password"; // SMTP password $mail->SMTPSecure = "tls"; // Enable encryption, 'ssl' also accepted $mail->Port = 465; // SMTP Port number e.g. smtp.gmail.com uses port 465 $mail->IsHTML(true); $mail->From = $email; $mail->CharSet = "UTF-8"; $mail->FromName = "J-forms"; $mail->Encoding = "base64"; $mail->Timeout = 200; $mail->SMTPDebug = 0; $mail->ContentType = "text/html"; $mail->addAddress($your_email, $your_name); $mail->Subject = $your_subject; $mail->Body = $letter; $mail->AltBody = "Use an HTML compatible email client"; } /* Multiple email recepients */ /* If you want to add multiple email recepients - true, if you don't - false */ /* Enter email and name of the recipients */ $recipients = false; if ($recipients) { $recipients = array("email@domain.com" => "name of recipient", "email@domain.com" => "name of recipient", "email@domain.com" => "name of recipient" ); foreach ($recipients as $email => $name) { $mail->AddBCC($email, $name); } } /* if error occurs while email sending */ if(!$mail->send()) { echo '<div class="error-message unit"><i class="fa fa-close"></i>Mailer Error: ' . $mail->ErrorInfo . '</div>'; exit; } } /************************************************/ /* Success message */ /************************************************/ echo '<div class="success-message unit"><i class="fa fa-check"></i>Your message has been sent</div>'; ?>
Serious-Rage/SOCIAL-RAGE
j-forms/source/forms/smtp_sendmail_database/registration_without_footer_header_2/j-folder/php/action.php
PHP
mit
9,179
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import URI from 'vs/base/common/uri'; import Severity from 'vs/base/common/severity'; import EditorCommon = require('vs/editor/common/editorCommon'); import Modes = require('vs/editor/common/modes'); import HtmlContent = require('vs/base/common/htmlContent'); import Parser = require('./parser/jsonParser'); import JSONFormatter = require('vs/languages/json/common/features/jsonFormatter'); import SchemaService = require('./jsonSchemaService'); import JSONSchema = require('vs/base/common/jsonSchema'); import JSONIntellisense = require('./jsonIntellisense'); import WinJS = require('vs/base/common/winjs.base'); import Strings = require('vs/base/common/strings'); import ProjectJSONContribution = require('./contributions/projectJSONContribution'); import PackageJSONContribution = require('./contributions/packageJSONContribution'); import BowerJSONContribution = require('./contributions/bowerJSONContribution'); import GlobPatternContribution = require('./contributions/globPatternContribution'); import errors = require('vs/base/common/errors'); import {IMarkerService, IMarkerData} from 'vs/platform/markers/common/markers'; import {IRequestService} from 'vs/platform/request/common/request'; import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace'; import {ISchemaContributions} from 'vs/platform/jsonschemas/common/jsonContributionRegistry'; import {IResourceService} from 'vs/editor/common/services/resourceService'; import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation'; import {JSONLocation} from './parser/jsonLocation'; import {filterSuggestions} from 'vs/editor/common/modes/supports/suggestSupport'; import {ValidationHelper} from 'vs/editor/common/worker/validationHelper'; export interface IOptionsSchema { /** * HTTP schema URL or a relative path to schema file in workspace */ url: string; /** * The patterns (e.g. *.pack.json) to map files to this schema */ fileMatch: string[]; /** * A unresolved schema definition. Optional, to avoid fetching from a URL. */ schema?: JSONSchema.IJSONSchema; /* deprecated */ schemaPath: string; /* deprecated */ filePattern: string; } export interface IOptions { schemas: IOptionsSchema[]; } export interface ISuggestionsCollector { add(suggestion: Modes.ISuggestion): void; setAsIncomplete() : void; error(message:string): void; } export interface IJSONWorkerContribution { getInfoContribution(resource: URI, location: JSONLocation) : WinJS.TPromise<HtmlContent.IHTMLContentElement[]>; collectPropertySuggestions(resource: URI, location: JSONLocation, currentWord: string, addValue: boolean, isLast:boolean, result: ISuggestionsCollector) : WinJS.Promise; collectValueSuggestions(resource: URI, location: JSONLocation, propertyKey: string, result: ISuggestionsCollector): WinJS.Promise; collectDefaultSuggestions(resource: URI, result: ISuggestionsCollector): WinJS.Promise; } export class JSONWorker implements Modes.IExtraInfoSupport { private schemaService: SchemaService.IJSONSchemaService; private requestService: IRequestService; private contextService: IWorkspaceContextService; private jsonIntellisense : JSONIntellisense.JSONIntellisense; private contributions: IJSONWorkerContribution[]; private _validationHelper: ValidationHelper; private resourceService:IResourceService; private markerService: IMarkerService; private _modeId: string; constructor( modeId: string, @IResourceService resourceService: IResourceService, @IMarkerService markerService: IMarkerService, @IRequestService requestService: IRequestService, @IWorkspaceContextService contextService: IWorkspaceContextService, @IInstantiationService instantiationService: IInstantiationService ) { this._modeId = modeId; this.resourceService = resourceService; this.markerService = markerService; this._validationHelper = new ValidationHelper( this.resourceService, this._modeId, (toValidate) => this.doValidate(toValidate) ); this.requestService = requestService; this.contextService = contextService; this.schemaService = instantiationService.createInstance(SchemaService.JSONSchemaService); this.contributions = [ instantiationService.createInstance(ProjectJSONContribution.ProjectJSONContribution), instantiationService.createInstance(PackageJSONContribution.PackageJSONContribution), instantiationService.createInstance(BowerJSONContribution.BowerJSONContribution), instantiationService.createInstance(GlobPatternContribution.GlobPatternContribution) ]; this.jsonIntellisense = new JSONIntellisense.JSONIntellisense(this.schemaService, this.requestService, this.contributions); } public navigateValueSet(resource:URI, range:EditorCommon.IRange, up:boolean):WinJS.TPromise<Modes.IInplaceReplaceSupportResult> { var modelMirror = this.resourceService.get(resource); var offset = modelMirror.getOffsetFromPosition({ lineNumber: range.startLineNumber, column: range.startColumn }); var parser = new Parser.JSONParser(); var config = new Parser.JSONDocumentConfig(); config.ignoreDanglingComma = true; var doc = parser.parse(modelMirror.getValue(), config); var node = doc.getNodeFromOffsetEndInclusive(offset); if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) { return this.schemaService.getSchemaForResource(resource.toString(), doc).then((schema) => { if (schema) { var proposals : Modes.ISuggestion[] = []; var proposed: any = {}; var collector = { add: (suggestion: Modes.ISuggestion) => { if (!proposed[suggestion.label]) { proposed[suggestion.label] = true; proposals.push(suggestion); } }, setAsIncomplete: () => { /* ignore */ }, error: (message: string) => { errors.onUnexpectedError(message); } }; this.jsonIntellisense.getValueSuggestions(resource, schema, doc, node.parent, node.start, collector); var range = modelMirror.getRangeFromOffsetAndLength(node.start, node.end - node.start); var text = modelMirror.getValueInRange(range); for (var i = 0, len = proposals.length; i < len; i++) { if (Strings.equalsIgnoreCase(proposals[i].label, text)) { var nextIdx = i; if (up) { nextIdx = (i + 1) % len; } else { nextIdx = i - 1; if (nextIdx < 0) { nextIdx = len - 1; } } return { value: proposals[nextIdx].label, range: range }; } } return null; } }); } return null; } /** * @return true if you want to revalidate your models */ _doConfigure(options:IOptions): WinJS.TPromise<void> { if (options && options.schemas) { this.schemaService.clearExternalSchemas(); options.schemas.forEach((schema) => { if (schema.url && (schema.fileMatch || schema.schema)) { var url = schema.url; if (!Strings.startsWith(url, 'http://') && !Strings.startsWith(url, 'https://') && !Strings.startsWith(url, 'file://')) { var resourceURL = this.contextService.toResource(url); if (resourceURL) { url = resourceURL.toString(); } } if (url) { this.schemaService.registerExternalSchema(url, schema.fileMatch, schema.schema); } } else if (schema.filePattern && schema.schemaPath) { var url = this.contextService.toResource(schema.schemaPath).toString(); var patterns = schema.filePattern ? [ schema.filePattern ] : []; this.schemaService.registerExternalSchema(url, patterns); } }); } this._validationHelper.triggerDueToConfigurationChange(); return WinJS.TPromise.as(void 0); } public setSchemaContributions(contributions:ISchemaContributions): WinJS.TPromise<boolean> { this.schemaService.setSchemaContributions(contributions); return WinJS.TPromise.as(true); } public enableValidator(): WinJS.TPromise<void> { this._validationHelper.enable(); return WinJS.TPromise.as(null); } public doValidate(resources: URI[]):void { for (var i = 0; i < resources.length; i++) { this.doValidate1(resources[i]); } } private doValidate1(resource: URI):void { var modelMirror = this.resourceService.get(resource); var parser = new Parser.JSONParser(); var content = modelMirror.getValue(); if (content.length === 0) { // ignore empty content, no marker can be set anyway return; } var result = parser.parse(content); this.schemaService.getSchemaForResource(resource.toString(), result).then((schema) => { if (schema) { if (schema.errors.length && result.root) { var property = result.root.type === 'object' ? (<Parser.ObjectASTNode> result.root).getFirstProperty('$schema') : null; if (property) { var node = property.value || property; result.warnings.push({ location: { start: node.start, end: node.end }, message: schema.errors[0] }); } else { result.warnings.push({ location: { start: result.root.start, end: result.root.start + 1 }, message: schema.errors[0] }); } } else { result.validate(schema.schema); } } var added : { [signature:string]: boolean} = {}; var markerData: IMarkerData[] = []; result.errors.concat(result.warnings).forEach((error, idx) => { // remove duplicated messages var signature = error.location.start + ' ' + error.location.end + ' ' + error.message; if (!added[signature]) { added[signature] = true; var startPosition = modelMirror.getPositionFromOffset(error.location.start); var endPosition = modelMirror.getPositionFromOffset(error.location.end); markerData.push({ message: error.message, severity: idx >= result.errors.length ? Severity.Warning : Severity.Error, startLineNumber: startPosition.lineNumber, startColumn: startPosition.column, endLineNumber: endPosition.lineNumber, endColumn: endPosition.column }); } }); this.markerService.changeOne(this._modeId, resource, markerData); }); } public suggest(resource:URI, position:EditorCommon.IPosition):WinJS.TPromise<Modes.ISuggestResult[]> { return this.doSuggest(resource, position).then(value => filterSuggestions(value)); } private doSuggest(resource:URI, position:EditorCommon.IPosition):WinJS.TPromise<Modes.ISuggestResult> { var modelMirror = this.resourceService.get(resource); return this.jsonIntellisense.doSuggest(resource, modelMirror, position); } public computeInfo(resource:URI, position:EditorCommon.IPosition): WinJS.TPromise<Modes.IComputeExtraInfoResult> { var modelMirror = this.resourceService.get(resource); var parser = new Parser.JSONParser(); var doc = parser.parse(modelMirror.getValue()); var offset = modelMirror.getOffsetFromPosition(position); var node = doc.getNodeFromOffset(offset); var originalNode = node; // use the property description when hovering over an object key if (node && node.type === 'string') { var stringNode = <Parser.StringASTNode>node; if (stringNode.isKey) { var propertyNode = <Parser.PropertyASTNode>node.parent; node = propertyNode.value; } } if (!node) { return WinJS.TPromise.as(null); } return this.schemaService.getSchemaForResource(resource.toString(), doc).then((schema) => { if (schema) { var matchingSchemas : Parser.IApplicableSchema[] = []; doc.validate(schema.schema, matchingSchemas, node.start); var description: string = null; var contributonId: string = null; matchingSchemas.every((s) => { if (s.node === node && !s.inverted && s.schema) { description = description || s.schema.description; contributonId = contributonId || s.schema.id; } return true; }); var location = node.getNodeLocation(); for (var i= this.contributions.length -1; i >= 0; i--) { var contribution = this.contributions[i]; var promise = contribution.getInfoContribution(resource, location); if (promise) { return promise.then((htmlContent) => { return this.createInfoResult(htmlContent, originalNode, modelMirror); } ); } } if (description) { var htmlContent = [ {className: 'documentation', text: description } ]; return this.createInfoResult(htmlContent, originalNode, modelMirror); } } return null; }); } private createInfoResult(htmlContent : HtmlContent.IHTMLContentElement[], node: Parser.ASTNode, modelMirror: EditorCommon.IMirrorModel) : Modes.IComputeExtraInfoResult { var range = modelMirror.getRangeFromOffsetAndLength(node.start, node.end - node.start); var result:Modes.IComputeExtraInfoResult = { value: '', htmlContent: htmlContent, className: 'typeInfo json', range: range }; return result; } public getOutline(resource:URI):WinJS.TPromise<Modes.IOutlineEntry[]> { var modelMirror = this.resourceService.get(resource); var parser = new Parser.JSONParser(); var doc = parser.parse(modelMirror.getValue()); var root = doc.root; if (!root) { return WinJS.TPromise.as(null); } // special handling for key bindings var resourceString = resource.toString(); if ((resourceString === 'vscode://defaultsettings/keybindings.json') || Strings.endsWith(resourceString.toLowerCase(), '/user/keybindings.json')) { if (root.type === 'array') { var result : Modes.IOutlineEntry[] = []; (<Parser.ArrayASTNode> root).items.forEach((item) => { if (item.type === 'object') { var property = (<Parser.ObjectASTNode> item).getFirstProperty('key'); if (property && property.value) { var range = modelMirror.getRangeFromOffsetAndLength(item.start, item.end - item.start); result.push({ label: property.value.getValue(), icon: 'function', type: 'string', range: range, children: []}); } } }); return WinJS.TPromise.as(result); } } function collectOutlineEntries(result: Modes.IOutlineEntry[], node: Parser.ASTNode): Modes.IOutlineEntry[] { if (node.type === 'array') { (<Parser.ArrayASTNode>node).items.forEach((node:Parser.ASTNode) => { collectOutlineEntries(result, node); }); } else if (node.type === 'object') { var objectNode = <Parser.ObjectASTNode>node; objectNode.properties.forEach((property:Parser.PropertyASTNode) => { var range = modelMirror.getRangeFromOffsetAndLength(property.start, property.end - property.start); var valueNode = property.value; if (valueNode) { var children = collectOutlineEntries([], valueNode); var icon = valueNode.type === 'object' ? 'module' : valueNode.type; result.push({ label: property.key.getValue(), icon: icon, type: valueNode.type, range: range, children: children}); } }); } return result; } var result = collectOutlineEntries([], root); return WinJS.TPromise.as(result); } public format(resource: URI, range: EditorCommon.IRange, options: Modes.IFormattingOptions): WinJS.TPromise<EditorCommon.ISingleEditOperation[]> { var model = this.resourceService.get(resource); return WinJS.TPromise.as(JSONFormatter.format(model, range, options)); } }
sifue/vscode
src/vs/languages/json/common/jsonWorker.ts
TypeScript
mit
15,489
using Machine.Specifications; using PlainElastic.Net.IndexSettings; using PlainElastic.Net.Utils; namespace PlainElastic.Net.Tests.Builders.IndexSettings { [Subject(typeof(StandardAnalyzer))] class When_complete_StandardAnalyzer_built { Because of = () => result = new StandardAnalyzer() .Name("name") .Version("3.5") .Alias("second", "third") .Stopwords("stop", "word") .StopwordsPath("stopwords path") .MaxTokenLength(10) .CustomPart("{ Custom }") .ToString(); It should_start_with_name = () => result.ShouldStartWith("'name': {".AltQuote()); It should_contain_type_part = () => result.ShouldContain("'type': 'standard'".AltQuote()); It should_contain_version_part = () => result.ShouldContain("'version': '3.5'".AltQuote()); It should_contain_alias_part = () => result.ShouldContain("'alias': [ 'second','third' ]".AltQuote()); It should_contain_stopwords_part = () => result.ShouldContain("'stopwords': [ 'stop','word' ]".AltQuote()); It should_contain_stopwords_path_part = () => result.ShouldContain("'stopwords_path': 'stopwords path'".AltQuote()); It should_contain_max_token_length_part = () => result.ShouldContain("'max_token_length': 10".AltQuote()); It should_contain_custom_part = () => result.ShouldContain("{ Custom }".AltQuote()); It should_return_correct_result = () => result.ShouldEqual(("'name': { " + "'type': 'standard'," + "'version': '3.5'," + "'alias': [ 'second','third' ]," + "'stopwords': [ 'stop','word' ]," + "'stopwords_path': 'stopwords path'," + "'max_token_length': 10," + "{ Custom } }").AltQuote()); private static string result; } }
mbinot/PlainElastic.Net
src/PlainElastic.Net.Tests/Builders/Analysis/Analyzers/Standard/When_complete_StandardAnalyzer_built.cs
C#
mit
2,524
const path = require(`path`) exports.chunkNamer = chunk => { if (chunk.name) return chunk.name let n = [] chunk.forEachModule(m => { n.push(path.relative(m.context, m.userRequest)) }) return n.join(`_`) }
mingaldrichgan/gatsby
packages/gatsby/src/utils/webpack-helpers.js
JavaScript
mit
220
<?php require_once(dirname(__FILE__)."/../pages/icalendar/icalendar_functions.php"); function init_calendar() { return ' '.schedule_icalendar_tostring().' '.schedule_calendar_preview().' <input type=\'button\' style=\'display:none;\' name=\'onselect\' />'; } function schedule_calendar_preview() { $s_header = ' <table class=\'table_title\'><tr><td> <div class=\'centered\'>Calendar Preview</div> </td></tr></table>'; return $s_header." <div id='calendar_preview' class='centered'>&nbsp;</div>"; } function schedule_icalendar_tostring() { global $global_user; $s_header = ''; if ($global_user->get_name() == "guest") { return ' <table class=\'table_title\'><tr><td> <div class=\'centered\'>Download Semester Calendar</div> </td></tr></table> <div class=\'centered\'><a class=\'icalendarGuestDownloadLink\' href=\'\' target=\'_blank\'>Download</a></div> <br />'; } else { $s_header = ' <table class=\'table_title\'><tr><td> <div class=\'centered\'>Export Full Calendar</div> </td></tr></table>'; } if ($global_user->get_server_setting('enable_icalendar') != '1') { return $s_header." <div class='centered'>You don't have the calendar exports enabled.<br /> Go to the <a href='#scroll_to_element' onclick='draw_tab(\"settings\");'>Settings Tab</a>, check \"Enable icalendar,\" and click \"Save\" to enable.</div><br />"; } $s_web_link = icalendarFunctions::calendarLinkToString("web"); $s_view_link = icalendarFunctions::calendarLinkToString("view"); $s_download_link = icalendarFunctions::calendarLinkToString("download"); return $s_header.' <div class=\'centered\'>'.": <a href='#scroll_to_element' onclick='scrollWindowCurrent(); o_schedule.drawicalendarLink();'>Link To Calendar</a> : <a href='$s_download_link' target='_blank'>Download Calendar</a> : <a href='http://nmt.edu/~bbean/banweb/icalendar/exporting.html' target=\'_blank\'>Help</a> :".'</div> <div class=\'centered\' id=\'icalendar_reveal_link\' style=\'display:none;\'><input type=\'textarea\' value=\''.$s_web_link.'\'></input></div> <br />'; } $tab_init_function = 'init_calendar'; ?>
nocylah/banwebplus
tabs/Calendar.php
PHP
mit
2,095
/* Copyright 2017 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package fakevtworkerclient contains a fake for the vtworkerclient interface. package fakevtworkerclient import ( "time" "golang.org/x/net/context" "github.com/youtube/vitess/go/vt/logutil" "github.com/youtube/vitess/go/vt/vtctl/fakevtctlclient" "github.com/youtube/vitess/go/vt/worker/vtworkerclient" ) // FakeVtworkerClient is a fake which implements the vtworkerclient interface. // The fake can be used to return a specific result for a given command. // If the command is not registered, an error will be thrown. type FakeVtworkerClient struct { *fakevtctlclient.FakeLoggerEventStreamingClient } // NewFakeVtworkerClient creates a FakeVtworkerClient struct. func NewFakeVtworkerClient() *FakeVtworkerClient { return &FakeVtworkerClient{fakevtctlclient.NewFakeLoggerEventStreamingClient()} } // FakeVtworkerClientFactory returns the current instance and stores the // dialed server address in an outer struct. func (f *FakeVtworkerClient) FakeVtworkerClientFactory(addr string, dialTimeout time.Duration) (vtworkerclient.Client, error) { return &perAddrFakeVtworkerClient{f, addr}, nil } // perAddrFakeVtworkerClient is a client instance which captures the server // address which was dialed by the client. type perAddrFakeVtworkerClient struct { *FakeVtworkerClient addr string } // ExecuteVtworkerCommand is part of the vtworkerclient interface. func (c *perAddrFakeVtworkerClient) ExecuteVtworkerCommand(ctx context.Context, args []string) (logutil.EventStream, error) { return c.FakeLoggerEventStreamingClient.StreamResult(c.addr, args) } // Close is part of the vtworkerclient interface. func (c *perAddrFakeVtworkerClient) Close() {}
NazarethCollege/heweb2017-devops-presentation
sites/tweetheat/src/backend/vendor/src/github.com/youtube/vitess/go/vt/worker/fakevtworkerclient/fakevtworkerclient.go
GO
mit
2,225
<?php /** * @package WPSEO\Main */ if ( ! function_exists( 'add_filter' ) ) { header( 'Status: 403 Forbidden' ); header( 'HTTP/1.1 403 Forbidden' ); exit(); } /** * @internal Nobody should be able to overrule the real version number as this can cause serious issues * with the options, so no if ( ! defined() ) */ define( 'WPSEO_VERSION', '4.3' ); if ( ! defined( 'WPSEO_PATH' ) ) { define( 'WPSEO_PATH', plugin_dir_path( WPSEO_FILE ) ); } if ( ! defined( 'WPSEO_BASENAME' ) ) { define( 'WPSEO_BASENAME', plugin_basename( WPSEO_FILE ) ); } /* ***************************** CLASS AUTOLOADING *************************** */ /** * Auto load our class files * * @param string $class Class name. * * @return void */ function wpseo_auto_load( $class ) { static $classes = null; if ( $classes === null ) { $classes = array( 'wp_list_table' => ABSPATH . 'wp-admin/includes/class-wp-list-table.php', 'walker_category' => ABSPATH . 'wp-includes/category-template.php', 'pclzip' => ABSPATH . 'wp-admin/includes/class-pclzip.php', ); } $cn = strtolower( $class ); if ( ! class_exists( $class ) && isset( $classes[ $cn ] ) ) { require_once( $classes[ $cn ] ); } } if ( file_exists( WPSEO_PATH . '/vendor/autoload_52.php' ) ) { require WPSEO_PATH . '/vendor/autoload_52.php'; } elseif ( ! class_exists( 'WPSEO_Options' ) ) { // Still checking since might be site-level autoload R. add_action( 'admin_init', 'yoast_wpseo_missing_autoload', 1 ); return; } if ( function_exists( 'spl_autoload_register' ) ) { spl_autoload_register( 'wpseo_auto_load' ); } /* ********************* DEFINES DEPENDING ON AUTOLOADED CODE ********************* */ /** * Defaults to production, for safety */ if ( ! defined( 'YOAST_ENVIRONMENT' ) ) { define( 'YOAST_ENVIRONMENT', 'production' ); } /** * Only use minified assets when we are in a production environment */ if ( ! defined( 'WPSEO_CSSJS_SUFFIX' ) ) { define( 'WPSEO_CSSJS_SUFFIX', ( 'development' !== YOAST_ENVIRONMENT ) ? '.min' : '' ); } /* ***************************** PLUGIN (DE-)ACTIVATION *************************** */ /** * Run single site / network-wide activation of the plugin. * * @param bool $networkwide Whether the plugin is being activated network-wide. */ function wpseo_activate( $networkwide = false ) { if ( ! is_multisite() || ! $networkwide ) { _wpseo_activate(); } else { /* Multi-site network activation - activate the plugin for all blogs */ wpseo_network_activate_deactivate( true ); } } /** * Run single site / network-wide de-activation of the plugin. * * @param bool $networkwide Whether the plugin is being de-activated network-wide. */ function wpseo_deactivate( $networkwide = false ) { if ( ! is_multisite() || ! $networkwide ) { _wpseo_deactivate(); } else { /* Multi-site network activation - de-activate the plugin for all blogs */ wpseo_network_activate_deactivate( false ); } } /** * Run network-wide (de-)activation of the plugin * * @param bool $activate True for plugin activation, false for de-activation. */ function wpseo_network_activate_deactivate( $activate = true ) { global $wpdb; $network_blogs = $wpdb->get_col( $wpdb->prepare( "SELECT blog_id FROM $wpdb->blogs WHERE site_id = %d", $wpdb->siteid ) ); if ( is_array( $network_blogs ) && $network_blogs !== array() ) { foreach ( $network_blogs as $blog_id ) { switch_to_blog( $blog_id ); if ( $activate === true ) { _wpseo_activate(); } else { _wpseo_deactivate(); } restore_current_blog(); } } } /** * Runs on activation of the plugin. */ function _wpseo_activate() { require_once( WPSEO_PATH . 'inc/wpseo-functions.php' ); require_once( WPSEO_PATH . 'inc/class-wpseo-installation.php' ); wpseo_load_textdomain(); // Make sure we have our translations available for the defaults. new WPSEO_Installation(); WPSEO_Options::get_instance(); if ( ! is_multisite() ) { WPSEO_Options::initialize(); } else { WPSEO_Options::maybe_set_multisite_defaults( true ); } WPSEO_Options::ensure_options_exist(); if ( is_multisite() && ms_is_switched() ) { delete_option( 'rewrite_rules' ); } else { $wpseo_rewrite = new WPSEO_Rewrite(); $wpseo_rewrite->schedule_flush(); } wpseo_add_capabilities(); // Clear cache so the changes are obvious. WPSEO_Utils::clear_cache(); do_action( 'wpseo_activate' ); } /** * On deactivation, flush the rewrite rules so XML sitemaps stop working. */ function _wpseo_deactivate() { require_once( WPSEO_PATH . 'inc/wpseo-functions.php' ); if ( is_multisite() && ms_is_switched() ) { delete_option( 'rewrite_rules' ); } else { add_action( 'shutdown', 'flush_rewrite_rules' ); } wpseo_remove_capabilities(); // Clear cache so the changes are obvious. WPSEO_Utils::clear_cache(); do_action( 'wpseo_deactivate' ); } /** * Run wpseo activation routine on creation / activation of a multisite blog if WPSEO is activated * network-wide. * * Will only be called by multisite actions. * * @internal Unfortunately will fail if the plugin is in the must-use directory * @see https://core.trac.wordpress.org/ticket/24205 * * @param int $blog_id Blog ID. */ function wpseo_on_activate_blog( $blog_id ) { if ( ! function_exists( 'is_plugin_active_for_network' ) ) { require_once( ABSPATH . '/wp-admin/includes/plugin.php' ); } if ( is_plugin_active_for_network( plugin_basename( WPSEO_FILE ) ) ) { switch_to_blog( $blog_id ); wpseo_activate( false ); restore_current_blog(); } } /* ***************************** PLUGIN LOADING *************************** */ /** * Load translations */ function wpseo_load_textdomain() { $wpseo_path = str_replace( '\\', '/', WPSEO_PATH ); $mu_path = str_replace( '\\', '/', WPMU_PLUGIN_DIR ); if ( false !== stripos( $wpseo_path, $mu_path ) ) { load_muplugin_textdomain( 'wordpress-seo', dirname( WPSEO_BASENAME ) . '/languages/' ); } else { load_plugin_textdomain( 'wordpress-seo', false, dirname( WPSEO_BASENAME ) . '/languages/' ); } } add_action( 'plugins_loaded', 'wpseo_load_textdomain' ); /** * On plugins_loaded: load the minimum amount of essential files for this plugin */ function wpseo_init() { require_once( WPSEO_PATH . 'inc/wpseo-functions.php' ); require_once( WPSEO_PATH . 'inc/wpseo-functions-deprecated.php' ); // Make sure our option and meta value validation routines and default values are always registered and available. WPSEO_Options::get_instance(); WPSEO_Meta::init(); $options = WPSEO_Options::get_options( array( 'wpseo', 'wpseo_permalinks', 'wpseo_xml' ) ); if ( version_compare( $options['version'], WPSEO_VERSION, '<' ) ) { new WPSEO_Upgrade(); // Get a cleaned up version of the $options. $options = WPSEO_Options::get_options( array( 'wpseo', 'wpseo_permalinks', 'wpseo_xml' ) ); } if ( $options['stripcategorybase'] === true ) { $GLOBALS['wpseo_rewrite'] = new WPSEO_Rewrite; } if ( $options['enablexmlsitemap'] === true ) { $GLOBALS['wpseo_sitemaps'] = new WPSEO_Sitemaps; } if ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) { require_once( WPSEO_PATH . 'inc/wpseo-non-ajax-functions.php' ); } // Init it here because the filter must be present on the frontend as well or it won't work in the customizer. new WPSEO_Customizer(); } /** * Loads the rest api endpoints. */ function wpseo_init_rest_api() { // We can't do anything when requirements are not met. if ( WPSEO_Utils::is_api_available() ) { // Boot up REST API. $configuration_service = new WPSEO_Configuration_Service(); $configuration_service->initialize(); } } /** * Used to load the required files on the plugins_loaded hook, instead of immediately. */ function wpseo_frontend_init() { add_action( 'init', 'initialize_wpseo_front' ); $options = WPSEO_Options::get_option( 'wpseo_internallinks' ); if ( $options['breadcrumbs-enable'] === true ) { /** * If breadcrumbs are active (which they supposedly are if the users has enabled this settings, * there's no reason to have bbPress breadcrumbs as well. * * @internal The class itself is only loaded when the template tag is encountered via * the template tag function in the wpseo-functions.php file */ add_filter( 'bbp_get_breadcrumb', '__return_false' ); } add_action( 'template_redirect', 'wpseo_frontend_head_init', 999 ); } /** * Instantiate the different social classes on the frontend */ function wpseo_frontend_head_init() { $options = WPSEO_Options::get_option( 'wpseo_social' ); if ( $options['twitter'] === true ) { add_action( 'wpseo_head', array( 'WPSEO_Twitter', 'get_instance' ), 40 ); } if ( $options['opengraph'] === true ) { $GLOBALS['wpseo_og'] = new WPSEO_OpenGraph; } } /** * Used to load the required files on the plugins_loaded hook, instead of immediately. */ function wpseo_admin_init() { new WPSEO_Admin_Init(); } /* ***************************** BOOTSTRAP / HOOK INTO WP *************************** */ $spl_autoload_exists = function_exists( 'spl_autoload_register' ); $filter_exists = function_exists( 'filter_input' ); if ( ! $spl_autoload_exists ) { add_action( 'admin_init', 'yoast_wpseo_missing_spl', 1 ); } if ( ! $filter_exists ) { add_action( 'admin_init', 'yoast_wpseo_missing_filter', 1 ); } if ( ! function_exists( 'wp_installing' ) ) { /** * We need to define wp_installing in WordPress versions older than 4.4 * * @return bool */ function wp_installing() { return defined( 'WP_INSTALLING' ); } } if ( ! wp_installing() && ( $spl_autoload_exists && $filter_exists ) ) { add_action( 'plugins_loaded', 'wpseo_init', 14 ); add_action( 'rest_api_init', 'wpseo_init_rest_api' ); if ( is_admin() ) { new Yoast_Alerts(); if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) { require_once( WPSEO_PATH . 'admin/ajax.php' ); // Plugin conflict ajax hooks. new Yoast_Plugin_Conflict_Ajax(); if ( filter_input( INPUT_POST, 'action' ) === 'inline-save' ) { add_action( 'plugins_loaded', 'wpseo_admin_init', 15 ); } } else { add_action( 'plugins_loaded', 'wpseo_admin_init', 15 ); } } else { add_action( 'plugins_loaded', 'wpseo_frontend_init', 15 ); } add_action( 'plugins_loaded', 'load_yoast_notifications' ); } // Activation and deactivation hook. register_activation_hook( WPSEO_FILE, 'wpseo_activate' ); register_deactivation_hook( WPSEO_FILE, 'wpseo_deactivate' ); add_action( 'wpmu_new_blog', 'wpseo_on_activate_blog' ); add_action( 'activate_blog', 'wpseo_on_activate_blog' ); // Loading OnPage integration. new WPSEO_OnPage(); /** * Wraps for notifications center class. */ function load_yoast_notifications() { // Init Yoast_Notification_Center class. Yoast_Notification_Center::get(); } /** * Throw an error if the PHP SPL extension is disabled (prevent white screens) and self-deactivate plugin * * @since 1.5.4 * * @return void */ function yoast_wpseo_missing_spl() { if ( is_admin() ) { add_action( 'admin_notices', 'yoast_wpseo_missing_spl_notice' ); yoast_wpseo_self_deactivate(); } } /** * Returns the notice in case of missing spl extension */ function yoast_wpseo_missing_spl_notice() { $message = esc_html__( 'The Standard PHP Library (SPL) extension seem to be unavailable. Please ask your web host to enable it.', 'wordpress-seo' ); yoast_wpseo_activation_failed_notice( $message ); } /** * Throw an error if the Composer autoload is missing and self-deactivate plugin * * @return void */ function yoast_wpseo_missing_autoload() { if ( is_admin() ) { add_action( 'admin_notices', 'yoast_wpseo_missing_autoload_notice' ); yoast_wpseo_self_deactivate(); } } /** * Returns the notice in case of missing Composer autoload */ function yoast_wpseo_missing_autoload_notice() { /* translators: %1$s expands to Yoast SEO, %2$s / %3$s: links to the installation manual in the Readme for the Yoast SEO code repository on GitHub */ $message = esc_html__( 'The %1$s plugin installation is incomplete. Please refer to %2$sinstallation instructions%3$s.', 'wordpress-seo' ); $message = sprintf( $message, 'Yoast SEO', '<a href="https://github.com/Yoast/wordpress-seo#installation">', '</a>' ); yoast_wpseo_activation_failed_notice( $message ); } /** * Throw an error if the filter extension is disabled (prevent white screens) and self-deactivate plugin * * @since 2.0 * * @return void */ function yoast_wpseo_missing_filter() { if ( is_admin() ) { add_action( 'admin_notices', 'yoast_wpseo_missing_filter_notice' ); yoast_wpseo_self_deactivate(); } } /** * Returns the notice in case of missing filter extension */ function yoast_wpseo_missing_filter_notice() { $message = esc_html__( 'The filter extension seem to be unavailable. Please ask your web host to enable it.', 'wordpress-seo' ); yoast_wpseo_activation_failed_notice( $message ); } /** * Echo's the Activation failed notice with any given message. * * @param string $message Message string. */ function yoast_wpseo_activation_failed_notice( $message ) { echo '<div class="error"><p>' . __( 'Activation failed:', 'wordpress-seo' ) . ' ' . $message . '</p></div>'; } /** * The method will deactivate the plugin, but only once, done by the static $is_deactivated */ function yoast_wpseo_self_deactivate() { static $is_deactivated; if ( $is_deactivated === null ) { $is_deactivated = true; deactivate_plugins( plugin_basename( WPSEO_FILE ) ); if ( isset( $_GET['activate'] ) ) { unset( $_GET['activate'] ); } } }
michaelbontyes/ekogito
wp-content/plugins/wordpress-seo/wp-seo-main.php
PHP
mit
13,520
var engine = require('../'); var express = require('express'); var path = require('path'); var app = express(); app.engine('dot', engine.__express); app.set('views', path.join(__dirname, './views')); app.set('view engine', 'dot'); app.get('/', function(req, res) { res.render('index', { fromServer: 'Hello from server', }); }); app.get('/layout', function(req, res) { res.render('layout/index'); }); app.get('/cascade', function(req, res) { res.render('cascade/me'); }); app.get('/partial', function(req, res) { res.render('partial/index'); }); app.get('/helper', function(req, res) { // helper as a property engine.helper.myHelperProperty = 'Hello from server property helper'; // helper as a method engine.helper.myHelperMethod = function(param) { return 'Hello from server method helper (parameter: ' + param + ', server model: ' + this.model.fromServer + ')'; } res.render('helper/index', { fromServer: 'Hello from server', }); }); var server = app.listen(2015, function() { console.log('Run the example at http://locahost:%d', server.address().port); });
danlevan/express-dot-engine
examples/index.js
JavaScript
mit
1,097
using UnityEngine; using System.Collections; using System.Collections.Generic; namespace Fungus { [CommandInfo("Flow", "If", "If the test expression is true, execute the following command block.")] [AddComponentMenu("")] public class If : Condition { [Tooltip("Variable to use in expression")] [VariableProperty(typeof(BooleanVariable), typeof(IntegerVariable), typeof(FloatVariable), typeof(StringVariable))] public Variable variable; [Tooltip("Boolean value to compare against")] public BooleanData booleanData; [Tooltip("Integer value to compare against")] public IntegerData integerData; [Tooltip("Float value to compare against")] public FloatData floatData; [Tooltip("String value to compare against")] public StringData stringData; public override void OnEnter() { if (parentBlock == null) { return; } if (variable == null) { Continue(); return; } EvaluateAndContinue(); } public bool EvaluateCondition() { BooleanVariable booleanVariable = variable as BooleanVariable; IntegerVariable integerVariable = variable as IntegerVariable; FloatVariable floatVariable = variable as FloatVariable; StringVariable stringVariable = variable as StringVariable; bool condition = false; if (booleanVariable != null) { condition = booleanVariable.Evaluate(compareOperator, booleanData.Value); } else if (integerVariable != null) { condition = integerVariable.Evaluate(compareOperator, integerData.Value); } else if (floatVariable != null) { condition = floatVariable.Evaluate(compareOperator, floatData.Value); } else if (stringVariable != null) { condition = stringVariable.Evaluate(compareOperator, stringData.Value); } return condition; } protected void EvaluateAndContinue() { if (EvaluateCondition()) { OnTrue(); } else { OnFalse(); } } protected virtual void OnTrue() { Continue(); } protected virtual void OnFalse() { // Last command in block if (commandIndex >= parentBlock.commandList.Count) { Stop(); return; } // Find the next Else, ElseIf or End command at the same indent level as this If command for (int i = commandIndex + 1; i < parentBlock.commandList.Count; ++i) { Command nextCommand = parentBlock.commandList[i]; if (nextCommand == null) { continue; } // Find next command at same indent level as this If command // Skip disabled commands, comments & labels if (!nextCommand.enabled || nextCommand.GetType() == typeof(Comment) || nextCommand.GetType() == typeof(Label) || nextCommand.indentLevel != indentLevel) { continue; } System.Type type = nextCommand.GetType(); if (type == typeof(Else) || type == typeof(End)) { if (i >= parentBlock.commandList.Count - 1) { // Last command in Block, so stop Stop(); } else { // Execute command immediately after the Else or End command Continue(nextCommand.commandIndex + 1); return; } } else if (type == typeof(ElseIf)) { // Execute the Else If command Continue(i); return; } } // No matching End command found, so just stop the block Stop(); } public override string GetSummary() { if (variable == null) { return "Error: No variable selected"; } string summary = variable.key + " "; summary += Condition.GetOperatorDescription(compareOperator) + " "; if (variable.GetType() == typeof(BooleanVariable)) { summary += booleanData.GetDescription(); } else if (variable.GetType() == typeof(IntegerVariable)) { summary += integerData.GetDescription(); } else if (variable.GetType() == typeof(FloatVariable)) { summary += floatData.GetDescription(); } else if (variable.GetType() == typeof(StringVariable)) { summary += stringData.GetDescription(); } return summary; } public override bool HasReference(Variable variable) { return (variable == this.variable); } public override bool OpenBlock() { return true; } public override Color GetButtonColor() { return new Color32(253, 253, 150, 255); } } }
RonanPearce/Fungus
Assets/Fungus/Flowchart/Scripts/Commands/If.cs
C#
mit
4,397
var EventEmitter = require('events').EventEmitter; var util = require('util'); var WSProcessor = require('./wsprocessor'); var TCPProcessor = require('./tcpprocessor'); var logger = require('pomelo-logger').getLogger('pomelo', __filename); var HTTP_METHODS = [ 'GET', 'POST', 'DELETE', 'PUT', 'HEAD' ]; var ST_STARTED = 1; var ST_CLOSED = 2; var DEFAULT_TIMEOUT = 90; /** * Switcher for tcp and websocket protocol * * @param {Object} server tcp server instance from node.js net module */ var Switcher = function(server, opts) { EventEmitter.call(this); this.server = server; this.wsprocessor = new WSProcessor(); this.tcpprocessor = new TCPProcessor(opts.closeMethod); this.id = 1; this.timers = {}; this.timeout = opts.timeout || DEFAULT_TIMEOUT; this.setNoDelay = opts.setNoDelay; this.server.on('connection', this.newSocket.bind(this)); this.wsprocessor.on('connection', this.emit.bind(this, 'connection')); this.tcpprocessor.on('connection', this.emit.bind(this, 'connection')); this.state = ST_STARTED; }; util.inherits(Switcher, EventEmitter); module.exports = Switcher; Switcher.prototype.newSocket = function(socket) { if(this.state !== ST_STARTED) { return; } // if set connection timeout if(!!this.timeout) { var timer = setTimeout(function() { logger.warn('connection is timeout without communication, the remote ip is %s && port is %s', socket.remoteAddress, socket.remotePort); socket.destroy(); }, this.timeout * 1000); this.timers[this.id] = timer; socket.id = this.id++; } var self = this; socket.once('close', function() { if (!!socket.id) { clearTimeout(self.timers[socket.id]); delete self.timers[socket.id]; } }); socket.once('data', function(data) { if(!!socket.id) { clearTimeout(self.timers[socket.id]); delete self.timers[socket.id]; } if(isHttp(data)) { processHttp(self, self.wsprocessor, socket, data); } else { if(!!self.setNoDelay) { socket.setNoDelay(true); } processTcp(self, self.tcpprocessor, socket, data); } }); }; Switcher.prototype.close = function() { if(this.state !== ST_STARTED) { return; } this.state = ST_CLOSED; this.wsprocessor.close(); this.tcpprocessor.close(); }; var isHttp = function(data) { var head = data.toString('utf8', 0, 4); for(var i=0, l=HTTP_METHODS.length; i<l; i++) { if(head.indexOf(HTTP_METHODS[i]) === 0) { return true; } } return false; }; var processHttp = function(switcher, processor, socket, data) { processor.add(socket, data); }; var processTcp = function(switcher, processor, socket, data) { processor.add(socket, data); };
zdqk/pomelo
lib/connectors/hybrid/switcher.js
JavaScript
mit
2,721
using System; using PlainElastic.Net.Utils; namespace PlainElastic.Net.IndexSettings { /// <summary> /// Allows to configure token filters to be used in custom analyzers. /// </summary> public class TokenFilterSettings : SettingsBase<TokenFilterSettings> { #region Asciifolding /// <summary> /// A token filter of type asciifolding that converts alphabetic, numeric, and symbolic Unicode characters /// which are not in the first 127 ASCII characters (the "Basic Latin" Unicode block) into their ASCII equivalents, if one exists. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/asciifolding-tokenfilter.html /// </summary> public TokenFilterSettings Asciifolding(string name, Func<AsciifoldingTokenFilter, AsciifoldingTokenFilter> asciifolding = null) { RegisterJsonPartExpression(asciifolding.Bind(tokenizer => tokenizer.Name(name))); return this; } /// <summary> /// A token filter of type asciifolding that converts alphabetic, numeric, and symbolic Unicode characters /// which are not in the first 127 ASCII characters (the "Basic Latin" Unicode block) into their ASCII equivalents, if one exists. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/asciifolding-tokenfilter.html /// </summary> public TokenFilterSettings Asciifolding(Func<AsciifoldingTokenFilter, AsciifoldingTokenFilter> asciifolding) { return Asciifolding(DefaultTokenFilters.asciifolding.AsString(), asciifolding); } #endregion #region DictionaryDecompounder /// <summary> /// A token filter of type dictionary_decompounder that allows to decompose compound words. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/compound-word-tokenfilter.html /// </summary> public TokenFilterSettings DictionaryDecompounder(string name, Func<DictionaryDecompounderTokenFilter, DictionaryDecompounderTokenFilter> dictionaryDecompounder = null) { RegisterJsonPartExpression(dictionaryDecompounder.Bind(tokenizer => tokenizer.Name(name))); return this; } /// <summary> /// A token filter of type dictionary_decompounder that allows to decompose compound words. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/compound-word-tokenfilter.html /// </summary> public TokenFilterSettings DictionaryDecompounder(Func<DictionaryDecompounderTokenFilter, DictionaryDecompounderTokenFilter> dictionaryDecompounder) { return DictionaryDecompounder(DefaultTokenFilters.dictionary_decompounder.AsString(), dictionaryDecompounder); } #endregion #region EdgeNGram /// <summary> /// A token filter of type edgeNGram that builds N-characters substrings from text. Substrings are built from one side of a text. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/edgengram-tokenfilter.html /// </summary> public TokenFilterSettings EdgeNGram(string name, Func<EdgeNGramTokenFilter, EdgeNGramTokenFilter> edgeNGram = null) { RegisterJsonPartExpression(edgeNGram.Bind(tokenizer => tokenizer.Name(name))); return this; } /// <summary> /// A token filter of type edgeNGram that builds N-characters substrings from text. Substrings are built from one side of a text. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/edgengram-tokenfilter.html /// </summary> public TokenFilterSettings EdgeNGram(Func<EdgeNGramTokenFilter, EdgeNGramTokenFilter> edgeNGram) { return EdgeNGram(DefaultTokenFilters.edgeNGram.AsString(), edgeNGram); } #endregion #region Elision /// <summary> /// A token filter which removes elisions. For example, "l'avion" (the plane) will be tokenized as "avion" (plane). /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/elision-tokenfilter.html /// </summary> public TokenFilterSettings Elision(string name, Func<ElisionTokenFilter, ElisionTokenFilter> elision = null) { RegisterJsonPartExpression(elision.Bind(tokenizer => tokenizer.Name(name))); return this; } /// <summary> /// A token filter which removes elisions. For example, "l'avion" (the plane) will be tokenized as "avion" (plane). /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/elision-tokenfilter.html /// </summary> public TokenFilterSettings Elision(Func<ElisionTokenFilter, ElisionTokenFilter> elision) { return Elision(DefaultTokenFilters.elision.AsString(), elision); } #endregion #region HyphenationDecompounder /// <summary> /// A token filter of type hyphenation_decompounder that allows to decompose compound words. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/compound-word-tokenfilter.html /// </summary> public TokenFilterSettings HyphenationDecompounder(string name, Func<HyphenationDecompounderTokenFilter, DictionaryDecompounderTokenFilter> hyphenationDecompounder = null) { RegisterJsonPartExpression(hyphenationDecompounder.Bind(tokenizer => tokenizer.Name(name))); return this; } /// <summary> /// A token filter of type hyphenation_decompounder that allows to decompose compound words. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/compound-word-tokenfilter.html /// </summary> public TokenFilterSettings HyphenationDecompounder(Func<HyphenationDecompounderTokenFilter, DictionaryDecompounderTokenFilter> hyphenationDecompounder) { return HyphenationDecompounder(DefaultTokenFilters.hyphenation_decompounder.AsString(), hyphenationDecompounder); } #endregion #region Kstem /// <summary> /// The kstem token filter is a high performance filter for english. /// All terms must already be lowercased (use lowercase filter) for this filter to work correctly. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/kstem-tokenfilter.html /// </summary> public TokenFilterSettings Kstem(string name, Func<KstemTokenFilter, KstemTokenFilter> kstem = null) { RegisterJsonPartExpression(kstem.Bind(tokenizer => tokenizer.Name(name))); return this; } /// <summary> /// The kstem token filter is a high performance filter for english. /// All terms must already be lowercased (use lowercase filter) for this filter to work correctly. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/kstem-tokenfilter.html /// </summary> public TokenFilterSettings Kstem(Func<KstemTokenFilter, KstemTokenFilter> kstem) { return Kstem(DefaultTokenFilters.kstem.AsString(), kstem); } #endregion #region Length /// <summary> /// A token filter of type length that removes words that are too long or too short for the stream. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/length-tokenfilter.html /// </summary> public TokenFilterSettings Length(string name, Func<LengthTokenFilter, LengthTokenFilter> length = null) { RegisterJsonPartExpression(length.Bind(tokenizer => tokenizer.Name(name))); return this; } /// <summary> /// A token filter of type length that removes words that are too long or too short for the stream. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/length-tokenfilter.html /// </summary> public TokenFilterSettings Length(Func<LengthTokenFilter, LengthTokenFilter> length) { return Length(DefaultTokenFilters.length.AsString(), length); } #endregion #region Lowercase /// <summary> /// A token filter of type lowercase that normalizes token text to lower case. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/lowercase-tokenfilter.html /// </summary> public TokenFilterSettings Lowercase(string name, Func<LowercaseTokenFilter, LowercaseTokenFilter> lowercase = null) { RegisterJsonPartExpression(lowercase.Bind(tokenizer => tokenizer.Name(name))); return this; } /// <summary> /// A token filter of type lowercase that normalizes token text to lower case. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/lowercase-tokenfilter.html /// </summary> public TokenFilterSettings Lowercase(Func<LowercaseTokenFilter, LowercaseTokenFilter> lowercase) { return Lowercase(DefaultTokenFilters.lowercase.AsString(), lowercase); } #endregion #region NGram /// <summary> /// A token filter of type nGram that builds N-characters substrings from text. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/ngram-tokenfilter.html /// </summary> public TokenFilterSettings NGram(string name, Func<NGramTokenFilter, NGramTokenFilter> nGram = null) { RegisterJsonPartExpression(nGram.Bind(tokenizer => tokenizer.Name(name))); return this; } /// <summary> /// A token filter of type nGram that builds N-characters substrings from text. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/ngram-tokenfilter.html /// </summary> public TokenFilterSettings NGram(Func<NGramTokenFilter, NGramTokenFilter> nGram) { return NGram(DefaultTokenFilters.nGram.AsString(), nGram); } #endregion #region PatternReplace /// <summary> /// The pattern_replace token filter allows to easily handle string replacements based on a regular expression. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/pattern_replace-tokenfilter.html /// </summary> public TokenFilterSettings PatternReplace(string name, Func<PatternReplaceTokenFilter, PatternReplaceTokenFilter> patternReplace = null) { RegisterJsonPartExpression(patternReplace.Bind(tokenizer => tokenizer.Name(name))); return this; } /// <summary> /// The pattern_replace token filter allows to easily handle string replacements based on a regular expression. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/pattern_replace-tokenfilter.html /// </summary> public TokenFilterSettings PatternReplace(Func<PatternReplaceTokenFilter, PatternReplaceTokenFilter> patternReplace) { return PatternReplace(DefaultTokenFilters.pattern_replace.AsString(), patternReplace); } #endregion #region Phonetic /// <summary> /// A phonetic analysis token filter plugin. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/phonetic-tokenfilter.html /// </summary> public TokenFilterSettings Phonetic(string name, Func<PhoneticTokenFilter, PhoneticTokenFilter> phonetic = null) { RegisterJsonPartExpression(phonetic.Bind(tokenizer => tokenizer.Name(name))); return this; } /// <summary> /// A phonetic analysis token filter plugin. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/phonetic-tokenfilter.html /// </summary> public TokenFilterSettings Phonetic(Func<PhoneticTokenFilter, PhoneticTokenFilter> phonetic) { return Phonetic(DefaultTokenFilters.phonetic.AsString(), phonetic); } #endregion #region PorterStem /// <summary> /// A token filter of type porterStem that transforms the token stream as per the Porter stemming algorithm. /// Note, the input to the stemming filter must already be in lower case, so you will need to use Lower Case Token Filter /// or Lower Case Tokenizer farther down the Tokenizer chain in order for this to work properly! /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/porterstem-tokenfilter.html /// </summary> public TokenFilterSettings PorterStem(string name, Func<PorterStemTokenFilter, PorterStemTokenFilter> porterStem = null) { RegisterJsonPartExpression(porterStem.Bind(tokenizer => tokenizer.Name(name))); return this; } /// <summary> /// A token filter of type porterStem that transforms the token stream as per the Porter stemming algorithm. /// Note, the input to the stemming filter must already be in lower case, so you will need to use Lower Case Token Filter /// or Lower Case Tokenizer farther down the Tokenizer chain in order for this to work properly! /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/porterstem-tokenfilter.html /// </summary> public TokenFilterSettings PorterStem(Func<PorterStemTokenFilter, PorterStemTokenFilter> porterStem) { return PorterStem(DefaultTokenFilters.porterStem.AsString(), porterStem); } #endregion #region Reverse /// <summary> /// A token filter of type reverse that simply reverses the tokens. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/reverse-tokenfilter.html /// </summary> public TokenFilterSettings Reverse(string name, Func<ReverseTokenFilter, ReverseTokenFilter> reverse = null) { RegisterJsonPartExpression(reverse.Bind(tokenizer => tokenizer.Name(name))); return this; } /// <summary> /// A token filter of type reverse that simply reverses the tokens. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/reverse-tokenfilter.html /// </summary> public TokenFilterSettings Reverse(Func<ReverseTokenFilter, ReverseTokenFilter> reverse) { return Reverse(DefaultTokenFilters.reverse.AsString(), reverse); } #endregion #region Shingle /// <summary> /// A token filter of type shingle that constructs shingles (token n-grams) from a token stream. /// In other words, it creates combinations of tokens as a single token. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/shingle-tokenfilter.html /// </summary> public TokenFilterSettings Shingle(string name, Func<ShingleTokenFilter, ShingleTokenFilter> shingle = null) { RegisterJsonPartExpression(shingle.Bind(tokenizer => tokenizer.Name(name))); return this; } /// <summary> /// A token filter of type shingle that constructs shingles (token n-grams) from a token stream. /// In other words, it creates combinations of tokens as a single token. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/shingle-tokenfilter.html /// </summary> public TokenFilterSettings Shingle(Func<ShingleTokenFilter, ShingleTokenFilter> shingle) { return Shingle(DefaultTokenFilters.shingle.AsString(), shingle); } #endregion #region Snowball /// <summary> /// A token filter that stems words using a Snowball-generated stemmer. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/snowball-tokenfilter.html /// </summary> public TokenFilterSettings Snowball(string name, Func<SnowballTokenFilter, SnowballTokenFilter> snowball = null) { RegisterJsonPartExpression(snowball.Bind(tokenizer => tokenizer.Name(name))); return this; } /// <summary> /// A token filter that stems words using a Snowball-generated stemmer. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/snowball-tokenfilter.html /// </summary> public TokenFilterSettings Snowball(Func<SnowballTokenFilter, SnowballTokenFilter> snowball) { return Snowball(DefaultTokenFilters.snowball.AsString(), snowball); } #endregion #region Standard /// <summary> /// A token filter of type standard that normalizes tokens extracted with the Standard Tokenizer. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/standard-tokenfilter.html /// </summary> public TokenFilterSettings Standard(string name, Func<StandardTokenFilter, StandardTokenFilter> standard = null) { RegisterJsonPartExpression(standard.Bind(tokenizer => tokenizer.Name(name))); return this; } /// <summary> /// A token filter of type standard that normalizes tokens extracted with the Standard Tokenizer. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/standard-tokenfilter.html /// </summary> public TokenFilterSettings Standard(Func<StandardTokenFilter, StandardTokenFilter> standard) { return Standard(DefaultTokenFilters.standard.AsString(), standard); } #endregion #region Stemmer /// <summary> /// A token filter that stems words (similar to snowball, but with more options). /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/stemmer-tokenfilter.html /// </summary> public TokenFilterSettings Stemmer(string name, Func<StemmerTokenFilter, StemmerTokenFilter> stemmer = null) { RegisterJsonPartExpression(stemmer.Bind(tokenizer => tokenizer.Name(name))); return this; } /// <summary> /// A token filter that stems words (similar to snowball, but with more options). /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/stemmer-tokenfilter.html /// </summary> public TokenFilterSettings Stemmer(Func<StemmerTokenFilter, StemmerTokenFilter> stemmer) { return Stemmer(DefaultTokenFilters.stemmer.AsString(), stemmer); } #endregion #region Stop /// <summary> /// A token filter of type stop that removes stop words from token streams. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/stop-tokenfilter.html /// </summary> public TokenFilterSettings Stop(string name, Func<StopTokenFilter, StopTokenFilter> stop = null) { RegisterJsonPartExpression(stop.Bind(tokenizer => tokenizer.Name(name))); return this; } /// <summary> /// A token filter of type stop that removes stop words from token streams. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/stop-tokenfilter.html /// </summary> public TokenFilterSettings Stop(Func<StopTokenFilter, StopTokenFilter> stop) { return Stop(DefaultTokenFilters.stop.AsString(), stop); } #endregion #region Synonym /// <summary> /// The synonym token filter allows to easily handle synonyms during the analysis process. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/synonym-tokenfilter.html /// </summary> public TokenFilterSettings Synonym(string name, Func<SynonymTokenFilter, SynonymTokenFilter> synonym = null) { RegisterJsonPartExpression(synonym.Bind(tokenizer => tokenizer.Name(name))); return this; } /// <summary> /// The synonym token filter allows to easily handle synonyms during the analysis process. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/synonym-tokenfilter.html /// </summary> public TokenFilterSettings Synonym(Func<SynonymTokenFilter, SynonymTokenFilter> synonym) { return Synonym(DefaultTokenFilters.synonym.AsString(), synonym); } #endregion #region Trim /// <summary> /// The trim token filter trims surrounding whitespaces around a token. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/trim-tokenfilter.html /// </summary> public TokenFilterSettings Trim(string name, Func<TrimTokenFilter, TrimTokenFilter> trim = null) { RegisterJsonPartExpression(trim.Bind(tokenizer => tokenizer.Name(name))); return this; } /// <summary> /// The trim token filter trims surrounding whitespaces around a token. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/trim-tokenfilter.html /// </summary> public TokenFilterSettings Trim(Func<TrimTokenFilter, TrimTokenFilter> trim) { return Trim(DefaultTokenFilters.trim.AsString(), trim); } #endregion #region Truncate /// <summary> /// The truncate token filter can be used to truncate tokens into a specific length. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/truncate-tokenfilter.html /// </summary> public TokenFilterSettings Truncate(string name, Func<TruncateTokenFilter, TruncateTokenFilter> truncate = null) { RegisterJsonPartExpression(truncate.Bind(tokenizer => tokenizer.Name(name))); return this; } /// <summary> /// The truncate token filter can be used to truncate tokens into a specific length. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/truncate-tokenfilter.html /// </summary> public TokenFilterSettings Truncate(Func<TruncateTokenFilter, TruncateTokenFilter> truncate) { return Truncate(DefaultTokenFilters.truncate.AsString(), truncate); } #endregion #region Unique /// <summary> /// The unique token filter can be used to only index unique tokens during analysis. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/unique-tokenfilter.html /// </summary> public TokenFilterSettings Unique(string name, Func<UniqueTokenFilter, UniqueTokenFilter> unique = null) { RegisterJsonPartExpression(unique.Bind(tokenizer => tokenizer.Name(name))); return this; } /// <summary> /// The unique token filter can be used to only index unique tokens during analysis. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/unique-tokenfilter.html /// </summary> public TokenFilterSettings Unique(Func<UniqueTokenFilter, UniqueTokenFilter> unique) { return Unique(DefaultTokenFilters.unique.AsString(), unique); } #endregion #region WordDelimiter /// <summary> /// Named word_delimiter, it splits words into subwords and performs optional transformations on subword groups. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/word-delimiter-tokenfilter.html /// </summary> public TokenFilterSettings WordDelimiter(string name, Func<WordDelimiterTokenFilter, WordDelimiterTokenFilter> wordDelimiter = null) { RegisterJsonPartExpression(wordDelimiter.Bind(tokenizer => tokenizer.Name(name))); return this; } /// <summary> /// Named word_delimiter, it splits words into subwords and performs optional transformations on subword groups. /// see http://www.elasticsearch.org/guide/reference/index-modules/analysis/word-delimiter-tokenfilter.html /// </summary> public TokenFilterSettings WordDelimiter(Func<WordDelimiterTokenFilter, WordDelimiterTokenFilter> wordDelimiter) { return WordDelimiter(DefaultTokenFilters.word_delimiter.AsString(), wordDelimiter); } #endregion protected override string ApplyJsonTemplate(string body) { return "'filter': {{ {0} }}".AltQuoteF(body); } } }
mbinot/PlainElastic.Net
src/PlainElastic.Net/Builders/IndexSettings/Analysis/TokenFilters/TokenFilterSettings.cs
C#
mit
25,174
package com.findingsoft.studentregistration; import gateways.DepartmentGateWay; import java.util.ArrayList; import utilities.Departments; import adapters.DepartmentAdapter; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; public class ManageDepartment extends Activity { EditText dCodetxt, dNametxt; Button btnCreateD, btnDeleteD, btnUpdateD; ListView deptList; DepartmentGateWay gatewayDept = new DepartmentGateWay(this); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.manage_departments); initialControls(); eventRegister(); proccessListView(); } private void initialControls(){ dCodetxt = (EditText)findViewById(R.id.txtDCode); dNametxt = (EditText)findViewById(R.id.txtDName); btnCreateD = (Button)findViewById(R.id.btnCreateD); btnDeleteD = (Button)findViewById(R.id.btnDeleteD); btnUpdateD = (Button)findViewById(R.id.btnUpdateD); deptList = (ListView)findViewById(R.id.deptListAll); } private void eventRegister(){ btnCreateD.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub saveDept(); } }); btnDeleteD.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub deleteDept(); } }); btnUpdateD.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub updateDept(); } }); } private void saveDept(){ if( !dCodetxt.getText().equals("") && !dNametxt.getText().equals("") ){ Departments aDept = new Departments(); aDept.setDeptCode(dCodetxt.getText().toString()); aDept.setDeptName(dNametxt.getText().toString()); String res = gatewayDept.save(aDept); showToast(res); proccessListView(); } } private void deleteDept(){ if( !dCodetxt.getText().equals("") ){ Departments aDept = new Departments(); aDept.setDeptCode(dCodetxt.getText().toString()); aDept.setDeptName(dNametxt.getText().toString()); String res = gatewayDept.deptDelete(dCodetxt.getText().toString()); showToast(res); proccessListView(); } } private void updateDept(){ if( !dCodetxt.getText().equals("") && !dNametxt.getText().equals("") ){ Departments aDept = new Departments(); aDept.setDeptCode(dCodetxt.getText().toString()); aDept.setDeptName(dNametxt.getText().toString()); String res = gatewayDept.deptUpdate(aDept); showToast(res); proccessListView(); } } private void proccessListView(){ ArrayList<Departments> aDept = new ArrayList<Departments>(); aDept = gatewayDept.getAll(); loadListView(aDept); } private void loadListView(ArrayList<Departments> aDept){ ListView listView = (ListView)findViewById(R.id.deptListAll); listView.setAdapter(new DepartmentAdapter(this, aDept)); } private void showToast(String msg) { Toast.makeText(getApplicationContext(), msg, 2000).show(); } }
pengzhao001/android-apps
StudentRegistration/src/com/findingsoft/studentregistration/ManageDepartment.java
Java
mit
3,266
# frozen_string_literal: true # Copyright 2015-2017, the Linux Foundation, IDA, and the # CII Best Practices badge contributors # SPDX-License-Identifier: MIT require 'test_helper' class BlankDetectiveTest < ActiveSupport::TestCase setup do # @user = User.new(name: 'Example User', email: 'user@example.com', # password: 'p@$$w0rd', password_confirmation: 'p@$$w0rd') end test 'Blank' do results = BlankDetective.new.analyze( nil, license: '(GPL-2.0 WITH CLASSPATH' ) assert results == {} end end
yannickmoy/cii-best-practices-badge
test/unit/lib/blank_detective_test.rb
Ruby
mit
551
/* Copyright (C) 2013-2014 by Kristina Simpson <sweet.kristas@gmail.com> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgement in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "BlendModeScope.hpp" namespace KRE { namespace { BlendModeScope::color_stack_type& get_mode_stack() { static BlendModeScope::color_stack_type res; return res; } const BlendMode& get_default_mode() { static BlendMode res = BlendMode(); return res; } } BlendModeScope::BlendModeScope(const BlendMode& bm) { it_ = get_mode_stack().emplace(get_mode_stack().end(), bm); } BlendModeScope::BlendModeScope(const BlendModeConstants& src, const BlendModeConstants& dst) { it_ = get_mode_stack().emplace(get_mode_stack().end(), BlendMode(src, dst)); } BlendModeScope::~BlendModeScope() { get_mode_stack().erase(it_); } const BlendMode& BlendModeScope::getCurrentMode() { if(get_mode_stack().empty()) { return get_default_mode(); } return get_mode_stack().back(); } }
cbeck88/render_engine
src/kre/BlendModeScope.cpp
C++
mit
1,753
'use strict'; var app = angular.module('myApp.payloads.directives', []); app.directive('runPayload', ['Payload', 'Command', '$routeParams', 'showToast', 'showErrors', 'gettextCatalog', function(Payload, Command, $routeParams, showToast, showErrors, gettextCatalog) { var link = function( scope, element, attrs ) { scope.location = { slug: $routeParams.id }; var box = { slug: $routeParams.box_id }; var loadCommands = function() { Command.query().$promise.then(function(results) { scope.commands = results; scope.loading_commands = undefined; }); }; scope.runCommand = function() { scope.processing = true; updateCT(); }; var updateCT = function() { var cmd = scope.command.selected; scope.command.selected = undefined; Payload.create({}, { location_id: scope.location.slug, box_id: box.slug, payload: { box_ids: box.slug, command_id: cmd, save: true } }).$promise.then(function() { showToast(gettextCatalog.getString('Payload running, please wait.')); }, function(errors) { showErrors(errors); }); }; loadCommands(); }; return { link: link, scope: { command: '=', allowed: '@' }, templateUrl: 'components/payloads/_run_payload.html', }; }]);
ZakMooney/cucumber-frontend
client/components/payloads/payloads.directives.js
JavaScript
mit
1,390
package org.knowm.xchange.dsx.service; import java.io.IOException; import java.math.BigDecimal; import java.time.Instant; import java.util.Date; import java.util.List; import java.util.Optional; import org.knowm.xchange.Exchange; import org.knowm.xchange.dsx.DsxAdapters; import org.knowm.xchange.dsx.dto.DsxBalance; import org.knowm.xchange.dsx.dto.DsxMarketOrder; import org.knowm.xchange.dsx.dto.DsxOrder; import org.knowm.xchange.dsx.dto.DsxOwnTrade; import org.knowm.xchange.dsx.dto.DsxSort; import org.knowm.xchange.dto.trade.LimitOrder; import org.knowm.xchange.dto.trade.MarketOrder; public class DsxTradeServiceRaw extends DsxBaseService { public DsxTradeServiceRaw(Exchange exchange) { super(exchange); } public List<DsxOrder> getOpenOrdersRaw() throws IOException { return dsx.getDsxActiveOrders(); } public DsxOrder placeMarketOrderRaw(MarketOrder marketOrder) throws IOException { String symbol = DsxAdapters.adaptCurrencyPair(marketOrder.getCurrencyPair()); String side = DsxAdapters.getSide(marketOrder.getType()).toString(); String clientOrderId = null; if (marketOrder instanceof DsxMarketOrder) { clientOrderId = ((DsxMarketOrder) marketOrder).getClientOrderId(); } return dsx.postDsxNewOrder( clientOrderId, symbol, side, null, marketOrder.getOriginalAmount(), DsxOrderType.market, DsxTimeInForce.IOC); } public DsxOrder placeLimitOrderRaw(LimitOrder limitOrder, DsxTimeInForce timeInForce) throws IOException { String symbol = DsxAdapters.adaptCurrencyPair(limitOrder.getCurrencyPair()); String side = DsxAdapters.getSide(limitOrder.getType()).toString(); return dsx.postDsxNewOrder( limitOrder.getUserReference(), symbol, side, limitOrder.getLimitPrice(), limitOrder.getOriginalAmount(), DsxOrderType.limit, timeInForce); } public DsxOrder placeLimitOrderRaw(LimitOrder limitOrder) throws IOException { return placeLimitOrderRaw(limitOrder, DsxTimeInForce.GTC); } public DsxOrder updateMarketOrderRaw( String clientOrderId, BigDecimal quantity, String requestClientId, Optional<BigDecimal> price) throws IOException { return dsx.updateDsxOrder(clientOrderId, quantity, requestClientId, price.orElse(null)); } public DsxOrder cancelOrderRaw(String clientOrderId) throws IOException { return dsx.cancelSingleOrder(clientOrderId); } public List<DsxOrder> cancelAllOrdersRaw(String symbol) throws IOException { return dsx.cancelAllOrders(symbol); } public List<DsxOwnTrade> getHistorialTradesByOrder(String orderId) throws IOException { return dsx.getHistorialTradesByOrder(orderId); } public List<DsxOrder> getDsxRecentOrders() throws IOException { return dsx.getDsxRecentOrders(); } public List<DsxOwnTrade> getTradeHistoryRaw(String symbol, Integer limit, long offset) throws IOException { return dsx.getDsxTrades(symbol, null, null, null, null, limit, offset); } public List<DsxOwnTrade> getTradeHistoryRaw( String symbol, DsxSort sort, Date from, Date till, Integer limit, long offset) throws IOException { String sortValue = sort != null ? sort.toString().toUpperCase() : null; String fromValue = from != null ? Instant.ofEpochMilli(from.getTime()).toString() : null; String tillValue = till != null ? Instant.ofEpochMilli(till.getTime()).toString() : null; return dsx.getDsxTrades(symbol, sortValue, "timestamp", fromValue, tillValue, limit, offset); } public List<DsxOwnTrade> getTradeHistoryRaw( String symbol, DsxSort sort, Long fromId, Long tillId, Integer limit, long offset) throws IOException { String sortValue = sort != null ? sort.toString().toUpperCase() : null; String fromValue = fromId != null ? fromId.toString() : null; String tillValue = tillId != null ? tillId.toString() : null; return dsx.getDsxTrades(symbol, sortValue, "id", fromValue, tillValue, limit, offset); } public DsxOrder getDsxOrder(String symbol, String clientOrderId) throws IOException { List<DsxOrder> orders = dsx.getDsxOrder(symbol, clientOrderId); if (orders == null || orders.isEmpty()) { return null; } else { return orders.iterator().next(); } } public List<DsxBalance> getTradingBalance() throws IOException { return dsx.getTradingBalance(); } }
stachon/XChange
xchange-dsx/src/main/java/org/knowm/xchange/dsx/service/DsxTradeServiceRaw.java
Java
mit
4,449
<div class="sidebar"> <h2><?= t('Actions') ?></h2> <ul> <li <?= $this->app->getRouterAction() === 'show' ? 'class="active"' : '' ?>> <?= $this->url->link(t('Summary'), 'project', 'show', array('project_id' => $project['id'])) ?> </li> <?php if ($this->user->isProjectManagementAllowed($project['id'])): ?> <li <?= $this->app->getRouterController() === 'project' && $this->app->getRouterAction() === 'share' ? 'class="active"' : '' ?>> <?= $this->url->link(t('Public access'), 'project', 'share', array('project_id' => $project['id'])) ?> </li> <li <?= $this->app->getRouterController() === 'project' && $this->app->getRouterAction() === 'integration' ? 'class="active"' : '' ?>> <?= $this->url->link(t('Integrations'), 'project', 'integration', array('project_id' => $project['id'])) ?> </li> <li <?= $this->app->getRouterController() === 'project' && $this->app->getRouterAction() === 'edit' ? 'class="active"' : '' ?>> <?= $this->url->link(t('Edit project'), 'project', 'edit', array('project_id' => $project['id'])) ?> </li> <li <?= $this->app->getRouterController() === 'column' ? 'class="active"' : '' ?>> <?= $this->url->link(t('Columns'), 'column', 'index', array('project_id' => $project['id'])) ?> </li> <li <?= $this->app->getRouterController() === 'swimlane' ? 'class="active"' : '' ?>> <?= $this->url->link(t('Swimlanes'), 'swimlane', 'index', array('project_id' => $project['id'])) ?> </li> <li <?= $this->app->getRouterController() === 'category' ? 'class="active"' : '' ?>> <?= $this->url->link(t('Categories'), 'category', 'index', array('project_id' => $project['id'])) ?> </li> <?php if ($this->user->isAdmin() || $project['is_private'] == 0): ?> <li <?= $this->app->getRouterController() === 'project' && $this->app->getRouterAction() === 'users' ? 'class="active"' : '' ?>> <?= $this->url->link(t('Users'), 'project', 'users', array('project_id' => $project['id'])) ?> </li> <?php endif ?> <li <?= $this->app->getRouterController() === 'action' ? 'class="active"' : '' ?>> <?= $this->url->link(t('Automatic actions'), 'action', 'index', array('project_id' => $project['id'])) ?> </li> <li <?= $this->app->getRouterController() === 'project' && $this->app->getRouterAction() === 'duplicate' ? 'class="active"' : '' ?>> <?= $this->url->link(t('Duplicate'), 'project', 'duplicate', array('project_id' => $project['id'])) ?> </li> <li <?= $this->app->getRouterController() === 'project' && ($this->app->getRouterAction() === 'disable' || $this->app->getRouterAction() === 'enable') ? 'class="active"' : '' ?>> <?php if ($project['is_active']): ?> <?= $this->url->link(t('Disable'), 'project', 'disable', array('project_id' => $project['id']), true) ?> <?php else: ?> <?= $this->url->link(t('Enable'), 'project', 'enable', array('project_id' => $project['id']), true) ?> <?php endif ?> </li> <?php if ($this->user->isProjectAdministrationAllowed($project['id'])): ?> <li <?= $this->app->getRouterController() === 'project' && $this->app->getRouterAction() === 'remove' ? 'class="active"' : '' ?>> <?= $this->url->link(t('Remove'), 'project', 'remove', array('project_id' => $project['id'])) ?> </li> <?php endif ?> <?php endif ?> <?= $this->hook->render('project:sidebar') ?> </ul> <div class="sidebar-collapse"><a href="#" title="<?= t('Hide sidebar') ?>"><i class="fa fa-chevron-left"></i></a></div> <div class="sidebar-expand" style="display: none"><a href="#" title="<?= t('Expand sidebar') ?>"><i class="fa fa-chevron-right"></i></a></div> </div>
manishlad/kanboard
app/Template/project/sidebar.php
PHP
mit
4,113
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Cache; use Symfony\Contracts\Cache\CacheInterface; use Symfony\Contracts\Cache\ItemInterface; /** * LockRegistry is used internally by existing adapters to protect against cache stampede. * * It does so by wrapping the computation of items in a pool of locks. * Foreach each apps, there can be at most 20 concurrent processes that * compute items at the same time and only one per cache-key. * * @author Nicolas Grekas <p@tchwork.com> */ class LockRegistry { private static $save; private static $openedFiles = array(); private static $lockedFiles = array(); /** * The number of items in this list controls the max number of concurrent processes. */ private static $files = array( __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'AbstractAdapter.php', __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'AdapterInterface.php', __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'ApcuAdapter.php', __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'ArrayAdapter.php', __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'ChainAdapter.php', __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'DoctrineAdapter.php', __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'FilesystemAdapter.php', __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'MemcachedAdapter.php', __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'NullAdapter.php', __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'PdoAdapter.php', __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'PhpArrayAdapter.php', __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'PhpFilesAdapter.php', __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'ProxyAdapter.php', __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'RedisAdapter.php', __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'SimpleCacheAdapter.php', __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'TagAwareAdapter.php', __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'TagAwareAdapterInterface.php', __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'TraceableAdapter.php', __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'TraceableTagAwareAdapter.php', ); /** * Defines a set of existing files that will be used as keys to acquire locks. * * @return array The previously defined set of files */ public static function setFiles(array $files): array { $previousFiles = self::$files; self::$files = $files; foreach (self::$openedFiles as $file) { if ($file) { flock($file, LOCK_UN); fclose($file); } } self::$openedFiles = self::$lockedFiles = array(); return $previousFiles; } public static function compute(ItemInterface $item, callable $callback, CacheInterface $pool) { $key = self::$files ? crc32($item->getKey()) % \count(self::$files) : -1; if ($key < 0 || (self::$lockedFiles[$key] ?? false) || !$lock = self::open($key)) { return $callback($item); } try { // race to get the lock in non-blocking mode if (flock($lock, LOCK_EX | LOCK_NB)) { self::$lockedFiles[$key] = true; return $callback($item); } // if we failed the race, retry locking in blocking mode to wait for the winner flock($lock, LOCK_SH); } finally { flock($lock, LOCK_UN); unset(self::$lockedFiles[$key]); } return $pool->get($item->getKey(), $callback, 0); } private static function open(int $key) { if (null !== $h = self::$openedFiles[$key] ?? null) { return $h; } set_error_handler(function () {}); try { $h = fopen(self::$files[$key], 'r+'); } finally { restore_error_handler(); } self::$openedFiles[$key] = $h ?: @fopen(self::$files[$key], 'r'); } }
weaverryan/symfony
src/Symfony/Component/Cache/LockRegistry.php
PHP
mit
4,546
import React, { memo } from 'react'; import SideBarItemTemplateWithData from '../RoomList/SideBarItemTemplateWithData'; import UserItem from './UserItem'; const Row = ({ item, data }) => { const { t, SideBarItemTemplate, avatarTemplate: AvatarTemplate, useRealName, extended } = data; if (item.t === 'd' && !item.u) { return ( <UserItem id={`search-${item._id}`} useRealName={useRealName} t={t} item={item} SideBarItemTemplate={SideBarItemTemplate} AvatarTemplate={AvatarTemplate} /> ); } return ( <SideBarItemTemplateWithData id={`search-${item._id}`} tabIndex={-1} extended={extended} t={t} room={item} SideBarItemTemplate={SideBarItemTemplate} AvatarTemplate={AvatarTemplate} /> ); }; export default memo(Row);
VoiSmart/Rocket.Chat
client/sidebar/search/Row.js
JavaScript
mit
782
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.Msagl.Core.DataStructures; using Microsoft.Msagl.Core.Geometry; using Microsoft.Msagl.Core.Geometry.Curves; using Microsoft.Msagl.Core.GraphAlgorithms; using Microsoft.Msagl.Core.Layout; using Microsoft.Msagl.DebugHelpers; using SymmetricSegment = Microsoft.Msagl.Core.DataStructures.SymmetricTuple<Microsoft.Msagl.Core.Geometry.Point>; namespace Microsoft.Msagl.Layout.LargeGraphLayout { /// <summary> /// class keeping a level info /// </summary> public class LgLevel { internal readonly Dictionary<SymmetricSegment, Rail> _railDictionary = new Dictionary<SymmetricSegment, Rail>(); internal Dictionary<SymmetricSegment, Rail> RailDictionary { get { return _railDictionary; } } internal readonly Dictionary<Edge, Set<Rail>> _railsOfEdges = new Dictionary<Edge, Set<Rail>>(); internal Set<Rail> HighlightedRails = new Set<Rail>(); internal readonly int ZoomLevel; readonly GeometryGraph _geomGraph; internal RTree<Rail> _railTree = new RTree<Rail>(); internal RTree<Rail> RailTree { get { return _railTree; } } RTree<LgNodeInfo> _nodeInfoTree = new RTree<LgNodeInfo>(); internal readonly Dictionary<Edge, List<Rail>> _orderedRailsOfEdges = new Dictionary<Edge, List<Rail>>(); /// <summary> /// /// </summary> /// <param name="zoomLevel"></param> /// <param name="geomGraph">needed only for statistics</param> internal LgLevel(int zoomLevel, GeometryGraph geomGraph) { _geomGraph = geomGraph; ZoomLevel = zoomLevel; } internal RTree<LgNodeInfo> NodeInfoTree { get { return _nodeInfoTree; } } internal void CreateEmptyRailTree() { _railTree = new RTree<Rail>(); } //public void CreateRailTree() { // RailTree = new RTree<Rail>( // RailDictionary.Values.Select(rail => new KeyValuePair<Rectangle, Rail>(rail.BoundingBox, rail))); //} /// <summary> /// get endpoint tuples of all rails /// </summary> /// <returns></returns> public List<SymmetricSegment> GetAllRailsEndpoints() { var endpts = new List<SymmetricSegment>(); Point p0, p1; foreach (var rail in _railTree.GetAllLeaves()) { if (rail.GetStartEnd(out p0, out p1)) { endpts.Add(new SymmetricSegment(p0, p1)); } } return endpts; } public List<Rail> FetchOrCreateRailSequence(List<Point> path) { List<Rail> rails = new List<Rail>(); for (int i = 0; i < path.Count - 1; i++) { var rail = FindOrCreateRail(path[i], path[i + 1]); if (rail == null) continue; rails.Add(rail); } return rails; } public Rail FindOrCreateRail(Point s, Point t) { var p0 = s; var p1 = t; var t1 = new SymmetricSegment(p0, p1); Rail rail; if (RailDictionary.TryGetValue(t1, out rail)) return rail; var t2 = new SymmetricSegment(p1, p0); if (RailDictionary.TryGetValue(t2, out rail)) return rail; // no rail exists // roman: please check that this code really can be commented out and does need to be fixed instead /* * var q0 = VisGraph.GetPointOfVisGraphVertex(s); var q1 = VisGraph.GetPointOfVisGraphVertex(t); if (q0 == null || q1 == null) { //no visgraph vertex found } else { var edge = VisGraph.FindEdge(q0.Point, q1.Point); }*/ return CreateRail(p0, p1); } public Rail CreateRail(Point ep0, Point ep1) { var st = new SymmetricSegment(ep0, ep1); Rail rail; if (RailDictionary.TryGetValue(st, out rail)) { return rail; } var ls = new LineSegment(ep0, ep1); rail = new Rail(ls, ZoomLevel); RailTree.Add(rail.BoundingBox, rail); RailDictionary.Add(st, rail); return rail; } public Rail FindRail(Point s, Point t) { var p0 = s; var p1 = t; var ss = new SymmetricSegment(p1, p0); Rail rail; RailDictionary.TryGetValue(ss, out rail); return rail; } internal IEnumerable<Rail> GetRailsIntersectingRect(Rectangle visibleRectange) { var ret = new Set<Rail>(); foreach (var rail in _railTree.GetAllIntersecting(visibleRectange)) ret.Insert(rail); return ret; } internal List<Edge> GetEdgesPassingThroughRail(Rail rail) { return (from kv in _railsOfEdges where kv.Value.Contains(rail) select kv.Key).ToList(); } public Rail RemoveRailFromRtree(Rail rail) { return _railTree.Remove(rail.BoundingBox, rail); } /// <summary> /// try adding single rail to dictionary /// </summary> /// <param name="rail"></param> /// <returns>true iff the rail does not belong to _railDictionary</returns> public bool AddRailToDictionary(Rail rail) { Point p0, p1; if (!rail.GetStartEnd(out p0, out p1)) return false; var st = new SymmetricSegment(p0, p1); if (!_railDictionary.ContainsKey(st)) { _railDictionary.Add(st, rail); return true; } return false; } public void AddRailToRtree(Rail rail) { Point p0, p1; if (!rail.GetStartEnd(out p0, out p1)) return; if (_railTree.Contains(new Rectangle(p0, p1), rail)) return; _railTree.Add(new Rectangle(p0, p1), rail); } public void RemoveRailFromDictionary(Rail rail) { Point p0, p1; if (!rail.GetStartEnd(out p0, out p1)) return; _railDictionary.Remove(new SymmetricSegment(p0, p1)); } #region Statistics internal void RunLevelStatistics(IEnumerable<Node> nodes) { Console.WriteLine("running stats"); foreach (var rail in _railDictionary.Values) CreateStatisticsForRail(rail); RunStatisticsForNodes(nodes); double numberOfTiles = (double) ZoomLevel*ZoomLevel; double averageRailsForTile = 0; double averageVerticesForTile = 0; int maxVerticesPerTile = 0; int maxRailsPerTile = 0; int maxTotalPerTile = 0; foreach (var tileStatistic in tileTableForStatistic.Values) { averageVerticesForTile += tileStatistic.vertices/numberOfTiles; averageRailsForTile += tileStatistic.rails/numberOfTiles; if (maxRailsPerTile < tileStatistic.rails) maxRailsPerTile = tileStatistic.rails; if (maxVerticesPerTile < tileStatistic.vertices) maxVerticesPerTile = tileStatistic.vertices; if (maxTotalPerTile < tileStatistic.vertices + tileStatistic.rails) maxTotalPerTile = tileStatistic.vertices + tileStatistic.rails; } Console.WriteLine("level {0}: average rails per tile {1}\n" + "average verts per tile {2}, total average per tile {1}.\n", ZoomLevel, averageRailsForTile, averageVerticesForTile); Console.WriteLine("max rails per tile {0}\n" + "max verts per tile {1}, total max per tile {2}.\n", maxRailsPerTile, maxVerticesPerTile, maxTotalPerTile); Console.WriteLine("done with stats"); } void RunStatisticsForNodes(IEnumerable<Node> nodes) { foreach (var node in nodes) CreateStatisticsForNode(node); } void CreateStatisticsForNode(Node node) { foreach (var tile in GetCurveTiles(node.BoundaryCurve)) tile.vertices++; } void CreateStatisticsForRail(Rail rail) { var arrowhead = rail.Geometry as Arrowhead; if (arrowhead != null) CreateStatisticsForArrowhead(arrowhead); else foreach (var t in GetCurveTiles(rail.Geometry as ICurve)) t.rails++; } void CreateStatisticsForArrowhead(Arrowhead arrowhead) { TileStatistic tile = GetOrCreateTileStatistic(arrowhead.TipPosition); tile.rails++; } TileStatistic GetOrCreateTileStatistic(Point p) { Tuple<int, int> t = DeviceIndependendZoomCalculatorForNodes.PointToTuple(_geomGraph.LeftBottom, p, GetGridSize()); TileStatistic ts; if (tileTableForStatistic.TryGetValue(t, out ts)) return ts; tileTableForStatistic[t] = ts = new TileStatistic {rails = 0, vertices = 0}; return ts; } IEnumerable<TileStatistic> GetCurveTiles(ICurve curve) { var tiles = new Set<TileStatistic>(); const int n = 64; var s = curve.ParStart; var e = curve.ParEnd; var d = (e - s)/(n - 1); for (int i = 0; i < 64; i++) { var t = s + i*d; var ts = GetOrCreateTileStatistic(curve[t]); tiles.Insert(ts); } return tiles; } class TileStatistic { public int vertices; public int rails; } readonly Dictionary<Tuple<int, int>, TileStatistic> tileTableForStatistic = new Dictionary<Tuple<int, int>, TileStatistic>(); double GetGridSize() { return Math.Max(_geomGraph.Width, _geomGraph.Height)/ZoomLevel; } #endregion internal void AddRail(Rail rail) { if (AddRailToDictionary(rail)) AddRailToRtree(rail); } public void ClearRailTree() { _railTree.Clear(); } public void CreateNodeTree(IEnumerable<LgNodeInfo> nodeInfos, double nodeDotWidth) { foreach (var n in nodeInfos) NodeInfoTree.Add(new RectangleNode<LgNodeInfo>(n, new Rectangle(new Size(nodeDotWidth, nodeDotWidth),n.Center))); } public IEnumerable<Node> GetNodesIntersectingRect(Rectangle visibleRectangle) { return NodeInfoTree.GetAllIntersecting(visibleRectangle).Select(n => n.GeometryNode); } public bool RectIsEmptyOnLevel(Rectangle tileBox) { LgNodeInfo lg; return !NodeInfoTree.OneIntersecting(tileBox, out lg); } internal void RemoveFromRailEdges(List<SymmetricTuple<LgNodeInfo>> removeList) { foreach (var symmetricTuple in removeList) RemoveTupleFromRailEdges(symmetricTuple); } void RemoveTupleFromRailEdges(SymmetricTuple<LgNodeInfo> tuple) { var a = tuple.A.GeometryNode; var b = tuple.B.GeometryNode; foreach (var edge in EdgesBetween(a, b)) _railsOfEdges.Remove(edge); } IEnumerable<Edge> EdgesBetween(Node a, Node b) { foreach (var e in a.InEdges.Where(e => e.Source == b)) yield return e; foreach (var e in a.OutEdges.Where(e => e.Target == b)) yield return e; } } }
bilsaboob/RapidPliant
external_libs/Msagl/Msagl/Layout/LargeGraphLayout/LgLevel.cs
C#
mit
11,927
from __future__ import print_function __title__ = 'pif.utils' __author__ = 'Artur Barseghyan' __copyright__ = 'Copyright (c) 2013 Artur Barseghyan' __license__ = 'GPL 2.0/LGPL 2.1' __all__ = ('ensure_autodiscover', 'list_checkers', 'get_public_ip') from pif.base import registry from pif.discover import autodiscover def ensure_autodiscover(): """ Ensures the IP checkers are discovered. """ if not registry._registry: autodiscover() def list_checkers(): """ Lists available checkers. :return list: """ return registry._registry.keys() def get_public_ip(preferred_checker=None, verbose=False): """ Gets IP using one of the services. :param str preffered checker: Checker UID. If given, the preferred checker is used. :param bool verbose: If set to True, debug info is printed. :return str: """ ensure_autodiscover() # If use preferred checker. if preferred_checker: ip_checker_cls = registry.get(preferred_checker) if not ip_checker_cls: return False ip_checker = ip_checker_cls(verbose=verbose) ip = ip_checker.get_public_ip() if verbose: print('provider: ', ip_checker_cls) return ip # Using all checkers. for ip_checker_name, ip_checker_cls in registry._registry.items(): ip_checker = ip_checker_cls(verbose=verbose) try: ip = ip_checker.get_public_ip() if ip: if verbose: print('provider: ', ip_checker_cls) return ip except Exception as e: if verbose: print(e) return False
djabber/Dashboard
bottle/dash/local/lib/pif-0.7/src/pif/utils.py
Python
mit
1,686
from abc import abstractmethod import sys, abc if sys.version_info >= (3, 4): ABC = abc.ABC else: ABC = abc.ABCMeta('ABC', (), {}) import numpy as np from enum import Enum class Env(ABC): class Terminate(Enum): Null = 0 Fail = 1 Succ = 2 def __init__(self, args, enable_draw): self.enable_draw = enable_draw return
MadManRises/Madgine
shared/bullet3-2.89/examples/pybullet/gym/pybullet_envs/deep_mimic/env/env.py
Python
mit
348
<?php defined('BX_DOL') or die('hack attempt'); /** * Copyright (c) BoonEx Pty Limited - http://www.boonex.com/ * CC-BY License - http://creativecommons.org/licenses/by/3.0/ * * @defgroup TridentStudio Trident Studio * @{ */ bx_import('BxDolDb'); class BxDolStudioPageQuery extends BxDolDb { function __construct() { parent::__construct(); } function getPages($aParams, &$aItems, $bReturnCount = true) { $aMethod = array('name' => 'getAll', 'params' => array(0 => 'query')); $sSelectClause = $sJoinClause = $sWhereClause = $sOrderClause = $sLimitClause = ""; if(!isset($aParams['order']) || empty($aParams['order'])) $sOrderClause = "ORDER BY `tp`.`id` ASC"; switch($aParams['type']) { case 'all': break; case 'by_page_id': $aMethod['name'] = 'getRow'; $sWhereClause .= $this->prepare("AND `tp`.`id`=?", $aParams['value']); $sOrderClause = ""; $sLimitClause = "LIMIT 1"; break; case 'by_page_id_full': $aMethod['name'] = 'getRow'; $sSelectClause .= ", `tw`.`id` AS `wid_id`, `tw`.`module` AS `wid_module`, `tw`.`url` AS `wid_url`, `tw`.`click` AS `wid_click`, `tw`.`icon` AS `wid_icon`, `tw`.`caption` AS `wid_caption`, `tw`.`cnt_notices` AS `wid_cnt_notices`, `tw`.`cnt_actions` AS `wid_cnt_actions` "; $sJoinClause .= "LEFT JOIN `sys_std_widgets` AS `tw` ON `tp`.`id`=`tw`.`page_id` "; $sWhereClause .= $this->prepare("AND `tp`.`id`=?", $aParams['value']); $sLimitClause = "LIMIT 1"; break; case 'by_page_name': $aMethod['name'] = 'getRow'; $sWhereClause .= $this->prepare("AND `tp`.`name`=?", $aParams['value']); $sLimitClause = "LIMIT 1"; break; case 'by_page_name_full': $aMethod['name'] = 'getRow'; $sSelectClause .= ", `tw`.`id` AS `wid_id`, `tw`.`module` AS `wid_module`, `tw`.`url` AS `wid_url`, `tw`.`click` AS `wid_click`, `tw`.`icon` AS `wid_icon`, `tw`.`caption` AS `wid_caption`, `tw`.`cnt_notices` AS `wid_cnt_notices`, `tw`.`cnt_actions` AS `wid_cnt_actions` "; $sJoinClause .= "LEFT JOIN `sys_std_widgets` AS `tw` ON `tp`.`id`=`tw`.`page_id` "; $sWhereClause .= $this->prepare("AND `tp`.`name`=?", $aParams['value']); $sLimitClause = "LIMIT 1"; break; case 'by_page_names_full': $aMethod['name'] = 'getAll'; $sSelectClause .= ", `tw`.`id` AS `wid_id`, `tw`.`module` AS `wid_module`, `tw`.`url` AS `wid_url`, `tw`.`click` AS `wid_click`, `tw`.`icon` AS `wid_icon`, `tw`.`caption` AS `wid_caption`, `tw`.`cnt_notices` AS `wid_cnt_notices`, `tw`.`cnt_actions` AS `wid_cnt_actions` "; $sJoinClause .= "LEFT JOIN `sys_std_widgets` AS `tw` ON `tp`.`id`=`tw`.`page_id` "; foreach($aParams['value'] as $sValue) $sWhereClause .= $this->prepare(" OR `tp`.`name`=?", $sValue); $sWhereClause = "AND (0" . $sWhereClause . ")"; break; } $aMethod['params'][0] = "SELECT " . ($bReturnCount ? "SQL_CALC_FOUND_ROWS" : "") . " `tp`.`id` AS `id`, `tp`.`index` AS `index`, `tp`.`name` AS `name`, `tp`.`header` AS `header`, `tp`.`caption` AS `caption`, `tp`.`icon` AS `icon`" . $sSelectClause . " FROM `sys_std_pages` AS `tp` " . $sJoinClause . " WHERE 1 " . $sWhereClause . " " . $sOrderClause . " " . $sLimitClause; $aItems = call_user_func_array(array($this, $aMethod['name']), $aMethod['params']); if(!$bReturnCount) return !empty($aItems); return (int)$this->getOne("SELECT FOUND_ROWS()"); } function isBookmarked($aPage) { if(empty($aPage['wid_id'])) return false; $sSql = $this->prepare("SELECT `bookmark` FROM `sys_std_widgets` WHERE `id`=? LIMIT 1", $aPage['wid_id']); if((int)$this->getOne($sSql) == 0) return false; return true; } function bookmark(&$aPage) { if(empty($aPage['wid_id'])) return false; $aPageHome = array(); $iPageHome = $this->getPages(array('type' => 'by_page_name', 'value' => BX_DOL_STUDIO_PAGE_HOME), $aPageHome); if($iPageHome != 1) return false; $sSql = $this->prepare("UPDATE `sys_std_widgets` SET `bookmark`=? WHERE `id`=?", $aPage['bookmarked'] ? 0 : 1, $aPage['wid_id']); if(($bResult = (int)$this->query($sSql) > 0) === true) $aPage['bookmarked'] = !$aPage['bookmarked']; return $bResult; } } /** @} */
camperjz/trident
upgrade/files/8.0.0.A9-8.0.0.A10/files/studio/classes/BxDolStudioPageQuery.php
PHP
mit
4,919
module CiteProc module Ruby class Renderer def citation_mode? state.mode == 'citation' end def bibliography_mode? state.mode == 'bibliography' end def sort_mode? state.mode == 'key' end def substitution_mode? !state.substitute.nil? end def style return unless state.node && !state.node.root? && state.node.root.is_a?(CSL::Style) state.node.root end class State include Observable attr_reader :history, :node, :item, :authors, :substitute def initialize @history, @authors = History.new(self, 3), [] end def store!(item, node) @item, @node = item, node ensure changed end def store_authors!(authors) @authors << authors ensure changed end def clear!(result = nil) memories = conserve(result) reset ensure notify_observers :clear!, memories.delete(:mode), memories end def reset @item, @node, @substitute, @authors, @names = nil, nil, nil, [], nil self ensure changed end def mode node && node.nodename end def substitute!(names) @substitute = names end def clear_substitute!(backup = nil) @substitute = backup end def previous_authors past = history.recall(mode) return unless past && !past.empty? past[:authors] end def rendered_names? @names end def rendered_names! @names = true end def conserve(result = nil) { :mode => mode, :item => item, :authors => authors, :result => result } end end end end end
TiSU32/tisu32.github.io
vendor/bundle/ruby/3.0.0/gems/citeproc-ruby-1.1.13/lib/citeproc/ruby/renderer/state.rb
Ruby
mit
1,967
using System; using System.Windows.Forms; namespace BoundTreeView { static class Program { /// <summary> /// The main entry point for the application. /// </summary> #if WINFORMS [STAThread] #endif private static void Main() { #if WINFORMS Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); #endif new AppBootstrapper().Run(); } } }
tfreitasleal/MvvmFx
Samples/CaliburnMicro/BoundTreeView/BoundTreeView.WisejWeb/Program.cs
C#
mit
479
package com.aspose.cells.model; import java.util.ArrayList; import java.util.List; public class Columns { private Integer MaxColumn = null; private Integer ColumnsCount = null; private List<LinkElement> ColumnsList = new ArrayList<LinkElement>(); private Link link = null; /** * getMaxColumn * Gets Integer * @return MaxColumn */ public Integer getMaxColumn() { return MaxColumn; } /** * setMaxColumn * Sets Integer * @param MaxColumn Integer */ public void setMaxColumn(Integer MaxColumn) { this.MaxColumn = MaxColumn; } /** * getColumnsCount * Gets Integer * @return ColumnsCount */ public Integer getColumnsCount() { return ColumnsCount; } /** * setColumnsCount * Sets Integer * @param ColumnsCount Integer */ public void setColumnsCount(Integer ColumnsCount) { this.ColumnsCount = ColumnsCount; } /** * getColumnsList * Gets List<LinkElement> * @return ColumnsList */ public List<LinkElement> getColumnsList() { return ColumnsList; } /** * setColumnsList * Sets List<LinkElement> * @param ColumnsList List<LinkElement> */ public void setColumnsList(List<LinkElement> ColumnsList) { this.ColumnsList = ColumnsList; } /** * getLink * Gets Link * @return link */ public Link getLink() { return link; } /** * setLink * Sets Link * @param link Link */ public void setLink(Link link) { this.link = link; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Columns {\n"); sb.append(" MaxColumn: ").append(MaxColumn).append("\n"); sb.append(" ColumnsCount: ").append(ColumnsCount).append("\n"); sb.append(" ColumnsList: ").append(ColumnsList).append("\n"); sb.append(" link: ").append(link).append("\n"); sb.append("}\n"); return sb.toString(); } }
asposecells/Aspose_Cells_Cloud
SDKs/Aspose.Cells-Cloud-SDK-for-Java/src/main/java/com/aspose/cells/model/Columns.java
Java
mit
1,890
/* Copyright (c) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.appengine.demos.jdoexamples; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class GuestbookServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { GuestbookUtils.insert(req.getParameter("who"), req.getParameter("message")); resp.sendRedirect("/guestbook.jsp"); } }
dougkoellmer/swarm
tools/appengine-java-sdk/demos/jdoexamples/src/com/google/appengine/demos/jdoexamples/GuestbookServlet.java
Java
mit
1,159
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- VERSION = "1.0.0b3"
Azure/azure-sdk-for-python
sdk/videoanalyzer/azure-mgmt-videoanalyzer/azure/mgmt/videoanalyzer/_version.py
Python
mit
488
package metrics import ( "fmt" "sort" ) type Registry struct { descriptors []*groupDesc groups []groupRegistry } const ( // DefaultGroup is the identifier for the default group. DefaultGroup = GID(0) ) // NewRegistry creates a new Registry with a single group identified by DefaultGroup. func NewRegistry() *Registry { var r Registry r.MustRegisterGroup("global") return &r } func (r *Registry) register(gd *groupDesc) error { p := sort.Search(len(r.descriptors), func(i int) bool { return r.descriptors[i].Name == gd.Name }) if p != len(r.descriptors) { return fmt.Errorf("group name '%s' already in use", gd.Name) } r.descriptors = append(r.descriptors, gd) sort.Slice(r.descriptors, func(i, j int) bool { return r.descriptors[i].Name < r.descriptors[j].Name }) gd.id = GID(len(r.groups)) r.groups = append(r.groups, groupRegistry{desc: gd}) return nil } func (r *Registry) mustRegister(gd *groupDesc) { if err := r.register(gd); err != nil { panic(err.Error()) } } // MustRegisterGroup registers a new group and panics if a group already exists with the same name. // // MustRegisterGroup is not safe to call from concurrent goroutines. func (r *Registry) MustRegisterGroup(name string) GID { gd := &groupDesc{Name: name} r.mustRegister(gd) return gd.id } func (r *Registry) mustGetGroupRegistry(id GID) *groupRegistry { if int(id) >= len(r.groups) { panic("invalid group ID") } return &r.groups[id] } // MustRegisterCounter registers a new counter metric using the provided descriptor. // If the metric name is not unique within the group, MustRegisterCounter will panic. // // MustRegisterCounter is not safe to call from concurrent goroutines. func (r *Registry) MustRegisterCounter(name string, opts ...descOption) ID { desc := newDesc(name, opts...) return r.mustGetGroupRegistry(desc.gid).mustRegisterCounter(desc) } // MustRegisterTimer registers a new timer metric using the provided descriptor. // If the metric name is not unique within the group, MustRegisterTimer will panic. // // MustRegisterTimer is not safe to call from concurrent goroutines. func (r *Registry) MustRegisterTimer(name string, opts ...descOption) ID { desc := newDesc(name, opts...) return r.mustGetGroupRegistry(desc.gid).mustRegisterTimer(desc) } func (r *Registry) NewGroup(gid GID) *Group { return r.mustGetGroupRegistry(gid).newGroup() }
influxdb/influxdb
pkg/metrics/registry.go
GO
mit
2,391
/* * This file is part of Poedit (http://poedit.net) * * Copyright (C) 2010-2015 Vaclav Slavik * * 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 "concurrency.h" #include "errors.h" #include <wx/log.h> #if defined(HAVE_DISPATCH) #include <dispatch/dispatch.h> void call_on_main_thread_impl(std::function<void()>&& f) { std::function<void()> func(std::move(f)); dispatch_async(dispatch_get_main_queue(), [func]{ try { func(); } catch (...) { // FIXME: This is gross. Should be reported better and properly, but this // is consistent with pplx/ConcurrencyRT/futures, so do it for now. wxLogDebug("uncaught exception: %s", DescribeCurrentException()); } }); } void concurrency_queue::enqueue(std::function<void()>&& f) { std::function<void()> func(std::move(f)); dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(q, [func]{ try { func(); } catch (...) { // FIXME: This is gross. Should be reported better and properly, but this // is consistent with pplx/ConcurrencyRT/futures, so do it for now. wxLogDebug("uncaught exception: %s", DescribeCurrentException()); } }); } void concurrency_queue::cleanup() { } #elif !defined(HAVE_PPL) // generic implementation #include "ThreadPool.h" #include <thread> namespace { std::unique_ptr<ThreadPool> gs_pool; static std::once_flag initializationFlag; ThreadPool& pool() { std::call_once(initializationFlag, []{ gs_pool.reset(new ThreadPool(std::thread::hardware_concurrency() + 1)); }); return *gs_pool; } } // anonymous namespace void concurrency_queue::enqueue(std::function<void()>&& f) { pool().enqueue_func(std::move(f)); } void concurrency_queue::cleanup() { gs_pool.reset(); } #endif // !HAVE_DISPATCH
egoitzro/poedit
src/concurrency.cpp
C++
mit
3,039
<?php /** * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @since 2.0.0 * @license http://www.opensource.org/licenses/mit-license.php MIT License */ namespace Cake\Controller\Component; use Cake\Controller\Component; use Cake\Datasource\QueryInterface; use Cake\Datasource\RepositoryInterface; use Cake\Network\Exception\NotFoundException; use Cake\Utility\Hash; /** * This component is used to handle automatic model data pagination. The primary way to use this * component is to call the paginate() method. There is a convenience wrapper on Controller as well. * * ### Configuring pagination * * You configure pagination when calling paginate(). See that method for more details. * * @link http://book.cakephp.org/3.0/en/controllers/components/pagination.html */ class PaginatorComponent extends Component { /** * Default pagination settings. * * When calling paginate() these settings will be merged with the configuration * you provide. * * - `maxLimit` - The maximum limit users can choose to view. Defaults to 100 * - `limit` - The initial number of items per page. Defaults to 20. * - `page` - The starting page, defaults to 1. * - `whitelist` - A list of parameters users are allowed to set using request * parameters. Modifying this list will allow users to have more influence * over pagination, be careful with what you permit. * * @var array */ protected $_defaultConfig = [ 'page' => 1, 'limit' => 20, 'maxLimit' => 100, 'whitelist' => ['limit', 'sort', 'page', 'direction'] ]; /** * Events supported by this component. * * @return array */ public function implementedEvents() { return []; } /** * Handles automatic pagination of model records. * * ### Configuring pagination * * When calling `paginate()` you can use the $settings parameter to pass in pagination settings. * These settings are used to build the queries made and control other pagination settings. * * If your settings contain a key with the current table's alias. The data inside that key will be used. * Otherwise the top level configuration will be used. * * ``` * $settings = [ * 'limit' => 20, * 'maxLimit' => 100 * ]; * $results = $paginator->paginate($table, $settings); * ``` * * The above settings will be used to paginate any Table. You can configure Table specific settings by * keying the settings with the Table alias. * * ``` * $settings = [ * 'Articles' => [ * 'limit' => 20, * 'maxLimit' => 100 * ], * 'Comments' => [ ... ] * ]; * $results = $paginator->paginate($table, $settings); * ``` * * This would allow you to have different pagination settings for `Articles` and `Comments` tables. * * ### Controlling sort fields * * By default CakePHP will automatically allow sorting on any column on the table object being * paginated. Often times you will want to allow sorting on either associated columns or calculated * fields. In these cases you will need to define a whitelist of all the columns you wish to allow * sorting on. You can define the whitelist in the `$settings` parameter: * * ``` * $settings = [ * 'Articles' => [ * 'finder' => 'custom', * 'sortWhitelist' => ['title', 'author_id', 'comment_count'], * ] * ]; * ``` * * Passing an empty array as whitelist disallows sorting altogether. * * ### Paginating with custom finders * * You can paginate with any find type defined on your table using the `finder` option. * * ``` * $settings = [ * 'Articles' => [ * 'finder' => 'popular' * ] * ]; * $results = $paginator->paginate($table, $settings); * ``` * * Would paginate using the `find('popular')` method. * * You can also pass an already created instance of a query to this method: * * ``` * $query = $this->Articles->find('popular')->matching('Tags', function ($q) { * return $q->where(['name' => 'CakePHP']) * }); * $results = $paginator->paginate($query); * ``` * * ### Scoping Request parameters * * By using request parameter scopes you can paginate multiple queries in the same controller action: * * ``` * $articles = $paginator->paginate($articlesQuery, ['scope' => 'articles']); * $tags = $paginator->paginate($tagsQuery, ['scope' => 'tags']); * ``` * * Each of the above queries will use different query string parameter sets * for pagination data. An example URL paginating both results would be: * * ``` * /dashboard?articles[page]=1&tags[page]=2 * ``` * * @param \Cake\Datasource\RepositoryInterface|\Cake\Datasource\QueryInterface $object The table or query to paginate. * @param array $settings The settings/configuration used for pagination. * @return \Cake\Datasource\ResultSetInterface Query results * @throws \Cake\Network\Exception\NotFoundException */ public function paginate($object, array $settings = []) { if ($object instanceof QueryInterface) { $query = $object; $object = $query->repository(); } $alias = $object->alias(); $options = $this->mergeOptions($alias, $settings); $options = $this->validateSort($object, $options); $options = $this->checkLimit($options); $options += ['page' => 1, 'scope' => null]; $options['page'] = (int)$options['page'] < 1 ? 1 : (int)$options['page']; list($finder, $options) = $this->_extractFinder($options); /* @var \Cake\Datasource\RepositoryInterface $object */ if (empty($query)) { $query = $object->find($finder, $options); } else { $query->applyOptions($options); } $results = $query->all(); $numResults = count($results); $count = $numResults ? $query->count() : 0; $defaults = $this->getDefaults($alias, $settings); unset($defaults[0]); $page = $options['page']; $limit = $options['limit']; $pageCount = (int)ceil($count / $limit); $requestedPage = $page; $page = max(min($page, $pageCount), 1); $request = $this->_registry->getController()->request; $order = (array)$options['order']; $sortDefault = $directionDefault = false; if (!empty($defaults['order']) && count($defaults['order']) == 1) { $sortDefault = key($defaults['order']); $directionDefault = current($defaults['order']); } $paging = [ 'finder' => $finder, 'page' => $page, 'current' => $numResults, 'count' => $count, 'perPage' => $limit, 'prevPage' => ($page > 1), 'nextPage' => ($count > ($page * $limit)), 'pageCount' => $pageCount, 'sort' => key($order), 'direction' => current($order), 'limit' => $defaults['limit'] != $limit ? $limit : null, 'sortDefault' => $sortDefault, 'directionDefault' => $directionDefault, 'scope' => $options['scope'], ]; if (!isset($request['paging'])) { $request['paging'] = []; } $request['paging'] = [$alias => $paging] + (array)$request['paging']; if ($requestedPage > $page) { throw new NotFoundException(); } return $results; } /** * Extracts the finder name and options out of the provided pagination options * * @param array $options the pagination options * @return array An array containing in the first position the finder name and * in the second the options to be passed to it */ protected function _extractFinder($options) { $type = !empty($options['finder']) ? $options['finder'] : 'all'; unset($options['finder'], $options['maxLimit']); if (is_array($type)) { $options = (array)current($type) + $options; $type = key($type); } return [$type, $options]; } /** * Merges the various options that Pagination uses. * Pulls settings together from the following places: * * - General pagination settings * - Model specific settings. * - Request parameters * * The result of this method is the aggregate of all the option sets combined together. You can change * config value `whitelist` to modify which options/values can be set using request parameters. * * @param string $alias Model alias being paginated, if the general settings has a key with this value * that key's settings will be used for pagination instead of the general ones. * @param array $settings The settings to merge with the request data. * @return array Array of merged options. */ public function mergeOptions($alias, $settings) { $defaults = $this->getDefaults($alias, $settings); $request = $this->_registry->getController()->request; $scope = Hash::get($settings, 'scope', null); $query = $request->query; if ($scope) { $query = Hash::get($request->query, $scope, []); } $request = array_intersect_key($query, array_flip($this->_config['whitelist'])); return array_merge($defaults, $request); } /** * Get the settings for a $model. If there are no settings for a specific model, the general settings * will be used. * * @param string $alias Model name to get settings for. * @param array $settings The settings which is used for combining. * @return array An array of pagination settings for a model, or the general settings. */ public function getDefaults($alias, $settings) { if (isset($settings[$alias])) { $settings = $settings[$alias]; } $defaults = $this->config(); $maxLimit = isset($settings['maxLimit']) ? $settings['maxLimit'] : $defaults['maxLimit']; $limit = isset($settings['limit']) ? $settings['limit'] : $defaults['limit']; if ($limit > $maxLimit) { $limit = $maxLimit; } $settings['maxLimit'] = $maxLimit; $settings['limit'] = $limit; return $settings + $defaults; } /** * Validate that the desired sorting can be performed on the $object. Only fields or * virtualFields can be sorted on. The direction param will also be sanitized. Lastly * sort + direction keys will be converted into the model friendly order key. * * You can use the whitelist parameter to control which columns/fields are available for sorting. * This helps prevent users from ordering large result sets on un-indexed values. * * If you need to sort on associated columns or synthetic properties you will need to use a whitelist. * * Any columns listed in the sort whitelist will be implicitly trusted. You can use this to sort * on synthetic columns, or columns added in custom find operations that may not exist in the schema. * * @param \Cake\Datasource\RepositoryInterface $object Repository object. * @param array $options The pagination options being used for this request. * @return array An array of options with sort + direction removed and replaced with order if possible. */ public function validateSort(RepositoryInterface $object, array $options) { if (isset($options['sort'])) { $direction = null; if (isset($options['direction'])) { $direction = strtolower($options['direction']); } if (!in_array($direction, ['asc', 'desc'])) { $direction = 'asc'; } $options['order'] = [$options['sort'] => $direction]; } unset($options['sort'], $options['direction']); if (empty($options['order'])) { $options['order'] = []; } if (!is_array($options['order'])) { return $options; } $inWhitelist = false; if (isset($options['sortWhitelist'])) { $field = key($options['order']); $inWhitelist = in_array($field, $options['sortWhitelist'], true); if (!$inWhitelist) { $options['order'] = []; return $options; } } $options['order'] = $this->_prefix($object, $options['order'], $inWhitelist); return $options; } /** * Prefixes the field with the table alias if possible. * * @param \Cake\Datasource\RepositoryInterface $object Repository object. * @param array $order Order array. * @param bool $whitelisted Whether or not the field was whitelisted * @return array Final order array. */ protected function _prefix(RepositoryInterface $object, $order, $whitelisted = false) { $tableAlias = $object->alias(); $tableOrder = []; foreach ($order as $key => $value) { if (is_numeric($key)) { $tableOrder[] = $value; continue; } $field = $key; $alias = $tableAlias; if (strpos($key, '.') !== false) { list($alias, $field) = explode('.', $key); } $correctAlias = ($tableAlias === $alias); if ($correctAlias && $whitelisted) { // Disambiguate fields in schema. As id is quite common. if ($object->hasField($field)) { $field = $alias . '.' . $field; } $tableOrder[$field] = $value; } elseif ($correctAlias && $object->hasField($field)) { $tableOrder[$tableAlias . '.' . $field] = $value; } elseif (!$correctAlias && $whitelisted) { $tableOrder[$alias . '.' . $field] = $value; } } return $tableOrder; } /** * Check the limit parameter and ensure it's within the maxLimit bounds. * * @param array $options An array of options with a limit key to be checked. * @return array An array of options for pagination */ public function checkLimit(array $options) { $options['limit'] = (int)$options['limit']; if (empty($options['limit']) || $options['limit'] < 1) { $options['limit'] = 1; } $options['limit'] = max(min($options['limit'], $options['maxLimit']), 1); return $options; } }
batmorell/downloadsCenter
vendor/cakephp/cakephp/src/Controller/Component/PaginatorComponent.php
PHP
mit
15,385
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = global || self, factory(global.VueMask = {})); }(this, function (exports) { 'use strict'; function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function (obj) { return typeof obj; }; } else { _typeof = function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } var placeholderChar = '_'; var strFunction = 'function'; var emptyArray = []; function convertMaskToPlaceholder() { var mask = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : emptyArray; var placeholderChar$1 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : placeholderChar; if (!isArray(mask)) { throw new Error('Text-mask:convertMaskToPlaceholder; The mask property must be an array.'); } if (mask.indexOf(placeholderChar$1) !== -1) { throw new Error('Placeholder character must not be used as part of the mask. Please specify a character ' + 'that is not present in your mask as your placeholder character.\n\n' + "The placeholder character that was received is: ".concat(JSON.stringify(placeholderChar$1), "\n\n") + "The mask that was received is: ".concat(JSON.stringify(mask))); } return mask.map(function (char) { return char instanceof RegExp ? placeholderChar$1 : char; }).join(''); } function isArray(value) { return Array.isArray && Array.isArray(value) || value instanceof Array; } var strCaretTrap = '[]'; function processCaretTraps(mask) { var indexes = []; var indexOfCaretTrap; while (indexOfCaretTrap = mask.indexOf(strCaretTrap), indexOfCaretTrap !== -1) { indexes.push(indexOfCaretTrap); mask.splice(indexOfCaretTrap, 1); } return { maskWithoutCaretTraps: mask, indexes: indexes }; } var emptyArray$1 = []; var emptyString = ''; function conformToMask() { var rawValue = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : emptyString; var mask = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : emptyArray$1; var config = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; if (!isArray(mask)) { if (_typeof(mask) === strFunction) { mask = mask(rawValue, config); mask = processCaretTraps(mask).maskWithoutCaretTraps; } else { throw new Error('Text-mask:conformToMask; The mask property must be an array.'); } } var _config$guide = config.guide, guide = _config$guide === void 0 ? true : _config$guide, _config$previousConfo = config.previousConformedValue, previousConformedValue = _config$previousConfo === void 0 ? emptyString : _config$previousConfo, _config$placeholderCh = config.placeholderChar, placeholderChar$1 = _config$placeholderCh === void 0 ? placeholderChar : _config$placeholderCh, _config$placeholder = config.placeholder, placeholder = _config$placeholder === void 0 ? convertMaskToPlaceholder(mask, placeholderChar$1) : _config$placeholder, currentCaretPosition = config.currentCaretPosition, keepCharPositions = config.keepCharPositions; var suppressGuide = guide === false && previousConformedValue !== undefined; var rawValueLength = rawValue.length; var previousConformedValueLength = previousConformedValue.length; var placeholderLength = placeholder.length; var maskLength = mask.length; var editDistance = rawValueLength - previousConformedValueLength; var isAddition = editDistance > 0; var indexOfFirstChange = currentCaretPosition + (isAddition ? -editDistance : 0); var indexOfLastChange = indexOfFirstChange + Math.abs(editDistance); if (keepCharPositions === true && !isAddition) { var compensatingPlaceholderChars = emptyString; for (var i = indexOfFirstChange; i < indexOfLastChange; i++) { if (placeholder[i] === placeholderChar$1) { compensatingPlaceholderChars += placeholderChar$1; } } rawValue = rawValue.slice(0, indexOfFirstChange) + compensatingPlaceholderChars + rawValue.slice(indexOfFirstChange, rawValueLength); } var rawValueArr = rawValue.split(emptyString).map(function (char, i) { return { char: char, isNew: i >= indexOfFirstChange && i < indexOfLastChange }; }); for (var _i = rawValueLength - 1; _i >= 0; _i--) { var char = rawValueArr[_i].char; if (char !== placeholderChar$1) { var shouldOffset = _i >= indexOfFirstChange && previousConformedValueLength === maskLength; if (char === placeholder[shouldOffset ? _i - editDistance : _i]) { rawValueArr.splice(_i, 1); } } } var conformedValue = emptyString; var someCharsRejected = false; placeholderLoop: for (var _i2 = 0; _i2 < placeholderLength; _i2++) { var charInPlaceholder = placeholder[_i2]; if (charInPlaceholder === placeholderChar$1) { if (rawValueArr.length > 0) { while (rawValueArr.length > 0) { var _rawValueArr$shift = rawValueArr.shift(), rawValueChar = _rawValueArr$shift.char, isNew = _rawValueArr$shift.isNew; if (rawValueChar === placeholderChar$1 && suppressGuide !== true) { conformedValue += placeholderChar$1; continue placeholderLoop; } else if (mask[_i2].test(rawValueChar)) { if (keepCharPositions !== true || isNew === false || previousConformedValue === emptyString || guide === false || !isAddition) { conformedValue += rawValueChar; } else { var rawValueArrLength = rawValueArr.length; var indexOfNextAvailablePlaceholderChar = null; for (var _i3 = 0; _i3 < rawValueArrLength; _i3++) { var charData = rawValueArr[_i3]; if (charData.char !== placeholderChar$1 && charData.isNew === false) { break; } if (charData.char === placeholderChar$1) { indexOfNextAvailablePlaceholderChar = _i3; break; } } if (indexOfNextAvailablePlaceholderChar !== null) { conformedValue += rawValueChar; rawValueArr.splice(indexOfNextAvailablePlaceholderChar, 1); } else { _i2--; } } continue placeholderLoop; } else { someCharsRejected = true; } } } if (suppressGuide === false) { conformedValue += placeholder.substr(_i2, placeholderLength); } break; } else { conformedValue += charInPlaceholder; } } if (suppressGuide && isAddition === false) { var indexOfLastFilledPlaceholderChar = null; for (var _i4 = 0; _i4 < conformedValue.length; _i4++) { if (placeholder[_i4] === placeholderChar$1) { indexOfLastFilledPlaceholderChar = _i4; } } if (indexOfLastFilledPlaceholderChar !== null) { conformedValue = conformedValue.substr(0, indexOfLastFilledPlaceholderChar + 1); } else { conformedValue = emptyString; } } return { conformedValue: conformedValue, meta: { someCharsRejected: someCharsRejected } }; } var NEXT_CHAR_OPTIONAL = { __nextCharOptional__: true }; var defaultMaskReplacers = { '#': /\d/, A: /[a-z]/i, N: /[a-z0-9]/i, '?': NEXT_CHAR_OPTIONAL, X: /./ }; var stringToRegexp = function stringToRegexp(str) { var lastSlash = str.lastIndexOf('/'); return new RegExp(str.slice(1, lastSlash), str.slice(lastSlash + 1)); }; var makeRegexpOptional = function makeRegexpOptional(charRegexp) { return stringToRegexp(charRegexp.toString().replace(/.(\/)[gmiyus]{0,6}$/, function (match) { return match.replace('/', '?/'); })); }; var escapeIfNeeded = function escapeIfNeeded(char) { return '[\\^$.|?*+()'.indexOf(char) > -1 ? "\\".concat(char) : char; }; var charRegexp = function charRegexp(char) { return new RegExp("/[".concat(escapeIfNeeded(char), "]/")); }; var isRegexp = function isRegexp(entity) { return entity instanceof RegExp; }; var castToRegexp = function castToRegexp(char) { return isRegexp(char) ? char : charRegexp(char); }; function stringMaskToRegExpMask(stringMask) { return stringMask.split('').map(function (char, index, array) { var maskChar = defaultMaskReplacers[char] || char; var previousChar = array[index - 1]; var previousMaskChar = defaultMaskReplacers[previousChar] || previousChar; if (maskChar === NEXT_CHAR_OPTIONAL) { return null; } if (previousMaskChar === NEXT_CHAR_OPTIONAL) { return makeRegexpOptional(castToRegexp(maskChar)); } return maskChar; }).filter(Boolean); } var trigger = function trigger(el, type) { var e = document.createEvent('HTMLEvents'); e.initEvent(type, true, true); el.dispatchEvent(e); }; var queryInputElementInside = function queryInputElementInside(el) { return el instanceof HTMLInputElement ? el : el.querySelector('input') || el; }; var inBrowser = typeof window !== 'undefined'; var UA = inBrowser && window.navigator.userAgent.toLowerCase(); var isEdge = UA && UA.indexOf('edge/') > 0; var isAndroid = UA && UA.indexOf('android') > 0; var isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge; function createOptions() { var elementOptions = new Map(); var defaultOptions = { previousValue: '', mask: [] }; function get(el) { return elementOptions.get(el) || _objectSpread2({}, defaultOptions); } function partiallyUpdate(el, newOptions) { elementOptions.set(el, _objectSpread2({}, get(el), {}, newOptions)); } function remove(el) { elementOptions.delete(el); } return { partiallyUpdate: partiallyUpdate, remove: remove, get: get }; } var options = createOptions(); function triggerInputUpdate(el) { var fn = trigger.bind(null, el, 'input'); if (isAndroid && isChrome) { setTimeout(fn, 0); } else { fn(); } } function updateValue(el) { var force = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var value = el.value; var _options$get = options.get(el), previousValue = _options$get.previousValue, mask = _options$get.mask; var isValueChanged = value !== previousValue; var isLengthIncreased = value.length > previousValue.length; var isUpdateNeeded = value && isValueChanged && isLengthIncreased; if (force || isUpdateNeeded) { var _conformToMask = conformToMask(value, mask, { guide: false }), conformedValue = _conformToMask.conformedValue; el.value = conformedValue; triggerInputUpdate(el); } options.partiallyUpdate(el, { previousValue: value }); } function updateMask(el, mask) { options.partiallyUpdate(el, { mask: stringMaskToRegExpMask(mask) }); } var directive = { bind: function bind(el, _ref) { var value = _ref.value; el = queryInputElementInside(el); updateMask(el, value); updateValue(el); }, componentUpdated: function componentUpdated(el, _ref2) { var value = _ref2.value, oldValue = _ref2.oldValue; el = queryInputElementInside(el); var isMaskChanged = value !== oldValue; if (isMaskChanged) { updateMask(el, value); } updateValue(el, isMaskChanged); }, unbind: function unbind(el) { el = queryInputElementInside(el); options.remove(el); } }; var plugin = (function (Vue) { Vue.directive('mask', directive); }); exports.VueMaskDirective = directive; exports.VueMaskPlugin = plugin; exports.default = plugin; Object.defineProperty(exports, '__esModule', { value: true }); }));
sufuf3/cdnjs
ajax/libs/v-mask/2.0.2/v-mask.js
JavaScript
mit
13,896
module Locomotive module Extensions module ContentType module Sync extend ActiveSupport::Concern included do after_save :sync_relationships_order_by end protected # If the user changes the order of the content type, we have to make # sure that other related content types tied to the current one through # a belongs_to / has_many relationship also gets updated. # def sync_relationships_order_by current_class_name = self.klass_with_custom_fields(:entries).name self.entries_custom_fields.where(type: 'belongs_to').each do |field| target_content_type = self.class_name_to_content_type(field.class_name) operations = { '$set' => {} } target_content_type.entries_custom_fields.where(:type.in => %w(has_many many_to_many), ui_enabled: false, class_name: current_class_name).each do |target_field| if target_field.order_by != self.order_by_definition target_field.order_by = self.order_by_definition # needed by the custom_fields_recipe_for method in order to be up to date operations['$set']["entries_custom_fields.#{target_field._index}.order_by"] = self.order_by_definition end end unless operations['$set'].empty? persist_content_type_changes target_content_type, operations end end end # Save the changes for the content type passed in parameter without forgetting # to bump the version.. It also updates the recipe for related entries. # That method does not call the Mongoid API but directly MongoDB. # # @param [ ContentType ] content_type The content type to update # @param [ Hash ] operations The MongoDB atomic operations # def persist_content_type_changes(content_type, operations) content_type.entries_custom_fields_version += 1 operations['$set']['entries_custom_fields_version'] = content_type.entries_custom_fields_version self.collection.find(_id: content_type._id).update(operations) collection, selector = content_type.entries.collection, content_type.entries.criteria.selector collection.find(selector).update({ '$set' => { 'custom_fields_recipe' => content_type.custom_fields_recipe_for(:entries) } }, multi: true) end end end end end
LaunchPadLab/engine
app/models/locomotive/extensions/content_type/sync.rb
Ruby
mit
2,479
<?xml version="1.0" ?><!DOCTYPE TS><TS language="zh_TW" version="2.0"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Bitcoin</source> <translation>關於位元幣</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;Bitcoin&lt;/b&gt; version</source> <translation>&lt;b&gt;位元幣&lt;/b&gt;版本</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation> 這是一套實驗性的軟體. 此軟體是依據 MIT/X11 軟體授權條款散布, 詳情請見附帶的 COPYING 檔案, 或是以下網站: http://www.opensource.org/licenses/mit-license.php. 此產品也包含了由 OpenSSL Project 所開發的 OpenSSL Toolkit (http://www.openssl.org/) 軟體, 由 Eric Young (eay@cryptsoft.com) 撰寫的加解密軟體, 以及由 Thomas Bernard 所撰寫的 UPnP 軟體.</translation> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation>版權</translation> </message> <message> <location line="+0"/> <source>The Bitcoin developers</source> <translation>位元幣開發人員</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>位址簿</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>點兩下來修改位址或標記</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>產生新位址</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>複製目前選取的位址到系統剪貼簿</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>新增位址</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your Bitcoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>這些是你用來收款的位元幣位址. 你可以提供不同的位址給不同的付款人, 來追蹤是誰支付給你.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>複製位址</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>顯示 &amp;QR 條碼</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a Bitcoin address</source> <translation>簽署訊息是用來證明位元幣位址是你的</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>訊息簽署</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>從列表中刪除目前選取的位址</translation> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>將目前分頁的資料匯出存成檔案</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation>匯出</translation> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified Bitcoin address</source> <translation>驗證訊息是用來確認訊息是用指定的位元幣位址簽署的</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>訊息驗證</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>刪除</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your Bitcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>這是你用來付款的位元幣位址. 在付錢之前, 務必要檢查金額和收款位址是否正確.</translation> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>複製標記</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>編輯</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation>付錢</translation> </message> <message> <location line="+265"/> <source>Export Address Book Data</source> <translation>匯出位址簿資料</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>逗號區隔資料檔 (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>匯出失敗</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>無法寫入檔案 %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>標記</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>位址</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(沒有標記)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>密碼對話視窗</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>輸入密碼</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>新的密碼</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>重複新密碼</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>輸入錢包的新密碼.&lt;br/&gt;請用&lt;b&gt;10個以上的字元&lt;/b&gt;, 或是&lt;b&gt;8個以上的單字&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>錢包加密</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>這個動作需要用你的錢包密碼來解鎖</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>錢包解鎖</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>這個動作需要用你的錢包密碼來解密</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>錢包解密</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>變更密碼</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>輸入錢包的新舊密碼.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>錢包加密確認</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR BITCOINS&lt;/b&gt;!</source> <translation>警告: 如果將錢包加密後忘記密碼, 你會&lt;b&gt;失去其中所有的位元幣&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>你確定要將錢包加密嗎?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>重要: 請改用新產生有加密的錢包檔, 來取代之前錢包檔的備份. 為了安全性的理由, 當你開始使用新的有加密的錢包時, 舊錢包的備份就不能再使用了.</translation> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>警告: 大寫字母鎖定作用中!</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>錢包已加密</translation> </message> <message> <location line="-56"/> <source>Bitcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your bitcoins from being stolen by malware infecting your computer.</source> <translation>位元幣現在要關閉以完成加密程序. 請記住, 加密錢包無法完全防止入侵電腦的惡意程式偷取你的位元幣.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>錢包加密失敗</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>錢包加密因程式內部錯誤而失敗. 你的錢包還是沒有加密.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>提供的密碼不符.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>錢包解鎖失敗</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>用來解密錢包的密碼輸入錯誤.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>錢包解密失敗</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>錢包密碼變更成功.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+254"/> <source>Sign &amp;message...</source> <translation>訊息簽署...</translation> </message> <message> <location line="+246"/> <source>Synchronizing with network...</source> <translation>網路同步中...</translation> </message> <message> <location line="-321"/> <source>&amp;Overview</source> <translation>總覽</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>顯示錢包一般總覽</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>交易</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>瀏覽交易紀錄</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>編輯位址與標記的儲存列表</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>顯示收款位址的列表</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>結束</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>結束應用程式</translation> </message> <message> <location line="+7"/> <source>Show information about Bitcoin</source> <translation>顯示位元幣相關資訊</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>關於 &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>顯示有關於 Qt 的資訊</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>選項...</translation> </message> <message> <location line="+9"/> <source>&amp;Encrypt Wallet...</source> <translation>錢包加密...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>錢包備份...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>密碼變更...</translation> </message> <message> <location line="+251"/> <source>Importing blocks from disk...</source> <translation>從磁碟匯入區塊中...</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation>重建磁碟區塊索引中...</translation> </message> <message> <location line="-319"/> <source>Send coins to a Bitcoin address</source> <translation>付錢到位元幣位址</translation> </message> <message> <location line="+52"/> <source>Modify configuration options for Bitcoin</source> <translation>修改位元幣的設定選項</translation> </message> <message> <location line="+12"/> <source>Backup wallet to another location</source> <translation>將錢包備份到其它地方</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>變更錢包加密用的密碼</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>除錯視窗</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>開啓除錯與診斷主控台</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>驗證訊息...</translation> </message> <message> <location line="-183"/> <location line="+6"/> <location line="+508"/> <source>Bitcoin</source> <translation>位元幣</translation> </message> <message> <location line="-514"/> <location line="+6"/> <source>Wallet</source> <translation>錢包</translation> </message> <message> <location line="+107"/> <source>&amp;Send</source> <translation>付出</translation> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation>收受</translation> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation>位址</translation> </message> <message> <location line="+23"/> <location line="+2"/> <source>&amp;About Bitcoin</source> <translation>關於位元幣</translation> </message> <message> <location line="+10"/> <location line="+2"/> <source>&amp;Show / Hide</source> <translation>顯示或隱藏</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation>顯示或隱藏主視窗</translation> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation>將屬於你的錢包的密鑰加密</translation> </message> <message> <location line="+7"/> <source>Sign messages with your Bitcoin addresses to prove you own them</source> <translation>用位元幣位址簽署訊息來證明那是你的</translation> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified Bitcoin addresses</source> <translation>驗證訊息來確認是用指定的位元幣位址簽署的</translation> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>檔案</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>設定</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>求助</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>分頁工具列</translation> </message> <message> <location line="-228"/> <location line="+288"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="-5"/> <location line="+5"/> <source>Bitcoin client</source> <translation>位元幣客戶端軟體</translation> </message> <message numerus="yes"> <location line="+121"/> <source>%n active connection(s) to Bitcoin network</source> <translation><numerusform>與位元幣網路有 %n 個連線在使用中</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation>目前沒有區塊來源...</translation> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation>已處理了估計全部 %2 個中的 %1 個區塊的交易紀錄.</translation> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>已處理了 %1 個區塊的交易紀錄.</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation><numerusform>%n 個小時</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>%n 天</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation><numerusform>%n 個星期</numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation>落後 %1</translation> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation>最近收到的區塊是在 %1 之前生產出來.</translation> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation>會看不見在這之後的交易.</translation> </message> <message> <location line="+22"/> <source>Error</source> <translation>錯誤</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation>警告</translation> </message> <message> <location line="+3"/> <source>Information</source> <translation>資訊</translation> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation>這筆交易的資料大小超過限制了. 你還是可以付出 %1 的費用來傳送, 這筆費用會付給處理你的交易的節點, 並幫助維持整個網路. 你願意支付這項費用嗎?</translation> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>最新狀態</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>進度追趕中...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>確認交易手續費</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>付款交易</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>收款交易</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>日期: %1 金額: %2 類別: %3 位址: %4</translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation>URI 處理</translation> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid Bitcoin address or malformed URI parameters.</source> <translation>無法解析 URI! 也許位元幣位址無效或 URI 參數有誤.</translation> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>錢包&lt;b&gt;已加密&lt;/b&gt;並且正&lt;b&gt;解鎖中&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>錢包&lt;b&gt;已加密&lt;/b&gt;並且正&lt;b&gt;上鎖中&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+110"/> <source>A fatal error occurred. Bitcoin can no longer continue safely and will quit.</source> <translation>發生了致命的錯誤. 位元幣程式無法再繼續安全執行, 只好結束.</translation> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+105"/> <source>Network Alert</source> <translation>網路警報</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>編輯位址</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>標記</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>與這個位址簿項目關聯的標記</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>位址</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>與這個位址簿項目關聯的位址. 付款位址才能被更改.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>新收款位址</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>新增付款位址</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>編輯收款位址</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>編輯付款位址</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>輸入的位址&quot;%1&quot;已存在於位址簿中.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Bitcoin address.</source> <translation>輸入的位址 &quot;%1&quot; 並不是有效的位元幣位址.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>無法將錢包解鎖.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>新密鑰產生失敗.</translation> </message> </context> <context> <name>FreespaceChecker</name> <message> <location filename="../intro.cpp" line="+61"/> <source>A new data directory will be created.</source> <translation>將會建立新的資料目錄.</translation> </message> <message> <location line="+22"/> <source>name</source> <translation>名稱</translation> </message> <message> <location line="+2"/> <source>Directory already exists. Add %1 if you intend to create a new directory here.</source> <translation>目錄已經存在了. 如果你要在裡面建立新目錄的話, 請加上 %1.</translation> </message> <message> <location line="+3"/> <source>Path already exists, and is not a directory.</source> <translation>已經存在該路徑了, 並且不是一個目錄.</translation> </message> <message> <location line="+7"/> <source>Cannot create data directory here.</source> <translation>無法在這裡新增資料目錄</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+517"/> <location line="+13"/> <source>Bitcoin-Qt</source> <translation>位元幣-Qt</translation> </message> <message> <location line="-13"/> <source>version</source> <translation>版本</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>用法:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>命令列選項</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>使用界面選項</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>設定語言, 比如說 &quot;de_DE&quot; (預設: 系統語系)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>啓動時最小化 </translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>顯示啓動畫面 (預設: 1)</translation> </message> <message> <location line="+1"/> <source>Choose data directory on startup (default: 0)</source> <translation>啓動時選擇資料目錄 (預設值: 0)</translation> </message> </context> <context> <name>Intro</name> <message> <location filename="../forms/intro.ui" line="+14"/> <source>Welcome</source> <translation>歡迎</translation> </message> <message> <location line="+9"/> <source>Welcome to Bitcoin-Qt.</source> <translation>歡迎使用&quot;位元幣-Qt&quot;</translation> </message> <message> <location line="+26"/> <source>As this is the first time the program is launched, you can choose where Bitcoin-Qt will store its data.</source> <translation>由於這是程式第一次啓動, 你可以選擇&quot;位元幣-Qt&quot;儲存資料的地方.</translation> </message> <message> <location line="+10"/> <source>Bitcoin-Qt will download and store a copy of the Bitcoin block chain. At least %1GB of data will be stored in this directory, and it will grow over time. The wallet will also be stored in this directory.</source> <translation>位元幣-Qt 會下載並儲存一份位元幣區塊鏈結的拷貝. 至少有 %1GB 的資料會儲存到這個目錄中, 並且還會持續增長. 另外錢包資料也會儲存在這個目錄.</translation> </message> <message> <location line="+10"/> <source>Use the default data directory</source> <translation>用預設的資料目錄</translation> </message> <message> <location line="+7"/> <source>Use a custom data directory:</source> <translation>用自定的資料目錄:</translation> </message> <message> <location filename="../intro.cpp" line="+100"/> <source>Error</source> <translation>錯誤</translation> </message> <message> <location line="+9"/> <source>GB of free space available</source> <translation>GB 可用空間</translation> </message> <message> <location line="+3"/> <source>(of %1GB needed)</source> <translation>(需要 %1GB)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>選項</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>主要</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation>非必要的交易手續費, 以 kB 為計費單位, 且有助於縮短你的交易處理時間. 大部份交易資料的大小是 1 kB.</translation> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>付交易手續費</translation> </message> <message> <location line="+31"/> <source>Automatically start Bitcoin after logging in to the system.</source> <translation>在登入系統後自動啓動位元幣.</translation> </message> <message> <location line="+3"/> <source>&amp;Start Bitcoin on system login</source> <translation>系統登入時啟動位元幣</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation>回復所有客戶端軟體選項成預設值.</translation> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation>選項回復</translation> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation>網路</translation> </message> <message> <location line="+6"/> <source>Automatically open the Bitcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>自動在路由器上開啟 Bitcoin 的客戶端通訊埠. 只有在你的路由器支援 UPnP 且開啟時才有作用.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>用 &amp;UPnP 設定通訊埠對應</translation> </message> <message> <location line="+7"/> <source>Connect to the Bitcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>透過 SOCKS 代理伺服器連線至位元幣網路 (比如說要透過 Tor 連線).</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>透過 SOCKS 代理伺服器連線:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>代理伺服器位址:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>代理伺服器的網際網路位址 (比如說 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>通訊埠:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>代理伺服器的通訊埠 (比如說 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS 協定版本:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>代理伺服器的 SOCKS 協定版本 (比如說 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>視窗</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>最小化視窗後只在通知區域顯示圖示</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>最小化至通知區域而非工作列</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>當視窗關閉時將其最小化, 而非結束應用程式. 當勾選這個選項時, 應用程式只能用選單中的結束來停止執行.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>關閉時最小化</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>顯示</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>使用界面語言</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting Bitcoin.</source> <translation>可以在這裡設定使用者介面的語言. 這個設定在位元幣程式重啓後才會生效.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>金額顯示單位:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>選擇操作界面與付錢時預設顯示的細分單位.</translation> </message> <message> <location line="+9"/> <source>Whether to show Bitcoin addresses in the transaction list or not.</source> <translation>是否要在交易列表中顯示位元幣位址.</translation> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>在交易列表顯示位址</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>好</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>取消</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>套用</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+54"/> <source>default</source> <translation>預設</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation>確認回復選項</translation> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation>有些設定可能需要重新啓動客戶端軟體才會生效.</translation> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation>你想要就做下去嗎?</translation> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>警告</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting Bitcoin.</source> <translation>這個設定會在位元幣程式重啓後生效.</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>提供的代理伺服器位址無效</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>表單</translation> </message> <message> <location line="+50"/> <location line="+202"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Bitcoin network after a connection is established, but this process has not completed yet.</source> <translation>顯示的資訊可能是過期的. 與位元幣網路的連線建立後, 你的錢包會自動和網路同步, 但這個步驟還沒完成.</translation> </message> <message> <location line="-131"/> <source>Unconfirmed:</source> <translation>未確認金額:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>錢包</translation> </message> <message> <location line="+49"/> <source>Confirmed:</source> <translation>已確認金額:</translation> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation>目前可用餘額</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source> <translation>尚未確認的交易的總金額, 可用餘額不包含此金額</translation> </message> <message> <location line="+13"/> <source>Immature:</source> <translation>未熟成</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>尚未熟成的開採金額</translation> </message> <message> <location line="+13"/> <source>Total:</source> <translation>總金額:</translation> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation>目前全部餘額</translation> </message> <message> <location line="+53"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;最近交易&lt;/b&gt;</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>沒同步</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+108"/> <source>Cannot start bitcoin: click-to-pay handler</source> <translation>無法啟動 bitcoin 隨按隨付處理器</translation> </message> </context> <context> <name>QObject</name> <message> <location filename="../bitcoin.cpp" line="+92"/> <location filename="../intro.cpp" line="-32"/> <source>Bitcoin</source> <translation>位元幣</translation> </message> <message> <location line="+1"/> <source>Error: Specified data directory &quot;%1&quot; does not exist.</source> <translation>錯誤: 不存在指定的資料目錄 &quot;%1&quot;.</translation> </message> <message> <location filename="../intro.cpp" line="+1"/> <source>Error: Specified data directory &quot;%1&quot; can not be created.</source> <translation>錯誤: 無法新增指定的資料目錄 &quot;%1&quot;.</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>QR 條碼對話視窗</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>付款單</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>金額:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>標記:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>訊息:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>儲存為...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+64"/> <source>Error encoding URI into QR Code.</source> <translation>將 URI 編碼成 QR 條碼失敗</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>輸入的金額無效, 請檢查看看.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>造出的網址太長了,請把標籤或訊息的文字縮短再試看看.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>儲存 QR 條碼</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>PNG 圖檔 (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>客戶端軟體名稱</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+345"/> <source>N/A</source> <translation>無</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>客戶端軟體版本</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>資訊</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>使用 OpenSSL 版本</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>啓動時間</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>網路</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>連線數</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>位於測試網路</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>區塊鎖鏈</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>目前區塊數</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>估算總區塊數</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>最近區塊時間</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>開啓</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>命令列選項</translation> </message> <message> <location line="+7"/> <source>Show the Bitcoin-Qt help message to get a list with possible Bitcoin command-line options.</source> <translation>顯示&quot;位元幣-Qt&quot;的求助訊息, 來取得可用的命令列選項列表.</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>顯示</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>主控台</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>建置日期</translation> </message> <message> <location line="-104"/> <source>Bitcoin - Debug window</source> <translation>位元幣 - 除錯視窗</translation> </message> <message> <location line="+25"/> <source>Bitcoin Core</source> <translation>位元幣核心</translation> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>除錯紀錄檔</translation> </message> <message> <location line="+7"/> <source>Open the Bitcoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>從目前的資料目錄下開啓位元幣的除錯紀錄檔. 當紀錄檔很大時可能要花好幾秒的時間.</translation> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>清主控台</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the Bitcoin RPC console.</source> <translation>歡迎使用位元幣 RPC 主控台.</translation> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>請用上下游標鍵來瀏覽歷史指令, 且可用 &lt;b&gt;Ctrl-L&lt;/b&gt; 來清理畫面.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>請打 &lt;b&gt;help&lt;/b&gt; 來看可用指令的簡介.</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+128"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>付錢</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>一次付給多個人</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>加收款人</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>移除所有交易欄位</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>全部清掉</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>餘額:</translation> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>確認付款動作</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>付出</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-62"/> <location line="+2"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; 給 %2 (%3)</translation> </message> <message> <location line="+6"/> <source>Confirm send coins</source> <translation>確認要付錢</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>確定要付出 %1 嗎?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation>和</translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>無效的收款位址, 請再檢查看看.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>付款金額必須大於 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>金額超過餘額了.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>包含 %1 的交易手續費後, 總金額超過你的餘額了.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>發現有重複的位址. 每個付款動作中, 只能付給個別的位址一次.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation>錯誤: 交易產生失敗!</translation> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>錯誤: 交易被拒絕. 有時候會發生這種錯誤, 是因為你錢包中的一些錢已經被花掉了. 比如說你複製了錢包檔 wallet.dat, 然後用複製的錢包花掉了錢, 你現在所用的原來的錢包中卻沒有該筆交易紀錄.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>表單</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>金額:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>付給:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>付款的目標位址 (比如說 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>輸入一個標記給這個位址, 並加到位址簿中</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>標記:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>從位址簿中選一個位址</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>從剪貼簿貼上位址</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>去掉這個收款人</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a Bitcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>輸入位元幣位址 (比如說 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>簽章 - 簽署或驗證訊息</translation> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>訊息簽署</translation> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>你可以用自己的位址來簽署訊息, 以證明你對它的所有權. 但是請小心, 不要簽署語意含糊不清的內容, 因為釣魚式詐騙可能會用騙你簽署的手法來冒充是你. 只有在語句中的細節你都同意時才簽署.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>用來簽署訊息的位址 (比如說 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>從位址簿選一個位址</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>從剪貼簿貼上位址</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>在這裡輸入你想簽署的訊息</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation>簽章</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation>複製目前的簽章到系統剪貼簿</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Bitcoin address</source> <translation>簽署訊息是用來證明這個位元幣位址是你的</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>訊息簽署</translation> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation>重置所有訊息簽署欄位</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>全部清掉</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>訊息驗證</translation> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation>請在下面輸入簽署的位址, 訊息(請確認完整複製了所包含的換行, 空格, 跳位符號等等), 與簽章, 以驗證該訊息. 請小心, 除了訊息內容外, 不要對簽章本身過度解讀, 以避免被用&quot;中間人攻擊法&quot;詐騙.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>簽署該訊息的位址 (比如說 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified Bitcoin address</source> <translation>驗證訊息是用來確認訊息是用指定的位元幣位址簽署的</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation>訊息驗證</translation> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation>重置所有訊息驗證欄位</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a Bitcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>輸入位元幣位址 (比如說 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>按&quot;訊息簽署&quot;來產生簽章</translation> </message> <message> <location line="+3"/> <source>Enter Bitcoin signature</source> <translation>輸入位元幣簽章</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>輸入的位址無效.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>請檢查位址是否正確後再試一次.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>輸入的位址沒有指到任何密鑰.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>錢包解鎖已取消.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>沒有所輸入位址的密鑰.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>訊息簽署失敗.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>訊息已簽署.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>無法將這個簽章解碼.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>請檢查簽章是否正確後再試一次.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>這個簽章與訊息的數位摘要不符.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>訊息驗證失敗.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>訊息已驗證.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The Bitcoin developers</source> <translation>位元幣開發人員</translation> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>在 %1 前未定</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1/離線中</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/未確認</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>經確認 %1 次</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>狀態</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>, 已公告至 %n 個節點</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>日期</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>來源</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>生產出</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>來處</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>目的</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>自己的位址</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>標籤</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>入帳</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>將在 %n 個區塊產出後熟成</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>不被接受</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>出帳</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>交易手續費</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>淨額</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>訊息</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>附註</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>交易識別碼</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>生產出來的錢要再等 120 個區塊熟成之後, 才能夠花用. 當你產出區塊時, 它會被公布到網路上, 以被串連至區塊鎖鏈. 如果串連失敗了, 它的狀態就會變成&quot;不被接受&quot;, 且不能被花用. 當你產出區塊的幾秒鐘內, 也有其他節點產出區塊的話, 有時候就會發生這種情形.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>除錯資訊</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>交易</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation>輸入</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>金額</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>是</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>否</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, 尚未成功公告出去</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation><numerusform>在接下來 %n 個區塊產出前未定</numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>未知</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>交易明細</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>此版面顯示交易的詳細說明</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>日期</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>種類</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>位址</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>金額</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation><numerusform>在接下來 %n 個區塊產出前未定</numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>在 %1 前未定</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>離線中 (經確認 %1 次)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>未確認 (經確認 %1 次, 應確認 %2 次)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>已確認 (經確認 %1 次)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation><numerusform>開採金額將可在 %n 個區塊熟成後可用</numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>沒有其他節點收到這個區塊, 也許它不被接受!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>生產出但不被接受</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>收受於</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>收受自</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>付出至</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>付給自己</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>開採所得</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(不適用)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>交易狀態. 移動游標至欄位上方來顯示確認次數.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>收到交易的日期與時間.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>交易的種類.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>交易的目標位址.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>減去或加入至餘額的金額</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>全部</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>今天</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>這週</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>這個月</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>上個月</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>今年</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>指定範圍...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>收受於</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>付出至</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>給自己</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>開採所得</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>其他</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>輸入位址或標記來搜尋</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>最小金額</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>複製位址</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>複製標記</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>複製金額</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>複製交易識別碼</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>編輯標記</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>顯示交易明細</translation> </message> <message> <location line="+143"/> <source>Export Transaction Data</source> <translation>匯出交易資料</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>逗號分隔資料檔 (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>已確認</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>日期</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>種類</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>標記</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>位址</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>金額</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>識別碼</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>匯出失敗</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>無法寫入至 %1 檔案.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>範圍:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>至</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>付錢</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+46"/> <source>&amp;Export</source> <translation>匯出</translation> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation>將目前分頁的資料匯出存成檔案</translation> </message> <message> <location line="+197"/> <source>Backup Wallet</source> <translation>錢包備份</translation> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation>錢包資料檔 (*.dat)</translation> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation>備份失敗</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>儲存錢包資料到新的地方失敗</translation> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation>備份成功</translation> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation>錢包的資料已經成功儲存到新的地方了.</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+98"/> <source>Bitcoin version</source> <translation>位元幣版本</translation> </message> <message> <location line="+104"/> <source>Usage:</source> <translation>用法:</translation> </message> <message> <location line="-30"/> <source>Send command to -server or bitcoind</source> <translation>送指令給 -server 或 bitcoind </translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>列出指令 </translation> </message> <message> <location line="-13"/> <source>Get help for a command</source> <translation>取得指令說明 </translation> </message> <message> <location line="+25"/> <source>Options:</source> <translation>選項: </translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: bitcoin.conf)</source> <translation>指定設定檔 (預設: bitcoin.conf) </translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: bitcoind.pid)</source> <translation>指定行程識別碼檔案 (預設: bitcoind.pid) </translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>指定資料目錄 </translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>設定資料庫快取大小為多少百萬位元組(MB, 預設: 25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 8333 or testnet: 18333)</source> <translation>在通訊埠 &lt;port&gt; 聽候連線 (預設: 8333, 或若為測試網路: 18333)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>維持與節點連線數的上限為 &lt;n&gt; 個 (預設: 125)</translation> </message> <message> <location line="-49"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>連線到某個節點以取得其它節點的位址, 然後斷線</translation> </message> <message> <location line="+84"/> <source>Specify your own public address</source> <translation>指定自己公開的位址</translation> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>與亂搞的節點斷線的臨界值 (預設: 100)</translation> </message> <message> <location line="-136"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>避免與亂搞的節點連線的秒數 (預設: 86400)</translation> </message> <message> <location line="-33"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>在 IPv4 網路上以通訊埠 %u 聽取 RPC 連線時發生錯誤: %s</translation> </message> <message> <location line="+31"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 8332 or testnet: 18332)</source> <translation>在通訊埠 &lt;port&gt; 聽候 JSON-RPC 連線 (預設: 8332, 或若為測試網路: 18332)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>接受命令列與 JSON-RPC 指令 </translation> </message> <message> <location line="+77"/> <source>Run in the background as a daemon and accept commands</source> <translation>以背景程式執行並接受指令</translation> </message> <message> <location line="+38"/> <source>Use the test network</source> <translation>使用測試網路 </translation> </message> <message> <location line="-114"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>是否接受外來連線 (預設: 當沒有 -proxy 或 -connect 時預設為 1)</translation> </message> <message> <location line="-84"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=bitcoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;Bitcoin Alert&quot; admin@foo.com </source> <translation>%s, 你必須要在以下設定檔中設定 RPC 密碼(rpcpassword): %s 建議你使用以下隨機產生的密碼: rpcuser=bitcoinrpc rpcpassword=%s (你不用記住這個密碼) 使用者名稱(rpcuser)和密碼(rpcpassword)不可以相同! 如果設定檔還不存在, 請在新增時, 設定檔案權限為&quot;只有主人才能讀取&quot;. 也建議你設定警示通知, 發生問題時你才會被通知到; 比如說設定為: alertnotify=echo %%s | mail -s &quot;Bitcoin Alert&quot; admin@foo.com </translation> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>設定在 IPv6 網路的通訊埠 %u 上聽候 RPC 連線失敗, 退而改用 IPv4 網路: %s</translation> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation>和指定的位址繫結, 並總是在該位址聽候連線. IPv6 請用 &quot;[主機]:通訊埠&quot; 這種格式</translation> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. Bitcoin is probably already running.</source> <translation>無法鎖定資料目錄 %s. 也許位元幣已經在執行了.</translation> </message> <message> <location line="+3"/> <source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly. This is intended for regression testing tools and app development.</source> <translation>進入回歸測試模式, 特別的區塊鎖鏈使用中, 可以立即解出區塊. 目的是用來做回歸測試, 以及配合應用程式的開發.</translation> </message> <message> <location line="+4"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>錯誤: 交易被拒絕了! 有時候會發生這種錯誤, 是因為你錢包中的一些錢已經被花掉了. 比如說你複製了錢包檔 wallet.dat, 然後用複製的錢包花掉了錢, 你現在所用的原來的錢包中卻沒有該筆交易紀錄.</translation> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation>錯誤: 這筆交易需要至少 %s 的手續費! 因為它的金額太大, 或複雜度太高, 或是使用了最近才剛收到的款項.</translation> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation>當收到相關警示時所要執行的指令 (指令中的 %s 會被取代為警示訊息)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>當錢包有交易改變時所要執行的指令 (指令中的 %s 會被取代為交易識別碼)</translation> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation>設定高優先權或低手續費的交易資料大小上限為多少位元組 (預設: 27000)</translation> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation>這是尚未發表的測試版本 - 使用請自負風險 - 請不要用於開採或商業應用</translation> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>警告: -paytxfee 設定了很高的金額! 這可是你交易付款所要付的手續費.</translation> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation>警告: 顯示的交易可能不正確! 你可能需要升級, 或者需要等其它的節點升級.</translation> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Bitcoin will not work properly.</source> <translation>警告: 請檢查電腦時間與日期是否正確! 位元幣無法在時鐘不準的情況下正常運作.</translation> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>警告: 讀取錢包檔 wallet.dat 失敗了! 所有的密鑰都正確讀取了, 但是交易資料或位址簿資料可能會缺少或不正確.</translation> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>警告: 錢包檔 wallet.dat 壞掉, 但資料被拯救回來了! 原來的 wallet.dat 會改儲存在 %s, 檔名為 wallet.{timestamp}.bak. 如果餘額或交易資料有誤, 你應該要用備份資料復原回來.</translation> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>嘗試從壞掉的錢包檔 wallet.dat 復原密鑰</translation> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation>區塊產生選項:</translation> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>只連線至指定節點(可多個)</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation>發現區塊資料庫壞掉了</translation> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>找出自己的網際網路位址 (預設: 當有聽候連線且沒有 -externalip 時為 1)</translation> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation>你要現在重建區塊資料庫嗎?</translation> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation>初始化區塊資料庫失敗</translation> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation>錢包資料庫環境 %s 初始化錯誤!</translation> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation>載入區塊資料庫失敗</translation> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation>打開區塊資料庫檔案失敗</translation> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation>錯誤: 磁碟空間很少!</translation> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation>錯誤: 錢包被上鎖了, 無法產生新的交易!</translation> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation>錯誤: 系統錯誤:</translation> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>在任意的通訊埠聽候失敗. 如果你想的話可以用 -listen=0.</translation> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation>讀取區塊資訊失敗</translation> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation>讀取區塊失敗</translation> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation>同步區塊索引失敗</translation> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation>寫入區塊索引失敗</translation> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation>寫入區塊資訊失敗</translation> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation>寫入區塊失敗</translation> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation>寫入檔案資訊失敗</translation> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation>寫入位元幣資料庫失敗</translation> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation>寫入交易索引失敗</translation> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation>寫入回復資料失敗</translation> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation>是否允許在找節點時使用域名查詢 (預設: 當沒用 -connect 時為 1)</translation> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation>生產位元幣 (預設值: 0)</translation> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation>啓動時檢查的區塊數 (預設: 288, 指定 0 表示全部)</translation> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation>區塊檢查的仔細程度 (0 至 4, 預設: 3)</translation> </message> <message> <location line="+2"/> <source>Incorrect or no genesis block found. Wrong datadir for network?</source> <translation>創世區塊不正確或找不到. 資料目錄錯了嗎?</translation> </message> <message> <location line="+18"/> <source>Not enough file descriptors available.</source> <translation>檔案描述器不足.</translation> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation>從目前的區塊檔 blk000??.dat 重建鎖鏈索引</translation> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation>設定處理 RPC 服務請求的執行緒數目 (預設為 4)</translation> </message> <message> <location line="+7"/> <source>Specify wallet file (within data directory)</source> <translation>指定錢包檔(會在資料目錄中)</translation> </message> <message> <location line="+20"/> <source>Verifying blocks...</source> <translation>驗證區塊資料中...</translation> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation>驗證錢包資料中...</translation> </message> <message> <location line="+1"/> <source>Wallet %s resides outside data directory %s</source> <translation>錢包檔 %s 沒有在資料目錄 %s 裡面</translation> </message> <message> <location line="+4"/> <source>You need to rebuild the database using -reindex to change -txindex</source> <translation>改變 -txindex 參數後, 必須要用 -reindex 參數來重建資料庫</translation> </message> <message> <location line="-76"/> <source>Imports blocks from external blk000??.dat file</source> <translation>從其它來源的 blk000??.dat 檔匯入區塊</translation> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation>設定指令碼驗證的執行緒數目 (最多為 16, 若為 0 表示程式自動決定, 小於 0 表示保留不用的處理器核心數目, 預設為 0)</translation> </message> <message> <location line="+78"/> <source>Information</source> <translation>資訊</translation> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>無效的 -tor 位址: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>設定 -minrelaytxfee=&lt;金額&gt; 的金額無效: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>設定 -mintxfee=&lt;amount&gt; 的金額無效: &apos;%s&apos;</translation> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation>維護全部交易的索引 (預設為 0)</translation> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>每個連線的接收緩衝區大小上限為 &lt;n&gt;*1000 個位元組 (預設: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>每個連線的傳送緩衝區大小上限為 &lt;n&gt;*1000 位元組 (預設: 1000)</translation> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation>只接受與內建的檢查段點吻合的區塊鎖鏈 (預設: 1)</translation> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>只和 &lt;net&gt; 網路上的節點連線 (IPv4, IPv6, 或 Tor)</translation> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>輸出額外的除錯資訊. 包含了其它所有的 -debug* 選項</translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation>輸出額外的網路除錯資訊</translation> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>在除錯輸出內容前附加時間</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation>SSL 選項: (SSL 設定程序請見 Bitcoin Wiki)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>選擇 SOCKS 代理伺服器的協定版本(4 或 5, 預設: 5)</translation> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>在終端機顯示追蹤或除錯資訊, 而非寫到 debug.log 檔</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>輸出追蹤或除錯資訊給除錯器</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>設定區塊大小上限為多少位元組 (預設: 250000)</translation> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>設定區塊大小下限為多少位元組 (預設: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>客戶端軟體啓動時將 debug.log 檔縮小 (預設: 當沒有 -debug 時為 1)</translation> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation>簽署交易失敗</translation> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>指定連線在幾毫秒後逾時 (預設: 5000)</translation> </message> <message> <location line="+5"/> <source>System error: </source> <translation>系統錯誤:</translation> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation>交易金額太小</translation> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation>交易金額必須是正的</translation> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation>交易位元量太大</translation> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>是否使用通用即插即用(UPnP)協定來設定聽候連線的通訊埠 (預設: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>是否使用通用即插即用(UPnP)協定來設定聽候連線的通訊埠 (預設: 當有聽候連線為 1)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation>透過代理伺服器來使用 Tor 隱藏服務 (預設: 同 -proxy)</translation> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>JSON-RPC 連線使用者名稱</translation> </message> <message> <location line="+5"/> <source>Warning</source> <translation>警告</translation> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>警告: 這個版本已經被淘汰掉了, 必須要升級!</translation> </message> <message> <location line="+2"/> <source>wallet.dat corrupt, salvage failed</source> <translation>錢包檔 weallet.dat 壞掉了, 拯救失敗</translation> </message> <message> <location line="-52"/> <source>Password for JSON-RPC connections</source> <translation>JSON-RPC 連線密碼</translation> </message> <message> <location line="-68"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>只允許從指定網路位址來的 JSON-RPC 連線</translation> </message> <message> <location line="+77"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>送指令給在 &lt;ip&gt; 的節點 (預設: 127.0.0.1) </translation> </message> <message> <location line="-121"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>當最新區塊改變時所要執行的指令 (指令中的 %s 會被取代為區塊的雜湊值)</translation> </message> <message> <location line="+149"/> <source>Upgrade wallet to latest format</source> <translation>將錢包升級成最新的格式</translation> </message> <message> <location line="-22"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>設定密鑰池大小為 &lt;n&gt; (預設: 100) </translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>重新掃描區塊鎖鏈, 以尋找錢包所遺漏的交易.</translation> </message> <message> <location line="+36"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>於 JSON-RPC 連線使用 OpenSSL (https) </translation> </message> <message> <location line="-27"/> <source>Server certificate file (default: server.cert)</source> <translation>伺服器憑證檔 (預設: server.cert) </translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>伺服器密鑰檔 (預設: server.pem) </translation> </message> <message> <location line="-156"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>可以接受的加密法 (預設: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH) </translation> </message> <message> <location line="+171"/> <source>This help message</source> <translation>此協助訊息 </translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>無法和這台電腦上的 %s 繫結 (繫結回傳錯誤 %d, %s)</translation> </message> <message> <location line="-93"/> <source>Connect through socks proxy</source> <translation>透過 SOCKS 代理伺服器連線</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>允許對 -addnode, -seednode, -connect 的參數使用域名查詢 </translation> </message> <message> <location line="+56"/> <source>Loading addresses...</source> <translation>載入位址中...</translation> </message> <message> <location line="-36"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>載入檔案 wallet.dat 失敗: 錢包壞掉了</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of Bitcoin</source> <translation>載入檔案 wallet.dat 失敗: 此錢包需要新版的 Bitcoin</translation> </message> <message> <location line="+96"/> <source>Wallet needed to be rewritten: restart Bitcoin to complete</source> <translation>錢包需要重寫: 請重啟位元幣來完成</translation> </message> <message> <location line="-98"/> <source>Error loading wallet.dat</source> <translation>載入檔案 wallet.dat 失敗</translation> </message> <message> <location line="+29"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>無效的 -proxy 位址: &apos;%s&apos;</translation> </message> <message> <location line="+57"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>在 -onlynet 指定了不明的網路別: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>在 -socks 指定了不明的代理協定版本: %i</translation> </message> <message> <location line="-98"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>無法解析 -bind 位址: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>無法解析 -externalip 位址: &apos;%s&apos;</translation> </message> <message> <location line="+45"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>設定 -paytxfee=&lt;金額&gt; 的金額無效: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>無效的金額</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>累積金額不足</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>載入區塊索引中...</translation> </message> <message> <location line="-58"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>加入一個要連線的節線, 並試著保持對它的連線暢通</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. Bitcoin is probably already running.</source> <translation>無法和這台電腦上的 %s 繫結. 也許位元幣已經在執行了.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>交易付款時每 KB 的交易手續費</translation> </message> <message> <location line="+20"/> <source>Loading wallet...</source> <translation>載入錢包中...</translation> </message> <message> <location line="-53"/> <source>Cannot downgrade wallet</source> <translation>無法將錢包格式降級</translation> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>無法寫入預設位址</translation> </message> <message> <location line="+65"/> <source>Rescanning...</source> <translation>重新掃描中...</translation> </message> <message> <location line="-58"/> <source>Done loading</source> <translation>載入完成</translation> </message> <message> <location line="+84"/> <source>To use the %s option</source> <translation>為了要使用 %s 選項</translation> </message> <message> <location line="-76"/> <source>Error</source> <translation>錯誤</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>你必須在下列設定檔中設定 RPC 密碼(rpcpassword=&lt;password&gt;): %s 如果這個檔案還不存在, 請在新增時, 設定檔案權限為&quot;只有主人才能讀取&quot;.</translation> </message> </context> </TS>
safecoin/safecoin
src/qt/locale/bitcoin_zh_TW.ts
TypeScript
mit
119,012
<?php /** * This file is part of the Propel package. * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @license MIT License */ /** * dblib doesn't support transactions so we need to add a workaround for transactions, last insert ID, and quoting * * @package propel.runtime.adapter.MSSQL */ class MssqlPropelPDO extends PropelPDO { /** * Begin a transaction. * * It is necessary to override the abstract PDO transaction functions here, as * the PDO driver for MSSQL does not support transactions. * * @return integer */ public function beginTransaction() { $return = true; $opcount = $this->getNestedTransactionCount(); if ( $opcount === 0 ) { $return = self::exec('BEGIN TRANSACTION'); if ($this->useDebug) { $this->log('Begin transaction', null, __METHOD__); } $this->isUncommitable = false; } $this->nestedTransactionCount++; return $return; } /** * Commit a transaction. * * It is necessary to override the abstract PDO transaction functions here, as * the PDO driver for MSSQL does not support transactions. * * @return integer * * @throws PropelException */ public function commit() { $return = true; $opcount = $this->getNestedTransactionCount(); if ($opcount > 0) { if ($opcount === 1) { if ($this->isUncommitable) { throw new PropelException('Cannot commit because a nested transaction was rolled back'); } else { $return = self::exec('COMMIT TRANSACTION'); if ($this->useDebug) { $this->log('Commit transaction', null, __METHOD__); } } } $this->nestedTransactionCount--; } return $return; } /** * Roll-back a transaction. * * It is necessary to override the abstract PDO transaction functions here, as * the PDO driver for MSSQL does not support transactions. * * @return integer */ public function rollBack() { $return = true; $opcount = $this->getNestedTransactionCount(); if ($opcount > 0) { if ($opcount === 1) { $return = self::exec('ROLLBACK TRANSACTION'); if ($this->useDebug) { $this->log('Rollback transaction', null, __METHOD__); } } else { $this->isUncommitable = true; } $this->nestedTransactionCount--; } return $return; } /** * Rollback the whole transaction, even if this is a nested rollback * and reset the nested transaction count to 0. * * It is necessary to override the abstract PDO transaction functions here, as * the PDO driver for MSSQL does not support transactions. * * @return integer */ public function forceRollBack() { $return = true; $opcount = $this->getNestedTransactionCount(); if ($opcount > 0) { // If we're in a transaction, always roll it back // regardless of nesting level. $return = self::exec('ROLLBACK TRANSACTION'); // reset nested transaction count to 0 so that we don't // try to commit (or rollback) the transaction outside this scope. $this->nestedTransactionCount = 0; if ($this->useDebug) { $this->log('Rollback transaction', null, __METHOD__); } } return $return; } /** * @param string $seqname * @return integer */ public function lastInsertId($seqname = null) { $result = self::query('SELECT SCOPE_IDENTITY()'); return (int) $result->fetchColumn(); } /** * @param string $text * @return string */ public function quoteIdentifier($text) { return '[' . $text . ']'; } /** * @return boolean */ public function useQuoteIdentifier() { return true; } }
Lola85/chattest
vendor/propel/runtime/lib/adapter/MSSQL/MssqlPropelPDO.php
PHP
mit
4,327
import { PipeTransform } from '@angular/core'; import { ValueGetter } from '../utils/column-prop-getters'; /** * Column property that indicates how to retrieve this column's * value from a row. * 'a.deep.value', 'normalprop', 0 (numeric) */ export declare type TableColumnProp = string | number; /** * Column Type * @type {object} */ export interface TableColumn { /** * Internal unique id * * @type {string} * @memberOf TableColumn */ $$id?: string; /** * Internal for column width distributions * * @type {number} * @memberOf TableColumn */ $$oldWidth?: number; /** * Internal for setColumnDefaults * * @type {ValueGetter} * @memberOf TableColumn */ $$valueGetter?: ValueGetter; /** * Determines if column is checkbox * * @type {boolean} * @memberOf TableColumn */ checkboxable?: boolean; /** * Determines if the column is frozen to the left * * @type {boolean} * @memberOf TableColumn */ frozenLeft?: boolean; /** * Determines if the column is frozen to the right * * @type {boolean} * @memberOf TableColumn */ frozenRight?: boolean; /** * The grow factor relative to other columns. Same as the flex-grow * API from http =//www.w3.org/TR/css3-flexbox/. Basically; * take any available extra width and distribute it proportionally * according to all columns' flexGrow values. * * @type {number} * @memberOf TableColumn */ flexGrow?: number; /** * Min width of the column * * @type {number} * @memberOf TableColumn */ minWidth?: number; /** * Max width of the column * * @type {number} * @memberOf TableColumn */ maxWidth?: number; /** * The default width of the column, in pixels * * @type {number} * @memberOf TableColumn */ width?: number; /** * Can the column be resized * * @type {boolean} * @memberOf TableColumn */ resizeable?: boolean; /** * Custom sort comparator * * @type {*} * @memberOf TableColumn */ comparator?: any; /** * Custom pipe transforms * * @type {PipeTransform} * @memberOf TableColumn */ pipe?: PipeTransform; /** * Can the column be sorted * * @type {boolean} * @memberOf TableColumn */ sortable?: boolean; /** * Can the column be re-arranged by dragging * * @type {boolean} * @memberOf TableColumn */ draggable?: boolean; /** * Whether the column can automatically resize to fill space in the table. * * @type {boolean} * @memberOf TableColumn */ canAutoResize?: boolean; /** * Column name or label * * @type {string} * @memberOf TableColumn */ name?: string; /** * Property to bind to the row. Example: * * `someField` or `some.field.nested`, 0 (numeric) * * If left blank, will use the name as camel case conversion * * @type {TableColumnProp} * @memberOf TableColumn */ prop?: TableColumnProp; /** * Cell template ref * * @type {*} * @memberOf TableColumn */ cellTemplate?: any; /** * Header template ref * * @type {*} * @memberOf TableColumn */ headerTemplate?: any; /** * CSS Classes for the cell * * * @memberOf TableColumn */ cellClass?: string | ((data: any) => string | any); /** * CSS classes for the header * * * @memberOf TableColumn */ headerClass?: string | ((data: any) => string | any); /** * Header checkbox enabled * * @type {boolean} * @memberOf TableColumn */ headerCheckboxable?: boolean; }
stupiduglyfool/ngx-datatable
release/types/table-column.type.d.ts
TypeScript
mit
3,942
<?php namespace Bolt\Storage\ContentRequest; use Bolt\Config; use Bolt\Exception\AccessControlException; use Bolt\Helpers\Input; use Bolt\Logger\FlashLoggerInterface; use Bolt\Storage\Entity; use Bolt\Storage\EntityManager; use Bolt\Translation\Translator as Trans; use Bolt\Users; use Carbon\Carbon; use Psr\Log\LoggerInterface; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; /** * Helper class for ContentType record editor saves. * * Prior to v3.0 this functionality existed in \Bolt\Controllers\Backend::editcontent(). * * @author Gawain Lynch <gawain.lynch@gmail.com> */ class Save { /** @var EntityManager */ protected $em; /** @var Config */ protected $config; /** @var Users */ protected $users; /** @var LoggerInterface */ protected $loggerChange; /** @var LoggerInterface */ protected $loggerSystem; /** @var FlashLoggerInterface */ protected $loggerFlash; /** @var UrlGeneratorInterface */ protected $urlGenerator; /** * Constructor function. * * @param EntityManager $em * @param Config $config * @param Users $users * @param LoggerInterface $loggerChange * @param LoggerInterface $loggerSystem * @param FlashLoggerInterface $loggerFlash * @param UrlGeneratorInterface $urlGenerator */ public function __construct( EntityManager $em, Config $config, Users $users, LoggerInterface $loggerChange, LoggerInterface $loggerSystem, FlashLoggerInterface $loggerFlash, UrlGeneratorInterface $urlGenerator ) { $this->em = $em; $this->config = $config; $this->users = $users; $this->loggerChange = $loggerChange; $this->loggerSystem = $loggerSystem; $this->loggerFlash = $loggerFlash; $this->urlGenerator = $urlGenerator; } /** * Do the save for a POSTed record. * * @param array $formValues * @param array $contenttype The contenttype data * @param integer $id The record ID * @param boolean $new If TRUE this is a new record * @param string $returnTo * @param string $editReferrer * * @throws AccessControlException * * @return Response */ public function action(array $formValues, array $contenttype, $id, $new, $returnTo, $editReferrer) { $contentTypeSlug = $contenttype['slug']; $repo = $this->em->getRepository($contentTypeSlug); // If we have an ID now, this is an existing record if ($id) { $content = $repo->find($id); $oldContent = clone $content; $oldStatus = $content['status']; } else { $content = $repo->create(['contenttype' => $contentTypeSlug, 'status' => $contenttype['default_status']]); $oldContent = null; $oldStatus = 'draft'; } // Don't allow spoofing the ID. if ($content->getId() !== null && (integer) $id !== $content->getId()) { if ($returnTo === 'ajax') { throw new AccessControlException("Don't try to spoof the id!"); } $this->loggerFlash->error("Don't try to spoof the id!"); return new RedirectResponse($this->generateUrl('dashboard')); } $this->setPostedValues($content, $formValues, $contenttype); $this->setTransitionStatus($content, $contentTypeSlug, $id, $oldStatus); // Get the associated record change comment $comment = isset($formValues['changelog-comment']) ? $formValues['changelog-comment'] : ''; // Save the record return $this->saveContentRecord($content, $oldContent, $contenttype, $new, $comment, $returnTo, $editReferrer); } /** * Check whether the status is allowed. * * We act as if a status *transition* were requested and fallback to the old * status otherwise. * * @param Entity\Entity $content * @param string $contentTypeSlug * @param integer $id * @param string $oldStatus */ private function setTransitionStatus(Entity\Entity $content, $contentTypeSlug, $id, $oldStatus) { $canTransition = $this->users->isContentStatusTransitionAllowed($oldStatus, $content->getStatus(), $contentTypeSlug, $id); if (!$canTransition) { $content->setStatus($oldStatus); } } /** * Set a Contenttype record values from a HTTP POST. * * @param Entity\Content $content * @param array $formValues * @param array $contentType * * @throws AccessControlException */ private function setPostedValues(Entity\Content $content, $formValues, $contentType) { // Ensure all fields have valid values $formValues = $this->setSuccessfulControlValues($formValues, $contentType['fields']); $formValues = Input::cleanPostedData($formValues); unset($formValues['contenttype']); $user = $this->users->getCurrentUser(); if ($id = $content->getId()) { // Owner is set explicitly, is current user is allowed to do this? if (isset($formValues['ownerid']) && (integer) $formValues['ownerid'] !== $content->getOwnerid()) { if (!$this->users->isAllowed("contenttype:{$contentType['slug']}:change-ownership:$id")) { throw new AccessControlException('Changing ownership is not allowed.'); } $content->setOwnerid($formValues['ownerid']); } } else { $content->setOwnerid($user['id']); } // Make sure we have a proper status. if (!in_array($formValues['status'], ['published', 'timed', 'held', 'draft'])) { if ($status = $content->getStatus()) { $formValues['status'] = $status; } else { $formValues['status'] = 'draft'; } } // Set the object values appropriately foreach ($formValues as $name => $value) { if ($name === 'relation' || $name === 'taxonomy') { continue; } else { $content->set($name, empty($value) ? null : $value); } } $this->setPostedRelations($content, $formValues); $this->setPostedTaxonomies($content, $formValues); } /** * Convert POST relationship values to an array of Entity objects keyed by * ContentType. * * @param Entity\Content $content * @param array|null $formValues */ private function setPostedRelations(Entity\Content $content, $formValues) { $related = $this->em->createCollection('Bolt\Storage\Entity\Relations'); $related->setFromPost($formValues, $content); $content->setRelation($related); } /** * Set valid POST taxonomies. * * @param Entity\Content $content * @param array|null $formValues */ private function setPostedTaxonomies(Entity\Content $content, $formValues) { $taxonomies = $this->em->createCollection('Bolt\Storage\Entity\Taxonomy'); $taxonomies->setFromPost($formValues, $content); $content->setTaxonomy($taxonomies); } /** * Commit the record to the database. * * @param Entity\Content $content * @param Entity\Content|null $oldContent * @param array $contentType * @param boolean $new * @param string $comment * @param string $returnTo * @param string $editReferrer * * @return Response */ private function saveContentRecord(Entity\Content $content, $oldContent, array $contentType, $new, $comment, $returnTo, $editReferrer) { // Save the record $repo = $this->em->getRepository($contentType['slug']); // Update the date modified timestamp $content->setDatechanged('now'); $repo->save($content); $id = $content->getId(); // Create the change log entry if configured $this->logChange($contentType, $content->getId(), $content, $oldContent, $comment); // Log the change if ($new) { $this->loggerFlash->success(Trans::__('contenttypes.generic.saved-new', ['%contenttype%' => $contentType['slug']])); $this->loggerSystem->info('Created: ' . $content->getTitle(), ['event' => 'content']); } else { $this->loggerFlash->success(Trans::__('contenttypes.generic.saved-changes', ['%contenttype%' => $contentType['slug']])); $this->loggerSystem->info('Saved: ' . $content->getTitle(), ['event' => 'content']); } /* * We now only get a returnto parameter if we are saving a new * record and staying on the same page, i.e. "Save {contenttype}" */ if ($returnTo) { if ($returnTo === 'new') { return new RedirectResponse( $this->generateUrl( 'editcontent', [ 'contenttypeslug' => $contentType['slug'], 'id' => $id, '#' => $returnTo, ] ) ); } elseif ($returnTo === 'saveandnew') { return new RedirectResponse( $this->generateUrl( 'editcontent', [ 'contenttypeslug' => $contentType['slug'], '#' => $returnTo, ] ) ); } elseif ($returnTo === 'ajax') { return $this->createJsonUpdate($content, true); } elseif ($returnTo === 'test') { return $this->createJsonUpdate($content, false); } } // No returnto, so we go back to the 'overview' for this contenttype. // check if a pager was set in the referrer - if yes go back there if ($editReferrer) { return new RedirectResponse($editReferrer); } else { return new RedirectResponse($this->generateUrl('overview', ['contenttypeslug' => $contentType['slug']])); } } /** * Add successful control values to request values, and do needed corrections. * * @see http://www.w3.org/TR/html401/interact/forms.html#h-17.13.2 * * @param array $formValues * @param array $fields * * @return array */ private function setSuccessfulControlValues(array $formValues, $fields) { foreach ($fields as $key => $values) { if (isset($formValues[$key])) { if ($values['type'] === 'float') { // We allow ',' and '.' as decimal point and need '.' internally $formValues[$key] = str_replace(',', '.', $formValues[$key]); } } else { if ($values['type'] === 'select' && isset($values['multiple']) && $values['multiple'] === true) { $formValues[$key] = []; } elseif ($values['type'] === 'checkbox') { $formValues[$key] = 0; } } } return $formValues; } /** * Build a valid AJAX response for in-place saves that account for pre/post * save events. * * @param Entity\Content $content * @param boolean $flush * * @return JsonResponse */ private function createJsonUpdate(Entity\Content $content, $flush) { /* * Flush any buffers from saveConent() dispatcher hooks * and make sure our JSON output is clean. * * Currently occurs due to exceptions being generated in the dispatchers * in \Bolt\Storage::saveContent() * StorageEvents::PRE_SAVE * StorageEvents::POST_SAVE */ if ($flush) { Response::closeOutputBuffers(0, false); } $val = $content->toArray(); if ($val['datechanged'] instanceof Carbon) { $val['datechanged'] = $val['datechanged']->toIso8601String(); } elseif (isset($val['datechanged'])) { $val['datechanged'] = (new Carbon($val['datechanged']))->toIso8601String(); } // Adjust decimal point as some locales use a comma and… JavaScript $lc = localeconv(); $fields = $this->config->get('contenttypes/' . $content->getContenttype() . '/fields'); foreach ($fields as $key => $values) { if ($values['type'] === 'float' && $lc['decimal_point'] === ',') { $val[$key] = str_replace('.', ',', $val[$key]); } } // Unset flashbag for ajax $this->loggerFlash->clear(); return new JsonResponse($val); } /** * Add a change log entry to track the change. * * @param string $contentType * @param integer $contentId * @param Entity\Content $newContent * @param Entity\Content|null $oldContent * @param string|null $comment */ private function logChange($contentType, $contentId, $newContent = null, $oldContent = null, $comment = null) { $type = $oldContent ? 'Update' : 'Insert'; $this->loggerChange->info( $type . ' record', [ 'action' => strtoupper($type), 'contenttype' => $contentType, 'id' => $contentId, 'new' => $newContent ? $newContent->toArray() : null, 'old' => $oldContent ? $oldContent->toArray() : null, 'comment' => $comment, ] ); } /** * Shortcut for {@see UrlGeneratorInterface::generate} * * @param string $name The name of the route * @param array $params An array of parameters * @param bool $referenceType The type of reference to be generated (one of the constants) * * @return string */ private function generateUrl($name, $params = [], $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH) { /** @var UrlGeneratorInterface $generator */ $generator = $this->urlGenerator; return $generator->generate($name, $params, $referenceType); } }
Raistlfiren/bolt
src/Storage/ContentRequest/Save.php
PHP
mit
14,861
<?php namespace Modules\Core\Console\Installers\Writers; use Dotenv; use Illuminate\Filesystem\Filesystem; class EnvFileWriter { /** * @var Filesystem */ private $finder; /** * @var array */ protected $search = [ "DB_HOST=localhost", "DB_DATABASE=homestead", "DB_USERNAME=homestead", "DB_PASSWORD=secret", ]; /** * @var string */ protected $template = '.env.example'; /** * @var string */ protected $file = '.env'; /** * @param Filesystem $finder */ public function __construct(Filesystem $finder) { $this->finder = $finder; } /** * @param $name * @param $username * @param $password * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException */ public function write($name, $username, $password, $host) { Dotenv::makeMutable(); $environmentFile = $this->finder->get($this->template); $replace = [ "DB_HOST=$host", "DB_DATABASE=$name", "DB_USERNAME=$username", "DB_PASSWORD=$password", ]; $newEnvironmentFile = str_replace($this->search, $replace, $environmentFile); $this->finder->put($this->file, $newEnvironmentFile); Dotenv::makeImmutable(); } }
mikemand/Core
Console/Installers/Writers/EnvFileWriter.php
PHP
mit
1,355
// Copyright 2015 The Gogs Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package user import ( api "code.gitea.io/sdk/gitea" "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" ) func responseAPIUsers(ctx *context.APIContext, users []*models.User) { apiUsers := make([]*api.User, len(users)) for i := range users { apiUsers[i] = users[i].APIFormat() } ctx.JSON(200, &apiUsers) } func listUserFollowers(ctx *context.APIContext, u *models.User) { users, err := u.GetFollowers(ctx.QueryInt("page")) if err != nil { ctx.Error(500, "GetUserFollowers", err) return } responseAPIUsers(ctx, users) } // ListMyFollowers list all my followers func ListMyFollowers(ctx *context.APIContext) { // swagger:route GET /user/followers userCurrentListFollowers // // Produces: // - application/json // // Responses: // 200: UserList // 500: error listUserFollowers(ctx, ctx.User) } // ListFollowers list user's followers func ListFollowers(ctx *context.APIContext) { // swagger:route GET /users/:username/followers userListFollowers // // Produces: // - application/json // // Responses: // 200: UserList // 500: error u := GetUserByParams(ctx) if ctx.Written() { return } listUserFollowers(ctx, u) } func listUserFollowing(ctx *context.APIContext, u *models.User) { users, err := u.GetFollowing(ctx.QueryInt("page")) if err != nil { ctx.Error(500, "GetFollowing", err) return } responseAPIUsers(ctx, users) } // ListMyFollowing list all my followings func ListMyFollowing(ctx *context.APIContext) { // swagger:route GET /user/following userCurrentListFollowing // // Produces: // - application/json // // Responses: // 200: UserList // 500: error listUserFollowing(ctx, ctx.User) } // ListFollowing list user's followings func ListFollowing(ctx *context.APIContext) { // swagger:route GET /users/{username}/following userListFollowing // // Produces: // - application/json // // Responses: // 200: UserList // 500: error u := GetUserByParams(ctx) if ctx.Written() { return } listUserFollowing(ctx, u) } func checkUserFollowing(ctx *context.APIContext, u *models.User, followID int64) { if u.IsFollowing(followID) { ctx.Status(204) } else { ctx.Status(404) } } // CheckMyFollowing check if the repo is followed by me func CheckMyFollowing(ctx *context.APIContext) { // swagger:route GET /user/following/{username} userCurrentCheckFollowing // // Responses: // 204: empty // 404: notFound target := GetUserByParams(ctx) if ctx.Written() { return } checkUserFollowing(ctx, ctx.User, target.ID) } // CheckFollowing check if the repo is followed by user func CheckFollowing(ctx *context.APIContext) { // swagger:route GET /users/{username}/following/:target userCheckFollowing // // Responses: // 204: empty // 404: notFound u := GetUserByParams(ctx) if ctx.Written() { return } target := GetUserByParamsName(ctx, ":target") if ctx.Written() { return } checkUserFollowing(ctx, u, target.ID) } // Follow follow one repository func Follow(ctx *context.APIContext) { // swagger:route PUT /user/following/{username} userCurrentPutFollow // // Responses: // 204: empty // 500: error target := GetUserByParams(ctx) if ctx.Written() { return } if err := models.FollowUser(ctx.User.ID, target.ID); err != nil { ctx.Error(500, "FollowUser", err) return } ctx.Status(204) } // Unfollow unfollow one repository func Unfollow(ctx *context.APIContext) { // swagger:route DELETE /user/following/{username} userCurrentDeleteFollow // // Responses: // 204: empty // 500: error target := GetUserByParams(ctx) if ctx.Written() { return } if err := models.UnfollowUser(ctx.User.ID, target.ID); err != nil { ctx.Error(500, "UnfollowUser", err) return } ctx.Status(204) }
cybe/gitea
routers/api/v1/user/follower.go
GO
mit
4,054
# frozen_string_literal: true module Ci module BuildsHelper def build_summary(build, skip: false) if build.has_trace? if skip link_to _('View job log'), pipeline_job_url(build.pipeline, build) else build.trace.html(last_lines: 10).html_safe end else _('No job log') end end def sidebar_build_class(build, current_build) build_class = [] build_class << 'active' if build.id === current_build.id build_class << 'retried' if build.retried? build_class.join(' ') end def javascript_build_options { page_path: project_job_path(@project, @build), build_status: @build.status, build_stage: @build.stage, log_state: '' } end def build_failed_issue_options { title: _("Job Failed #%{build_id}") % { build_id: @build.id }, description: project_job_url(@project, @build) } end end end
mmkassem/gitlabhq
app/helpers/ci/builds_helper.rb
Ruby
mit
980
module.exports = { visionKey: 'AIzaSyAA14j-7sIJLDTRZd3bYpZrmCEoFA9IN40', pairingID: 'b5378ca6', pairingKey: '690be2968f8f08b26fcc1f2c9c8f5b90', recipesKey: 'qAjqbB5sPamshJwWJJh01Y3exb3Jp1wBzcOjsnrqegcRf1PCXT', backUpRecipesKey: 'jHbWfZqPEUmsh0NElMAPdMXlfPm1p1M9n5NjsnPD1l0Vjhsjng' }
fjjk-snacktime/snacktime
server/utils/apiKeys.js
JavaScript
mit
293
def uniquer(seq, idfun=None): if idfun is None: def idfun(x): return x seen = {} result = [] for item in seq: marker = idfun(item) if marker in seen: continue seen[marker] = 1 result.append(item) return result
audreyr/opencomparison
package/utils.py
Python
mit
269
onOpenDialog = function(dialog) { $('.ui-dialog').corner('6px').find('.ui-dialog-titlebar').corner('1px top'); $(document.body).addClass('hide-overflow'); } onCloseDialog = function(dialog) { $(document.body).removeClass('hide-overflow'); } var wymeditor_inputs = []; var wymeditors_loaded = 0; // supply custom_wymeditor_boot_options if you want to override anything here. if (typeof(custom_wymeditor_boot_options) == "undefined") { custom_wymeditor_boot_options = {}; } var form_actions = "<div id='dialog-form-actions' class='form-actions'>" + "<div class='form-actions-left'>" + "<input id='submit_button' class='wym_submit button' type='submit' value='{Insert}' class='button' />" + "<a href='' class='wym_cancel close_dialog button'>{Cancel}</a>" + "</div>" + "</div>"; var wymeditor_boot_options = $.extend({ skin: 'refinery' , basePath: "/" , wymPath: "/javascripts/wymeditor/jquery.refinery.wymeditor.js" , cssSkinPath: "/stylesheets/wymeditor/skins/" , jsSkinPath: "/javascripts/wymeditor/skins/" , langPath: "/javascripts/wymeditor/lang/" , iframeBasePath: '/' , classesItems: [ {name: 'text-align', rules:['left', 'center', 'right', 'justify'], join: '-'} , {name: 'image-align', rules:['left', 'right'], join: '-'} , {name: 'font-size', rules:['small', 'normal', 'large'], join: '-'} ] , containersItems: [ {'name': 'h1', 'title':'Heading_1', 'css':'wym_containers_h1'} , {'name': 'h2', 'title':'Heading_2', 'css':'wym_containers_h2'} , {'name': 'h3', 'title':'Heading_3', 'css':'wym_containers_h3'} , {'name': 'p', 'title':'Paragraph', 'css':'wym_containers_p'} ] , toolsItems: [ {'name': 'Bold', 'title': 'Bold', 'css': 'wym_tools_strong'} ,{'name': 'Italic', 'title': 'Emphasis', 'css': 'wym_tools_emphasis'} ,{'name': 'InsertOrderedList', 'title': 'Ordered_List', 'css': 'wym_tools_ordered_list'} ,{'name': 'InsertUnorderedList', 'title': 'Unordered_List', 'css': 'wym_tools_unordered_list'} /*,{'name': 'Indent', 'title': 'Indent', 'css': 'wym_tools_indent'} ,{'name': 'Outdent', 'title': 'Outdent', 'css': 'wym_tools_outdent'} ,{'name': 'Undo', 'title': 'Undo', 'css': 'wym_tools_undo'} ,{'name': 'Redo', 'title': 'Redo', 'css': 'wym_tools_redo'}*/ ,{'name': 'CreateLink', 'title': 'Link', 'css': 'wym_tools_link'} ,{'name': 'Unlink', 'title': 'Unlink', 'css': 'wym_tools_unlink'} ,{'name': 'InsertImage', 'title': 'Image', 'css': 'wym_tools_image'} ,{'name': 'InsertTable', 'title': 'Table', 'css': 'wym_tools_table'} //,{'name': 'Paste', 'title': 'Paste_From_Word', 'css': 'wym_tools_paste'} ,{'name': 'ToggleHtml', 'title': 'HTML', 'css': 'wym_tools_html'} ] ,toolsHtml: "<ul class='wym_tools wym_section wym_buttons'>" + WYMeditor.TOOLS_ITEMS + WYMeditor.CLASSES + "</ul>" ,toolsItemHtml: "<li class='" + WYMeditor.TOOL_CLASS + "'>" + "<a href='#' name='" + WYMeditor.TOOL_NAME + "' title='" + WYMeditor.TOOL_TITLE + "'>" + WYMeditor.TOOL_TITLE + "</a>" + "</li>" , classesHtml: "<li class='wym_tools_class'>" + "<a href='#' name='" + WYMeditor.APPLY_CLASS + "' title='"+ titleize(WYMeditor.APPLY_CLASS) +"'></a>" + "<ul class='wym_classes wym_classes_hidden'>" + WYMeditor.CLASSES_ITEMS + "</ul>" + "</li>" , classesItemHtml: "<li><a href='#' name='"+ WYMeditor.CLASS_NAME + "'>"+ WYMeditor.CLASS_TITLE+ "</a></li>" , classesItemHtmlMultiple: "<li class='wym_tools_class_multiple_rules'>" + "<span>" + WYMeditor.CLASS_TITLE + "</span>" + "<ul>{classesItemHtml}</ul>" +"</li>" , containersHtml: "<ul class='wym_containers wym_section'>" + WYMeditor.CONTAINERS_ITEMS + "</ul>" , containersItemHtml: "<li class='" + WYMeditor.CONTAINER_CLASS + "'>" + "<a href='#' name='" + WYMeditor.CONTAINER_NAME + "' title='" + WYMeditor.CONTAINER_TITLE + "'></a>" + "</li>" , boxHtml: "<div class='wym_box'>" + "<div class='wym_area_top clearfix'>" + WYMeditor.CONTAINERS + WYMeditor.TOOLS + "</div>" + "<div class='wym_area_main'>" + WYMeditor.HTML + WYMeditor.IFRAME + WYMeditor.STATUS + "</div>" + "</div>" , iframeHtml: "<div class='wym_iframe wym_section'>" + "<iframe id='WYMeditor_" + WYMeditor.INDEX + "' src='" + WYMeditor.IFRAME_BASE_PATH + "wymiframe' frameborder='0'" + " onload='this.contentWindow.parent.WYMeditor.INSTANCES[" + WYMeditor.INDEX + "].initIframe(this);'></iframe>" +"</div>" , dialogImageHtml: "" , dialogLinkHtml: "" , dialogTableHtml: "<div class='wym_dialog wym_dialog_table'>" + "<form>" + "<input type='hidden' id='wym_dialog_type' class='wym_dialog_type' value='"+ WYMeditor.DIALOG_TABLE + "' />" + "<div class='field'>" + "<label for='wym_caption'>{Caption}</label>" + "<input type='text' id='wym_caption' class='wym_caption' value='' size='40' />" + "</div>" + "<div class='field'>" + "<label for='wym_rows'>{Number_Of_Rows}</label>" + "<input type='text' id='wym_rows' class='wym_rows' value='3' size='3' />" + "</div>" + "<div class='field'>" + "<label for='wym_cols'>{Number_Of_Cols}</label>" + "<input type='text' id='wym_cols' class='wym_cols' value='2' size='3' />" + "</div>" + form_actions + "</form>" + "</div>" , dialogPasteHtml: "<div class='wym_dialog wym_dialog_paste'>" + "<form>" + "<input type='hidden' id='wym_dialog_type' class='wym_dialog_type' value='" + WYMeditor.DIALOG_PASTE + "' />" + "<div class='field'>" + "<textarea class='wym_text' rows='10' cols='50'></textarea>" + "</div>" + form_actions + "</form>" + "</div>" , dialogPath: "/refinery/dialogs/" , dialogFeatures: { width: 866 , height: 455 , modal: true , draggable: true , resizable: false , autoOpen: true , open: onOpenDialog , close: onCloseDialog } , dialogInlineFeatures: { width: 600 , height: 485 , modal: true , draggable: true , resizable: false , autoOpen: true , open: onOpenDialog , close: onCloseDialog } , dialogId: 'editor_dialog' , dialogHtml: "<!DOCTYPE html>" + "<html dir='" + WYMeditor.DIRECTION + "'>" + "<head>" + "<link rel='stylesheet' type='text/css' media='screen' href='" + WYMeditor.CSS_PATH + "' />" + "<title>" + WYMeditor.DIALOG_TITLE + "</title>" + "<script type='text/javascript' src='" + WYMeditor.JQUERY_PATH + "'></script>" + "<script type='text/javascript' src='" + WYMeditor.WYM_PATH + "'></script>" + "</head>" + "<body>" + "<div id='page'>" + WYMeditor.DIALOG_BODY + "</div>" + "</body>" + "</html>" , postInit: function(wym) { // register loaded wymeditors_loaded += 1; // fire loaded if all editors loaded if(WYMeditor.INSTANCES.length == wymeditors_loaded){ $('.wym_loading_overlay').remove(); WYMeditor.loaded(); } $('.field.hide-overflow').removeClass('hide-overflow').css('height', 'auto'); } , lang: (typeof(I18n.locale) != "undefined" ? I18n.locale : 'en') }, custom_wymeditor_boot_options); // custom function added by us to hook into when all wymeditor instances on the page have finally loaded: WYMeditor.loaded = function(){}; $(function() { wymeditor_inputs = $('.wymeditor'); wymeditor_inputs.each(function(input) { if ((containing_field = $(this).parents('.field')).get(0).style.height == '') { containing_field.addClass('hide-overflow').css('height', $(this).outerHeight() - containing_field.offset().top + $(this).offset().top + 45); } $(this).hide(); }); wymeditor_inputs.wymeditor(wymeditor_boot_options); });
mdoyle13/haymarket-ref
public/javascripts/refinery/boot_wym.js
JavaScript
mit
7,963
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import _extends from "@babel/runtime/helpers/esm/extends"; import * as React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import { integerPropType, deepmerge } from '@material-ui/utils'; import { unstable_composeClasses as composeClasses } from '@material-ui/unstyled'; import Paper from '../Paper'; import capitalize from '../utils/capitalize'; import LinearProgress from '../LinearProgress'; import useThemeProps from '../styles/useThemeProps'; import experimentalStyled from '../styles/experimentalStyled'; import mobileStepperClasses, { getMobileStepperUtilityClass } from './mobileStepperClasses'; import { jsxs as _jsxs } from "react/jsx-runtime"; import { jsx as _jsx } from "react/jsx-runtime"; const overridesResolver = (props, styles) => { const { styleProps } = props; return deepmerge(_extends({}, styles[`position${capitalize(styleProps.position)}`], { [`& .${mobileStepperClasses.dots}`]: styles.dots, [`& .${mobileStepperClasses.dot}`]: _extends({}, styles.dot, styleProps.dotActive && styles.dotActive), [`& .${mobileStepperClasses.dotActive}`]: styles.dotActive, [`& .${mobileStepperClasses.progress}`]: styles.progress }), styles.root || {}); }; const useUtilityClasses = styleProps => { const { classes, position } = styleProps; const slots = { root: ['root', `position${capitalize(position)}`], dots: ['dots'], dot: ['dot'], dotActive: ['dotActive'], progress: ['progress'] }; return composeClasses(slots, getMobileStepperUtilityClass, classes); }; const MobileStepperRoot = experimentalStyled(Paper, {}, { name: 'MuiMobileStepper', slot: 'Root', overridesResolver })(({ theme, styleProps }) => _extends({ /* Styles applied to the root element. */ display: 'flex', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', background: theme.palette.background.default, padding: 8 }, styleProps.position === 'bottom' && { position: 'fixed', bottom: 0, left: 0, right: 0, zIndex: theme.zIndex.mobileStepper }, styleProps.position === 'top' && { position: 'fixed', top: 0, left: 0, right: 0, zIndex: theme.zIndex.mobileStepper })); const MobileStepperDots = experimentalStyled('div', {}, { name: 'MuiMobileStepper', slot: 'Dots' })(({ styleProps }) => _extends({}, styleProps.variant === 'dots' && { display: 'flex', flexDirection: 'row' })); const MobileStepperDot = experimentalStyled('div', {}, { name: 'MuiMobileStepper', slot: 'Dot' })(({ theme, styleProps }) => _extends({}, styleProps.variant === 'dots' && _extends({ transition: theme.transitions.create('background-color', { duration: theme.transitions.duration.shortest }), backgroundColor: theme.palette.action.disabled, borderRadius: '50%', width: 8, height: 8, margin: '0 2px' }, styleProps.dotActive && { backgroundColor: theme.palette.primary.main }))); const MobileStepperProgress = experimentalStyled(LinearProgress, {}, { name: 'MuiMobileStepper', slot: 'Progress' })(({ styleProps }) => _extends({}, styleProps.variant === 'progress' && { width: '50%' })); const MobileStepper = /*#__PURE__*/React.forwardRef(function MobileStepper(inProps, ref) { const props = useThemeProps({ props: inProps, name: 'MuiMobileStepper' }); const { activeStep = 0, backButton, className, LinearProgressProps, nextButton, position = 'bottom', steps, variant = 'dots' } = props, other = _objectWithoutPropertiesLoose(props, ["activeStep", "backButton", "className", "LinearProgressProps", "nextButton", "position", "steps", "variant"]); const styleProps = _extends({}, props, { activeStep, position, variant }); const classes = useUtilityClasses(styleProps); return /*#__PURE__*/_jsxs(MobileStepperRoot, _extends({ square: true, elevation: 0, className: clsx(classes.root, className), ref: ref, styleProps: styleProps }, other, { children: [backButton, variant === 'text' && /*#__PURE__*/_jsxs(React.Fragment, { children: [activeStep + 1, " / ", steps] }), variant === 'dots' && /*#__PURE__*/_jsx(MobileStepperDots, { styleProps: styleProps, className: classes.dots, children: [...new Array(steps)].map((_, index) => /*#__PURE__*/_jsx(MobileStepperDot, { className: clsx(classes.dot, index === activeStep && classes.dotActive), styleProps: _extends({}, styleProps, { dotActive: index === activeStep }) }, index)) }), variant === 'progress' && /*#__PURE__*/_jsx(MobileStepperProgress, _extends({ styleProps: styleProps, className: classes.progress, variant: "determinate", value: Math.ceil(activeStep / (steps - 1) * 100) }, LinearProgressProps)), nextButton] })); }); process.env.NODE_ENV !== "production" ? MobileStepper.propTypes /* remove-proptypes */ = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * Set the active step (zero based index). * Defines which dot is highlighted when the variant is 'dots'. * @default 0 */ activeStep: integerPropType, /** * A back button element. For instance, it can be a `Button` or an `IconButton`. */ backButton: PropTypes.node, /** * Override or extend the styles applied to the component. */ classes: PropTypes.object, /** * @ignore */ className: PropTypes.string, /** * Props applied to the `LinearProgress` element. */ LinearProgressProps: PropTypes.object, /** * A next button element. For instance, it can be a `Button` or an `IconButton`. */ nextButton: PropTypes.node, /** * Set the positioning type. * @default 'bottom' */ position: PropTypes.oneOf(['bottom', 'static', 'top']), /** * The total steps. */ steps: integerPropType.isRequired, /** * The system prop that allows defining system overrides as well as additional CSS styles. */ sx: PropTypes.object, /** * The variant to use. * @default 'dots' */ variant: PropTypes.oneOf(['dots', 'progress', 'text']) } : void 0; export default MobileStepper;
cdnjs/cdnjs
ajax/libs/material-ui/5.0.0-alpha.31/modern/MobileStepper/MobileStepper.js
JavaScript
mit
6,518
/******************************************************************************** * The contents of this file are subject to the GNU General Public License * * (GPL) Version 2 or later (the "License"); you may not use this file except * * in compliance with the License. You may obtain a copy of the License at * * http://www.gnu.org/copyleft/gpl.html * * * * Software distributed under the License is distributed on an "AS IS" basis, * * without warranty of any kind, either expressed or implied. See the License * * for the specific language governing rights and limitations under the * * License. * * * * This file was originally developed as part of the software suite that * * supports the book "The Elements of Computing Systems" by Nisan and Schocken, * * MIT Press 2005. If you modify the contents of this file, please document and * * mark your changes clearly, for the benefit of others. * ********************************************************************************/ package SimulatorsGUI; import javax.swing.*; import java.awt.*; import HackGUI.*; /** * This Panel contains six MemorySegmentComponents: static, local, arg, * this, that, and temp - and provides the split pane feature between * them. */ public class MemorySegmentsComponent extends JPanel { // The spllit pane containing static and local. private JSplitPane segmentsSplitPane1; // The split pane between arg and the previous split pane. private JSplitPane segmentsSplitPane2; // The split pane between this and the previous split pane. private JSplitPane segmentsSplitPane3; // The split pane between that and the previous split pane. private JSplitPane segmentsSplitPane4; // The split pane between temp and the previous split pane. private JSplitPane segmentsSplitPane5; // 'Static' memory segment private MemorySegmentComponent staticSegment; // 'Local' memory segment private MemorySegmentComponent localSegment; // 'Arg' memory segment private MemorySegmentComponent argSegment; // 'This' memory segment private MemorySegmentComponent thisSegment; // 'That' memory segment private MemorySegmentComponent thatSegment; // 'Temp' memory segment private MemorySegmentComponent tempSegment; /** * Constructs a new MemorySegmentsComponent. */ public MemorySegmentsComponent() { // creating the segments and giving them names. staticSegment = new MemorySegmentComponent(); staticSegment.setSegmentName("Static"); localSegment = new MemorySegmentComponent(); localSegment.setSegmentName("Local"); argSegment = new MemorySegmentComponent(); argSegment.setSegmentName("Argument"); thisSegment = new MemorySegmentComponent(); thisSegment.setSegmentName("This"); thatSegment = new MemorySegmentComponent(); thatSegment.setSegmentName("That"); tempSegment = new MemorySegmentComponent(); tempSegment.setSegmentName("Temp"); // creating the split panes. segmentsSplitPane5 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, thatSegment, tempSegment); segmentsSplitPane4 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, thisSegment, segmentsSplitPane5); segmentsSplitPane3 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, argSegment, segmentsSplitPane4); segmentsSplitPane2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, localSegment, segmentsSplitPane3); segmentsSplitPane1 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, staticSegment, segmentsSplitPane2); // providing a one touch expandable feature to the split panes. segmentsSplitPane1.setOneTouchExpandable(true); segmentsSplitPane2.setOneTouchExpandable(true); segmentsSplitPane3.setOneTouchExpandable(true); segmentsSplitPane4.setOneTouchExpandable(true); segmentsSplitPane5.setOneTouchExpandable(true); // disabling the automatic border of each one of the first four // split panes. enabling the border of the fifth one. segmentsSplitPane5.setBorder(null); segmentsSplitPane4.setBorder(null); segmentsSplitPane3.setBorder(null); segmentsSplitPane2.setBorder(null); segmentsSplitPane1.setDividerLocation(30 + staticSegment.getTable().getRowHeight() * 5); segmentsSplitPane2.setDividerLocation(30 + localSegment.getTable().getRowHeight() * 5); segmentsSplitPane3.setDividerLocation(30 + argSegment.getTable().getRowHeight() * 5); segmentsSplitPane4.setDividerLocation(30 + thisSegment.getTable().getRowHeight() * 5); segmentsSplitPane5.setDividerLocation(30 + thatSegment.getTable().getRowHeight() * 2); segmentsSplitPane1.setSize(new Dimension(195, 587)); segmentsSplitPane1.setPreferredSize(new Dimension(195, 587)); } /** * Returns the split pane which contains all of the other split peanes. */ public JSplitPane getSplitPane() { return segmentsSplitPane1; } /** * Returns static memory segment. */ public MemorySegmentComponent getStaticSegment() { return staticSegment; } /** * Returns local memory segment. */ public MemorySegmentComponent getLocalSegment() { return localSegment; } /** * Returns arg memory segment. */ public MemorySegmentComponent getArgSegment() { return argSegment; } /** * Returns this memory segment. */ public MemorySegmentComponent getThisSegment() { return thisSegment; } /** * Returns that memory segment. */ public MemorySegmentComponent getThatSegment() { return thatSegment; } /** * Returns temp memory segment. */ public MemorySegmentComponent getTempSegment() { return tempSegment; } }
andyandy1992/MyMOOCs
courses/Other/Nand2Tetris(Partial)/Code/SimulatorsGUIPackageSource/SimulatorsGUI/MemorySegmentsComponent.java
Java
cc0-1.0
6,216
/************************************************************************************* * Copyright (c) 2004 Actuate Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - Initial implementation. ************************************************************************************/ package org.eclipse.birt.report.presentation.aggregation.dialog; import org.eclipse.birt.report.resource.BirtResources; import org.eclipse.birt.report.resource.ResourceConstants; /** * Fragment help rendering print dialog in side bar. * <p> * * @see BaseFragment */ public class PrintReportDialogFragment extends BaseDialogFragment { /** * Get unique id of the corresponding UI gesture. * * @return id */ public String getClientId( ) { return "printReportDialog"; //$NON-NLS-1$ } /** * Get name of the corresponding UI gesture. * * @return id */ public String getClientName( ) { return "Print Report"; //$NON-NLS-1$ } /** * Gets the title ID for the html page. * * @return title id */ public String getTitle( ) { return BirtResources.getMessage( ResourceConstants.PRINT_REPORT_DIALOG_TITLE ); } }
sguan-actuate/birt
viewer/org.eclipse.birt.report.viewer/birt/WEB-INF/classes/org/eclipse/birt/report/presentation/aggregation/dialog/PrintReportDialogFragment.java
Java
epl-1.0
1,404
/******************************************************************************* * Copyright (c) 2006, 2009 David A Carlson. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * David A Carlson (XMLmodeling.com) - initial API and implementation * * $Id$ *******************************************************************************/ package org.openhealthtools.mdht.uml.hdf.tooling.rsm.providers; import org.eclipse.emf.ecore.EObject; import org.eclipse.gef.EditPart; import org.eclipse.gmf.runtime.common.core.service.AbstractProvider; import org.eclipse.gmf.runtime.common.core.service.IOperation; import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; import org.eclipse.gmf.runtime.diagram.ui.services.editpolicy.CreateEditPoliciesOperation; import org.eclipse.gmf.runtime.diagram.ui.services.editpolicy.IEditPolicyProvider; import org.eclipse.gmf.runtime.emf.type.core.IElementType; import org.eclipse.gmf.runtime.emf.type.core.ISpecializationType; import org.openhealthtools.mdht.uml.hdf.tooling.rsm.types.RIMElementTypes; /** * @generated */ public class RIMEditPolicyProvider extends AbstractProvider implements IEditPolicyProvider { private final static String PROFILE_ASSOCIATIONS_SEMANTIC_ROLE = "ProfileAssociationsSemanticRole"; //$NON-NLS-1$ /** * @generated */ public void createEditPolicies(EditPart editPart) { editPart.installEditPolicy(PROFILE_ASSOCIATIONS_SEMANTIC_ROLE, new RIMAssociationEditPolicy()); } /** * @generated */ public boolean provides(IOperation operation) { if (operation instanceof CreateEditPoliciesOperation) { EditPart ep = ((CreateEditPoliciesOperation) operation).getEditPart(); if (ep instanceof IGraphicalEditPart) { IGraphicalEditPart gep = (IGraphicalEditPart) ep; EObject element = gep.getNotationView().getElement(); if (element != null) { for (IElementType elementType : RIMElementTypes.NODE_TYPES) { if (elementType instanceof ISpecializationType) { if (((ISpecializationType) elementType).getMatcher().matches(element)) { return true; } } } } } } return false; } }
drbgfc/mdht
hl7/plugins/org.openhealthtools.mdht.uml.hdf.tooling.rsm/src/org/openhealthtools/mdht/uml/hdf/tooling/rsm/providers/RIMEditPolicyProvider.java
Java
epl-1.0
2,440