repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
goxberry/homebrew-cask | Casks/rubymine.rb | 1013 | cask 'rubymine' do
version '2018.1.4,181.5281.41'
sha256 'e89880cfed154e01545063f830e444f0a9ae3509b177f254a92032544cffe24a'
url "https://download.jetbrains.com/ruby/RubyMine-#{version.before_comma}.dmg"
appcast 'https://data.services.jetbrains.com/products/releases?code=RM&latest=true&type=release'
name 'RubyMine'
homepage 'https://www.jetbrains.com/ruby/'
auto_updates true
app 'RubyMine.app'
uninstall_postflight do
ENV['PATH'].split(File::PATH_SEPARATOR).map { |path| File.join(path, 'mine') }.each { |path| File.delete(path) if File.exist?(path) && File.readlines(path).grep(%r{# see com.intellij.idea.SocketLock for the server side of this interface}).any? }
end
zap trash: [
"~/Library/Application Support/RubyMine#{version.major_minor}",
"~/Library/Caches/RubyMine#{version.major_minor}",
"~/Library/Logs/RubyMine#{version.major_minor}",
"~/Library/Preferences/RubyMine#{version.major_minor}",
]
end
| bsd-2-clause |
maschinenbau/freecodecamp | client/loopbackClient.js | 142 | var loopback = require('loopback'),
boot = require('loopback-boot');
var app = loopback();
boot(app, __dirname);
module.exports = app;
| bsd-3-clause |
leighpauls/k2cro4 | base/allocator/allocator_extension.cc | 1997 | // 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 "base/allocator/allocator_extension.h"
#include "base/logging.h"
namespace base {
namespace allocator {
bool GetProperty(const char* name, size_t* value) {
thunks::GetPropertyFunction get_property_function =
base::allocator::thunks::GetGetPropertyFunction();
return get_property_function != NULL && get_property_function(name, value);
}
void GetStats(char* buffer, int buffer_length) {
DCHECK_GT(buffer_length, 0);
thunks::GetStatsFunction get_stats_function =
base::allocator::thunks::GetGetStatsFunction();
if (get_stats_function)
get_stats_function(buffer, buffer_length);
else
buffer[0] = '\0';
}
void ReleaseFreeMemory() {
thunks::ReleaseFreeMemoryFunction release_free_memory_function =
base::allocator::thunks::GetReleaseFreeMemoryFunction();
if (release_free_memory_function)
release_free_memory_function();
}
void SetGetPropertyFunction(
thunks::GetPropertyFunction get_property_function) {
DCHECK_EQ(base::allocator::thunks::GetGetPropertyFunction(),
reinterpret_cast<thunks::GetPropertyFunction>(NULL));
base::allocator::thunks::SetGetPropertyFunction(get_property_function);
}
void SetGetStatsFunction(thunks::GetStatsFunction get_stats_function) {
DCHECK_EQ(base::allocator::thunks::GetGetStatsFunction(),
reinterpret_cast<thunks::GetStatsFunction>(NULL));
base::allocator::thunks::SetGetStatsFunction(get_stats_function);
}
void SetReleaseFreeMemoryFunction(
thunks::ReleaseFreeMemoryFunction release_free_memory_function) {
DCHECK_EQ(base::allocator::thunks::GetReleaseFreeMemoryFunction(),
reinterpret_cast<thunks::ReleaseFreeMemoryFunction>(NULL));
base::allocator::thunks::SetReleaseFreeMemoryFunction(
release_free_memory_function);
}
} // namespace allocator
} // namespace base
| bsd-3-clause |
jhbsz/OSI-OS | sys/dev/ed/if_ed_novell.c | 9160 | /*-
* Copyright (c) 2005, M. Warner Losh
* All rights reserved.
* Copyright (c) 1995, David Greenman
* 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 unmodified, 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*/
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");
#include "opt_ed.h"
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/sockio.h>
#include <sys/mbuf.h>
#include <sys/kernel.h>
#include <sys/socket.h>
#include <sys/syslog.h>
#include <sys/bus.h>
#include <machine/bus.h>
#include <sys/rman.h>
#include <machine/resource.h>
#include <net/ethernet.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <net/if_dl.h>
#include <net/if_mib.h>
#include <net/if_media.h>
#include <net/bpf.h>
#include <dev/ed/if_edreg.h>
#include <dev/ed/if_edvar.h>
static int ed_probe_gwether(device_t);
/*
* Probe and vendor-specific initialization routine for NE1000/2000 boards
*/
int
ed_probe_Novell_generic(device_t dev, int flags)
{
struct ed_softc *sc = device_get_softc(dev);
u_int memsize;
int error;
u_char tmp;
static char test_pattern[32] = "THIS is A memory TEST pattern";
char test_buffer[32];
/* Reset the board */
if (ED_FLAGS_GETTYPE(flags) == ED_FLAGS_GWETHER) {
ed_asic_outb(sc, ED_NOVELL_RESET, 0);
DELAY(200);
}
tmp = ed_asic_inb(sc, ED_NOVELL_RESET);
/*
* I don't know if this is necessary; probably cruft leftover from
* Clarkson packet driver code. Doesn't do a thing on the boards I've
* tested. -DG
*/
ed_asic_outb(sc, ED_NOVELL_RESET, tmp);
DELAY(5000);
/*
* This is needed because some NE clones apparently don't reset the
* NIC properly (or the NIC chip doesn't reset fully on power-up) XXX
* - this makes the probe invasive! ...Done against my better
* judgement. -DLG
*/
ed_nic_outb(sc, ED_P0_CR, ED_CR_RD2 | ED_CR_STP);
DELAY(5000);
/* Make sure that we really have an 8390 based board */
if (!ed_probe_generic8390(sc))
return (ENXIO);
sc->vendor = ED_VENDOR_NOVELL;
sc->mem_shared = 0;
sc->cr_proto = ED_CR_RD2;
/*
* Test the ability to read and write to the NIC memory. This has the
* side affect of determining if this is an NE1000 or an NE2000.
*/
/*
* This prevents packets from being stored in the NIC memory when the
* readmem routine turns on the start bit in the CR.
*/
ed_nic_outb(sc, ED_P0_RCR, ED_RCR_MON);
/* Temporarily initialize DCR for byte operations */
ed_nic_outb(sc, ED_P0_DCR, ED_DCR_FT1 | ED_DCR_LS);
ed_nic_outb(sc, ED_P0_PSTART, 8192 / ED_PAGE_SIZE);
ed_nic_outb(sc, ED_P0_PSTOP, 16384 / ED_PAGE_SIZE);
/*
* Some devices identify themselves. Some of those devices
* can't handle being probed, so we allow forcing a mode. If
* these flags are set, force it, otherwise probe.
*/
if (flags & ED_FLAGS_FORCE_8BIT_MODE) {
sc->isa16bit = 0;
sc->type = ED_TYPE_NE1000;
sc->type_str = "NE1000";
} else if (flags & ED_FLAGS_FORCE_16BIT_MODE) {
sc->isa16bit = 1;
sc->type = ED_TYPE_NE2000;
sc->type_str = "NE2000";
ed_nic_outb(sc, ED_P0_DCR, ED_DCR_WTS | ED_DCR_FT1 | ED_DCR_LS);
ed_nic_outb(sc, ED_P0_PSTART, 16384 / ED_PAGE_SIZE);
ed_nic_outb(sc, ED_P0_PSTOP, 32768 / ED_PAGE_SIZE);
} else {
/*
* Write a test pattern in byte mode. If this fails, then there
* probably isn't any memory at 8k - which likely means that the board
* is an NE2000.
*/
ed_pio_writemem(sc, test_pattern, 8192, sizeof(test_pattern));
ed_pio_readmem(sc, 8192, test_buffer, sizeof(test_pattern));
if (bcmp(test_pattern, test_buffer, sizeof(test_pattern)) == 0) {
sc->type = ED_TYPE_NE1000;
sc->type_str = "NE1000";
sc->isa16bit = 0;
} else {
/* Not an NE1000 - try NE2000 */
sc->isa16bit = 1;
ed_nic_outb(sc, ED_P0_DCR, ED_DCR_WTS | ED_DCR_FT1 | ED_DCR_LS);
ed_nic_outb(sc, ED_P0_PSTART, 16384 / ED_PAGE_SIZE);
ed_nic_outb(sc, ED_P0_PSTOP, 32768 / ED_PAGE_SIZE);
/*
* Write a test pattern in word mode. If this also fails, then
* we don't know what this board is.
*/
ed_pio_writemem(sc, test_pattern, 16384, sizeof(test_pattern));
ed_pio_readmem(sc, 16384, test_buffer, sizeof(test_pattern));
if (bcmp(test_pattern, test_buffer, sizeof(test_pattern)) == 0) {
sc->type = ED_TYPE_NE2000;
sc->type_str = "NE2000";
} else {
return (ENXIO);
}
}
}
sc->chip_type = ED_CHIP_TYPE_DP8390;
/* 8k of memory plus an additional 8k if 16bit */
memsize = 8192 + sc->isa16bit * 8192;
sc->mem_size = memsize;
/* NIC memory doesn't start at zero on an NE board */
/* The start address is tied to the bus width */
sc->mem_start = 8192 + sc->isa16bit * 8192;
sc->mem_end = sc->mem_start + memsize;
sc->tx_page_start = memsize / ED_PAGE_SIZE;
if (ED_FLAGS_GETTYPE(flags) == ED_FLAGS_GWETHER) {
error = ed_probe_gwether(dev);
if (error)
return (error);
}
/*
* Use one xmit buffer if < 16k, two buffers otherwise (if not told
* otherwise).
*/
if ((memsize < 16384) || (flags & ED_FLAGS_NO_MULTI_BUFFERING))
sc->txb_cnt = 1;
else
sc->txb_cnt = 2;
sc->rec_page_start = sc->tx_page_start + sc->txb_cnt * ED_TXBUF_SIZE;
sc->rec_page_stop = sc->tx_page_start + memsize / ED_PAGE_SIZE;
sc->mem_ring = sc->mem_start + sc->txb_cnt * ED_PAGE_SIZE * ED_TXBUF_SIZE;
/* clear any pending interrupts that might have occurred above */
ed_nic_outb(sc, ED_P0_ISR, 0xff);
sc->sc_write_mbufs = ed_pio_write_mbufs;
return (0);
}
int
ed_probe_Novell(device_t dev, int port_rid, int flags)
{
struct ed_softc *sc = device_get_softc(dev);
int error;
error = ed_alloc_port(dev, port_rid, ED_NOVELL_IO_PORTS);
if (error)
return (error);
sc->asic_offset = ED_NOVELL_ASIC_OFFSET;
sc->nic_offset = ED_NOVELL_NIC_OFFSET;
return ed_probe_Novell_generic(dev, flags);
}
static int
ed_probe_gwether(device_t dev)
{
int x, i, msize = 0;
bus_size_t mstart = 0;
char pbuf0[ED_PAGE_SIZE], pbuf[ED_PAGE_SIZE], tbuf[ED_PAGE_SIZE];
struct ed_softc *sc = device_get_softc(dev);
for (i = 0; i < ED_PAGE_SIZE; i++)
pbuf0[i] = 0;
/* Clear all the memory. */
for (x = 1; x < 256; x++)
ed_pio_writemem(sc, pbuf0, x * 256, ED_PAGE_SIZE);
/* Search for the start of RAM. */
for (x = 1; x < 256; x++) {
ed_pio_readmem(sc, x * 256, tbuf, ED_PAGE_SIZE);
if (bcmp(pbuf0, tbuf, ED_PAGE_SIZE) == 0) {
for (i = 0; i < ED_PAGE_SIZE; i++)
pbuf[i] = 255 - x;
ed_pio_writemem(sc, pbuf, x * 256, ED_PAGE_SIZE);
ed_pio_readmem(sc, x * 256, tbuf, ED_PAGE_SIZE);
if (bcmp(pbuf, tbuf, ED_PAGE_SIZE) == 0) {
mstart = x * ED_PAGE_SIZE;
msize = ED_PAGE_SIZE;
break;
}
}
}
if (mstart == 0) {
device_printf(dev, "Cannot find start of RAM.\n");
return (ENXIO);
}
/* Probe the size of RAM. */
for (x = (mstart / ED_PAGE_SIZE) + 1; x < 256; x++) {
ed_pio_readmem(sc, x * 256, tbuf, ED_PAGE_SIZE);
if (bcmp(pbuf0, tbuf, ED_PAGE_SIZE) == 0) {
for (i = 0; i < ED_PAGE_SIZE; i++)
pbuf[i] = 255 - x;
ed_pio_writemem(sc, pbuf, x * 256, ED_PAGE_SIZE);
ed_pio_readmem(sc, x * 256, tbuf, ED_PAGE_SIZE);
if (bcmp(pbuf, tbuf, ED_PAGE_SIZE) == 0)
msize += ED_PAGE_SIZE;
else {
break;
}
} else {
break;
}
}
if (msize == 0) {
device_printf(dev,
"Cannot find any RAM, start : %d, x = %d.\n",
(int)mstart, x);
return (ENXIO);
}
if (bootverbose)
device_printf(dev,
"RAM start at %d, size : %d.\n", (int)mstart, msize);
sc->mem_size = msize;
sc->mem_start = mstart;
sc->mem_end = msize + mstart;
sc->tx_page_start = mstart / ED_PAGE_SIZE;
return 0;
}
void
ed_Novell_read_mac(struct ed_softc *sc)
{
int n;
uint8_t romdata[16];
/*
* Most ne1000/ne2000 compatible cards have their MAC address
* located in the first few words of the address space. This seems
* universally true for ISA and PCI implementations, but PC Card
* devices seem to have more variance.
*/
ed_pio_readmem(sc, 0, romdata, 16);
for (n = 0; n < ETHER_ADDR_LEN; n++)
sc->enaddr[n] = romdata[n * (sc->isa16bit + 1)];
}
| bsd-3-clause |
frivoal/presto-testo | css/image-fit/reftests/video-ogg-wide/hidden_none_right_50-ref.html | 411 | <!doctype html>
<!-- This file is generated by build.py. -->
<title>Reference for video 240x160.ogv; overflow:hidden; -o-object-fit:none; -o-object-position:right 50%</title>
<link rel="stylesheet" href="../../support/reftests.css">
<style>
.helper { overflow:hidden }
.helper > * { right:0; top:20.0px; }
</style>
<div id="ref">
<span class="helper"><img src="../../support/240x160.ogv.png"></span>
</div>
| bsd-3-clause |
joergdietrich/astropy | cextern/erfa/pvppv.c | 3699 | #include "erfa.h"
void eraPvppv(double a[2][3], double b[2][3], double apb[2][3])
/*
** - - - - - - - - -
** e r a P v p p v
** - - - - - - - - -
**
** Add one pv-vector to another.
**
** Given:
** a double[2][3] first pv-vector
** b double[2][3] second pv-vector
**
** Returned:
** apb double[2][3] a + b
**
** Note:
** It is permissible to re-use the same array for any of the
** arguments.
**
** Called:
** eraPpp p-vector plus p-vector
**
** Copyright (C) 2013-2016, NumFOCUS Foundation.
** Derived, with permission, from the SOFA library. See notes at end of file.
*/
{
eraPpp(a[0], b[0], apb[0]);
eraPpp(a[1], b[1], apb[1]);
return;
}
/*----------------------------------------------------------------------
**
**
** Copyright (C) 2013-2016, NumFOCUS Foundation.
** All rights reserved.
**
** This library is derived, with permission, from the International
** Astronomical Union's "Standards of Fundamental Astronomy" library,
** available from http://www.iausofa.org.
**
** The ERFA version is intended to retain identical functionality to
** the SOFA library, but made distinct through different function and
** file names, as set out in the SOFA license conditions. The SOFA
** original has a role as a reference standard for the IAU and IERS,
** and consequently redistribution is permitted only in its unaltered
** state. The ERFA version is not subject to this restriction and
** therefore can be included in distributions which do not support the
** concept of "read only" software.
**
** Although the intent is to replicate the SOFA API (other than
** replacement of prefix names) and results (with the exception of
** bugs; any that are discovered will be fixed), SOFA is not
** responsible for any errors found in this version of the library.
**
** If you wish to acknowledge the SOFA heritage, please acknowledge
** that you are using a library derived from SOFA, rather than SOFA
** itself.
**
**
** TERMS AND CONDITIONS
**
** 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 of the Standards Of Fundamental Astronomy Board,
** the International Astronomical Union 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 HOLDER 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.
**
*/
| bsd-3-clause |
kaushik94/sympy | sympy/ntheory/generate.py | 28626 | """
Generating and counting primes.
"""
from __future__ import print_function, division
import random
from bisect import bisect
# Using arrays for sieving instead of lists greatly reduces
# memory consumption
from array import array as _array
from sympy import Function, S
from sympy.core.compatibility import as_int, range
from .primetest import isprime
def _azeros(n):
return _array('l', [0]*n)
def _aset(*v):
return _array('l', v)
def _arange(a, b):
return _array('l', range(a, b))
class Sieve:
"""An infinite list of prime numbers, implemented as a dynamically
growing sieve of Eratosthenes. When a lookup is requested involving
an odd number that has not been sieved, the sieve is automatically
extended up to that number.
Examples
========
>>> from sympy import sieve
>>> sieve._reset() # this line for doctest only
>>> 25 in sieve
False
>>> sieve._list
array('l', [2, 3, 5, 7, 11, 13, 17, 19, 23])
"""
# data shared (and updated) by all Sieve instances
def __init__(self):
self._n = 6
self._list = _aset(2, 3, 5, 7, 11, 13) # primes
self._tlist = _aset(0, 1, 1, 2, 2, 4) # totient
self._mlist = _aset(0, 1, -1, -1, 0, -1) # mobius
assert all(len(i) == self._n for i in (self._list, self._tlist, self._mlist))
def __repr__(self):
return ("<%s sieve (%i): %i, %i, %i, ... %i, %i\n"
"%s sieve (%i): %i, %i, %i, ... %i, %i\n"
"%s sieve (%i): %i, %i, %i, ... %i, %i>") % (
'prime', len(self._list),
self._list[0], self._list[1], self._list[2],
self._list[-2], self._list[-1],
'totient', len(self._tlist),
self._tlist[0], self._tlist[1],
self._tlist[2], self._tlist[-2], self._tlist[-1],
'mobius', len(self._mlist),
self._mlist[0], self._mlist[1],
self._mlist[2], self._mlist[-2], self._mlist[-1])
def _reset(self, prime=None, totient=None, mobius=None):
"""Reset all caches (default). To reset one or more set the
desired keyword to True."""
if all(i is None for i in (prime, totient, mobius)):
prime = totient = mobius = True
if prime:
self._list = self._list[:self._n]
if totient:
self._tlist = self._tlist[:self._n]
if mobius:
self._mlist = self._mlist[:self._n]
def extend(self, n):
"""Grow the sieve to cover all primes <= n (a real number).
Examples
========
>>> from sympy import sieve
>>> sieve._reset() # this line for doctest only
>>> sieve.extend(30)
>>> sieve[10] == 29
True
"""
n = int(n)
if n <= self._list[-1]:
return
# We need to sieve against all bases up to sqrt(n).
# This is a recursive call that will do nothing if there are enough
# known bases already.
maxbase = int(n**0.5) + 1
self.extend(maxbase)
# Create a new sieve starting from sqrt(n)
begin = self._list[-1] + 1
newsieve = _arange(begin, n + 1)
# Now eliminate all multiples of primes in [2, sqrt(n)]
for p in self.primerange(2, maxbase):
# Start counting at a multiple of p, offsetting
# the index to account for the new sieve's base index
startindex = (-begin) % p
for i in range(startindex, len(newsieve), p):
newsieve[i] = 0
# Merge the sieves
self._list += _array('l', [x for x in newsieve if x])
def extend_to_no(self, i):
"""Extend to include the ith prime number.
Parameters
==========
i : integer
Examples
========
>>> from sympy import sieve
>>> sieve._reset() # this line for doctest only
>>> sieve.extend_to_no(9)
>>> sieve._list
array('l', [2, 3, 5, 7, 11, 13, 17, 19, 23])
Notes
=====
The list is extended by 50% if it is too short, so it is
likely that it will be longer than requested.
"""
i = as_int(i)
while len(self._list) < i:
self.extend(int(self._list[-1] * 1.5))
def primerange(self, a, b):
"""Generate all prime numbers in the range [a, b).
Examples
========
>>> from sympy import sieve
>>> print([i for i in sieve.primerange(7, 18)])
[7, 11, 13, 17]
"""
from sympy.functions.elementary.integers import ceiling
# wrapping ceiling in as_int will raise an error if there was a problem
# determining whether the expression was exactly an integer or not
a = max(2, as_int(ceiling(a)))
b = as_int(ceiling(b))
if a >= b:
return
self.extend(b)
i = self.search(a)[1]
maxi = len(self._list) + 1
while i < maxi:
p = self._list[i - 1]
if p < b:
yield p
i += 1
else:
return
def totientrange(self, a, b):
"""Generate all totient numbers for the range [a, b).
Examples
========
>>> from sympy import sieve
>>> print([i for i in sieve.totientrange(7, 18)])
[6, 4, 6, 4, 10, 4, 12, 6, 8, 8, 16]
"""
from sympy.functions.elementary.integers import ceiling
# wrapping ceiling in as_int will raise an error if there was a problem
# determining whether the expression was exactly an integer or not
a = max(1, as_int(ceiling(a)))
b = as_int(ceiling(b))
n = len(self._tlist)
if a >= b:
return
elif b <= n:
for i in range(a, b):
yield self._tlist[i]
else:
self._tlist += _arange(n, b)
for i in range(1, n):
ti = self._tlist[i]
startindex = (n + i - 1) // i * i
for j in range(startindex, b, i):
self._tlist[j] -= ti
if i >= a:
yield ti
for i in range(n, b):
ti = self._tlist[i]
for j in range(2 * i, b, i):
self._tlist[j] -= ti
if i >= a:
yield ti
def mobiusrange(self, a, b):
"""Generate all mobius numbers for the range [a, b).
Parameters
==========
a : integer
First number in range
b : integer
First number outside of range
Examples
========
>>> from sympy import sieve
>>> print([i for i in sieve.mobiusrange(7, 18)])
[-1, 0, 0, 1, -1, 0, -1, 1, 1, 0, -1]
"""
from sympy.functions.elementary.integers import ceiling
# wrapping ceiling in as_int will raise an error if there was a problem
# determining whether the expression was exactly an integer or not
a = max(1, as_int(ceiling(a)))
b = as_int(ceiling(b))
n = len(self._mlist)
if a >= b:
return
elif b <= n:
for i in range(a, b):
yield self._mlist[i]
else:
self._mlist += _azeros(b - n)
for i in range(1, n):
mi = self._mlist[i]
startindex = (n + i - 1) // i * i
for j in range(startindex, b, i):
self._mlist[j] -= mi
if i >= a:
yield mi
for i in range(n, b):
mi = self._mlist[i]
for j in range(2 * i, b, i):
self._mlist[j] -= mi
if i >= a:
yield mi
def search(self, n):
"""Return the indices i, j of the primes that bound n.
If n is prime then i == j.
Although n can be an expression, if ceiling cannot convert
it to an integer then an n error will be raised.
Examples
========
>>> from sympy import sieve
>>> sieve.search(25)
(9, 10)
>>> sieve.search(23)
(9, 9)
"""
from sympy.functions.elementary.integers import ceiling
# wrapping ceiling in as_int will raise an error if there was a problem
# determining whether the expression was exactly an integer or not
test = as_int(ceiling(n))
n = as_int(n)
if n < 2:
raise ValueError("n should be >= 2 but got: %s" % n)
if n > self._list[-1]:
self.extend(n)
b = bisect(self._list, n)
if self._list[b - 1] == test:
return b, b
else:
return b, b + 1
def __contains__(self, n):
try:
n = as_int(n)
assert n >= 2
except (ValueError, AssertionError):
return False
if n % 2 == 0:
return n == 2
a, b = self.search(n)
return a == b
def __getitem__(self, n):
"""Return the nth prime number"""
if isinstance(n, slice):
self.extend_to_no(n.stop)
return self._list[n.start - 1:n.stop - 1:n.step]
else:
n = as_int(n)
self.extend_to_no(n)
return self._list[n - 1]
# Generate a global object for repeated use in trial division etc
sieve = Sieve()
def prime(nth):
""" Return the nth prime, with the primes indexed as prime(1) = 2,
prime(2) = 3, etc.... The nth prime is approximately n*log(n).
Logarithmic integral of x is a pretty nice approximation for number of
primes <= x, i.e.
li(x) ~ pi(x)
In fact, for the numbers we are concerned about( x<1e11 ),
li(x) - pi(x) < 50000
Also,
li(x) > pi(x) can be safely assumed for the numbers which
can be evaluated by this function.
Here, we find the least integer m such that li(m) > n using binary search.
Now pi(m-1) < li(m-1) <= n,
We find pi(m - 1) using primepi function.
Starting from m, we have to find n - pi(m-1) more primes.
For the inputs this implementation can handle, we will have to test
primality for at max about 10**5 numbers, to get our answer.
Examples
========
>>> from sympy import prime
>>> prime(10)
29
>>> prime(1)
2
>>> prime(100000)
1299709
See Also
========
sympy.ntheory.primetest.isprime : Test if n is prime
primerange : Generate all primes in a given range
primepi : Return the number of primes less than or equal to n
References
==========
.. [1] https://en.wikipedia.org/wiki/Prime_number_theorem#Table_of_.CF.80.28x.29.2C_x_.2F_log_x.2C_and_li.28x.29
.. [2] https://en.wikipedia.org/wiki/Prime_number_theorem#Approximations_for_the_nth_prime_number
.. [3] https://en.wikipedia.org/wiki/Skewes%27_number
"""
n = as_int(nth)
if n < 1:
raise ValueError("nth must be a positive integer; prime(1) == 2")
if n <= len(sieve._list):
return sieve[n]
from sympy.functions.special.error_functions import li
from sympy.functions.elementary.exponential import log
a = 2 # Lower bound for binary search
b = int(n*(log(n) + log(log(n)))) # Upper bound for the search.
while a < b:
mid = (a + b) >> 1
if li(mid) > n:
b = mid
else:
a = mid + 1
n_primes = primepi(a - 1)
while n_primes < n:
if isprime(a):
n_primes += 1
a += 1
return a - 1
class primepi(Function):
""" Represents the prime counting function pi(n) = the number
of prime numbers less than or equal to n.
Algorithm Description:
In sieve method, we remove all multiples of prime p
except p itself.
Let phi(i,j) be the number of integers 2 <= k <= i
which remain after sieving from primes less than
or equal to j.
Clearly, pi(n) = phi(n, sqrt(n))
If j is not a prime,
phi(i,j) = phi(i, j - 1)
if j is a prime,
We remove all numbers(except j) whose
smallest prime factor is j.
Let x= j*a be such a number, where 2 <= a<= i / j
Now, after sieving from primes <= j - 1,
a must remain
(because x, and hence a has no prime factor <= j - 1)
Clearly, there are phi(i / j, j - 1) such a
which remain on sieving from primes <= j - 1
Now, if a is a prime less than equal to j - 1,
x= j*a has smallest prime factor = a, and
has already been removed(by sieving from a).
So, we don't need to remove it again.
(Note: there will be pi(j - 1) such x)
Thus, number of x, that will be removed are:
phi(i / j, j - 1) - phi(j - 1, j - 1)
(Note that pi(j - 1) = phi(j - 1, j - 1))
=> phi(i,j) = phi(i, j - 1) - phi(i / j, j - 1) + phi(j - 1, j - 1)
So,following recursion is used and implemented as dp:
phi(a, b) = phi(a, b - 1), if b is not a prime
phi(a, b) = phi(a, b-1)-phi(a / b, b-1) + phi(b-1, b-1), if b is prime
Clearly a is always of the form floor(n / k),
which can take at most 2*sqrt(n) values.
Two arrays arr1,arr2 are maintained
arr1[i] = phi(i, j),
arr2[i] = phi(n // i, j)
Finally the answer is arr2[1]
Examples
========
>>> from sympy import primepi
>>> primepi(25)
9
See Also
========
sympy.ntheory.primetest.isprime : Test if n is prime
primerange : Generate all primes in a given range
prime : Return the nth prime
"""
@classmethod
def eval(cls, n):
if n is S.Infinity:
return S.Infinity
if n is S.NegativeInfinity:
return S.Zero
try:
n = int(n)
except TypeError:
if n.is_real == False or n is S.NaN:
raise ValueError("n must be real")
return
if n < 2:
return S.Zero
if n <= sieve._list[-1]:
return S(sieve.search(n)[0])
lim = int(n ** 0.5)
lim -= 1
lim = max(lim, 0)
while lim * lim <= n:
lim += 1
lim -= 1
arr1 = [0] * (lim + 1)
arr2 = [0] * (lim + 1)
for i in range(1, lim + 1):
arr1[i] = i - 1
arr2[i] = n // i - 1
for i in range(2, lim + 1):
# Presently, arr1[k]=phi(k,i - 1),
# arr2[k] = phi(n // k,i - 1)
if arr1[i] == arr1[i - 1]:
continue
p = arr1[i - 1]
for j in range(1, min(n // (i * i), lim) + 1):
st = i * j
if st <= lim:
arr2[j] -= arr2[st] - p
else:
arr2[j] -= arr1[n // st] - p
lim2 = min(lim, i * i - 1)
for j in range(lim, lim2, -1):
arr1[j] -= arr1[j // i] - p
return S(arr2[1])
def nextprime(n, ith=1):
""" Return the ith prime greater than n.
i must be an integer.
Notes
=====
Potential primes are located at 6*j +/- 1. This
property is used during searching.
>>> from sympy import nextprime
>>> [(i, nextprime(i)) for i in range(10, 15)]
[(10, 11), (11, 13), (12, 13), (13, 17), (14, 17)]
>>> nextprime(2, ith=2) # the 2nd prime after 2
5
See Also
========
prevprime : Return the largest prime smaller than n
primerange : Generate all primes in a given range
"""
n = int(n)
i = as_int(ith)
if i > 1:
pr = n
j = 1
while 1:
pr = nextprime(pr)
j += 1
if j > i:
break
return pr
if n < 2:
return 2
if n < 7:
return {2: 3, 3: 5, 4: 5, 5: 7, 6: 7}[n]
if n <= sieve._list[-2]:
l, u = sieve.search(n)
if l == u:
return sieve[u + 1]
else:
return sieve[u]
nn = 6*(n//6)
if nn == n:
n += 1
if isprime(n):
return n
n += 4
elif n - nn == 5:
n += 2
if isprime(n):
return n
n += 4
else:
n = nn + 5
while 1:
if isprime(n):
return n
n += 2
if isprime(n):
return n
n += 4
def prevprime(n):
""" Return the largest prime smaller than n.
Notes
=====
Potential primes are located at 6*j +/- 1. This
property is used during searching.
>>> from sympy import prevprime
>>> [(i, prevprime(i)) for i in range(10, 15)]
[(10, 7), (11, 7), (12, 11), (13, 11), (14, 13)]
See Also
========
nextprime : Return the ith prime greater than n
primerange : Generates all primes in a given range
"""
from sympy.functions.elementary.integers import ceiling
# wrapping ceiling in as_int will raise an error if there was a problem
# determining whether the expression was exactly an integer or not
n = as_int(ceiling(n))
if n < 3:
raise ValueError("no preceding primes")
if n < 8:
return {3: 2, 4: 3, 5: 3, 6: 5, 7: 5}[n]
if n <= sieve._list[-1]:
l, u = sieve.search(n)
if l == u:
return sieve[l-1]
else:
return sieve[l]
nn = 6*(n//6)
if n - nn <= 1:
n = nn - 1
if isprime(n):
return n
n -= 4
else:
n = nn + 1
while 1:
if isprime(n):
return n
n -= 2
if isprime(n):
return n
n -= 4
def primerange(a, b):
""" Generate a list of all prime numbers in the range [a, b).
If the range exists in the default sieve, the values will
be returned from there; otherwise values will be returned
but will not modify the sieve.
Examples
========
>>> from sympy import primerange, sieve
>>> print([i for i in primerange(1, 30)])
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
The Sieve method, primerange, is generally faster but it will
occupy more memory as the sieve stores values. The default
instance of Sieve, named sieve, can be used:
>>> list(sieve.primerange(1, 30))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
Notes
=====
Some famous conjectures about the occurrence of primes in a given
range are [1]:
- Twin primes: though often not, the following will give 2 primes
an infinite number of times:
primerange(6*n - 1, 6*n + 2)
- Legendre's: the following always yields at least one prime
primerange(n**2, (n+1)**2+1)
- Bertrand's (proven): there is always a prime in the range
primerange(n, 2*n)
- Brocard's: there are at least four primes in the range
primerange(prime(n)**2, prime(n+1)**2)
The average gap between primes is log(n) [2]; the gap between
primes can be arbitrarily large since sequences of composite
numbers are arbitrarily large, e.g. the numbers in the sequence
n! + 2, n! + 3 ... n! + n are all composite.
See Also
========
nextprime : Return the ith prime greater than n
prevprime : Return the largest prime smaller than n
randprime : Returns a random prime in a given range
primorial : Returns the product of primes based on condition
Sieve.primerange : return range from already computed primes
or extend the sieve to contain the requested
range.
References
==========
.. [1] https://en.wikipedia.org/wiki/Prime_number
.. [2] http://primes.utm.edu/notes/gaps.html
"""
from sympy.functions.elementary.integers import ceiling
if a >= b:
return
# if we already have the range, return it
if b <= sieve._list[-1]:
for i in sieve.primerange(a, b):
yield i
return
# otherwise compute, without storing, the desired range.
# wrapping ceiling in as_int will raise an error if there was a problem
# determining whether the expression was exactly an integer or not
a = as_int(ceiling(a)) - 1
b = as_int(ceiling(b))
while 1:
a = nextprime(a)
if a < b:
yield a
else:
return
def randprime(a, b):
""" Return a random prime number in the range [a, b).
Bertrand's postulate assures that
randprime(a, 2*a) will always succeed for a > 1.
Examples
========
>>> from sympy import randprime, isprime
>>> randprime(1, 30) #doctest: +SKIP
13
>>> isprime(randprime(1, 30))
True
See Also
========
primerange : Generate all primes in a given range
References
==========
.. [1] https://en.wikipedia.org/wiki/Bertrand's_postulate
"""
if a >= b:
return
a, b = map(int, (a, b))
n = random.randint(a - 1, b)
p = nextprime(n)
if p >= b:
p = prevprime(b)
if p < a:
raise ValueError("no primes exist in the specified range")
return p
def primorial(n, nth=True):
"""
Returns the product of the first n primes (default) or
the primes less than or equal to n (when ``nth=False``).
Examples
========
>>> from sympy.ntheory.generate import primorial, randprime, primerange
>>> from sympy import factorint, Mul, primefactors, sqrt
>>> primorial(4) # the first 4 primes are 2, 3, 5, 7
210
>>> primorial(4, nth=False) # primes <= 4 are 2 and 3
6
>>> primorial(1)
2
>>> primorial(1, nth=False)
1
>>> primorial(sqrt(101), nth=False)
210
One can argue that the primes are infinite since if you take
a set of primes and multiply them together (e.g. the primorial) and
then add or subtract 1, the result cannot be divided by any of the
original factors, hence either 1 or more new primes must divide this
product of primes.
In this case, the number itself is a new prime:
>>> factorint(primorial(4) + 1)
{211: 1}
In this case two new primes are the factors:
>>> factorint(primorial(4) - 1)
{11: 1, 19: 1}
Here, some primes smaller and larger than the primes multiplied together
are obtained:
>>> p = list(primerange(10, 20))
>>> sorted(set(primefactors(Mul(*p) + 1)).difference(set(p)))
[2, 5, 31, 149]
See Also
========
primerange : Generate all primes in a given range
"""
if nth:
n = as_int(n)
else:
n = int(n)
if n < 1:
raise ValueError("primorial argument must be >= 1")
p = 1
if nth:
for i in range(1, n + 1):
p *= prime(i)
else:
for i in primerange(2, n + 1):
p *= i
return p
def cycle_length(f, x0, nmax=None, values=False):
"""For a given iterated sequence, return a generator that gives
the length of the iterated cycle (lambda) and the length of terms
before the cycle begins (mu); if ``values`` is True then the
terms of the sequence will be returned instead. The sequence is
started with value ``x0``.
Note: more than the first lambda + mu terms may be returned and this
is the cost of cycle detection with Brent's method; there are, however,
generally less terms calculated than would have been calculated if the
proper ending point were determined, e.g. by using Floyd's method.
>>> from sympy.ntheory.generate import cycle_length
This will yield successive values of i <-- func(i):
>>> def iter(func, i):
... while 1:
... ii = func(i)
... yield ii
... i = ii
...
A function is defined:
>>> func = lambda i: (i**2 + 1) % 51
and given a seed of 4 and the mu and lambda terms calculated:
>>> next(cycle_length(func, 4))
(6, 2)
We can see what is meant by looking at the output:
>>> n = cycle_length(func, 4, values=True)
>>> list(ni for ni in n)
[17, 35, 2, 5, 26, 14, 44, 50, 2, 5, 26, 14]
There are 6 repeating values after the first 2.
If a sequence is suspected of being longer than you might wish, ``nmax``
can be used to exit early (and mu will be returned as None):
>>> next(cycle_length(func, 4, nmax = 4))
(4, None)
>>> [ni for ni in cycle_length(func, 4, nmax = 4, values=True)]
[17, 35, 2, 5]
Code modified from:
https://en.wikipedia.org/wiki/Cycle_detection.
"""
nmax = int(nmax or 0)
# main phase: search successive powers of two
power = lam = 1
tortoise, hare = x0, f(x0) # f(x0) is the element/node next to x0.
i = 0
while tortoise != hare and (not nmax or i < nmax):
i += 1
if power == lam: # time to start a new power of two?
tortoise = hare
power *= 2
lam = 0
if values:
yield hare
hare = f(hare)
lam += 1
if nmax and i == nmax:
if values:
return
else:
yield nmax, None
return
if not values:
# Find the position of the first repetition of length lambda
mu = 0
tortoise = hare = x0
for i in range(lam):
hare = f(hare)
while tortoise != hare:
tortoise = f(tortoise)
hare = f(hare)
mu += 1
if mu:
mu -= 1
yield lam, mu
def composite(nth):
""" Return the nth composite number, with the composite numbers indexed as
composite(1) = 4, composite(2) = 6, etc....
Examples
========
>>> from sympy import composite
>>> composite(36)
52
>>> composite(1)
4
>>> composite(17737)
20000
See Also
========
sympy.ntheory.primetest.isprime : Test if n is prime
primerange : Generate all primes in a given range
primepi : Return the number of primes less than or equal to n
prime : Return the nth prime
compositepi : Return the number of positive composite numbers less than or equal to n
"""
n = as_int(nth)
if n < 1:
raise ValueError("nth must be a positive integer; composite(1) == 4")
composite_arr = [4, 6, 8, 9, 10, 12, 14, 15, 16, 18]
if n <= 10:
return composite_arr[n - 1]
a, b = 4, sieve._list[-1]
if n <= b - primepi(b) - 1:
while a < b - 1:
mid = (a + b) >> 1
if mid - primepi(mid) - 1 > n:
b = mid
else:
a = mid
if isprime(a):
a -= 1
return a
from sympy.functions.special.error_functions import li
from sympy.functions.elementary.exponential import log
a = 4 # Lower bound for binary search
b = int(n*(log(n) + log(log(n)))) # Upper bound for the search.
while a < b:
mid = (a + b) >> 1
if mid - li(mid) - 1 > n:
b = mid
else:
a = mid + 1
n_composites = a - primepi(a) - 1
while n_composites > n:
if not isprime(a):
n_composites -= 1
a -= 1
if isprime(a):
a -= 1
return a
def compositepi(n):
""" Return the number of positive composite numbers less than or equal to n.
The first positive composite is 4, i.e. compositepi(4) = 1.
Examples
========
>>> from sympy import compositepi
>>> compositepi(25)
15
>>> compositepi(1000)
831
See Also
========
sympy.ntheory.primetest.isprime : Test if n is prime
primerange : Generate all primes in a given range
prime : Return the nth prime
primepi : Return the number of primes less than or equal to n
composite : Return the nth composite number
"""
n = int(n)
if n < 4:
return 0
return n - primepi(n) - 1
| bsd-3-clause |
whiteley/rbx-deb | web/_site/doc/fr/virtual-machine/custom-dispatch-logic/index.html | 6396 | <!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
<title>Custom Dispatch Logic - Rubinius</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta content='en' http-equiv='content-language'>
<meta content='Rubinius is an implementation of the Ruby programming language. The Rubinius bytecode virtual machine is written in C++. The bytecode compiler is written in pure Ruby. The vast majority of the core library is also written in Ruby, with some supporting primitives that interact with the VM directly.' name='description'>
<link href='/' rel='home'>
<link href='/' rel='start'>
<link href='/doc/en/virtual-machine/instructions' rel='prev' title='Instructions'>
<link href='/doc/en/bytecode-compiler' rel='next' title='Bytecode Compiler'>
<!--[if IE]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js" type="text/javascript"></script><![endif]-->
<script src="/javascripts/jquery-1.3.2.js"></script>
<script src="/javascripts/paging_keys.js"></script>
<script src="/javascripts/application.js"></script>
<style>article, aside, dialog, figure, footer, header, hgroup, menu, nav, section { display: block; }</style>
<link href="/stylesheets/blueprint/screen.css" media="screen" rel="stylesheet" />
<link href="/stylesheets/application.css" media="screen" rel="stylesheet" />
<link href="/stylesheets/blueprint/print.css" media="print" rel="stylesheet" />
<!--[if IE]><link href="/stylesheets/blueprint/ie.css" media="screen" rel="stylesheet" type="text/css" /><![endif]-->
<!--[if IE]><link href="/stylesheets/ie.css" media="screen" rel="stylesheet" type="text/css" /><![endif]-->
<link href="/stylesheets/pygments.css" media="screen" rel="stylesheet" />
<link href="/favicon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon" />
<link href="/images/apple-touch-icon.png" rel="apple-touch-icon" type="image/png" />
<link href="/images/apple-touch-icon.png" rel="apple-touch-icon" type="image/png" sizes="72x72" />
<link href="/images/apple-touch-icon.png" rel="apple-touch-icon" type="image/png" sizes="114x114" />
</head>
<body>
<div class='container'>
<div class='span-21 doc_menu'>
<header>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a id="blog" href="/blog">Blog</a></li>
<li><a id="documentation" href="/doc/en">Documentation</a></li>
<li><a href="/projects">Projects</a></li>
<li><a href="/roadmap">Roadmap</a></li>
<li><a href="/releases">Releases</a></li>
</ul>
</nav>
</header>
</div>
<div class='span-3 last'>
<div id='version'>
<a href="/releases/1.2.4">1.2.4</a>
</div>
</div>
</div>
<div class="container languages">
<nav>
<span class="label">Languages:</span>
<ul>
<li><a href="/doc/fr/virtual-machine/custom-dispatch-logic/"
>de</a></li>
<li><a href="/doc/fr/virtual-machine/custom-dispatch-logic/"
class="current"
>en</a></li>
<li><a href="/doc/fr/virtual-machine/custom-dispatch-logic/"
>es</a></li>
<li><a href="/doc/fr/virtual-machine/custom-dispatch-logic/"
>fr</a></li>
<li><a href="/doc/fr/virtual-machine/custom-dispatch-logic/"
>it</a></li>
<li><a href="/doc/fr/virtual-machine/custom-dispatch-logic/"
>ja</a></li>
<li><a href="/doc/fr/virtual-machine/custom-dispatch-logic/"
>pl</a></li>
<li><a href="/doc/fr/virtual-machine/custom-dispatch-logic/"
>pt-br</a></li>
<li><a href="/doc/fr/virtual-machine/custom-dispatch-logic/"
>ru</a></li>
</ul>
</nav>
</div>
<div class="container doc_page_nav">
<span class="label">Previous:</span>
<a href="/doc/en/virtual-machine/instructions">Instructions</a>
<span class="label">Up:</span>
<a href="/doc/en/">Table of Contents</a>
<span class="label">Next:</span>
<a href="/doc/en/bytecode-compiler">Bytecode Compiler</a>
</div>
<div class="container documentation">
<h2>Custom Dispatch Logic</h2>
<div class="review">
<p>This topic has missing or partial documentation. Please help us improve it.</p>
<p>
See <a href="/doc/en/how-to/write-documentation">How-To - Write Documentation</a>
</p>
</div>
</div>
<div class="container doc_page_nav">
<span class="label">Previous:</span>
<a href="/doc/en/virtual-machine/instructions">Instructions</a>
<span class="label">Up:</span>
<a href="/doc/en/">Table of Contents</a>
<span class="label">Next:</span>
<a href="/doc/en/bytecode-compiler">Bytecode Compiler</a>
</div>
<div class="container">
<div id="disqus_thread"></div>
<script type="text/javascript">
var disqus_shortname = 'rubinius';
var disqus_identifier = '/doc/fr/virtual-machine/custom-dispatch-logic/';
var disqus_url = 'http://rubini.us/doc/fr/virtual-machine/custom-dispatch-logic/';
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
</div>
<footer>
<div class='container'>
<nav>
<ul>
<li><a rel="external" href="http://twitter.com/rubinius">Follow Rubinius on Twitter</a></li>
<li><a rel="external" href="http://github.com/rubinius/rubinius">Fork Rubinius on github</a></li>
<li><a rel="external" href="http://engineyard.com">An Engine Yard project</a></li>
</ul>
</nav>
</div>
</footer>
<script>
var _gaq=[['_setAccount','UA-12328521-1'],['_trackPageview']];
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.async=1;
g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
s.parentNode.insertBefore(g,s)}(document,'script'));
</script>
</body>
</html>
| bsd-3-clause |
joergdietrich/astropy | cextern/erfa/h2fk5.c | 6147 | #include "erfa.h"
void eraH2fk5(double rh, double dh,
double drh, double ddh, double pxh, double rvh,
double *r5, double *d5,
double *dr5, double *dd5, double *px5, double *rv5)
/*
** - - - - - - - - -
** e r a H 2 f k 5
** - - - - - - - - -
**
** Transform Hipparcos star data into the FK5 (J2000.0) system.
**
** Given (all Hipparcos, epoch J2000.0):
** rh double RA (radians)
** dh double Dec (radians)
** drh double proper motion in RA (dRA/dt, rad/Jyear)
** ddh double proper motion in Dec (dDec/dt, rad/Jyear)
** pxh double parallax (arcsec)
** rvh double radial velocity (km/s, positive = receding)
**
** Returned (all FK5, equinox J2000.0, epoch J2000.0):
** r5 double RA (radians)
** d5 double Dec (radians)
** dr5 double proper motion in RA (dRA/dt, rad/Jyear)
** dd5 double proper motion in Dec (dDec/dt, rad/Jyear)
** px5 double parallax (arcsec)
** rv5 double radial velocity (km/s, positive = receding)
**
** Notes:
**
** 1) This function transforms Hipparcos star positions and proper
** motions into FK5 J2000.0.
**
** 2) The proper motions in RA are dRA/dt rather than
** cos(Dec)*dRA/dt, and are per year rather than per century.
**
** 3) The FK5 to Hipparcos transformation is modeled as a pure
** rotation and spin; zonal errors in the FK5 catalog are not
** taken into account.
**
** 4) See also eraFk52h, eraFk5hz, eraHfk5z.
**
** Called:
** eraStarpv star catalog data to space motion pv-vector
** eraFk5hip FK5 to Hipparcos rotation and spin
** eraRv2m r-vector to r-matrix
** eraRxp product of r-matrix and p-vector
** eraTrxp product of transpose of r-matrix and p-vector
** eraPxp vector product of two p-vectors
** eraPmp p-vector minus p-vector
** eraPvstar space motion pv-vector to star catalog data
**
** Reference:
**
** F.Mignard & M.Froeschle, Astron. Astrophys. 354, 732-739 (2000).
**
** Copyright (C) 2013-2016, NumFOCUS Foundation.
** Derived, with permission, from the SOFA library. See notes at end of file.
*/
{
int i;
double pvh[2][3], r5h[3][3], s5h[3], sh[3], wxp[3], vv[3], pv5[2][3];
/* Hipparcos barycentric position/velocity pv-vector (normalized). */
eraStarpv(rh, dh, drh, ddh, pxh, rvh, pvh);
/* FK5 to Hipparcos orientation matrix and spin vector. */
eraFk5hip(r5h, s5h);
/* Make spin units per day instead of per year. */
for ( i = 0; i < 3; s5h[i++] /= 365.25 );
/* Orient the spin into the Hipparcos system. */
eraRxp(r5h, s5h, sh);
/* De-orient the Hipparcos position into the FK5 system. */
eraTrxp(r5h, pvh[0], pv5[0]);
/* Apply spin to the position giving an extra space motion component. */
eraPxp(pvh[0], sh, wxp);
/* Subtract this component from the Hipparcos space motion. */
eraPmp(pvh[1], wxp, vv);
/* De-orient the Hipparcos space motion into the FK5 system. */
eraTrxp(r5h, vv, pv5[1]);
/* FK5 pv-vector to spherical. */
eraPvstar(pv5, r5, d5, dr5, dd5, px5, rv5);
return;
}
/*----------------------------------------------------------------------
**
**
** Copyright (C) 2013-2016, NumFOCUS Foundation.
** All rights reserved.
**
** This library is derived, with permission, from the International
** Astronomical Union's "Standards of Fundamental Astronomy" library,
** available from http://www.iausofa.org.
**
** The ERFA version is intended to retain identical functionality to
** the SOFA library, but made distinct through different function and
** file names, as set out in the SOFA license conditions. The SOFA
** original has a role as a reference standard for the IAU and IERS,
** and consequently redistribution is permitted only in its unaltered
** state. The ERFA version is not subject to this restriction and
** therefore can be included in distributions which do not support the
** concept of "read only" software.
**
** Although the intent is to replicate the SOFA API (other than
** replacement of prefix names) and results (with the exception of
** bugs; any that are discovered will be fixed), SOFA is not
** responsible for any errors found in this version of the library.
**
** If you wish to acknowledge the SOFA heritage, please acknowledge
** that you are using a library derived from SOFA, rather than SOFA
** itself.
**
**
** TERMS AND CONDITIONS
**
** 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 of the Standards Of Fundamental Astronomy Board,
** the International Astronomical Union 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 HOLDER 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.
**
*/
| bsd-3-clause |
nacl-webkit/chrome_deps | android_webview/browser/net/aw_url_request_job_factory.cc | 3024 | // 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 "android_webview/browser/net/aw_url_request_job_factory.h"
#include "net/base/net_errors.h"
#include "net/url_request/url_request_error_job.h"
#include "net/url_request/url_request_job_factory_impl.h"
#include "net/url_request/url_request_job_manager.h"
using net::NetworkDelegate;
using net::URLRequest;
using net::URLRequestJob;
namespace android_webview {
AwURLRequestJobFactory::AwURLRequestJobFactory()
: next_factory_(new net::URLRequestJobFactoryImpl()) {
}
AwURLRequestJobFactory::~AwURLRequestJobFactory() {
}
bool AwURLRequestJobFactory::IsHandledProtocol(
const std::string& scheme) const {
// This introduces a dependency on the URLRequestJobManager
// implementation. The assumption is that if true is returned from this
// method it is still valid to return NULL from the
// MaybeCreateJobWithProtocolHandler method and in that case the
// URLRequestJobManager will try and create the URLRequestJob by using the
// set of built in handlers.
return true;
}
bool AwURLRequestJobFactory::IsHandledURL(const GURL& url) const {
return true;
}
URLRequestJob* AwURLRequestJobFactory::MaybeCreateJobWithProtocolHandler(
const std::string& scheme,
URLRequest* request,
NetworkDelegate* network_delegate) const {
URLRequestJob* job = next_factory_->MaybeCreateJobWithProtocolHandler(
scheme, request, network_delegate);
if (job)
return job;
// If the URLRequestJobManager supports the scheme NULL should be returned
// from this method. In that case the built in handlers in
// URLRequestJobManager will then be used to create the job.
if (net::URLRequestJobManager::GetInstance()->SupportsScheme(scheme))
return NULL;
return new net::URLRequestErrorJob(
request, network_delegate, net::ERR_UNKNOWN_URL_SCHEME);
}
bool AwURLRequestJobFactory::SetProtocolHandler(
const std::string& scheme,
ProtocolHandler* protocol_handler) {
return next_factory_->SetProtocolHandler(scheme, protocol_handler);
}
void AwURLRequestJobFactory::AddInterceptor(Interceptor* interceptor) {
next_factory_->AddInterceptor(interceptor);
}
URLRequestJob* AwURLRequestJobFactory::MaybeCreateJobWithInterceptor(
URLRequest* request, NetworkDelegate* network_delegate) const {
return next_factory_->MaybeCreateJobWithInterceptor(
request, network_delegate);
}
URLRequestJob* AwURLRequestJobFactory::MaybeInterceptRedirect(
const GURL& location,
URLRequest* request,
NetworkDelegate* network_delegate) const {
return next_factory_->MaybeInterceptRedirect(
location, request, network_delegate);
}
URLRequestJob* AwURLRequestJobFactory::MaybeInterceptResponse(
URLRequest* request,
NetworkDelegate* network_delegate) const {
return next_factory_->MaybeInterceptResponse(request, network_delegate);
}
} // namespace android_webview
| bsd-3-clause |
dlodato/AliPhysics | PWGLF/STRANGENESS/Cascades/AliAnalysisTaskCheckCascadepp.h | 19650 | #ifndef ALIANALYSISTASKCHECKCASCADEPP_H
#define ALIANALYSISTASKCHECKCASCADEPP_H
/* See cxx source for full Copyright notice */
//-----------------------------------------------------------------
// AliAnalysisTaskCheckCascadePbPb class
// Origin AliAnalysisTaskCheckCascade
// This task has four roles :
// 1. QAing the Cascades from ESD and AOD
// Origin: AliAnalysisTaskESDCheckV0 by Boris Hippolyte Nov2007, hippolyt@in2p3.fr
// 2. Prepare the plots which stand as raw material for yield extraction (wi/wo PID)
// 3. Supply an AliCFContainer meant to define the optimised topological selections
// Adapted to Cascade : A.Maire Mar2008, antonin.maire@ires.in2p3.fr
// Modified : A.Maire Mar2010, antonin.maire@ires.in2p3.fr
// Modified for PbPb analysis: M. Nicassio Feb 2011, maria.nicassio@ba.infn.it
// Modified for pp@2.76 analysis: D. Colella Feb2012, domenico.colella@ba.infn.it
//-----------------------------------------------------------------
class TList;
class TH1F;
class TH2F;
class TH3F;
class TVector3;
class THnSparse;
class AliESDEvent;
class AliPhysicsSelection;
class AliCFContainer;
class AliPIDResponse;
class AliAnalysisUtils;
#include "TString.h"
#include "AliAnalysisTaskSE.h"
class AliAnalysisTaskCheckCascadepp : public AliAnalysisTaskSE {
public:
AliAnalysisTaskCheckCascadepp();
AliAnalysisTaskCheckCascadepp(const char *name);
virtual ~AliAnalysisTaskCheckCascadepp();
virtual void UserCreateOutputObjects();
virtual void UserExec(Option_t *option);
virtual Int_t DoESDTrackWithTPCrefitMultiplicity(const AliESDEvent *lESDevent);
virtual void Terminate(Option_t *);
//Setters
void SetAnalysisType (const char* analysisType ) { fAnalysisType = analysisType; }
void SetCollidingSystem (Int_t collidingSystem ) { fCollidingSystem = collidingSystem; }
void SetSelectedTriggerClass (AliVEvent::EOfflineTriggerTypes trigType ) { fkTriggerClass = trigType; }
void SetEventSelSDDstatus (Bool_t eventselSDDstatus ) { fApplyEvSelSDDstatus = eventselSDDstatus; }
void SetEventSelDAQIncomplete (Bool_t eventselDAQincomplete ) { fApplyEvSelDAQincomplete = eventselDAQincomplete; }
void SetEventSelSPDclustervstracklet (Bool_t eventselSPDclustervstracklet ) { fApplyEvSelSPDclustervstracklet = eventselSPDclustervstracklet; }
void SetEventSelPileup (Bool_t eventselPileup ) { fApplyEvSelPileup = eventselPileup; }
void SetEventSelPhysicsSel (Bool_t eventselPhysicsSel ) { fApplyEvSelPhysicsSel = eventselPhysicsSel; }
void SetEventSelNoTPConlyPrimVtx (Bool_t eventselNoTPConlyPrimVtx ) { fApplyEvSelNoTPConlyPrimVtx = eventselNoTPConlyPrimVtx; }
void SetEventSelSPDvtxres (Bool_t eventselSPDvtxres ) { fApplyEvSelSPDvtxres = eventselSPDvtxres; }
void SetEventSelVtxProximity (Bool_t eventselVtxProximity ) { fApplyEvSelVtxProximity = eventselVtxProximity; }
void SetEventSelZprimVtxPos (Bool_t eventselZprimVtxPos ) { fApplyEvSelZprimVtxPos = eventselZprimVtxPos; }
void SetRelaunchV0CascVertexers (Bool_t rerunV0CascVertexers ) { fRerunV0CascVertexers = rerunV0CascVertexers; }
void SetWithSDDOn (Bool_t withsddOn ) { fwithSDD = withsddOn; }
void SetExtraSelections (Bool_t extraSelections ) { fExtraSelections = extraSelections; }
void SetTrackQualityCutTPCrefit (Bool_t trackqualityCutTPCrefit ) { fTrackQualityCutTPCrefit = trackqualityCutTPCrefit; }
void SetTrackQualityCutnTPCcls (Bool_t trackqualityCutnTPCcls ) { fTrackQualityCutnTPCcls = trackqualityCutnTPCcls; }
void SetQualityCutMinnTPCcls (Int_t minnTPCcls ) { fMinnTPCcls = minnTPCcls; }
void SetQualityCutClusterOverFindable (Float_t minTPCcrossrawoverfindable ) { fMinTPCcrossrawoverfindable = minTPCcrossrawoverfindable; }
void SetVertexRange (Float_t vtxrangemin, Float_t vtxrangemax ) { fVtxRangeMax = vtxrangemax;
fVtxRangeMin = vtxrangemin; }
void SetMinptCutOnDaughterTracks (Float_t minptdaughtrks ) { fMinPtCutOnDaughterTracks = minptdaughtrks; }
void SetEtaCutOnDaughterTracks (Float_t etadaughtrks ) { fEtaCutOnDaughterTracks = etadaughtrks; }
void SetSPDPileUpminContributors (Int_t spdpileupmincontributors ) { fSPDPileUpminContributors = spdpileupmincontributors; }
void SetNumTPCPIDsigma (Double_t ftpcpidsigma ) { fTPCPIDsigma = ftpcpidsigma; }
void SetSuffix (const char* suffix ) { fSuffix = suffix; }
//Setters for the V0 and cascade Vertexer Parameters
void SetV0VertexerMaxChisquare (Double_t lParameter){ fV0Sels[0] = lParameter; }
void SetV0VertexerDCAFirstToPV (Double_t lParameter){ fV0Sels[1] = lParameter; }
void SetV0VertexerDCASecondtoPV (Double_t lParameter){ fV0Sels[2] = lParameter; }
void SetV0VertexerDCAV0Daughters (Double_t lParameter){ fV0Sels[3] = lParameter; }
void SetV0VertexerCosinePA (Double_t lParameter){ fV0Sels[4] = lParameter; }
void SetV0VertexerMinRadius (Double_t lParameter){ fV0Sels[5] = lParameter; }
void SetV0VertexerMaxRadius (Double_t lParameter){ fV0Sels[6] = lParameter; }
void SetCascVertexerMaxChisquare (Double_t lParameter){ fCascSels[0] = lParameter; }
void SetCascVertexerMinV0ImpactParameter (Double_t lParameter){ fCascSels[1] = lParameter; }
void SetCascVertexerV0MassWindow (Double_t lParameter){ fCascSels[2] = lParameter; }
void SetCascVertexerDCABachToPV (Double_t lParameter){ fCascSels[3] = lParameter; }
void SetCascVertexerDCACascadeDaughters (Double_t lParameter){ fCascSels[4] = lParameter; }
void SetCascVertexerCascadeCosinePA (Double_t lParameter){ fCascSels[5] = lParameter; }
void SetCascVertexerCascadeMinRadius (Double_t lParameter){ fCascSels[6] = lParameter; }
void SetCascVertexerCascadeMaxRadius (Double_t lParameter){ fCascSels[7] = lParameter; }
private:
// Note : In ROOT, "//!" means "do not stream the data from Master node to Worker node" ...
// your data member object is created on the worker nodes and streaming is not needed.
// http://root.cern.ch/download/doc/11InputOutput.pdf, page 14
TString fAnalysisType; // "ESD" or "AOD" analysis type
AliESDtrackCuts *fESDtrackCuts; // ESD track cuts used for primary track definition
AliAnalysisUtils *fUtils; // analysis utils (for pA vertex selection)
Int_t fCollidingSystem; // "pPb" or "pp" colliding system
AliVEvent::EOfflineTriggerTypes fkTriggerClass; // Trigger selection: kMB, kINT7, etc as needed
AliPIDResponse *fPIDResponse; //! PID response object
Bool_t fApplyEvSelSDDstatus;
Bool_t fApplyEvSelDAQincomplete; //
Bool_t fApplyEvSelSPDclustervstracklet; //
Bool_t fApplyEvSelPileup; //
Bool_t fApplyEvSelPhysicsSel; //
Bool_t fApplyEvSelNoTPConlyPrimVtx; //
Bool_t fApplyEvSelSPDvtxres; //
Bool_t fApplyEvSelVtxProximity; //
Bool_t fApplyEvSelZprimVtxPos; //
Bool_t fRerunV0CascVertexers; // Boolean : kTRUE = relaunch both V0 + Cascade vertexers
Bool_t fwithSDD; // Boolean : kTRUE = select events with SDD reco
Bool_t fExtraSelections; // Boolean : kTRUE = apply tighter selections, before starting the analysis
Bool_t fTrackQualityCutTPCrefit; //
Bool_t fTrackQualityCutnTPCcls; //
Int_t fMinnTPCcls; // Minimum number of TPC cluster for daughter tracks
Float_t fMinTPCcrossrawoverfindable; // Minimum value for clusters/findable ratio
Float_t fVtxRangeMax; // to select events with |zvtx|<fVtxRange cm
Float_t fVtxRangeMin; // to select events with |zvtx|>fVtxRangeMin cm
Float_t fMinPtCutOnDaughterTracks; // minimum pt cut on daughter tracks
Float_t fEtaCutOnDaughterTracks; // pseudorapidity cut on daughter tracks
Int_t fSPDPileUpminContributors; //
Double_t fTPCPIDsigma; //
TString fSuffix;
Double_t fV0Sels[7]; // Array to store the 7 values for the different selections V0 related (if fkRerunV0CascVertexers)
Double_t fCascSels[8]; // Array to store the 8 values for the different selections Casc. related (if fkRerunV0CascVertexers)
TList *fListHistCascade; //! List of Cascade histograms
// Cascades multiplicity plots
TH1F *fHistCascadeMultiplicityBeforeAnySel;
TH1F *fHistCascadeMultiplicityAfterSDDstatusSel;
TH1F *fHistCascadeMultiplicityAfterDAQincompleteEvRej;
TH1F *fHistCascadeMultiplicityAfterSPDclustervstrackletSel;
TH1F *fHistCascadeMultiplicityAfterPileupRej;
TH1F *fHistCascadeMultiplicityAfterPhysicsSel;
TH1F *fHistCascadeMultiplicityAfterRevertexing;
TH1F *fHistCascadeMultiplicityAfterNoTPConlyPrimVtxSel;
TH1F *fHistCascadeMultiplicityAfterSPDresolution;
TH1F *fHistCascadeMultiplicityAfterVerticesProximity;
TH1F *fHistCascadeMultiplicityAfterZprimVtxPosSel;
// Vertex position plots (BestVertex)
TH1F *fHistPVx; //! Best primary vertex X position distribution after all evnt selection
TH1F *fHistPVy; //! Best primary vertex Y position distribution after all evnt selection
TH1F *fHistPVz; //! Best primary vertex Z position distribution after all evnt selection
TH1F *fHistPVxAnalysis; //! Best primary vertex X position distribution after all evnt selection and |z|>10cm cut
TH1F *fHistPVyAnalysis; //! Best primary vertex Y position distribution after all evnt selection and |z|>10cm cut
TH1F *fHistPVzAnalysis; //! Best primary vertex Z position distribution after all evnt selection and |z|>10cm cut
// TPC cluster distributions for daughters
TH1F *fHistPosV0TPCClusters; //! TPC clusters distribution for Positive V0 daughter track
TH1F *fHistNegV0TPCClusters; //! TPC clusters distribution for Negative V0 daughter track
TH1F *fHistBachTPCClusters; //! TPC clusters distribution for Bachelor V0 daughter track
// Cut's variables distributions
TH1F *fHistEffMassXi; //! reconstructed cascade effective mass
TH1F *fHistDcaXiDaughters; //! dca between Xi's daughters
TH1F *fHistDcaBachToPrimVertex; //! dca of the bachelor track to primary vertex
TH1F *fHistXiCosineOfPointingAngle; //! cosine of Xi pointing angle in a cascade
TH1F *fHistXiRadius; //! (transverse) radius of the cascade vertex
TH1F *fHistMassLambdaAsCascDghter; //! Test Invariant Mass of Lambda coming from Cascade
TH1F *fHistDcaV0DaughtersXi; //! Dca between V0 daughters, for the V0 associated to a cascade
TH1F *fHistDcaV0ToPrimVertexXi; //! Dca of V0 to primary vertex, for the V0 associated to a cascade
TH1F *fHistV0CosineOfPointingAngleXi; //! Cosine of V0 pointing angle, for the V0 associated to a cascade
TH1F *fHistV0RadiusXi; //! V0 (transverse) distance distribution, for the V0 associated to a cascade
TH1F *fHistDcaPosToPrimVertexXi; //! Dca of V0 positive daughter to primary vertex, for the V0 associated to a cascade
TH1F *fHistDcaNegToPrimVertexXi; //! Dca of V0 negative daughter to primary vertex, for the V0 associated to a cascade
// Invariant mass distributions
TH1F *fHistMassXiMinus; //! reconstructed cascade effective mass, under Xi- hyp.
TH1F *fHistMassXiPlus; //! reconstructed cascade effective mass, under Xi+ hyp.
TH1F *fHistMassOmegaMinus; //! reconstructed cascade effective mass, under Omega- hyp.
TH1F *fHistMassOmegaPlus; //! reconstructed cascade effective mass, under Omega+ hyp.
// Transverse and total momentum distributions
TH1F *fHistXiTransvMom; //! Xi transverse momentum, around the mass peak of Xi-/+
TH1F *fHistXiTotMom; //! Xi momentum norm, around the mass peak of Xi-/+
TH1F *fHistBachTransvMomXi; //! bachelor transverse momentum, for cand. around the mass peak of Xi-/+
TH1F *fHistBachTotMomXi; //! bachelor momentum norm, for cand. around the mass peak of Xi-/+
// Others QA plots
TH1F *fHistChargeXi; //! Charge sign of the cascade candidate
TH1F *fHistV0toXiCosineOfPointingAngle; //! Cos. of Pointing angle between the V0 mom and the Xi-V0 vtx line
TH1F *fHistRapXi; //! rapidity of Xi candidates, around the mass peak of Xi-/+
TH1F *fHistRapOmega; //! rapidity of Omega candidates, around the mass peak of Omega-/+
TH1F *fHistEtaXi; //! eta distrib. of all the cascade candidates, around the mass peak of Xi-/+
TH1F *fHistEtaBachXi;
TH1F *fHistEtaPosXi;
TH1F *fHistEtaNegXi;
TH1F *fHistThetaXi; //! theta distrib. of all the cascade candidates, around the mass peak of Xi-/+
TH1F *fHistPhiXi; //! phi distrib. of all the cascade candidates, around the mass peak of Xi-/+
TH2F *f2dHistArmenteros; //! alpha(casc. cand.) Vs PtArm(casc. cand.)
TH2F *f2dHistEffMassLambdaVsEffMassXiMinus; //! Xi- Eff mass Vs V0 Eff mass, under Xi- hyp.
TH2F *f2dHistEffMassXiVsEffMassOmegaMinus; //! Xi- Eff mass Vs Omega- Eff mass, for negative cascades
TH2F *f2dHistEffMassLambdaVsEffMassXiPlus; //! Xi+ Eff mass Vs V0 Eff mass, under Xi+ hyp.
TH2F *f2dHistEffMassXiVsEffMassOmegaPlus; //! Xi+ Eff mass Vs Omega+ Eff mass, for positive cascades
TH2F *f2dHistXiRadiusVsEffMassXiMinus; //! transv. casc. decay radius Vs Xi- Eff mass, under Xi- hyp.
TH2F *f2dHistXiRadiusVsEffMassXiPlus; //! transv. casc. decay radius Vs Xi+ Eff mass, under Xi+ hyp.
TH2F *f2dHistXiRadiusVsEffMassOmegaMinus; //! transv. casc. decay radius Vs Omega- Eff mass, under Omega- hyp.
TH2F *f2dHistXiRadiusVsEffMassOmegaPlus; //! transv. casc. decay radius Vs Omega+ Eff mass, under Omega+ hyp.
TH2F *f2dHistTPCdEdxOfCascDghters; //! TPC Bethe-Bloch curve, populated with the cascade daughters
TH2F *f2dHistDcaXiDaughtersvsInvMass; //! cut variables vs inv. mass
TH2F *f2dHistDcaBachToPrimVertexvsInvMass; //! cut variables vs inv. mass
TH2F *f2dHistXiCosineOfPointingAnglevsInvMass; //! cut variables vs inv. mass
TH2F *f2dHistMassLambdaAsCascDghtervsInvMass; //! cut variables vs inv. mass
TH2F *f2dHistDcaV0DaughtersXivsInvMass; //! cut variables vs inv. mass
TH2F *f2dHistDcaV0ToPrimVertexXivsInvMass; //! cut variables vs inv. mass
// Containers for cuts study
AliCFContainer *fCFContCascadePIDXiMinus; //! for Xi- : Container to store any 3D histos with the different PID flavours
AliCFContainer *fCFContCascadePIDXiPlus; //! for Xi+ : Container to store any 3D histos with the different PID flavours
AliCFContainer *fCFContCascadePIDOmegaMinus; //! for Omega-: Container to store any 3D histos with the different PID flavours
AliCFContainer *fCFContCascadePIDOmegaPlus; //! for Omega+: Container to store any 3D histos with the different PID flavours
AliCFContainer *fCFContCascadeCuts; //! Container meant to store all the relevant distributions corresponding to the cut variables
AliAnalysisTaskCheckCascadepp(const AliAnalysisTaskCheckCascadepp&); // not implemented
AliAnalysisTaskCheckCascadepp& operator=(const AliAnalysisTaskCheckCascadepp&); // not implemented
ClassDef(AliAnalysisTaskCheckCascadepp, 11);
};
#endif
| bsd-3-clause |
mxOBS/deb-pkg_trusty_chromium-browser | third_party/webrtc/modules/rtp_rtcp/interface/fec_receiver.h | 1162 | /*
* Copyright (c) 2013 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.
*/
#ifndef WEBRTC_MODULES_RTP_RTCP_INTERFACE_FEC_RECEIVER_H_
#define WEBRTC_MODULES_RTP_RTCP_INTERFACE_FEC_RECEIVER_H_
#include "webrtc/modules/rtp_rtcp/interface/rtp_rtcp_defines.h"
#include "webrtc/typedefs.h"
namespace webrtc {
class FecReceiver {
public:
static FecReceiver* Create(RtpData* callback);
virtual ~FecReceiver() {}
virtual int32_t AddReceivedRedPacket(const RTPHeader& rtp_header,
const uint8_t* incoming_rtp_packet,
size_t packet_length,
uint8_t ulpfec_payload_type) = 0;
virtual int32_t ProcessReceivedFec() = 0;
};
} // namespace webrtc
#endif // WEBRTC_MODULES_RTP_RTCP_INTERFACE_FEC_RECEIVER_H_
| bsd-3-clause |
operasoftware/presto-testo | wpt/FileAPI/non-automated/File-015-001.html | 1099 | <!DOCTYPE html>
<title>File-015-001-Enumerablity check: File.name</title>
<link rel="stylesheet" href="../resources/style.css"/>
<script src="../resources/lib.js"></script>
<script>
onload = function() {
try {
var t_file = document.getElementById('t_file');
t_file.onchange = function() {
try {
var t_blob = t_file.files[0];
var found = false;
for (var x in t_blob) {
if (x === "name") {
found = true;
break;
}
};
if (found) {
setResult(1, "File.name is enumerable.");
} else {
setResult(0, "File.name is not enumerable.");
}
} catch(e) {
setResult(0, "Threw exception: " + e);
}
}
} catch(e) {
setResult(0, "Threw: " + e);
}
}
</script>
<body>
<p>Please select "blob.txt" from resources folder to test: <input type='file' id='t_file' name='t_file' /></p>
</body> | bsd-3-clause |
whshev/pipes | src/main/java/com/tinkerpop/pipes/transform/BothEdgesPipe.java | 855 | package com.tinkerpop.pipes.transform;
import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.pipes.util.PipeHelper;
import java.util.Arrays;
/**
* BothEdgesPipe emits both the outgoing and incoming edges of a vertex.
*
* @author Marko A. Rodriguez (http://markorodriguez.com)
*/
public class BothEdgesPipe extends VerticesEdgesPipe {
public BothEdgesPipe(final String... labels) {
super(Direction.BOTH, labels);
}
public BothEdgesPipe(final int branchFactor, final String... labels) {
super(Direction.BOTH, branchFactor, labels);
}
public String toString() {
return (this.branchFactor == Integer.MAX_VALUE) ?
PipeHelper.makePipeString(this, Arrays.asList(this.labels)) :
PipeHelper.makePipeString(this, this.branchFactor, Arrays.asList(this.labels));
}
}
| bsd-3-clause |
jordan-brough/solidus_avatax | spec/support/sales_invoice_soap_responses.rb | 7800 | module SalesInvoiceSoapResponses
def sales_invoice_gettax_response(doc_code, line_item, shipment, time = Time.now)
{
transaction_id: "4314427373575624",
result_code: "Success",
doc_id: "56879220",
doc_type: "SalesInvoice",
doc_code: doc_code,
doc_date: time.to_date,
doc_status: "Saved",
reconciled: false,
timestamp: time,
total_amount: "110",
total_discount: "0",
total_exemption: "0",
total_taxable: "110",
total_tax: "9.77",
total_tax_calculated: "9.77",
hash_code: "0",
tax_lines: {
tax_line: [
{
no: SpreeAvatax::SalesShared.avatax_id(line_item),
tax_code: "P0000000",
taxability: true,
boundary_level: "Zip5",
exemption: "0",
discount: "0",
taxable: "10",
rate: "0.088750",
tax: "0.89",
tax_calculated: "0.89",
tax_included: false,
tax_details: {
tax_detail: [
{
country: "US",
region: "NY",
juris_type: "State",
juris_code: "36",
tax_type: "Sales",
base: "10",
taxable: "10",
rate: "0.040000",
tax: "0.4",
tax_calculated: "0.4",
non_taxable: "0",
exemption: "0",
juris_name: "NEW YORK",
tax_name: "NY STATE TAX",
tax_authority_type: "45",
tax_group: nil,
rate_type: "G",
state_assigned_no: nil
},
{
country: "US",
region: "NY",
juris_type: "City",
juris_code: "51000",
tax_type: "Sales",
base: "10",
taxable: "10",
rate: "0.045000",
tax: "0.45",
tax_calculated: "0.45",
non_taxable: "0",
exemption: "0",
juris_name: "NEW YORK CITY",
tax_name: "NY CITY TAX",
tax_authority_type: "45",
tax_group: nil,
rate_type: "G",
state_assigned_no: "NE 8081"
},
{
country: "US",
region: "NY",
juris_type: "Special",
juris_code: "359071",
tax_type: "Sales",
base: "10",
taxable: "10",
rate: "0.003750",
tax: "0.04",
tax_calculated: "0.04",
non_taxable: "0",
exemption: "0",
juris_name: "METROPOLITAN COMMUTER TRANSPORTATION DISTRICT",
tax_name: "NY SPECIAL TAX",
tax_authority_type: "45",
tax_group: nil,
rate_type: "G",
state_assigned_no: "NE 8061"
}
]
},
exempt_cert_id: "0",
tax_date: time.to_date,
reporting_date: time.to_date,
accounting_method: "Accrual"
},
{
no: SpreeAvatax::SalesShared.avatax_id(shipment),
tax_code: "FR020100",
taxability: true,
boundary_level: "Zip5",
exemption: "0",
discount: "0",
taxable: "100",
rate: "0.088750",
tax: "8.88",
tax_calculated: "8.88",
tax_included: false,
tax_details: {
tax_detail: [
{
country: "US",
region: "NY",
juris_type: "State",
juris_code: "36",
tax_type: "Sales",
base: "100",
taxable: "100",
rate: "0.040000",
tax: "4",
tax_calculated: "4",
non_taxable: "0",
exemption: "0",
juris_name: "NEW YORK",
tax_name: "NY STATE TAX",
tax_authority_type: "45",
tax_group: nil,
rate_type: "G",
state_assigned_no: nil
},
{
country: "US",
region: "NY",
juris_type: "City",
juris_code: "51000",
tax_type: "Sales",
base: "100",
taxable: "100",
rate: "0.045000",
tax: "4.5",
tax_calculated: "4.5",
non_taxable: "0",
exemption: "0",
juris_name: "NEW YORK CITY",
tax_name: "NY CITY TAX",
tax_authority_type: "45",
tax_group: nil,
rate_type: "G",
state_assigned_no: "NE 8081"
},
{
country: "US",
region: "NY",
juris_type: "Special",
juris_code: "359071",
tax_type: "Sales",
base: "100",
taxable: "100",
rate: "0.003750",
tax: "0.38",
tax_calculated: "0.38",
non_taxable: "0",
exemption: "0",
juris_name: "METROPOLITAN COMMUTER TRANSPORTATION DISTRICT",
tax_name: "NY SPECIAL TAX",
tax_authority_type: "45",
tax_group: nil,
rate_type: "G",
state_assigned_no: "NE 8061"
}
]
},
exempt_cert_id: "0",
tax_date: time.to_date,
reporting_date: time.to_date,
accounting_method: "Accrual"
}
]
},
tax_addresses: {
tax_address: {
address: "1234 Way",
address_code: "1",
boundary_level: "2",
city: "New York",
country: "US",
postal_code: "10010",
region: "NY",
tax_region_id: "2088629",
juris_code: "3600051000",
latitude: nil,
longitude: nil,
geocode_type: "ZIP5Centroid",
validate_status: "HouseNotOnStreet",
distance_to_boundary: "0"
}
},
locked: false,
adjustment_reason: "0",
adjustment_description: nil,
version: "1",
tax_date: time.to_date,
tax_summary: nil,
volatile_tax_rates: false,
messages: [
{
summary: nil,
details: nil,
helplink: nil,
refersto: nil,
severity: nil,
source: nil
}
]
}
end
def sales_invoice_posttax_response
{
transaction_id: "4314427475194657",
result_code: "Success",
doc_id: "56879220",
messages:[
{
summary: nil,
details: nil,
helplink: nil,
refersto: nil,
severity: nil,
source: nil,
},
],
}
end
def sales_invoice_canceltax_response
{
transaction_id: "4321919394664864",
result_code: "Success",
doc_id: "57305344",
messages: [
{
summary: nil,
details: nil,
helplink: nil,
refersto: nil,
severity: nil,
source: nil,
},
],
}
end
end
| bsd-3-clause |
jamiehodge/express-graphql | resources/interfaces/express.js | 333 | /* @flow */
/* Flow declarations for express requests and responses */
/* eslint-disable no-unused-vars */
declare class Request {
method: String;
body: Object;
query: Object;
}
declare class Response {
status: (code: Number) => Response;
set: (field: String, value: String) => Response;
send: (body: String) => void;
}
| bsd-3-clause |
frivoal/presto-testo | css/animations/automated/0_as_keyframe_selector.html | 3046 | <!DOCTYPE html>
<html>
<head>
<title>CSS Animations - 0 as keyframe selector</title>
<link rel="author" title="Opera Software ASA" href="http://www.opera.com/">
<link rel="help" href="http://dev.w3.org/csswg/css3-animations/#keyframes">
<meta name="flags" content="dom invalid">
<!--
**************************************************************************
ISSUE: Spec is not clear on parsing behavior
**************************************************************************
-->
<meta name="assert" content='"0" is an invalid keyframe selector'>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<style type="text/css">
@keyframes percent-sign {
0% {
left: 0px;
}
100% {
left: 200px;
}
}
@keyframes no-percent-sign {
0 {
top: 50px;
}
50% {
top: 0px;
}
100% {
top: 100px;
}
}
div {
width: 100px;
height: 100px;
background: blue;
position: relative;
top: 0px;
}
.test {
animation: percent-sign 1s forwards, no-percent-sign 1s forwards;
animation-timing-function: linear;
}
</style>
<script type="text/javascript">
setup({explicit_done:true});
onload = function() {
var testName = document.querySelector('title').firstChild.data;
var div = document.querySelector('div');
var divStyle = getComputedStyle(div, null);
var log = document.querySelectorAll('p')[1].firstChild;
var topStartOK, leftEndOK, topEndOK;
var passed = false;
function report() {
clearTimeout(timeout);
test(function(){assert_true(passed);}, testName);
done();
log.data = passed ? 'PASS if the animation occurred.' : 'FAIL';
}
div.addEventListener('animationstart', function(evt) {
if (evt.animationName == 'no-percent-sign') {
topStartOK = (divStyle.top == '0px');
}
});
div.addEventListener('animationend', function(evt) {
if (evt.animationName == 'percent-sign') {
leftEndOK = (divStyle.left == '200px');
} else if (evt.animationName == 'no-percent-sign') {
topEndOK = (divStyle.top == '100px');
}
if (leftEndOK !== undefined && topEndOK !== undefined) {
passed = (topStartOK && leftEndOK && topEndOK);
report();
}
});
var timeout = setTimeout(report, 1500);
div.className = 'test';
}
</script>
<script src="../resources/add_prefixes.js"></script>
<style>iframe{display:none}</style>
</head>
<body>
<p>The square below should slide straight rightwards at first, then
diagonally down+right.</p>
<p>Testing...</p>
<div></div>
</body>
</html>
| bsd-3-clause |
wkschwartz/django | django/contrib/sessions/backends/base.py | 13900 | import base64
import logging
import string
import warnings
from datetime import datetime, timedelta
from django.conf import settings
from django.contrib.sessions.exceptions import SuspiciousSession
from django.core import signing
from django.core.exceptions import SuspiciousOperation
from django.utils import timezone
from django.utils.crypto import (
constant_time_compare, get_random_string, salted_hmac,
)
from django.utils.deprecation import RemovedInDjango40Warning
from django.utils.module_loading import import_string
from django.utils.translation import LANGUAGE_SESSION_KEY
# session_key should not be case sensitive because some backends can store it
# on case insensitive file systems.
VALID_KEY_CHARS = string.ascii_lowercase + string.digits
class CreateError(Exception):
"""
Used internally as a consistent exception type to catch from save (see the
docstring for SessionBase.save() for details).
"""
pass
class UpdateError(Exception):
"""
Occurs if Django tries to update a session that was deleted.
"""
pass
class SessionBase:
"""
Base class for all Session classes.
"""
TEST_COOKIE_NAME = 'testcookie'
TEST_COOKIE_VALUE = 'worked'
__not_given = object()
def __init__(self, session_key=None):
self._session_key = session_key
self.accessed = False
self.modified = False
self.serializer = import_string(settings.SESSION_SERIALIZER)
def __contains__(self, key):
return key in self._session
def __getitem__(self, key):
if key == LANGUAGE_SESSION_KEY:
warnings.warn(
'The user language will no longer be stored in '
'request.session in Django 4.0. Read it from '
'request.COOKIES[settings.LANGUAGE_COOKIE_NAME] instead.',
RemovedInDjango40Warning, stacklevel=2,
)
return self._session[key]
def __setitem__(self, key, value):
self._session[key] = value
self.modified = True
def __delitem__(self, key):
del self._session[key]
self.modified = True
@property
def key_salt(self):
return 'django.contrib.sessions.' + self.__class__.__qualname__
def get(self, key, default=None):
return self._session.get(key, default)
def pop(self, key, default=__not_given):
self.modified = self.modified or key in self._session
args = () if default is self.__not_given else (default,)
return self._session.pop(key, *args)
def setdefault(self, key, value):
if key in self._session:
return self._session[key]
else:
self.modified = True
self._session[key] = value
return value
def set_test_cookie(self):
self[self.TEST_COOKIE_NAME] = self.TEST_COOKIE_VALUE
def test_cookie_worked(self):
return self.get(self.TEST_COOKIE_NAME) == self.TEST_COOKIE_VALUE
def delete_test_cookie(self):
del self[self.TEST_COOKIE_NAME]
def _hash(self, value):
# RemovedInDjango40Warning: pre-Django 3.1 format will be invalid.
key_salt = "django.contrib.sessions" + self.__class__.__name__
return salted_hmac(key_salt, value).hexdigest()
def encode(self, session_dict):
"Return the given session dictionary serialized and encoded as a string."
# RemovedInDjango40Warning: DEFAULT_HASHING_ALGORITHM will be removed.
if settings.DEFAULT_HASHING_ALGORITHM == 'sha1':
return self._legacy_encode(session_dict)
return signing.dumps(
session_dict, salt=self.key_salt, serializer=self.serializer,
compress=True,
)
def decode(self, session_data):
try:
return signing.loads(session_data, salt=self.key_salt, serializer=self.serializer)
# RemovedInDjango40Warning: when the deprecation ends, handle here
# exceptions similar to what _legacy_decode() does now.
except signing.BadSignature:
try:
# Return an empty session if data is not in the pre-Django 3.1
# format.
return self._legacy_decode(session_data)
except Exception:
logger = logging.getLogger('django.security.SuspiciousSession')
logger.warning('Session data corrupted')
return {}
except Exception:
return self._legacy_decode(session_data)
def _legacy_encode(self, session_dict):
# RemovedInDjango40Warning.
serialized = self.serializer().dumps(session_dict)
hash = self._hash(serialized)
return base64.b64encode(hash.encode() + b':' + serialized).decode('ascii')
def _legacy_decode(self, session_data):
# RemovedInDjango40Warning: pre-Django 3.1 format will be invalid.
encoded_data = base64.b64decode(session_data.encode('ascii'))
try:
# could produce ValueError if there is no ':'
hash, serialized = encoded_data.split(b':', 1)
expected_hash = self._hash(serialized)
if not constant_time_compare(hash.decode(), expected_hash):
raise SuspiciousSession("Session data corrupted")
else:
return self.serializer().loads(serialized)
except Exception as e:
# ValueError, SuspiciousOperation, unpickling exceptions. If any of
# these happen, just return an empty dictionary (an empty session).
if isinstance(e, SuspiciousOperation):
logger = logging.getLogger('django.security.%s' % e.__class__.__name__)
logger.warning(str(e))
return {}
def update(self, dict_):
self._session.update(dict_)
self.modified = True
def has_key(self, key):
return key in self._session
def keys(self):
return self._session.keys()
def values(self):
return self._session.values()
def items(self):
return self._session.items()
def clear(self):
# To avoid unnecessary persistent storage accesses, we set up the
# internals directly (loading data wastes time, since we are going to
# set it to an empty dict anyway).
self._session_cache = {}
self.accessed = True
self.modified = True
def is_empty(self):
"Return True when there is no session_key and the session is empty."
try:
return not self._session_key and not self._session_cache
except AttributeError:
return True
def _get_new_session_key(self):
"Return session key that isn't being used."
while True:
session_key = get_random_string(32, VALID_KEY_CHARS)
if not self.exists(session_key):
return session_key
def _get_or_create_session_key(self):
if self._session_key is None:
self._session_key = self._get_new_session_key()
return self._session_key
def _validate_session_key(self, key):
"""
Key must be truthy and at least 8 characters long. 8 characters is an
arbitrary lower bound for some minimal key security.
"""
return key and len(key) >= 8
def _get_session_key(self):
return self.__session_key
def _set_session_key(self, value):
"""
Validate session key on assignment. Invalid values will set to None.
"""
if self._validate_session_key(value):
self.__session_key = value
else:
self.__session_key = None
session_key = property(_get_session_key)
_session_key = property(_get_session_key, _set_session_key)
def _get_session(self, no_load=False):
"""
Lazily load session from storage (unless "no_load" is True, when only
an empty dict is stored) and store it in the current instance.
"""
self.accessed = True
try:
return self._session_cache
except AttributeError:
if self.session_key is None or no_load:
self._session_cache = {}
else:
self._session_cache = self.load()
return self._session_cache
_session = property(_get_session)
def get_session_cookie_age(self):
return settings.SESSION_COOKIE_AGE
def get_expiry_age(self, **kwargs):
"""Get the number of seconds until the session expires.
Optionally, this function accepts `modification` and `expiry` keyword
arguments specifying the modification and expiry of the session.
"""
try:
modification = kwargs['modification']
except KeyError:
modification = timezone.now()
# Make the difference between "expiry=None passed in kwargs" and
# "expiry not passed in kwargs", in order to guarantee not to trigger
# self.load() when expiry is provided.
try:
expiry = kwargs['expiry']
except KeyError:
expiry = self.get('_session_expiry')
if not expiry: # Checks both None and 0 cases
return self.get_session_cookie_age()
if not isinstance(expiry, datetime):
return expiry
delta = expiry - modification
return delta.days * 86400 + delta.seconds
def get_expiry_date(self, **kwargs):
"""Get session the expiry date (as a datetime object).
Optionally, this function accepts `modification` and `expiry` keyword
arguments specifying the modification and expiry of the session.
"""
try:
modification = kwargs['modification']
except KeyError:
modification = timezone.now()
# Same comment as in get_expiry_age
try:
expiry = kwargs['expiry']
except KeyError:
expiry = self.get('_session_expiry')
if isinstance(expiry, datetime):
return expiry
expiry = expiry or self.get_session_cookie_age()
return modification + timedelta(seconds=expiry)
def set_expiry(self, value):
"""
Set a custom expiration for the session. ``value`` can be an integer,
a Python ``datetime`` or ``timedelta`` object or ``None``.
If ``value`` is an integer, the session will expire after that many
seconds of inactivity. If set to ``0`` then the session will expire on
browser close.
If ``value`` is a ``datetime`` or ``timedelta`` object, the session
will expire at that specific future time.
If ``value`` is ``None``, the session uses the global session expiry
policy.
"""
if value is None:
# Remove any custom expiration for this session.
try:
del self['_session_expiry']
except KeyError:
pass
return
if isinstance(value, timedelta):
value = timezone.now() + value
self['_session_expiry'] = value
def get_expire_at_browser_close(self):
"""
Return ``True`` if the session is set to expire when the browser
closes, and ``False`` if there's an expiry date. Use
``get_expiry_date()`` or ``get_expiry_age()`` to find the actual expiry
date/age, if there is one.
"""
if self.get('_session_expiry') is None:
return settings.SESSION_EXPIRE_AT_BROWSER_CLOSE
return self.get('_session_expiry') == 0
def flush(self):
"""
Remove the current session data from the database and regenerate the
key.
"""
self.clear()
self.delete()
self._session_key = None
def cycle_key(self):
"""
Create a new session key, while retaining the current session data.
"""
data = self._session
key = self.session_key
self.create()
self._session_cache = data
if key:
self.delete(key)
# Methods that child classes must implement.
def exists(self, session_key):
"""
Return True if the given session_key already exists.
"""
raise NotImplementedError('subclasses of SessionBase must provide an exists() method')
def create(self):
"""
Create a new session instance. Guaranteed to create a new object with
a unique key and will have saved the result once (with empty data)
before the method returns.
"""
raise NotImplementedError('subclasses of SessionBase must provide a create() method')
def save(self, must_create=False):
"""
Save the session data. If 'must_create' is True, create a new session
object (or raise CreateError). Otherwise, only update an existing
object and don't create one (raise UpdateError if needed).
"""
raise NotImplementedError('subclasses of SessionBase must provide a save() method')
def delete(self, session_key=None):
"""
Delete the session data under this key. If the key is None, use the
current session key value.
"""
raise NotImplementedError('subclasses of SessionBase must provide a delete() method')
def load(self):
"""
Load the session data and return a dictionary.
"""
raise NotImplementedError('subclasses of SessionBase must provide a load() method')
@classmethod
def clear_expired(cls):
"""
Remove expired sessions from the session store.
If this operation isn't possible on a given backend, it should raise
NotImplementedError. If it isn't necessary, because the backend has
a built-in expiration mechanism, it should be a no-op.
"""
raise NotImplementedError('This backend does not support clear_expired().')
| bsd-3-clause |
douban/code | vilya/libs/permdir.py | 407 | # -*- coding: utf-8 -*-
import os
CODE_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
def get_permdir():
return os.path.join(CODE_DIR, 'permdir')
def get_repo_root():
return get_permdir()
def get_tmpdir():
return os.path.join(CODE_DIR, 'tmpdir')
def init_permdir():
path = get_permdir()
if not os.path.exists(path):
os.makedirs(path)
init_permdir()
| bsd-3-clause |
otavioarc/freeCodeCamp | guide/spanish/certifications/coding-interview-prep/project-euler/problem-142-perfect-square-collection/index.md | 509 | ---
title: Perfect Square Collection
localeTitle: Perfecta colección cuadrada
---
## Problema 142: Perfect Square Collection
Esto es un talón. [Ayuda a nuestra comunidad a expandirla](https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/project-euler/problem-142-perfect-square-collection/index.md) .
[Esta guía rápida de estilo ayudará a asegurar que su solicitud de extracción sea aceptada](https://github.com/freecodecamp/guides/blob/master/README.md) . | bsd-3-clause |
smartdevicelink/sdl_ios | SmartDeviceLink/public/SDLOnTBTClientState.h | 386 | // SDLOnTBTClientState.h
//
#import "SDLRPCNotification.h"
#import "SDLTBTState.h"
NS_ASSUME_NONNULL_BEGIN
/**
Provides applications with notifications specific to the current TBT client status on the module
*/
@interface SDLOnTBTClientState : SDLRPCNotification
/**
Current State of TBT client
*/
@property (strong, nonatomic) SDLTBTState state;
@end
NS_ASSUME_NONNULL_END
| bsd-3-clause |
cjltsod/python-social-auth | social/backends/upwork.py | 52 | from social_core.backends.upwork import UpworkOAuth
| bsd-3-clause |
ds-hwang/chromium-crosswalk | components/web_resource/eula_accepted_notifier_unittest.cc | 2473 | // 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 "components/web_resource/eula_accepted_notifier.h"
#include "base/macros.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/testing_pref_service.h"
#include "components/web_resource/web_resource_pref_names.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace web_resource {
class EulaAcceptedNotifierTest : public testing::Test,
public EulaAcceptedNotifier::Observer {
public:
EulaAcceptedNotifierTest() : eula_accepted_called_(false) {
}
// testing::Test overrides.
void SetUp() override {
local_state_.registry()->RegisterBooleanPref(prefs::kEulaAccepted, false);
notifier_.reset(new EulaAcceptedNotifier(&local_state_));
notifier_->Init(this);
}
// EulaAcceptedNotifier::Observer overrides.
void OnEulaAccepted() override {
EXPECT_FALSE(eula_accepted_called_);
eula_accepted_called_ = true;
}
void SetEulaAcceptedPref() {
local_state_.SetBoolean(prefs::kEulaAccepted, true);
}
EulaAcceptedNotifier* notifier() {
return notifier_.get();
}
bool eula_accepted_called() {
return eula_accepted_called_;
}
private:
TestingPrefServiceSimple local_state_;
scoped_ptr<EulaAcceptedNotifier> notifier_;
bool eula_accepted_called_;
DISALLOW_COPY_AND_ASSIGN(EulaAcceptedNotifierTest);
};
TEST_F(EulaAcceptedNotifierTest, EulaAlreadyAccepted) {
SetEulaAcceptedPref();
EXPECT_TRUE(notifier()->IsEulaAccepted());
EXPECT_FALSE(eula_accepted_called());
// Call it a second time, to ensure the answer doesn't change.
EXPECT_TRUE(notifier()->IsEulaAccepted());
EXPECT_FALSE(eula_accepted_called());
}
TEST_F(EulaAcceptedNotifierTest, EulaNotAccepted) {
EXPECT_FALSE(notifier()->IsEulaAccepted());
EXPECT_FALSE(eula_accepted_called());
// Call it a second time, to ensure the answer doesn't change.
EXPECT_FALSE(notifier()->IsEulaAccepted());
EXPECT_FALSE(eula_accepted_called());
}
TEST_F(EulaAcceptedNotifierTest, EulaNotInitiallyAccepted) {
EXPECT_FALSE(notifier()->IsEulaAccepted());
SetEulaAcceptedPref();
EXPECT_TRUE(notifier()->IsEulaAccepted());
EXPECT_TRUE(eula_accepted_called());
// Call it a second time, to ensure the answer doesn't change.
EXPECT_TRUE(notifier()->IsEulaAccepted());
}
} // namespace web_resource
| bsd-3-clause |
doismellburning/django | django/shortcuts.py | 7865 | """
This module collects helper functions and classes that "span" multiple levels
of MVC. In other words, these functions/classes introduce controlled coupling
for convenience's sake.
"""
import warnings
from django.template import loader, RequestContext
from django.template.context import _current_app_undefined
from django.template.engine import (
_context_instance_undefined, _dictionary_undefined, _dirs_undefined)
from django.http import HttpResponse, Http404
from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect
from django.db.models.base import ModelBase
from django.db.models.manager import Manager
from django.db.models.query import QuerySet
from django.core import urlresolvers
from django.utils import six
from django.utils.deprecation import RemovedInDjango20Warning
from django.utils.encoding import force_text
from django.utils.functional import Promise
def render_to_response(template_name, context=None,
context_instance=_context_instance_undefined,
content_type=None, status=None, dirs=_dirs_undefined,
dictionary=_dictionary_undefined):
"""
Returns a HttpResponse whose content is filled with the result of calling
django.template.loader.render_to_string() with the passed arguments.
"""
if (context_instance is _context_instance_undefined
and dirs is _dirs_undefined
and dictionary is _dictionary_undefined):
# No deprecated arguments were passed - use the new code path
content = loader.render_to_string(template_name, context)
else:
# Some deprecated arguments were passed - use the legacy code path
content = loader.render_to_string(
template_name, context, context_instance, dirs, dictionary)
return HttpResponse(content, content_type, status)
def render(request, template_name, context=None,
context_instance=_context_instance_undefined,
content_type=None, status=None, current_app=_current_app_undefined,
dirs=_dirs_undefined, dictionary=_dictionary_undefined):
"""
Returns a HttpResponse whose content is filled with the result of calling
django.template.loader.render_to_string() with the passed arguments.
Uses a RequestContext by default.
"""
if (context_instance is _context_instance_undefined
and current_app is _current_app_undefined
and dirs is _dirs_undefined
and dictionary is _dictionary_undefined):
# No deprecated arguments were passed - use the new code path
# In Django 2.0, request should become a positional argument.
content = loader.render_to_string(template_name, context, request=request)
else:
# Some deprecated arguments were passed - use the legacy code path
if context_instance is not _context_instance_undefined:
if current_app is not _current_app_undefined:
raise ValueError('If you provide a context_instance you must '
'set its current_app before calling render()')
else:
context_instance = RequestContext(request)
if current_app is not _current_app_undefined:
warnings.warn(
"The current_app argument of render is deprecated. "
"Set the current_app attribute of request instead.",
RemovedInDjango20Warning, stacklevel=2)
request.current_app = current_app
# Directly set the private attribute to avoid triggering the
# warning in RequestContext.__init__.
context_instance._current_app = current_app
content = loader.render_to_string(
template_name, context, context_instance, dirs, dictionary)
return HttpResponse(content, content_type, status)
def redirect(to, *args, **kwargs):
"""
Returns an HttpResponseRedirect to the appropriate URL for the arguments
passed.
The arguments could be:
* A model: the model's `get_absolute_url()` function will be called.
* A view name, possibly with arguments: `urlresolvers.reverse()` will
be used to reverse-resolve the name.
* A URL, which will be used as-is for the redirect location.
By default issues a temporary redirect; pass permanent=True to issue a
permanent redirect
"""
if kwargs.pop('permanent', False):
redirect_class = HttpResponsePermanentRedirect
else:
redirect_class = HttpResponseRedirect
return redirect_class(resolve_url(to, *args, **kwargs))
def _get_queryset(klass):
"""
Returns a QuerySet from a Model, Manager, or QuerySet. Created to make
get_object_or_404 and get_list_or_404 more DRY.
Raises a ValueError if klass is not a Model, Manager, or QuerySet.
"""
if isinstance(klass, QuerySet):
return klass
elif isinstance(klass, Manager):
manager = klass
elif isinstance(klass, ModelBase):
manager = klass._default_manager
else:
if isinstance(klass, type):
klass__name = klass.__name__
else:
klass__name = klass.__class__.__name__
raise ValueError("Object is of type '%s', but must be a Django Model, "
"Manager, or QuerySet" % klass__name)
return manager.all()
def get_object_or_404(klass, *args, **kwargs):
"""
Uses get() to return an object, or raises a Http404 exception if the object
does not exist.
klass may be a Model, Manager, or QuerySet object. All other passed
arguments and keyword arguments are used in the get() query.
Note: Like with get(), an MultipleObjectsReturned will be raised if more than one
object is found.
"""
queryset = _get_queryset(klass)
try:
return queryset.get(*args, **kwargs)
except queryset.model.DoesNotExist:
raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
def get_list_or_404(klass, *args, **kwargs):
"""
Uses filter() to return a list of objects, or raise a Http404 exception if
the list is empty.
klass may be a Model, Manager, or QuerySet object. All other passed
arguments and keyword arguments are used in the filter() query.
"""
queryset = _get_queryset(klass)
obj_list = list(queryset.filter(*args, **kwargs))
if not obj_list:
raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
return obj_list
def resolve_url(to, *args, **kwargs):
"""
Return a URL appropriate for the arguments passed.
The arguments could be:
* A model: the model's `get_absolute_url()` function will be called.
* A view name, possibly with arguments: `urlresolvers.reverse()` will
be used to reverse-resolve the name.
* A URL, which will be returned as-is.
"""
# If it's a model, use get_absolute_url()
if hasattr(to, 'get_absolute_url'):
return to.get_absolute_url()
if isinstance(to, Promise):
# Expand the lazy instance, as it can cause issues when it is passed
# further to some Python functions like urlparse.
to = force_text(to)
if isinstance(to, six.string_types):
# Handle relative URLs
if any(to.startswith(path) for path in ('./', '../')):
return to
# Next try a reverse URL resolution.
try:
return urlresolvers.reverse(to, args=args, kwargs=kwargs)
except urlresolvers.NoReverseMatch:
# If this is a callable, re-raise.
if callable(to):
raise
# If this doesn't "feel" like a URL, re-raise.
if '/' not in to and '.' not in to:
raise
# Finally, fall back and assume it's a URL
return to
| bsd-3-clause |
leighpauls/k2cro4 | third_party/WebKit/Source/WebKit2/UIProcess/API/efl/ewk_text_checker.h | 6740 | /*
* Copyright (C) 2012 Samsung Electronics
*
* 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.
*
* 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 HOLDER 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 ewk_text_checker.h
* @brief Provides API to overwrite the default WebKit spellchecker implementation.
*
* There is one spellchecker object per application and it's disabled by default.
* It allows to check spelling in the editable areas.
* If application wants to enable the feature, API from ewk_settings.h
* should be used.
*
* The default WebKit spellchecker implementation is based on the Enchant library.
* It doesn't ensure grammar checking. Application is able to overwrite the default
* WebKit spellchecker implementation by defining its own implementation and setting
* appropriate callback functions.
*/
#ifndef ewk_text_checker_h
#define ewk_text_checker_h
#include <Evas.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Defines a type name for the callback function to return a tag (identifier) which is guaranteed to be unique.
*
* Unique tags help to avoid collisions with other objects that are checked for spelling mistakes.
*
* @param o the view object to get unique tag
*
* @return unique tag for the given @a o view object
*/
typedef uint64_t (*Ewk_Text_Checker_Unique_Spell_Document_Tag_Get_Cb)(const Evas_Object *o);
/**
* Defines a type name for the callback function to close the prviously set tag.
*
* This callback will notify the receiver that the user has finished with the tagged document.
*
* @param tag the tag to be closed
*/
typedef void (*Ewk_Text_Checker_Unique_Spell_Document_Tag_Close_Cb)(uint64_t tag);
/**
* Defines a type name for the callback function to search for a misspelled words in the given string.
*
* @param tag unique tag to notify the spell checker which document that @a text is associated,
* in most cases not necessarily, just for ignored word,
* @c 0 can be passed in for text not associated with a particular document
* @param text the text containing the words to spellcheck
* @param misspelling_location a pointer to store the beginning of the misspelled @a text, @c -1 if the @a text is correct
* @param misspelling_length a pointer to store the length of misspelled @a text, @c 0 if the @a text is correct
*/
typedef void (*Ewk_Text_Checker_String_Spelling_Check_Cb)(uint64_t tag, const char *text, int32_t *misspelling_location, int32_t *misspelling_length);
/**
* Defines a type name for the callback function to get a list of suggested spellings for a misspelled @a word.
*
* @param tag unique tag to notify the spell checker which document that @a text is associated,
* @c 0 can be passed for text not associated with a particular document
* @param word the word to get guesses
* @return a list of dynamically allocated strings (as char*) and
* caller is responsible for destroying them.
*/
typedef Eina_List *(*Ewk_Text_Checker_Word_Guesses_Get_Cb)(uint64_t tag, const char *word);
/**
* Sets a callback function to add the word to the spell checker dictionary.
*
* @param tag unique tag to notify the spell checker which document that @a text is associated,
* @c 0 can be passed for text not associated with a particular document
* @param word the word to add
*/
typedef void (*Ewk_Text_Checker_Word_Learn_Cb)(uint64_t tag, const char *word);
/**
* Sets a callback function to tell the spell checker to ignore a given word.
*
* @param tag unique tag to notify the spell checker which document that @a text is associated,
* @c 0 can be passed for text not associated with a particular document
* @param word the word to ignore
*/
typedef void (*Ewk_Text_Checker_Word_Ignore_Cb)(uint64_t tag, const char *word);
/**
* Sets a callback function to get a unique spell document tag.
*
* @param cb a new callback to set or @c NULL to restore the default WebKit callback implementation
*/
EAPI void ewk_text_checker_unique_spell_document_tag_get_cb_set(Ewk_Text_Checker_Unique_Spell_Document_Tag_Get_Cb cb);
/**
* Sets a callback function to close a unique spell document tag.
*
* @param cb a new callback to set or @c NULL to restore the default WebKit callback implementation
*/
EAPI void ewk_text_checker_unique_spell_document_tag_close_cb_set(Ewk_Text_Checker_Unique_Spell_Document_Tag_Close_Cb cb);
/**
* Sets a callback function to search for a misspelled words in the given string.
*
* @param cb a new callback to set or @c NULL to restore the default WebKit callback implementation
*/
EAPI void ewk_text_checker_string_spelling_check_cb_set(Ewk_Text_Checker_String_Spelling_Check_Cb cb);
/**
* Sets a callback function to get an array of suggested spellings for a misspelled word.
*
* @param cb a new callback to set or @c NULL to restore the default WebKit callback implementation
*/
EAPI void ewk_text_checker_word_guesses_get_cb_set(Ewk_Text_Checker_Word_Guesses_Get_Cb cb);
/**
* Sets a callback function to add the word to the spell checker dictionary.
*
* @param cb a new callback to set or @c NULL to restore the default WebKit callback implementation
*/
EAPI void ewk_text_checker_word_learn_cb_set(Ewk_Text_Checker_Word_Learn_Cb cb);
/**
* Sets a callback function to tell the spell checker to ignore a given word.
*
* @param cb a new callback to set or @c NULL to restore the default WebKit callback implementation
*/
EAPI void ewk_text_checker_word_ignore_cb_set(Ewk_Text_Checker_Word_Ignore_Cb cb);
#ifdef __cplusplus
}
#endif
#endif // ewk_text_checker_h
| bsd-3-clause |
mjtamlyn/django-denorm | test_project/settings_mysql.py | 221 | from settings import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'denorm',
'HOST': 'localhost',
'USER': 'denorm',
'PASSWORD': 'denorm1',
}
}
| bsd-3-clause |
modulexcite/catapult | perf_insights/perf_insights/results/results_test.html | 1729 | <!DOCTYPE html>
<!--
Copyright (c) 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.
-->
<link rel="import" href="/tracing/base/utils.html">
<link rel="import" href="/perf_insights/results/results.html">
<script>
'use strict';
tr.b.unittest.testSuite(function() {
test('resultsAllSuccessful', function() {
var runInfo1 = new pi.v.RunInfo('file1.json');
var runInfo2 = new pi.v.RunInfo('file2.json');
var results = new pi.r.Results();
results.addValue(new pi.v.DictValue(runInfo1, 'res',
{my_key: 'my_value'}));
results.addValue(new pi.v.DictValue(runInfo2, 'res',
{my_key: 'my_value'}));
assert.isFalse(results.hadFailures);
assert.equal(results.allValuesFromFailureFreeRuns.length, 2);
assert.equal(results.getValuesFromFailureFreeRunsNamed('res').length, 2);
});
test('oneFailed', function() {
var runInfo1 = new pi.v.RunInfo('file1.json');
var runInfo2 = new pi.v.RunInfo('file2.json');
var results = new pi.r.Results();
results.addValue(new pi.v.DictValue(runInfo1, 'res',
{my_key: 'my_value'}));
results.addValue(new pi.v.FailureValue(runInfo2, 'res',
{description: 'blah',
stack: 'stack'}));
assert.isTrue(results.hadFailures);
assert.isTrue(results.doesRunContainFailure(runInfo2));
assert.equal(results.allValuesFromFailureFreeRuns.length, 1);
assert.equal(results.getValuesFromFailureFreeRunsNamed('res').length, 1);
});
});
</script> | bsd-3-clause |
yob/debian-rubinius | web/_site/doc/de/index.html | 9767 | <!DOCTYPE html>
<html dir="ltr" lang="de">
<head>
<title>Inhaltsverzeichnis - Rubinius</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta content='de' http-equiv='content-language'>
<meta content='Rubinius is an implementation of the Ruby programming language. The Rubinius bytecode virtual machine is written in C++. The bytecode compiler is written in pure Ruby. The vast majority of the core library is also written in Ruby, with some supporting primitives that interact with the VM directly.' name='description'>
<link href='/' rel='home'>
<link href='/' rel='start'>
<link href='/doc/de/what-is-rubinius' rel='next' title='Was ist Rubinius?'>
<!--[if IE]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js" type="text/javascript"></script><![endif]-->
<script src="/javascripts/jquery-1.3.2.js"></script>
<script src="/javascripts/paging_keys.js"></script>
<script src="/javascripts/application.js"></script>
<style>article, aside, dialog, figure, footer, header, hgroup, menu, nav, section { display: block; }</style>
<link href="/stylesheets/blueprint/screen.css" media="screen" rel="stylesheet" />
<link href="/stylesheets/application.css" media="screen" rel="stylesheet" />
<link href="/stylesheets/blueprint/print.css" media="print" rel="stylesheet" />
<!--[if IE]><link href="/stylesheets/blueprint/ie.css" media="screen" rel="stylesheet" type="text/css" /><![endif]-->
<!--[if IE]><link href="/stylesheets/ie.css" media="screen" rel="stylesheet" type="text/css" /><![endif]-->
<link href="/stylesheets/pygments.css" media="screen" rel="stylesheet" />
<link href="/favicon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon" />
<link href="/images/apple-touch-icon.png" rel="apple-touch-icon" type="image/png" />
<link href="/images/apple-touch-icon.png" rel="apple-touch-icon" type="image/png" sizes="72x72" />
<link href="/images/apple-touch-icon.png" rel="apple-touch-icon" type="image/png" sizes="114x114" />
</head>
<body>
<div class='container'>
<div class='span-21 doc_menu'>
<header>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a id="blog" href="/blog">Blog</a></li>
<li><a id="documentation" href="/doc/en">Documentation</a></li>
<li><a href="/projects">Projects</a></li>
<li><a href="/roadmap">Roadmap</a></li>
<li><a href="/releases">Releases</a></li>
</ul>
</nav>
</header>
</div>
<div class='span-3 last'>
<div id='version'>
<a href="/releases/1.2.4">1.2.4</a>
</div>
</div>
</div>
<div class="container languages">
<nav>
<span class="label">Sprachen:</span>
<ul>
<li><a href="/doc/de/index.html"
class="current"
>de</a></li>
<li><a href="/doc/en/index.html"
>en</a></li>
<li><a href="/doc/es/index.html"
>es</a></li>
<li><a href="/doc/fr/index.html"
>fr</a></li>
<li><a href="/doc/it/index.html"
>it</a></li>
<li><a href="/doc/ja/index.html"
>ja</a></li>
<li><a href="/doc/pl/index.html"
>pl</a></li>
<li><a href="/doc/pt-br/index.html"
>pt-br</a></li>
<li><a href="/doc/ru/index.html"
>ru</a></li>
</ul>
</nav>
</div>
<div class="container doc_page_nav">
</div>
<div class="container documentation">
<h2>Inhaltsverzeichnis</h2>
<ol>
<li><a href="/doc/de/what-is-rubinius/">Was ist Rubinius?</a></li>
<li><a href="/doc/de/getting-started/">Erste Schritte</a>
<ol>
<li><a href="/doc/de/getting-started/requirements/">Voraussetzungen</a></li>
<li><a href="/doc/de/getting-started/building/">Rubinius bauen</a></li>
<li><a href="/doc/de/getting-started/running-rubinius/">Rubinius ausführen</a></li>
<li><a href="/doc/de/getting-started/troubleshooting/">Problemlösungen</a></li>
</ol>
</li>
<li><a href="/doc/de/contributing/">Mitmachen</a>
<ol>
<li><a href="/doc/de/contributing/communication/">Kommunikation</a></li>
<li><a href="/doc/de/contributing/style-guide">Stilvorlage</a></li>
</ol>
</li>
<li><a href="/doc/de/ruby/">Ruby</a>
<ol>
<li><a href="/doc/de/ruby/scripts/">Scripte</a></li>
<li><a href="/doc/de/ruby/methods/">Methoden</a></li>
<li><a href="/doc/de/ruby/constants/">Konstanten</a></li>
<li><a href="/doc/de/ruby/classes-and-modules/">Klassen & Module</a></li>
<li><a href="/doc/de/ruby/blocks-and-procs/">Blöcke & Procs</a></li>
<li><a href="/doc/de/ruby/local-variables/">Lokale Variablen</a></li>
<li><a href="/doc/de/ruby/instance-variables/">Instanzvariablen</a></li>
<li><a href="/doc/de/ruby/class-variables/">Klassenvariablen</a></li>
<li><a href="/doc/de/ruby/global-variables/">Globale Variablen</a></li>
</ol>
</li>
<li><a href="/doc/de/specs/">Specs</a>
<ol>
<li><a href="/doc/de/specs/rubyspec/">RubySpec</a></li>
<li><a href="/doc/de/specs/compiler/">Compiler</a></li>
</ol>
</li>
<li><a href="/doc/de/build-system/">Build System</a></li>
<li><a href="/doc/de/bootstrapping/">Bootstrapping</a></li>
<li><a href="/doc/de/virtual-machine/">Virtuelle Maschine</a>
<ol>
<li><a href="/doc/de/virtual-machine/instructions/">Instruktionen</a></li>
<li><a href="/doc/de/virtual-machine/custom-dispatch-logic/">Benutzerdefinierte Dispatch Logik</a></li>
</ol>
</li>
<li><a href="/doc/de/bytecode-compiler/">Bytecode Compiler</a>
<ol>
<li><a href="/doc/de/bytecode-compiler/parser/">Parser</a></li>
<li><a href="/doc/de/bytecode-compiler/ast/">AST</a></li>
<li><a href="/doc/de/bytecode-compiler/compiler/">Compiler</a></li>
<li><a href="/doc/de/bytecode-compiler/transformations/">Transformationen</a></li>
<li><a href="/doc/de/bytecode-compiler/generator/">Generator</a></li>
</ol>
</li>
<li><a href="/doc/de/jit/">JIT Compiler</a></li>
<li><a href="/doc/de/garbage-collector/">Garbage Collector</a>
<ol>
<li><a href="/doc/de/garbage-collector/nursery/">Junge Generation</a></li>
<li><a href="/doc/de/garbage-collector/young-generation/">Mittlere Generation</a></li>
<li><a href="/doc/de/garbage-collector/mature-generation/">Alte Generation</a></li>
<li><a href="/doc/de/garbage-collector/large-objects/">Große Objekte</a></li>
</ol>
</li>
<li><a href="/doc/de/systems/">Rubinius Systeme</a>
<ol>
<li><a href="/doc/de/systems/primitives/">Primitive</a></li>
<li><a href="/doc/de/systems/ffi/">FFI</a></li>
<li><a href="/doc/de/systems/concurrency/">Concurrency / Nebenläufigkeit</a></li>
<li><a href="/doc/de/systems/io/">IO</a></li>
<li><a href="/doc/de/systems/c-api/">C-API</a></li>
</ol>
</li>
<li><a href="/doc/de/tools/">Tools</a>
<ol>
<li><a href="/doc/de/tools/debugger/">Debugger</a></li>
<li><a href="/doc/de/tools/profiler/">Profiler</a></li>
<li><a href="/doc/de/tools/memory-analysis/">Speicher Analyse</a></li>
</ol>
</li>
<li><a href="/doc/de/how-to/">Anleitungen</a>
<ol>
<li><a href="/doc/de/how-to/write-a-ticket/">Ein Ticket erstellen</a></li>
<li><a href="/doc/de/how-to/write-a-ruby-spec/">Einen Ruby Spec schreiben</a></li>
<li><a href="/doc/de/how-to/fix-a-failing-spec/">Einen fehlgeschlagenen Spec reparieren</a></li>
<li><a href="/doc/de/how-to/write-benchmarks">Benchmarks schreiben</a></li>
<li><a href="/doc/de/how-to/write-a-blog-post/">Einen Blogeintrag schreiben</a></li>
<li><a href="/doc/de/how-to/write-documentation/">Dokumentation schreiben</a></li>
<li><a href="/doc/de/how-to/translate-documentation/">Dokumentation übersetzen</a></li>
</ol>
</li>
<li><a href="/doc/de/appendix-a-glossary/">Anhang A - Glossar</a></li>
<li><a href="/doc/de/appendix-b-reading-list/">Anhang B - Literaturverzeichnis</a></li>
<li><a href="/doc/de/index-of-terms/">Begriffsindex</a></li>
</ol>
</div>
<div class="container doc_page_nav">
</div>
<div class="container">
<div id="disqus_thread"></div>
<script type="text/javascript">
var disqus_shortname = 'rubinius';
var disqus_identifier = '/doc/de/index.html';
var disqus_url = 'http://rubini.us/doc/de/index.html';
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
</div>
<footer>
<div class='container'>
<nav>
<ul>
<li><a rel="external" href="http://twitter.com/rubinius">Follow Rubinius on Twitter</a></li>
<li><a rel="external" href="http://github.com/rubinius/rubinius">Fork Rubinius on github</a></li>
<li><a rel="external" href="http://engineyard.com">An Engine Yard project</a></li>
</ul>
</nav>
</div>
</footer>
<script>
var _gaq=[['_setAccount','UA-12328521-1'],['_trackPageview']];
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.async=1;
g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
s.parentNode.insertBefore(g,s)}(document,'script'));
</script>
</body>
</html>
| bsd-3-clause |
jolth/CowFleet-1.0.0 | static/css/login.css | 3043 | body {
color: #3E3E3E;
font: 90% "Open Sans", "lucida grande", "Segoe UI", arial, verdana, "lucida sans unicode", tahoma, sans-serif;
/*font: 75% arial,helvetica,sans-serif;*/
/*font-family: Verdana;*/
background-color: #FFF;
font-size: 90%; /* importante tamaño relativo para todos */
/*IE6*/
text-align: center;
}
#login-box {
width:590px;
vertical-align: middle;
position: middle;
margin-top: -205px;
margin-left: -242px;
position: absolute;
top: 50%;
left: 50%;
/*
width: 590px;
margin: 0 auto;
padding: 5px;
text-align: left;
border: 1px solid #888;
*/
/*1*/
text-shadow: #355782 0 1px 2px;
-webkit-text-shadow: #355782 0 1px 2px;
moz-text-shadow: #355782 0 1px 2px;
}
#car {
width: 310px;
height: 160px;
padding: 70px 0 0 200px;
background: url('/static/img/intro_gmys.png') transparent no-repeat 0 0;
margin: 40px 0 30px 100px;
}
#car #form {
padding: 0px 10% 0 0;
margin: 0;
}
#car .submit {
width: 95%;
float: left;
display: block;
text-align: right;
}
#car #submit {
clear: both;
padding: 15px 51px;
border: 0;
margin: 15px 0 0 155px;
background: url('/static/img/login-btn.png') transparent no-repeat 0 0;
}
.boton:hover {
color: #333;
border-top: 1px #0070CC solid;
border-right: 1px #006AC1 solid;
border-bottom: 1px #005CA6 solid;
border-left: 1px #006AC1 solid;
-moz-box-shadow: 0 1px 1px rgba(0,0,0,.3), inset 0 0 3px #35bff4;
-webkit-box-shadow: 0 1px 1px rgba(0,0,0,.3), inset 0 0 3px #35bff4;
box-shadow: 0 1px 1px rgba(0,0,0,.3), inset 0 0 3px #35bff4;
}
.boton {
/*display: block;
background-color: #008AD0;
color: white;
border: solid 1px #8ED8F8;
margin: 2% 0 0 75%;
font-weight: bold;
-webkit-box-shadow: 2px 2px 5px #333;
-moz-box-shadow: 2px 2px 5px #333;
filter: shadow(color=#333, direction=135, strength=2);*/
border-top: 1px #2270AB solid;
border-right: 1px #18639A solid;
border-bottom: 1px #0F568B solid;
border-left: 1px #18639A solid;
background:#2180CE;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#33a0e8', endColorstr='#2180ce');
background: -webkit-gradient(linear, left top, left bottom, from(#33A0E8), to(#2180CE));
background: -moz-linear-gradient(top, #33A0E8, #2180CE);
text-shadow: #355782 0 1px 2px;
-webkit-text-shadow: #355782 0 1px 2px;
-moz-text-shadow: #355782 0 1px 2px;
-moz-box-shadow: 0 1px 1px rgba(0, 0, 0, .3), inset 0 1px 0 #83c5f1;
-webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .3), inset 0 1px 0 #83c5f1;
box-shadow:0 1px 1px rgba(0, 0, 0, .3), inset 0 1px 0 #83c5f1;
/* Texto */
text-align: center;
color: #FFF;
/* Mouse */
cursor: pointer;
overflow: visible;
}
form input {
border-radius: 3px;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
/* width/height box */
padding: 3px 5px;
font-size: 13px;
font-weight: 400;
}
#car label {
display: block;
color: #FFF;
padding-bottom: 5px;
padding-right: 0px;
margin-right: 0px;
float: left;
width: 70px;
text-align: right;
margin-top: 1%;
font-weight: 550;
}
.input {
/**/
/*font-size: small;*/
border: 1px solid #BBB;
background: #FFF;
color: #2E2E2E;
}
input {
margin-top: 3px;
}
| bsd-3-clause |
alishakiba/libflame | src/blas/3/gemm/tt/flamec/FLA_Gemm_tt.h | 1558 | /*
Copyright (C) 2014, The University of Texas at Austin
This file is part of libflame and is available under the 3-Clause
BSD license, which can be found in the LICENSE file at the top-level
directory, or at http://opensource.org/licenses/BSD-3-Clause
*/
#include "FLAME.h"
FLA_Error FLA_Gemm_tt_blk_var1( FLA_Obj alpha, FLA_Obj A, FLA_Obj B, FLA_Obj beta, FLA_Obj C, fla_gemm_t* cntl );
FLA_Error FLA_Gemm_tt_blk_var2( FLA_Obj alpha, FLA_Obj A, FLA_Obj B, FLA_Obj beta, FLA_Obj C, fla_gemm_t* cntl );
FLA_Error FLA_Gemm_tt_blk_var3( FLA_Obj alpha, FLA_Obj A, FLA_Obj B, FLA_Obj beta, FLA_Obj C, fla_gemm_t* cntl );
FLA_Error FLA_Gemm_tt_blk_var4( FLA_Obj alpha, FLA_Obj A, FLA_Obj B, FLA_Obj beta, FLA_Obj C, fla_gemm_t* cntl );
FLA_Error FLA_Gemm_tt_blk_var5( FLA_Obj alpha, FLA_Obj A, FLA_Obj B, FLA_Obj beta, FLA_Obj C, fla_gemm_t* cntl );
FLA_Error FLA_Gemm_tt_blk_var6( FLA_Obj alpha, FLA_Obj A, FLA_Obj B, FLA_Obj beta, FLA_Obj C, fla_gemm_t* cntl );
FLA_Error FLA_Gemm_tt_unb_var1( FLA_Obj alpha, FLA_Obj A, FLA_Obj B, FLA_Obj beta, FLA_Obj C );
FLA_Error FLA_Gemm_tt_unb_var2( FLA_Obj alpha, FLA_Obj A, FLA_Obj B, FLA_Obj beta, FLA_Obj C );
FLA_Error FLA_Gemm_tt_unb_var3( FLA_Obj alpha, FLA_Obj A, FLA_Obj B, FLA_Obj beta, FLA_Obj C );
FLA_Error FLA_Gemm_tt_unb_var4( FLA_Obj alpha, FLA_Obj A, FLA_Obj B, FLA_Obj beta, FLA_Obj C );
FLA_Error FLA_Gemm_tt_unb_var5( FLA_Obj alpha, FLA_Obj A, FLA_Obj B, FLA_Obj beta, FLA_Obj C );
FLA_Error FLA_Gemm_tt_unb_var6( FLA_Obj alpha, FLA_Obj A, FLA_Obj B, FLA_Obj beta, FLA_Obj C );
| bsd-3-clause |
sgraham/nope | chrome/browser/geolocation/geolocation_permission_context_unittest.cc | 37152 | // 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 "chrome/browser/geolocation/geolocation_permission_context.h"
#include <set>
#include <string>
#include <utility>
#include "base/bind.h"
#include "base/command_line.h"
#include "base/containers/hash_tables.h"
#include "base/id_map.h"
#include "base/memory/scoped_vector.h"
#include "base/synchronization/waitable_event.h"
#include "base/test/simple_test_clock.h"
#include "base/time/clock.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/content_settings/tab_specific_content_settings.h"
#include "chrome/browser/geolocation/geolocation_permission_context_factory.h"
#include "chrome/browser/infobars/infobar_service.h"
#include "chrome/browser/ui/website_settings/mock_permission_bubble_view.h"
#include "chrome/browser/ui/website_settings/permission_bubble_manager.h"
#include "chrome/browser/ui/website_settings/permission_bubble_request.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/chrome_render_view_host_test_harness.h"
#include "chrome/test/base/testing_profile.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/content_settings/core/common/permission_request_id.h"
#include "components/infobars/core/confirm_infobar_delegate.h"
#include "components/infobars/core/infobar.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/navigation_details.h"
#include "content/public/browser/notification_observer.h"
#include "content/public/browser/notification_registrar.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/mock_render_process_host.h"
#include "content/public/test/test_renderer_host.h"
#include "content/public/test/test_utils.h"
#include "content/public/test/web_contents_tester.h"
#include "testing/gtest/include/gtest/gtest.h"
#if defined(OS_ANDROID)
#include "base/prefs/pref_service.h"
#include "chrome/browser/android/mock_location_settings.h"
#include "chrome/browser/geolocation/geolocation_permission_context_android.h"
#endif
#if defined(ENABLE_EXTENSIONS)
#include "extensions/browser/view_type_utils.h"
#endif
using content::MockRenderProcessHost;
// ClosedInfoBarTracker -------------------------------------------------------
// We need to track which infobars were closed.
class ClosedInfoBarTracker : public content::NotificationObserver {
public:
ClosedInfoBarTracker();
~ClosedInfoBarTracker() override;
// content::NotificationObserver:
void Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) override;
size_t size() const { return removed_infobars_.size(); }
bool Contains(infobars::InfoBar* infobar) const;
void Clear();
private:
FRIEND_TEST_ALL_PREFIXES(GeolocationPermissionContextTests, TabDestroyed);
content::NotificationRegistrar registrar_;
std::set<infobars::InfoBar*> removed_infobars_;
};
ClosedInfoBarTracker::ClosedInfoBarTracker() {
registrar_.Add(this, chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_REMOVED,
content::NotificationService::AllSources());
}
ClosedInfoBarTracker::~ClosedInfoBarTracker() {
}
void ClosedInfoBarTracker::Observe(
int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
DCHECK(type == chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_REMOVED);
removed_infobars_.insert(
content::Details<infobars::InfoBar::RemovedDetails>(details)->first);
}
bool ClosedInfoBarTracker::Contains(infobars::InfoBar* infobar) const {
return removed_infobars_.count(infobar) != 0;
}
void ClosedInfoBarTracker::Clear() {
removed_infobars_.clear();
}
// GeolocationPermissionContextTests ------------------------------------------
class GeolocationPermissionContextTests
: public ChromeRenderViewHostTestHarness {
protected:
// ChromeRenderViewHostTestHarness:
void SetUp() override;
void TearDown() override;
PermissionRequestID RequestID(int bridge_id);
PermissionRequestID RequestIDForTab(int tab, int bridge_id);
InfoBarService* infobar_service() {
return InfoBarService::FromWebContents(web_contents());
}
InfoBarService* infobar_service_for_tab(int tab) {
return InfoBarService::FromWebContents(extra_tabs_[tab]);
}
void RequestGeolocationPermission(content::WebContents* web_contents,
const PermissionRequestID& id,
const GURL& requesting_frame,
bool user_gesture);
void PermissionResponse(const PermissionRequestID& id,
ContentSetting content_setting);
void CheckPermissionMessageSent(int bridge_id, bool allowed);
void CheckPermissionMessageSentForTab(int tab, int bridge_id, bool allowed);
void CheckPermissionMessageSentInternal(MockRenderProcessHost* process,
int bridge_id,
bool allowed);
void AddNewTab(const GURL& url);
void CheckTabContentsState(const GURL& requesting_frame,
ContentSetting expected_content_setting);
size_t GetBubblesQueueSize(PermissionBubbleManager* manager);
void AcceptBubble(PermissionBubbleManager* manager);
void DenyBubble(PermissionBubbleManager* manager);
void CloseBubble(PermissionBubbleManager* manager);
void BubbleManagerDocumentLoadCompleted();
void BubbleManagerDocumentLoadCompleted(content::WebContents* web_contents);
ContentSetting GetGeolocationContentSetting(GURL frame_0, GURL frame_1);
// owned by the browser context
GeolocationPermissionContext* geolocation_permission_context_;
ClosedInfoBarTracker closed_infobar_tracker_;
MockPermissionBubbleView bubble_view_;
ScopedVector<content::WebContents> extra_tabs_;
// A map between renderer child id and a pair represending the bridge id and
// whether the requested permission was allowed.
base::hash_map<int, std::pair<int, bool> > responses_;
};
PermissionRequestID GeolocationPermissionContextTests::RequestID(
int bridge_id) {
return PermissionRequestID(
web_contents()->GetRenderProcessHost()->GetID(),
web_contents()->GetRenderViewHost()->GetRoutingID(),
bridge_id,
GURL());
}
PermissionRequestID GeolocationPermissionContextTests::RequestIDForTab(
int tab,
int bridge_id) {
return PermissionRequestID(
extra_tabs_[tab]->GetRenderProcessHost()->GetID(),
extra_tabs_[tab]->GetRenderViewHost()->GetRoutingID(),
bridge_id,
GURL());
}
void GeolocationPermissionContextTests::RequestGeolocationPermission(
content::WebContents* web_contents,
const PermissionRequestID& id,
const GURL& requesting_frame,
bool user_gesture) {
geolocation_permission_context_->RequestPermission(
web_contents, id, requesting_frame, user_gesture,
base::Bind(&GeolocationPermissionContextTests::PermissionResponse,
base::Unretained(this), id));
content::RunAllBlockingPoolTasksUntilIdle();
}
void GeolocationPermissionContextTests::PermissionResponse(
const PermissionRequestID& id,
ContentSetting content_setting) {
responses_[id.render_process_id()] =
std::make_pair(id.bridge_id(), content_setting == CONTENT_SETTING_ALLOW);
}
void GeolocationPermissionContextTests::CheckPermissionMessageSent(
int bridge_id,
bool allowed) {
CheckPermissionMessageSentInternal(process(), bridge_id, allowed);
}
void GeolocationPermissionContextTests::CheckPermissionMessageSentForTab(
int tab,
int bridge_id,
bool allowed) {
CheckPermissionMessageSentInternal(static_cast<MockRenderProcessHost*>(
extra_tabs_[tab]->GetRenderProcessHost()),
bridge_id, allowed);
}
void GeolocationPermissionContextTests::CheckPermissionMessageSentInternal(
MockRenderProcessHost* process,
int bridge_id,
bool allowed) {
ASSERT_EQ(responses_.count(process->GetID()), 1U);
EXPECT_EQ(bridge_id, responses_[process->GetID()].first);
EXPECT_EQ(allowed, responses_[process->GetID()].second);
responses_.erase(process->GetID());
}
void GeolocationPermissionContextTests::AddNewTab(const GURL& url) {
content::WebContents* new_tab = CreateTestWebContents();
new_tab->GetController().LoadURL(
url, content::Referrer(), ui::PAGE_TRANSITION_TYPED, std::string());
content::RenderFrameHostTester::For(new_tab->GetMainFrame())
->SendNavigate(extra_tabs_.size() + 1, url);
// Set up required helpers, and make this be as "tabby" as the code requires.
#if defined(ENABLE_EXTENSIONS)
extensions::SetViewType(new_tab, extensions::VIEW_TYPE_TAB_CONTENTS);
#endif
InfoBarService::CreateForWebContents(new_tab);
PermissionBubbleManager::CreateForWebContents(new_tab);
PermissionBubbleManager::FromWebContents(new_tab)->SetView(&bubble_view_);
extra_tabs_.push_back(new_tab);
}
void GeolocationPermissionContextTests::CheckTabContentsState(
const GURL& requesting_frame,
ContentSetting expected_content_setting) {
TabSpecificContentSettings* content_settings =
TabSpecificContentSettings::FromWebContents(web_contents());
const ContentSettingsUsagesState::StateMap& state_map =
content_settings->geolocation_usages_state().state_map();
EXPECT_EQ(1U, state_map.count(requesting_frame.GetOrigin()));
EXPECT_EQ(0U, state_map.count(requesting_frame));
ContentSettingsUsagesState::StateMap::const_iterator settings =
state_map.find(requesting_frame.GetOrigin());
ASSERT_FALSE(settings == state_map.end())
<< "geolocation state not found " << requesting_frame;
EXPECT_EQ(expected_content_setting, settings->second);
}
void GeolocationPermissionContextTests::SetUp() {
ChromeRenderViewHostTestHarness::SetUp();
// Set up required helpers, and make this be as "tabby" as the code requires.
#if defined(ENABLE_EXTENSIONS)
extensions::SetViewType(web_contents(), extensions::VIEW_TYPE_TAB_CONTENTS);
#endif
InfoBarService::CreateForWebContents(web_contents());
TabSpecificContentSettings::CreateForWebContents(web_contents());
geolocation_permission_context_ =
GeolocationPermissionContextFactory::GetForProfile(profile());
#if defined(OS_ANDROID)
static_cast<GeolocationPermissionContextAndroid*>(
geolocation_permission_context_)
->SetLocationSettingsForTesting(
scoped_ptr<LocationSettings>(new MockLocationSettings()));
MockLocationSettings::SetLocationStatus(true, true);
#endif
PermissionBubbleManager::CreateForWebContents(web_contents());
PermissionBubbleManager::FromWebContents(web_contents())->SetView(
&bubble_view_);
}
void GeolocationPermissionContextTests::TearDown() {
extra_tabs_.clear();
ChromeRenderViewHostTestHarness::TearDown();
}
size_t GeolocationPermissionContextTests::GetBubblesQueueSize(
PermissionBubbleManager* manager) {
return manager->requests_.size();
}
void GeolocationPermissionContextTests::AcceptBubble(
PermissionBubbleManager* manager) {
manager->Accept();
}
void GeolocationPermissionContextTests::DenyBubble(
PermissionBubbleManager* manager) {
manager->Deny();
}
void GeolocationPermissionContextTests::CloseBubble(
PermissionBubbleManager* manager) {
manager->Closing();
}
void GeolocationPermissionContextTests::BubbleManagerDocumentLoadCompleted() {
GeolocationPermissionContextTests::BubbleManagerDocumentLoadCompleted(
web_contents());
}
void GeolocationPermissionContextTests::BubbleManagerDocumentLoadCompleted(
content::WebContents* web_contents) {
PermissionBubbleManager::FromWebContents(web_contents)->
DocumentOnLoadCompletedInMainFrame();
}
ContentSetting GeolocationPermissionContextTests::GetGeolocationContentSetting(
GURL frame_0, GURL frame_1) {
return profile()->GetHostContentSettingsMap()->GetContentSetting(
frame_0, frame_1, CONTENT_SETTINGS_TYPE_GEOLOCATION, std::string());
}
// Needed to parameterize the tests for both infobars & permission bubbles.
class GeolocationPermissionContextParamTests :
public GeolocationPermissionContextTests,
public ::testing::WithParamInterface<bool> {
protected:
GeolocationPermissionContextParamTests() {}
~GeolocationPermissionContextParamTests() override {}
bool BubbleEnabled() const {
#if defined (OS_ANDROID)
return false;
#else
return GetParam();
#endif
}
void SetUp() override {
GeolocationPermissionContextTests::SetUp();
#if !defined(OS_ANDROID)
if (BubbleEnabled()) {
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnablePermissionsBubbles);
EXPECT_TRUE(PermissionBubbleManager::Enabled());
} else {
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kDisablePermissionsBubbles);
EXPECT_FALSE(PermissionBubbleManager::Enabled());
}
#endif
}
size_t GetNumberOfPrompts() {
if (BubbleEnabled()) {
PermissionBubbleManager* manager =
PermissionBubbleManager::FromWebContents(web_contents());
return GetBubblesQueueSize(manager);
} else {
return infobar_service()->infobar_count();
}
}
void AcceptPrompt() {
if (BubbleEnabled()) {
PermissionBubbleManager* manager =
PermissionBubbleManager::FromWebContents(web_contents());
AcceptBubble(manager);
} else {
infobars::InfoBar* infobar = infobar_service()->infobar_at(0);
ConfirmInfoBarDelegate* infobar_delegate =
infobar->delegate()->AsConfirmInfoBarDelegate();
infobar_delegate->Accept();
}
}
base::string16 GetPromptText() {
if (BubbleEnabled()) {
PermissionBubbleManager* manager =
PermissionBubbleManager::FromWebContents(web_contents());
return manager->requests_.front()->GetMessageText();
}
infobars::InfoBar* infobar = infobar_service()->infobar_at(0);
ConfirmInfoBarDelegate* infobar_delegate =
infobar->delegate()->AsConfirmInfoBarDelegate();
return infobar_delegate->GetMessageText();
}
private:
DISALLOW_COPY_AND_ASSIGN(GeolocationPermissionContextParamTests);
};
// Tests ----------------------------------------------------------------------
TEST_P(GeolocationPermissionContextParamTests, SinglePermissionInfobar) {
if (BubbleEnabled()) return;
GURL requesting_frame("http://www.example.com/geolocation");
NavigateAndCommit(requesting_frame);
EXPECT_EQ(0U, infobar_service()->infobar_count());
RequestGeolocationPermission(
web_contents(), RequestID(0), requesting_frame, true);
ASSERT_EQ(1U, infobar_service()->infobar_count());
infobars::InfoBar* infobar = infobar_service()->infobar_at(0);
ConfirmInfoBarDelegate* infobar_delegate =
infobar->delegate()->AsConfirmInfoBarDelegate();
ASSERT_TRUE(infobar_delegate);
infobar_delegate->Cancel();
infobar_service()->RemoveInfoBar(infobar);
EXPECT_EQ(1U, closed_infobar_tracker_.size());
EXPECT_TRUE(closed_infobar_tracker_.Contains(infobar));
}
TEST_P(GeolocationPermissionContextParamTests, SinglePermissionBubble) {
if (!BubbleEnabled()) return;
GURL requesting_frame("http://www.example.com/geolocation");
NavigateAndCommit(requesting_frame);
BubbleManagerDocumentLoadCompleted();
EXPECT_EQ(0U, GetNumberOfPrompts());
RequestGeolocationPermission(
web_contents(), RequestID(0), requesting_frame, true);
ASSERT_EQ(1U, GetNumberOfPrompts());
}
#if defined(OS_ANDROID)
// Infobar-only tests; Android doesn't support permission bubbles.
TEST_F(GeolocationPermissionContextTests, GeolocationEnabledDisabled) {
GURL requesting_frame("http://www.example.com/geolocation");
NavigateAndCommit(requesting_frame);
MockLocationSettings::SetLocationStatus(true, true);
EXPECT_EQ(0U, infobar_service()->infobar_count());
RequestGeolocationPermission(
web_contents(), RequestID(0), requesting_frame, true);
EXPECT_EQ(1U, infobar_service()->infobar_count());
ConfirmInfoBarDelegate* infobar_delegate_0 =
infobar_service()->infobar_at(0)->delegate()->AsConfirmInfoBarDelegate();
ASSERT_TRUE(infobar_delegate_0);
base::string16 text_0 = infobar_delegate_0->GetButtonLabel(
ConfirmInfoBarDelegate::BUTTON_OK);
Reload();
MockLocationSettings::SetLocationStatus(true, false);
EXPECT_EQ(0U, infobar_service()->infobar_count());
RequestGeolocationPermission(
web_contents(), RequestID(0), requesting_frame, true);
EXPECT_EQ(0U, infobar_service()->infobar_count());
}
TEST_F(GeolocationPermissionContextTests, MasterEnabledGoogleAppsEnabled) {
GURL requesting_frame("http://www.example.com/geolocation");
NavigateAndCommit(requesting_frame);
MockLocationSettings::SetLocationStatus(true, true);
EXPECT_EQ(0U, infobar_service()->infobar_count());
RequestGeolocationPermission(
web_contents(), RequestID(0), requesting_frame, true);
EXPECT_EQ(1U, infobar_service()->infobar_count());
ConfirmInfoBarDelegate* infobar_delegate =
infobar_service()->infobar_at(0)->delegate()->AsConfirmInfoBarDelegate();
ASSERT_TRUE(infobar_delegate);
infobar_delegate->Accept();
CheckTabContentsState(requesting_frame, CONTENT_SETTING_ALLOW);
CheckPermissionMessageSent(0, true);
}
TEST_F(GeolocationPermissionContextTests, MasterEnabledGoogleAppsDisabled) {
GURL requesting_frame("http://www.example.com/geolocation");
NavigateAndCommit(requesting_frame);
MockLocationSettings::SetLocationStatus(true, false);
EXPECT_EQ(0U, infobar_service()->infobar_count());
RequestGeolocationPermission(
web_contents(), RequestID(0), requesting_frame, true);
EXPECT_EQ(0U, infobar_service()->infobar_count());
}
#endif
TEST_P(GeolocationPermissionContextParamTests, QueuedPermission) {
GURL requesting_frame_0("http://www.example.com/geolocation");
GURL requesting_frame_1("http://www.example-2.com/geolocation");
EXPECT_EQ(
CONTENT_SETTING_ASK,
GetGeolocationContentSetting(requesting_frame_0, requesting_frame_1));
EXPECT_EQ(
CONTENT_SETTING_ASK,
GetGeolocationContentSetting(requesting_frame_1, requesting_frame_1));
NavigateAndCommit(requesting_frame_0);
if (BubbleEnabled()) BubbleManagerDocumentLoadCompleted();
// Check that no permission requests have happened yet.
EXPECT_EQ(0U, GetNumberOfPrompts());
// Request permission for two frames.
RequestGeolocationPermission(
web_contents(), RequestID(0), requesting_frame_0, true);
RequestGeolocationPermission(
web_contents(), RequestID(1), requesting_frame_1, true);
// Ensure only one infobar is created.
ASSERT_EQ(1U, GetNumberOfPrompts());
base::string16 text_0 = GetPromptText();
// Accept the first frame.
AcceptPrompt();
CheckTabContentsState(requesting_frame_0, CONTENT_SETTING_ALLOW);
CheckPermissionMessageSent(0, true);
if (!BubbleEnabled()) {
infobars::InfoBar* infobar_0 = infobar_service()->infobar_at(0);
infobar_service()->RemoveInfoBar(infobar_0);
EXPECT_EQ(1U, closed_infobar_tracker_.size());
EXPECT_TRUE(closed_infobar_tracker_.Contains(infobar_0));
closed_infobar_tracker_.Clear();
}
// Now we should have a new infobar for the second frame.
ASSERT_EQ(1U, GetNumberOfPrompts());
base::string16 text_1 = GetPromptText();
// Check that the messages differ.
EXPECT_NE(text_0, text_1);
// Cancel (block) this frame.
if (BubbleEnabled()) {
PermissionBubbleManager* manager =
PermissionBubbleManager::FromWebContents(web_contents());
DenyBubble(manager);
} else {
infobars::InfoBar* infobar_1 = infobar_service()->infobar_at(0);
infobar_1->delegate()->AsConfirmInfoBarDelegate()->Cancel();
}
CheckTabContentsState(requesting_frame_1, CONTENT_SETTING_BLOCK);
CheckPermissionMessageSent(1, false);
// Ensure the persisted permissions are ok.
EXPECT_EQ(
CONTENT_SETTING_ALLOW,
GetGeolocationContentSetting(requesting_frame_0, requesting_frame_0));
EXPECT_EQ(
CONTENT_SETTING_BLOCK,
GetGeolocationContentSetting(requesting_frame_1, requesting_frame_0));
}
TEST_P(GeolocationPermissionContextParamTests, HashIsIgnored) {
GURL url_a("http://www.example.com/geolocation#a");
GURL url_b("http://www.example.com/geolocation#b");
// Navigate to the first url.
NavigateAndCommit(url_a);
if (BubbleEnabled()) BubbleManagerDocumentLoadCompleted();
// Check permission is requested.
ASSERT_EQ(0U, GetNumberOfPrompts());
RequestGeolocationPermission(
web_contents(), RequestID(0), url_a, BubbleEnabled());
ASSERT_EQ(1U, GetNumberOfPrompts());
// Change the hash, we'll still be on the same page.
NavigateAndCommit(url_b);
if (BubbleEnabled()) BubbleManagerDocumentLoadCompleted();
// Accept.
AcceptPrompt();
CheckTabContentsState(url_a, CONTENT_SETTING_ALLOW);
CheckTabContentsState(url_b, CONTENT_SETTING_ALLOW);
CheckPermissionMessageSent(0, true);
// Cleanup.
if (!BubbleEnabled()) {
infobars::InfoBar* infobar = infobar_service()->infobar_at(0);
infobar_service()->RemoveInfoBar(infobar);
EXPECT_EQ(1U, closed_infobar_tracker_.size());
EXPECT_TRUE(closed_infobar_tracker_.Contains(infobar));
}
}
TEST_P(GeolocationPermissionContextParamTests, PermissionForFileScheme) {
// TODO(felt): The bubble is rejecting file:// permission requests.
// Fix and enable this test. crbug.com/444047
if (BubbleEnabled()) return;
GURL requesting_frame("file://example/geolocation.html");
NavigateAndCommit(requesting_frame);
if (BubbleEnabled()) BubbleManagerDocumentLoadCompleted();
// Check permission is requested.
ASSERT_EQ(0U, GetNumberOfPrompts());
RequestGeolocationPermission(
web_contents(), RequestID(0), requesting_frame, true);
EXPECT_EQ(1U, GetNumberOfPrompts());
// Accept the frame.
AcceptPrompt();
CheckTabContentsState(requesting_frame, CONTENT_SETTING_ALLOW);
CheckPermissionMessageSent(0, true);
// Make sure the setting is not stored.
EXPECT_EQ(
CONTENT_SETTING_ASK,
GetGeolocationContentSetting(requesting_frame, requesting_frame));
}
TEST_P(GeolocationPermissionContextParamTests,
CancelGeolocationPermissionRequest) {
GURL frame_0("http://www.example.com/geolocation");
GURL frame_1("http://www.example-2.com/geolocation");
EXPECT_EQ(
CONTENT_SETTING_ASK, GetGeolocationContentSetting(frame_0, frame_0));
EXPECT_EQ(
CONTENT_SETTING_ASK, GetGeolocationContentSetting(frame_1, frame_0));
NavigateAndCommit(frame_0);
if (BubbleEnabled()) BubbleManagerDocumentLoadCompleted();
ASSERT_EQ(0U, GetNumberOfPrompts());
// Request permission for two frames.
RequestGeolocationPermission(
web_contents(), RequestID(0), frame_0, true);
RequestGeolocationPermission(
web_contents(), RequestID(1), frame_1, true);
// Get the first permission request text.
ASSERT_EQ(1U, GetNumberOfPrompts());
base::string16 text_0 = GetPromptText();
ASSERT_FALSE(text_0.empty());
// Simulate the frame going away; the request should be removed.
if (BubbleEnabled()) {
PermissionBubbleManager* manager =
PermissionBubbleManager::FromWebContents(web_contents());
CloseBubble(manager);
} else {
geolocation_permission_context_->CancelPermissionRequest(web_contents(),
RequestID(0));
}
// Check that the next pending request is created correctly.
base::string16 text_1 = GetPromptText();
EXPECT_NE(text_0, text_1);
// Allow this frame and check that it worked.
AcceptPrompt();
CheckTabContentsState(frame_1, CONTENT_SETTING_ALLOW);
CheckPermissionMessageSent(1, true);
// Ensure the persisted permissions are ok.
EXPECT_EQ(
CONTENT_SETTING_ASK, GetGeolocationContentSetting(frame_0, frame_0));
EXPECT_EQ(
CONTENT_SETTING_ALLOW, GetGeolocationContentSetting(frame_1, frame_0));
}
TEST_P(GeolocationPermissionContextParamTests, InvalidURL) {
// Navigate to the first url.
GURL invalid_embedder("about:blank");
GURL requesting_frame;
NavigateAndCommit(invalid_embedder);
if (BubbleEnabled()) BubbleManagerDocumentLoadCompleted();
// Nothing should be displayed.
EXPECT_EQ(0U, GetNumberOfPrompts());
RequestGeolocationPermission(
web_contents(), RequestID(0), requesting_frame, true);
EXPECT_EQ(0U, GetNumberOfPrompts());
CheckPermissionMessageSent(0, false);
}
TEST_P(GeolocationPermissionContextParamTests, SameOriginMultipleTabs) {
GURL url_a("http://www.example.com/geolocation");
GURL url_b("http://www.example-2.com/geolocation");
NavigateAndCommit(url_a); // Tab A0
AddNewTab(url_b); // Tab B (extra_tabs_[0])
AddNewTab(url_a); // Tab A1 (extra_tabs_[1])
if (BubbleEnabled()) {
BubbleManagerDocumentLoadCompleted();
BubbleManagerDocumentLoadCompleted(extra_tabs_[0]);
BubbleManagerDocumentLoadCompleted(extra_tabs_[1]);
}
PermissionBubbleManager* manager_a0 =
PermissionBubbleManager::FromWebContents(web_contents());
PermissionBubbleManager* manager_b =
PermissionBubbleManager::FromWebContents(extra_tabs_[0]);
PermissionBubbleManager* manager_a1 =
PermissionBubbleManager::FromWebContents(extra_tabs_[1]);
// Request permission in all three tabs.
RequestGeolocationPermission(
web_contents(), RequestID(0), url_a, true);
RequestGeolocationPermission(
extra_tabs_[0], RequestIDForTab(0, 0), url_b, true);
RequestGeolocationPermission(
extra_tabs_[1], RequestIDForTab(1, 0), url_a, true);
ASSERT_EQ(1U, GetNumberOfPrompts()); // For A0.
if (BubbleEnabled()) {
ASSERT_EQ(1U, GetBubblesQueueSize(manager_b));
ASSERT_EQ(1U, GetBubblesQueueSize(manager_a1));
} else {
ASSERT_EQ(1U, infobar_service_for_tab(0)->infobar_count());
ASSERT_EQ(1U, infobar_service_for_tab(1)->infobar_count());
}
// Accept the permission in tab A0.
if (BubbleEnabled()) {
AcceptBubble(manager_a0);
} else {
infobars::InfoBar* infobar_a0 = infobar_service()->infobar_at(0);
ConfirmInfoBarDelegate* infobar_delegate_a0 =
infobar_a0->delegate()->AsConfirmInfoBarDelegate();
ASSERT_TRUE(infobar_delegate_a0);
infobar_delegate_a0->Accept();
infobar_service()->RemoveInfoBar(infobar_a0);
EXPECT_EQ(2U, closed_infobar_tracker_.size());
EXPECT_TRUE(closed_infobar_tracker_.Contains(infobar_a0));
}
CheckPermissionMessageSent(0, true);
// Because they're the same origin, this will cause tab A1's infobar to
// disappear. It does not cause the bubble to disappear: crbug.com/443013.
// TODO(felt): Update this test when the bubble's behavior is changed.
if (BubbleEnabled())
ASSERT_EQ(1U, GetBubblesQueueSize(manager_a1));
else
CheckPermissionMessageSentForTab(1, 0, true);
// Either way, tab B should still have a pending permission request.
if (BubbleEnabled())
ASSERT_EQ(1U, GetBubblesQueueSize(manager_b));
else
ASSERT_EQ(1U, infobar_service_for_tab(0)->infobar_count());
}
TEST_P(GeolocationPermissionContextParamTests, QueuedOriginMultipleTabs) {
GURL url_a("http://www.example.com/geolocation");
GURL url_b("http://www.example-2.com/geolocation");
NavigateAndCommit(url_a); // Tab A0.
AddNewTab(url_a); // Tab A1.
if (BubbleEnabled()) {
BubbleManagerDocumentLoadCompleted();
BubbleManagerDocumentLoadCompleted(extra_tabs_[0]);
}
PermissionBubbleManager* manager_a0 =
PermissionBubbleManager::FromWebContents(web_contents());
PermissionBubbleManager* manager_a1 =
PermissionBubbleManager::FromWebContents(extra_tabs_[0]);
// Request permission in both tabs; the extra tab will have two permission
// requests from two origins.
RequestGeolocationPermission(
web_contents(), RequestID(0), url_a, true);
RequestGeolocationPermission(
extra_tabs_[0], RequestIDForTab(0, 0), url_a, true);
RequestGeolocationPermission(
extra_tabs_[0], RequestIDForTab(0, 1), url_b, true);
if (BubbleEnabled()) {
ASSERT_EQ(1U, GetBubblesQueueSize(manager_a0));
ASSERT_EQ(1U, GetBubblesQueueSize(manager_a1));
} else {
ASSERT_EQ(1U, infobar_service()->infobar_count());
ASSERT_EQ(1U, infobar_service_for_tab(0)->infobar_count());
}
// Accept the first request in tab A1.
if (BubbleEnabled()) {
AcceptBubble(manager_a1);
} else {
infobars::InfoBar* infobar_a1 = infobar_service_for_tab(0)->infobar_at(0);
ConfirmInfoBarDelegate* infobar_delegate_a1 =
infobar_a1->delegate()->AsConfirmInfoBarDelegate();
ASSERT_TRUE(infobar_delegate_a1);
infobar_delegate_a1->Accept();
infobar_service_for_tab(0)->RemoveInfoBar(infobar_a1);
EXPECT_EQ(2U, closed_infobar_tracker_.size());
EXPECT_TRUE(closed_infobar_tracker_.Contains(infobar_a1));
}
CheckPermissionMessageSentForTab(0, 0, true);
// Because they're the same origin, this will cause tab A0's infobar to
// disappear. It does not cause the bubble to disappear: crbug.com/443013.
// TODO(felt): Update this test when the bubble's behavior is changed.
if (BubbleEnabled()) {
EXPECT_EQ(1U, GetBubblesQueueSize(manager_a0));
} else {
EXPECT_EQ(0U, infobar_service()->infobar_count());
CheckPermissionMessageSent(0, true);
}
// The second request should now be visible in tab A1.
if (BubbleEnabled())
ASSERT_EQ(1U, GetBubblesQueueSize(manager_a1));
else
ASSERT_EQ(1U, infobar_service_for_tab(0)->infobar_count());
// Accept the second request and check that it's gone.
if (BubbleEnabled()) {
AcceptBubble(manager_a1);
EXPECT_EQ(0U, GetBubblesQueueSize(manager_a1));
} else {
infobars::InfoBar* infobar_1 = infobar_service_for_tab(0)->infobar_at(0);
ConfirmInfoBarDelegate* infobar_delegate_1 =
infobar_1->delegate()->AsConfirmInfoBarDelegate();
ASSERT_TRUE(infobar_delegate_1);
infobar_delegate_1->Accept();
}
}
TEST_P(GeolocationPermissionContextParamTests, TabDestroyed) {
GURL requesting_frame_0("http://www.example.com/geolocation");
GURL requesting_frame_1("http://www.example-2.com/geolocation");
EXPECT_EQ(
CONTENT_SETTING_ASK,
GetGeolocationContentSetting(requesting_frame_0, requesting_frame_0));
EXPECT_EQ(
CONTENT_SETTING_ASK,
GetGeolocationContentSetting(requesting_frame_1, requesting_frame_0));
NavigateAndCommit(requesting_frame_0);
if (BubbleEnabled()) BubbleManagerDocumentLoadCompleted();
// Request permission for two frames.
RequestGeolocationPermission(
web_contents(), RequestID(0), requesting_frame_0, false);
RequestGeolocationPermission(
web_contents(), RequestID(1), requesting_frame_1, false);
// Ensure only one prompt is created.
ASSERT_EQ(1U, GetNumberOfPrompts());
// Delete the tab contents.
if (!BubbleEnabled()) {
infobars::InfoBar* infobar = infobar_service()->infobar_at(0);
DeleteContents();
ASSERT_EQ(1U, closed_infobar_tracker_.size());
ASSERT_TRUE(closed_infobar_tracker_.Contains(infobar));
}
// The content settings should not have changed.
EXPECT_EQ(
CONTENT_SETTING_ASK,
GetGeolocationContentSetting(requesting_frame_0, requesting_frame_0));
EXPECT_EQ(
CONTENT_SETTING_ASK,
GetGeolocationContentSetting(requesting_frame_1, requesting_frame_0));
}
TEST_P(GeolocationPermissionContextParamTests, LastUsageAudited) {
GURL requesting_frame("http://www.example.com/geolocation");
NavigateAndCommit(requesting_frame);
if (BubbleEnabled()) BubbleManagerDocumentLoadCompleted();
base::SimpleTestClock* test_clock = new base::SimpleTestClock;
test_clock->SetNow(base::Time::UnixEpoch() +
base::TimeDelta::FromSeconds(10));
HostContentSettingsMap* map = profile()->GetHostContentSettingsMap();
map->SetPrefClockForTesting(scoped_ptr<base::Clock>(test_clock));
// The permission shouldn't have been used yet.
EXPECT_EQ(map->GetLastUsage(requesting_frame.GetOrigin(),
requesting_frame.GetOrigin(),
CONTENT_SETTINGS_TYPE_GEOLOCATION).ToDoubleT(),
0);
ASSERT_EQ(0U, GetNumberOfPrompts());
RequestGeolocationPermission(
web_contents(), RequestID(0), requesting_frame, false);
ASSERT_EQ(1U, GetNumberOfPrompts());
AcceptPrompt();
CheckTabContentsState(requesting_frame, CONTENT_SETTING_ALLOW);
CheckPermissionMessageSent(0, true);
// Permission has been used at the starting time.
EXPECT_EQ(map->GetLastUsage(requesting_frame.GetOrigin(),
requesting_frame.GetOrigin(),
CONTENT_SETTINGS_TYPE_GEOLOCATION).ToDoubleT(),
10);
test_clock->Advance(base::TimeDelta::FromSeconds(3));
RequestGeolocationPermission(
web_contents(), RequestID(0), requesting_frame, false);
// Permission has been used three seconds later.
EXPECT_EQ(map->GetLastUsage(requesting_frame.GetOrigin(),
requesting_frame.GetOrigin(),
CONTENT_SETTINGS_TYPE_GEOLOCATION).ToDoubleT(),
13);
}
TEST_P(GeolocationPermissionContextParamTests, LastUsageAuditedMultipleFrames) {
base::SimpleTestClock* test_clock = new base::SimpleTestClock;
test_clock->SetNow(base::Time::UnixEpoch() +
base::TimeDelta::FromSeconds(10));
HostContentSettingsMap* map = profile()->GetHostContentSettingsMap();
map->SetPrefClockForTesting(scoped_ptr<base::Clock>(test_clock));
GURL requesting_frame_0("http://www.example.com/geolocation");
GURL requesting_frame_1("http://www.example-2.com/geolocation");
// The permission shouldn't have been used yet.
EXPECT_EQ(map->GetLastUsage(requesting_frame_0.GetOrigin(),
requesting_frame_0.GetOrigin(),
CONTENT_SETTINGS_TYPE_GEOLOCATION).ToDoubleT(),
0);
EXPECT_EQ(map->GetLastUsage(requesting_frame_1.GetOrigin(),
requesting_frame_0.GetOrigin(),
CONTENT_SETTINGS_TYPE_GEOLOCATION).ToDoubleT(),
0);
NavigateAndCommit(requesting_frame_0);
if (BubbleEnabled()) BubbleManagerDocumentLoadCompleted();
EXPECT_EQ(0U, GetNumberOfPrompts());
// Request permission for two frames.
RequestGeolocationPermission(
web_contents(), RequestID(0), requesting_frame_0, false);
RequestGeolocationPermission(
web_contents(), RequestID(1), requesting_frame_1, false);
// Ensure only one infobar is created.
ASSERT_EQ(1U, GetNumberOfPrompts());
// Accept the first frame.
AcceptPrompt();
if (!BubbleEnabled())
infobar_service()->RemoveInfoBar(infobar_service()->infobar_at(0));
CheckTabContentsState(requesting_frame_0, CONTENT_SETTING_ALLOW);
CheckPermissionMessageSent(0, true);
// Verify that accepting the first didn't accept because it's embedded
// in the other.
EXPECT_EQ(map->GetLastUsage(requesting_frame_0.GetOrigin(),
requesting_frame_0.GetOrigin(),
CONTENT_SETTINGS_TYPE_GEOLOCATION).ToDoubleT(),
10);
EXPECT_EQ(map->GetLastUsage(requesting_frame_1.GetOrigin(),
requesting_frame_0.GetOrigin(),
CONTENT_SETTINGS_TYPE_GEOLOCATION).ToDoubleT(),
0);
ASSERT_EQ(1U, GetNumberOfPrompts());
test_clock->Advance(base::TimeDelta::FromSeconds(1));
// Allow the second frame.
AcceptPrompt();
CheckTabContentsState(requesting_frame_1, CONTENT_SETTING_ALLOW);
CheckPermissionMessageSent(1, true);
if (!BubbleEnabled())
infobar_service()->RemoveInfoBar(infobar_service()->infobar_at(0));
// Verify that the times are different.
EXPECT_EQ(map->GetLastUsage(requesting_frame_0.GetOrigin(),
requesting_frame_0.GetOrigin(),
CONTENT_SETTINGS_TYPE_GEOLOCATION).ToDoubleT(),
10);
EXPECT_EQ(map->GetLastUsage(requesting_frame_1.GetOrigin(),
requesting_frame_0.GetOrigin(),
CONTENT_SETTINGS_TYPE_GEOLOCATION).ToDoubleT(),
11);
test_clock->Advance(base::TimeDelta::FromSeconds(2));
RequestGeolocationPermission(
web_contents(), RequestID(0), requesting_frame_0, false);
// Verify that requesting permission in one frame doesn't update other where
// it is the embedder.
EXPECT_EQ(map->GetLastUsage(requesting_frame_0.GetOrigin(),
requesting_frame_0.GetOrigin(),
CONTENT_SETTINGS_TYPE_GEOLOCATION).ToDoubleT(),
13);
EXPECT_EQ(map->GetLastUsage(requesting_frame_1.GetOrigin(),
requesting_frame_0.GetOrigin(),
CONTENT_SETTINGS_TYPE_GEOLOCATION).ToDoubleT(),
11);
}
INSTANTIATE_TEST_CASE_P(GeolocationPermissionContextTestsWithAndWithoutBubbles,
GeolocationPermissionContextParamTests,
::testing::Values(false, true));
| bsd-3-clause |
hoangt/djinn | tonic-suite/asr/src/transform/fmllr-raw.cc | 21344 | // transform/fmllr-raw.cc
// Copyright 2013 Johns Hopkins University (author: Daniel Povey)
// See ../../COPYING for clarification regarding multiple authors
//
// 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
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#include <utility>
#include <vector>
using std::vector;
#include "transform/fmllr-raw.h"
#include "transform/fmllr-diag-gmm.h"
namespace kaldi {
FmllrRawAccs::FmllrRawAccs(int32 raw_dim, int32 model_dim,
const Matrix<BaseFloat> &full_transform)
: raw_dim_(raw_dim), model_dim_(model_dim) {
if (full_transform.NumCols() != full_transform.NumRows() &&
full_transform.NumCols() != full_transform.NumRows() + 1) {
KALDI_ERR << "Expecting full LDA+MLLT transform to be square or d by d+1 "
<< "(make sure you are including rejected rows).";
}
if (raw_dim <= 0 || full_transform.NumRows() % raw_dim != 0)
KALDI_ERR << "Raw feature dimension is invalid " << raw_dim
<< "(must be positive and divide feature dimension)";
int32 full_dim = full_transform.NumRows();
full_transform_ = full_transform.Range(0, full_dim, 0, full_dim);
transform_offset_.Resize(full_dim);
if (full_transform_.NumCols() == full_dim + 1)
transform_offset_.CopyColFromMat(full_transform_, full_dim);
int32 full_dim2 = ((full_dim + 1) * (full_dim + 2)) / 2;
count_ = 0.0;
temp_.Resize(full_dim + 1);
Q_.Resize(model_dim + 1, full_dim + 1);
S_.Resize(model_dim + 1, full_dim2);
single_frame_stats_.s.Resize(full_dim + 1);
single_frame_stats_.transformed_data.Resize(full_dim);
single_frame_stats_.count = 0.0;
single_frame_stats_.a.Resize(model_dim);
single_frame_stats_.b.Resize(model_dim);
}
bool FmllrRawAccs::DataHasChanged(const VectorBase<BaseFloat> &data) const {
KALDI_ASSERT(data.Dim() == FullDim());
return !data.ApproxEqual(single_frame_stats_.s.Range(0, FullDim()), 0.0);
}
void FmllrRawAccs::CommitSingleFrameStats() {
// Commit the stats for this from (in SingleFrameStats).
int32 model_dim = ModelDim(), full_dim = FullDim();
SingleFrameStats &stats = single_frame_stats_;
if (stats.count == 0.0) return;
count_ += stats.count;
// a_ext and b_ext are a and b extended with the count,
// which we'll later use to reconstruct the full stats for
// the rejected dimensions.
Vector<double> a_ext(model_dim + 1), b_ext(model_dim + 1);
a_ext.Range(0, model_dim).CopyFromVec(stats.a);
b_ext.Range(0, model_dim).CopyFromVec(stats.b);
a_ext(model_dim) = stats.count;
b_ext(model_dim) = stats.count;
Q_.AddVecVec(1.0, a_ext, Vector<double>(stats.s));
temp_.SetZero();
temp_.AddVec2(1.0, stats.s);
int32 full_dim2 = ((full_dim + 1) * (full_dim + 2)) / 2;
SubVector<double> temp_vec(temp_.Data(), full_dim2);
S_.AddVecVec(1.0, b_ext, temp_vec);
}
void FmllrRawAccs::InitSingleFrameStats(const VectorBase<BaseFloat> &data) {
SingleFrameStats &stats = single_frame_stats_;
int32 full_dim = FullDim();
KALDI_ASSERT(data.Dim() == full_dim);
stats.s.Range(0, full_dim).CopyFromVec(data);
stats.s(full_dim) = 1.0;
stats.transformed_data.AddMatVec(1.0, full_transform_, kNoTrans, data, 0.0);
stats.transformed_data.AddVec(1.0, transform_offset_);
stats.count = 0.0;
stats.a.SetZero();
stats.b.SetZero();
}
BaseFloat FmllrRawAccs::AccumulateForGmm(const DiagGmm &gmm,
const VectorBase<BaseFloat> &data,
BaseFloat weight) {
int32 model_dim = ModelDim(), full_dim = FullDim();
KALDI_ASSERT(data.Dim() == full_dim &&
"Expect raw, spliced data, which should have same dimension as "
"full transform.");
if (DataHasChanged(data)) {
// this is part of our mechanism to accumulate certain sub-parts of
// the computation for each frame, to avoid excessive compute.
CommitSingleFrameStats();
InitSingleFrameStats(data);
}
SingleFrameStats &stats = single_frame_stats_;
SubVector<BaseFloat> projected_data(stats.transformed_data, 0, model_dim);
int32 num_gauss = gmm.NumGauss();
Vector<BaseFloat> posterior(num_gauss);
BaseFloat log_like = gmm.ComponentPosteriors(projected_data, &posterior);
posterior.Scale(weight);
// Note: AccumulateFromPosteriors takes the original, spliced data,
// and returns the log-like of the rejected dimensions.
AccumulateFromPosteriors(gmm, data, posterior);
// Add the likelihood of the rejected dimensions to the objective function
// (assume zero-mean, unit-variance Gaussian; the LDA should have any offset
// required to ensure this).
if (full_dim > model_dim) {
SubVector<BaseFloat> rejected_data(stats.transformed_data, model_dim,
full_dim - model_dim);
log_like += -0.5 * (VecVec(rejected_data, rejected_data) +
(full_dim - model_dim) * M_LOG_2PI);
}
return log_like;
}
/*
// Extended comment here.
//
// Let x_t(i) be the fully processed feature, dimension i (with fMLLR
transform
// and LDA transform), but *without* any offset term from the LDA, which
// it's more convenient to view as an offset in the model.
//
//
// For a given dimension i (either accepted or rejected), the auxf can
// be expressed as a quadratic function of x_t(i). We ultimately will want to
// express x_t(i) as a linear function of the parameters of the linearized
// fMLLR transform matrix. Some notation:
// Let l be the linearized transform matrix, i.e. the concatenation of the
// m rows, each of length m+1, of the fMLLR transform.
// Let n be the number of frames we splice together each time.
// Let s_t be the spliced-together features on time t, with a one appended;
// it will have n blocks each of size m, followed by a 1. (dim is n*m +
1).
//
// x(i) [note, this is the feature without any LDA offset], is bilinear in the
// transform matrix and the features, so:
//
// x(i) = l^T M_i s_t, where s_t is the spliced features on time t,
// with a 1 appended
// [we need to compute M_i but we know the function is bilinear so it
exists].
//
// The auxf can be written as:
// F = sum_i sum_t a_{ti} x(i) - 0.5 b_{ti} x(i)^2
// = sum_i sum_t a_{ti} x(i) - 0.5 b_{ti} x(i)^2
// = sum_i sum_t a_{ti} (l^T M_i s_t) - 0.5 b_{ti} (l^T M_i s_t )^2
// = sum_i l^T M_i q_i + l^T M_i S_i M_i^T l
// where
// q_i = sum_t a_{ti} s_t, and
// S_i = sum_t b_{ti} s_t s_t^T
// [Note that we only need store S_i for the model-dim plus one, because
// all the rejected dimensions have the same value]
//
// We define a matrix Q whose rows are q_d, with
// Q = \sum_t d_t s_t^T
// [The Q we actually store as stats will use a modified form of d that
// has a 1 for all dimensions past the model dim, to avoid redundancy;
// we'll reconstruct the true Q from this later on.]
//
//
// What is M_i? Working it out is a little tedious.
// Note: each M_i (from i = 0 ... full_dim) is of
// dimension (raw_dim*(raw_dim+1)) by full_dim + 1
//
// We want to express x(i) [we forget the subscript "t" sometimes],
// as a bilinear function of l and s_t.
// We have x(i) = l^T M_i s.
//
// The (j,k)'th component of M_i is the term in x(i) that corresponds to the
j'th
// component of l and the k'th of s.
// Before defining M_i, let us define N_i, where l^t N_i s will equal the
spliced and
// transformed pre-LDA features of dimension i. the N's have the same
dimensions as the
// M's.
//
// We'll first define the j,k'th component of N_i, as this is easier; we'll
then define the M_i
// as combinations of N_i.
//
// For a given i, j and k, the value of n_{i,j,k} will be as follows:
// We first decompose index j into j1, j2 (both functions of
// the original index j), where
// j1 corresponds to the row-index of the fMLLR transform, j2 to the
col-index.
// We next decompose i into i1, i2, where i1 corresponds to the splicing
number
// (0...n-1), and i2 corresponds to the cepstral index.
//
// If (j1 != i2) then n_{ijk} == 0.
//
// Elsif k corresponds to the last element [i.e. k == m * n], then this
m_{ijk} corresponds
// to the effect of the j'th component of l for zero input, so:
// If j2 == m (i.e. this the offset term in the fMLLR matrix), then
// n_{ijk} = 1.0,
// Else
// n_{ijk} = 0.0
// Fi
//
// Else:
// Decompose k into k1, k2, where k1 = 0.. n-1 is the splicing index, and
k2 = 0...m-1 is
// the cepstral index.
// If k1 != i1 then
// n_{ijk} = 0.0
// elsif k2 != j2 then
// n_{ijk} = 0.0
// else
// n_{ijk} = 1.0
// fi
// Endif
// Now, M_i will be defined as sum_i T_{ij} N_j, where T_{ij} are the
elements of the
// LDA+MLLT transform (but excluding any linear offset, which gets
accounted for by
// c_i, above).
//
// Now suppose we want to express the auxiliary function in a simpler form
// as l^T v - 0.5 l^T W l, where v and W are the "simple" linear and
quadratic stats,
// we can do so with:
// v = \sum_i M_i q_i
// and
// W = \sum_i M_i S_i M_i^T
//
*/
void FmllrRawAccs::AccumulateFromPosteriors(
const DiagGmm &diag_gmm, const VectorBase<BaseFloat> &data,
const VectorBase<BaseFloat> &posterior) {
// The user may call this function directly, even though we also
// call it from AccumulateForGmm(), so check again:
if (DataHasChanged(data)) {
CommitSingleFrameStats();
InitSingleFrameStats(data);
}
int32 model_dim = ModelDim();
SingleFrameStats &stats = single_frame_stats_;
// The quantities a and b describe the diagonal auxiliary function
// for each of the retained dimensions in the transformed space--
// in the format F = \sum_d alpha(d) x(d) -0.5 beta(d) x(d)^2,
// where x(d) is the d'th dimensional fully processed feature.
// For d, see the comment-- it's alpha processed to take into
// account any offset in the LDA. Note that it's a reference.
//
Vector<double> a(model_dim), b(model_dim);
int32 num_comp = diag_gmm.NumGauss();
double count = 0.0; // data-count contribution from this frame.
// Note: we could do this using matrix-matrix operations instead of
// row by row. In the end it won't really matter as this is not
// the slowest part of the computation.
for (size_t m = 0; m < num_comp; m++) {
BaseFloat this_post = posterior(m);
if (this_post != 0.0) {
count += this_post;
a.AddVec(this_post, diag_gmm.means_invvars().Row(m));
b.AddVec(this_post, diag_gmm.inv_vars().Row(m));
}
}
// Correct "a" for any offset term in the LDA transform-- we view it as
// the opposite offset in the model [note: we'll handle the rejected
// dimensions
// in update time.] Here, multiplying the element of "b" (which is the
// weighted inv-vars) by transform_offset_, and subtracting the result from
// a, is like subtracting the transform-offset from the original means
// (because a contains the means times inv-vars_.
Vector<double> offset(transform_offset_.Range(0, model_dim));
a.AddVecVec(-1.0, b, offset, 1.0);
stats.a.AddVec(1.0, a);
stats.b.AddVec(1.0, b);
stats.count += count;
}
void FmllrRawAccs::Update(const FmllrRawOptions &opts,
MatrixBase<BaseFloat> *raw_fmllr_mat,
BaseFloat *objf_impr, BaseFloat *count) {
// First commit any pending stats from the last frame.
if (single_frame_stats_.count != 0.0) CommitSingleFrameStats();
if (this->count_ < opts.min_count) {
KALDI_WARN << "Not updating (raw) fMLLR since count " << this->count_
<< " is less than min count " << opts.min_count;
*objf_impr = 0.0;
*count = this->count_;
return;
}
KALDI_ASSERT(raw_fmllr_mat->NumRows() == RawDim() &&
raw_fmllr_mat->NumCols() == RawDim() + 1 &&
!raw_fmllr_mat->IsZero());
Matrix<double> fmllr_mat(
*raw_fmllr_mat); // temporary, double-precision version
// of matrix.
Matrix<double> linear_stats; // like K in diagonal update.
std::vector<SpMatrix<double> > diag_stats; // like G in diagonal update.
// Note: we will invert these.
std::vector<std::vector<Matrix<double> > > off_diag_stats; // these will
// contribute to the linear term.
Vector<double> simple_linear_stats;
SpMatrix<double> simple_quadratic_stats;
ConvertToSimpleStats(&simple_linear_stats, &simple_quadratic_stats);
ConvertToPerRowStats(simple_linear_stats, simple_quadratic_stats,
&linear_stats, &diag_stats, &off_diag_stats);
try {
for (size_t i = 0; i < diag_stats.size(); i++) {
diag_stats[i].Invert();
}
} catch (...) {
KALDI_WARN << "Error inverting stats matrices for fMLLR "
<< "[min-count too small? Bad data?], not updating.";
return;
}
int32 raw_dim = RawDim(), splice_width = SpliceWidth();
double effective_beta = count_ * splice_width; // We "count" the determinant
// splice_width times in the objective function.
double auxf_orig =
GetAuxf(simple_linear_stats, simple_quadratic_stats, fmllr_mat);
for (int32 iter = 0; iter < opts.num_iters; iter++) {
for (int32 row = 0; row < raw_dim; row++) {
SubVector<double> this_row(fmllr_mat, row);
Vector<double> this_linear(raw_dim + 1); // Here, k_i is the linear term
// in the auxf expressed as a function of this row.
this_linear.CopyFromVec(linear_stats.Row(row));
for (int32 row2 = 0; row2 < raw_dim; row2++) {
if (row2 != row) {
if (row2 < row) {
this_linear.AddMatVec(-1.0, off_diag_stats[row][row2], kNoTrans,
fmllr_mat.Row(row2), 1.0);
} else {
// We won't have the element [row][row2] stored, but use symmetry.
this_linear.AddMatVec(-1.0, off_diag_stats[row2][row], kTrans,
fmllr_mat.Row(row2), 1.0);
}
}
}
FmllrInnerUpdate(diag_stats[row], this_linear, effective_beta, row,
&fmllr_mat);
}
if (GetVerboseLevel() >= 2) {
double cur_auxf = GetAuxf(simple_linear_stats, simple_quadratic_stats,
fmllr_mat),
auxf_change = cur_auxf - auxf_orig;
KALDI_VLOG(2) << "Updating raw fMLLR: objf improvement per frame was "
<< (auxf_change / this->count_) << " over " << this->count_
<< " frames, by the " << iter << "'th iteration";
}
}
double auxf_final =
GetAuxf(simple_linear_stats, simple_quadratic_stats, fmllr_mat),
auxf_change = auxf_final - auxf_orig;
*count = this->count_;
KALDI_VLOG(1) << "Updating raw fMLLR: objf improvement per frame was "
<< (auxf_change / this->count_) << " over " << this->count_
<< " frames.";
if (auxf_final > auxf_orig) {
*objf_impr = auxf_change;
*count = this->count_;
raw_fmllr_mat->CopyFromMat(fmllr_mat);
} else {
*objf_impr = 0.0;
// don't update "raw_fmllr_mat"
}
}
void FmllrRawAccs::SetZero() {
count_ = 0.0;
single_frame_stats_.count = 0.0;
single_frame_stats_.s.SetZero();
Q_.SetZero();
S_.SetZero();
}
// Compute the M_i quantities, needed in the update. This function could be
// greatly speeded up but I don't think it's the limiting factor.
void FmllrRawAccs::ComputeM(std::vector<Matrix<double> > *M) const {
int32 full_dim = FullDim(), raw_dim = RawDim(),
raw_dim2 = raw_dim * (raw_dim + 1);
M->resize(full_dim);
for (int32 i = 0; i < full_dim; i++) (*M)[i].Resize(raw_dim2, full_dim + 1);
// the N's are simpler matrices from which we'll interpolate the M's.
// In this loop we imagine w are computing the vector of N's, but
// when we get each element, if it's nonzero we propagate it straight
// to the M's.
for (int32 i = 0; i < full_dim; i++) {
// i is index after fMLLR transform; i1 is splicing index,
// i2 is cepstral index.
int32 i1 = i / raw_dim, i2 = i % raw_dim;
for (int32 j = 0; j < raw_dim2; j++) {
// j1 is row-index of fMLLR transform, j2 is column-index
int32 j1 = j / (raw_dim + 1), j2 = j % (raw_dim + 1);
for (int32 k = 0; k < full_dim + 1; k++) {
BaseFloat n_ijk;
if (j1 != i2) {
n_ijk = 0.0;
} else if (k == full_dim) {
if (j2 == raw_dim) // offset term in fMLLR matrix.
n_ijk = 1.0;
else
n_ijk = 0.0;
} else {
// k1 is splicing index, k2 is cepstral idnex.
int32 k1 = k / raw_dim, k2 = k % raw_dim;
if (k1 != i1 || k2 != j2)
n_ijk = 0.0;
else
n_ijk = 1.0;
}
if (n_ijk != 0.0)
for (int32 l = 0; l < full_dim; l++)
(*M)[l](j, k) += n_ijk * full_transform_(l, i);
}
}
}
}
void FmllrRawAccs::ConvertToSimpleStats(
Vector<double> *simple_linear_stats,
SpMatrix<double> *simple_quadratic_stats) const {
std::vector<Matrix<double> > M;
ComputeM(&M);
int32 full_dim = FullDim(), raw_dim = RawDim(), model_dim = ModelDim(),
raw_dim2 = raw_dim * (raw_dim + 1),
full_dim2 = ((full_dim + 1) * (full_dim + 2)) / 2;
simple_linear_stats->Resize(raw_dim2);
simple_quadratic_stats->Resize(raw_dim2);
for (int32 i = 0; i < full_dim; i++) {
Vector<double> q_i(full_dim + 1);
SpMatrix<double> S_i(full_dim + 1);
SubVector<double> S_i_vec(S_i.Data(), full_dim2);
if (i < model_dim) {
q_i.CopyFromVec(Q_.Row(i));
S_i_vec.CopyFromVec(S_.Row(i));
} else {
q_i.CopyFromVec(
Q_.Row(model_dim)); // The last row contains stats proportional
// to "count", which we need to modify to be correct.
q_i.Scale(
-transform_offset_(i)); // These stats are zero (corresponding to
// a zero-mean model) if there is no offset in the LDA transform. Note:
// the two statements above are the equivalent, for the rejected dims,
// of the statement "a.AddVecVec(-1.0, b, offset);" for the kept ones.
//
S_i_vec.CopyFromVec(S_.Row(model_dim)); // these are correct, and
// all the same (corresponds to unit variance).
}
// The equation v = \sum_i M_i q_i:
simple_linear_stats->AddMatVec(1.0, M[i], kNoTrans, q_i, 1.0);
// The equation W = \sum_i M_i S_i M_i^T
// Here, M[i] is quite sparse, so AddSmat2Sp will be faster.
simple_quadratic_stats->AddSmat2Sp(1.0, M[i], kNoTrans, S_i, 1.0);
}
}
// See header for comment.
void FmllrRawAccs::ConvertToPerRowStats(
const Vector<double> &simple_linear_stats,
const SpMatrix<double> &simple_quadratic_stats_sp,
Matrix<double> *linear_stats, std::vector<SpMatrix<double> > *diag_stats,
std::vector<std::vector<Matrix<double> > > *off_diag_stats) const {
// get it as a Matrix, which makes it easier to extract sub-parts.
Matrix<double> simple_quadratic_stats(simple_quadratic_stats_sp);
linear_stats->Resize(RawDim(), RawDim() + 1);
linear_stats->CopyRowsFromVec(simple_linear_stats);
diag_stats->resize(RawDim());
off_diag_stats->resize(RawDim());
// Set *diag_stats
int32 rd1 = RawDim() + 1;
for (int32 i = 0; i < RawDim(); i++) {
SubMatrix<double> this_diag(simple_quadratic_stats, i * rd1, rd1, i * rd1,
rd1);
(*diag_stats)[i].Resize(RawDim() + 1);
(*diag_stats)[i].CopyFromMat(this_diag, kTakeMean);
}
for (int32 i = 0; i < RawDim(); i++) {
(*off_diag_stats)[i].resize(i);
for (int32 j = 0; j < i; j++) {
SubMatrix<double> this_off_diag(simple_quadratic_stats, i * rd1, rd1,
j * rd1, rd1);
(*off_diag_stats)[i][j] = this_off_diag;
}
}
}
double FmllrRawAccs::GetAuxf(const Vector<double> &simple_linear_stats,
const SpMatrix<double> &simple_quadratic_stats,
const Matrix<double> &fmllr_mat) const {
// linearize transform...
int32 raw_dim = RawDim(), spice_width = SpliceWidth();
Vector<double> fmllr_vec(raw_dim * (raw_dim + 1));
fmllr_vec.CopyRowsFromMat(fmllr_mat);
SubMatrix<double> square_part(fmllr_mat, 0, raw_dim, 0, raw_dim);
double logdet = square_part.LogDet();
return VecVec(fmllr_vec, simple_linear_stats) -
0.5 * VecSpVec(fmllr_vec, simple_quadratic_stats, fmllr_vec) +
logdet * spice_width * count_;
}
} // namespace kaldi
| bsd-3-clause |
leighpauls/k2cro4 | content/test/data/layout_tests/LayoutTests/storage/indexeddb/resources/transaction-abort.js | 2204 | if (this.importScripts) {
importScripts('../../../fast/js/resources/js-test-pre.js');
importScripts('shared.js');
}
description("Test transaction aborts send the proper onabort messages..");
indexedDBTest(prepareDatabase, startTest);
function prepareDatabase()
{
db = event.target.result;
store = evalAndLog("store = db.createObjectStore('storeName', null)");
request = evalAndLog("store.add({x: 'value', y: 'zzz'}, 'key')");
request.onerror = unexpectedErrorCallback;
}
function startTest()
{
trans = evalAndLog("trans = db.transaction(['storeName'], 'readwrite')");
evalAndLog("trans.onabort = transactionAborted");
evalAndLog("trans.oncomplete = unexpectedCompleteCallback");
store = evalAndLog("store = trans.objectStore('storeName')");
request = evalAndLog("store.add({x: 'value2', y: 'zzz2'}, 'key2')");
request.onerror = firstAdd;
request.onsuccess = unexpectedSuccessCallback;
request = evalAndLog("store.add({x: 'value3', y: 'zzz3'}, 'key3')");
request.onerror = secondAdd;
request.onsuccess = unexpectedSuccessCallback;
trans.abort();
firstError = false;
secondError = false;
abortFired = false;
}
function firstAdd()
{
shouldBe("event.target.error.name", "'AbortError'");
shouldBeNull("trans.error");
shouldBeFalse("firstError");
shouldBeFalse("secondError");
shouldBeFalse("abortFired");
firstError = true;
evalAndExpectException("store.add({x: 'value4', y: 'zzz4'}, 'key4')", "0", "'TransactionInactiveError'");
}
function secondAdd()
{
shouldBe("event.target.error.name", "'AbortError'");
shouldBeNull("trans.error");
shouldBeTrue("firstError");
shouldBeFalse("secondError");
shouldBeFalse("abortFired");
secondError = true;
}
function transactionAborted()
{
shouldBeTrue("firstError");
shouldBeTrue("secondError");
shouldBeFalse("abortFired");
shouldBeNull("trans.error");
abortFired = true;
evalAndExpectException("store.add({x: 'value5', y: 'zzz5'}, 'key5')", "0", "'TransactionInactiveError'");
evalAndExpectException("trans.abort()", "DOMException.INVALID_STATE_ERR", "'InvalidStateError'");
finishJSTest();
}
| bsd-3-clause |
XiaosongWei/blink-crosswalk | Source/modules/webcl/WebCLObject.cpp | 970 | // Copyright (C) 2015 Intel Corporation All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "config.h"
#if ENABLE(WEBCL)
#include "modules/webcl/WebCLContext.h"
#include "modules/webcl/WebCLObject.h"
namespace blink {
WebCLObject::~WebCLObject()
{
if (m_context)
m_context->untrackReleaseableWebCLObject(createWeakPtr());
}
WebCLObject::WebCLObject(WebCLContext* context)
: m_weakFactory(this)
, m_context(context)
{
ASSERT(m_context);
m_context->trackReleaseableWebCLObject(createWeakPtr());
}
WebCLObject::WebCLObject()
: m_weakFactory(this)
, m_context(nullptr)
{
}
WebCLContext* WebCLObject::context()
{
ASSERT(m_context);
return m_context;
}
void WebCLObject::setContext(WebCLContext* context)
{
m_context = context;
m_context->trackReleaseableWebCLObject(createWeakPtr());
}
} // namespace blink
#endif // ENABLE(WEBCL)
| bsd-3-clause |
arirubinstein/ThreatExchange | scripts/get_compromised_credentials.py | 2285 | #!/usr/bin/env python
import argparse
import time
from pytx import ThreatIndicator
from pytx.vocabulary import ThreatExchange as te
from pytx.vocabulary import ThreatType as tt
from pytx.vocabulary import Types as t
def get_results(options):
'''
Builds a query string based on the specified options and runs it.
'''
if options.since is None or options.until is None:
raise Exception('You must specify both "since" and "until" values')
results = ThreatIndicator.objects(threat_type=tt.COMPROMISED_CREDENTIAL, type_=t.EMAIL_ADDRESS, limit=options.limit,
fields=['indicator', 'passwords'], since=options.since, until=options.until)
return results
def process_result(handle, result):
'''
Process the threat indicators received from the server. This version
writes the indicators to the output file specified by 'handle', if any.
Indicators are written one per line.
'''
for password in result.passwords:
output = '%s:%s\n' % (result.indicator, password)
if handle is None:
print output,
else:
handle.write(output)
def run_query(options, handle):
start = int(time.time())
print 'READING %s%s' % (te.URL, te.THREAT_INDICATORS)
results = get_results(options)
count = 0
for result in results:
process_result(handle, result)
count += 1
end = int(time.time())
print ('SUCCESS: Got %d indicators in %d seconds' %
(count, end - start))
return
def get_args():
parser = argparse.ArgumentParser(description='Query ThreatExchange for Compromised Credentials')
parser.add_argument('-o', '--output', default='/dev/stdout',
help='[OPTIONAL] output file path.')
parser.add_argument('-s', '--since',
help='[OPTIONAL] Start time for search')
parser.add_argument('-u', '--until',
help='[OPTIONAL] End time for search')
parser.add_argument('-l', '--limit',
help='[OPTIONAL] Maximum number of results')
return parser.parse_args()
def main():
args = get_args()
with open(args.output, 'w') as fp:
run_query(args, fp)
if __name__ == '__main__':
main()
| bsd-3-clause |
endlessm/chromium-browser | third_party/llvm/libcxx/www/index.html | 10074 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<!-- Material used from: HTML 4.01 specs: http://www.w3.org/TR/html401/ -->
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>"libc++" C++ Standard Library</title>
<link type="text/css" rel="stylesheet" href="menu.css">
<link type="text/css" rel="stylesheet" href="content.css">
</head>
<body>
<div id="menu">
<div>
<a href="https://llvm.org/">LLVM Home</a>
</div>
<div class="submenu">
<label>libc++ Info</label>
<a href="/index.html">About</a>
</div>
<div class="submenu">
<label>Quick Links</label>
<a href="https://libcxxabi.llvm.org/">libc++abi</a>
<a href="https://lists.llvm.org/mailman/listinfo/libcxx-dev">libcxx-dev</a>
<a href="https://lists.llvm.org/mailman/listinfo/libcxx-commits">libcxx-commits</a>
<a href="https://bugs.llvm.org/">Bug Reports</a>
<a href="https://github.com/llvm/llvm-project/tree/master/libcxx/">Browse Sources</a>
</div>
</div>
<div id="content">
<!--*********************************************************************-->
<h1>"libc++" C++ Standard Library</h1>
<!--*********************************************************************-->
<p>libc++ is an implementation of the C++ standard library, targeting
C++11, C++14 and above.</p>
<p>All of the code in libc++ is <a
href="https://llvm.org/docs/DeveloperPolicy.html#copyright-license-and-patents">dual licensed</a>
under the MIT license and the UIUC License (a BSD-like license).</p>
<!--=====================================================================-->
<h2>New Documentation Coming Soon!</h2>
<!--=====================================================================-->
<p> Looking for documentation on how to use, build and test libc++? If so
checkout the new libc++ documentation.</p>
<p><a href="https://libcxx.llvm.org/docs/">
Click here for the new libc++ documentation.</a></p>
<!--=====================================================================-->
<h2 id="goals">Features and Goals</h2>
<!--=====================================================================-->
<ul>
<li>Correctness as defined by the C++11 standard.</li>
<li>Fast execution.</li>
<li>Minimal memory use.</li>
<li>Fast compile times.</li>
<li>ABI compatibility with gcc's libstdc++ for some low-level features
such as exception objects, rtti and memory allocation.</li>
<li>Extensive unit tests.</li>
</ul>
<!--=====================================================================-->
<h2 id="why">Why a new C++ Standard Library for C++11?</h2>
<!--=====================================================================-->
<p>After its initial introduction, many people have asked "why start a new
library instead of contributing to an existing library?" (like Apache's
libstdcxx, GNU's libstdc++, STLport, etc). There are many contributing
reasons, but some of the major ones are:</p>
<ul>
<li><p>From years of experience (including having implemented the standard
library before), we've learned many things about implementing
the standard containers which require ABI breakage and fundamental changes
to how they are implemented. For example, it is generally accepted that
building std::string using the "short string optimization" instead of
using Copy On Write (COW) is a superior approach for multicore
machines (particularly in C++11, which has rvalue references). Breaking
ABI compatibility with old versions of the library was
determined to be critical to achieving the performance goals of
libc++.</p></li>
<li><p>Mainline libstdc++ has switched to GPL3, a license which the developers
of libc++ cannot use. libstdc++ 4.2 (the last GPL2 version) could be
independently extended to support C++11, but this would be a fork of the
codebase (which is often seen as worse for a project than starting a new
independent one). Another problem with libstdc++ is that it is tightly
integrated with G++ development, tending to be tied fairly closely to the
matching version of G++.</p>
</li>
<li><p>STLport and the Apache libstdcxx library are two other popular
candidates, but both lack C++11 support. Our experience (and the
experience of libstdc++ developers) is that adding support for C++11 (in
particular rvalue references and move-only types) requires changes to
almost every class and function, essentially amounting to a rewrite.
Faced with a rewrite, we decided to start from scratch and evaluate every
design decision from first principles based on experience.</p>
<p>Further, both projects are apparently abandoned: STLport 5.2.1 was
released in Oct'08, and STDCXX 4.2.1 in May'08.</p>
</ul>
<!--=====================================================================-->
<h2 id="requirements">Platform Support</h2>
<!--=====================================================================-->
<p>
libc++ is known to work on the following platforms, using g++ and
clang. Note that functionality provided by <atomic> is only functional with
clang.
</p>
<ul>
<li>Mac OS X i386</li>
<li>Mac OS X x86_64</li>
<li>FreeBSD 10+ i386</li>
<li>FreeBSD 10+ x86_64</li>
<li>FreeBSD 10+ ARM</li>
<li>Linux i386</li>
<li>Linux x86_64</li>
</ul>
<!--=====================================================================-->
<h2 id="dir-structure">Current Status</h2>
<!--=====================================================================-->
<p>libc++ is a 100% complete C++11 implementation on Apple's OS X. </p>
<p>LLVM and Clang can self host in C++ and C++11 mode with libc++ on Linux.</p>
<p>libc++ is also a 100% complete C++14 implementation. A list of new features and
changes for C++14 can be found <a href="cxx1y_status.html">here</a>.</p>
<p>libc++'s C++17 implementation is not yet complete. A list of features and changes
for C++17 can be found <a href="cxx1z_status.html">here</a>.</p>
<p>A list of features and changes for the next C++ standard, known here as
"C++2a" (probably to be C++20) can be found <a href="cxx2a_status.html">here</a>.</p>
<p>Implementation of the post-C++14 Technical Specifications is in progress. A list of features
and the current status of these features can be found <a href="ts1z_status.html">here</a>.</p>
<p>As features get moved from the Technical Specifications into the main standard, we
will (after a period for migration) remove them from the TS implementation. This
process is detailed <a href="DesignDocs/ExperimentalFeatures.html">here</a>.</p>
<!--======================================================================-->
<h2 id="buildbots">Build Bots</h2>
<!--======================================================================-->
<p>The latest libc++ build results can be found at the following locations.</p>
<ul>
<li><a href="http://lab.llvm.org:8011/console">
Buildbot libc++ builders
</a></li>
<li><a href="http://lab.llvm.org:8080/green/view/Libcxx/">
Jenkins libc++ builders
</a></li>
</ul>
<!--=====================================================================-->
<h2>Get it and get involved!</h2>
<!--=====================================================================-->
<p>First please review our
<a href="https://llvm.org/docs/DeveloperPolicy.html">Developer's Policy</a>.
The documentation for building and using libc++ can be found below.
<ul>
<li><a href="https://libcxx.llvm.org/docs/UsingLibcxx.html">
<b>Using libc++</b></a>
Documentation on using the library in your programs</li>
<li><a href="https://libcxx.llvm.org/docs/BuildingLibcxx.html">
<b>Building libc++</b></a>
Documentation on building the library using CMake</li>
<li><a href="https://libcxx.llvm.org/docs/TestingLibcxx.html">
<b>Testing libc++</b></a>
Documentation for developers wishing to test the library</li>
</ul>
<!--=====================================================================-->
<h3>Notes and Known Issues</h3>
<!--=====================================================================-->
<p>
<ul>
<li>
Building libc++ with <code>-fno-rtti</code> is not supported. However
linking against it with <code>-fno-rtti</code> is supported.
</li>
</ul>
</p>
<p>Send discussions to the
<a href="https://lists.llvm.org/mailman/listinfo/libcxx-dev">libc++ mailing list</a>.</p>
<!--=====================================================================-->
<h2>Bug reports and patches</h2>
<!--=====================================================================-->
<p>
If you think you've found a bug in libc++, please report it using
the <a href="https://bugs.llvm.org/">LLVM Bugzilla</a>. If you're not sure, you
can post a message to the <a href="https://lists.llvm.org/mailman/listinfo/libcxx-dev">libcxx-dev</a>
mailing list or on IRC.
</p>
<p>
If you want to contribute a patch to libc++, the best place for that is
<a href="https://llvm.org/docs/Phabricator.html">Phabricator</a>. Please
add libcxx-commits as a subscriber.
</p>
<!--=====================================================================-->
<h2>Design Documents</h2>
<!--=====================================================================-->
<ul>
<li><a href="atomic_design.html"><tt><atomic></tt></a></li>
<li><a href="type_traits_design.html"><tt><type_traits></tt></a></li>
<li><a href="https://cplusplusmusings.wordpress.com/2012/07/05/clang-and-standard-libraries-on-mac-os-x/">Excellent notes by Marshall Clow</a></li>
</ul>
</div>
</body>
</html>
| bsd-3-clause |
cawka/packaging-ndn-cpp-dev | include/ndnboost/mpl/aux_/preprocessed/bcc_pre590/arg.hpp | 2771 |
// Copyright Peter Dimov 2001-2002
// Copyright Aleksey Gurtovoy 2001-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// *Preprocessed* version of the main "arg.hpp" header
// -- DO NOT modify by hand!
NDNBOOST_MPL_AUX_ADL_BARRIER_NAMESPACE_OPEN
template<> struct arg< -1 >
{
NDNBOOST_STATIC_CONSTANT(int, value = -1);
NDNBOOST_MPL_AUX_ARG_TYPEDEF(na, tag)
NDNBOOST_MPL_AUX_ARG_TYPEDEF(na, type)
template<
typename U1, typename U2, typename U3, typename U4, typename U5
>
struct apply
{
typedef U1 type;
NDNBOOST_MPL_AUX_ASSERT_NOT_NA(type);
};
};
template<> struct arg<1>
{
NDNBOOST_STATIC_CONSTANT(int, value = 1);
typedef arg<2> next;
NDNBOOST_MPL_AUX_ARG_TYPEDEF(na, tag)
NDNBOOST_MPL_AUX_ARG_TYPEDEF(na, type)
template<
typename U1, typename U2, typename U3, typename U4, typename U5
>
struct apply
{
typedef U1 type;
NDNBOOST_MPL_AUX_ASSERT_NOT_NA(type);
};
};
template<> struct arg<2>
{
NDNBOOST_STATIC_CONSTANT(int, value = 2);
typedef arg<3> next;
NDNBOOST_MPL_AUX_ARG_TYPEDEF(na, tag)
NDNBOOST_MPL_AUX_ARG_TYPEDEF(na, type)
template<
typename U1, typename U2, typename U3, typename U4, typename U5
>
struct apply
{
typedef U2 type;
NDNBOOST_MPL_AUX_ASSERT_NOT_NA(type);
};
};
template<> struct arg<3>
{
NDNBOOST_STATIC_CONSTANT(int, value = 3);
typedef arg<4> next;
NDNBOOST_MPL_AUX_ARG_TYPEDEF(na, tag)
NDNBOOST_MPL_AUX_ARG_TYPEDEF(na, type)
template<
typename U1, typename U2, typename U3, typename U4, typename U5
>
struct apply
{
typedef U3 type;
NDNBOOST_MPL_AUX_ASSERT_NOT_NA(type);
};
};
template<> struct arg<4>
{
NDNBOOST_STATIC_CONSTANT(int, value = 4);
typedef arg<5> next;
NDNBOOST_MPL_AUX_ARG_TYPEDEF(na, tag)
NDNBOOST_MPL_AUX_ARG_TYPEDEF(na, type)
template<
typename U1, typename U2, typename U3, typename U4, typename U5
>
struct apply
{
typedef U4 type;
NDNBOOST_MPL_AUX_ASSERT_NOT_NA(type);
};
};
template<> struct arg<5>
{
NDNBOOST_STATIC_CONSTANT(int, value = 5);
typedef arg<6> next;
NDNBOOST_MPL_AUX_ARG_TYPEDEF(na, tag)
NDNBOOST_MPL_AUX_ARG_TYPEDEF(na, type)
template<
typename U1, typename U2, typename U3, typename U4, typename U5
>
struct apply
{
typedef U5 type;
NDNBOOST_MPL_AUX_ASSERT_NOT_NA(type);
};
};
NDNBOOST_MPL_AUX_NONTYPE_ARITY_SPEC(1,int, arg)
NDNBOOST_MPL_AUX_ADL_BARRIER_NAMESPACE_CLOSE
| bsd-3-clause |
keishi/chromium | content/common/zygote_commands_linux.h | 1449 | // 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.
#ifndef CONTENT_COMMON_ZYGOTE_COMMANDS_LINUX_H_
#define CONTENT_COMMON_ZYGOTE_COMMANDS_LINUX_H_
namespace content {
// Contents of the initial message sent from the zygote to the browser when it
// is ready to go.
static const char kZygoteHelloMessage[] = "ZYGOTE_OK";
// File descriptors initialized by the Zygote Host
const int kZygoteSocketPairFd = 3;
const int kZygoteRendererSocketFd = 5;
// This file descriptor is special. It is passed to the Zygote and a setuid
// helper will be called to locate the process of the Zygote on the system.
// This mechanism is used when multiple PID namespaces exist because of the
// setuid sandbox.
// It is very important that this file descriptor does not exist in multiple
// processes.
// This number must be kept in sync in sandbox/linux/suid/sandbox.c
const int kZygoteIdFd = 7;
// These are the command codes used on the wire between the browser and the
// zygote.
enum {
// Fork off a new renderer.
kZygoteCommandFork = 0,
// Reap a renderer child.
kZygoteCommandReap = 1,
// Check what happend to a child process.
kZygoteCommandGetTerminationStatus = 2,
// Read a bitmask of kSandboxLinux*
kZygoteCommandGetSandboxStatus = 3
};
} // namespace content
#endif // CONTENT_COMMON_ZYGOTE_COMMANDS_LINUX_H_
| bsd-3-clause |
aospX/platform_external_libvpx | vp8/common/arm/neon/loopfiltersimpleverticaledge_neon.asm | 6188 | ;
; Copyright (c) 2010 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.
;
EXPORT |vp8_loop_filter_simple_vertical_edge_neon|
ARM
REQUIRE8
PRESERVE8
AREA ||.text||, CODE, READONLY, ALIGN=2
;Note: flimit, limit, and thresh should be positive numbers. All 16 elements in flimit
;are equal. So, in the code, only one load is needed
;for flimit. Same way applies to limit and thresh.
; r0 unsigned char *s,
; r1 int p, //pitch
; r2 const signed char *flimit,
; r3 const signed char *limit,
; stack(r4) const signed char *thresh,
; //stack(r5) int count --unused
|vp8_loop_filter_simple_vertical_edge_neon| PROC
sub r0, r0, #2 ; move src pointer down by 2 columns
vld4.8 {d6[0], d7[0], d8[0], d9[0]}, [r0], r1
vld1.s8 {d2[], d3[]}, [r2] ; flimit
vld1.s8 {d26[], d27[]}, [r3] ; limit -> q13
vld4.8 {d6[1], d7[1], d8[1], d9[1]}, [r0], r1
adr r12, vlfy_coeff
vld4.8 {d6[2], d7[2], d8[2], d9[2]}, [r0], r1
vld4.8 {d6[3], d7[3], d8[3], d9[3]}, [r0], r1
vld4.8 {d6[4], d7[4], d8[4], d9[4]}, [r0], r1
vld4.8 {d6[5], d7[5], d8[5], d9[5]}, [r0], r1
vld4.8 {d6[6], d7[6], d8[6], d9[6]}, [r0], r1
vld4.8 {d6[7], d7[7], d8[7], d9[7]}, [r0], r1
vld4.8 {d10[0], d11[0], d12[0], d13[0]}, [r0], r1
vld1.u8 {q0}, [r12]! ; 0x80
vld4.8 {d10[1], d11[1], d12[1], d13[1]}, [r0], r1
vld1.u8 {q11}, [r12]! ; 0x03
vld4.8 {d10[2], d11[2], d12[2], d13[2]}, [r0], r1
vld1.u8 {q12}, [r12]! ; 0x04
vld4.8 {d10[3], d11[3], d12[3], d13[3]}, [r0], r1
vld4.8 {d10[4], d11[4], d12[4], d13[4]}, [r0], r1
vld4.8 {d10[5], d11[5], d12[5], d13[5]}, [r0], r1
vld4.8 {d10[6], d11[6], d12[6], d13[6]}, [r0], r1
vld4.8 {d10[7], d11[7], d12[7], d13[7]}, [r0], r1
vswp d7, d10
vswp d12, d9
;vswp q4, q5 ; p1:q3, p0:q5, q0:q4, q1:q6
;vp8_filter_mask() function
;vp8_hevmask() function
sub r0, r0, r1, lsl #4
vabd.u8 q15, q5, q4 ; abs(p0 - q0)
vabd.u8 q14, q3, q6 ; abs(p1 - q1)
vqadd.u8 q15, q15, q15 ; abs(p0 - q0) * 2
vshr.u8 q14, q14, #1 ; abs(p1 - q1) / 2
vqadd.u8 q15, q15, q14 ; abs(p0 - q0) * 2 + abs(p1 - q1) / 2
veor q4, q4, q0 ; qs0: q0 offset to convert to a signed value
veor q5, q5, q0 ; ps0: p0 offset to convert to a signed value
veor q3, q3, q0 ; ps1: p1 offset to convert to a signed value
veor q6, q6, q0 ; qs1: q1 offset to convert to a signed value
vadd.u8 q1, q1, q1 ; flimit * 2
vadd.u8 q1, q1, q13 ; flimit * 2 + limit
vcge.u8 q15, q1, q15 ; abs(p0 - q0)*2 + abs(p1-q1)/2 > flimit*2 + limit)*-1
;vp8_filter() function
;;;;;;;;;;
;vqsub.s8 q2, q5, q4 ; ( qs0 - ps0)
vsubl.s8 q2, d8, d10 ; ( qs0 - ps0)
vsubl.s8 q13, d9, d11
vqsub.s8 q1, q3, q6 ; vp8_filter = vp8_signed_char_clamp(ps1-qs1)
;vmul.i8 q2, q2, q11 ; vp8_filter = vp8_signed_char_clamp(vp8_filter + 3 * ( qs0 - ps0))
vadd.s16 q10, q2, q2 ; 3 * ( qs0 - ps0)
vadd.s16 q14, q13, q13
vadd.s16 q2, q2, q10
vadd.s16 q13, q13, q14
;vqadd.s8 q1, q1, q2
vaddw.s8 q2, q2, d2 ; vp8_filter + 3 * ( qs0 - ps0)
vaddw.s8 q13, q13, d3
vqmovn.s16 d2, q2 ; vp8_filter = vp8_signed_char_clamp(vp8_filter + 3 * ( qs0 - ps0))
vqmovn.s16 d3, q13
add r0, r0, #1
add r2, r0, r1
;;;;;;;;;;;
vand q1, q1, q15 ; vp8_filter &= mask
vqadd.s8 q2, q1, q11 ; Filter2 = vp8_signed_char_clamp(vp8_filter+3)
vqadd.s8 q1, q1, q12 ; Filter1 = vp8_signed_char_clamp(vp8_filter+4)
vshr.s8 q2, q2, #3 ; Filter2 >>= 3
vshr.s8 q1, q1, #3 ; Filter1 >>= 3
;calculate output
vqsub.s8 q10, q4, q1 ; u = vp8_signed_char_clamp(qs0 - Filter1)
vqadd.s8 q11, q5, q2 ; u = vp8_signed_char_clamp(ps0 + Filter2)
veor q7, q10, q0 ; *oq0 = u^0x80
veor q6, q11, q0 ; *op0 = u^0x80
add r3, r2, r1
vswp d13, d14
add r12, r3, r1
;store op1, op0, oq0, oq1
vst2.8 {d12[0], d13[0]}, [r0]
vst2.8 {d12[1], d13[1]}, [r2]
vst2.8 {d12[2], d13[2]}, [r3]
vst2.8 {d12[3], d13[3]}, [r12], r1
add r0, r12, r1
vst2.8 {d12[4], d13[4]}, [r12]
vst2.8 {d12[5], d13[5]}, [r0], r1
add r2, r0, r1
vst2.8 {d12[6], d13[6]}, [r0]
vst2.8 {d12[7], d13[7]}, [r2], r1
add r3, r2, r1
vst2.8 {d14[0], d15[0]}, [r2]
vst2.8 {d14[1], d15[1]}, [r3], r1
add r12, r3, r1
vst2.8 {d14[2], d15[2]}, [r3]
vst2.8 {d14[3], d15[3]}, [r12], r1
add r0, r12, r1
vst2.8 {d14[4], d15[4]}, [r12]
vst2.8 {d14[5], d15[5]}, [r0], r1
add r2, r0, r1
vst2.8 {d14[6], d15[6]}, [r0]
vst2.8 {d14[7], d15[7]}, [r2]
bx lr
ENDP ; |vp8_loop_filter_simple_vertical_edge_neon|
;-----------------
vlfy_coeff
DCD 0x80808080, 0x80808080, 0x80808080, 0x80808080
DCD 0x03030303, 0x03030303, 0x03030303, 0x03030303
DCD 0x04040404, 0x04040404, 0x04040404, 0x04040404
END
| bsd-3-clause |
vishwesh3/BuildmLearn-Toolkit-Android | source-code/app/src/main/java/org/buildmlearn/toolkit/fragment/HomeFragment.java | 1033 | package org.buildmlearn.toolkit.fragment;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import org.buildmlearn.toolkit.R;
import org.buildmlearn.toolkit.activity.TemplateActivity;
/**
* @brief Fragment displayed on the home screen.
*/
public class HomeFragment extends Fragment {
/**
* {@inheritDoc}
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
view.findViewById(R.id.button_template).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(getActivity(), TemplateActivity.class));
}
});
return view;
}
}
| bsd-3-clause |
felixhaedicke/nst-kernel | src/arch/avr32/include/asm/pgtable.h | 11945 | /*
* Copyright (C) 2004-2006 Atmel Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#ifndef __ASM_AVR32_PGTABLE_H
#define __ASM_AVR32_PGTABLE_H
#include <asm/addrspace.h>
#ifndef __ASSEMBLY__
#include <linux/sched.h>
#endif /* !__ASSEMBLY__ */
/*
* Use two-level page tables just as the i386 (without PAE)
*/
#include <asm/pgtable-2level.h>
/*
* The following code might need some cleanup when the values are
* final...
*/
#define PMD_SIZE (1UL << PMD_SHIFT)
#define PMD_MASK (~(PMD_SIZE-1))
#define PGDIR_SIZE (1UL << PGDIR_SHIFT)
#define PGDIR_MASK (~(PGDIR_SIZE-1))
#define USER_PTRS_PER_PGD (TASK_SIZE / PGDIR_SIZE)
#define FIRST_USER_ADDRESS 0
#ifndef __ASSEMBLY__
extern pgd_t swapper_pg_dir[PTRS_PER_PGD];
extern void paging_init(void);
/*
* ZERO_PAGE is a global shared page that is always zero: used for
* zero-mapped memory areas etc.
*/
extern struct page *empty_zero_page;
#define ZERO_PAGE(vaddr) (empty_zero_page)
/*
* Just any arbitrary offset to the start of the vmalloc VM area: the
* current 8 MiB value just means that there will be a 8 MiB "hole"
* after the uncached physical memory (P2 segment) until the vmalloc
* area starts. That means that any out-of-bounds memory accesses will
* hopefully be caught; we don't know if the end of the P1/P2 segments
* are actually used for anything, but it is anyway safer to let the
* MMU catch these kinds of errors than to rely on the memory bus.
*
* A "hole" of the same size is added to the end of the P3 segment as
* well. It might seem wasteful to use 16 MiB of virtual address space
* on this, but we do have 512 MiB of it...
*
* The vmalloc() routines leave a hole of 4 KiB between each vmalloced
* area for the same reason.
*/
#define VMALLOC_OFFSET (8 * 1024 * 1024)
#define VMALLOC_START (P3SEG + VMALLOC_OFFSET)
#define VMALLOC_END (P4SEG - VMALLOC_OFFSET)
#endif /* !__ASSEMBLY__ */
/*
* Page flags. Some of these flags are not directly supported by
* hardware, so we have to emulate them.
*/
#define _TLBEHI_BIT_VALID 9
#define _TLBEHI_VALID (1 << _TLBEHI_BIT_VALID)
#define _PAGE_BIT_WT 0 /* W-bit : write-through */
#define _PAGE_BIT_DIRTY 1 /* D-bit : page changed */
#define _PAGE_BIT_SZ0 2 /* SZ0-bit : Size of page */
#define _PAGE_BIT_SZ1 3 /* SZ1-bit : Size of page */
#define _PAGE_BIT_EXECUTE 4 /* X-bit : execute access allowed */
#define _PAGE_BIT_RW 5 /* AP0-bit : write access allowed */
#define _PAGE_BIT_USER 6 /* AP1-bit : user space access allowed */
#define _PAGE_BIT_BUFFER 7 /* B-bit : bufferable */
#define _PAGE_BIT_GLOBAL 8 /* G-bit : global (ignore ASID) */
#define _PAGE_BIT_CACHABLE 9 /* C-bit : cachable */
/* If we drop support for 1K pages, we get two extra bits */
#define _PAGE_BIT_PRESENT 10
#define _PAGE_BIT_ACCESSED 11 /* software: page was accessed */
/* The following flags are only valid when !PRESENT */
#define _PAGE_BIT_FILE 0 /* software: pagecache or swap? */
#define _PAGE_WT (1 << _PAGE_BIT_WT)
#define _PAGE_DIRTY (1 << _PAGE_BIT_DIRTY)
#define _PAGE_EXECUTE (1 << _PAGE_BIT_EXECUTE)
#define _PAGE_RW (1 << _PAGE_BIT_RW)
#define _PAGE_USER (1 << _PAGE_BIT_USER)
#define _PAGE_BUFFER (1 << _PAGE_BIT_BUFFER)
#define _PAGE_GLOBAL (1 << _PAGE_BIT_GLOBAL)
#define _PAGE_CACHABLE (1 << _PAGE_BIT_CACHABLE)
/* Software flags */
#define _PAGE_ACCESSED (1 << _PAGE_BIT_ACCESSED)
#define _PAGE_PRESENT (1 << _PAGE_BIT_PRESENT)
#define _PAGE_FILE (1 << _PAGE_BIT_FILE)
/*
* Page types, i.e. sizes. _PAGE_TYPE_NONE corresponds to what is
* usually called _PAGE_PROTNONE on other architectures.
*
* XXX: Find out if _PAGE_PROTNONE is equivalent with !_PAGE_USER. If
* so, we can encode all possible page sizes (although we can't really
* support 1K pages anyway due to the _PAGE_PRESENT and _PAGE_ACCESSED
* bits)
*
*/
#define _PAGE_TYPE_MASK ((1 << _PAGE_BIT_SZ0) | (1 << _PAGE_BIT_SZ1))
#define _PAGE_TYPE_NONE (0 << _PAGE_BIT_SZ0)
#define _PAGE_TYPE_SMALL (1 << _PAGE_BIT_SZ0)
#define _PAGE_TYPE_MEDIUM (2 << _PAGE_BIT_SZ0)
#define _PAGE_TYPE_LARGE (3 << _PAGE_BIT_SZ0)
/*
* Mask which drop software flags. We currently can't handle more than
* 512 MiB of physical memory, so we can use bits 29-31 for other
* stuff. With a fixed 4K page size, we can use bits 10-11 as well as
* bits 2-3 (SZ)
*/
#define _PAGE_FLAGS_HARDWARE_MASK 0xfffff3ff
#define _PAGE_FLAGS_CACHE_MASK (_PAGE_CACHABLE | _PAGE_BUFFER | _PAGE_WT)
/* Flags that may be modified by software */
#define _PAGE_CHG_MASK (PTE_MASK | _PAGE_ACCESSED | _PAGE_DIRTY \
| _PAGE_FLAGS_CACHE_MASK)
#define _PAGE_FLAGS_READ (_PAGE_CACHABLE | _PAGE_BUFFER)
#define _PAGE_FLAGS_WRITE (_PAGE_FLAGS_READ | _PAGE_RW | _PAGE_DIRTY)
#define _PAGE_NORMAL(x) __pgprot((x) | _PAGE_PRESENT | _PAGE_TYPE_SMALL \
| _PAGE_ACCESSED)
#define PAGE_NONE (_PAGE_ACCESSED | _PAGE_TYPE_NONE)
#define PAGE_READ (_PAGE_FLAGS_READ | _PAGE_USER)
#define PAGE_EXEC (_PAGE_FLAGS_READ | _PAGE_EXECUTE | _PAGE_USER)
#define PAGE_WRITE (_PAGE_FLAGS_WRITE | _PAGE_USER)
#define PAGE_KERNEL _PAGE_NORMAL(_PAGE_FLAGS_WRITE | _PAGE_EXECUTE | _PAGE_GLOBAL)
#define PAGE_KERNEL_RO _PAGE_NORMAL(_PAGE_FLAGS_READ | _PAGE_EXECUTE | _PAGE_GLOBAL)
#define _PAGE_P(x) _PAGE_NORMAL((x) & ~(_PAGE_RW | _PAGE_DIRTY))
#define _PAGE_S(x) _PAGE_NORMAL(x)
#define PAGE_COPY _PAGE_P(PAGE_WRITE | PAGE_READ)
#define PAGE_SHARED _PAGE_S(PAGE_WRITE | PAGE_READ)
#ifndef __ASSEMBLY__
/*
* The hardware supports flags for write- and execute access. Read is
* always allowed if the page is loaded into the TLB, so the "-w-",
* "--x" and "-wx" mappings are implemented as "rw-", "r-x" and "rwx",
* respectively.
*
* The "---" case is handled by software; the page will simply not be
* loaded into the TLB if the page type is _PAGE_TYPE_NONE.
*/
#define __P000 __pgprot(PAGE_NONE)
#define __P001 _PAGE_P(PAGE_READ)
#define __P010 _PAGE_P(PAGE_WRITE)
#define __P011 _PAGE_P(PAGE_WRITE | PAGE_READ)
#define __P100 _PAGE_P(PAGE_EXEC)
#define __P101 _PAGE_P(PAGE_EXEC | PAGE_READ)
#define __P110 _PAGE_P(PAGE_EXEC | PAGE_WRITE)
#define __P111 _PAGE_P(PAGE_EXEC | PAGE_WRITE | PAGE_READ)
#define __S000 __pgprot(PAGE_NONE)
#define __S001 _PAGE_S(PAGE_READ)
#define __S010 _PAGE_S(PAGE_WRITE)
#define __S011 _PAGE_S(PAGE_WRITE | PAGE_READ)
#define __S100 _PAGE_S(PAGE_EXEC)
#define __S101 _PAGE_S(PAGE_EXEC | PAGE_READ)
#define __S110 _PAGE_S(PAGE_EXEC | PAGE_WRITE)
#define __S111 _PAGE_S(PAGE_EXEC | PAGE_WRITE | PAGE_READ)
#define pte_none(x) (!pte_val(x))
#define pte_present(x) (pte_val(x) & _PAGE_PRESENT)
#define pte_clear(mm,addr,xp) \
do { \
set_pte_at(mm, addr, xp, __pte(0)); \
} while (0)
/*
* The following only work if pte_present() is true.
* Undefined behaviour if not..
*/
static inline int pte_write(pte_t pte)
{
return pte_val(pte) & _PAGE_RW;
}
static inline int pte_dirty(pte_t pte)
{
return pte_val(pte) & _PAGE_DIRTY;
}
static inline int pte_young(pte_t pte)
{
return pte_val(pte) & _PAGE_ACCESSED;
}
static inline int pte_special(pte_t pte)
{
return 0;
}
/*
* The following only work if pte_present() is not true.
*/
static inline int pte_file(pte_t pte)
{
return pte_val(pte) & _PAGE_FILE;
}
/* Mutator functions for PTE bits */
static inline pte_t pte_wrprotect(pte_t pte)
{
set_pte(&pte, __pte(pte_val(pte) & ~_PAGE_RW));
return pte;
}
static inline pte_t pte_mkclean(pte_t pte)
{
set_pte(&pte, __pte(pte_val(pte) & ~_PAGE_DIRTY));
return pte;
}
static inline pte_t pte_mkold(pte_t pte)
{
set_pte(&pte, __pte(pte_val(pte) & ~_PAGE_ACCESSED));
return pte;
}
static inline pte_t pte_mkwrite(pte_t pte)
{
set_pte(&pte, __pte(pte_val(pte) | _PAGE_RW));
return pte;
}
static inline pte_t pte_mkdirty(pte_t pte)
{
set_pte(&pte, __pte(pte_val(pte) | _PAGE_DIRTY));
return pte;
}
static inline pte_t pte_mkyoung(pte_t pte)
{
set_pte(&pte, __pte(pte_val(pte) | _PAGE_ACCESSED));
return pte;
}
static inline pte_t pte_mkspecial(pte_t pte)
{
return pte;
}
#define pmd_none(x) (!pmd_val(x))
#define pmd_present(x) (pmd_val(x))
static inline void pmd_clear(pmd_t *pmdp)
{
set_pmd(pmdp, __pmd(0));
}
#define pmd_bad(x) (pmd_val(x) & ~PAGE_MASK)
/*
* Permanent address of a page. We don't support highmem, so this is
* trivial.
*/
#define pages_to_mb(x) ((x) >> (20-PAGE_SHIFT))
#define pte_page(x) (pfn_to_page(pte_pfn(x)))
/*
* Mark the prot value as uncacheable and unbufferable
*/
#define pgprot_noncached(prot) \
__pgprot(pgprot_val(prot) & ~(_PAGE_BUFFER | _PAGE_CACHABLE))
/*
* Mark the prot value as uncacheable but bufferable
*/
#define pgprot_writecombine(prot) \
__pgprot((pgprot_val(prot) & ~_PAGE_CACHABLE) | _PAGE_BUFFER)
/*
* Conversion functions: convert a page and protection to a page entry,
* and a page entry and page directory to the page they refer to.
*
* extern pte_t mk_pte(struct page *page, pgprot_t pgprot)
*/
#define mk_pte(page, pgprot) pfn_pte(page_to_pfn(page), (pgprot))
static inline pte_t pte_modify(pte_t pte, pgprot_t newprot)
{
set_pte(&pte, __pte((pte_val(pte) & _PAGE_CHG_MASK)
| pgprot_val(newprot)));
return pte;
}
#define page_pte(page) page_pte_prot(page, __pgprot(0))
#define pmd_page_vaddr(pmd) pmd_val(pmd)
#define pmd_page(pmd) (virt_to_page(pmd_val(pmd)))
/* to find an entry in a page-table-directory. */
#define pgd_index(address) (((address) >> PGDIR_SHIFT) \
& (PTRS_PER_PGD - 1))
#define pgd_offset(mm, address) ((mm)->pgd + pgd_index(address))
/* to find an entry in a kernel page-table-directory */
#define pgd_offset_k(address) pgd_offset(&init_mm, address)
/* Find an entry in the third-level page table.. */
#define pte_index(address) \
((address >> PAGE_SHIFT) & (PTRS_PER_PTE - 1))
#define pte_offset(dir, address) \
((pte_t *) pmd_page_vaddr(*(dir)) + pte_index(address))
#define pte_offset_kernel(dir, address) \
((pte_t *) pmd_page_vaddr(*(dir)) + pte_index(address))
#define pte_offset_map(dir, address) pte_offset_kernel(dir, address)
#define pte_offset_map_nested(dir, address) pte_offset_kernel(dir, address)
#define pte_unmap(pte) do { } while (0)
#define pte_unmap_nested(pte) do { } while (0)
struct vm_area_struct;
extern void update_mmu_cache(struct vm_area_struct * vma,
unsigned long address, pte_t pte);
/*
* Encode and decode a swap entry
*
* Constraints:
* _PAGE_FILE at bit 0
* _PAGE_TYPE_* at bits 2-3 (for emulating _PAGE_PROTNONE)
* _PAGE_PRESENT at bit 10
*
* We encode the type into bits 4-9 and offset into bits 11-31. This
* gives us a 21 bits offset, or 2**21 * 4K = 8G usable swap space per
* device, and 64 possible types.
*
* NOTE: We should set ZEROs at the position of _PAGE_PRESENT
* and _PAGE_PROTNONE bits
*/
#define __swp_type(x) (((x).val >> 4) & 0x3f)
#define __swp_offset(x) ((x).val >> 11)
#define __swp_entry(type, offset) ((swp_entry_t) { ((type) << 4) | ((offset) << 11) })
#define __pte_to_swp_entry(pte) ((swp_entry_t) { pte_val(pte) })
#define __swp_entry_to_pte(x) ((pte_t) { (x).val })
/*
* Encode and decode a nonlinear file mapping entry. We have to
* preserve _PAGE_FILE and _PAGE_PRESENT here. _PAGE_TYPE_* isn't
* necessary, since _PAGE_FILE implies !_PAGE_PROTNONE (?)
*/
#define PTE_FILE_MAX_BITS 30
#define pte_to_pgoff(pte) (((pte_val(pte) >> 1) & 0x1ff) \
| ((pte_val(pte) >> 11) << 9))
#define pgoff_to_pte(off) ((pte_t) { ((((off) & 0x1ff) << 1) \
| (((off) >> 9) << 11) \
| _PAGE_FILE) })
typedef pte_t *pte_addr_t;
#define kern_addr_valid(addr) (1)
#define io_remap_pfn_range(vma, vaddr, pfn, size, prot) \
remap_pfn_range(vma, vaddr, pfn, size, prot)
/* No page table caches to initialize (?) */
#define pgtable_cache_init() do { } while(0)
#include <asm-generic/pgtable.h>
#endif /* !__ASSEMBLY__ */
#endif /* __ASM_AVR32_PGTABLE_H */
| gpl-2.0 |
ProZachJ/appsensor | appsensor-dot-org/site-contents/docs/v2.2.0/javadoc/org/owasp/appsensor/core/logging/package-summary.html | 2487 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0) on Fri Oct 02 00:10:12 EDT 2015 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.owasp.appsensor.core.logging (appsensor-parent 2.2.0 API)</title>
<meta name="date" content="2015-10-02">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="org.owasp.appsensor.core.logging (appsensor-parent 2.2.0 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="header">
<h1 title="Package" class="title">Package org.owasp.appsensor.core.logging</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation">
<caption><span>Class Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/owasp/appsensor/core/logging/LoggerBeanPostProcessor.html" title="class in org.owasp.appsensor.core.logging">LoggerBeanPostProcessor</a></td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Annotation Types Summary table, listing annotation types, and an explanation">
<caption><span>Annotation Types Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Annotation Type</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/owasp/appsensor/core/logging/Loggable.html" title="annotation in org.owasp.appsensor.core.logging">Loggable</a></td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<p class="legalCopy"><small>Copyright © 2015 <a href="http://www.owasp.org">The Open Web Application Security Project (OWASP)</a>. All rights reserved.</small></p>
</body>
</html>
| mit |
cinjoff/XChange-1 | xchange-btcchina/src/main/java/com/xeiam/xchange/btcchina/BTCChina.java | 14863 | package com.xeiam.xchange.btcchina;
import java.io.IOException;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import si.mazi.rescu.ParamsDigest;
import si.mazi.rescu.SynchronizedValueFactory;
import com.xeiam.xchange.btcchina.dto.account.request.BTCChinaGetAccountInfoRequest;
import com.xeiam.xchange.btcchina.dto.account.request.BTCChinaGetDepositsRequest;
import com.xeiam.xchange.btcchina.dto.account.request.BTCChinaGetWithdrawalRequest;
import com.xeiam.xchange.btcchina.dto.account.request.BTCChinaGetWithdrawalsRequest;
import com.xeiam.xchange.btcchina.dto.account.request.BTCChinaRequestWithdrawalRequest;
import com.xeiam.xchange.btcchina.dto.account.response.BTCChinaGetAccountInfoResponse;
import com.xeiam.xchange.btcchina.dto.account.response.BTCChinaGetDepositsResponse;
import com.xeiam.xchange.btcchina.dto.account.response.BTCChinaGetWithdrawalResponse;
import com.xeiam.xchange.btcchina.dto.account.response.BTCChinaGetWithdrawalsResponse;
import com.xeiam.xchange.btcchina.dto.account.response.BTCChinaRequestWithdrawalResponse;
import com.xeiam.xchange.btcchina.dto.marketdata.BTCChinaDepth;
import com.xeiam.xchange.btcchina.dto.marketdata.BTCChinaTicker;
import com.xeiam.xchange.btcchina.dto.marketdata.BTCChinaTrade;
import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaBuyIcebergOrderRequest;
import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaBuyOrderRequest;
import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaBuyStopOrderRequest;
import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaCancelIcebergOrderRequest;
import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaCancelOrderRequest;
import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaCancelStopOrderRequest;
import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaGetIcebergOrderRequest;
import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaGetIcebergOrdersRequest;
import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaGetMarketDepthRequest;
import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaGetOrderRequest;
import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaGetOrdersRequest;
import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaGetStopOrderRequest;
import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaGetStopOrdersRequest;
import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaSellIcebergOrderRequest;
import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaSellOrderRequest;
import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaSellStopOrderRequest;
import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaTransactionsRequest;
import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaBooleanResponse;
import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaGetIcebergOrderResponse;
import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaGetIcebergOrdersResponse;
import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaGetMarketDepthResponse;
import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaGetOrderResponse;
import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaGetOrdersResponse;
import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaGetStopOrderResponse;
import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaGetStopOrdersResponse;
import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaIntegerResponse;
import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaTransactionsResponse;
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public interface BTCChina {
@GET
@Path("data/ticker")
BTCChinaTicker getTicker(@QueryParam("market") String market) throws IOException;
/**
* Returns all the open orders from the specified {@code market}.
*
* @param market the market could be {@code btccny}, {@code ltccny}, {@code ltcbtc}.
* @return the order book.
* @throws IOException indicates I/O exception.
* @see #getOrderBook(String, int)
*/
@GET
@Path("data/orderbook")
BTCChinaDepth getFullDepth(@QueryParam("market") String market) throws IOException;
/**
* Order book default contains all open ask and bid orders. Set 'limit' parameter to specify the number of records fetched per request.
* <p>
* Bid orders are {@code limit} orders with highest price while ask with lowest, and orders are descendingly sorted by price.
* </p>
*
* @param market market could be {@code btccny}, {@code ltccny}, {@code ltcbtc}.
* @param limit number of records fetched per request.
* @return the order book.
* @throws IOException indicates I/O exception.
* @see #getFullDepth(String)
*/
@GET
@Path("data/orderbook")
BTCChinaDepth getOrderBook(@QueryParam("market") String market, @QueryParam("limit") int limit) throws IOException;
/**
* Returns last 100 trade records.
*/
@GET
@Path("data/historydata")
BTCChinaTrade[] getHistoryData(@QueryParam("market") String market) throws IOException;
/**
* Returns last {@code limit} trade records.
*
* @param market
* @param limit the range of limit is [0,5000].
* @throws IOException
*/
@GET
@Path("data/historydata")
BTCChinaTrade[] getHistoryData(@QueryParam("market") String market, @QueryParam("limit") int limit) throws IOException;
/**
* Returns 100 trade records starting from id {@code since}.
*
* @param market
* @param since the starting trade ID(exclusive).
* @throws IOException
*/
@GET
@Path("data/historydata")
BTCChinaTrade[] getHistoryData(@QueryParam("market") String market, @QueryParam("since") long since) throws IOException;
/**
* Returns {@code limit} trades starting from id {@code since}
*
* @param market
* @param since the starting trade ID(exclusive).
* @param limit the range of limit is [0,5000].
* @throws IOException
*/
@GET
@Path("data/historydata")
BTCChinaTrade[] getHistoryData(@QueryParam("market") String market, @QueryParam("since") long since, @QueryParam("limit") int limit)
throws IOException;
@GET
@Path("data/historydata")
BTCChinaTrade[] getHistoryData(@QueryParam("market") String market, @QueryParam("since") long since, @QueryParam("limit") int limit,
@QueryParam("sincetype") @DefaultValue("id") String sincetype) throws IOException;
@POST
@Path("api_trade_v1.php")
@Consumes(MediaType.APPLICATION_JSON)
BTCChinaGetAccountInfoResponse getAccountInfo(@HeaderParam("Authorization") ParamsDigest authorization,
@HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetAccountInfoRequest getAccountInfoRequest)
throws IOException;
@POST
@Path("api_trade_v1.php")
@Consumes(MediaType.APPLICATION_JSON)
BTCChinaGetDepositsResponse getDeposits(@HeaderParam("Authorization") ParamsDigest authorization,
@HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetDepositsRequest getDepositsRequest) throws IOException;
/**
* Get the complete market depth. Returns all open bid and ask orders.
*/
@POST
@Path("api_trade_v1.php")
@Consumes(MediaType.APPLICATION_JSON)
BTCChinaGetMarketDepthResponse getMarketDepth(@HeaderParam("Authorization") ParamsDigest authorization,
@HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetMarketDepthRequest request) throws IOException;
@POST
@Path("api_trade_v1.php")
@Consumes(MediaType.APPLICATION_JSON)
BTCChinaGetWithdrawalResponse getWithdrawal(@HeaderParam("Authorization") ParamsDigest authorization,
@HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetWithdrawalRequest request) throws IOException;
@POST
@Path("api_trade_v1.php")
@Consumes(MediaType.APPLICATION_JSON)
BTCChinaGetWithdrawalsResponse getWithdrawals(@HeaderParam("Authorization") ParamsDigest authorization,
@HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetWithdrawalsRequest request) throws IOException;
@POST
@Path("api_trade_v1.php")
@Consumes(MediaType.APPLICATION_JSON)
BTCChinaRequestWithdrawalResponse requestWithdrawal(@HeaderParam("Authorization") ParamsDigest authorization,
@HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaRequestWithdrawalRequest requestWithdrawalRequest)
throws IOException;
@POST
@Path("api_trade_v1.php")
@Consumes(MediaType.APPLICATION_JSON)
BTCChinaGetOrderResponse getOrder(@HeaderParam("Authorization") ParamsDigest authorization,
@HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetOrderRequest getOrderRequest) throws IOException;
@POST
@Path("api_trade_v1.php")
@Consumes(MediaType.APPLICATION_JSON)
BTCChinaGetOrdersResponse getOrders(@HeaderParam("Authorization") ParamsDigest authorization,
@HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetOrdersRequest getOrdersRequest) throws IOException;
@POST
@Path("api_trade_v1.php")
@Consumes(MediaType.APPLICATION_JSON)
BTCChinaBooleanResponse cancelOrder(@HeaderParam("Authorization") ParamsDigest authorization,
@HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaCancelOrderRequest cancelOrderRequest) throws IOException;
@POST
@Path("api_trade_v1.php")
@Consumes(MediaType.APPLICATION_JSON)
BTCChinaIntegerResponse buyOrder2(@HeaderParam("Authorization") ParamsDigest authorization,
@HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaBuyOrderRequest buyOrderRequest) throws IOException;
@POST
@Path("api_trade_v1.php")
@Consumes(MediaType.APPLICATION_JSON)
BTCChinaIntegerResponse sellOrder2(@HeaderParam("Authorization") ParamsDigest authorization,
@HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaSellOrderRequest sellOrderRequest) throws IOException;
@POST
@Path("api_trade_v1.php")
@Consumes(MediaType.APPLICATION_JSON)
BTCChinaTransactionsResponse getTransactions(@HeaderParam("Authorization") ParamsDigest authorization,
@HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaTransactionsRequest transactionRequest) throws IOException;
/**
* Place a buy iceberg order. This method will return an iceberg order id.
*/
@POST
@Path("api_trade_v1.php")
@Consumes(MediaType.APPLICATION_JSON)
BTCChinaIntegerResponse buyIcebergOrder(@HeaderParam("Authorization") ParamsDigest authorization,
@HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaBuyIcebergOrderRequest request) throws IOException;
/**
* Place a sell iceberg order. This method will return an iceberg order id.
*/
@POST
@Path("api_trade_v1.php")
@Consumes(MediaType.APPLICATION_JSON)
BTCChinaIntegerResponse sellIcebergOrder(@HeaderParam("Authorization") ParamsDigest authorization,
@HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaSellIcebergOrderRequest request) throws IOException;
/**
* Get an iceberg order, including the orders placed.
*/
@POST
@Path("api_trade_v1.php")
@Consumes(MediaType.APPLICATION_JSON)
BTCChinaGetIcebergOrderResponse getIcebergOrder(@HeaderParam("Authorization") ParamsDigest authorization,
@HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetIcebergOrderRequest request) throws IOException;
/**
* Get iceberg orders, including the orders placed inside each iceberg order.
*/
@POST
@Path("api_trade_v1.php")
@Consumes(MediaType.APPLICATION_JSON)
BTCChinaGetIcebergOrdersResponse getIcebergOrders(@HeaderParam("Authorization") ParamsDigest authorization,
@HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetIcebergOrdersRequest request) throws IOException;
/**
* Cancels an open iceberg order. Fails if iceberg order is already cancelled or closed. The related order with the iceberg order will also be
* cancelled.
*/
@POST
@Path("api_trade_v1.php")
@Consumes(MediaType.APPLICATION_JSON)
BTCChinaBooleanResponse cancelIcebergOrder(@HeaderParam("Authorization") ParamsDigest authorization,
@HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaCancelIcebergOrderRequest request) throws IOException;
/**
* Place a buy stop order. This method will return a stop order id.
*/
@POST
@Path("api_trade_v1.php")
@Consumes(MediaType.APPLICATION_JSON)
BTCChinaIntegerResponse buyStopOrder(@HeaderParam("Authorization") ParamsDigest authorization,
@HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaBuyStopOrderRequest request) throws IOException;
/**
* Place a sell stop order. This method will return an stop order id.
*/
@POST
@Path("api_trade_v1.php")
@Consumes(MediaType.APPLICATION_JSON)
BTCChinaIntegerResponse sellStopOrder(@HeaderParam("Authorization") ParamsDigest authorization,
@HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaSellStopOrderRequest request) throws IOException;
/**
* Get a stop order.
*/
@POST
@Path("api_trade_v1.php")
@Consumes(MediaType.APPLICATION_JSON)
BTCChinaGetStopOrderResponse getStopOrder(@HeaderParam("Authorization") ParamsDigest authorization,
@HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetStopOrderRequest request) throws IOException;
/**
* Get stop orders.
*/
@POST
@Path("api_trade_v1.php")
@Consumes(MediaType.APPLICATION_JSON)
BTCChinaGetStopOrdersResponse getStopOrders(@HeaderParam("Authorization") ParamsDigest authorization,
@HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetStopOrdersRequest request) throws IOException;
/**
* Cancels an open stop order. Fails if stop order is already cancelled or closed.
*/
@POST
@Path("api_trade_v1.php")
@Consumes(MediaType.APPLICATION_JSON)
BTCChinaBooleanResponse cancelStopOrder(@HeaderParam("Authorization") ParamsDigest authorization,
@HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaCancelStopOrderRequest request) throws IOException;
}
| mit |
cqw1/palliassist_webportal | webjobs/sync-redcap/node_modules/xhr-response/README.md | 1641 | # xhr-response
[![Made by unshift][made-by]](http://unshift.io)[![Version npm][version]](http://browsenpm.org/package/xhr-response)[![Build Status][build]](https://travis-ci.org/unshiftio/xhr-response)[![Dependencies][david]](https://david-dm.org/unshiftio/xhr-response)[![Coverage Status][cover]](https://coveralls.io/r/unshiftio/xhr-response?branch=master)[![IRC channel][irc]](http://webchat.freenode.net/?channels=unshift)
[made-by]: https://img.shields.io/badge/made%20by-unshift-00ffcc.svg?style=flat-square
[version]: https://img.shields.io/npm/v/xhr-response.svg?style=flat-square
[build]: https://img.shields.io/travis/unshiftio/xhr-response/master.svg?style=flat-square
[david]: https://img.shields.io/david/unshiftio/xhr-response.svg?style=flat-square
[cover]: https://img.shields.io/coveralls/unshiftio/xhr-response/master.svg?style=flat-square
[irc]: https://img.shields.io/badge/IRC-irc.freenode.net%23unshift-00a8ff.svg?style=flat-square
The `xhr-response` is a small helper library for safely extracting response data
from XHR requests. There are some minor bugs in browsers which can cause
exceptions to be thrown when accessing the wrong properties of an XHR request
instance. This module works around these bugs.
## Installation
This module is primary written for client-side code which use the commonjs
module pattern for exporting.
```
npm install --save xhr-response
```
## Usage
It's just as simple as:
```js
var response = require("xhr-response");
var xhr = new XMLHTTPRequest();
// .. stuffs ..
xhr.onload = function () {
var data = response(xhr);
console.log('data', data);
};
```
## License
MIT
| mit |
moufmouf/mouf | doc/extending_mouf_ui.md | 13734 | Extending Mouf's user interface
===============================
In your package, you can write custom controllers and views in order to add your own user interface.
There are plenty of hook points that let you:
- add menu items
- add HTML in any zone
- add any controller
Let's focus on the most common use case: adding a controller.
User interface types
--------------------
When you extend the user interface, the first question you must ask is:
*"Is my user interface dependent on a particular instance or not?"*.
Most of the time, it is, but it might not always be true.
For instance:
Let's suppose you are developing a cache system, like the one in package [utils.cache.CacheInterface](http://mouf-php.com/packages/mouf/utils.cache.cache-interface/README.md).
You will certainly end-up with instances representing different cache services. You might want to offer a special user interface for the user to purge the cache.
If your user interface is purging all caches at once, it is a **global** user interface.
On the other end, if you must first choose what instance you are working on before purging the cache,
you are working on a **instance related** user interface.
Understanding Mouf structure
----------------------------
Mouf is developed using Mouf (yes, it is recursive!)
Actually, Mouf uses a number of packages:
- Splash for the MVC part
- A Bootstrap based template
- ...
Therefore, to interact with the user, we will be [writing a Splash controller](http://mouf-php.com/packages/mouf/mvc.splash/index.md).
Finally, you will have to declare the controller instance manually, but we will see this in the next chapter. Before reading through this document, please be sure you understand [the way Splash works](http://mouf-php.com/packages/mouf/mvc.splash/index.md)!
<div class="alert alert-info">Mouf's own packages are stored in the <code>/vendor/mouf/mouf/vendor</code> directory.
This means that your project and Mouf can use a different version of Splash for instance.<br/><br/>
Mouf has its own container, with its own <code>MoufComponents.php</code> file (see the "vendor/mouf/mouf/mouf/MoufComponents.php" file).
This file contains all the instances used by Mouf.
Your package <b>cannot</b> modify this file.<br/><br/>
However, at runtime, you can add your own instances in the Mouf's container.</div>
Using Mouf internal API
-----------------------
If you want to extend the administration interface, it is almost sure you will want to create or modify
instances programmatically. You can learn how to do this in the ["Managing instances programmatically" section](managing_instances_programmatically.md).
Registering an 'admin' file
---------------------------
In order to register your own instances at runtime, your package can declare an "admin" file.
An "admin" file is a file that is executed each time a request if performed in the Mouf user interface.
If you already read the [*Writing an install process*](install_process.md) documentation, you should already
be familiar with this kind of file.
In order to declare an "admin" file, you need to add a `require-admin` section in the **extra/mouf** section
of the `composer.json`
**composer.json**
```json
{
...
"extra" : {
"mouf" : {
"require-admin" : [
"src/MyAdminFile.php"
]
}
},
...
}
```
In this sample, the `src/MyAdminFile.php` will be executed each time a request is made to the Mouf user interface.
<div class="alert"><b>Important:</b> Mouf will not detect any changes you make to <code>composer.json</code>
unless you commit/push the changes in your repository and you run a <code>php composer.phar update</code>.
In other words, the <code>composer.json</code> file taken into account by Mouf is the one coming from
Packagist, not the one on your hard disk.</div>
Writing a **global** user interface
-----------------------------------
Let's get started by writing a global user interface. We will see the instance related user interface in the next chapter.
To get started, we need 3 files:
- src/MyVendor/Controller/MyAdminController.php: This file will contain the controller class.
- src/views/myAdminView.php: This file will contain the view (HTML code).
- src/MyAdminFile.php: We already spoke about this file in the previous chapter. It must be registered in the `composer.json`.
###Writing the controller
**MyAdminController.php**
```php
namespace MyVendor\Controller\MyAdminController;
...
/**
* A sample controller that will be displayed in the administration interface.
*/
class MyAdminController extends Controller {
/**
* The content block that will contain the HTML.
* @var HtmlBlock
*/
public $content;
/**
* The default template to use for this controller (will be the Mouf template)
* @var TemplateInterface
*/
public $template;
protected $selfedit;
/**
* The action displaying the page.
*
* @Action
* @Logged
*/
public function index($selfedit = "false") {
// Do stuff
$this->selfedit = $selfedit;
$this->content->addFile(__DIR__."/../../views/myAdminView.php", $this);
$this->template->toHtml();
}
...
}
```
The controller is pretty standard. It contains a template property (that will be linked to the Mouf template).
<div class="alert alert-info">
<p><strong>What is this selfedit thing I see all around?</strong></p>
<p>As you already know, Mouf is developed using Mouf. So this means that the Mouf administration interface
can also be used to administrate the Mouf administration interface (instead of your application).
To do this, you just have to put Mouf in <strong>selfedit mode</strong>, by appending <code>?selfedit=true</code> to any Mouf URL.
When you develop a package, unless you are a core Mouf developer, it is unlikely you will want to use this
package in selfedit mode. You can therefore completely disregard this parameter.
However, if your package may at some time be embeded in the code of Mouf (for instance, Splash is embedded
in Mouf, regardless of the fact the application developer is using Splash or not), then you will need to
take the <strong>selfedit</strong> parameter into account, in order to know the context in which you are working.</p>
</div>
###Writing the view
Now, let's develop the view:
**myAdminView.php**
```php
<?php /* @var $this MyVendor\Controller\MyAdminController */ ?>
This is the view file. You can put here any PHP and HTML you want to build your view.
```
###Registering the controller and adding a menu item
We already talked about the **MyAdminFile.php** and the way it was registered in **composer.json**.
Let's put some content in this file.
**src/MyAdminFile.php**
```php
// Let's create a sample menu for our controller.
// The MoufUtils::registerMenuItem is an easy to use function to create menu items quickly.
// First parameter is the menu item instance name
// Second parameter the text of the menu
// Third parameter the link to point to
// Fourth parameter the name of the parent menu instance (the top level menu is named "mainMenu"
// Last parameter is the priority of the menu. The lowest number ranks first.
MoufUtils::registerMainMenu('myMainMenu', 'My Menu', null, 'mainMenu', 70);
// Let's make a submenu itme
MoufUtils::registerMenuItem('mySubMenu', 'My submenu', null, 'myMainMenu', 80);
// And a sub-submenu item
MoufUtils::registerMenuItem('mySubSubMenu', 'My menu-item', ROOT_URL.'myAdminController/', 'mySubMenu', 10);
$moufManager = MoufManager::getMoufManager();
// Controller declaration
$moufManager->declareComponent('myAdminController', 'MyVendor\\Controller\\MyAdminController', true);
// Let's bind the "moufTemplate" instance to the "myAdminController".
$moufManager->bindComponents('myAdminController', 'template', 'moufTemplate');
// Let's bind the "block.content" instance to the "myAdminController".
$moufManager->bindComponents('myAdminController', 'content', 'block.content');
```
As you probably noticed, when declaring the controller, we are not using the `getInstanceDescriptor()` method
that is described in the ["Managing instances programmatically" section](managing_instances_programmatically.md).
Instead, we are using `declareComponent` and `bindComponents`. These are "low level" methods of
the MoufManager that can add/edit instances really quickly. Since the code in **MyAdminFile.php** is run
on each request to Mouf, we need it to be lightning quick. This is why we are using those low-level methods
instead of the more advanced (and more slow) `getInstanceDescriptor()`.
Writing an **instance-related** user interface
----------------------------------------------
It might not be obvious at the beginning, but you will realize that most of your controllers/routes will probably
be related to an instance in your application. Let's see what tools Mouf offers to make this work
a little easier.
###Adding a **special action button** on the instance page
When you are on the instance page, you can add a special action button.
Special actions are actually additional pages that are specific to an instance.
Here is a sample special action you can see for any [TDBMService instance (package: database.tdbm)](https://github.com/thecodingmachine/database.tdbm/blob/3.1/src/Mouf/Database/TDBM/TDBMService.php#L37)

Adding a special action for an instance is very simple.
In the PHPDoc of the class, you just need to add a `@ExtendedAction` annotation.
Here is a sample:
```php
/**
* @ExtendedAction {"name":"Generate DAOs", "url":"tdbmadmin/", "default":false}
*/
class TDBM_Service {
...
}
```
As you can see:
- the `name` attribute is the special action text displayed in the menu,
- the `url` attribute is the URL of the controller. Please note that the name of the instance will automatically be appended: ?name=[instancename].
- If the `default` attribute is set to true, the extended action will be displayed by default, instead of the default instance page. Using this feature, you can completely integrate a special action into the Mouf workflow.
###Using the **AbstractMoufInstanceController** base controller
Instead of extending your controller from the default `Controller` class, you might want to extend
the `AbstractMoufInstanceController` class. It offers a number of advantages:
- It declares a template (you still have to bind your controller instance to the template)
- It automatically fills the left menu with useful menuitems:
- A link to the instance's main page
- The list of instances using this instance...
- It retrieves the instance so you can easily access it without going through the `MoufManager` class
Here is a sample:
**MyAdminController.php**
/**
* A sample instance-specific admin controller
*/
class MyAdminController extends AbstractMoufInstanceController {
/**
*
* @var HtmlBlock
*/
public $content;
/**
* Admin page for my instance
*
* @Action
*/
public function index($name, $selfedit="false") {
// Let's initialize the controller
$this->initController($name, $selfedit);
// In this code, you can access a number of variables:
// $this->template points to the template
// $this->moufManager points to the MoufManager instance
// ...
$this->content->addFile(__DIR__."/../../views/myAdminView.php", $this);
$this->template->toHtml();
}
}
###Special menus: menus that depend on instances
So far, things where easy:
- global actions are accessed through the main menu
- instance related actions are accessed through the "special action" menu, on the instance page
This is simple, but in many cases, you might want to **promote** a special action directly in the main menu.
Indeed, menu items displayed in the main menu are easier to find.
Mouf offers a simple way to add instance related actions in the main menu.
It works using a special kind of meny item that acts this way:
- When you click on the menu item, a pop-up is displayed, asking you to choose your instance. You select your instance, click the "ok" button and the instance-related controller is displayed
- If there is only one eligible instance for this special action, the drop-down is not displayed, you have a direct access to the controller for that special instance
- If there is no eligible instance, an message is displayed, explaining that we need at least one instance of type "X".
Here is what the "choose-instance" popup looks like when you click on the menu:

To develop such a popup, you will need to use the `MoufUtils::registerChooseInstanceMenuItem` method.
Here is how to code such a popup in your **MyAdminFile.php** file.
**src/MyAdminFile.php**
```php
use Mouf\MoufUtils;
MoufUtils::registerMainMenu('dbMainMenu', 'DB', null, 'mainMenu', 70);
MoufUtils::registerMenuItem('dbTDBMAdminSubMenu', 'DAOs', null, 'dbMainMenu', 80);
// First parameter: the name of the new menu item
// Second parameter: the label of the menu
// Third parameter: the URL we should access when the instance is selected. The instance name is automatically appended to the link.
// in this sample: tdbmadmin/?name=xxx where xxx is the name of the selected instance
// Fourth parameter: the name of the class or interface that is targeted
// Fifth parameter: the parent menu item
// Sixth parameter: the priority of the menu item compared to sibblings.
MoufUtils::registerChooseInstanceMenuItem('dbTDBMGenereateDAOAdminSubMenu', 'Generate DAOs', 'tdbmadmin/', "Mouf\\Database\\TDBM\\TDBMService", 'dbTDBMAdminSubMenu', 10);
...
```
| mit |
max05/bootstrap | src/Test/TestBundle/DependencyInjection/Configuration.php | 873 | <?php
namespace Test\TestBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('test_test');
// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.
return $treeBuilder;
}
}
| mit |
mike1808/godtracks | src/app/index.config.js | 124 | function config ($logProvider) {
'ngInject';
// Enable log
$logProvider.debugEnabled(true);
}
export default config;
| mit |
wirebirdlabs/incredible | webui/logic.css | 2479 | .connection {
stroke: #999;
}
.connection.error {
stroke: #F00;
}
.connection-wrap {
stroke-linecap: butt;
transition: all 0.5s linear 0.2s;
}
.connection-wrap:hover {
stroke: black;
stroke-width: 9px;
transition: all 0s;
}
.link-tools .tool-remove circle {
fill: white;
stroke: #ccc;
stroke-width: 1px;
stroke-opacity: .5;
}
.link-tools .tool-remove:hover circle {
fill: #e74c3c;
stroke: #c0392b;
}
.link-tools .tool-remove path {
stroke: #ccc;
}
.link-tools .tool-remove circle {
transition: fill 1s;
}
.link-tools .tool-remove:hover path {
stroke: none;
}
.marker-arrowhead, .marker-vertex {
fill: #fff;
stroke: #7f8c8d;
stroke-opacity: 0.4;
stroke-width: 2px;
}
.marker-arrowhead:hover, .marker-vertex:hover {
fill: #ecf0f1;
stroke: #bdc3c7;
}
.marker-vertex-remove-area {
fill: white;
stroke: #ccc;
stroke-opacity: .5;
}
.marker-vertex-remove-group:hover .marker-vertex-remove-area {
transition: fill 1s;
fill: #e74c3c;
stroke: #c0392b;
}
.marker-vertex-remove {
stroke: #eee;
}
.marker-vertex-remove-group:hover .marker-vertex-remove {
stroke: none;
}
.live .connection {
stroke: #2ecc71;
stroke-width: 3px;
}
.live .connection-wrap {
stroke: #2ecc71;
}
.element.live .body {
fill: #2ecc71;
stroke: #27ae60;
}
.element.live text {
fill: #ffffff;
}
/* Custom incredible rules */
.ui-draggable {
cursor: move
}
.block .label {
font-family: sans;
font-size: 17px;
fill: black;
}
.block .resize-left {
cursor: ew-resize
}
.block .resize-right {
cursor: ew-resize
}
.block .number {
fill: #000;
opacity: 0.5;
font-size: 8px;
}
.block .body {
fill:#ecf0f1;
}
.block.qed .body {
fill:#0f0;
}
.block:hover .body {
fill:white;
}
.block.qed:hover .body {
fill:#afa;
}
.selected .block .body {
stroke:blue;
stroke-opacity:1;
}
.port-body[magnet=true]:hover {
fill:black;
}
.block .tool-remove {
opacity: 0;
cursor: pointer;
}
.block:hover .tool-remove {
opacity: 1;
}
.block .tool-remove circle {
fill: white;
stroke: #ccc;
stroke-width: 1px;
stroke-opacity: .5;
}
.block .tool-remove:hover circle {
fill: #e74c3c;
stroke: #c0392b;
}
.block .tool-remove path {
fill: white;
stroke: #ccc;
}
.block .tool-remove circle {
transition: fill 1s;
}
.block .tool-remove:hover path {
stroke: none;
}
| mit |
gernest/gforms | passwordinputwidget.go | 266 | package gforms
// Generate password input field: <input type="password" ...>
func PasswordInputWidget(attrs map[string]string) Widget {
w := new(textInputWidget)
w.Type = "password"
if attrs == nil {
attrs = map[string]string{}
}
w.Attrs = attrs
return w
}
| mit |
vslavik/poedit | deps/boost/doc/html/boost/intrusive/rbtree_algorithms.html | 80930 | <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Class template rbtree_algorithms</title>
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../../intrusive/reference.html#header.boost.intrusive.rbtree_algorithms_hpp" title="Header <boost/intrusive/rbtree_algorithms.hpp>">
<link rel="prev" href="make_rbtree.html" title="Struct template make_rbtree">
<link rel="next" href="set.html" title="Class template set">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td>
<td align="center"><a href="../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="make_rbtree.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../intrusive/reference.html#header.boost.intrusive.rbtree_algorithms_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="set.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.intrusive.rbtree_algorithms"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Class template rbtree_algorithms</span></h2>
<p>boost::intrusive::rbtree_algorithms</p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../intrusive/reference.html#header.boost.intrusive.rbtree_algorithms_hpp" title="Header <boost/intrusive/rbtree_algorithms.hpp>">boost/intrusive/rbtree_algorithms.hpp</a>>
</span><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> NodeTraits<span class="special">></span>
<span class="keyword">class</span> <a class="link" href="rbtree_algorithms.html" title="Class template rbtree_algorithms">rbtree_algorithms</a> <span class="special">{</span>
<span class="keyword">public</span><span class="special">:</span>
<span class="comment">// <a class="link" href="rbtree_algorithms.html#boost.intrusive.rbtree_algorithmstypes">types</a></span>
<span class="keyword">typedef</span> <span class="identifier">NodeTraits</span> <a name="boost.intrusive.rbtree_algorithms.node_traits"></a><span class="identifier">node_traits</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">NodeTraits</span><span class="special">::</span><span class="identifier">node</span> <a name="boost.intrusive.rbtree_algorithms.node"></a><span class="identifier">node</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">NodeTraits</span><span class="special">::</span><span class="identifier">node_ptr</span> <a name="boost.intrusive.rbtree_algorithms.node_ptr"></a><span class="identifier">node_ptr</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">NodeTraits</span><span class="special">::</span><span class="identifier">const_node_ptr</span> <a name="boost.intrusive.rbtree_algorithms.const_node_ptr"></a><span class="identifier">const_node_ptr</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">NodeTraits</span><span class="special">::</span><span class="identifier">color</span> <a name="boost.intrusive.rbtree_algorithms.color"></a><span class="identifier">color</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">bstree_algo</span><span class="special">::</span><span class="identifier">insert_commit_data</span> <a class="link" href="rbtree_algorithms.html#boost.intrusive.rbtree_algorithms.insert_commit_data"><span class="identifier">insert_commit_data</span></a><span class="special">;</span>
<span class="comment">// <a class="link" href="rbtree_algorithms.html#idp78900816-bb">public static functions</a></span>
<span class="keyword">static</span> <span class="identifier">node_ptr</span> <a class="link" href="rbtree_algorithms.html#idp78901376-bb"><span class="identifier">get_header</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">const_node_ptr</span> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">static</span> <span class="identifier">node_ptr</span> <a class="link" href="rbtree_algorithms.html#idp78906752-bb"><span class="identifier">begin_node</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">const_node_ptr</span> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">static</span> <span class="identifier">node_ptr</span> <a class="link" href="rbtree_algorithms.html#idp78912160-bb"><span class="identifier">end_node</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">const_node_ptr</span> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">static</span> <span class="keyword">void</span> <a class="link" href="rbtree_algorithms.html#idp78917536-bb"><span class="identifier">swap_tree</span></a><span class="special">(</span><span class="identifier">node_ptr</span><span class="special">,</span> <span class="identifier">node_ptr</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">static</span> <span class="keyword">void</span> <a class="link" href="rbtree_algorithms.html#idp78923712-bb"><span class="identifier">swap_nodes</span></a><span class="special">(</span><span class="identifier">node_ptr</span><span class="special">,</span> <span class="identifier">node_ptr</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">static</span> <span class="keyword">void</span> <a class="link" href="rbtree_algorithms.html#idp78931168-bb"><span class="identifier">swap_nodes</span></a><span class="special">(</span><span class="identifier">node_ptr</span><span class="special">,</span> <span class="identifier">node_ptr</span><span class="special">,</span> <span class="identifier">node_ptr</span><span class="special">,</span> <span class="identifier">node_ptr</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">static</span> <span class="keyword">void</span> <a class="link" href="rbtree_algorithms.html#idp78940032-bb"><span class="identifier">replace_node</span></a><span class="special">(</span><span class="identifier">node_ptr</span><span class="special">,</span> <span class="identifier">node_ptr</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">static</span> <span class="keyword">void</span> <a class="link" href="rbtree_algorithms.html#idp78947328-bb"><span class="identifier">replace_node</span></a><span class="special">(</span><span class="identifier">node_ptr</span><span class="special">,</span> <span class="identifier">node_ptr</span><span class="special">,</span> <span class="identifier">node_ptr</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">static</span> <span class="keyword">void</span> <a class="link" href="rbtree_algorithms.html#idp78955328-bb"><span class="identifier">unlink</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">node_ptr</span> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">static</span> <span class="identifier">node_ptr</span> <a class="link" href="rbtree_algorithms.html#idp78960736-bb"><span class="identifier">unlink_leftmost_without_rebalance</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">node_ptr</span> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">static</span> <span class="keyword">bool</span> <a class="link" href="rbtree_algorithms.html#idp78967232-bb"><span class="identifier">unique</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">const_node_ptr</span> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">static</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <a class="link" href="rbtree_algorithms.html#idp78972672-bb"><span class="identifier">size</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">const_node_ptr</span> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">static</span> <span class="identifier">node_ptr</span> <a class="link" href="rbtree_algorithms.html#idp78978064-bb"><span class="identifier">next_node</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">node_ptr</span> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">static</span> <span class="identifier">node_ptr</span> <a class="link" href="rbtree_algorithms.html#idp78983456-bb"><span class="identifier">prev_node</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">node_ptr</span> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">static</span> <span class="keyword">void</span> <a class="link" href="rbtree_algorithms.html#idp78988880-bb"><span class="identifier">init</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">node_ptr</span> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">static</span> <span class="keyword">void</span> <a class="link" href="rbtree_algorithms.html#idp78995152-bb"><span class="identifier">init_header</span></a><span class="special">(</span><span class="identifier">node_ptr</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">static</span> <span class="identifier">node_ptr</span> <a class="link" href="rbtree_algorithms.html#idp79001456-bb"><span class="identifier">erase</span></a><span class="special">(</span><span class="identifier">node_ptr</span><span class="special">,</span> <span class="identifier">node_ptr</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> NodePtrCompare<span class="special">></span>
<span class="keyword">static</span> <span class="keyword">bool</span> <a class="link" href="rbtree_algorithms.html#idp79007584-bb"><span class="identifier">transfer_unique</span></a><span class="special">(</span><span class="identifier">node_ptr</span><span class="special">,</span> <span class="identifier">NodePtrCompare</span><span class="special">,</span> <span class="identifier">node_ptr</span><span class="special">,</span> <span class="identifier">node_ptr</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> NodePtrCompare<span class="special">></span>
<span class="keyword">static</span> <span class="keyword">void</span> <a class="link" href="rbtree_algorithms.html#idp79016944-bb"><span class="identifier">transfer_equal</span></a><span class="special">(</span><span class="identifier">node_ptr</span><span class="special">,</span> <span class="identifier">NodePtrCompare</span><span class="special">,</span> <span class="identifier">node_ptr</span><span class="special">,</span> <span class="identifier">node_ptr</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Cloner<span class="special">,</span> <span class="keyword">typename</span> Disposer<span class="special">></span>
<span class="keyword">static</span> <span class="keyword">void</span> <a class="link" href="rbtree_algorithms.html#idp79025376-bb"><span class="identifier">clone</span></a><span class="special">(</span><span class="identifier">const_node_ptr</span><span class="special">,</span> <span class="identifier">node_ptr</span><span class="special">,</span> <span class="identifier">Cloner</span><span class="special">,</span> <span class="identifier">Disposer</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Disposer<span class="special">></span>
<span class="keyword">static</span> <span class="keyword">void</span> <a class="link" href="rbtree_algorithms.html#idp79036400-bb"><span class="identifier">clear_and_dispose</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">node_ptr</span> <span class="special">&</span><span class="special">,</span> <span class="identifier">Disposer</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> KeyType<span class="special">,</span> <span class="keyword">typename</span> KeyNodePtrCompare<span class="special">></span>
<span class="keyword">static</span> <span class="identifier">node_ptr</span>
<a class="link" href="rbtree_algorithms.html#idp79044032-bb"><span class="identifier">lower_bound</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">const_node_ptr</span> <span class="special">&</span><span class="special">,</span> <span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span><span class="special">,</span> <span class="identifier">KeyNodePtrCompare</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> KeyType<span class="special">,</span> <span class="keyword">typename</span> KeyNodePtrCompare<span class="special">></span>
<span class="keyword">static</span> <span class="identifier">node_ptr</span>
<a class="link" href="rbtree_algorithms.html#idp79052496-bb"><span class="identifier">upper_bound</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">const_node_ptr</span> <span class="special">&</span><span class="special">,</span> <span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span><span class="special">,</span> <span class="identifier">KeyNodePtrCompare</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> KeyType<span class="special">,</span> <span class="keyword">typename</span> KeyNodePtrCompare<span class="special">></span>
<span class="keyword">static</span> <span class="identifier">node_ptr</span>
<a class="link" href="rbtree_algorithms.html#idp79060960-bb"><span class="identifier">find</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">const_node_ptr</span> <span class="special">&</span><span class="special">,</span> <span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span><span class="special">,</span> <span class="identifier">KeyNodePtrCompare</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> KeyType<span class="special">,</span> <span class="keyword">typename</span> KeyNodePtrCompare<span class="special">></span>
<span class="keyword">static</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span> <span class="identifier">node_ptr</span><span class="special">,</span> <span class="identifier">node_ptr</span> <span class="special">></span>
<a class="link" href="rbtree_algorithms.html#idp79069424-bb"><span class="identifier">equal_range</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">const_node_ptr</span> <span class="special">&</span><span class="special">,</span> <span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span><span class="special">,</span> <span class="identifier">KeyNodePtrCompare</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> KeyType<span class="special">,</span> <span class="keyword">typename</span> KeyNodePtrCompare<span class="special">></span>
<span class="keyword">static</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span> <span class="identifier">node_ptr</span><span class="special">,</span> <span class="identifier">node_ptr</span> <span class="special">></span>
<a class="link" href="rbtree_algorithms.html#idp79078016-bb"><span class="identifier">bounded_range</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">const_node_ptr</span> <span class="special">&</span><span class="special">,</span> <span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span><span class="special">,</span> <span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span><span class="special">,</span>
<span class="identifier">KeyNodePtrCompare</span><span class="special">,</span> <span class="keyword">bool</span><span class="special">,</span> <span class="keyword">bool</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> KeyType<span class="special">,</span> <span class="keyword">typename</span> KeyNodePtrCompare<span class="special">></span>
<span class="keyword">static</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span>
<a class="link" href="rbtree_algorithms.html#idp79091152-bb"><span class="identifier">count</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">const_node_ptr</span> <span class="special">&</span><span class="special">,</span> <span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span><span class="special">,</span> <span class="identifier">KeyNodePtrCompare</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> NodePtrCompare<span class="special">></span>
<span class="keyword">static</span> <span class="identifier">node_ptr</span>
<a class="link" href="rbtree_algorithms.html#idp79099568-bb"><span class="identifier">insert_equal_upper_bound</span></a><span class="special">(</span><span class="identifier">node_ptr</span><span class="special">,</span> <span class="identifier">node_ptr</span><span class="special">,</span> <span class="identifier">NodePtrCompare</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> NodePtrCompare<span class="special">></span>
<span class="keyword">static</span> <span class="identifier">node_ptr</span>
<a class="link" href="rbtree_algorithms.html#idp79107456-bb"><span class="identifier">insert_equal_lower_bound</span></a><span class="special">(</span><span class="identifier">node_ptr</span><span class="special">,</span> <span class="identifier">node_ptr</span><span class="special">,</span> <span class="identifier">NodePtrCompare</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> NodePtrCompare<span class="special">></span>
<span class="keyword">static</span> <span class="identifier">node_ptr</span> <a class="link" href="rbtree_algorithms.html#idp79115344-bb"><span class="identifier">insert_equal</span></a><span class="special">(</span><span class="identifier">node_ptr</span><span class="special">,</span> <span class="identifier">node_ptr</span><span class="special">,</span> <span class="identifier">node_ptr</span><span class="special">,</span> <span class="identifier">NodePtrCompare</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">static</span> <span class="identifier">node_ptr</span> <a class="link" href="rbtree_algorithms.html#idp79124112-bb"><span class="identifier">insert_before</span></a><span class="special">(</span><span class="identifier">node_ptr</span><span class="special">,</span> <span class="identifier">node_ptr</span><span class="special">,</span> <span class="identifier">node_ptr</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">static</span> <span class="keyword">void</span> <a class="link" href="rbtree_algorithms.html#idp79132080-bb"><span class="identifier">push_back</span></a><span class="special">(</span><span class="identifier">node_ptr</span><span class="special">,</span> <span class="identifier">node_ptr</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">static</span> <span class="keyword">void</span> <a class="link" href="rbtree_algorithms.html#idp79139232-bb"><span class="identifier">push_front</span></a><span class="special">(</span><span class="identifier">node_ptr</span><span class="special">,</span> <span class="identifier">node_ptr</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> KeyType<span class="special">,</span> <span class="keyword">typename</span> KeyNodePtrCompare<span class="special">></span>
<span class="keyword">static</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span> <span class="identifier">node_ptr</span><span class="special">,</span> <span class="keyword">bool</span> <span class="special">></span>
<a class="link" href="rbtree_algorithms.html#idp79146384-bb"><span class="identifier">insert_unique_check</span></a><span class="special">(</span><span class="identifier">const_node_ptr</span><span class="special">,</span> <span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span><span class="special">,</span> <span class="identifier">KeyNodePtrCompare</span><span class="special">,</span>
<span class="identifier">insert_commit_data</span> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> KeyType<span class="special">,</span> <span class="keyword">typename</span> KeyNodePtrCompare<span class="special">></span>
<span class="keyword">static</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span> <span class="identifier">node_ptr</span><span class="special">,</span> <span class="keyword">bool</span> <span class="special">></span>
<a class="link" href="rbtree_algorithms.html#idp79158960-bb"><span class="identifier">insert_unique_check</span></a><span class="special">(</span><span class="identifier">const_node_ptr</span><span class="special">,</span> <span class="identifier">node_ptr</span><span class="special">,</span> <span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span><span class="special">,</span>
<span class="identifier">KeyNodePtrCompare</span><span class="special">,</span> <span class="identifier">insert_commit_data</span> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">static</span> <span class="keyword">void</span> <a class="link" href="rbtree_algorithms.html#idp79172528-bb"><span class="identifier">insert_unique_commit</span></a><span class="special">(</span><span class="identifier">node_ptr</span><span class="special">,</span> <span class="identifier">node_ptr</span><span class="special">,</span>
<span class="keyword">const</span> <span class="identifier">insert_commit_data</span> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">static</span> <span class="keyword">bool</span> <a class="link" href="rbtree_algorithms.html#idp79180672-bb"><span class="identifier">is_header</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">const_node_ptr</span> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="special">}</span><span class="special">;</span></pre></div>
<div class="refsect1">
<a name="id-1.3.20.42.29.3.4"></a><h2>Description</h2>
<p><a class="link" href="rbtree_algorithms.html" title="Class template rbtree_algorithms">rbtree_algorithms</a> provides basic algorithms to manipulate nodes forming a red-black tree. The insertion and deletion algorithms are based on those in Cormen, Leiserson, and Rivest, Introduction to Algorithms (MIT Press, 1990), except that</p>
<p>(1) the header node is maintained with links not only to the root but also to the leftmost node of the tree, to enable constant time begin(), and to the rightmost node of the tree, to enable linear time performance when used with the generic set algorithms (set_union, etc.);</p>
<p>(2) when a node being deleted has two children its successor node is relinked into its place, rather than copied, so that the only pointers invalidated are those referring to the deleted node.</p>
<p><a class="link" href="rbtree_algorithms.html" title="Class template rbtree_algorithms">rbtree_algorithms</a> is configured with a NodeTraits class, which encapsulates the information about the node to be manipulated. NodeTraits must support the following interface:</p>
<p><span class="bold"><strong>Typedefs</strong></span>:</p>
<p><code class="computeroutput">node</code>: The type of the node that forms the binary search tree</p>
<p><code class="computeroutput">node_ptr</code>: A pointer to a node</p>
<p><code class="computeroutput">const_node_ptr</code>: A pointer to a const node</p>
<p><code class="computeroutput">color</code>: The type that can store the color of a node</p>
<p><span class="bold"><strong>Static functions</strong></span>:</p>
<p><code class="computeroutput">static node_ptr get_parent(const_node_ptr n);</code></p>
<p><code class="computeroutput">static void set_parent(node_ptr n, node_ptr parent);</code></p>
<p><code class="computeroutput">static node_ptr get_left(const_node_ptr n);</code></p>
<p><code class="computeroutput">static void set_left(node_ptr n, node_ptr left);</code></p>
<p><code class="computeroutput">static node_ptr get_right(const_node_ptr n);</code></p>
<p><code class="computeroutput">static void set_right(node_ptr n, node_ptr right);</code></p>
<p><code class="computeroutput">static color get_color(const_node_ptr n);</code></p>
<p><code class="computeroutput">static void set_color(node_ptr n, color c);</code></p>
<p><code class="computeroutput">static color black();</code></p>
<p><code class="computeroutput">static color red();</code> </p>
<div class="refsect2">
<a name="id-1.3.20.42.29.3.4.22"></a><h3>
<a name="boost.intrusive.rbtree_algorithmstypes"></a><code class="computeroutput">rbtree_algorithms</code>
public
types</h3>
<div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem">
<p>
<span class="keyword">typedef</span> <span class="identifier">bstree_algo</span><span class="special">::</span><span class="identifier">insert_commit_data</span> <a name="boost.intrusive.rbtree_algorithms.insert_commit_data"></a><span class="identifier">insert_commit_data</span><span class="special">;</span></p>
<p>This type is the information that will be filled by insert_unique_check </p>
</li></ol></div>
</div>
<div class="refsect2">
<a name="id-1.3.20.42.29.3.4.23"></a><h3>
<a name="idp78900816-bb"></a><code class="computeroutput">rbtree_algorithms</code> public static functions</h3>
<div class="orderedlist"><ol class="orderedlist" type="1">
<li class="listitem">
<pre class="literallayout"><span class="keyword">static</span> <span class="identifier">node_ptr</span> <a name="idp78901376-bb"></a><span class="identifier">get_header</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">const_node_ptr</span> <span class="special">&</span> n<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: 'node' is a node of the tree or a header node.</p>
<p><span class="bold"><strong>Effects</strong></span>: Returns the header of the tree.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Logarithmic.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing. </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">static</span> <span class="identifier">node_ptr</span> <a name="idp78906752-bb"></a><span class="identifier">begin_node</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">const_node_ptr</span> <span class="special">&</span> header<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: 'header' is the header node of a tree.</p>
<p><span class="bold"><strong>Effects</strong></span>: Returns the first node of the tree, the header if the tree is empty.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant time.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing. </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">static</span> <span class="identifier">node_ptr</span> <a name="idp78912160-bb"></a><span class="identifier">end_node</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">const_node_ptr</span> <span class="special">&</span> header<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: 'header' is the header node of a tree.</p>
<p><span class="bold"><strong>Effects</strong></span>: Returns the header of the tree.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant time.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing. </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">static</span> <span class="keyword">void</span> <a name="idp78917536-bb"></a><span class="identifier">swap_tree</span><span class="special">(</span><span class="identifier">node_ptr</span> header1<span class="special">,</span> <span class="identifier">node_ptr</span> header2<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: header1 and header2 must be the header nodes of two trees.</p>
<p><span class="bold"><strong>Effects</strong></span>: Swaps two trees. After the function header1 will contain links to the second tree and header2 will have links to the first tree.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing. </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">static</span> <span class="keyword">void</span> <a name="idp78923712-bb"></a><span class="identifier">swap_nodes</span><span class="special">(</span><span class="identifier">node_ptr</span> node1<span class="special">,</span> <span class="identifier">node_ptr</span> node2<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: node1 and node2 can't be header nodes of two trees.</p>
<p><span class="bold"><strong>Effects</strong></span>: Swaps two nodes. After the function node1 will be inserted in the position node2 before the function. node2 will be inserted in the position node1 had before the function.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Logarithmic.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing.</p>
<p><span class="bold"><strong>Note</strong></span>: This function will break container ordering invariants if node1 and node2 are not equivalent according to the ordering rules.</p>
<p>Experimental function </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">static</span> <span class="keyword">void</span> <a name="idp78931168-bb"></a><span class="identifier">swap_nodes</span><span class="special">(</span><span class="identifier">node_ptr</span> node1<span class="special">,</span> <span class="identifier">node_ptr</span> header1<span class="special">,</span> <span class="identifier">node_ptr</span> node2<span class="special">,</span>
<span class="identifier">node_ptr</span> header2<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: node1 and node2 can't be header nodes of two trees with header header1 and header2.</p>
<p><span class="bold"><strong>Effects</strong></span>: Swaps two nodes. After the function node1 will be inserted in the position node2 before the function. node2 will be inserted in the position node1 had before the function.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing.</p>
<p><span class="bold"><strong>Note</strong></span>: This function will break container ordering invariants if node1 and node2 are not equivalent according to the ordering rules.</p>
<p>Experimental function </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">static</span> <span class="keyword">void</span> <a name="idp78940032-bb"></a><span class="identifier">replace_node</span><span class="special">(</span><span class="identifier">node_ptr</span> node_to_be_replaced<span class="special">,</span> <span class="identifier">node_ptr</span> new_node<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: node_to_be_replaced must be inserted in a tree and new_node must not be inserted in a tree.</p>
<p><span class="bold"><strong>Effects</strong></span>: Replaces node_to_be_replaced in its position in the tree with new_node. The tree does not need to be rebalanced</p>
<p><span class="bold"><strong>Complexity</strong></span>: Logarithmic.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing.</p>
<p><span class="bold"><strong>Note</strong></span>: This function will break container ordering invariants if new_node is not equivalent to node_to_be_replaced according to the ordering rules. This function is faster than erasing and inserting the node, since no rebalancing and comparison is needed. Experimental function </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">static</span> <span class="keyword">void</span> <a name="idp78947328-bb"></a><span class="identifier">replace_node</span><span class="special">(</span><span class="identifier">node_ptr</span> node_to_be_replaced<span class="special">,</span> <span class="identifier">node_ptr</span> header<span class="special">,</span>
<span class="identifier">node_ptr</span> new_node<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: node_to_be_replaced must be inserted in a tree with header "header" and new_node must not be inserted in a tree.</p>
<p><span class="bold"><strong>Effects</strong></span>: Replaces node_to_be_replaced in its position in the tree with new_node. The tree does not need to be rebalanced</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing.</p>
<p><span class="bold"><strong>Note</strong></span>: This function will break container ordering invariants if new_node is not equivalent to node_to_be_replaced according to the ordering rules. This function is faster than erasing and inserting the node, since no rebalancing or comparison is needed. Experimental function </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">static</span> <span class="keyword">void</span> <a name="idp78955328-bb"></a><span class="identifier">unlink</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">node_ptr</span> <span class="special">&</span> node<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: node is a tree node but not the header.</p>
<p><span class="bold"><strong>Effects</strong></span>: Unlinks the node and rebalances the tree.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Average complexity is constant time.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing. </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">static</span> <span class="identifier">node_ptr</span> <a name="idp78960736-bb"></a><span class="identifier">unlink_leftmost_without_rebalance</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">node_ptr</span> <span class="special">&</span> header<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: header is the header of a tree.</p>
<p><span class="bold"><strong>Effects</strong></span>: Unlinks the leftmost node from the tree, and updates the header link to the new leftmost node.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Average complexity is constant time.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing.</p>
<p><span class="bold"><strong>Notes</strong></span>: This function breaks the tree and the tree can only be used for more unlink_leftmost_without_rebalance calls. This function is normally used to achieve a step by step controlled destruction of the tree. </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">static</span> <span class="keyword">bool</span> <a name="idp78967232-bb"></a><span class="identifier">unique</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">const_node_ptr</span> <span class="special">&</span> node<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: 'node' is a node of the tree or a node initialized by init(...) or init_node.</p>
<p><span class="bold"><strong>Effects</strong></span>: Returns true if the node is initialized by init() or init_node().</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant time.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing. </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">static</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <a name="idp78972672-bb"></a><span class="identifier">size</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">const_node_ptr</span> <span class="special">&</span> header<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: node is a node of the tree but it's not the header.</p>
<p><span class="bold"><strong>Effects</strong></span>: Returns the number of nodes of the subtree.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Linear time.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing. </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">static</span> <span class="identifier">node_ptr</span> <a name="idp78978064-bb"></a><span class="identifier">next_node</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">node_ptr</span> <span class="special">&</span> node<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: 'node' is a node from the tree except the header.</p>
<p><span class="bold"><strong>Effects</strong></span>: Returns the next node of the tree.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Average constant time.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing. </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">static</span> <span class="identifier">node_ptr</span> <a name="idp78983456-bb"></a><span class="identifier">prev_node</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">node_ptr</span> <span class="special">&</span> node<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: 'node' is a node from the tree except the leftmost node.</p>
<p><span class="bold"><strong>Effects</strong></span>: Returns the previous node of the tree.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Average constant time.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing. </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">static</span> <span class="keyword">void</span> <a name="idp78988880-bb"></a><span class="identifier">init</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">node_ptr</span> <span class="special">&</span> node<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: 'node' must not be part of any tree.</p>
<p><span class="bold"><strong>Effects</strong></span>: After the function unique(node) == true.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing.</p>
<p><span class="bold"><strong>Nodes</strong></span>: If node is inserted in a tree, this function corrupts the tree. </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">static</span> <span class="keyword">void</span> <a name="idp78995152-bb"></a><span class="identifier">init_header</span><span class="special">(</span><span class="identifier">node_ptr</span> header<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: node must not be part of any tree.</p>
<p><span class="bold"><strong>Effects</strong></span>: Initializes the header to represent an empty tree. unique(header) == true.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing.</p>
<p><span class="bold"><strong>Nodes</strong></span>: If node is inserted in a tree, this function corrupts the tree. </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">static</span> <span class="identifier">node_ptr</span> <a name="idp79001456-bb"></a><span class="identifier">erase</span><span class="special">(</span><span class="identifier">node_ptr</span> header<span class="special">,</span> <span class="identifier">node_ptr</span> z<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: header must be the header of a tree, z a node of that tree and z != header.</p>
<p><span class="bold"><strong>Effects</strong></span>: Erases node "z" from the tree with header "header".</p>
<p><span class="bold"><strong>Complexity</strong></span>: Amortized constant time.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing. </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> NodePtrCompare<span class="special">></span>
<span class="keyword">static</span> <span class="keyword">bool</span> <a name="idp79007584-bb"></a><span class="identifier">transfer_unique</span><span class="special">(</span><span class="identifier">node_ptr</span> header1<span class="special">,</span> <span class="identifier">NodePtrCompare</span> comp<span class="special">,</span>
<span class="identifier">node_ptr</span> header2<span class="special">,</span> <span class="identifier">node_ptr</span> z<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: header1 and header2 must be the headers of trees tree1 and tree2 respectively, z a non-header node of tree1. NodePtrCompare is the comparison function of tree1..</p>
<p><span class="bold"><strong>Effects</strong></span>: Transfers node "z" from tree1 to tree2 if tree1 does not contain a node that is equivalent to z.</p>
<p><span class="bold"><strong>Returns</strong></span>: True if the node was trasferred, false otherwise.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Logarithmic.</p>
<p><span class="bold"><strong>Throws</strong></span>: If the comparison throws. </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> NodePtrCompare<span class="special">></span>
<span class="keyword">static</span> <span class="keyword">void</span> <a name="idp79016944-bb"></a><span class="identifier">transfer_equal</span><span class="special">(</span><span class="identifier">node_ptr</span> header1<span class="special">,</span> <span class="identifier">NodePtrCompare</span> comp<span class="special">,</span>
<span class="identifier">node_ptr</span> header2<span class="special">,</span> <span class="identifier">node_ptr</span> z<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: header1 and header2 must be the headers of trees tree1 and tree2 respectively, z a non-header node of tree1. NodePtrCompare is the comparison function of tree1..</p>
<p><span class="bold"><strong>Effects</strong></span>: Transfers node "z" from tree1 to tree2.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Logarithmic.</p>
<p><span class="bold"><strong>Throws</strong></span>: If the comparison throws. </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Cloner<span class="special">,</span> <span class="keyword">typename</span> Disposer<span class="special">></span>
<span class="keyword">static</span> <span class="keyword">void</span> <a name="idp79025376-bb"></a><span class="identifier">clone</span><span class="special">(</span><span class="identifier">const_node_ptr</span> source_header<span class="special">,</span> <span class="identifier">node_ptr</span> target_header<span class="special">,</span>
<span class="identifier">Cloner</span> cloner<span class="special">,</span> <span class="identifier">Disposer</span> disposer<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: "cloner" must be a function object taking a node_ptr and returning a new cloned node of it. "disposer" must take a node_ptr and shouldn't throw.</p>
<p><span class="bold"><strong>Effects</strong></span>: First empties target tree calling <code class="computeroutput">void disposer::operator()(const node_ptr &)</code> for every node of the tree except the header.</p>
<p>Then, duplicates the entire tree pointed by "source_header" cloning each source node with <code class="computeroutput">node_ptr Cloner::operator()(const node_ptr &)</code> to obtain the nodes of the target tree. If "cloner" throws, the cloned target nodes are disposed using <code class="computeroutput">void disposer(const node_ptr &)</code>.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Linear to the number of element of the source tree plus the number of elements of tree target tree when calling this function.</p>
<p><span class="bold"><strong>Throws</strong></span>: If cloner functor throws. If this happens target nodes are disposed. </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Disposer<span class="special">></span>
<span class="keyword">static</span> <span class="keyword">void</span> <a name="idp79036400-bb"></a><span class="identifier">clear_and_dispose</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">node_ptr</span> <span class="special">&</span> header<span class="special">,</span> <span class="identifier">Disposer</span> disposer<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: "disposer" must be an object function taking a node_ptr parameter and shouldn't throw.</p>
<p><span class="bold"><strong>Effects</strong></span>: Empties the target tree calling <code class="computeroutput">void disposer::operator()(const node_ptr &)</code> for every node of the tree except the header.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Linear to the number of element of the source tree plus the. number of elements of tree target tree when calling this function.</p>
<p><span class="bold"><strong>Throws</strong></span>: If cloner functor throws. If this happens target nodes are disposed. </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> KeyType<span class="special">,</span> <span class="keyword">typename</span> KeyNodePtrCompare<span class="special">></span>
<span class="keyword">static</span> <span class="identifier">node_ptr</span>
<a name="idp79044032-bb"></a><span class="identifier">lower_bound</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">const_node_ptr</span> <span class="special">&</span> header<span class="special">,</span> <span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span> key<span class="special">,</span>
<span class="identifier">KeyNodePtrCompare</span> comp<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: "header" must be the header node of a tree. KeyNodePtrCompare is a function object that induces a strict weak ordering compatible with the strict weak ordering used to create the the tree. KeyNodePtrCompare can compare KeyType with tree's node_ptrs.</p>
<p><span class="bold"><strong>Effects</strong></span>: Returns a node_ptr to the first element that is not less than "key" according to "comp" or "header" if that element does not exist.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Logarithmic.</p>
<p><span class="bold"><strong>Throws</strong></span>: If "comp" throws. </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> KeyType<span class="special">,</span> <span class="keyword">typename</span> KeyNodePtrCompare<span class="special">></span>
<span class="keyword">static</span> <span class="identifier">node_ptr</span>
<a name="idp79052496-bb"></a><span class="identifier">upper_bound</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">const_node_ptr</span> <span class="special">&</span> header<span class="special">,</span> <span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span> key<span class="special">,</span>
<span class="identifier">KeyNodePtrCompare</span> comp<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: "header" must be the header node of a tree. KeyNodePtrCompare is a function object that induces a strict weak ordering compatible with the strict weak ordering used to create the the tree. KeyNodePtrCompare can compare KeyType with tree's node_ptrs.</p>
<p><span class="bold"><strong>Effects</strong></span>: Returns a node_ptr to the first element that is greater than "key" according to "comp" or "header" if that element does not exist.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Logarithmic.</p>
<p><span class="bold"><strong>Throws</strong></span>: If "comp" throws. </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> KeyType<span class="special">,</span> <span class="keyword">typename</span> KeyNodePtrCompare<span class="special">></span>
<span class="keyword">static</span> <span class="identifier">node_ptr</span>
<a name="idp79060960-bb"></a><span class="identifier">find</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">const_node_ptr</span> <span class="special">&</span> header<span class="special">,</span> <span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span> key<span class="special">,</span>
<span class="identifier">KeyNodePtrCompare</span> comp<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: "header" must be the header node of a tree. KeyNodePtrCompare is a function object that induces a strict weak ordering compatible with the strict weak ordering used to create the the tree. KeyNodePtrCompare can compare KeyType with tree's node_ptrs.</p>
<p><span class="bold"><strong>Effects</strong></span>: Returns a node_ptr to the first element that is equivalent to "key" according to "comp" or "header" if that element does not exist.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Logarithmic.</p>
<p><span class="bold"><strong>Throws</strong></span>: If "comp" throws. </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> KeyType<span class="special">,</span> <span class="keyword">typename</span> KeyNodePtrCompare<span class="special">></span>
<span class="keyword">static</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span> <span class="identifier">node_ptr</span><span class="special">,</span> <span class="identifier">node_ptr</span> <span class="special">></span>
<a name="idp79069424-bb"></a><span class="identifier">equal_range</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">const_node_ptr</span> <span class="special">&</span> header<span class="special">,</span> <span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span> key<span class="special">,</span>
<span class="identifier">KeyNodePtrCompare</span> comp<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: "header" must be the header node of a tree. KeyNodePtrCompare is a function object that induces a strict weak ordering compatible with the strict weak ordering used to create the the tree. KeyNodePtrCompare can compare KeyType with tree's node_ptrs.</p>
<p><span class="bold"><strong>Effects</strong></span>: Returns an a pair of node_ptr delimiting a range containing all elements that are equivalent to "key" according to "comp" or an empty range that indicates the position where those elements would be if there are no equivalent elements.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Logarithmic.</p>
<p><span class="bold"><strong>Throws</strong></span>: If "comp" throws. </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> KeyType<span class="special">,</span> <span class="keyword">typename</span> KeyNodePtrCompare<span class="special">></span>
<span class="keyword">static</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span> <span class="identifier">node_ptr</span><span class="special">,</span> <span class="identifier">node_ptr</span> <span class="special">></span>
<a name="idp79078016-bb"></a><span class="identifier">bounded_range</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">const_node_ptr</span> <span class="special">&</span> header<span class="special">,</span> <span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span> lower_key<span class="special">,</span>
<span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span> upper_key<span class="special">,</span> <span class="identifier">KeyNodePtrCompare</span> comp<span class="special">,</span>
<span class="keyword">bool</span> left_closed<span class="special">,</span> <span class="keyword">bool</span> right_closed<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: "header" must be the header node of a tree. KeyNodePtrCompare is a function object that induces a strict weak ordering compatible with the strict weak ordering used to create the the tree. KeyNodePtrCompare can compare KeyType with tree's node_ptrs. 'lower_key' must not be greater than 'upper_key' according to 'comp'. If 'lower_key' == 'upper_key', ('left_closed' || 'right_closed') must be true.</p>
<p><span class="bold"><strong>Effects</strong></span>: Returns an a pair with the following criteria:</p>
<p>first = lower_bound(lower_key) if left_closed, upper_bound(lower_key) otherwise</p>
<p>second = upper_bound(upper_key) if right_closed, lower_bound(upper_key) otherwise</p>
<p><span class="bold"><strong>Complexity</strong></span>: Logarithmic.</p>
<p><span class="bold"><strong>Throws</strong></span>: If "comp" throws.</p>
<p><span class="bold"><strong>Note</strong></span>: This function can be more efficient than calling upper_bound and lower_bound for lower_key and upper_key.</p>
<p><span class="bold"><strong>Note</strong></span>: Experimental function, the interface might change. </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> KeyType<span class="special">,</span> <span class="keyword">typename</span> KeyNodePtrCompare<span class="special">></span>
<span class="keyword">static</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span>
<a name="idp79091152-bb"></a><span class="identifier">count</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">const_node_ptr</span> <span class="special">&</span> header<span class="special">,</span> <span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span> key<span class="special">,</span>
<span class="identifier">KeyNodePtrCompare</span> comp<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: "header" must be the header node of a tree. KeyNodePtrCompare is a function object that induces a strict weak ordering compatible with the strict weak ordering used to create the the tree. KeyNodePtrCompare can compare KeyType with tree's node_ptrs.</p>
<p><span class="bold"><strong>Effects</strong></span>: Returns the number of elements with a key equivalent to "key" according to "comp".</p>
<p><span class="bold"><strong>Complexity</strong></span>: Logarithmic.</p>
<p><span class="bold"><strong>Throws</strong></span>: If "comp" throws. </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> NodePtrCompare<span class="special">></span>
<span class="keyword">static</span> <span class="identifier">node_ptr</span>
<a name="idp79099568-bb"></a><span class="identifier">insert_equal_upper_bound</span><span class="special">(</span><span class="identifier">node_ptr</span> h<span class="special">,</span> <span class="identifier">node_ptr</span> new_node<span class="special">,</span> <span class="identifier">NodePtrCompare</span> comp<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: "h" must be the header node of a tree. NodePtrCompare is a function object that induces a strict weak ordering compatible with the strict weak ordering used to create the the tree. NodePtrCompare compares two node_ptrs.</p>
<p><span class="bold"><strong>Effects</strong></span>: Inserts new_node into the tree before the upper bound according to "comp".</p>
<p><span class="bold"><strong>Complexity</strong></span>: Average complexity for insert element is at most logarithmic.</p>
<p><span class="bold"><strong>Throws</strong></span>: If "comp" throws. </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> NodePtrCompare<span class="special">></span>
<span class="keyword">static</span> <span class="identifier">node_ptr</span>
<a name="idp79107456-bb"></a><span class="identifier">insert_equal_lower_bound</span><span class="special">(</span><span class="identifier">node_ptr</span> h<span class="special">,</span> <span class="identifier">node_ptr</span> new_node<span class="special">,</span> <span class="identifier">NodePtrCompare</span> comp<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: "h" must be the header node of a tree. NodePtrCompare is a function object that induces a strict weak ordering compatible with the strict weak ordering used to create the the tree. NodePtrCompare compares two node_ptrs.</p>
<p><span class="bold"><strong>Effects</strong></span>: Inserts new_node into the tree before the lower bound according to "comp".</p>
<p><span class="bold"><strong>Complexity</strong></span>: Average complexity for insert element is at most logarithmic.</p>
<p><span class="bold"><strong>Throws</strong></span>: If "comp" throws. </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> NodePtrCompare<span class="special">></span>
<span class="keyword">static</span> <span class="identifier">node_ptr</span>
<a name="idp79115344-bb"></a><span class="identifier">insert_equal</span><span class="special">(</span><span class="identifier">node_ptr</span> header<span class="special">,</span> <span class="identifier">node_ptr</span> hint<span class="special">,</span> <span class="identifier">node_ptr</span> new_node<span class="special">,</span>
<span class="identifier">NodePtrCompare</span> comp<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: "header" must be the header node of a tree. NodePtrCompare is a function object that induces a strict weak ordering compatible with the strict weak ordering used to create the the tree. NodePtrCompare compares two node_ptrs. "hint" is node from the "header"'s tree.</p>
<p><span class="bold"><strong>Effects</strong></span>: Inserts new_node into the tree, using "hint" as a hint to where it will be inserted. If "hint" is the upper_bound the insertion takes constant time (two comparisons in the worst case).</p>
<p><span class="bold"><strong>Complexity</strong></span>: Logarithmic in general, but it is amortized constant time if new_node is inserted immediately before "hint".</p>
<p><span class="bold"><strong>Throws</strong></span>: If "comp" throws. </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">static</span> <span class="identifier">node_ptr</span>
<a name="idp79124112-bb"></a><span class="identifier">insert_before</span><span class="special">(</span><span class="identifier">node_ptr</span> header<span class="special">,</span> <span class="identifier">node_ptr</span> pos<span class="special">,</span> <span class="identifier">node_ptr</span> new_node<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: "header" must be the header node of a tree. "pos" must be a valid iterator or header (end) node. "pos" must be an iterator pointing to the successor to "new_node" once inserted according to the order of already inserted nodes. This function does not check "pos" and this precondition must be guaranteed by the caller.</p>
<p><span class="bold"><strong>Effects</strong></span>: Inserts new_node into the tree before "pos".</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant-time.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing.</p>
<p><span class="bold"><strong>Note</strong></span>: If "pos" is not the successor of the newly inserted "new_node" tree invariants might be broken. </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">static</span> <span class="keyword">void</span> <a name="idp79132080-bb"></a><span class="identifier">push_back</span><span class="special">(</span><span class="identifier">node_ptr</span> header<span class="special">,</span> <span class="identifier">node_ptr</span> new_node<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: "header" must be the header node of a tree. "new_node" must be, according to the used ordering no less than the greatest inserted key.</p>
<p><span class="bold"><strong>Effects</strong></span>: Inserts new_node into the tree before "pos".</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant-time.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing.</p>
<p><span class="bold"><strong>Note</strong></span>: If "new_node" is less than the greatest inserted key tree invariants are broken. This function is slightly faster than using "insert_before". </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">static</span> <span class="keyword">void</span> <a name="idp79139232-bb"></a><span class="identifier">push_front</span><span class="special">(</span><span class="identifier">node_ptr</span> header<span class="special">,</span> <span class="identifier">node_ptr</span> new_node<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: "header" must be the header node of a tree. "new_node" must be, according to the used ordering, no greater than the lowest inserted key.</p>
<p><span class="bold"><strong>Effects</strong></span>: Inserts new_node into the tree before "pos".</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant-time.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing.</p>
<p><span class="bold"><strong>Note</strong></span>: If "new_node" is greater than the lowest inserted key tree invariants are broken. This function is slightly faster than using "insert_before". </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> KeyType<span class="special">,</span> <span class="keyword">typename</span> KeyNodePtrCompare<span class="special">></span>
<span class="keyword">static</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span> <span class="identifier">node_ptr</span><span class="special">,</span> <span class="keyword">bool</span> <span class="special">></span>
<a name="idp79146384-bb"></a><span class="identifier">insert_unique_check</span><span class="special">(</span><span class="identifier">const_node_ptr</span> header<span class="special">,</span> <span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span> key<span class="special">,</span>
<span class="identifier">KeyNodePtrCompare</span> comp<span class="special">,</span>
<span class="identifier">insert_commit_data</span> <span class="special">&</span> commit_data<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: "header" must be the header node of a tree. KeyNodePtrCompare is a function object that induces a strict weak ordering compatible with the strict weak ordering used to create the the tree. NodePtrCompare compares KeyType with a node_ptr.</p>
<p><span class="bold"><strong>Effects</strong></span>: Checks if there is an equivalent node to "key" in the tree according to "comp" and obtains the needed information to realize a constant-time node insertion if there is no equivalent node.</p>
<p><span class="bold"><strong>Returns</strong></span>: If there is an equivalent value returns a pair containing a node_ptr to the already present node and false. If there is not equivalent key can be inserted returns true in the returned pair's boolean and fills "commit_data" that is meant to be used with the "insert_commit" function to achieve a constant-time insertion function.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Average complexity is at most logarithmic.</p>
<p><span class="bold"><strong>Throws</strong></span>: If "comp" throws.</p>
<p><span class="bold"><strong>Notes</strong></span>: This function is used to improve performance when constructing a node is expensive and the user does not want to have two equivalent nodes in the tree: if there is an equivalent value the constructed object must be discarded. Many times, the part of the node that is used to impose the order is much cheaper to construct than the node and this function offers the possibility to use that part to check if the insertion will be successful.</p>
<p>If the check is successful, the user can construct the node and use "insert_commit" to insert the node in constant-time. This gives a total logarithmic complexity to the insertion: check(O(log(N)) + commit(O(1)).</p>
<p>"commit_data" remains valid for a subsequent "insert_unique_commit" only if no more objects are inserted or erased from the set. </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> KeyType<span class="special">,</span> <span class="keyword">typename</span> KeyNodePtrCompare<span class="special">></span>
<span class="keyword">static</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span> <span class="identifier">node_ptr</span><span class="special">,</span> <span class="keyword">bool</span> <span class="special">></span>
<a name="idp79158960-bb"></a><span class="identifier">insert_unique_check</span><span class="special">(</span><span class="identifier">const_node_ptr</span> header<span class="special">,</span> <span class="identifier">node_ptr</span> hint<span class="special">,</span>
<span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span> key<span class="special">,</span> <span class="identifier">KeyNodePtrCompare</span> comp<span class="special">,</span>
<span class="identifier">insert_commit_data</span> <span class="special">&</span> commit_data<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: "header" must be the header node of a tree. KeyNodePtrCompare is a function object that induces a strict weak ordering compatible with the strict weak ordering used to create the the tree. NodePtrCompare compares KeyType with a node_ptr. "hint" is node from the "header"'s tree.</p>
<p><span class="bold"><strong>Effects</strong></span>: Checks if there is an equivalent node to "key" in the tree according to "comp" using "hint" as a hint to where it should be inserted and obtains the needed information to realize a constant-time node insertion if there is no equivalent node. If "hint" is the upper_bound the function has constant time complexity (two comparisons in the worst case).</p>
<p><span class="bold"><strong>Returns</strong></span>: If there is an equivalent value returns a pair containing a node_ptr to the already present node and false. If there is not equivalent key can be inserted returns true in the returned pair's boolean and fills "commit_data" that is meant to be used with the "insert_commit" function to achieve a constant-time insertion function.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Average complexity is at most logarithmic, but it is amortized constant time if new_node should be inserted immediately before "hint".</p>
<p><span class="bold"><strong>Throws</strong></span>: If "comp" throws.</p>
<p><span class="bold"><strong>Notes</strong></span>: This function is used to improve performance when constructing a node is expensive and the user does not want to have two equivalent nodes in the tree: if there is an equivalent value the constructed object must be discarded. Many times, the part of the node that is used to impose the order is much cheaper to construct than the node and this function offers the possibility to use that part to check if the insertion will be successful.</p>
<p>If the check is successful, the user can construct the node and use "insert_commit" to insert the node in constant-time. This gives a total logarithmic complexity to the insertion: check(O(log(N)) + commit(O(1)).</p>
<p>"commit_data" remains valid for a subsequent "insert_unique_commit" only if no more objects are inserted or erased from the set. </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">static</span> <span class="keyword">void</span> <a name="idp79172528-bb"></a><span class="identifier">insert_unique_commit</span><span class="special">(</span><span class="identifier">node_ptr</span> header<span class="special">,</span> <span class="identifier">node_ptr</span> new_value<span class="special">,</span>
<span class="keyword">const</span> <span class="identifier">insert_commit_data</span> <span class="special">&</span> commit_data<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: "header" must be the header node of a tree. "commit_data" must have been obtained from a previous call to "insert_unique_check". No objects should have been inserted or erased from the set between the "insert_unique_check" that filled "commit_data" and the call to "insert_commit".</p>
<p><span class="bold"><strong>Effects</strong></span>: Inserts new_node in the set using the information obtained from the "commit_data" that a previous "insert_check" filled.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant time.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing.</p>
<p><span class="bold"><strong>Notes</strong></span>: This function has only sense if a "insert_unique_check" has been previously executed to fill "commit_data". No value should be inserted or erased between the "insert_check" and "insert_commit" calls. </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">static</span> <span class="keyword">bool</span> <a name="idp79180672-bb"></a><span class="identifier">is_header</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">const_node_ptr</span> <span class="special">&</span> p<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: p is a node of a tree.</p>
<p><span class="bold"><strong>Effects</strong></span>: Returns true if p is the header of the tree.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing. </p>
</li>
</ol></div>
</div>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2005 Olaf Krzikalla<br>Copyright © 2006-2015 Ion Gaztanaga<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="make_rbtree.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../intrusive/reference.html#header.boost.intrusive.rbtree_algorithms_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="set.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| mit |
nazar/DarkFallSage | vendor/plugins/smurf/test/rails/public/stylesheets/cache/expected.css | 814 | html{color:#000;background:#FFF}body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,textarea,p,blockquote,th,td{margin:0;padding:0}table{border-collapse:collapse;border-spacing:0}fieldset,img{border:0}address,caption,cite,code,dfn,em,strong,th,var{font-style:normal;font-weight:normal}li{list-style:none}caption,th{text-align:left}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal}q:before,q:after{content:''}abbr,acronym{border:0;font-variant:normal}sup{vertical-align:text-top}sub{vertical-align:text-bottom}input,textarea,select{font-family:inherit;font-size:inherit;font-weight:inherit}input,textarea,select{*font-size:100%}legend{color:#000}del,ins{text-decoration:none}smurf{content:"pa pa"}.smurf :link li{color:blue}smurf #smurf,:smurf .smurf{color:black}smurfdom{papa:smurf} | mit |
TyRoXx/cdm | original_sources/boost_1_59_0/doc/html/boost/accumulators/feature_of_tag_idp65056752.html | 4874 | <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Struct feature_of<tag::immediate_mean_of_weights></title>
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../../accumulators/reference.html#header.boost.accumulators.statistics.mean_hpp" title="Header <boost/accumulators/statistics/mean.hpp>">
<link rel="prev" href="feature_of_tag_idp65053584.html" title="Struct template feature_of<tag::immediate_mean_of_variates< VariateType, VariateTag >>">
<link rel="next" href="feature_of_tag_idp65058464.html" title="Struct feature_of<tag::immediate_weighted_mean>">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td>
<td align="center"><a href="../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="feature_of_tag_idp65053584.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../accumulators/reference.html#header.boost.accumulators.statistics.mean_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="feature_of_tag_idp65058464.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.accumulators.feature_of_tag_idp65056752"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Struct feature_of<tag::immediate_mean_of_weights></span></h2>
<p>boost::accumulators::feature_of<tag::immediate_mean_of_weights></p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../accumulators/reference.html#header.boost.accumulators.statistics.mean_hpp" title="Header <boost/accumulators/statistics/mean.hpp>">boost/accumulators/statistics/mean.hpp</a>>
</span>
<span class="keyword">struct</span> <a class="link" href="feature_of_tag_idp65056752.html" title="Struct feature_of<tag::immediate_mean_of_weights>">feature_of</a><span class="special"><</span><span class="identifier">tag</span><span class="special">::</span><span class="identifier">immediate_mean_of_weights</span><span class="special">></span> <span class="special">:</span>
<span class="keyword">public</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">accumulators</span><span class="special">::</span><span class="identifier">feature_of</span><span class="special"><</span> <span class="identifier">tag</span><span class="special">::</span><span class="identifier">mean_of_weights</span> <span class="special">></span>
<span class="special">{</span>
<span class="special">}</span><span class="special">;</span></pre></div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2005, 2006 Eric Niebler<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="feature_of_tag_idp65053584.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../accumulators/reference.html#header.boost.accumulators.statistics.mean_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="feature_of_tag_idp65058464.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| mit |
soramugi/gistub | config/initializers/simple_form.rb | 6878 | # -*- encoding : utf-8 -*-
# Use this setup block to configure all options available in SimpleForm.
SimpleForm.setup do |config|
# Wrappers are used by the form builder to generate a
# complete input. You can remove any component from the
# wrapper, change the order or even add your own to the
# stack. The options given below are used to wrap the
# whole input.
config.wrappers :default, :class => :input,
:hint_class => :field_with_hint, :error_class => :field_with_errors do |b|
## Extensions enabled by default
# Any of these extensions can be disabled for a
# given input by passing: `f.input EXTENSION_NAME => false`.
# You can make any of these extensions optional by
# renaming `b.use` to `b.optional`.
# Determines whether to use HTML5 (:email, :url, ...)
# and required attributes
b.use :html5
# Calculates placeholders automatically from I18n
# You can also pass a string as f.input :placeholder => "Placeholder"
b.use :placeholder
## Optional extensions
# They are disabled unless you pass `f.input EXTENSION_NAME => :lookup`
# to the input. If so, they will retrieve the values from the model
# if any exists. If you want to enable the lookup for any of those
# extensions by default, you can change `b.optional` to `b.use`.
# Calculates maxlength from length validations for string inputs
b.optional :maxlength
# Calculates pattern from format validations for string inputs
b.optional :pattern
# Calculates min and max from length validations for numeric inputs
b.optional :min_max
# Calculates readonly automatically from readonly attributes
b.optional :readonly
## Inputs
b.use :label_input
b.use :hint, :wrap_with => { :tag => :span, :class => :hint }
b.use :error, :wrap_with => { :tag => :span, :class => :error }
end
config.wrappers :bootstrap, :tag => 'div', :class => 'control-group', :error_class => 'error' do |b|
b.use :html5
b.use :placeholder
b.use :label
b.wrapper :tag => 'div', :class => 'controls' do |ba|
ba.use :input
ba.use :error, :wrap_with => { :tag => 'span', :class => 'help-inline' }
ba.use :hint, :wrap_with => { :tag => 'p', :class => 'help-block' }
end
end
config.wrappers :prepend, :tag => 'div', :class => "control-group", :error_class => 'error' do |b|
b.use :html5
b.use :placeholder
b.use :label
b.wrapper :tag => 'div', :class => 'controls' do |input|
input.wrapper :tag => 'div', :class => 'input-prepend' do |prepend|
prepend.use :input
end
input.use :hint, :wrap_with => { :tag => 'span', :class => 'help-block' }
input.use :error, :wrap_with => { :tag => 'span', :class => 'help-inline' }
end
end
config.wrappers :append, :tag => 'div', :class => "control-group", :error_class => 'error' do |b|
b.use :html5
b.use :placeholder
b.use :label
b.wrapper :tag => 'div', :class => 'controls' do |input|
input.wrapper :tag => 'div', :class => 'input-append' do |append|
append.use :input
end
input.use :hint, :wrap_with => { :tag => 'span', :class => 'help-block' }
input.use :error, :wrap_with => { :tag => 'span', :class => 'help-inline' }
end
end
# Wrappers for forms and inputs using the Twitter Bootstrap toolkit.
# Check the Bootstrap docs (http://twitter.github.com/bootstrap)
# to learn about the different styles for forms and inputs,
# buttons and other elements.
config.default_wrapper = :bootstrap
# Define the way to render check boxes / radio buttons with labels.
# Defaults to :nested for bootstrap config.
# :inline => input + label
# :nested => label > input
config.boolean_style = :nested
# Default class for buttons
config.button_class = 'btn'
# Method used to tidy up errors. Specify any Rails Array method.
# :first lists the first message for each field.
# Use :to_sentence to list all errors for each field.
# config.error_method = :first
# Default tag used for error notification helper.
config.error_notification_tag = :div
# CSS class to add for error notification helper.
config.error_notification_class = 'alert alert-error'
# ID to add for error notification helper.
# config.error_notification_id = nil
# Series of attempts to detect a default label method for collection.
# config.collection_label_methods = [ :to_label, :name, :title, :to_s ]
# Series of attempts to detect a default value method for collection.
# config.collection_value_methods = [ :id, :to_s ]
# You can wrap a collection of radio/check boxes in a pre-defined tag, defaulting to none.
# config.collection_wrapper_tag = nil
# You can define the class to use on all collection wrappers. Defaulting to none.
# config.collection_wrapper_class = nil
# You can wrap each item in a collection of radio/check boxes with a tag,
# defaulting to :span. Please note that when using :boolean_style = :nested,
# SimpleForm will force this option to be a label.
# config.item_wrapper_tag = :span
# You can define a class to use in all item wrappers. Defaulting to none.
# config.item_wrapper_class = nil
# How the label text should be generated altogether with the required text.
# config.label_text = lambda { |label, required| "#{required} #{label}" }
# You can define the class to use on all labels. Default is nil.
config.label_class = 'control-label'
# You can define the class to use on all forms. Default is simple_form.
# config.form_class = :simple_form
# You can define which elements should obtain additional classes
# config.generate_additional_classes_for = [:wrapper, :label, :input]
# Whether attributes are required by default (or not). Default is true.
# config.required_by_default = true
# Tell browsers whether to use default HTML5 validations (novalidate option).
# Default is enabled.
config.browser_validations = false
# Collection of methods to detect if a file type was given.
# config.file_methods = [ :mounted_as, :file?, :public_filename ]
# Custom mappings for input types. This should be a hash containing a regexp
# to match as key, and the input type that will be used when the field name
# matches the regexp as value.
# config.input_mappings = { /count/ => :integer }
# Default priority for time_zone inputs.
# config.time_zone_priority = nil
# Default priority for country inputs.
# config.country_priority = nil
# Default size for text inputs.
# config.default_input_size = 50
# When false, do not use translations for labels.
# config.translate_labels = true
# Automatically discover new inputs in Rails' autoload path.
# config.inputs_discovery = true
# Cache SimpleForm inputs discovery
# config.cache_discovery = !Rails.env.development?
end
| mit |
PhilAndrew/JumpMicro | JMShared/src/main/scala/jumpmicro/shared/model/MRegistryMMicroConfig.scala | 786 | package jumpmicro.shared.model
//: -------------------------------------------------------------------------------------
//: Copyright © 2017 Philip Andrew https://github.com/PhilAndrew All Rights Reserved.
//: Released under the MIT License, refer to the project website for licence information.
//: -------------------------------------------------------------------------------------
import org.neo4j.ogm.annotation.{GraphId, NodeEntity, Relationship}
import java.lang.{Long => JLong}
import java.util.{Set => JSet}
import java.util.{HashSet => JHashSet}
import java.lang.{String => JString}
import scala.beans.BeanProperty
import scala.collection.JavaConverters._
class MRegistryMMicroConfig extends MMicroConfig {
@BeanProperty
var storagePathOnDisk: String = "./data"
}
| mit |
arunabhdas/pizzashop | target/work/plugins/spring-security-core-2.0-RC4/src/java/grails/plugin/springsecurity/web/access/channel/HeaderCheckInsecureChannelProcessor.java | 2217 | /* Copyright 2012-2014 SpringSource.
*
* 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 grails.plugin.springsecurity.web.access.channel;
import java.io.IOException;
import java.util.Collection;
import javax.servlet.ServletException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.channel.InsecureChannelProcessor;
import org.springframework.util.Assert;
/**
* @author <a href='mailto:burt@burtbeckwith.com'>Burt Beckwith</a>
*/
public class HeaderCheckInsecureChannelProcessor extends InsecureChannelProcessor {
protected String headerName;
protected String headerValue;
@Override
public void decide(FilterInvocation invocation, Collection<ConfigAttribute> config)
throws IOException, ServletException {
Assert.isTrue(invocation != null && config != null, "Nulls cannot be provided");
for (ConfigAttribute attribute : config) {
if (supports(attribute)) {
if (headerValue.equals(invocation.getHttpRequest().getHeader(headerName))) {
getEntryPoint().commence(invocation.getRequest(), invocation.getResponse());
}
}
}
}
/**
* Set the name of the header to check.
* @param name the name
*/
public void setHeaderName(String name) {
headerName = name;
}
/**
* Set the header value to trigger a redirect.
* @param value the value
*/
public void setHeaderValue(String value) {
headerValue = value;
}
@Override
public void afterPropertiesSet() throws Exception {
super.afterPropertiesSet();
Assert.hasLength(headerName, "Header name is required");
Assert.hasLength(headerValue, "Header value is required");
}
}
| mit |
numediaweb/grunt-contrib-jasmine | docs/jasmine-overview.md | 1026 | Automatically builds and maintains your spec runner and runs your tests headlessly through PhantomJS.
## Run specs locally or on a remote server
Run your tests on your local filesystem or via a server task like [grunt-contrib-connect][].
## Customize your SpecRunner with templates
Use your own SpecRunner templates to customize how `grunt-contrib-jasmine` builds the SpecRunner. See the
[wiki](https://github.com/gruntjs/grunt-contrib-jasmine/wiki/Jasmine-Templates) for details and third party templates for examples.
### AMD Support
Supports AMD tests via the [grunt-template-jasmine-requirejs](https://github.com/jsoverson/grunt-template-jasmine-requirejs) module
### Third party templates
- [RequireJS](https://github.com/jsoverson/grunt-template-jasmine-requirejs)
- [Code coverage output with Istanbul](https://github.com/maenu/grunt-template-jasmine-istanbul)
- [StealJS](https://github.com/jaredstehler/grunt-template-jasmine-steal)
[grunt-contrib-connect]: https://github.com/gruntjs/grunt-contrib-connect
| mit |
zweidner/hubzero-cms | core/plugins/editors/ckeditor/assets/plugins/colorbutton/lang/bs.js | 2069 | /*
Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'colorbutton', 'bs', {
auto: 'Automatska',
bgColorTitle: 'Boja pozadine',
colors: {
'000': 'Black',
'800000': 'Maroon',
'8B4513': 'Saddle Brown',
'2F4F4F': 'Dark Slate Gray',
'008080': 'Teal',
'000080': 'Navy',
'4B0082': 'Indigo',
'696969': 'Dark Gray',
B22222: 'Fire Brick',
A52A2A: 'Brown',
DAA520: 'Golden Rod',
'006400': 'Dark Green',
'40E0D0': 'Turquoise',
'0000CD': 'Medium Blue',
'800080': 'Purple',
'808080': 'Gray',
F00: 'Red',
FF8C00: 'Dark Orange',
FFD700: 'Gold',
'008000': 'Green',
'0FF': 'Cyan',
'00F': 'Blue',
EE82EE: 'Violet',
A9A9A9: 'Dim Gray',
FFA07A: 'Light Salmon',
FFA500: 'Orange',
FFFF00: 'Yellow',
'00FF00': 'Lime',
AFEEEE: 'Pale Turquoise',
ADD8E6: 'Light Blue',
DDA0DD: 'Plum',
D3D3D3: 'Light Grey',
FFF0F5: 'Lavender Blush',
FAEBD7: 'Antique White',
FFFFE0: 'Light Yellow',
F0FFF0: 'Honeydew',
F0FFFF: 'Azure',
F0F8FF: 'Alice Blue',
E6E6FA: 'Lavender',
FFF: 'White',
'1ABC9C': 'Strong Cyan', // MISSING
'2ECC71': 'Emerald', // MISSING
'3498DB': 'Bright Blue', // MISSING
'9B59B6': 'Amethyst', // MISSING
'4E5F70': 'Grayish Blue', // MISSING
'F1C40F': 'Vivid Yellow', // MISSING
'16A085': 'Dark Cyan', // MISSING
'27AE60': 'Dark Emerald', // MISSING
'2980B9': 'Strong Blue', // MISSING
'8E44AD': 'Dark Violet', // MISSING
'2C3E50': 'Desaturated Blue', // MISSING
'F39C12': 'Orange', // MISSING
'E67E22': 'Carrot', // MISSING
'E74C3C': 'Pale Red', // MISSING
'ECF0F1': 'Bright Silver', // MISSING
'95A5A6': 'Light Grayish Cyan', // MISSING
'DDD': 'Light Gray', // MISSING
'D35400': 'Pumpkin', // MISSING
'C0392B': 'Strong Red', // MISSING
'BDC3C7': 'Silver', // MISSING
'7F8C8D': 'Grayish Cyan', // MISSING
'999': 'Dark Gray' // MISSING
},
more: 'Više boja...',
panelTitle: 'Colors',
textColorTitle: 'Boja teksta'
} );
| mit |
tpena/phony | spec/lib/phony/countries_spec.rb | 56003 | # encoding: utf-8
#
require 'spec_helper'
describe 'country descriptions' do
def self.it_splits number, expected
it { Phony.split(number).should == expected }
end
describe 'regression' do
it_splits '33630588659', ["33", "6", "30", "58", "86", "59"]
end
describe 'splitting' do
describe 'Ascension Island' do
it_splits '2473551', ['247', false, '3551']
end
describe 'Afghanistan' do
it_splits '93201234567', ['93', '20', '1234567'] # Kabul
end
describe 'Algeria' do
it_splits '213211231234', ['213', '21', '123', '1234'] # Algiers
it_splits '213331231234', ['213', '33', '123', '1234'] # Batna
end
describe 'Argentina' do
it_splits '541112345678', ['54', '11', '1234', '5678']
it_splits '542911234567', ['54', '291', '123', '4567']
it_splits '542965123456', ['54', '2965', '12', '3456']
it_splits '5491112345678', ['54', '911', '1234', '5678']
it_splits '5492201234567', ['54', '9220', '123', '4567']
it_splits '5492221123456', ['54', '92221', '12', '3456']
it_splits '548001234567', ['54', '800', '123', '4567']
end
describe 'Austria' do
it_splits '43198110', %w( 43 1 98110 ) # Vienna
it_splits '4310000000', %w( 43 1 0000000 ) # Vienna
it_splits '43800123456789', %w( 43 800 123456789 ) # Free
it_splits '4368100000000', %w( 43 681 0000 0000 ) # Mobile
it_splits '436880000000', %w( 43 688 0000 000 ) # Mobile
it_splits '4366900000000', %w( 43 669 0000 0000 ) # Mobile
it_splits '433161234567891', %w( 43 316 1234567891 ) # Graz
it_splits '432164123456789', %w( 43 2164 123456789 ) # Rohrau
# mobile numbers can have from 7 to 10 digits in the subscriber number
it_splits '436641234567', %w( 43 664 1234 567 )
it_splits '4366412345678', %w( 43 664 1234 5678 )
it_splits '43664123456789', %w( 43 664 1234 56789 )
it_splits '436641234567890', %w( 43 664 1234 567890 )
end
describe 'Australia' do
it_splits '61512341234', ['61', '5', '1234', '1234'] # Landline
it_splits '61423123123', ['61', '423', '123', '123'] # Mobile
end
describe 'Bahrain' do
it_splits '97312345678', ['973', false, '1234', '5678']
end
describe 'Bangladesh' do
it_splits '88021234567', %w(880 2 1234567)
it_splits '8805112345', %w(880 51 12345)
it_splits '88031123456', %w(880 31 123456)
it_splits '88032112345', %w(880 321 12345)
it_splits '8804311234567', %w(880 431 1234567)
it_splits '880902012345', %w(880 9020 12345)
end
describe 'Belarus' do
it_splits '375152123456', %w(375 152 123456)
it_splits '375151512345', %w(375 1515 12345)
it_splits '375163423456', %w(375 163 423456)
it_splits '375163112345', %w(375 1631 12345)
it_splits '375291234567', %w(375 29 1234567)
it_splits '375800123', %w(375 800 123)
it_splits '3758001234', %w(375 800 1234)
it_splits '3758001234567', %w(375 800 1234567)
it_splits '37582012345678', %w(375 820 12345678)
end
describe 'Belgium' do
it_splits '3235551212', ['32', '3', '555', '12', '12'] # Antwerpen
it_splits '3250551212', ['32', '50', '55', '12', '12'] # Brugge
it_splits '3225551212', ['32', '2', '555', '12', '12'] # Brussels
it_splits '3295551914', ['32', '9', '555', '19', '14'] # Gent
it_splits '3245551414', ['32', '4', '555', '14', '14'] # Liège
it_splits '3216473200', ['32', '16', '47', '32', '00'] # Leuven
it_splits '32475279584', ['32', '475', '27', '95', '84'] # mobile
it_splits '32468279584', ['32', '468', '27', '95', '84'] # mobile (Telenet)
it_splits '3270123123', ['32', '70', '123', '123'] # Bus Service?
end
describe 'Belize' do
it_splits '5012051234', %w(501 205 1234)
end
describe 'Benin' do
it_splits '22912345678', ['229', false, '1234', '5678']
end
describe 'Bolivia' do
it_splits '59122772266', %w(591 2 277 2266)
end
describe 'Botswana' do
it_splits '26780123456', %w(267 80 123 456)
it_splits '2672956789', %w(267 29 567 89)
it_splits '2674634567', %w(267 463 4567)
it_splits '2675812345', %w(267 58 123 45)
it_splits '26776712345', %w(267 7 6712 345)
it_splits '26781234567', %w(267 8 1234 567)
end
describe 'Brazil' do
it_splits '551112341234', ['55', '11', '1234', '1234']
it_splits '5511981231234', ['55', '11', '98123', '1234'] # São Paulo's 9 digits mobile
it_splits '552181231234', ['55', '21', '8123', '1234']
it_splits '5521981231234', ['55', '21', '98123', '1234'] # Rio de Janeiro's 9 digits mobile
it_splits '551931311234', ['55', '19', '3131', '1234'] # Rio de Janeiro's 9 digits mobile
it_splits '5519991311234', ['55', '19', '99131', '1234'] # Rio de Janeiro's 9 digits mobile
context "special states with 9 in mobile" do
%w{ 11 12 13 14 15 16 17 18 19 21 22 24 27 28 81 82 83 84 85 86 87 88 89 91 92 93 94 95 96 97 98 99}.each do |state_code|
it_splits "55#{state_code}993051123", ['55', state_code, '99305', '1123']
end
end
context "special numbers" do
it_splits '5508002221234', ['55', '0800', '222', '1234']
it_splits '5530032221', ['55', '3003', '2221']
it_splits '5540209999', ['55', '4020', '9999']
it_splits '5540048999', ['55', '4004', '8999']
end
context "service numbers" do
it_splits '55100', ['55', '100', ""]
it_splits '55199', ['55', '199', ""]
end
end
describe 'Cambodia' do
it_splits '85512236142', ["855", "12", "236", "142"] # mobile (Mobitel)
it_splits '855977100872', ["855", "97", "710", "0872"] # mobile (Metfone)
it_splits '855234601183', ["855", "23", "460", "1183"] # Long fixed line (Phnom Penh)
it_splits '85533234567', ["855", "33", "234", "567"] # Regular fixed line (Kampot)
end
describe 'Chile' do
it_splits '5621234567', ['56', '2', '1234567'] # Santiago
it_splits '5675123456', ['56', '75', '123456'] # Curico
it_splits '56912345678', ['56', '9', '12345678'] # Mobile
it_splits '56137123456', ['56', '137', '123', '456'] # Service
end
describe 'China' do
it_splits '862112345678', ['86', '21', '1234', '5678'] # Shanghai
it_splits '8675582193447', ['86', '755', '8219', '3447'] # Shenzhen
end
describe 'Colombia' do
it_splits '5711234567', ['57', '1', '123', '4567']
it_splits '573101234567', ['57', '310', '123', '4567'] # mobile
end
describe 'Croatia' do
it_splits '38521695900', %w( 385 21 695 900 ) # Landline
it_splits '38514566666', %w( 385 1 4566 666 ) # Landline (Zagreb)
it_splits '385918967509', %w( 385 91 896 7509 ) # Mobile
end
describe 'Cuba' do
it_splits '5351231234', ['53', '5123', '1234'] # Mobile
it_splits '5371234567', ['53', '7', '1234567'] # Havana
it_splits '5342123456', ['53', '42', '123456'] # Villa Clara
end
describe 'Cyprus' do
it_splits '35712322123456', ['357', '123', '22', '123456'] # Voicemail
it_splits '35722123456', ['357', '22', '123456'] # Fixed
it_splits '35791123456', ['357', '91', '123456'] # Mobile
end
describe 'Denmark' do
it_splits '4532121212', ['45', false, '32', '12', '12', '12']
end
describe 'Egypt' do
it_splits '20212345678', ['20', '2', '12345678']
it_splits '20921234567', ['20', '92', '1234567']
it_splits '20951234567', ['20', '95', '1234567']
end
describe 'Equatorial Guinea' do
it_splits '240222201123', ['240', false, '222', '201', '123']
it_splits '240335201123', ['240', false, '335', '201', '123']
end
describe 'Estonia' do
it_splits '3723212345', ['372', '321', '2345'] # Landline
it_splits '37251231234', ['372', '5123', '1234'] # Mobile
it_splits '3728001234', ['372', '800', '1234'] # Freephone
it_splits '37281231234', ['372', '8123', '1234'] # Mobile
it_splits '37282231234', ['372', '8223', '1234'] # Mobile
it_splits '37252212345', ['372', '5221', '2345'] # Mobile
it_splits '3725221234', ['372', '5221', '234'] # Mobile
it_splits '37270121234', ['372', '7012', '1234'] # Premium
end
describe 'Finland' do
it_splits '3589123123', ['358', '9', '123', '123'] # Helsinki
it_splits '3581912312', ['358', '19', '123', '12'] # Nylandia
it_splits '3585012312', ['358', '50', '123', '12'] # Mobile
it_splits '358600123', ['358', '600', '123'] # Service
end
describe 'France' do
it_splits '33112345678', ['33', '1', '12','34','56','78'] # Paris
it_splits '33812345678', ['33', '8', '12','34','56','78'] # Service number
end
describe 'Georgia' do
it_splits '99522012345', %w(995 220 123 45)
it_splits '995321234567', %w(995 32 123 4567)
it_splits '995342123456', %w(995 342 123 456)
it_splits '995596123456', %w(995 596 123 456)
end
describe 'Germany' do
it_splits '493038625454', ['49', '30', '386', '25454'] # Berlin
it_splits '4932221764542', ['49', '32', '221', '764542'] # Non-Geographical
it_splits '4922137683323', ['49', '221', '376', '83323'] # Cologne
it_splits '497614767676', ['49', '761', '476', '7676'] # Freiburg im Breisgau
it_splits '4921535100', ['49', '2153', '510', '0'] # Nettetal-Lobberich
it_splits '493434144602', ['49', '34341', '446', '02'] # Geithain
it_splits '491805878323', ['49', '180', '587', '8323'] # Service number
it_splits '491815878323', ['49', '181', '587', '8323'] # Service number
it_splits '498001234567', ['49', '800', '123', '4567'] # Service number
it_splits '49800222340010', ['49', '800', '222', '340010'] # Service number
it_splits '4915111231234', ['49', '151', '1123', '1234'] # Mobile number
it_splits '4915771231234', ['49', '157', '7123', '1234'] # Mobile number
it_splits '491601234567', ['49', '160', '1234', '567'] # Mobile number
it_splits '4916312345678', ['49', '163', '1234', '5678'] # Mobile number
it_splits '4915211231234', ['49', '1521', '123', '1234'] # Mobile number
end
describe 'Ghana' do
it_splits '233302123456', ['233', '30', '212', '3456'] # Mobile Vodafone, Accra
end
describe 'Gibraltar' do
it_splits '35020012345', ['350', '200', '12345'] # Fixed
it_splits '35021112345', ['350', '211', '12345'] # Fixed
it_splits '35022212345', ['350', '222', '12345'] # Fixed
it_splits '35054123456', ['350', '54', '123456'] # Mobile
it_splits '35056123456', ['350', '56', '123456'] # Mobile
it_splits '35057123456', ['350', '57', '123456'] # Mobile
it_splits '35058123456', ['350', '58', '123456'] # Mobile
it_splits '35060123456', ['350', '60', '123456'] # Mobile
it_splits '3508012', ['350', '8012', '' ] # Freephone
end
describe 'Greece' do
it_splits '302142345678', %w(30 21 4234 5678)
it_splits '302442345678', %w(30 24 4234 5678)
it_splits '305034571234', %w(30 50 3457 1234)
it_splits '306901234567', %w(30 690 123 4567)
it_splits '307001234567', %w(30 70 0123 4567)
it_splits '308001001234', %w(30 800 100 1234)
it_splits '308011001234', %w(30 801 100 1234)
it_splits '308071001234', %w(30 807 100 1234)
it_splits '308961001234', %w(30 896 100 1234)
it_splits '309011234565', %w(30 901 123 4565)
it_splits '309091234565', %w(30 909 123 4565)
end
describe 'Haiti' do
it_splits '50922121234', ['509', '22', '12', '1234']
end
describe 'Hong Kong' do
it_splits '85212341234', ['852', false, '1234', '1234'] #
end
describe 'Hungary' do
it_splits'3612345678', ['36', '1', '234', '5678']
it_splits'3622123456', ['36', '22', '123', '456']
end
describe 'Iceland' do
it_splits '354112', ['354', false, '112'] # Emergency TODO
it_splits '3544211234', ['354', false, '421', '1234'] # Keflavík
it_splits '3544621234', ['354', false, '462', '1234'] # Akureyri
it_splits '3545511234', ['354', false, '551', '1234'] # Reykjavík
end
describe 'Indonesia' do
it_splits '6242323032', ["62", "4", "2323", "032"]
it_splits '6285220119289', ['62', '852', '2011', '9289']
it_splits '62217815263', %w(62 21 781 5263)
it_splits '6213123', %w(62 13 123)
it_splits '6213123456', %w(62 13 123 456)
it_splits '6217412', %w(62 174 12)
it_splits '6217412345', %w(62 174 12 345)
it_splits '6217712', %w(62 177 12)
it_splits '6217712123456', %w(62 177 1212 3456)
it_splits '62178123', %w(62 178 123)
it_splits '6217812345', %w(62 178 123 45)
it_splits '622112345', %w(62 21 123 45)
it_splits '622112345567', %w(62 21 1234 5567)
it_splits '622212345', %w(62 22 123 45)
it_splits '62221234567', %w(62 22 123 4567)
it_splits '624311234', %w(62 4 311 234)
it_splits '62431123456', %w(62 4 3112 3456)
it_splits '6262212345', %w(62 6 221 2345)
it_splits '62622123456', %w(62 6 2212 3456)
it_splits '6270123456', %w(62 70 123 456)
it_splits '6271123456', %w(62 71 123 456)
it_splits '62711234567', %w(62 71 123 4567)
it_splits '62810123456', %w(62 810 123 456)
it_splits '6281012345678', %w(62 810 1234 5678)
it_splits '628151234567', %w(62 815 123 4567)
it_splits '62820123456', %w(62 820 123 456)
it_splits '628231234567', %w(62 823 123 4567)
it_splits '6282312345678', %w(62 823 1234 5678)
it_splits '6287012345', %w(62 870 123 45)
it_splits '62877123456', %w(62 877 123 456)
it_splits '62881123456', %w(62 881 123 456)
it_splits '6288112345656', %w(62 881 1234 5656)
it_splits '6291234567', %w(62 9 1234 567)
it_splits '629123456789', %w(62 9 123 456 789)
end
describe 'India' do
it_splits '919911182111', ['91', '99', '111', '82', '111'] # mobile
it_splits '912212345678', ['91', '22', '123', '45', '678'] # New Delhi
it_splits '911411234567', ['91', '141', '123', '45', '67'] # Jaipur
it_splits '913525123456', ['91', '3525', '123', '456'] # DALKHOLA
it_splits '914433993939', ['91', '44', '339', '93', '939'] #
end
describe 'Iran' do
it_splits '982112341234', ['98', '21', '1234', '1234'] # Teheran
it_splits '989191231234', ['98', '919', '123', '1234'] # Example Cell Phone
end
describe 'Ireland' do
it_splits '35311234567', ['353', '1', '123', '4567'] # Dublin, 7 digit subscriber #
it_splits '353539233333', ['353', '53', '923', '3333'] # Wexford, 7 digit subscriber
it_splits '3532212345', ['353', '22', '12345'] # Mallow, 5 digit subscriber #
it_splits '35345123456', ['353', '45', '123456'] # Naas, 6 digit subscriber #
it_splits '353801234567', ['353', '80', '123', '4567'] # Mobile
it_splits '353761234567', ['353', '76', '123', '4567'] # VoIP
it_splits '353800123456', ['353', '800', '123456'] # Freefone
it_splits '353000123456', ['353', '000', '123456'] # Default fixed 3 split for unrecognized
end
describe 'Israel (972)' do
it_splits '972100', ['972', '1', '00'] # Police
it_splits '97221231234', ['972', '2', '123', '1234'] # Jerusalem Area
it_splits '97282411234', ['972', '8', '241', '1234'] # Gaza Strip (Palestine)
it_splits '97291231234', ['972', '9', '123', '1234'] # Sharon Area
it_splits '972501231234', ['972', '50', '123', '1234'] # Mobile (Pelephone)
it_splits '972591231234', ['972', '59', '123', '1234'] # Mobile Jawwal (Palestine)
it_splits '972771231234', ['972', '77', '123', '1234'] # Cable Phone Services
it_splits '9721700123123', ['972', '1', '700', '123', '123'] # Cable Phone Services
end
describe 'Israel (970)' do
it_splits '97021231234', ['970', '2', '123', '1234'] # Jerusalem Area
it_splits '97082411234', ['970', '8', '241', '1234'] # Gaza Strip (Palestine)
it_splits '97091231234', ['970', '9', '123', '1234'] # Sharon Area
it_splits '970501231234', ['970', '50', '123', '1234'] # Mobile (Pelephone)
it_splits '970591231234', ['970', '59', '123', '1234'] # Mobile Jawwal (Palestine)
it_splits '970771231234', ['970', '77', '123', '1234'] # Cable Phone Services
it_splits '9701700123123', ['970', '1', '700', '123', '123'] # Cable Phone Services
end
describe 'Italy' do
it_splits '39348695281', ['39', '348', '695', '281'] # Mobile (6-digit subscriber no. - rare, but still used)
it_splits '393486952812', ['39', '348', '695', '2812'] # Mobile (7-digit subscriber no. - common)
it_splits '3934869528123',['39', '348', '695', '2812', '3'] # Mobile (8-digit subscriber no - new)
it_splits '393357210488', ['39', '335', '721', '0488'] # Mobile
it_splits '393248644272', ['39', '324', '864', '4272'] # Mobile
it_splits '390612341234', ['39', '06', '1234', '1234'] # Roma
it_splits '390288838883', ['39', '02', '8883', '8883'] # Milano
it_splits '390141595661', ['39', '0141', '595', '661'] # Asti
it_splits '3903123391', ['39', '031', '23391'] # Como
it_splits '390909709511', ['39', '090', '9709511'] # Barcellona
it_splits '390471811353', ['39', '0471', '811', '353'] # Bolzano
end
describe 'Japan' do
it_splits '81312345678', %w(81 3 1234 5678) # Tokyo
it_splits '81612345678', %w(81 6 1234 5678) # Osaka
it_splits '81120123456', %w(81 120 123 456) # Freephone
it_splits '81111234567', %w(81 11 123 4567)
it_splits '81123123456', %w(81 123 12 3456)
it_splits '81126712345', %w(81 1267 1 2345)
it_splits '812012345678', %w(81 20 1234 5678) # Pager(Calling Party Pay)
it_splits '815012345678', %w(81 50 1234 5678) # IP Telephone
it_splits '816012345678', %w(81 60 1234 5678) # UPT
it_splits '817012345678', %w(81 70 1234 5678) # PHS
it_splits '818012345678', %w(81 80 1234 5678) # Cellular
it_splits '819012345678', %w(81 90 1234 5678) # Cellular
end
describe 'Kenya' do
it_splits '254201234567', ['254', '20', '1234567'] # Nairobi
it_splits '254111234567', ['254', '11', '1234567'] # Mombasa
it_splits '254723100220', ['254', '723', '100220'] # Mombasa
end
describe 'Kyrgyzstan' do
it_splits '996312212345', %w(996 312 212 345)
it_splits '996315212345', %w(996 315 212 345)
it_splits '996313121234', %w(996 3131 212 34)
it_splits '996394621234', %w(996 3946 212 34)
it_splits '996501234567', %w(996 50 123 4567)
it_splits '996521234567', %w(996 52 123 4567)
it_splits '996581234567', %w(996 58 123 4567)
it_splits '996800123456', %w(996 800 123 456)
end
describe 'Lithuania' do
it_splits '37070012123', ['370', '700', '12', '123'] # Service
it_splits '37061212123', ['370', '612', '12', '123'] # Mobile
it_splits '37051231212', ['370', '5', '123', '12', '12'] # Vilnius
it_splits '37037121212', ['370', '37', '12', '12', '12'] # Kaunas
it_splits '37044011212', ['370', '440', '1', '12', '12'] # Skuodas
end
describe 'Luxembourg' do
it_splits '352222809', ['352', '22', '28', '09']
it_splits '35226222809', ['352', '26', '22', '28', '09']
it_splits '352621123456', ['352', '621', '123', '456']
it_splits '3524123456', ['352', '4', '12', '34', '56']
it_splits '352602112345678', ['352', '6021', '12', '34', '56', '78']
it_splits '352370431', ['352', '37', '04', '31']
it_splits '35227855', ['352', '27', '85', '5']
end
describe 'Malaysia' do
it_splits '6082123456', ['60', '82', '123456'] # Kuching
it_splits '60312345678', ['60', '3', '12345678'] # Kuala Lumpur
it_splits '60212345678', ['60', '2', '12345678'] # Singapore
it_splits '60111231234', ['60', '11', '123', '1234'] # Mobile
it_splits '601112312345', ['60', '11', '123', '12345'] # Mobile
it_splits '60800121234', ['60', '800', '12', '1234'] # Freephone
# it_splits '60112', ['60', '112'] # Service
end
describe 'Malta' do
it_splits '35621231234', ['356', '2123', '1234'] # Fixed
it_splits '35677123456', ['356', '77', '123456'] # Mobile
it_splits '35698123456', ['356', '98', '123456'] # Mobile
it_splits '35651231234', ['356', '5123', '1234'] # Voice Mail
end
describe 'Mexico' do
it_splits '525512121212', ['52', '55', '1212', '1212'] # Mexico City
it_splits '5215512121212', ['52', '1', '55', '1212', '1212'] # Mexico City cell phone from abroad
it_splits '526641231212', ['52', '664', '123', '1212'] # Tijuana
it_splits '5216641231212', ['52', '1', '664', '123', '1212'] # Tijuana cell phone from abroad
it_splits '520446641231212', ['52', '044', '664', '123', '1212'] # Tijuana cell phone local from landline
end
describe 'Monaco' do
it_splits '37741123456', ['377', '41', '12', '34', '56'] # Mobile
it_splits '377612345678', ['377', '6', '12', '34', '56', '78'] # Mobile
end
describe 'Montenegro' do
it_splits '38280123456', %w(382 80 123 456)
it_splits '3822012345', %w(382 20 123 45)
it_splits '38220123456', %w(382 20 123 456)
it_splits '38232123456', %w(382 32 123 456)
it_splits '38278103456', %w(382 78 103 456)
it_splits '38263123', %w(382 63 123)
it_splits '382631234567890', %w(382 63 123 456 7890)
it_splits '38277103456', %w(382 77 103 456)
it_splits '38294103456', %w(382 94 103 456)
it_splits '38288103456', %w(382 88 103 456)
it_splits '3826812', %w(382 68 12)
it_splits '382681212345678', %w(382 68 12 1234 5678)
it_splits '38270123', %w(382 70 123)
it_splits '382701234567890', %w(382 70 123 456 7890)
end
describe 'Morocco' do
it_splits '212537718685', ['212', '53', '7718', '685']
it_splits '212612345678', ['212', '6', '12', '34', '56', '78']
end
describe 'The Netherlands' do
it_splits '31612345678', ['31', '6', '12', '34', '56', '78'] # mobile
it_splits '31201234567', ['31', '20', '123', '4567']
it_splits '31222123456', ['31', '222', '123', '456']
end
describe 'Norway' do
it_splits '4721234567', ['47',false,'21','23','45','67']
it_splits '4731234567', ['47',false,'31','23','45','67']
it_splits '4741234567', ['47',false,'412','34','567']
it_splits '4751234567', ['47',false,'51','23','45','67']
it_splits '4761234567', ['47',false,'61','23','45','67']
it_splits '4771234567', ['47',false,'71','23','45','67']
it_splits '4781234567', ['47',false,'812','34','567']
it_splits '4791234567', ['47',false,'912','34','567']
end
describe 'Oman' do
it_splits '96824423123', %w(968 24 423 123)
it_splits '96825423123', %w(968 25 423 123)
end
describe 'Pakistan' do
it_splits '922112345678', %w(92 21 1234 5678)
it_splits '92221234567', %w(92 22 1234 567)
it_splits '92232123456', %w(92 232 123 456)
it_splits '923012345678', %w(92 30 1234 5678)
end
describe 'Paraguay (Republic of)' do
it_splits '59521123456', %w(595 21 123 456)
it_splits '595211234567', %w(595 21 123 4567)
it_splits '595345123456', %w(595 345 123 456)
it_splits '595961611234', %w(595 96 161 1234)
end
describe 'Peru' do
it_splits '51112341234', ['51', '1', '1234', '1234'] # Lima
it_splits '51912341234', ['51', '9', '1234', '1234'] # mobile
it_splits '51841234123', ['51', '84', '1234', '123'] # Cuzco, best effort
end
describe 'Philippines' do
it_splits '6321234567', ['63', '2', '1234567']
it_splits '6321234567890', ['63', '2', '1234567890']
it_splits '632123456789012', ['63', '2', '123456789012']
it_splits '639121234567', ['63', '912', '1234567']
it_splits '63881234567', ['63', '88', '1234567']
end
describe 'Poland' do
it_splits '48123456789', ['48', '12', '345', '67', '89'] # Landline
it_splits '48501123456', ['48', '501', '123', '456'] # Mobile
it_splits '48800123456', ['48', '800', '123', '456'] # Free
it_splits '48801123456', ['48', '801', '123', '456'] # Shared cost
it_splits '48701123456', ['48', '701', '123', '456'] # Premium
end
describe 'Portugal' do
it_splits '351211231234', ['351', '21', '123', '1234'] # Lisboa
it_splits '351241123123', ['351', '241', '123', '123'] # Abrantes
it_splits '351931231234', ['351', '93', '123', '1234'] # mobile
end
describe 'Qatar' do
it_splits '9741245123456', %w(974 1245 123 456)
it_splits '9742613456', %w(974 26 134 56)
it_splits '97433123456', %w(974 33 123 456)
it_splits '97444412456', %w(974 44 412 456)
it_splits '9748001234', %w(974 800 12 34)
it_splits '9749001234', %w(974 900 12 34)
it_splits '97492123', %w(974 92 123)
it_splits '97497123', %w(974 97 123)
end
describe 'Romania' do
it_splits '40211231234', ['40', '21', '123', '1234'] # Bucureşti
it_splits '40721231234', ['40', '72', '123', '1234'] # mobile
it_splits '40791231234', ['40', '79', '123', '1234'] # mobile
it_splits '40249123123', ['40', '249', '123', '123'] # Olt
end
describe 'Russia' do
it_splits '78122345678', ['7', '812', '234', '56', '78'] # Russia 3-digit
it_splits '74012771077', ['7', '4012', '77', '10', '77'] # Russia 4-digit
it_splits '78402411212', ['7', '84024', '1', '12', '12'] # Russia 5-digit
it_splits '79296119119', ['7', '929', '611', '91', '19'] # Russia 3-digit, Megafon Mobile.
it_splits '7840121212', ['7', '840', '12', '1212'] # Abhasia
it_splits '7799121212', ['7', '799', '12', '1212'] # Kazachstan
it_splits '7995344121212', ['7','995344','12','1212'] # South Osetia
it_splits '7209175276', ['7', '209', '17', '5276'] # Fantasy number
end
describe 'Rwanda' do
it_splits '250781234567', ['250', '78', '1234567'] # mobile
it_splits '250721234567', ['250', '72', '1234567'] # mobile
it_splits '250731234567', ['250', '73', '1234567'] # mobile
it_splits '250251234567', ['250', '25', '1234567'] # fixed
it_splits '25006123456', ['250', '06', '123456'] # fixed
end
describe 'Sao Tome and Principe' do
it_splits '2392220012', %w(239 2 220 012)
it_splits '2399920012', %w(239 9 920 012)
end
describe 'South Korea' do
it_splits '82212345678', ['82', '2', '1234', '5678'] # Seoul
it_splits '825112345678', ['82', '51', '1234', '5678'] # Busan
it_splits '821027975588', ['82', '10', '2797', '5588'] # mobile
it_splits '821087971234', ['82', '10', '8797', '1234'] # mobile
end
describe 'Serbia' do
it_splits '38163512529', ['381', '63', '512', '529']
end
describe 'South Sudan' do
it_splits '211123212345', ['211', '123', '212', '345']
it_splits '211973212345', ['211', '973', '212', '345']
end
describe 'Sudan' do
it_splits '249187171100', ['249', '18', '717', '1100']
end
describe 'Thailand' do
it_splits '6621231234', ['66', '2', '123', '1234'] # Bangkok
it_splits '6636123123', ['66', '36', '123', '123'] # Lop Buri
it_splits '66851234567', ['66', '851', '234', '567'] # Lop Buri
it_splits '66921234567', ['66', '921', '234', '567'] # mobile
end
describe 'Tunesia' do
it_splits '21611231234', ['216', '1', '123', '1234'] # Ariana
it_splits '21621231234', ['216', '2', '123', '1234'] # Bizerte
end
describe 'Salvador (El)' do
it_splits '50321121234', ['503', '2112', '1234'] # Fixed number
it_splits '50361121234', ['503', '6112', '1234'] # Mobile number
end
describe 'Singapore' do
it_splits '6561231234', ['65', false, '6123', '1234'] # Fixed line
end
describe 'Slovakia' do
it_splits '421912123456', ['421', '912', '123456'] # Mobile
it_splits '421212345678', ['421', '2', '12345678'] # Bratislava
it_splits '421371234567', ['421', '37', '1234567'] # Nitra / Other
end
describe 'Slovenia' do
it_splits '38651234567', ['386', '51', '234', '567'] # Mobile
it_splits '38611234567', ['386', '1', '123', '4567'] # LJUBLJANA
end
describe 'Spain' do
it_splits '34600123456', ['34', '600', '123', '456'] # Mobile
it_splits '34900123456', ['34', '900', '123', '456'] # Special
it_splits '34931234567', ['34', '93', '123', '45', '67'] # Landline large regions
it_splits '34975123456', ['34', '975', '12', '34', '56'] # Landline
it_splits '34123456789', ['34', '123', '456', '789'] # Default
end
describe 'Sri Lanka' do
it_splits '94711231212', ['94', '71', '123', '12', '12'] # Mobile
end
describe 'Sweden' do
it_splits '46812345678', ['46', '8', '123', '45', '678'] # Stockholm
it_splits '46111234567', ['46', '11', '123', '45', '67']
it_splits '46721234567', ['46', '72', '123', '45', '67'] # mobile
it_splits '46125123456', ['46', '125', '123', '456']
end
describe 'Switzerland' do
it_splits '41443643532', ['41', '44', '364', '35', '32'] # Zurich (usually)
it_splits '41800334455', ['41', '800', '334', '455'] # Service number
end
describe 'Tanzania' do
it_splits '255221231234', ['255', '22', '123', '1234'] # Dar Es Salaam
it_splits '255651231234', ['255', '65', '123', '1234'] # TIGO
it_splits '255861123123', ['255', '861', '123', '123'] # Special Rates
end
describe 'Turkey' do
it_splits '903121234567', ['90', '312', '123', '4567'] # Ankara
end
describe 'Uganda' do
it_splits '256414123456', ['256', '41', '4123456'] # Kampania
it_splits '256464441234', ['256', '464', '441234'] # Mubende
end
describe 'The UK' do
it_splits '442075671113', ['44', '20', '7567', '1113'] # [2+8] London
it_splits '442920229901', ['44', '29', '2022', '9901'] # [2+8] Cardiff
it_splits '441134770011', ['44', '113', '477', '0011'] # [3+7] Leeds
it_splits '441412770022', ['44', '141', '277', '0022'] # [3+7] Glasgow
it_splits '441204500532', ['44', '1204', '500532'] # [4+6] Bolton
it_splits '44120462532', ['44', '1204', '62532'] # [4+5] Bolton
it_splits '441333247700', ['44', '1333', '247700'] # [4+6] Leven (Fife)
it_splits '441382229845', ['44', '1382', '229845'] # [4+6] Dundee
it_splits '441420700378', ['44', '1420', '700378'] # [4+6] Alton
it_splits '44142080378', ['44', '1420', '80378'] # [4+5] Alton
it_splits '441475724688', ['44', '1475', '724688'] # [4+6] Greenock
it_splits '441539248756', ['44', '1539', '248756'] # [4+6] Kendal (Mixed area)
it_splits '441539648788', ['44', '15396', '48788'] # [5+5] Sedbergh (Mixed area)
it_splits '441652757248', ['44', '1652', '757248'] # [4+6] Brigg
it_splits '441664333456', ['44', '1664', '333456'] # [4+6] Melton Mowbray
it_splits '441697222555', ['44', '1697', '222555'] # [4+6] Brampton (Mixed area)
it_splits '441697388555', ['44', '16973', '88555'] # [5+5] Wigton (Mixed area)
it_splits '441697433777', ['44', '16974', '33777'] # [5+5] Raughton Head (Mixed area)
it_splits '44169772333', ['44', '16977', '2333'] # [5+4] Brampton (Mixed area)
it_splits '441697744888', ['44', '16977', '44888'] # [5+5] Brampton (Mixed area)
it_splits '441757850526', ['44', '1757', '850526'] # [4+6] Selby
it_splits '441890234567', ['44', '1890', '234567'] # [4+6] Coldstream (ELNS area)
it_splits '441890595378', ['44', '1890', '595378'] # [4+6] Ayton (ELNS area)
it_splits '441931306526', ['44', '1931', '306526'] # [4+6] Shap
it_splits '441946555777', ['44', '1946', '555777'] # [4+6] Whitehaven (Mixed area)
it_splits '44194662888', ['44', '1946', '62888'] # [4+5] Whitehaven (Mixed area)
it_splits '441946722444', ['44', '19467', '22444'] # [5+5] Gosforth (Mixed area)
it_splits '441987705337', ['44', '1987', '705337'] # [4+6] Ebbsfleet
it_splits '443005828323', ['44', '300', '582', '8323'] # Non-geographic (NTS)
it_splits '443334253344', ['44', '333', '425', '3344'] # Non-geographic (NTS)
it_splits '443437658834', ['44', '343', '765', '8834'] # Non-geographic (NTS)
it_splits '443452273512', ['44', '345', '227', '3512'] # Non-geographic (NTS)
it_splits '443707774444', ['44', '370', '777', '4444'] # Non-geographic (NTS)
it_splits '443725247722', ['44', '372', '524', '7722'] # Non-geographic (NTS)
it_splits '44500557788', ['44', '500', '557788'] # Freefone (500 + 6)
it_splits '445575671113', ['44', '55', '7567', '1113'] # Corporate numbers
it_splits '445644775533', ['44', '56', '4477', '5533'] # LIECS/VoIP
it_splits '447020229901', ['44', '70', '2022', '9901'] # Personal numbers
it_splits '447688554246', ['44', '76', '8855', '4246'] # Pager
it_splits '447180605207', ['44', '7180', '605207'] # Mobile
it_splits '447480605207', ['44', '7480', '605207'] # Mobile
it_splits '447624605207', ['44', '7624', '605207'] # Mobile (Isle of Man)
it_splits '447780605207', ['44', '7780', '605207'] # Mobile
it_splits '447980605207', ['44', '7980', '605207'] # Mobile
it_splits '44800557788', ['44', '800', '557788'] # Freefone (800 + 6)
it_splits '448084682355', ['44', '808', '468', '2355'] # Freefone (808 + 7)
it_splits '448005878323', ['44', '800', '587', '8323'] # Freefone (800 + 7), regression
it_splits '448437777334', ['44', '843', '777', '7334'] # Non-geographic (NTS)
it_splits '448457777334', ['44', '845', '777', '7334'] # Non-geographic (NTS)
it_splits '448707777334', ['44', '870', '777', '7334'] # Non-geographic (NTS)
it_splits '448727777334', ['44', '872', '777', '7334'] # Non-geographic (NTS)
it_splits '449052463456', ['44', '905', '246', '3456'] # Non-geographic (PRS)
it_splits '449122463456', ['44', '912', '246', '3456'] # Non-geographic (PRS)
it_splits '449832463456', ['44', '983', '246', '3456'] # Non-geographic (SES)
end
describe 'US' do
it_splits '15551115511', ['1', '555', '111', '5511']
end
describe 'Venezuela' do
it_splits '582121234567', ['58', '212', '1234567']
end
describe 'Vietnam' do
it_splits '8498123456', ['84', '98', '123456'] # Viettel Mobile
it_splits '8499612345', ['84', '996', '12345'] # GTel
it_splits '84412345678', ['84', '4', '1234', '5678'] # Hanoi
end
describe 'Zambia' do
it_splits '260955123456', ['260', '955', '123456'] # mobile
it_splits '260211123456', ['260', '211', '123456'] # fixed
end
describe 'New Zealand' do
it_splits '6491234567', ['64', '9', '123', '4567']
end
describe 'Bhutan (Kingdom of)' do
it_splits '9759723642', %w(975 9 723 642)
end
describe 'Brunei Darussalam' do
it_splits '6737932744', %w(673 7 932 744)
end
describe 'Burkina Faso' do
it_splits '22667839323', ['226', false, '6783', '9323']
end
describe 'Burundi' do
it_splits '25712345678', ['257', false, '1234', '5678']
end
describe 'Cameroon' do
it_splits '23727659381', ['237', false, '2765', '9381']
end
describe 'Cape Verde' do
it_splits '2385494177', ['238', false, '549', '4177']
end
describe 'Central African Republic' do
it_splits '23612345678', ['236', false, '1234', '5678']
end
describe 'Chad' do
it_splits '23512345678', ['235', false, '1234', '5678']
end
describe 'Comoros' do
it_splits '2693901234', ['269', false, '3901', '234']
it_splits '2693401234', ['269', false, '3401', '234']
end
describe 'Congo' do
it_splits '242123456789', ['242', false, '1234', '56789']
end
describe 'Cook Islands' do
it_splits '68251475', ['682', false, '51', '475']
end
describe 'Costa Rica' do
it_splits '50622345678', %w(506 2 234 5678)
end
describe "Côte d'Ivoire" do
it_splits '22507335518', ['225', '07', '33', '55', '18']
it_splits '22537335518', ['225', '37', '33', '55', '18']
end
describe 'Democratic Republic of Timor-Leste' do
it_splits '6701742945', ['670', false, '174', '2945']
end
describe 'Democratic Republic of the Congo' do
it_splits '24311995381', %w(243 1 199 5381)
end
describe 'Diego Garcia' do
it_splits '2461234683', ['246', false, '123', '4683']
end
describe 'Djibouti' do
it_splits '25349828978', ['253', false, '4982', '8978']
end
describe 'Ecuador' do
it_splits '593445876756', %w(593 44 587 6756)
end
describe 'Eritrea' do
it_splits '2916537192', %w(291 6 537 192)
end
describe 'Ethiopia' do
it_splits '251721233486', %w(251 72 123 3486)
end
describe 'Falkland Islands (Malvinas)' do
it_splits '50014963', ['500', false, '14', '963']
end
describe 'Faroe Islands' do
it_splits '298997986', ['298', false, '997', '986']
end
describe 'Fiji (Republic of)' do
it_splits '6798668123', ['679', false, '866', '8123']
end
describe 'French Guiana (French Department of)' do
it_splits '594594123456', %w(594 594 123 456)
end
describe "French Polynesia (Territoire français d'outre-mer)" do
it_splits '68921988900', ['689', false, '21', '98', '89', '00']
end
describe 'Gabonese Republic' do
it_splits '2411834375', ['241', '1', '834', '375']
end
describe 'Gambia' do
it_splits '2206683355', ['220', false, '668', '3355']
end
describe 'Greenland' do
it_splits '299314185', ['299', '31', '4185']
it_splits '299691123', ['299', '691', '123']
end
describe 'Guadeloupe (French Department of)' do
it_splits '590590456789', %w(590 590 45 67 89)
end
describe 'Guatemala (Republic of)' do
it_splits '50219123456789', ['502', '19', '123', '456', '789']
it_splits '50221234567', ['502', '2', '123', '4567']
end
describe 'Guinea' do
it_splits '22430311234', ['224', '3031', '12', '34']
it_splits '224662123456', ['224', '662', '12', '34', '56']
end
describe 'Guinea-Bissau' do
it_splits '2453837652', ['245', false, '383', '7652']
end
describe 'Guyana' do
it_splits '5922631234', %w(592 263 1234)
end
describe 'Honduras (Republic of)' do
it_splits '50412961637', %w(504 12 961 637)
end
describe 'Iraq' do
it_splits '96411234567', %w(964 1 123 4567)
it_splits '96421113456', %w(964 21 113 456)
it_splits '9647112345678', %w(964 71 1234 5678)
end
describe 'Jordan (Hashemite Kingdom of)' do
it_splits '96280012345', %w(962 800 123 45)
it_splits '96226201234', %w(962 2 620 1234)
it_splits '962712345678', %w(962 7 1234 5678)
it_splits '962746612345', %w(962 7 4661 2345)
it_splits '96290012345', %w(962 900 123 45)
it_splits '96285123456', %w(962 85 123 456)
it_splits '96270123456', %w(962 70 123 456)
it_splits '96262501456', %w(962 6250 1456)
it_splits '96287901456', %w(962 8790 1456)
end
describe 'Kiribati (Republic of)' do
it_splits '68634814', ['686', false, '34', '814']
end
describe "Democratic People's Republic of Korea" do
it_splits '850212345', %w(850 2 123 45)
it_splits '8502123456789', %w(850 2 123 456 789)
it_splits '85023812356', %w(850 2 381 2356)
#it_splits '85028801123456781256', %w(850 2 8801 1234 5678 1256)
it_splits '8501911234567', %w(850 191 123 4567)
end
describe 'Kuwait (State of)' do
it_splits '96523456789', ['965', false, '2345', '6789']
it_splits '9651812345', ['965', false, '181', '2345']
end
describe "Lao People's Democratic Republic" do
it_splits '85697831195', %w(856 97 831 195)
end
describe 'Latvia' do
it_splits '37180123456', %w(371 801 234 56)
it_splits '37163723456', %w(371 637 234 56)
it_splits '37129412345', %w(371 294 123 45)
end
describe 'Lebanon' do
it_splits '9611123456', %w(961 1 123 456)
it_splits '9614123456', %w(961 4 123 456)
it_splits '9613123456', %w(961 3 123 456)
it_splits '96170123456', %w(961 70 123 456)
it_splits '96190123456', %w(961 90 123 456)
it_splits '96181123456', %w(961 81 123 456)
end
describe 'Lesotho' do
it_splits '26623592495', ['266', false, '2359', '2495']
end
describe 'Liberia' do
it_splits '23121234567', ['231', false, '2123', '4567']
it_splits '2314123456', ['231', false, '4123', '456']
it_splits '231771234567', ['231', false, '77', '123', '4567']
end
describe 'Libya' do
it_splits '21820512345', %w(218 205 123 45)
it_splits '21822123456', %w(218 22 123 456)
it_splits '218211234456', %w(218 21 1234 456)
it_splits '218911234456', %w(218 91 1234 456)
end
describe 'Madagascar' do
it_splits '26120012345678', ['261', false, '20', '012', '345', '678']
it_splits '261201243456', ['261', false, *%w(20 124 3456)]
it_splits '261512345678', ['261', false, *%w(512 345 678)]
end
describe 'Malawi' do
it_splits '2651725123', ['265', false, '1725', '123']
it_splits '265213456789',[ '265', false, '213', '456', '789']
it_splits '2659123456', ['265', false, '9123', '456']
it_splits '265991123456', ['265', false, '991', '123', '456']
end
describe 'Maldives (Republic of)' do
it_splits '9606568279', ['960', '656', '8279']
end
describe 'Mali' do
it_splits '22379249349', ['223', false, '7924', '9349']
end
describe 'Marshall Islands (Republic of the)' do
it_splits '6924226536', ['692', false, '422', '6536']
end
describe 'Martinique (French Department of)' do
it_splits '596596123456', %w(596 596 12 34 56)
end
describe 'Mauritania' do
it_splits '22212345678', ['222', false, '1234', '5678']
end
describe 'Mauritius' do
it_splits '2309518919', ['230', false, '951', '8919']
end
describe 'Micronesia (Federated States of)' do
it_splits '6911991754', ['691', false, '199', '1754']
end
describe 'Moldova' do
it_splits '37380012345', %w(373 800 123 45)
it_splits '37322123345', %w(373 22 123 345)
it_splits '37324112345', %w(373 241 123 45)
it_splits '37360512345', %w(373 605 123 45)
it_splits '37380312345', %w(373 803 123 45)
end
describe 'Mongolia' do
it_splits '9761112345', %w(976 11 123 45)
it_splits '9761211234', %w(976 121 12 34)
it_splits '97612112345', %w(976 121 12 345)
it_splits '97670123456', %w(976 70 123 456)
it_splits '97675123456', %w(976 75 123 456)
it_splits '97688123456', %w(976 88 123 456)
it_splits '97650123456', %w(976 50 123 456)
end
describe 'Mozambique' do
it_splits '258600123456', %w(258 600 123 456)
it_splits '25825112345', %w(258 251 123 45)
it_splits '258821234456', %w(258 82 1234 456)
it_splits '258712344567', %w(258 7 1234 4567)
end
describe 'Namibia' do
it_splits '264675161324', %w(264 6751 613 24)
it_splits '26467175890', %w(264 67 175 890)
it_splits '26463088612345', %w(264 63 088 612 345)
it_splits '264851234567', %w(264 85 1234 567)
end
describe 'Nauru (Republic of)' do
it_splits '6741288739', ['674', false, '128', '8739']
end
describe 'Nepal' do
it_splits '97714345678', %w(977 1 434 5678)
it_splits '97710123456', %w(977 10 123 456)
it_splits '9779812345678', %w(977 98 1234 5678)
end
describe "New Caledonia (Territoire français d'outre-mer)" do
it_splits '687747184', ['687', false, '747', '184']
end
describe 'Nicaragua' do
it_splits '50512345678', ['505', '12', '345', '678']
end
describe 'Niger' do
it_splits '22712345678', ['227', false, '1234', '5678']
end
describe 'Nigeria' do
it_splits '23411231234', %w(234 1 123 1234) # Lagos
# mobile numbers
it_splits '2347007661234', %w(234 700 766 1234)
it_splits '2347017661234', %w(234 701 766 1234)
it_splits '2347027661234', %w(234 702 766 1234)
it_splits '2347037661234', %w(234 703 766 1234)
it_splits '2347047661234', %w(234 704 766 1234)
it_splits '2347057661234', %w(234 705 766 1234)
it_splits '2347067661234', %w(234 706 766 1234)
it_splits '2347077661234', %w(234 707 766 1234)
it_splits '2347087661234', %w(234 708 766 1234)
it_splits '2347097661234', %w(234 709 766 1234)
it_splits '2348007661234', %w(234 800 766 1234)
it_splits '2348017661234', %w(234 801 766 1234)
it_splits '2348027661234', %w(234 802 766 1234)
it_splits '2348037661234', %w(234 803 766 1234)
it_splits '2348047661234', %w(234 804 766 1234)
it_splits '2348057661234', %w(234 805 766 1234)
it_splits '2348067661234', %w(234 806 766 1234)
it_splits '2348077661234', %w(234 807 766 1234)
it_splits '2348087661234', %w(234 808 766 1234)
it_splits '2348097661234', %w(234 809 766 1234)
it_splits '2349007661234', %w(234 900 766 1234)
it_splits '2349017661234', %w(234 901 766 1234)
it_splits '2349027661234', %w(234 902 766 1234)
it_splits '2349037661234', %w(234 903 766 1234)
it_splits '2349047661234', %w(234 904 766 1234)
it_splits '2349057661234', %w(234 905 766 1234)
it_splits '2349067661234', %w(234 906 766 1234)
it_splits '2349077661234', %w(234 907 766 1234)
it_splits '2349087661234', %w(234 908 766 1234)
it_splits '2349097661234', %w(234 909 766 1234)
it_splits '2348107661234', %w(234 810 766 1234)
it_splits '2348117661234', %w(234 811 766 1234)
it_splits '2348127661234', %w(234 812 766 1234)
it_splits '2348137661234', %w(234 813 766 1234)
it_splits '2348147661234', %w(234 814 766 1234)
it_splits '2348157661234', %w(234 815 766 1234)
it_splits '2348167661234', %w(234 816 766 1234)
it_splits '2348177661234', %w(234 817 766 1234)
it_splits '2348187661234', %w(234 818 766 1234)
it_splits '2348197661234', %w(234 819 766 1234)
end
describe 'Niue' do
it_splits '6833651', ['683', false, '3651']
end
describe 'Palau (Republic of)' do
it_splits '6804873653', ['680', false, '487', '3653']
end
describe 'Panama (Republic of)' do
it_splits '5078001234', %w(507 800 1234)
it_splits '50761234567', %w(507 6 123 4567)
it_splits '5072123456', %w(507 2 123 456)
end
describe 'Papua New Guinea' do
it_splits '6753123567', %w(675 3 123 567)
it_splits '6751801234', %w(675 180 1234)
it_splits '67580123456', %w(675 80 123 456)
it_splits '67591123456', %w(675 91 123 456)
it_splits '6751612345', %w(675 16 123 45)
it_splits '67518412345678', %w(675 184 1234 5678)
it_splits '67517012', %w(675 170 12)
it_splits '6751891', %w(675 189 1)
it_splits '6752701234', %w(675 270 1234)
it_splits '6752751234', %w(675 275 1234)
it_splits '67527912', %w(675 279 12)
it_splits '67511512345678', %w(675 115 1234 5678)
end
describe 'Reunion / Mayotte (new)' do
it_splits '262594399265', ['262', '594', '39', '92', '65']
end
describe 'Saint Helena' do
it_splits '2903614', ['290', false, '3614']
end
describe 'Saint Pierre and Miquelon (Collectivité territoriale de la République française)' do
it_splits '508418826', ['508', false, '418', '826']
end
describe 'Samoa (Independent State of)' do
it_splits '685800123', ['685', false, '800', '123']
it_splits '68561123', ['685', false, '61', '123']
it_splits '6857212345', ['685', false, '721', '2345']
it_splits '685830123', ['685', false, '830', '123']
it_splits '685601234', ['685', false, '601', '234']
it_splits '6858412345', ['685', false, '841', '2345']
end
describe 'San Marino' do
it_splits '378800123', ['378', false, '800', '123']
it_splits '3788001234567', ['378', false, '800', '123', '4567']
it_splits '378012345', ['378', false, '012', '345']
it_splits '3780123456789', ['378', false, '012', '345', '6789']
it_splits '378512345', ['378', false, '512', '345']
it_splits '3785123456789', ['378', false, '512', '345', '6789']
end
describe 'Saudi Arabia (Kingdom of)' do
it_splits '9660208528423', %w(966 020 852 8423)
it_splits '966506306201', %w(966 50 630 6201)
end
describe 'Senegal' do
it_splits '221123456789', ['221', false, '1234', '56789']
end
describe 'Serbia' do
it_splits '38180012345', %w(381 800 123 45)
it_splits '3811012345', %w(381 10 123 45)
it_splits '38110123456', %w(381 10 123 456)
it_splits '38111123456', %w(381 11 123 456)
it_splits '381111234567', %w(381 11 123 4567)
it_splits '381721234567', %w(381 72 123 4567)
it_splits '38160123', %w(381 60 123)
it_splits '381601234567', %w(381 60 123 4567)
it_splits '38142123456', %w(381 42 123 456)
it_splits '38191234567', %w(381 9 123 4567)
it_splits '38160123', %w(381 60 123)
it_splits '381601234567890', %w(381 60 123 456 7890)
it_splits '38170123456', %w(381 70 123 456)
end
describe 'Sierra Leone' do
it_splits '23264629769', %w(232 64 629 769)
end
describe 'Solomon Islands' do
it_splits '67754692', ['677', false, '54', '692']
it_splits '6777546921', ['677', false, '7546', '921']
end
describe 'Somali Democratic Republic' do
it_splits '252103412345', %w(252 1034 123 45)
it_splits '2521313123', %w(252 1313 123)
it_splits '2521601234', %w(252 160 12 34)
it_splits '25250012345', %w(252 500 123 45)
it_splits '252671234567', %w(252 67 1234 567)
end
describe 'Suriname (Republic of)' do
it_splits '597958434', ['597', false, '958', '434']
it_splits '597212345', ['597', false, '212', '345']
it_splits '5976123456', ['597', false, '612', '3456']
end
describe 'Swaziland' do
it_splits '26822071234', ['268', false, '2207', '1234']
it_splits '2685501234', ['268', false, '550', '1234']
end
describe 'Syrian Arab Republic' do
it_splits '963111234567', %w(963 11 123 4567)
it_splits '963311234567', %w(963 31 123 4567)
it_splits '96315731234', %w(963 15 731 234)
it_splits '963912345678', %w(963 9 1234 5678)
end
describe 'Taiwan' do
it_splits '88618123456', %w(886 18 123 456)
it_splits '8866121234567', %w(886 612 123 4567)
it_splits '886212345678', %w(886 2 1234 5678)
it_splits '88631234567', %w(886 3 123 4567)
it_splits '88633123456', %w(886 33 123 456)
it_splits '88682712345', %w(886 827 123 45)
it_splits '8864121234', %w(886 412 1234)
it_splits '88690123456', %w(886 90 123 456)
it_splits '886901234567', %w(886 90 123 4567)
it_splits '88694991345', %w(886 94 991 345)
end
describe 'Togolese Republic' do
it_splits '22812345678', ['228', false, '1234', '5678']
end
describe 'Tajikistan' do
it_splits '992313012345', %w(992 3130 123 45)
it_splits '992331700123', %w(992 331700 123)
it_splits '992372123345', %w(992 372 123 345)
it_splits '992505123456', %w(992 505 123 456)
it_splits '992973123456', %w(992 973 123 456)
it_splits '992474456123', %w(992 474 456 123)
end
describe 'Tokelau' do
it_splits '6901371', %w(690 1 371)
end
describe 'Tonga (Kingdom of)' do
it_splits '67620123', ['676', false, '20', '123']
it_splits '67684123', ['676', false, '84', '123']
it_splits '6767712345', ['676', false, '77', '123', '45']
it_splits '6768912345', ['676', false, '89', '123', '45']
end
describe 'Tuvalu' do
it_splits '68893741', ['688', false, '93741']
end
describe 'Turkmenistan' do
it_splits '99312456789', %w(993 12 456 789)
it_splits '99313145678', %w(993 131 456 78)
it_splits '99313924567', %w(993 1392 4567)
it_splits '99361234567', %w(993 6 123 4567)
end
describe 'Ukraine' do
it_splits '380800123456', %w(380 800 123 456)
it_splits '380312123456', %w(380 312 123 456)
it_splits '380320123456', %w(380 32 0123 456)
it_splits '380325912345', %w(380 3259 123 45)
it_splits '380326061234', %w(380 32606 1234)
it_splits '380391234567', %w(380 39 123 45 67)
it_splits '380501234567', %w(380 50 123 45 67)
it_splits '380631234567', %w(380 63 123 45 67)
it_splits '380661234567', %w(380 66 123 45 67)
it_splits '380671234567', %w(380 67 123 45 67)
it_splits '380681234567', %w(380 68 123 45 67)
it_splits '380911234567', %w(380 91 123 45 67)
it_splits '380921234567', %w(380 92 123 45 67)
it_splits '380931234567', %w(380 93 123 45 67)
it_splits '380941234567', %w(380 94 123 45 67)
it_splits '380951234567', %w(380 95 123 45 67)
it_splits '380961234567', %w(380 96 123 45 67)
it_splits '380971234567', %w(380 97 123 45 67)
it_splits '380981234567', %w(380 98 123 45 67)
it_splits '380991234567', %w(380 99 123 45 67)
end
describe 'United Arab Emirates' do
it_splits '97180012', %w(971 800 12)
it_splits '971800123456789', %w(971 800 12 345 6789)
it_splits '97121234567', %w(971 2 123 4567)
it_splits '971506412345', %w(971 50 641 2345)
it_splits '971600641234', %w(971 600 641 234)
it_splits '971500641234', %w(971 500 641 234)
it_splits '971200641234', %w(971 200 641 234)
end
describe 'Uruguay (Eastern Republic of)' do
it_splits '59880012345', %w(598 800 123 45)
it_splits '59820123456', %w(598 2 012 3456)
it_splits '59821123456', %w(598 21 123 456)
it_splits '59890912345', %w(598 909 123 45)
it_splits '59893123456', %w(598 93 123 456)
it_splits '59890812345', %w(598 908 123 45)
it_splits '59880512345', %w(598 805 123 45)
end
describe 'Uzbekistan (Republic of)' do
it_splits '998433527869', %w(998 43 352 7869)
end
describe 'Vanuatu (Republic of)' do
it_splits '67889683', ['678', false, '89', '683']
end
describe 'Yemen' do
it_splits '9671234567', %w(967 1 234 567)
it_splits '96712345678', %w(967 1 234 5678)
it_splits '9677234567', %w(967 7 234 567)
it_splits '967771234567', %w(967 77 123 4567)
it_splits '967581234', %w(967 58 1234)
end
describe 'Zimbabwe' do
it_splits '2632582123456', %w(263 2582 123 456)
it_splits '2632582123', %w(263 2582 123)
it_splits '263147123456', %w(263 147 123 456)
it_splits '263147123', %w(263 147 123)
it_splits '263270123456', %w(263 270 123 456)
it_splits '26327012345', %w(263 270 123 45)
it_splits '2638612354567', %w(263 86 1235 4567)
# mobile numbers (see http://www.itu.int/dms_pub/itu-t/oth/02/02/T02020000E90002PDFE.pdf, Table 4, Page 25)
%w(71 73 77 78).each do |prefix|
number = "263#{prefix}2345678"
it_splits number, ['263', prefix, '234', '5678']
end
end
end
end
| mit |
MaximilianKucher/vs1Lab | Beispiele/nodejs_webserver/web.js | 1328 | var http = require("http");
var url = require("url");
var server;
// Diese Funktion reagiert auf HTTP Requests,
// hier wird also die Web Anwendung implementiert!
var simpleHTTPResponder = function(req, res) {
// Routing bedeutet, anhand der URL Adresse
// unterschiedliche Funktionen zu steuern.
// Dazu wird zunächst die URL Adresse benötigt
var url_parts = url.parse(req.url, true);
// Nun erfolgt die Fallunterscheidung,
// hier anhand des URL Pfads
if (url_parts.pathname == "/greetme") {
// HTTP Header müssen gesetzt werden
res.writeHead(200, {
"Content-Type": "text/html"
});
// Auch URL Query Parameter können abgefragt werden
var query = url_parts.query;
var name = "Anonymous";
if (query["name"] != undefined) {
name = query["name"];
}
// HTML im Script zu erzeugen ist mühselig...
res.end("<html><head><title>Greetme</title></head><body><H1>Greetings " +
name + "!</H1></body></html>");
// nun folgt der zweite Fall...
} else {
res.writeHead(404, {
"Content-Type": "text/html"
});
res.end(
"<html><head><title>Error</title></head><body><H1>Only /greetme is implemented.</H1></body></html>"
);
}
}
// Webserver erzeugen, an Endpunkt binden und starten
server = http.createServer(simpleHTTPResponder);
var port = process.argv[2];
server.listen(port);
| mit |
chcbaram/CupDrone_IDE | reference/arduino.cc/en/Reference/EsploraReadBlue.html | 23508 | <!DOCTYPE html>
<!--html5-->
<!--[if IE 8]> <html class="no-js lt-ie9" lang="en"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]-->
<!-- Mirrored from arduino.cc/en/Reference/EsploraReadBlue by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 06 Feb 2015 20:16:08 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8" /><!-- /Added by HTTrack -->
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta charset="utf-8" />
<title>Arduino - EsploraReadBlue </title>
<link rel="shortcut icon" type="image/x-icon" href="../favicon.png" />
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<link rel="stylesheet" href="../../fonts/fonts.css" type="text/css" />
<link rel="stylesheet" href="../../css/arduino-icons.css">
<link rel="stylesheet" href="../../css/animation.css"><!--[if IE 7]>
<link rel="stylesheet" href="http://arduino.cc/css/arduino-icons-ie7.css"><![endif]-->
<!--[if gte IE 9]><!-->
<link rel='stylesheet' href='../../css/foundation2.css' type='text/css' />
<!--<![endif]-->
<!--[if IE 8]>
<link rel='stylesheet' href='http://arduino.cc/css/foundation_ie8.css' type='text/css' />
<![endif]-->
<link rel='stylesheet' href='../../css/arduino_code_highlight.css' type='text/css' />
<link rel="stylesheet" type="text/css" media="screen" href="../../css/typeplate.css">
<link rel='stylesheet' href='../pub/skins/arduinoWide_SSO/css/arduinoWide_SSO.css' type='text/css' />
<link rel='stylesheet' href='../../css/common.css' type='text/css' />
<link rel="stylesheet" href="../../css/download_page.css" />
<link href="https://plus.google.com/114839908922424087554" rel="publisher" />
<!-- embedded JS and CSS from PmWiki plugins -->
<!--HeaderText--><style type='text/css'><!--
ul, ol, pre, dl, p { margin-top:0px; margin-bottom:0px; }
code { white-space: nowrap; }
.vspace { margin-top:1.33em; }
.indent { margin-left:40px; }
.outdent { margin-left:40px; text-indent:-40px; }
a.createlinktext { text-decoration:none; border-bottom:1px dotted gray; }
a.createlink { text-decoration:none; position:relative; top:-0.5em;
font-weight:bold; font-size:smaller; border-bottom:none; }
img { border:0px; }
span.anchor {
float: left;
font-size: 10px;
margin-left: -10px;
width: 10px;
position:relative; top:-0.1em;
text-align: center;
}
span.anchor a { text-decoration: none; }
span.anchor a:hover { text-decoration: underline; }
ol.toc { text-indent:-20px; list-style: none; }
ol.toc ol.toc { text-indent:-40px; }
div.tocfloat { font-size: smaller; margin-bottom: 10px;
border-top: 1px dotted #555555; border-bottom: 1px dotted #555555;
padding-top: 5px; padding-bottom: 5px;
width: 38%; float: right; margin-left: 10px; clear: right;
margin-right:-13px; padding-right: 13px; padding-left: 13px;
background-color: #eeeeee; }
div.toc { font-size: smaller;
padding: 5px; border: 1px dotted #cccccc;
background: #f7f7f7;
margin-bottom: 10px; }
div.toc p { background-color: #f9f6d6;
margin-top:-5px; padding-top: 5px;
margin-left:-5px; padding-left: 5px;
margin-right:-5px; padding-right: 5px;
padding-bottom: 3px;
border-bottom: 1px dotted #cccccc; }.editconflict { color:green;
font-style:italic; margin-top:1.33em; margin-bottom:1.33em; }
table.markup { border: 2px dotted #ccf; width:90%; }
td.markup1, td.markup2 { padding-left:10px; padding-right:10px; }
td.markup1 { border-bottom: 1px solid #ccf; }
div.faq { margin-left:2em; }
div.faq p.question { margin: 1em 0 0.75em -2em; font-weight:bold; }
div.faq hr { margin-left: -2em; }
.frame
{ border:1px solid #cccccc; padding:4px; background-color:#f9f9f9; }
.lfloat { float:left; margin-right:0.5em; }
.rfloat { float:right; margin-left:0.5em; }
a.varlink { text-decoration:none; }
/**
* GeSHi (C) 2004 - 2007 Nigel McNie, 2007 - 2008 Benny Baumann
* (http://qbnz.com/highlighter/ and http://geshi.org/)
*/
.arduino {font-family:monospace;}
.arduino .imp {font-weight: bold; color: red;}
.arduino .kw1 {color: #CC6600;}
.arduino .kw2 {color: #006699;}
.arduino .kw3 {color: #CC6600; font-weight: bold;}
.arduino .co1 {color: #7E7E7E; font-style: italic;}
.arduino .co2 {color: #7E7E7E;}
.arduino .coMULTI {color: #7E7E7E; font-style: italic;}
.arduino .es0 {color: #000099; font-weight: bold;}
.arduino .es1 {color: #000099; font-weight: bold;}
.arduino .es2 {color: #660099; font-weight: bold;}
.arduino .es3 {color: #660099; font-weight: bold;}
.arduino .es4 {color: #660099; font-weight: bold;}
.arduino .es5 {color: #006699; font-weight: bold;}
.arduino .br0 {color: #000000;}
.arduino .sy0 {color: #000000;}
.arduino .st0 {color: #0066CC;}
.arduino .nu0 {color: #000000;}
.arduino .nu6 {color: #208080;}
.arduino .nu8 {color: #208080;}
.arduino .nu12 {color: #208080;}
.arduino .nu16 {color:#800080;}
.arduino .nu17 {color:#800080;}
.arduino .nu18 {color:#800080;}
.arduino .nu19 {color:#800080;}
.arduino .me1 {color: #ff1493;}
.arduino .me2 {color: #ff1493;}
.arduino span.xtra { display:block; }
.sourceblocklink {
text-align: right;
font-size: smaller;
}
.sourceblocktext {
padding: 0.5em;
color: #000000;
background-color: #ffffff;
}
.sourceblocktext div {
font-family: monospace;
font-size: small;
line-height: 1;
height: 1%;
}
.sourceblocktext div.head,
.sourceblocktext div.foot {
font: italic medium serif;
padding: 0.5em;
}
--></style><script type="text/javascript">
function toggle(obj) {
var elstyle = document.getElementById(obj).style;
var text = document.getElementById(obj + "tog");
if (elstyle.display == 'none') {
elstyle.display = 'block';
text.innerHTML = "hide";
} else {
elstyle.display = 'none';
text.innerHTML = "show";
}
}
</script> <meta name='robots' content='index,follow' />
<script src="http://arduino.cc/js/vendor/custom.modernizr.js"></script>
<!-- do not remove none of those lines, comments embedding in pages will break! -->
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js" type="text/javascript"></script>
<script src="http://arduino.cc/en/pub/js/newsletter_subscribe_popup.js" type="text/javascript"></script>
<script src="https://checkout.stripe.com/checkout.js" type="text/javascript"></script>
<script src="https://arduino.cc/en/pub/js/software_download.js" type="text/javascript"></script><!-- keep https! -->
<link rel='stylesheet' href='../../../code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.min.css' type='text/css' />
<script src="http://arduino.cc/tools/comments/extern/?s=wiki" type="text/javascript"></script>
</head>
<body>
<div id="menuWings" class="fixed"></div>
<div id="page">
<script>
var userAgent = (navigator.userAgent || navigator.vendor || window.opera).toLowerCase();
if(userAgent.indexOf('mac')>0){
$("head").append('<style type="text/css">@-moz-document url-prefix() {h1 a, h2 a, h3 a, h4 a, h5 a, h1 a:hover, h2 a:hover, th a, th a:hover, h3 a:hover, h4 a:hover, h5 a:hover, #wikitext h2 a:hover, #wikitext h3 a:hover, #wikitext h4 a:hover {padding-bottom: 0.5em!important;} #pageheader .search input{font-family: "TyponineSans Regular 18";} #pagefooter .monospace{margin-top: -4px;} #navWrapper ul.left > li{margin-top: -2px; padding-bottom: 2px;}#navWrapper ul.right > li{margin-top: -5px; padding-bottom: 5px;}#navWrapper ul.right > li ul{margin-top: 4px;} .slider-container .fixed-caption p{padding:8px 0 14px 0}}</style>');
}
</script>
<!--[if IE]>
<link rel='stylesheet' href='https://id.arduino.cc//css/ie-monospace.css' type='text/css' />
<![endif]-->
<div id="menuWings" class="fixed"></div>
<!--[if IE 8]>
<div class="alert-box panel ie8alert">
<p><strong>Arduino.cc offers limited compatibility for Internet Explorer 8. Get a modern browser as Chrome, Firefox or Safari.</strong></p>
<a href="" class="close">×</a>
</div>
<![endif]-->
<div id="pageheader">
<div class="row" class="contain-to-grid">
<div class="small-6 large-8 eight columns">
<div class="title"><a href="http://arduino.cc/">Arduino</a></div>
</div>
<div class="small-6 large-4 four columns search">
<div class="row collapse">
<form method="GET" action="http://www.google.com/search">
<div class="small-12 twelve columns">
<i class="icon-search-2"></i>
<input type="hidden" name="ie" value="UTF-8">
<input type="hidden" name="oe" value="UTF-8">
<input type="text" name="q" size="25" maxlength="255" value="" placeholder="Search the Arduino Website">
<input type="submit" name="btnG" VALUE="search">
<input type="hidden" name="domains" value="http://arduino.cc">
<input type="hidden" name="sitesearch" value="http://arduino.cc">
</div>
</form> </div>
</div>
</div>
<!--[if gte IE 9]><!-->
<div id="navWrapper" class="sticky">
<!--<![endif]-->
<!--[if IE 8]>
<div id="navWrapper">
<![endif]-->
<nav class="top-bar" data-options="is_hover:true" >
<ul class="title-area">
<li class="name"></li>
</ul>
<section class="top-bar-section">
<ul class="left">
<li id="navLogo">
<a href="http://arduino.cc/">
<img src="../../img/logo_46.png" alt="userpicture" />
</a>
</li>
<li id="navHome"><a href="http://arduino.cc/">Home</a></li>
<li><a href="http://store.arduino.cc/">Buy</a></li>
<li><a href="http://arduino.cc/en/Main/Software">Download</a></li>
<li class="has-dropdown"><a href="#">Products</a>
<ul class="dropdown">
<li><a href="http://arduino.cc/en/Main/Products">Arduino</a></li>
<li><a href="http://arduino.cc/en/ArduinoAtHeart/Products">AtHeart</a></li>
<li><a href="http://arduino.cc/en/ArduinoCertified/Products">Certified</a></li>
</ul>
</li>
<li class="has-dropdown active"><a href="#">Learning</a>
<ul class="dropdown">
<li><a href="../Guide/HomePage.html">Getting started</a></li>
<li><a href="http://arduino.cc/en/Tutorial/HomePage">Examples</a></li>
<li><a href="HomePage.html">Reference</a></li>
<li><a href="http://playground.arduino.cc/">Playground</a></li>
</ul>
</li>
<li><a href="http://forum.arduino.cc/">Forum</a></li>
<li class="has-dropdown"><a href="#">Support</a>
<ul class="dropdown">
<li><a href="../Main/FAQ.html">FAQ</a></li>
<li><a href="http://arduino.cc/en/ContactUs">Contact Us</a></li>
</ul>
</li>
<li><a href="http://blog.arduino.cc/">Blog</a></li>
</ul>
<ul class="right">
<li><a href="https://id.arduino.cc/auth/login/?returnurl=http%3A%2F%2Farduino.cc%2Fen%2FReference%2FEsploraReadBlue" class="cart">LOG IN</a></li>
<li><a href="https://id.arduino.cc/auth/signup" class="cart">SIGN UP</a></li>
</ul>
</section>
</nav>
</div>
</div>
<br class="clear"/>
<div id="pagetext">
<!--PageText-->
<div id='wikitext'>
<p><strong>Reference</strong> <a class='wikilink' href='HomePage.html'>Language</a> | <a class='wikilink' href='Libraries.html'>Libraries</a> | <a class='wikilink' href='Comparison.html'>Comparison</a> | <a class='wikilink' href='Changes.html'>Changes</a>
</p>
<p class='vspace'></p><p><a class='wikilink' href='EsploraLibrary.html'>Esplora</a>
</p>
<p class='vspace'></p><h2>readBlue()</h2>
<h4>Description</h4>
<p>Read the brightness value of the blue LED.
</p>
<p class='vspace'></p><h4>Syntax</h4>
<p>Esplora.readBlue()
</p>
<p class='vspace'></p><h4>Parameters</h4>
<p>none
</p>
<p class='vspace'></p><h4>Returns</h4>
<p>int : the brightness of the blue LED between 0 and 255.
</p>
<p class='vspace'></p><h4>Example</h4>
<p>
<div class='sourceblock ' id='sourceblock1'>
<div class='sourceblocktext'><div class="arduino"><span class="co2">#include <Esplora.h></span><br />
<br />
<span class="kw1">void</span> <span class="kw3">setup</span><span class="br0">(</span><span class="br0">)</span> <br />
<span class="br0">{</span><br />
<span class="kw1">Serial</span>.<span class="kw1">begin</span><span class="br0">(</span><span class="nu0">9600</span><span class="br0">)</span><span class="sy0">;</span><br />
<span class="br0">}</span> <br />
<br />
<span class="kw1">void</span> <span class="kw3">loop</span><span class="br0">(</span><span class="br0">)</span><br />
<span class="br0">{</span><br />
<span class="kw1">int</span> dimmerValue <span class="sy0">=</span> Esplora.<span class="me1">readSlider</span><span class="br0">(</span><span class="br0">)</span><span class="sy0">;</span><br />
Esplora.<span class="me1">writeBlue</span><span class="br0">(</span>dimmerValue<span class="br0">)</span><span class="sy0">;</span><br />
<span class="kw1">Serial</span>.<span class="kw1">println</span><span class="br0">(</span>Esplora.<span class="me1">readBlue</span><span class="br0">(</span><span class="br0">)</span><span class="br0">)</span><span class="sy0">;</span><br />
<br />
<span class="kw1">delay</span><span class="br0">(</span><span class="nu0">500</span><span class="br0">)</span><span class="sy0">;</span><br />
<span class="br0">}</span></div></div>
<div class='sourceblocklink'><a href='http://arduino.cc/en/Reference/EsploraReadBlue?action=sourceblock&num=1' type='text/plain'>[Get Code]</a></div>
</div>
</p>
<p class='vspace'></p><h4>See also</h4>
<p><a class='wikilink' href='EsploraReadGreen.html'>readGreen()</a><br /><a class='wikilink' href='EsploraReadRed.html'>readRed()</a>
<a class='wikilink' href='HomePage.html'>Reference Home</a>
</p>
<p class='vspace'></p><p><em>Corrections, suggestions, and new documentation should be posted to the <a class='urllink' href='http://arduino.cc/forum/index.php/board,23.0.html' rel='nofollow'>Forum</a>.</em>
</p>
<p class='vspace'></p><p>The text of the Arduino reference is licensed under a
<a class='urllink' href='http://creativecommons.org/licenses/by-sa/3.0/' rel='nofollow'>Creative Commons Attribution-ShareAlike 3.0 License</a>. Code samples in the reference are released into the public domain.
</p>
</div>
<!-- AddThis Button Style BEGIN -->
<style>
.addthis_toolbox {
margin: 2em 0 1em;
}
.addthis_toolbox img {
float: left;
height: 25px;
margin-right: 10px;
width: auto;
}
.addthis_toolbox .social-container {
float: left;
height: 27px;
width: auto;
}
.addthis_toolbox .social-container .social-content {
float: left;
margin-top: 2px;
max-width: 0;
overflow: hidden;
-moz-transition: max-width .3s ease-out;
-webkit-transition: max-width .3s ease-out;
-o-transition: max-width .3s ease-out;
transition: max-width .3s ease-out;
}
.addthis_toolbox .social-container:hover .social-content {
max-width: 100px;
-moz-transition: max-width .2s ease-in;
-webkit-transition: max-width .2s ease-in;
-o-transition: max-width .2s ease-in;
transition: max-width .2s ease-in;
}
.addthis_toolbox .social-container .social-content a {
float: left;
margin-right: 5px;
}
.addthis_toolbox h3 {
font-size: 24px;
text-align: left;
}
</style>
<!-- AddThis Button Style END -->
<!-- AddThis Button BEGIN -->
<div class="addthis_toolbox addthis_default_style">
<h3>Share</h3>
<!-- FACEBOOK -->
<div class="social-container">
<img src="../pub/skins/arduinoWide_SSO/img/facebook.png" />
<div class="social-content">
<a class="addthis_button_facebook_like" fb:like:layout="button_count"></a>
</div>
</div>
<!-- TWITTER -->
<div class="social-container">
<img src="../pub/skins/arduinoWide_SSO/img/twitter.png">
<div class="social-content">
<a class="addthis_button_tweet"></a>
</div>
</div>
<!-- PINTEREST -->
<div class="social-container">
<img src="../pub/skins/arduinoWide_SSO/img/pinterest.png">
<div class="social-content">
<a class="addthis_button_pinterest_pinit" pi:pinit:url="http://www.addthis.com/features/pinterest" pi:pinit:media="http://www.addthis.com/cms-content/images/features/pinterest-lg.png"></a>
</div>
</div>
<!-- G+ -->
<div class="social-container">
<img src="../pub/skins/arduinoWide_SSO/img/gplus.png">
<div class="social-content">
<a class="addthis_button_google_plusone" g:plusone:size="medium"></a>
</div>
</div>
<script type="text/javascript">var addthis_config = {"data_track_addressbar":false};</script>
<script type="text/javascript" src="http://s7.addthis.com/js/300/addthis_widget.js#pubid=ra-50573fab238b0d34"></script>
</div>
<!-- AddThis Button END -->
</div> <!-- eof pagetext -->
</div> <!-- eof page -->
<!--PageFooterFmt-->
<div id="pagefooter">
<div id="newsletterModal" class="reveal-modal small">
<form action="http://arduino.cc/subscribe.php" method="post" name="sendy-subscribe-form" id="sendy-subscribe-form" class="form-popup">
<div class="modalHeader">
<h3 style="line-height: 1.8rem;" class="modal-header-alt">This link has expired. <br>Please re-subscribe to our Newsletters.</h3>
<h3 class="modal-header-main">Subscribe to our Newsletters</h3>
</div>
<div class="modalBody" id="newsletterModalBody">
<div id="newsletterEmailField" class="row" style="padding-left: 0">
<div class="large-2 columns">
<label for="email" class="newsletter-form-label inline">Email</label>
</div>
<div class="large-10 columns" style="padding-left: 0">
<input placeholder="Enter your email address" type="email" name="email" class="subscribe-form-input" />
<p id="emailMissing" class="newsletterPopupError">Please enter a valid email to subscribe</p>
</div>
</div>
<div style="margin-left:20px">
<div style="margin-bottom:0.3em">
<input style="display:none" type="checkbox" checked name="list[]" value="arduino_newsletter_id" id="worldwide" class="newsletter-form-checkbox" />
<label for="worldwide"></label>
<div style="display:inline-block" class="newsletter-form-label">Arduino Newsletter</div>
</div>
<div>
<input style="display:none" type="checkbox" checked name="list[]" value="arduino_store_newsletter_id" id="store" class="newsletter-form-checkbox" />
<label for="store"></label>
<div style="display:inline-block" class="newsletter-form-label">Arduino Store Newsletter</div>
</div>
</div>
<div>
<p class="newsletterPopupError2" id="newsletterSubscribeStatus"></p>
</div>
</div>
<div class="row modalFooter">
<div class="form-buttons-row">
<button type="button" value="Cancel" class="popup-form-button white cancel-modal close-reveal-modal">Cancel</button>
<button type="submit" name="Subscribe" id="subscribe-submit-btn" class="popup-form-button">Next</button>
</div>
</div>
</form>
<!-- step 2, confirm popup -->
<div class="confirm-popup" style="margin-bottom:1em">
<div class="modalHeader">
<h3>Confirm your email address</h3>
</div>
<div class="modalBody" id="newsletterModalBody" style="padding-right:1em;margin-bottom:0">
<p style="margin-bottom:1em;font-size:15px">
We need to confirm your email address.<br>
To complete the subscription, please click the link in the
email we just sent you.
</p>
<p style="margin-bottom:1em;font-size:15px">
Thank you for subscribing!
</p>
<p style="margin-bottom:1em;font-size:15px">
Arduino<br>
via Egeo 16<br>
Torino, 10131<br>
Italy<br>
</p>
</div>
<div class="row modalFooter">
<div class="form-buttons-row">
<button name="Ok" class="popup-form-button" id="close-confirm-popup">Ok</button>
</div>
</div>
</div>
</div><div id="pagefooter" class="pagefooter">
<div class="row">
<div class="large-8 eight columns">
<div class="large-4 four columns newsletter-box">
<!-- Begin Sendy Signup Form -->
<h6>Newsletter</h6>
<div>
<input type="email" name="email" class="email" id="sendy-EMAIL" placeholder="Enter your email to sign up">
<i class="icon-right-small"></i>
<input value="Subscribe" name="subscribe" id="sendy-subscribe" class="newsletter-button">
</div>
<!--End sendy_embed_signup-->
</div>
<div class="clearfix"></div>
<ul class="inline-list">
<li class="monospace">©2015 Arduino</li>
<li><a href="http://arduino.cc/en/Main/CopyrightNotice">Copyright Notice</a></li>
<li><a href='http://arduino.cc/en/Main/ContactUs'>Contact us</a></li>
<li><a href='http://arduino.cc/Careers'>Careers</a></li>
</ul>
</div>
<div class="large-4 four columns">
<ul id="arduinoSocialLinks" class="arduino-social-links">
<li>
<a href="https://twitter.com/arduino">
<img src="../../img/twitter.png" />
</a>
</li>
<li>
<a href="http://www.facebook.com/official.arduino">
<img src="../../img/facebook.png" />
</a>
</li>
<li>
<a href="https://plus.google.com/+Arduino">
<img src="../../img/gplus.png" />
</a>
</li>
<li>
<a href="http://www.flickr.com/photos/arduino_cc">
<img src="../../img/flickr.png" />
</a>
</li>
<li>
<a href="http://youtube.com/arduinoteam">
<img src="../../img/youtube.png" />
</a>
</li>
</ul>
</div>
</div>
</div>
</div>
<!--/PageFooterFmt-->
<!--[if gte IE 9]><!-->
<script src="http://arduino.cc/js/foundation.min.js"></script>
<script src="http://arduino.cc/js/foundation.topbar.custom.js"></script>
<script>
$(document).foundation();
</script>
<!--<![endif]-->
<!--[if IE 8]>
<script src="http://arduino.cc/js/foundation_ie8.min.js"></script>
<script src="http://arduino.cc/js/ie8/jquery.foundation.orbit.js"></script>
<script src="http://arduino.cc/js/ie8/jquery.foundation.alerts.js"></script>
<script src="http://arduino.cc/js/app.js"></script>
<script>
$(window).load(function(){
$("#featured").orbit();
});
</script>
<![endif]-->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-22581631-3']);
_gaq.push(['_setDomainName', 'arduino.cc']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<script>
$(window).load(function(){
$('a').each (function () {
href = $(this).attr ('href');
if (href.substring (0, 4) == 'http' && href.indexOf ('arduino.cc') == -1)
$(this).attr ('target', '_blank');
});
});
</script>
</body>
<!-- Mirrored from arduino.cc/en/Reference/EsploraReadBlue by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 06 Feb 2015 20:16:08 GMT -->
</html>
| mit |
yomikaze/OOGASalad | src/engine/menu/managers/WeaponManager.java | 2233 | package engine.menu.managers;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.util.List;
import engine.dialogue.InteractionBox;
import engine.gridobject.person.Player;
import engine.images.ScaledImage;
import engine.item.Weapon;
import engine.menu.MenuInteractionMatrix;
import engine.menu.nodes.WeaponInfoNode;
public class WeaponManager extends MenuManager implements InteractionBox {
private Player myPlayer;
private MenuInteractionMatrix myMIM;
private MenuManager myMenuManager;
public WeaponManager(Player p, MenuManager mm, MenuInteractionMatrix mim) {
super(p, null, mim);
myPlayer = p;
myMIM = mim;
myMenuManager = mm;
}
@Override
public void paintDisplay(Graphics2D g2d, int xSize, int ySize, int width,
int height) {
paintMenu(g2d, height, width);
paintFeatureBox(g2d, "ImageFiles/PokemonBox.png", 17, 20, 300, 200);
paintWeaponData(g2d);
drawSelector(g2d, 198, 40, 280, 45, 44, myMIM);
}
@Override
public void getNextText() {
// TODO Auto-generated method stub
}
protected void paintFeatureBox(Graphics g2d, String imgPath, int x, int y,
int width, int height) {
Image img = new ScaledImage(width, height, imgPath).scaleImage();
g2d.drawImage(img, x, y, null);
}
protected void paintFeatureImage(Graphics g2d, Image feature, int x, int y) {
g2d.drawImage(feature, x, y, null);
}
protected void paintFeatureName(Graphics g2d, String name, int x, int y) {
g2d.drawString(name, x, y);
}
private void paintWeaponData(Graphics g2d) {
List<Weapon> features = myPlayer.getWeaponList();
int emptySpace = 0;
for (int i = 0; i < features.size(); i++) {
if (i != 0) {
emptySpace = 1;
} else {
emptySpace = 0;
}
Image scaledWeaponImage = features.get(i).getImage()
.getScaledInstance(35, 35, Image.SCALE_SMOOTH);
paintFeatureImage(g2d, scaledWeaponImage, 37, 45 + i * 40 + 5
* emptySpace);
paintFeatureName(g2d, features.get(i).toString(), 80, 67 + i * 40 + 5
* emptySpace);
}
}
public void createWeaponInfoNodes() {
for (int i = 0; i < myPlayer.getWeaponList().size(); i++) {
myMIM.setNode(new WeaponInfoNode(myPlayer, this, myMenuManager, i),
0, i);
}
}
}
| mit |
sonata-project/sandbox-build | vendor/sonata-project/block-bundle/Tests/Block/BlockServiceManagerTest.php | 4478 | <?php
/*
* This file is part of the Sonata package.
*
* (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\BlockBundle\Tests\Block;
use Sonata\BlockBundle\Block\BlockServiceManager;
use Symfony\Component\DependencyInjection\ContainerInterface;
class BlockServiceManagerTest extends \PHPUnit_Framework_TestCase
{
public function testGetBlockService()
{
$service = $this->getMock('Sonata\BlockBundle\Block\BlockServiceInterface');
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->once())->method('get')->will($this->returnValue($service));
$manager = new BlockServiceManager($container, true);
$manager->add('test', 'test');
$block = $this->getMock('Sonata\BlockBundle\Model\BlockInterface');
$block->expects($this->any())->method('getType')->will($this->returnValue('test'));
$this->assertInstanceOf(get_class($service), $manager->get($block));
}
/**
* @expectedException \RuntimeException
*/
public function testInvalidServiceType()
{
$service = $this->getMock('stdClass');
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->once())->method('get')->will($this->returnValue($service));
$manager = new BlockServiceManager($container, true);
$manager->add('test', 'test');
$block = $this->getMock('Sonata\BlockBundle\Model\BlockInterface');
$block->expects($this->any())->method('getType')->will($this->returnValue('test'));
$this->assertInstanceOf(get_class($service), $manager->get($block));
}
/**
* @expectedException \RuntimeException
*/
public function testGetBlockServiceException()
{
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$manager = new BlockServiceManager($container, true);
$block = $this->getMock('Sonata\BlockBundle\Model\BlockInterface');
$block->expects($this->any())->method('getType')->will($this->returnValue('fakse'));
$manager->get($block);
}
public function testGetEmptyListFromInvalidContext()
{
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$manager = new BlockServiceManager($container, true);
$service = $this->getMock('Sonata\BlockBundle\Block\BlockServiceInterface');
$manager->add('foo.bar', $service);
$this->assertEmpty($manager->getServicesByContext('fake'));
}
public function testGetListFromValidContext()
{
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$manager = new BlockServiceManager($container, true);
$service = $this->getMock('Sonata\BlockBundle\Block\BlockServiceInterface');
$manager->add('foo.bar', $service, array('fake'));
$this->assertNotEmpty($manager->getServicesByContext('fake'));
}
public function testOrderServices()
{
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$manager = new BlockServiceManager($container, true);
$serviceAbc = $this->getMock('Sonata\BlockBundle\Block\BlockServiceInterface');
$serviceAbc->expects($this->any())->method('getName')->will($this->returnValue('GHI'));
$manager->add('ghi', $serviceAbc);
$serviceAbc = $this->getMock('Sonata\BlockBundle\Block\BlockServiceInterface');
$serviceAbc->expects($this->any())->method('getName')->will($this->returnValue('ABC'));
$manager->add('abc', $serviceAbc);
$serviceAbc = $this->getMock('Sonata\BlockBundle\Block\BlockServiceInterface');
$serviceAbc->expects($this->any())->method('getName')->will($this->returnValue('DEF'));
$manager->add('def', $serviceAbc);
$services = array_keys($manager->getServices());
$this->assertEquals('abc', $services[0], 'After order, the first service should be "ABC"');
$this->assertEquals('def', $services[1], 'After order, the second service should be "DEF"');
$this->assertEquals('ghi', $services[2], 'After order, the third service should be "GHI"');
}
}
| mit |
mavasani/roslyn | src/Features/CSharp/Portable/Highlighting/KeywordHighlighters/UsingStatementHighlighter.cs | 1116 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Composition;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Highlighting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.KeywordHighlighting.KeywordHighlighters
{
[ExportHighlighter(LanguageNames.CSharp), Shared]
internal class UsingStatementHighlighter : AbstractKeywordHighlighter<UsingStatementSyntax>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public UsingStatementHighlighter()
{
}
protected override void AddHighlights(UsingStatementSyntax usingStatement, List<TextSpan> highlights, CancellationToken cancellationToken)
=> highlights.Add(usingStatement.UsingKeyword.Span);
}
}
| mit |
CyrusNajmabadi/roslyn | src/VisualStudio/IntegrationTest/TestUtilities/OutOfProcess/VisualStudioWorkspace_OutOfProc.cs | 5369 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess;
using Microsoft.VisualStudio.LanguageServices.Telemetry;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess
{
public class VisualStudioWorkspace_OutOfProc : OutOfProcComponent
{
private readonly VisualStudioWorkspace_InProc _inProc;
internal VisualStudioWorkspace_OutOfProc(VisualStudioInstance visualStudioInstance)
: base(visualStudioInstance)
{
_inProc = CreateInProcComponent<VisualStudioWorkspace_InProc>(visualStudioInstance);
}
public void SetOptionInfer(string projectName, bool value)
{
_inProc.SetOptionInfer(projectName, value);
WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
}
public bool IsPrettyListingOn(string languageName)
=> _inProc.IsPrettyListingOn(languageName);
public void SetPrettyListing(string languageName, bool value)
=> _inProc.SetPrettyListing(languageName, value);
public void SetPerLanguageOption(string optionName, string feature, string language, object value)
=> _inProc.SetPerLanguageOption(optionName, feature, language, value);
public void SetOption(string optionName, string feature, object value)
=> _inProc.SetOption(optionName, feature, value);
public void WaitForAsyncOperations(TimeSpan timeout, string featuresToWaitFor, bool waitForWorkspaceFirst = true)
=> _inProc.WaitForAsyncOperations(timeout, featuresToWaitFor, waitForWorkspaceFirst);
public void WaitForAllAsyncOperations(TimeSpan timeout, params string[] featureNames)
=> _inProc.WaitForAllAsyncOperations(timeout, featureNames);
public void WaitForAllAsyncOperationsOrFail(TimeSpan timeout, params string[] featureNames)
=> _inProc.WaitForAllAsyncOperationsOrFail(timeout, featureNames);
public void CleanUpWorkspace()
=> _inProc.CleanUpWorkspace();
public void ResetOptions()
=> _inProc.ResetOptions();
public void CleanUpWaitingService()
=> _inProc.CleanUpWaitingService();
public void SetImportCompletionOption(bool value)
{
SetGlobalOption(WellKnownGlobalOption.CompletionOptions_ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, value);
SetGlobalOption(WellKnownGlobalOption.CompletionOptions_ShowItemsFromUnimportedNamespaces, LanguageNames.VisualBasic, value);
}
public void SetEnableDecompilationOption(bool value)
{
SetOption("NavigateToDecompiledSources", "FeatureOnOffOptions", value);
}
public void SetArgumentCompletionSnippetsOption(bool value)
{
SetGlobalOption(WellKnownGlobalOption.CompletionViewOptions_EnableArgumentCompletionSnippets, LanguageNames.CSharp, value);
SetGlobalOption(WellKnownGlobalOption.CompletionViewOptions_EnableArgumentCompletionSnippets, LanguageNames.VisualBasic, value);
}
public void SetTriggerCompletionInArgumentLists(bool value)
=> SetGlobalOption(WellKnownGlobalOption.CompletionOptions_TriggerInArgumentLists, LanguageNames.CSharp, value);
public void SetFullSolutionAnalysis(bool value)
{
SetPerLanguageOption(
optionName: SolutionCrawlerOptions.BackgroundAnalysisScopeOption.Name,
feature: SolutionCrawlerOptions.BackgroundAnalysisScopeOption.Feature,
language: LanguageNames.CSharp,
value: value ? BackgroundAnalysisScope.FullSolution : BackgroundAnalysisScope.Default);
SetPerLanguageOption(
optionName: SolutionCrawlerOptions.BackgroundAnalysisScopeOption.Name,
feature: SolutionCrawlerOptions.BackgroundAnalysisScopeOption.Feature,
language: LanguageNames.VisualBasic,
value: value ? BackgroundAnalysisScope.FullSolution : BackgroundAnalysisScope.Default);
}
public void SetFileScopedNamespaces(bool value)
=> _inProc.SetFileScopedNamespaces(value);
public void SetEnableOpeningSourceGeneratedFilesInWorkspaceExperiment(bool value)
{
SetGlobalOption(
WellKnownGlobalOption.VisualStudioSyntaxTreeConfigurationService_EnableOpeningSourceGeneratedFilesInWorkspace,
language: null,
value);
}
public void SetFeatureOption(string feature, string optionName, string? language, string? valueString)
=> _inProc.SetFeatureOption(feature, optionName, language, valueString);
public void SetGlobalOption(WellKnownGlobalOption option, string? language, object? value)
=> _inProc.SetGlobalOption(option, language, value);
}
}
| mit |
stuartbman/mediawiki-vagrant | mediawiki/extensions/SemanticMediaWiki/tests/phpunit/Unit/SPARQLStore/RedirectLookupTest.php | 7584 | <?php
namespace SMW\Tests\SPARQLStore;
use SMW\SPARQLStore\RedirectLookup;
use SMW\InMemoryPoolCache;
use SMW\DIWikiPage;
use SMW\DIProperty;
use SMW\Exporter\Escaper;
use SMWExpNsResource as ExpNsResource;
use SMWExpLiteral as ExpLiteral;
use SMWExpResource as ExpResource;
use SMWExporter as Exporter;
/**
* @covers \SMW\SPARQLStore\RedirectLookup
* @group semantic-mediawiki
*
* @license GNU GPL v2+
* @since 2.0
*
* @author mwjames
*/
class RedirectLookupTest extends \PHPUnit_Framework_TestCase {
public function testCanConstruct() {
$repositoryConnection = $this->getMockBuilder( '\SMW\SPARQLStore\RepositoryConnection' )
->disableOriginalConstructor()
->getMock();
$this->assertInstanceOf(
'\SMW\SPARQLStore\RedirectLookup',
new RedirectLookup( $repositoryConnection )
);
}
public function testRedirectTragetForBlankNode() {
$repositoryConnection = $this->getMockBuilder( '\SMW\SPARQLStore\RepositoryConnection' )
->disableOriginalConstructor()
->getMock();
$instance = new RedirectLookup( $repositoryConnection );
$expNsResource = new ExpNsResource( '', '', '', null );
$exists = null;
$this->assertSame(
$expNsResource,
$instance->findRedirectTargetResource( $expNsResource, $exists )
);
$this->assertFalse( $exists );
}
public function testRedirectTragetForDataItemWithSubobject() {
$repositoryConnection = $this->getMockBuilder( '\SMW\SPARQLStore\RepositoryConnection' )
->disableOriginalConstructor()
->getMock();
$instance = new RedirectLookup( $repositoryConnection );
$dataItem = new DIWikiPage( 'Foo', 1, '', 'beingASubobject' );
$expNsResource = new ExpNsResource( 'Foo', 'Bar', '', $dataItem );
$exists = null;
$this->assertSame(
$expNsResource,
$instance->findRedirectTargetResource( $expNsResource, $exists )
);
$this->assertTrue( $exists );
}
public function testRedirectTragetForDBLookupWithNoEntry() {
$repositoryConnection = $this->createRepositoryConnectionMockToUse( false );
$instance = new RedirectLookup( $repositoryConnection );
$dataItem = new DIWikiPage( 'Foo', 1, '', '' );
$expNsResource = new ExpNsResource( 'Foo', 'Bar', '', $dataItem );
$exists = null;
$this->assertSame(
$expNsResource,
$instance->findRedirectTargetResource( $expNsResource, $exists )
);
$this->assertFalse( $exists );
}
public function testRedirectTragetForDBLookupWithSingleEntry() {
$expLiteral = new ExpLiteral( 'Redirect' );
$repositoryConnection = $this->createRepositoryConnectionMockToUse( array( $expLiteral ) );
$instance = new RedirectLookup( $repositoryConnection );
$instance->reset();
$dataItem = new DIWikiPage( 'Foo', 1, '', '' );
$expNsResource = new ExpNsResource( 'Foo', 'Bar', '', $dataItem );
$exists = null;
$this->assertSame(
$expNsResource,
$instance->findRedirectTargetResource( $expNsResource, $exists )
);
$this->assertTrue( $exists );
}
public function testRedirectTragetForDBLookupWithMultipleEntries() {
$expLiteral = new ExpLiteral( 'Redirect' );
$repositoryConnection = $this->createRepositoryConnectionMockToUse( array( $expLiteral, null ) );
$instance = new RedirectLookup( $repositoryConnection );
$instance->reset();
$dataItem = new DIWikiPage( 'Foo', 1, '', '' );
$expNsResource = new ExpNsResource( 'Foo', 'Bar', '', $dataItem );
$exists = null;
$this->assertSame(
$expNsResource,
$instance->findRedirectTargetResource( $expNsResource, $exists )
);
$this->assertTrue( $exists );
}
public function testRedirectTragetForDBLookupWithMultipleEntriesForcesNewResource() {
$propertyPage = new DIWikiPage( 'Foo', SMW_NS_PROPERTY );
$resource = new ExpNsResource(
'Foo',
Exporter::getInstance()->getNamespaceUri( 'property' ),
'property',
$propertyPage
);
$repositoryConnection = $this->createRepositoryConnectionMockToUse( array( $resource, $resource ) );
$instance = new RedirectLookup( $repositoryConnection );
$instance->reset();
$dataItem = new DIWikiPage( 'Foo', 1, '', '' );
$expNsResource = new ExpNsResource( 'Foo', 'Bar', '', $dataItem );
$exists = null;
$targetResource = $instance->findRedirectTargetResource( $expNsResource, $exists );
$this->assertNotSame(
$expNsResource,
$targetResource
);
$expectedResource = new ExpNsResource(
Escaper::encodePage( $propertyPage ),
Exporter::getInstance()->getNamespaceUri( 'wiki' ),
'wiki'
);
$this->assertEquals(
$expectedResource,
$targetResource
);
$this->assertTrue( $exists );
}
public function testRedirectTragetForDBLookupWithForNonMultipleResourceEntryThrowsException() {
$expLiteral = new ExpLiteral( 'Redirect' );
$repositoryConnection = $this->createRepositoryConnectionMockToUse( array( $expLiteral, $expLiteral ) );
$instance = new RedirectLookup( $repositoryConnection );
$instance->reset();
$dataItem = new DIWikiPage( 'Foo', 1, '', '' );
$expNsResource = new ExpNsResource( 'Foo', 'Bar', '', $dataItem );
$exists = null;
$this->setExpectedException( 'RuntimeException' );
$instance->findRedirectTargetResource( $expNsResource, $exists );
}
public function testRedirectTargetForCachedLookup() {
$dataItem = new DIWikiPage( 'Foo', NS_MAIN );
$expNsResource = new ExpNsResource( 'Foo', 'Bar', '', $dataItem );
$poolCache = InMemoryPoolCache::getInstance()->getPoolCacheFor( 'sparql.store.redirectlookup' );
$poolCache->save(
$expNsResource->getUri(),
$expNsResource
);
$repositoryConnection = $this->getMockBuilder( '\SMW\SPARQLStore\RepositoryConnection' )
->disableOriginalConstructor()
->getMock();
$instance = new RedirectLookup( $repositoryConnection );
$exists = null;
$instance->findRedirectTargetResource( $expNsResource, $exists );
$this->assertTrue( $exists );
$instance->reset();
}
/**
* @dataProvider nonRedirectableResourceProvider
*/
public function testRedirectTargetForNonRedirectableResource( $expNsResource ) {
$repositoryConnection = $this->getMockBuilder( '\SMW\SPARQLStore\RepositoryConnection' )
->disableOriginalConstructor()
->getMock();
$instance = new RedirectLookup( $repositoryConnection );
$instance->reset();
$exists = null;
$instance->findRedirectTargetResource( $expNsResource, $exists );
$instance->reset();
$this->assertFalse( $exists );
}
private function createRepositoryConnectionMockToUse( $listReturnValue ) {
$repositoryResult = $this->getMockBuilder( '\SMW\SPARQLStore\QueryEngine\RepositoryResult' )
->disableOriginalConstructor()
->getMock();
$repositoryResult->expects( $this->once() )
->method( 'current' )
->will( $this->returnValue( $listReturnValue ) );
$repositoryConnection = $this->getMockBuilder( '\SMW\SPARQLStore\RepositoryConnection' )
->disableOriginalConstructor()
->getMock();
$repositoryConnection->expects( $this->once() )
->method( 'select' )
->will( $this->returnValue( $repositoryResult ) );
return $repositoryConnection;
}
public function nonRedirectableResourceProvider() {
$provider[] = array(
Exporter::getInstance()->getSpecialPropertyResource( '_INST' )
);
$provider[] = array(
Exporter::getInstance()->getSpecialPropertyResource( '_SUBC' )
);
$provider[] = array(
Exporter::getInstance()->getSpecialPropertyResource( '_REDI' )
);
$provider[] = array(
Exporter::getInstance()->getSpecialPropertyResource( '_MDAT' )
);
$provider[] = array(
Exporter::getInstance()->getSpecialPropertyResource( '_MDAT', true )
);
return $provider;
}
}
| mit |
jbowtie/gokogiri | xpath/xpath_test.go | 609 | package xpath
//please check the search tests in gokogiri/xml and gokogiri/html
import "testing"
func TestCompileGoodExpr(t *testing.T) {
defer CheckXmlMemoryLeaks(t)
e := Compile(`./*`)
if e == nil {
t.Error("expr should be good")
}
e.Free()
}
func TestCompileBadExpr(t *testing.T) {
//defer CheckXmlMemoryLeaks(t)
//this test causes memory leaks in libxml
//however, the memory leak is very small and does not grow as more bad expressions are compiled
e := Compile("./")
if e != nil {
t.Error("expr should be bad")
}
e = Compile(".//")
if e != nil {
t.Error("expr should be bad")
}
}
| mit |
druid628/Sismo | src/console.php | 9948 | <?php
/*
* This file is part of the Sismo utility.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
use Sismo\Sismo;
use Sismo\BuildException;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Process\ProcessBuilder;
$console = new Application('Sismo', Sismo::VERSION);
$console
->register('output')
->setDefinition(array(
new InputArgument('slug', InputArgument::REQUIRED, 'Project slug'),
))
->setDescription('Displays the latest output for a project')
->setHelp(<<<EOF
The <info>%command.name%</info> command displays the latest output for a project:
<info>php %command.full_name% twig</info>
EOF
)
->setCode(function (InputInterface $input, OutputInterface $output) use ($app) {
$sismo = $app['sismo'];
$slug = $input->getArgument('slug');
if (!$sismo->hasProject($slug)) {
$output->writeln(sprintf('<error>Project "%s" does not exist.</error>', $slug));
return 1;
}
$project = $sismo->getProject($slug);
if (!$project->getLatestCommit()) {
$output->writeln(sprintf('<error>Project "%s" has never been built yet.</error>', $slug));
return 2;
}
$output->write($project->getLatestCommit()->getOutput());
$now = new \DateTime();
$diff = $now->diff($project->getLatestCommit()->getBuildDate());
if ($m = $diff->format('%i')) {
$time = $m.' minutes';
} else {
$time = $diff->format('%s').' seconds';
}
$output->writeln('');
$output->writeln(sprintf('<info>This output was generated by Sismo %s ago</info>', $time));
})
;
$console
->register('projects')
->setDescription('List available projects')
->setHelp(<<<EOF
The <info>%command.name%</info> command displays the available projects Sismo can build.
EOF
)
->setCode(function (InputInterface $input, OutputInterface $output) use ($app) {
$sismo = $app['sismo'];
$projects = array();
$width = 0;
foreach ($sismo->getProjects() as $slug => $project) {
$projects[$slug] = $project->getName();
$width = strlen($project->getName()) > $width ? strlen($project->getName()) : $width;
}
$width += 2;
$output->writeln('');
$output->writeln('<comment>Available projects:</comment>');
foreach ($projects as $slug => $project) {
$output->writeln(sprintf(" <info>%-${width}s</info> %s", $slug, $project));
}
$output->writeln('');
})
;
$console
->register('build')
->setDefinition(array(
new InputArgument('slug', InputArgument::OPTIONAL, 'Project slug'),
new InputArgument('sha', InputArgument::OPTIONAL, 'Commit sha'),
new InputOption('force', '', InputOption::VALUE_NONE, 'Force the build'),
new InputOption('local', '', InputOption::VALUE_NONE, 'Disable remote sync'),
new InputOption('silent', '', InputOption::VALUE_NONE, 'Disable notifications'),
new InputOption('timeout', '', InputOption::VALUE_REQUIRED, 'Time limit'),
new InputOption('data-path', '', InputOption::VALUE_REQUIRED, 'The data path'),
new InputOption('config-file', '', InputOption::VALUE_REQUIRED, 'The config file'),
))
->setDescription('Build projects')
->setHelp(<<<EOF
Without any arguments, the <info>%command.name%</info> command builds the latest commit
of all configured projects one after the other:
<info>php %command.full_name%</info>
The command loads project configurations from
<comment>~/.sismo/config.php</comment>. Change it with the
<info>--config-file</info> option:
<info>php %command.full_name% --config-file=/path/to/config.php</info>
Data (repository, DB, ...) are stored in <comment>~/.sismo/data/</comment>.
The <info>--data-path</info> option allows you to change the default:
<info>php %command.full_name% --data-path=/path/to/data</info>
Pass the project slug to build a specific project:
<info>php %command.full_name% twig</info>
Force a specific commit to be built by passing the SHA:
<info>php %command.full_name% twig a1ef34</info>
Use <comment>--force</comment> to force the built even if it has already been
built previously:
<info>php %command.full_name% twig a1ef34 --force</info>
Disable notifications with <comment>--silent</comment>:
<info>php %command.full_name% twig a1ef34 --silent</info>
Disable repository synchonization with <comment>--local</comment>:
<info>php %command.full_name% twig a1ef34 --local</info>
Limit the time (in seconds) spent by the command building projects by using
the <comment>--timeout</comment> option:
<info>php %command.full_name% twig --timeout 3600</info>
When you use this command as a cron job, <comment>--timeout</comment> can avoid
the command to be run concurrently. Be warned that this is a rough estimate as
the time is only checked between two builds. When a build is started, it won't
be stopped if the time limit is over.
Use the <comment>--verbose</comment> option to debug builds in case of a
problem.
EOF
)
->setCode(function (InputInterface $input, OutputInterface $output) use ($app) {
if ($input->getOption('data-path')) {
$app['data.path'] = $input->getOption('data-path');
}
if ($input->getOption('config-file')) {
$app['config.file'] = $input->getOption('config-file');
}
$sismo = $app['sismo'];
if ($slug = $input->getArgument('slug')) {
if (!$sismo->hasProject($slug)) {
$output->writeln(sprintf('<error>Project "%s" does not exist.</error>', $slug));
return 1;
}
$projects = array($sismo->getProject($slug));
} else {
$projects = $sismo->getProjects();
}
$start = time();
$startedOut = false;
$startedErr = false;
$callback = null;
if (OutputInterface::VERBOSITY_VERBOSE === $output->getVerbosity()) {
$callback = function ($type, $buffer) use ($output, &$startedOut, &$startedErr) {
if ('err' === $type) {
if (!$startedErr) {
$output->write("\n<bg=red;fg=white> ERR </> ");
$startedErr = true;
$startedOut = false;
}
$output->write(str_replace("\n", "\n<bg=red;fg=white> ERR </> ", $buffer));
} else {
if (!$startedOut) {
$output->write("\n<bg=green;fg=white> OUT </> ");
$startedOut = true;
$startedErr = false;
}
$output->write(str_replace("\n", "\n<bg=green;fg=white> OUT </> ", $buffer));
}
};
}
$flags = 0;
if ($input->getOption('force')) {
$flags = $flags | Sismo::FORCE_BUILD;
}
if ($input->getOption('local')) {
$flags = $flags | Sismo::LOCAL_BUILD;
}
if ($input->getOption('silent')) {
$flags = $flags | Sismo::SILENT_BUILD;
}
$returnValue = 0;
foreach ($projects as $project) {
// out of time?
if ($input->getOption('timeout') && time() - $start > $input->getOption('timeout')) {
break;
}
try {
$output->writeln(sprintf('<info>Building Project "%s" (into "%s")</info>', $project, $app['builder']->getBuildDir($project)));
$sismo->build($project, $input->getArgument('sha'), $flags, $callback);
$output->writeln('');
} catch (BuildException $e) {
$output->writeln("\n".sprintf('<error>%s</error>', $e->getMessage()));
$returnValue = 1;
}
}
return $returnValue;
})
;
$console
->register('run')
->setDefinition(array(
new InputArgument('address', InputArgument::OPTIONAL, 'Address:port', 'localhost:9000'),
))
->setDescription('Runs Sismo with PHP built-in web server')
->setHelp(<<<EOF
The <info>%command.name%</info> command runs the embedded Sismo web server:
<info>%command.full_name%</info>
You can also customize the default address and port the web server listens to:
<info>%command.full_name% 127.0.0.1:8080</info>
EOF
)
->setCode(function (InputInterface $input, OutputInterface $output) use ($console) {
if (version_compare(PHP_VERSION, '5.4.0') < 0) {
throw new \Exception('This feature only runs with PHP 5.4.0 or higher.');
}
$sismo = __DIR__.'/sismo.php';
while (!file_exists($sismo)) {
$dialog = $console->getHelperSet()->get('dialog');
$sismo = $dialog->ask($output, sprintf('<comment>I cannot find "%s". What\'s the absoulte path of "sismo.php"?</comment> ', $sismo), __DIR__.'/sismo.php');
}
$output->writeln(sprintf("Sismo running on <info>%s</info>\n", $input->getArgument('address')));
$builder = new ProcessBuilder(array(PHP_BINARY, '-S', $input->getArgument('address'), $sismo));
$builder->setWorkingDirectory(getcwd());
$builder->setTimeout(null);
$builder->getProcess()->run(function ($type, $buffer) use ($output) {
if (OutputInterface::VERBOSITY_VERBOSE === $output->getVerbosity()) {
$output->write($buffer);
}
});
})
;
return $console;
| mit |
openilabs/crypto | node_modules/node-forge/nodejs/node_modules/grunt-mocha/HISTORY.md | 2393 | # History
## 0.3.4
* `grunt.warn` instead of `grunt.log.warn` on failures with bail false, correct exit code. (#71)
## 0.3.3
* Add `log` option to output `console.log`. False by default.
* Update Readme to reflect Grunt 0.4 changes (finally)
## 0.3.2
* Add `bail` option (false by default)
* Do not bail on error by default
## 0.3.1
* Update `grunt-lib-phantomjs` to 0.3.0
## 0.3.0
* You may now specify which reporter you want to use (thanks SBoudrias)
* Growl only shows notices on failures
```js
sampleTest: {
src: ['test.js'],
options: {
reporter: 'Nyan'
mocha: {
ui: 'tdd'
}
}
}
```
## 0.2.2
* Updating grunt/gruntplugin dependencies to rc6.
* Added travis.yml
* Added .jshintrc and jshint to Gruntfile.js
* Migrated documentation and Gruntfile.js to grunt-contrib standards
## 0.2.0
* **Grunt >=0.4.0 only, MIGRATION REQUIRED if updating from 0.1.x**
* Uses grunt-lib-phantomjs for easy PhantomJS installation!
* If things are not working right, try removing and installing via npm again.
* Config changes required
* `tasks/mocha/mocha-helper.js` has been moved to `phantomjs/bridge.js`, if you are including it manually, you must change the path/filename
* Task options are now nested in the `options` key per task/target
```js
all: {
src: ['test.js'],
options: {
mocha: {
ui: 'tdd'
},
run: true
}
}
```
## 0.1.7
* Fix bad legacy mocha check for mocha < 1.4.2 (rohni)
## 0.1.6
* Add ability to pass mocha config options (grep, etc) via grunt task config. (gamtiq)
* Add option to not include `mocha-spec-helper.js` and auto-inject/run with the `run` config option. Note: Still not required for AMD. This requires an if-statement in your HTML spec to check for PhantomJS environment, it's either that or include the helper. See `example/test2.html`. (gamtiq)
## 0.1.5
* Fix total duration when testing multiple html spec files in a single task. (chevalric)
## 0.1.4
* **Critical fix:** Compatibility with Mocha 1.4.2 (iammerick)
* If you use `mocha-helper.js` for non-AMD and you want to use Mocha >1.4.2, you replace it with the one in this update.
## 0.1.3
* Remove grunt from deps
## 0.1.2
* Added example for non-AMD usage. Modified mocha-helper to be included in page (optional)
* Added duration
## 0.1.1
* Consistency
* Make growl optional
## 0.1.0
init
| mit |
djsedulous/namecoind | libs/boost_1_50_0/libs/icl/doc/html/boost/icl/inplace_erase.html | 7027 | <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Struct template inplace_erase</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.74.0">
<link rel="home" href="../../index.html" title="Chapter 1. Boost.Icl">
<link rel="up" href="../../header/boost/icl/functors_hpp.html" title="Header <boost/icl/functors.hpp>">
<link rel="prev" href="inplace_insert.html" title="Struct template inplace_insert">
<link rel="next" href="inplace_star.html" title="Struct template inplace_star">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="inplace_insert.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../header/boost/icl/functors_hpp.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="inplace_star.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry" lang="en">
<a name="boost.icl.inplace_erase"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Struct template inplace_erase</span></h2>
<p>boost::icl::inplace_erase</p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../header/boost/icl/functors_hpp.html" title="Header <boost/icl/functors.hpp>">boost/icl/functors.hpp</a>>
</span><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Type<span class="special">></span>
<span class="keyword">struct</span> <a class="link" href="inplace_erase.html" title="Struct template inplace_erase">inplace_erase</a> <span class="special">:</span>
<span class="keyword">public</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">icl</span><span class="special">::</span><span class="identifier">identity_based_inplace_combine</span><span class="special"><</span> <span class="identifier">Type</span> <span class="special">></span>
<span class="special">{</span>
<span class="comment">// types</span>
<span class="keyword">typedef</span> <a class="link" href="inplace_erase.html" title="Struct template inplace_erase">inplace_erase</a><span class="special"><</span> <span class="identifier">Type</span> <span class="special">></span> <a name="boost.icl.inplace_erase.type"></a><span class="identifier">type</span><span class="special">;</span>
<span class="comment">// <a class="link" href="inplace_erase.html#id647077-bb">public member functions</a></span>
<span class="keyword">void</span> <a class="link" href="inplace_erase.html#id647079-bb"><span class="keyword">operator</span><span class="special">(</span><span class="special">)</span></a><span class="special">(</span><span class="identifier">Type</span> <span class="special">&</span><span class="special">,</span> <span class="keyword">const</span> <span class="identifier">Type</span> <span class="special">&</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="comment">// <a class="link" href="inplace_erase.html#id647095-bb">public static functions</a></span>
<span class="keyword">static</span> <span class="identifier">Type</span> <a class="link" href="inplace_erase.html#id647097-bb"><span class="identifier">identity_element</span></a><span class="special">(</span><span class="special">)</span><span class="special">;</span>
<span class="special">}</span><span class="special">;</span></pre></div>
<div class="refsect1" lang="en">
<a name="id1214462"></a><h2>Description</h2>
<div class="refsect2" lang="en">
<a name="id1214466"></a><h3>
<a name="id647077-bb"></a><code class="computeroutput">inplace_erase</code> public member functions</h3>
<div class="orderedlist"><ol type="1"><li><pre class="literallayout"><span class="keyword">void</span> <a name="id647079-bb"></a><span class="keyword">operator</span><span class="special">(</span><span class="special">)</span><span class="special">(</span><span class="identifier">Type</span> <span class="special">&</span> object<span class="special">,</span> <span class="keyword">const</span> <span class="identifier">Type</span> <span class="special">&</span> operand<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre></li></ol></div>
</div>
<div class="refsect2" lang="en">
<a name="id1214547"></a><h3>
<a name="id647095-bb"></a><code class="computeroutput">inplace_erase</code> public static functions</h3>
<div class="orderedlist"><ol type="1"><li><pre class="literallayout"><span class="keyword">static</span> <span class="identifier">Type</span> <a name="id647097-bb"></a><span class="identifier">identity_element</span><span class="special">(</span><span class="special">)</span><span class="special">;</span></pre></li></ol></div>
</div>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2007 -2010 Joachim Faulhaber<br>Copyright © 1999 -2006 Cortex Software GmbH<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="inplace_insert.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../header/boost/icl/functors_hpp.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="inplace_star.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| mit |
fungxu/ws2812esp8266 | user/mystuff.h | 198 | #ifndef _MYSTUFF_H
#define _MYSTUFF_H
extern char generic_print_buffer[384];
#define printf( ... ) os_sprintf( generic_print_buffer, __VA_ARGS__ ); uart0_sendStr( generic_print_buffer );
#endif
| mit |
tianxiawuzhei/cocos-quick-cpp | publibs/cocos2dx/cocos/scripting/lua-bindings/manual/ui/lua_cocos2dx_experimental_video_manual.cpp | 2501 | #include "scripting/lua-bindings/manual/ui/lua_cocos2dx_experimental_video_manual.hpp"
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
#include "ui/UIVideoPlayer.h"
#include "scripting/lua-bindings/manual/tolua_fix.h"
#include "scripting/lua-bindings/manual/LuaBasicConversions.h"
#include "scripting/lua-bindings/manual/CCLuaValue.h"
#include "scripting/lua-bindings/manual/CCLuaEngine.h"
static int lua_cocos2dx_experimental_video_VideoPlayer_addEventListener(lua_State* L)
{
int argc = 0;
cocos2d::experimental::ui::VideoPlayer* self = nullptr;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
if (!tolua_isusertype(L,1,"ccexp.VideoPlayer",0,&tolua_err)) goto tolua_lerror;
#endif
self = static_cast<cocos2d::experimental::ui::VideoPlayer*>(tolua_tousertype(L,1,0));
#if COCOS2D_DEBUG >= 1
if (nullptr == self) {
tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_Widget_addTouchEventListener'\n", nullptr);
return 0;
}
#endif
argc = lua_gettop(L) - 1;
if (argc == 1)
{
#if COCOS2D_DEBUG >= 1
if (!toluafix_isfunction(L,2,"LUA_FUNCTION",0,&tolua_err))
{
goto tolua_lerror;
}
#endif
LUA_FUNCTION handler = ( toluafix_ref_function(L,2,0));
self->addEventListener([=](cocos2d::Ref* ref, cocos2d::experimental::ui::VideoPlayer::EventType eventType){
LuaStack* stack = LuaEngine::getInstance()->getLuaStack();
stack->pushObject(ref, "cc.Ref");
stack->pushInt((int)eventType);
stack->executeFunctionByHandler(handler, 2);
});
return 0;
}
luaL_error(L, "%s has wrong number of arguments: %d, was expecting %d\n ", "ccexp.VideoPlayer:addEventListener",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(L, "#ferror in function 'lua_cocos2dx_experimental_VideoPlayer_addEventListener'.", &tolua_err);
#endif
return 0;
}
static void extendVideoPlayer(lua_State* L)
{
lua_pushstring(L, "ccexp.VideoPlayer");
lua_rawget(L, LUA_REGISTRYINDEX);
if (lua_istable(L,-1))
{
tolua_function(L, "addEventListener", lua_cocos2dx_experimental_video_VideoPlayer_addEventListener);
}
lua_pop(L, 1);
}
int register_all_cocos2dx_experimental_video_manual(lua_State* L)
{
if (nullptr == L)
return 0;
extendVideoPlayer(L);
return 0;
}
#endif
| mit |
natematias/Our-Things | vendor/gems/mocha-0.9.12/test/unit/metaclass_test.rb | 629 | require File.expand_path('../../test_helper', __FILE__)
require 'mocha/metaclass'
class MetaclassTest < Test::Unit::TestCase
def test_should_return_objects_singleton_class
object = Object.new
assert_raises(NoMethodError) { object.success? }
object = Object.new
assert object.__metaclass__.ancestors.include?(Object)
assert object.__metaclass__.ancestors.include?(Kernel)
assert object.__metaclass__.is_a?(Class)
object.__metaclass__.class_eval { def success?; true; end }
assert object.success?
object = Object.new
assert_raises(NoMethodError) { object.success? }
end
end | mit |
LothusMarque/Furnarchy | furnarchy2/furnarchyskin/gm/gmDebug.cpp | 22124 | /*
_____ __ ___ __ ____ _ __
/ ___/__ ___ _ ___ / |/ /__ ___ / /_____ __ __/ __/_______(_)__ / /_
/ (_ / _ `/ ' \/ -_) /|_/ / _ \/ _ \/ '_/ -_) // /\ \/ __/ __/ / _ \/ __/
\___/\_,_/_/_/_/\__/_/ /_/\___/_//_/_/\_\\__/\_, /___/\__/_/ /_/ .__/\__/
/___/ /_/
See Copyright Notice in gmMachine.h
*/
#include "gmDebug.h"
#include "gmConfig.h"
#include "gmMachine.h"
#include "gmThread.h"
#if GMDEBUG_SUPPORT
#define ID_mrun GM_MAKE_ID32('m','r','u','n')
#define ID_msin GM_MAKE_ID32('m','s','i','n')
#define ID_msou GM_MAKE_ID32('m','s','o','u')
#define ID_msov GM_MAKE_ID32('m','s','o','v')
#define ID_mgct GM_MAKE_ID32('m','g','c','t')
#define ID_mgsr GM_MAKE_ID32('m','g','s','r')
#define ID_mgsi GM_MAKE_ID32('m','g','s','i')
#define ID_mgti GM_MAKE_ID32('m','g','t','i')
#define ID_mgvi GM_MAKE_ID32('m','g','v','i')
#define ID_msbp GM_MAKE_ID32('m','s','b','p')
#define ID_mbrk GM_MAKE_ID32('m','b','r','k')
#define ID_mend GM_MAKE_ID32('m','e','n','d')
#define ID_dbrk GM_MAKE_ID32('d','b','r','k')
#define ID_dexc GM_MAKE_ID32('d','e','x','c')
#define ID_drun GM_MAKE_ID32('d','r','u','n')
#define ID_dstp GM_MAKE_ID32('d','s','t','p')
#define ID_dsrc GM_MAKE_ID32('d','s','r','c')
#define ID_dctx GM_MAKE_ID32('d','c','t','x')
#define ID_call GM_MAKE_ID32('c','a','l','l')
#define ID_vari GM_MAKE_ID32('v','a','r','i')
#define ID_done GM_MAKE_ID32('d','o','n','e')
#define ID_dsri GM_MAKE_ID32('d','s','r','i')
#define ID_srci GM_MAKE_ID32('s','r','c','i')
#define ID_done GM_MAKE_ID32('d','o','n','e')
#define ID_dthi GM_MAKE_ID32('d','t','h','i')
#define ID_thri GM_MAKE_ID32('t','h','r','i')
#define ID_done GM_MAKE_ID32('d','o','n','e')
#define ID_derr GM_MAKE_ID32('d','e','r','r')
#define ID_dmsg GM_MAKE_ID32('d','m','s','g')
#define ID_dack GM_MAKE_ID32('d','a','c','k')
#define ID_dend GM_MAKE_ID32('d','e','n','d')
//
// functions to handle incomming commands from a debugger
//
void gmMachineRun(gmDebugSession * a_session, int a_threadId);
void gmMachineStepInto(gmDebugSession * a_session, int a_threadId);
void gmMachineStepOver(gmDebugSession * a_session, int a_threadId);
void gmMachineStepOut(gmDebugSession * a_session, int a_threadId);
void gmMachineGetContext(gmDebugSession * a_session, int a_threadId, int a_callframe);
void gmMachineGetSource(gmDebugSession * a_session, int a_sourceId);
void gmMachineGetSourceInfo(gmDebugSession * a_session);
void gmMachineGetThreadInfo(gmDebugSession * a_session);
void gmMachineGetVariableInfo(gmDebugSession * a_session, int a_variableId);
void gmMachineSetBreakPoint(gmDebugSession * a_session, int a_responseId, int a_sourceId, int a_lineNumber, int a_threadId, int a_enabled);
void gmMachineBreak(gmDebugSession * a_session, int a_threadId);
void gmMachineQuit(gmDebugSession * a_session);
//
// functions to package outgoing messages to a debugger
//
void gmDebuggerBreak(gmDebugSession * a_session, int a_threadId, int a_sourceId, int a_lineNumber);
void gmDebuggerRun(gmDebugSession * a_session, int a_threadId);
void gmDebuggerStop(gmDebugSession * a_session, int a_threadId);
void gmDebuggerSource(gmDebugSession * a_session, int a_sourceId, const char * a_sourceName, const char * a_source);
void gmDebuggerException(gmDebugSession * a_session, int a_threadId);
void gmDebuggerBeginContext(gmDebugSession * a_session, int a_threadId, int a_callFrame);
void gmDebuggerContextCallFrame(gmDebugSession * a_session, int a_callFrame, const char * a_functionName, int a_sourceId, int a_lineNumber, const char * a_thisSymbol, const char * a_thisValue, int a_thisId);
void gmDebuggerContextVariable(gmDebugSession * a_session, const char * a_varSymbol, const char * a_varValue, int a_varId);
void gmDebuggerEndContext(gmDebugSession * a_session);
void gmDebuggerBeginSourceInfo(gmDebugSession * a_session);
void gmDebuggerSourceInfo(gmDebugSession * a_session, int a_sourceId, const char * a_sourceName);
void gmDebuggerEndSourceInfo(gmDebugSession * a_session);
void gmDebuggerBeginThreadInfo(gmDebugSession * a_session);
void gmDebuggerThreadInfo(gmDebugSession * a_session, int a_threadId, int a_threadState);
void gmDebuggerEndThreadInfo(gmDebugSession * a_session);
void gmDebuggerError(gmDebugSession * a_session, const char * a_error);
void gmDebuggerMessage(gmDebugSession * a_session, const char * a_message);
void gmDebuggerAck(gmDebugSession * a_session, int a_response, int a_posNeg);
void gmDebuggerQuit(gmDebugSession * a_session);
//
// debug machine callback
//
enum gmdThreadFlags
{
TF_STEPOVER = (1 << 0),
TF_STEPINTO = (1 << 1),
TF_STEPOUT = (1 << 2),
TF_BREAK = (1 << 3),
};
// the following callbacks return true if the thread is to yield after completion of the callback.
static bool LineCallback(gmThread * a_thread)
{
gmDebugSession * session = (gmDebugSession *) a_thread->GetMachine()->m_debugUser;
GM_ASSERT(session);
if(!(a_thread->m_debugFlags & TF_STEPOVER) ||
(a_thread->m_debugUser != ((a_thread->GetFrame()) ? a_thread->GetFrame()->m_returnBase : 0)))
{
int * bp = session->FindBreakPoint((void *) a_thread->GetInstruction());
if(bp == NULL)
return false;
if(*bp && *bp != a_thread->GetId())
return false;
}
a_thread->m_debugFlags = TF_BREAK;
const gmFunctionObject * fn = a_thread->GetFunctionObject();
gmDebuggerBreak(session, a_thread->GetId(), fn->GetSourceId(), fn->GetLine(a_thread->GetInstruction()));
return true;
}
static bool CallCallback(gmThread * a_thread)
{
gmDebugSession * session = (gmDebugSession *) a_thread->GetMachine()->m_debugUser;
GM_ASSERT(session);
if(a_thread->m_debugFlags & TF_STEPINTO)
{
a_thread->m_debugFlags = TF_BREAK;
const gmFunctionObject * fn = a_thread->GetFunctionObject();
gmDebuggerBreak(session, a_thread->GetId(), fn->GetSourceId(), fn->GetLine(a_thread->GetInstruction()));
return true;
}
return false;
}
static bool RetCallback(gmThread * a_thread)
{
gmDebugSession * session = (gmDebugSession *) a_thread->GetMachine()->m_debugUser;
GM_ASSERT(session);
if(((a_thread->m_debugFlags & TF_STEPOUT) && (a_thread->m_debugUser == a_thread->GetIntBase())) ||
((a_thread->m_debugFlags & TF_STEPOVER) && (a_thread->m_debugUser == a_thread->GetIntBase())))
{
a_thread->m_debugFlags = TF_BREAK;
const gmFunctionObject * fn = a_thread->GetFunctionObject();
gmDebuggerBreak(session, a_thread->GetId(), fn->GetSourceId(), fn->GetLine(a_thread->GetInstruction()));
return true;
}
return false;
}
static bool IsBrokenCallback(gmThread * a_thread)
{
return (a_thread->m_debugFlags & TF_BREAK) > 0;
}
static gmMachineCallback s_prevMachineCallback = NULL;
bool GM_CDECL gmdMachineCallback(gmMachine * a_machine, gmMachineCommand a_command, const void * a_context)
{
gmDebugSession * session = (gmDebugSession *) a_machine->m_debugUser;
const gmThread * thread = (const gmThread *) a_context;
// chain callback
if(s_prevMachineCallback) s_prevMachineCallback(a_machine, a_command, a_context);
// do we have a debug session?
if(session == NULL) return false;
// command
switch(a_command)
{
case MC_THREAD_EXCEPTION :
{
// send thread exception message
gmDebuggerException(session, thread->GetId());
a_machine->GetLog();
bool first = true;
const char * entry;
while((entry = a_machine->GetLog().GetEntry(first)))
{
gmDebuggerError(session, entry);
}
return true;
}
case MC_THREAD_CREATE :
{
gmDebuggerRun(session, thread->GetId());
break;
}
case MC_THREAD_DESTROY :
{
gmDebuggerStop(session, thread->GetId());
break;
}
default : break;
};
return false;
}
//
// debug session
//
gmDebugSession::gmDebugSession() :
m_breaks(32)
{
m_machine = NULL;
}
gmDebugSession::~gmDebugSession()
{
m_breaks.RemoveAndDeleteAll();
}
void gmDebugSession::Update()
{
for(;;)
{
int len;
const void * msg = m_pumpMessage(this, len);
if(msg == NULL)
break;
m_in.Open(msg, len);
// parse the message
int id, pa, pb, pc, pd;
Unpack(id);
switch(id)
{
case ID_mrun :
Unpack(id);
gmMachineRun(this, id);
break;
case ID_msin :
Unpack(id);
gmMachineStepInto(this, id);
break;
case ID_msou :
Unpack(id);
gmMachineStepOut(this, id);
break;
case ID_msov :
Unpack(id);
gmMachineStepOver(this, id);
break;
case ID_mgct :
Unpack(id).Unpack(pa);
gmMachineGetContext(this, id, pa);
break;
case ID_mgsr :
Unpack(id);
gmMachineGetSource(this, id);
break;
case ID_mgsi :
gmMachineGetSourceInfo(this);
break;
case ID_mgti :
gmMachineGetThreadInfo(this);
break;
case ID_mgvi :
Unpack(id);
gmMachineGetVariableInfo(this, id);
break;
case ID_msbp :
Unpack(pa).Unpack(pb).Unpack(pc).Unpack(id).Unpack(pd);
gmMachineSetBreakPoint(this, pa, pb, pc, id, pd);
break;
case ID_mbrk :
Unpack(id);
gmMachineBreak(this, id);
break;
case ID_mend :
gmMachineQuit(this);
break;
default:;
}
}
}
bool gmDebugSession::Open(gmMachine * a_machine)
{
Close();
m_machine = a_machine;
m_machine->m_debugUser = this;
m_machine->m_line = LineCallback;
m_machine->m_call = CallCallback;
m_machine->m_isBroken = IsBrokenCallback;
m_machine->m_return = RetCallback;
s_prevMachineCallback = a_machine->s_machineCallback;
a_machine->s_machineCallback = gmdMachineCallback;
return true;
}
static bool threadIterClose(gmThread * a_thread, void * a_context)
{
a_thread->m_debugFlags = 0;
a_thread->m_debugUser = 0;
return true;
}
bool gmDebugSession::Close()
{
if(m_machine && m_machine->m_debugUser == this)
{
gmDebuggerQuit(this);
m_machine->m_debugUser = NULL;
m_machine->s_machineCallback = s_prevMachineCallback;
m_machine->m_line = NULL;
m_machine->m_call = NULL;
m_machine->m_return = NULL;
m_machine->m_isBroken = NULL;
m_machine->KillExceptionThreads();
m_machine->ForEachThread(threadIterClose, NULL);
m_machine = NULL;
m_breaks.RemoveAndDeleteAll();
m_out.ResetAndFreeMemory();
return true;
}
m_breaks.RemoveAndDeleteAll();
m_out.ResetAndFreeMemory();
return false;
}
gmDebugSession &gmDebugSession::Pack(int a_val)
{
m_out << a_val;
return *this;
}
gmDebugSession &gmDebugSession::Pack(const char * a_val)
{
if(a_val)
m_out.Write(a_val, strlen(a_val) + 1);
else
m_out.Write("", 1);
return *this;
}
void gmDebugSession::Send()
{
m_sendMessage(this, m_out.GetData(), m_out.GetSize());
m_out.Reset();
}
gmDebugSession &gmDebugSession::Unpack(int &a_val)
{
if(m_in.Read(&a_val, 4) != 4) a_val = 0;
return *this;
}
gmDebugSession &gmDebugSession::Unpack(const char * &a_val)
{
// this is dangerous!!!
a_val = &m_in.GetData()[m_in.Tell()];
int len = strlen(a_val);
m_in.Seek(m_in.Tell() + len + 1);
return *this;
}
bool gmDebugSession::AddBreakPoint(const void * a_bp, int a_threadId)
{
BreakPoint * bp = m_breaks.Find((void *const&)a_bp);
if(bp) return false;
bp = GM_NEW( BreakPoint() );
bp->m_bp = a_bp;
bp->m_threadId = a_threadId;
m_breaks.Insert(bp);
return true;
}
int * gmDebugSession::FindBreakPoint(const void * a_bp)
{
BreakPoint * bp = m_breaks.Find((void *const&)a_bp);
if(bp)
{
return &bp->m_threadId;
}
return NULL;
}
bool gmDebugSession::RemoveBreakPoint(const void * a_bp)
{
BreakPoint * bp = m_breaks.Find((void *const&)a_bp);
if(bp)
{
m_breaks.Remove(bp);
delete bp;
return true;
}
return false;
}
//
// implementation
//
void gmMachineRun(gmDebugSession * a_session, int a_threadId)
{
gmThread * thread = a_session->GetMachine()->GetThread(a_threadId);
if(thread)
{
thread->m_debugFlags = 0;
}
}
void gmMachineStepInto(gmDebugSession * a_session, int a_threadId)
{
gmThread * thread = a_session->GetMachine()->GetThread(a_threadId);
if(thread)
{
thread->m_debugUser = (thread->GetFrame()) ? thread->GetFrame()->m_returnBase : 0;
thread->m_debugFlags = TF_STEPINTO | TF_STEPOVER;
}
}
void gmMachineStepOver(gmDebugSession * a_session, int a_threadId)
{
gmThread * thread = a_session->GetMachine()->GetThread(a_threadId);
if(thread)
{
thread->m_debugUser = (thread->GetFrame()) ? thread->GetFrame()->m_returnBase : 0;
thread->m_debugFlags = TF_STEPOVER;
}
}
void gmMachineStepOut(gmDebugSession * a_session, int a_threadId)
{
gmThread * thread = a_session->GetMachine()->GetThread(a_threadId);
if(thread)
{
thread->m_debugUser = (thread->GetFrame()) ? thread->GetFrame()->m_returnBase : 0;
thread->m_debugFlags = TF_STEPOUT;
}
}
void gmMachineGetContext(gmDebugSession * a_session, int a_threadId, int a_callframe)
{
const int buffSize = 256;
char buff[buffSize]; // buff is used for AsString
gmThread * thread = a_session->GetMachine()->GetThread(a_threadId);
if(thread)
{
// count the number of frames on the thread
int numFrames = 0;
const gmStackFrame * frame = thread->GetFrame();
while(frame)
{
++numFrames;
frame = frame->m_prev;
}
// if a valid frame was requested, fill out a context.
if(a_callframe >= 0 && a_callframe <= numFrames)
{
gmDebuggerBeginContext(a_session, a_threadId, a_callframe);
// pack frames
frame = thread->GetFrame();
numFrames = 0;
gmVariable * base = thread->GetBase();
const gmuint8 * ip = thread->GetInstruction();
while(frame)
{
// get the function object
gmVariable * fnVar = base - 1;
if(fnVar->m_type == GM_FUNCTION)
{
gmFunctionObject * fn = (gmFunctionObject *) GM_MOBJECT(thread->GetMachine(), fnVar->m_value.m_ref);
// this
base[-2].AsStringWithType(thread->GetMachine(), buff, buffSize);
gmDebuggerContextCallFrame(a_session, numFrames, fn->GetDebugName(), fn->GetSourceId(), fn->GetLine(ip), "this", buff, (base[-2].IsReference()) ? base[-2].m_value.m_ref : 0);
if(numFrames == a_callframe)
{
// this is the active frame, fill out the variables
int i;
for(i = 0; i < fn->GetNumParamsLocals(); ++i)
{
base[i].AsStringWithType(thread->GetMachine(), buff, buffSize);
gmDebuggerContextVariable(a_session, fn->GetSymbol(i), buff, (base[i].IsReference()) ? base[i].m_value.m_ref : 0);
}
}
}
else
{
base[-2].AsStringWithType(thread->GetMachine(), buff, buffSize);
gmDebuggerContextCallFrame(a_session, numFrames, "unknown", 0, 0, "this", buff, (base[-2].IsReference()) ? base[-2].m_value.m_ref : 0);
}
// next call frame
++numFrames;
base = thread->GetBottom() + frame->m_returnBase;
ip = frame->m_returnAddress;
frame = frame->m_prev;
}
gmDebuggerEndContext(a_session);
}
}
}
void gmMachineGetSource(gmDebugSession * a_session, int a_sourceId)
{
const char * source;
const char * filename;
if(a_session->GetMachine()->GetSourceCode(a_sourceId, source, filename))
{
gmDebuggerSource(a_session, a_sourceId, filename, source);
}
}
void gmMachineGetSourceInfo(gmDebugSession * a_session)
{
// todo
}
static bool threadIter(gmThread * a_thread, void * a_context)
{
gmDebugSession * session = (gmDebugSession *) a_context;
int state = 0; // 0 - running, 1 - blocked, 2 - sleeping, 3 - exception, 4 - debug
if(a_thread->m_debugFlags)
state = 4;
else if(a_thread->GetState() == gmThread::EXCEPTION)
state = 3;
else if(a_thread->GetState() == gmThread::RUNNING)
state = 0;
else if(a_thread->GetState() == gmThread::BLOCKED)
state = 1;
else if(a_thread->GetState() == gmThread::SLEEPING)
state = 2;
else
state = 3;
gmDebuggerThreadInfo(session, a_thread->GetId(), state);
return true;
}
void gmMachineGetThreadInfo(gmDebugSession * a_session)
{
gmDebuggerBeginThreadInfo(a_session);
a_session->GetMachine()->ForEachThread(threadIter, a_session);
gmDebuggerEndThreadInfo(a_session);
}
void gmMachineGetVariableInfo(gmDebugSession * a_session, int a_variableId)
{
// todo
}
void gmMachineSetBreakPoint(gmDebugSession * a_session, int a_responseId, int a_sourceId, int a_lineNumber, int a_threadId, int a_enabled)
{
bool sendAck = false;
// get break point
const void * bp = (const void *) a_session->GetMachine()->GetInstructionAtBreakPoint(a_sourceId, a_lineNumber);
if(bp)
{
// get to next instruction
bp = (const void *) (((const char *) bp) + 4);
int * id = a_session->FindBreakPoint(bp);
if(id)
{
if(!a_enabled)
{
a_session->RemoveBreakPoint(bp);
sendAck = true;
}
}
else
{
if(a_session->AddBreakPoint(bp, a_threadId))
{
sendAck = true;
}
}
}
if(sendAck)
gmDebuggerAck(a_session, a_responseId, 1);
else
gmDebuggerAck(a_session, a_responseId, 0);
}
void gmMachineBreak(gmDebugSession * a_session, int a_threadId)
{
gmThread * thread = a_session->GetMachine()->GetThread(a_threadId);
if(thread)
{
thread->m_debugUser = (thread->GetFrame()) ? thread->GetFrame()->m_returnBase : 0;
thread->m_debugFlags = TF_STEPINTO | TF_STEPOVER;
}
}
void gmMachineQuit(gmDebugSession * a_session)
{
a_session->Close();
}
void gmDebuggerBreak(gmDebugSession * a_session, int a_threadId, int a_sourceId, int a_lineNumber) {
a_session->Pack(ID_dbrk).Pack(a_threadId).Pack(a_sourceId).Pack(a_lineNumber).Send();
}
void gmDebuggerException(gmDebugSession * a_session, int a_threadId) {
a_session->Pack(ID_dexc).Pack(a_threadId).Send();
}
void gmDebuggerRun(gmDebugSession * a_session, int a_threadId) {
a_session->Pack(ID_drun).Pack(a_threadId).Send();
}
void gmDebuggerStop(gmDebugSession * a_session, int a_threadId) {
a_session->Pack(ID_dstp).Pack(a_threadId).Send();
}
void gmDebuggerSource(gmDebugSession * a_session, int a_sourceId, const char * a_sourceName, const char * a_source) {
a_session->Pack(ID_dsrc).Pack(a_sourceId).Pack(a_sourceName).Pack(a_source).Send();
}
void gmDebuggerBeginContext(gmDebugSession * a_session, int a_threadId, int a_callFrame) {
a_session->Pack(ID_dctx).Pack(a_threadId).Pack(a_callFrame);
}
void gmDebuggerContextCallFrame(gmDebugSession * a_session, int a_callFrame, const char * a_functionName, int a_sourceId, int a_lineNumber, const char * a_thisSymbol, const char * a_thisValue, int a_thisId) {
a_session->Pack(ID_call).Pack(a_callFrame).Pack(a_functionName).Pack(a_sourceId).Pack(a_lineNumber).Pack(a_thisSymbol).Pack(a_thisValue).Pack(a_thisId);
}
void gmDebuggerContextVariable(gmDebugSession * a_session, const char * a_varSymbol, const char * a_varValue, int a_varId) {
a_session->Pack(ID_vari).Pack(a_varSymbol).Pack(a_varValue).Pack(a_varId);
}
void gmDebuggerEndContext(gmDebugSession * a_session) {
a_session->Pack(ID_done).Send();
}
void gmDebuggerBeginSourceInfo(gmDebugSession * a_session) {
a_session->Pack(ID_dsri);
}
void gmDebuggerSourceInfo(gmDebugSession * a_session, int a_sourceId, const char * a_sourceName) {
a_session->Pack(ID_srci).Pack(a_sourceId).Pack(a_sourceName);
}
void gmDebuggerEndSourceInfo(gmDebugSession * a_session) {
a_session->Pack(ID_done).Send();
}
void gmDebuggerBeginThreadInfo(gmDebugSession * a_session) {
a_session->Pack(ID_dthi);
}
void gmDebuggerThreadInfo(gmDebugSession * a_session, int a_threadId, int a_threadState) {
a_session->Pack(ID_thri).Pack(a_threadId).Pack(a_threadState);
}
void gmDebuggerEndThreadInfo(gmDebugSession * a_session) {
a_session->Pack(ID_done).Send();
}
void gmDebuggerError(gmDebugSession * a_session, const char * a_error) {
a_session->Pack(ID_derr).Pack(a_error).Send();
}
void gmDebuggerMessage(gmDebugSession * a_session, const char * a_message) {
a_session->Pack(ID_dmsg).Pack(a_message).Send();
}
void gmDebuggerAck(gmDebugSession * a_session, int a_response, int a_posNeg) {
a_session->Pack(ID_dack).Pack(a_response).Pack(a_posNeg).Send();
}
void gmDebuggerQuit(gmDebugSession * a_session) {
a_session->Pack(ID_dend).Send();
}
//
// lib binding
//
int GM_CDECL gmdDebug(gmThread * a_thread)
{
// if the machine has a debug session, attach a debug hook to the thread
if(a_thread->GetMachine()->m_debugUser && a_thread->GetMachine()->GetDebugMode())
{
a_thread->m_debugUser = (a_thread->GetFrame()) ? a_thread->GetFrame()->m_returnBase : 0;
a_thread->m_debugFlags = TF_STEPINTO | TF_STEPOVER;
}
return GM_OK;
}
static gmFunctionEntry s_debugLib[] =
{
/*gm
\lib gm
\brief functions in the gm lib are all global scope
*/
/*gm
\function debug
\brief debug will cause a the debugger to break at this point while running.
*/
{"debug", gmdDebug},
};
void gmBindDebugLib(gmMachine * a_machine)
{
a_machine->RegisterLibrary(s_debugLib, sizeof(s_debugLib) / sizeof(s_debugLib[0]));
}
#endif
| mit |
ajacksified/restful-clients-in-rails-demo | rack-proxy/ruby/1.9.1/gems/jasminerice-0.0.8/app/helpers/jasminerice/application_helper.rb | 56 | module Jasminerice
module ApplicationHelper
end
end
| mit |
buddebej/ol3-dem | ol3/examples/export-map.js | 1180 | goog.require('ol.Map');
goog.require('ol.View');
goog.require('ol.control');
goog.require('ol.layer.Tile');
goog.require('ol.layer.Vector');
goog.require('ol.source.GeoJSON');
goog.require('ol.source.OSM');
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
new ol.layer.Vector({
source: new ol.source.GeoJSON({
projection: 'EPSG:3857',
url: 'data/geojson/countries.geojson'
})
})
],
target: 'map',
controls: ol.control.defaults({
attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
collapsible: false
})
}),
view: new ol.View({
center: [0, 0],
zoom: 2
})
});
var exportPNGElement = document.getElementById('export-png');
if ('download' in exportPNGElement) {
exportPNGElement.addEventListener('click', function(e) {
map.once('postcompose', function(event) {
var canvas = event.context.canvas;
exportPNGElement.href = canvas.toDataURL('image/png');
});
map.renderSync();
}, false);
} else {
var info = document.getElementById('no-download');
/**
* display error message
*/
info.style.display = '';
}
| mit |
cazzerson/Suma | analysis/src/scripts/services/actsLocs.js | 3247 | 'use strict';
angular.module('sumaAnalysis')
.factory('actsLocs', function () {
function calculateDepthAndTooltip (item, list, root, depth) {
var parent;
depth = depth || {depth: 0, tooltipTitle: item.title, ancestors: []};
if (parseInt(item.parent, 10) === parseInt(root, 10)) {
return depth;
}
parent = _.find(list, {'id': item.parent});
depth.depth += 1;
depth.tooltipTitle = parent.title + ': ' + depth.tooltipTitle;
depth.ancestors.push(parent.id);
return calculateDepthAndTooltip(parent, list, root, depth);
}
function processActivities (activities, activityGroups) {
var activityList = [],
activityGroupsHash;
// Sort activities and activity groups
activities = _.sortBy(activities, 'rank');
activityGroups = _.sortBy(activityGroups, 'rank');
activityGroupsHash = _.object(_.map(activityGroups, function (aGrp) {
return [aGrp.id, aGrp.title];
}));
// For each activity group, build a list of activities
_.each(activityGroups, function (activityGroup) {
// Add activity group metadata to activityGroupList array
activityList.push({
'id' : activityGroup.id,
'rank' : activityGroup.rank,
'title' : activityGroup.title,
'type' : 'activityGroup',
'depth' : 0,
'filter' : 'allow',
'enabled': true
});
// Loop over activities and add the ones belonging to the current activityGroup
_.each(activities, function (activity) {
if (activity.activityGroup === activityGroup.id) {
// Add activities to activityList array behind proper activityGroup
activityList.push({
'id' : activity.id,
'rank' : activity.rank,
'title' : activity.title,
'type' : 'activity',
'depth' : 1,
'activityGroup' : activityGroup.id,
'activityGroupTitle': activityGroupsHash[activityGroup.id],
'tooltipTitle' : activityGroupsHash[activityGroup.id] + ': ' + activity.title,
'altName' : activityGroupsHash[activityGroup.id] + ': ' + activity.title,
'filter' : 'allow',
'enabled' : true
});
}
});
});
return activityList;
}
function processLocations (locations, root) {
return _.map(locations, function (loc, index, list) {
var depth = calculateDepthAndTooltip(loc, list, root);
loc.depth = depth.depth;
loc.tooltipTitle = depth.tooltipTitle;
loc.ancestors = depth.ancestors;
loc.filter = true;
loc.enabled = true;
return loc;
});
}
return {
get: function (init) {
return {
activities: processActivities(init.dictionary.activities, init.dictionary.activityGroups),
locations: processLocations(init.dictionary.locations, init.rootLocation)
};
}
};
});
| mit |
sunze/py_flask | venv/lib/python3.4/site-packages/kombu/transport/pyamqp.py | 5008 | """
kombu.transport.pyamqp
======================
pure python amqp transport.
"""
from __future__ import absolute_import
import amqp
from kombu.five import items
from kombu.utils.amq_manager import get_manager
from kombu.utils.text import version_string_as_tuple
from . import base
DEFAULT_PORT = 5672
DEFAULT_SSL_PORT = 5671
class Message(base.Message):
def __init__(self, channel, msg, **kwargs):
props = msg.properties
super(Message, self).__init__(
channel,
body=msg.body,
delivery_tag=msg.delivery_tag,
content_type=props.get('content_type'),
content_encoding=props.get('content_encoding'),
delivery_info=msg.delivery_info,
properties=msg.properties,
headers=props.get('application_headers') or {},
**kwargs)
class Channel(amqp.Channel, base.StdChannel):
Message = Message
def prepare_message(self, body, priority=None,
content_type=None, content_encoding=None,
headers=None, properties=None, _Message=amqp.Message):
"""Prepares message so that it can be sent using this transport."""
return _Message(
body,
priority=priority,
content_type=content_type,
content_encoding=content_encoding,
application_headers=headers,
**properties or {}
)
def message_to_python(self, raw_message):
"""Convert encoded message body back to a Python value."""
return self.Message(self, raw_message)
class Connection(amqp.Connection):
Channel = Channel
class Transport(base.Transport):
Connection = Connection
default_port = DEFAULT_PORT
default_ssl_port = DEFAULT_SSL_PORT
# it's very annoying that pyamqp sometimes raises AttributeError
# if the connection is lost, but nothing we can do about that here.
connection_errors = amqp.Connection.connection_errors
channel_errors = amqp.Connection.channel_errors
recoverable_connection_errors = \
amqp.Connection.recoverable_connection_errors
recoverable_channel_errors = amqp.Connection.recoverable_channel_errors
driver_name = 'py-amqp'
driver_type = 'amqp'
supports_heartbeats = True
supports_ev = True
def __init__(self, client,
default_port=None, default_ssl_port=None, **kwargs):
self.client = client
self.default_port = default_port or self.default_port
self.default_ssl_port = default_ssl_port or self.default_ssl_port
def driver_version(self):
return amqp.__version__
def create_channel(self, connection):
return connection.channel()
def drain_events(self, connection, **kwargs):
return connection.drain_events(**kwargs)
def establish_connection(self):
"""Establish connection to the AMQP broker."""
conninfo = self.client
for name, default_value in items(self.default_connection_params):
if not getattr(conninfo, name, None):
setattr(conninfo, name, default_value)
if conninfo.hostname == 'localhost':
conninfo.hostname = '127.0.0.1'
opts = dict({
'host': conninfo.host,
'userid': conninfo.userid,
'password': conninfo.password,
'login_method': conninfo.login_method,
'virtual_host': conninfo.virtual_host,
'insist': conninfo.insist,
'ssl': conninfo.ssl,
'connect_timeout': conninfo.connect_timeout,
'heartbeat': conninfo.heartbeat,
}, **conninfo.transport_options or {})
conn = self.Connection(**opts)
conn.client = self.client
return conn
def verify_connection(self, connection):
return connection.connected
def close_connection(self, connection):
"""Close the AMQP broker connection."""
connection.client = None
connection.close()
def get_heartbeat_interval(self, connection):
return connection.heartbeat
def register_with_event_loop(self, connection, loop):
loop.add_reader(connection.sock, self.on_readable, connection, loop)
def heartbeat_check(self, connection, rate=2):
return connection.heartbeat_tick(rate=rate)
def qos_semantics_matches_spec(self, connection):
props = connection.server_properties
if props.get('product') == 'RabbitMQ':
return version_string_as_tuple(props['version']) < (3, 3)
return True
@property
def default_connection_params(self):
return {
'userid': 'guest',
'password': 'guest',
'port': (self.default_ssl_port if self.client.ssl
else self.default_port),
'hostname': 'localhost',
'login_method': 'AMQPLAIN',
}
def get_manager(self, *args, **kwargs):
return get_manager(self.client, *args, **kwargs)
| mit |
mlocati/concrete5 | concrete/blocks/social_links/form.php | 2919 | <?php
defined('C5_EXECUTE') or die("Access Denied.");
use Concrete\Core\Entity\Sharing\SocialNetwork\Link;
use Concrete\Core\Form\Service\Form;
use Concrete\Core\Sharing\SocialNetwork\Service;
use Concrete\Core\Support\Facade\Application;
use Concrete\Core\Support\Facade\Url;
/** @var Link[] $links */
/** @var Link[] $selectedLinks */
$app = Application::getFacadeApplication();
/** @var Form $form */
$form = $app->make(Form::class);
?>
<div class="form-group">
<label class="control-label form-label">
<?php echo t('Choose Social Links to Show'); ?>
</label>
<div id="ccm-block-social-links-list">
<?php if (0 == count($links)) { ?>
<p>
<?php echo t('You have not added any social links.'); ?>
</p>
<?php } ?>
<?php foreach ($links as $link) { ?>
<?php
/** @var Service $service */
$service = $link->getServiceObject();
?>
<?php if ($service) { ?>
<div class="form-check">
<label for="<?php echo "slID" . $link->getID(); ?>" class="form-check-label">
<?php echo $form->checkbox("socialService", $link->getID(), is_array($selectedLinks) && in_array($link, $selectedLinks), ["name" => "slID[]", "id" => "slID" . $link->getID()]); ?>
<?php echo $service->getDisplayName(); ?>
</label>
<i class="fas fa-arrows-alt"></i>
</div>
<?php } ?>
<?php } ?>
</div>
</div>
<div class="alert alert-info">
<?php echo t(/*i18n: the two %s will be replaced with HTML code*/'Add social links %sin the dashboard%s', '<a href="' . (string)Url::to('/dashboard/system/basics/social') . '">' ,'</a>'); ?>
</div>
<!--suppress CssUnusedSymbol -->
<style type="text/css">
#ccm-block-social-links-list {
-webkit-user-select: none;
position: relative;
}
#ccm-block-social-links-list .form-check {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
margin-bottom: 0;
padding: 6px;
}
#ccm-block-social-links-list .form-check:hover {
background: #e7e7e7;
border-radius: 4px;
transition: background-color .1s linear;
}
#ccm-block-social-links-list .form-check.ui-sortable-helper {
background: none;
}
#ccm-block-social-links-list i.fa-arrows-alt {
display: none;
color: #666;
cursor: move;
margin-left: auto;
}
#ccm-block-social-links-list div.form-check:hover i.fa-arrows-alt {
display: block;
}
</style>
<script>
$(function () {
$('#ccm-block-social-links-list').sortable({
axis: 'y'
});
});
</script>
| mit |
kieran-bamforth/our-boxen | vendor/bundle/ruby/2.0.0/gems/puppet-3.4.3/spec/unit/util/instrumentation/listener_spec.rb | 3283 | #! /usr/bin/env ruby
require 'spec_helper'
require 'matchers/json'
require 'puppet/util/instrumentation'
require 'puppet/util/instrumentation/listener'
describe Puppet::Util::Instrumentation::Listener do
Listener = Puppet::Util::Instrumentation::Listener
before(:each) do
@delegate = stub 'listener', :notify => nil, :name => 'listener'
@listener = Listener.new(@delegate)
@listener.enabled = true
end
it "should indirect instrumentation_listener" do
Listener.indirection.name.should == :instrumentation_listener
end
it "should raise an error if delegate doesn't support notify" do
lambda { Listener.new(Object.new) }.should raise_error
end
it "should not be enabled by default" do
Listener.new(@delegate).should_not be_enabled
end
it "should delegate notification" do
@delegate.expects(:notify).with(:event, :start, {})
listener = Listener.new(@delegate)
listener.notify(:event, :start, {})
end
it "should not listen is not enabled" do
@listener.enabled = false
@listener.should_not be_listen_to(:label)
end
it "should listen to all label if created without pattern" do
@listener.should be_listen_to(:improbable_label)
end
it "should listen to specific string pattern" do
listener = Listener.new(@delegate, "specific")
listener.enabled = true
listener.should be_listen_to(:specific)
end
it "should not listen to non-matching string pattern" do
listener = Listener.new(@delegate, "specific")
listener.enabled = true
listener.should_not be_listen_to(:unspecific)
end
it "should listen to specific regex pattern" do
listener = Listener.new(@delegate, /spe.*/)
listener.enabled = true
listener.should be_listen_to(:specific_pattern)
end
it "should not listen to non matching regex pattern" do
listener = Listener.new(@delegate, /^match.*/)
listener.enabled = true
listener.should_not be_listen_to(:not_matching)
end
it "should delegate its name to the underlying listener" do
@delegate.expects(:name).returns("myname")
@listener.name.should == "myname"
end
it "should delegate data fetching to the underlying listener" do
@delegate.expects(:data).returns(:data)
@listener.data.should == {:data => :data }
end
describe "when serializing to pson" do
it "should return a pson object containing pattern, name and status" do
@listener.should set_json_attribute('enabled').to(true)
@listener.should set_json_attribute('name').to("listener")
end
end
describe "when deserializing from pson" do
it "should lookup the archetype listener from the instrumentation layer" do
Puppet::Util::Instrumentation.expects(:[]).with("listener").returns(@listener)
Puppet::Util::Instrumentation::Listener.from_pson({"name" => "listener"})
end
it "should create a new listener shell instance delegating to the archetypal listener" do
Puppet::Util::Instrumentation.expects(:[]).with("listener").returns(@listener)
@listener.stubs(:listener).returns(@delegate)
Puppet::Util::Instrumentation::Listener.expects(:new).with(@delegate, nil, true)
Puppet::Util::Instrumentation::Listener.from_pson({"name" => "listener", "enabled" => true})
end
end
end
| mit |
uspgamedev/3D-experiment | externals/Ogre/OgreMain/src/OgreWindowEventUtilities.cpp | 14140 | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2013 Torus Knot Software Ltd
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 "OgreStableHeaders.h"
#include "OgreCommon.h"
#include "OgreWindowEventUtilities.h"
#include "OgreRenderWindow.h"
#include "OgreLogManager.h"
#include "OgreRoot.h"
#include "OgreException.h"
#include "OgreStringConverter.h"
#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX
#include <X11/Xlib.h>
void GLXProc( Ogre::RenderWindow *win, const XEvent &event );
#endif
//using namespace Ogre;
Ogre::WindowEventUtilities::WindowEventListeners Ogre::WindowEventUtilities::_msListeners;
Ogre::RenderWindowList Ogre::WindowEventUtilities::_msWindows;
namespace Ogre {
//--------------------------------------------------------------------------------//
void WindowEventUtilities::messagePump()
{
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
// Windows Message Loop (NULL means check all HWNDs belonging to this context)
MSG msg;
while( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
#elif OGRE_PLATFORM == OGRE_PLATFORM_LINUX
//GLX Message Pump
RenderWindowList::iterator win = _msWindows.begin();
RenderWindowList::iterator end = _msWindows.end();
Display* xDisplay = 0; // same for all windows
for (; win != end; win++)
{
XID xid;
XEvent event;
if (!xDisplay)
(*win)->getCustomAttribute("XDISPLAY", &xDisplay);
(*win)->getCustomAttribute("WINDOW", &xid);
while (XCheckWindowEvent (xDisplay, xid, StructureNotifyMask | VisibilityChangeMask | FocusChangeMask, &event))
{
GLXProc(*win, event);
}
// The ClientMessage event does not appear under any Event Mask
while (XCheckTypedWindowEvent (xDisplay, xid, ClientMessage, &event))
{
GLXProc(*win, event);
}
}
#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE && !defined __OBJC__ && !defined __LP64__
// OSX Message Pump
EventRef event = NULL;
EventTargetRef targetWindow;
targetWindow = GetEventDispatcherTarget();
// If we are unable to get the target then we no longer care about events.
if( !targetWindow ) return;
// Grab the next event, process it if it is a window event
while( ReceiveNextEvent( 0, NULL, kEventDurationNoWait, true, &event ) == noErr )
{
// Dispatch the event
SendEventToEventTarget( event, targetWindow );
ReleaseEvent( event );
}
#endif
}
//--------------------------------------------------------------------------------//
void WindowEventUtilities::addWindowEventListener( RenderWindow* window, WindowEventListener* listener )
{
_msListeners.insert(std::make_pair(window, listener));
}
//--------------------------------------------------------------------------------//
void WindowEventUtilities::removeWindowEventListener( RenderWindow* window, WindowEventListener* listener )
{
WindowEventListeners::iterator i = _msListeners.begin(), e = _msListeners.end();
for( ; i != e; ++i )
{
if( i->first == window && i->second == listener )
{
_msListeners.erase(i);
break;
}
}
}
//--------------------------------------------------------------------------------//
void WindowEventUtilities::_addRenderWindow(RenderWindow* window)
{
_msWindows.push_back(window);
}
//--------------------------------------------------------------------------------//
void WindowEventUtilities::_removeRenderWindow(RenderWindow* window)
{
RenderWindowList::iterator i = std::find(_msWindows.begin(), _msWindows.end(), window);
if( i != _msWindows.end() )
_msWindows.erase( i );
}
}
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
//--------------------------------------------------------------------------------//
namespace Ogre {
LRESULT CALLBACK WindowEventUtilities::_WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
if (uMsg == WM_CREATE)
{ // Store pointer to Win32Window in user data area
SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)(((LPCREATESTRUCT)lParam)->lpCreateParams));
return 0;
}
// look up window instance
// note: it is possible to get a WM_SIZE before WM_CREATE
RenderWindow* win = (RenderWindow*)GetWindowLongPtr(hWnd, GWLP_USERDATA);
if (!win)
return DefWindowProc(hWnd, uMsg, wParam, lParam);
//LogManager* log = LogManager::getSingletonPtr();
//Iterator of all listeners registered to this RenderWindow
WindowEventListeners::iterator index,
start = _msListeners.lower_bound(win),
end = _msListeners.upper_bound(win);
switch( uMsg )
{
case WM_ACTIVATE:
{
bool active = (LOWORD(wParam) != WA_INACTIVE);
if( active )
{
win->setActive( true );
}
else
{
if( win->isDeactivatedOnFocusChange() )
{
win->setActive( false );
}
}
for( ; start != end; ++start )
(start->second)->windowFocusChange(win);
break;
}
case WM_SYSKEYDOWN:
switch( wParam )
{
case VK_CONTROL:
case VK_SHIFT:
case VK_MENU: //ALT
//return zero to bypass defProc and signal we processed the message
return 0;
}
break;
case WM_SYSKEYUP:
switch( wParam )
{
case VK_CONTROL:
case VK_SHIFT:
case VK_MENU: //ALT
case VK_F10:
//return zero to bypass defProc and signal we processed the message
return 0;
}
break;
case WM_SYSCHAR:
// return zero to bypass defProc and signal we processed the message, unless it's an ALT-space
if (wParam != VK_SPACE)
return 0;
break;
case WM_ENTERSIZEMOVE:
//log->logMessage("WM_ENTERSIZEMOVE");
break;
case WM_EXITSIZEMOVE:
//log->logMessage("WM_EXITSIZEMOVE");
break;
case WM_MOVE:
//log->logMessage("WM_MOVE");
win->windowMovedOrResized();
for(index = start; index != end; ++index)
(index->second)->windowMoved(win);
break;
case WM_DISPLAYCHANGE:
win->windowMovedOrResized();
for(index = start; index != end; ++index)
(index->second)->windowResized(win);
break;
case WM_SIZE:
//log->logMessage("WM_SIZE");
win->windowMovedOrResized();
for(index = start; index != end; ++index)
(index->second)->windowResized(win);
break;
case WM_GETMINMAXINFO:
// Prevent the window from going smaller than some minimu size
((MINMAXINFO*)lParam)->ptMinTrackSize.x = 100;
((MINMAXINFO*)lParam)->ptMinTrackSize.y = 100;
break;
case WM_CLOSE:
{
//log->logMessage("WM_CLOSE");
bool close = true;
for(index = start; index != end; ++index)
{
if (!(index->second)->windowClosing(win))
close = false;
}
if (!close) return 0;
for(index = _msListeners.lower_bound(win); index != end; ++index)
(index->second)->windowClosed(win);
win->destroy();
return 0;
}
}
return DefWindowProc( hWnd, uMsg, wParam, lParam );
}
}
#elif OGRE_PLATFORM == OGRE_PLATFORM_LINUX
//--------------------------------------------------------------------------------//
void GLXProc( Ogre::RenderWindow *win, const XEvent &event )
{
//An iterator for the window listeners
Ogre::WindowEventUtilities::WindowEventListeners::iterator index,
start = Ogre::WindowEventUtilities::_msListeners.lower_bound(win),
end = Ogre::WindowEventUtilities::_msListeners.upper_bound(win);
switch(event.type)
{
case ClientMessage:
{
::Atom atom;
win->getCustomAttribute("ATOM", &atom);
if(event.xclient.format == 32 && event.xclient.data.l[0] == (long)atom)
{ //Window closed by window manager
//Send message first, to allow app chance to unregister things that need done before
//window is shutdown
bool close = true;
for(index = start ; index != end; ++index)
{
if (!(index->second)->windowClosing(win))
close = false;
}
if (!close) return;
for(index = start ; index != end; ++index)
(index->second)->windowClosed(win);
win->destroy();
}
break;
}
case DestroyNotify:
{
if (!win->isClosed())
{
// Window closed without window manager warning.
for(index = start ; index != end; ++index)
(index->second)->windowClosed(win);
win->destroy();
}
break;
}
case ConfigureNotify:
{
// This could be slightly more efficient if windowMovedOrResized took arguments:
unsigned int oldWidth, oldHeight, oldDepth;
int oldLeft, oldTop;
win->getMetrics(oldWidth, oldHeight, oldDepth, oldLeft, oldTop);
win->windowMovedOrResized();
unsigned int newWidth, newHeight, newDepth;
int newLeft, newTop;
win->getMetrics(newWidth, newHeight, newDepth, newLeft, newTop);
if (newLeft != oldLeft || newTop != oldTop)
{
for(index = start ; index != end; ++index)
(index->second)->windowMoved(win);
}
if (newWidth != oldWidth || newHeight != oldHeight)
{
for(index = start ; index != end; ++index)
(index->second)->windowResized(win);
}
break;
}
case FocusIn: // Gained keyboard focus
case FocusOut: // Lost keyboard focus
for(index = start ; index != end; ++index)
(index->second)->windowFocusChange(win);
break;
case MapNotify: //Restored
win->setActive( true );
for(index = start ; index != end; ++index)
(index->second)->windowFocusChange(win);
break;
case UnmapNotify: //Minimised
win->setActive( false );
win->setVisible( false );
for(index = start ; index != end; ++index)
(index->second)->windowFocusChange(win);
break;
case VisibilityNotify:
switch(event.xvisibility.state)
{
case VisibilityUnobscured:
win->setActive( true );
win->setVisible( true );
break;
case VisibilityPartiallyObscured:
win->setActive( true );
win->setVisible( true );
break;
case VisibilityFullyObscured:
win->setActive( false );
win->setVisible( false );
break;
}
for(index = start ; index != end; ++index)
(index->second)->windowFocusChange(win);
break;
default:
break;
} //End switch event.type
}
#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE && !defined __OBJC__ && !defined __LP64__
//--------------------------------------------------------------------------------//
namespace Ogre {
OSStatus WindowEventUtilities::_CarbonWindowHandler(EventHandlerCallRef nextHandler, EventRef event, void* wnd)
{
OSStatus status = noErr;
// Only events from our window should make it here
// This ensures that our user data is our WindowRef
RenderWindow* curWindow = (RenderWindow*)wnd;
if(!curWindow) return eventNotHandledErr;
//Iterator of all listeners registered to this RenderWindow
WindowEventListeners::iterator index,
start = _msListeners.lower_bound(curWindow),
end = _msListeners.upper_bound(curWindow);
// We only get called if a window event happens
UInt32 eventKind = GetEventKind( event );
switch( eventKind )
{
case kEventWindowActivated:
curWindow->setActive( true );
for( ; start != end; ++start )
(start->second)->windowFocusChange(curWindow);
break;
case kEventWindowDeactivated:
if( curWindow->isDeactivatedOnFocusChange() )
{
curWindow->setActive( false );
}
for( ; start != end; ++start )
(start->second)->windowFocusChange(curWindow);
break;
case kEventWindowShown:
case kEventWindowExpanded:
curWindow->setActive( true );
curWindow->setVisible( true );
for( ; start != end; ++start )
(start->second)->windowFocusChange(curWindow);
break;
case kEventWindowHidden:
case kEventWindowCollapsed:
curWindow->setActive( false );
curWindow->setVisible( false );
for( ; start != end; ++start )
(start->second)->windowFocusChange(curWindow);
break;
case kEventWindowDragCompleted:
curWindow->windowMovedOrResized();
for( ; start != end; ++start )
(start->second)->windowMoved(curWindow);
break;
case kEventWindowBoundsChanged:
curWindow->windowMovedOrResized();
for( ; start != end; ++start )
(start->second)->windowResized(curWindow);
break;
case kEventWindowClose:
{
bool close = true;
for( ; start != end; ++start )
{
if (!(start->second)->windowClosing(curWindow))
close = false;
}
if (close)
// This will cause event handling to continue on to the standard handler, which calls
// DisposeWindow(), which leads to the 'kEventWindowClosed' event
status = eventNotHandledErr;
break;
}
case kEventWindowClosed:
curWindow->destroy();
for( ; start != end; ++start )
(start->second)->windowClosed(curWindow);
break;
default:
status = eventNotHandledErr;
break;
}
return status;
}
}
#endif
| mit |
ayeletshpigelman/azure-sdk-for-net | sdk/synapse/Azure.Analytics.Synapse.Artifacts/src/Generated/Models/AzureSearchIndexSink.cs | 2405 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Collections.Generic;
namespace Azure.Analytics.Synapse.Artifacts.Models
{
/// <summary> A copy activity Azure Search Index sink. </summary>
public partial class AzureSearchIndexSink : CopySink
{
/// <summary> Initializes a new instance of AzureSearchIndexSink. </summary>
public AzureSearchIndexSink()
{
Type = "AzureSearchIndexSink";
}
/// <summary> Initializes a new instance of AzureSearchIndexSink. </summary>
/// <param name="type"> Copy sink type. </param>
/// <param name="writeBatchSize"> Write batch size. Type: integer (or Expression with resultType integer), minimum: 0. </param>
/// <param name="writeBatchTimeout"> Write batch timeout. Type: string (or Expression with resultType string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])). </param>
/// <param name="sinkRetryCount"> Sink retry count. Type: integer (or Expression with resultType integer). </param>
/// <param name="sinkRetryWait"> Sink retry wait. Type: string (or Expression with resultType string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])). </param>
/// <param name="maxConcurrentConnections"> The maximum concurrent connection count for the sink data store. Type: integer (or Expression with resultType integer). </param>
/// <param name="additionalProperties"> . </param>
/// <param name="writeBehavior"> Specify the write behavior when upserting documents into Azure Search Index. </param>
internal AzureSearchIndexSink(string type, object writeBatchSize, object writeBatchTimeout, object sinkRetryCount, object sinkRetryWait, object maxConcurrentConnections, IDictionary<string, object> additionalProperties, AzureSearchIndexWriteBehaviorType? writeBehavior) : base(type, writeBatchSize, writeBatchTimeout, sinkRetryCount, sinkRetryWait, maxConcurrentConnections, additionalProperties)
{
WriteBehavior = writeBehavior;
Type = type ?? "AzureSearchIndexSink";
}
/// <summary> Specify the write behavior when upserting documents into Azure Search Index. </summary>
public AzureSearchIndexWriteBehaviorType? WriteBehavior { get; set; }
}
}
| mit |
bussiere/pypyjs | website/demo/home/rfk/repos/pypy/lib_pypy/cffi/_pycparser/c_generator.py | 13798 | #------------------------------------------------------------------------------
# pycparser: c_generator.py
#
# C code generator from pycparser AST nodes.
#
# Copyright (C) 2008-2012, Eli Bendersky
# License: BSD
#------------------------------------------------------------------------------
from . import c_ast
class CGenerator(object):
""" Uses the same visitor pattern as c_ast.NodeVisitor, but modified to
return a value from each visit method, using string accumulation in
generic_visit.
"""
def __init__(self):
self.output = ''
# Statements start with indentation of self.indent_level spaces, using
# the _make_indent method
#
self.indent_level = 0
def _make_indent(self):
return ' ' * self.indent_level
def visit(self, node):
method = 'visit_' + node.__class__.__name__
return getattr(self, method, self.generic_visit)(node)
def generic_visit(self, node):
#~ print('generic:', type(node))
if node is None:
return ''
else:
return ''.join(self.visit(c) for c in node.children())
def visit_Constant(self, n):
return n.value
def visit_ID(self, n):
return n.name
def visit_ArrayRef(self, n):
arrref = self._parenthesize_unless_simple(n.name)
return arrref + '[' + self.visit(n.subscript) + ']'
def visit_StructRef(self, n):
sref = self._parenthesize_unless_simple(n.name)
return sref + n.type + self.visit(n.field)
def visit_FuncCall(self, n):
fref = self._parenthesize_unless_simple(n.name)
return fref + '(' + self.visit(n.args) + ')'
def visit_UnaryOp(self, n):
operand = self._parenthesize_unless_simple(n.expr)
if n.op == 'p++':
return '%s++' % operand
elif n.op == 'p--':
return '%s--' % operand
elif n.op == 'sizeof':
# Always parenthesize the argument of sizeof since it can be
# a name.
return 'sizeof(%s)' % self.visit(n.expr)
else:
return '%s%s' % (n.op, operand)
def visit_BinaryOp(self, n):
lval_str = self._parenthesize_if(n.left,
lambda d: not self._is_simple_node(d))
rval_str = self._parenthesize_if(n.right,
lambda d: not self._is_simple_node(d))
return '%s %s %s' % (lval_str, n.op, rval_str)
def visit_Assignment(self, n):
rval_str = self._parenthesize_if(
n.rvalue,
lambda n: isinstance(n, c_ast.Assignment))
return '%s %s %s' % (self.visit(n.lvalue), n.op, rval_str)
def visit_IdentifierType(self, n):
return ' '.join(n.names)
def visit_Decl(self, n, no_type=False):
# no_type is used when a Decl is part of a DeclList, where the type is
# explicitly only for the first delaration in a list.
#
s = n.name if no_type else self._generate_decl(n)
if n.bitsize: s += ' : ' + self.visit(n.bitsize)
if n.init:
if isinstance(n.init, c_ast.InitList):
s += ' = {' + self.visit(n.init) + '}'
elif isinstance(n.init, c_ast.ExprList):
s += ' = (' + self.visit(n.init) + ')'
else:
s += ' = ' + self.visit(n.init)
return s
def visit_DeclList(self, n):
s = self.visit(n.decls[0])
if len(n.decls) > 1:
s += ', ' + ', '.join(self.visit_Decl(decl, no_type=True)
for decl in n.decls[1:])
return s
def visit_Typedef(self, n):
s = ''
if n.storage: s += ' '.join(n.storage) + ' '
s += self._generate_type(n.type)
return s
def visit_Cast(self, n):
s = '(' + self._generate_type(n.to_type) + ')'
return s + ' ' + self._parenthesize_unless_simple(n.expr)
def visit_ExprList(self, n):
visited_subexprs = []
for expr in n.exprs:
if isinstance(expr, c_ast.ExprList):
visited_subexprs.append('{' + self.visit(expr) + '}')
else:
visited_subexprs.append(self.visit(expr))
return ', '.join(visited_subexprs)
def visit_InitList(self, n):
visited_subexprs = []
for expr in n.exprs:
if isinstance(expr, c_ast.InitList):
visited_subexprs.append('(' + self.visit(expr) + ')')
else:
visited_subexprs.append(self.visit(expr))
return ', '.join(visited_subexprs)
def visit_Enum(self, n):
s = 'enum'
if n.name: s += ' ' + n.name
if n.values:
s += ' {'
for i, enumerator in enumerate(n.values.enumerators):
s += enumerator.name
if enumerator.value:
s += ' = ' + self.visit(enumerator.value)
if i != len(n.values.enumerators) - 1:
s += ', '
s += '}'
return s
def visit_FuncDef(self, n):
decl = self.visit(n.decl)
self.indent_level = 0
body = self.visit(n.body)
if n.param_decls:
knrdecls = ';\n'.join(self.visit(p) for p in n.param_decls)
return decl + '\n' + knrdecls + ';\n' + body + '\n'
else:
return decl + '\n' + body + '\n'
def visit_FileAST(self, n):
s = ''
for ext in n.ext:
if isinstance(ext, c_ast.FuncDef):
s += self.visit(ext)
else:
s += self.visit(ext) + ';\n'
return s
def visit_Compound(self, n):
s = self._make_indent() + '{\n'
self.indent_level += 2
if n.block_items:
s += ''.join(self._generate_stmt(stmt) for stmt in n.block_items)
self.indent_level -= 2
s += self._make_indent() + '}\n'
return s
def visit_EmptyStatement(self, n):
return ';'
def visit_ParamList(self, n):
return ', '.join(self.visit(param) for param in n.params)
def visit_Return(self, n):
s = 'return'
if n.expr: s += ' ' + self.visit(n.expr)
return s + ';'
def visit_Break(self, n):
return 'break;'
def visit_Continue(self, n):
return 'continue;'
def visit_TernaryOp(self, n):
s = self.visit(n.cond) + ' ? '
s += self.visit(n.iftrue) + ' : '
s += self.visit(n.iffalse)
return s
def visit_If(self, n):
s = 'if ('
if n.cond: s += self.visit(n.cond)
s += ')\n'
s += self._generate_stmt(n.iftrue, add_indent=True)
if n.iffalse:
s += self._make_indent() + 'else\n'
s += self._generate_stmt(n.iffalse, add_indent=True)
return s
def visit_For(self, n):
s = 'for ('
if n.init: s += self.visit(n.init)
s += ';'
if n.cond: s += ' ' + self.visit(n.cond)
s += ';'
if n.next: s += ' ' + self.visit(n.next)
s += ')\n'
s += self._generate_stmt(n.stmt, add_indent=True)
return s
def visit_While(self, n):
s = 'while ('
if n.cond: s += self.visit(n.cond)
s += ')\n'
s += self._generate_stmt(n.stmt, add_indent=True)
return s
def visit_DoWhile(self, n):
s = 'do\n'
s += self._generate_stmt(n.stmt, add_indent=True)
s += self._make_indent() + 'while ('
if n.cond: s += self.visit(n.cond)
s += ');'
return s
def visit_Switch(self, n):
s = 'switch (' + self.visit(n.cond) + ')\n'
s += self._generate_stmt(n.stmt, add_indent=True)
return s
def visit_Case(self, n):
s = 'case ' + self.visit(n.expr) + ':\n'
for stmt in n.stmts:
s += self._generate_stmt(stmt, add_indent=True)
return s
def visit_Default(self, n):
s = 'default:\n'
for stmt in n.stmts:
s += self._generate_stmt(stmt, add_indent=True)
return s
def visit_Label(self, n):
return n.name + ':\n' + self._generate_stmt(n.stmt)
def visit_Goto(self, n):
return 'goto ' + n.name + ';'
def visit_EllipsisParam(self, n):
return '...'
def visit_Struct(self, n):
return self._generate_struct_union(n, 'struct')
def visit_Typename(self, n):
return self._generate_type(n.type)
def visit_Union(self, n):
return self._generate_struct_union(n, 'union')
def visit_NamedInitializer(self, n):
s = ''
for name in n.name:
if isinstance(name, c_ast.ID):
s += '.' + name.name
elif isinstance(name, c_ast.Constant):
s += '[' + name.value + ']'
s += ' = ' + self.visit(n.expr)
return s
def _generate_struct_union(self, n, name):
""" Generates code for structs and unions. name should be either
'struct' or union.
"""
s = name + ' ' + (n.name or '')
if n.decls:
s += '\n'
s += self._make_indent()
self.indent_level += 2
s += '{\n'
for decl in n.decls:
s += self._generate_stmt(decl)
self.indent_level -= 2
s += self._make_indent() + '}'
return s
def _generate_stmt(self, n, add_indent=False):
""" Generation from a statement node. This method exists as a wrapper
for individual visit_* methods to handle different treatment of
some statements in this context.
"""
typ = type(n)
if add_indent: self.indent_level += 2
indent = self._make_indent()
if add_indent: self.indent_level -= 2
if typ in (
c_ast.Decl, c_ast.Assignment, c_ast.Cast, c_ast.UnaryOp,
c_ast.BinaryOp, c_ast.TernaryOp, c_ast.FuncCall, c_ast.ArrayRef,
c_ast.StructRef, c_ast.Constant, c_ast.ID, c_ast.Typedef):
# These can also appear in an expression context so no semicolon
# is added to them automatically
#
return indent + self.visit(n) + ';\n'
elif typ in (c_ast.Compound,):
# No extra indentation required before the opening brace of a
# compound - because it consists of multiple lines it has to
# compute its own indentation.
#
return self.visit(n)
else:
return indent + self.visit(n) + '\n'
def _generate_decl(self, n):
""" Generation from a Decl node.
"""
s = ''
if n.funcspec: s = ' '.join(n.funcspec) + ' '
if n.storage: s += ' '.join(n.storage) + ' '
s += self._generate_type(n.type)
return s
def _generate_type(self, n, modifiers=[]):
""" Recursive generation from a type node. n is the type node.
modifiers collects the PtrDecl, ArrayDecl and FuncDecl modifiers
encountered on the way down to a TypeDecl, to allow proper
generation from it.
"""
typ = type(n)
#~ print(n, modifiers)
if typ == c_ast.TypeDecl:
s = ''
if n.quals: s += ' '.join(n.quals) + ' '
s += self.visit(n.type)
nstr = n.declname if n.declname else ''
# Resolve modifiers.
# Wrap in parens to distinguish pointer to array and pointer to
# function syntax.
#
for i, modifier in enumerate(modifiers):
if isinstance(modifier, c_ast.ArrayDecl):
if (i != 0 and isinstance(modifiers[i - 1], c_ast.PtrDecl)):
nstr = '(' + nstr + ')'
nstr += '[' + self.visit(modifier.dim) + ']'
elif isinstance(modifier, c_ast.FuncDecl):
if (i != 0 and isinstance(modifiers[i - 1], c_ast.PtrDecl)):
nstr = '(' + nstr + ')'
nstr += '(' + self.visit(modifier.args) + ')'
elif isinstance(modifier, c_ast.PtrDecl):
if modifier.quals:
nstr = '* %s %s' % (' '.join(modifier.quals), nstr)
else:
nstr = '*' + nstr
if nstr: s += ' ' + nstr
return s
elif typ == c_ast.Decl:
return self._generate_decl(n.type)
elif typ == c_ast.Typename:
return self._generate_type(n.type)
elif typ == c_ast.IdentifierType:
return ' '.join(n.names) + ' '
elif typ in (c_ast.ArrayDecl, c_ast.PtrDecl, c_ast.FuncDecl):
return self._generate_type(n.type, modifiers + [n])
else:
return self.visit(n)
def _parenthesize_if(self, n, condition):
""" Visits 'n' and returns its string representation, parenthesized
if the condition function applied to the node returns True.
"""
s = self.visit(n)
if condition(n):
return '(' + s + ')'
else:
return s
def _parenthesize_unless_simple(self, n):
""" Common use case for _parenthesize_if
"""
return self._parenthesize_if(n, lambda d: not self._is_simple_node(d))
def _is_simple_node(self, n):
""" Returns True for nodes that are "simple" - i.e. nodes that always
have higher precedence than operators.
"""
return isinstance(n,( c_ast.Constant, c_ast.ID, c_ast.ArrayRef,
c_ast.StructRef, c_ast.FuncCall))
| mit |
leoeuclids/ember-material-lite | tests/acceptance/navs-test.js | 412 | import Ember from 'ember';
import { module, test } from 'qunit';
import startApp from '../../tests/helpers/start-app';
module('Acceptance | navs', {
beforeEach() {
this.application = startApp();
},
afterEach() {
Ember.run(this.application, 'destroy');
}
});
test('visiting /navs', function(assert) {
visit('/navs');
andThen(function() {
assert.equal(currentURL(), '/navs');
});
});
| mit |
pocallaghan/n98-magerun | tests/N98/Magento/Command/Developer/Theme/ListCommandTest.php | 653 | <?php
namespace N98\Magento\Command\Developer\Theme;
use N98\Magento\Command\TestCase;
use Symfony\Component\Console\Tester\CommandTester;
class ListCommandTest extends TestCase
{
public function testExecute()
{
$application = $this->getApplication();
$application->add(new ListCommand());
$command = $this->getApplication()->find('dev:theme:list');
$commandTester = new CommandTester($command);
$commandTester->execute(
array(
'command' => $command->getName(),
)
);
$this->assertContains('base/default', $commandTester->getDisplay());
}
}
| mit |
dotnet/llilc | lib/Jit/jitoptions.cpp | 9832 | //===----------------- lib/Jit/options.cpp ----------------------*- C++ -*-===//
//
// LLILC
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief Definition of the Options class that encapsulates JIT options
/// extracted from CoreCLR config values.
///
//===----------------------------------------------------------------------===//
#include "earlyincludes.h"
#include "global.h"
#include "jitpch.h"
#include "LLILCJit.h"
#include "jitoptions.h"
// Define a macro for cross-platform UTF-16 string literals.
#if defined(_MSC_VER)
#define UTF16(lit) L##lit
#else
#define UTF16(lit) u##lit
#endif
// For now we're always running as the altjit
#define ALT_JIT 1
// These are the instantiations of the static method sets in Options.h.
// This MethodSets are initialized from CLRConfig values passed through
// the corinfo.h interface.
MethodSet JitOptions::AltJitMethodSet;
MethodSet JitOptions::AltJitNgenMethodSet;
MethodSet JitOptions::ExcludeMethodSet;
MethodSet JitOptions::BreakMethodSet;
MethodSet JitOptions::MSILMethodSet;
MethodSet JitOptions::LLVMMethodSet;
MethodSet JitOptions::CodeRangeMethodSet;
template <typename UTF16CharT>
char16_t *getStringConfigValue(ICorJitInfo *CorInfo, const UTF16CharT *Name) {
static_assert(sizeof(UTF16CharT) == 2, "UTF16CharT is the wrong size!");
return (char16_t *)LLILCJit::TheJitHost->getStringConfigValue(
(const wchar_t *)Name);
}
template <typename UTF16CharT>
void freeStringConfigValue(ICorJitInfo *CorInfo, UTF16CharT *Value) {
static_assert(sizeof(UTF16CharT) == 2, "UTF16CharT is the wrong size!");
return LLILCJit::TheJitHost->freeStringConfigValue((wchar_t *)Value);
}
JitOptions::JitOptions(LLILCJitContext &Context) {
// Set 'IsAltJit' based on environment information.
IsAltJit = queryIsAltJit(Context);
// Set dump level for this JIT invocation.
DumpLevel = queryDumpLevel(Context);
// Set optimization level for this JIT invocation.
OptLevel = queryOptLevel(Context);
EnableOptimization = OptLevel != ::OptLevel::DEBUG_CODE;
// Set whether to use conservative GC.
UseConservativeGC = queryUseConservativeGC(Context);
// Set whether to insert statepoints.
DoInsertStatepoints = queryDoInsertStatepoints(Context);
DoSIMDIntrinsic = queryDoSIMDIntrinsic(Context);
// Set whether to do tail call opt.
DoTailCallOpt = queryDoTailCallOpt(Context);
LogGcInfo = queryLogGcInfo(Context);
// Set whether to insert failfast in exception handlers.
ExecuteHandlers = queryExecuteHandlers(Context);
IsExcludeMethod = queryIsExcludeMethod(Context);
IsBreakMethod = queryIsBreakMethod(Context);
IsMSILDumpMethod = queryIsMSILDumpMethod(Context);
IsLLVMDumpMethod = queryIsLLVMDumpMethod(Context);
IsCodeRangeMethod = queryIsCodeRangeMethod(Context);
if (IsAltJit) {
PreferredIntrinsicSIMDVectorLength = 0;
} else {
PreferredIntrinsicSIMDVectorLength = 32;
}
// Validate Statepoint and Conservative GC state.
assert(DoInsertStatepoints ||
UseConservativeGC && "Statepoints required for precise-GC");
}
bool JitOptions::queryDoTailCallOpt(LLILCJitContext &Context) {
return (bool)DEFAULT_TAIL_CALL_OPT;
}
bool JitOptions::queryIsAltJit(LLILCJitContext &Context) {
// Initial state is that we are not an alternative jit until proven otherwise;
bool IsAlternateJit = false;
// NDEBUG is !Debug
#if !defined(NDEBUG)
// DEBUG case
// Get/reuse method set that contains the altjit method value.
MethodSet *AltJit = nullptr;
if (Context.Flags & CORJIT_FLG_PREJIT) {
if (!AltJitNgenMethodSet.isInitialized()) {
char16_t *NgenStr =
getStringConfigValue(Context.JitInfo, UTF16("AltJitNgen"));
std::unique_ptr<std::string> NgenUtf8 = Convert::utf16ToUtf8(NgenStr);
AltJitNgenMethodSet.init(std::move(NgenUtf8));
freeStringConfigValue(Context.JitInfo, NgenStr);
}
// Set up AltJitNgen set to be used for AltJit test.
AltJit = &AltJitNgenMethodSet;
} else {
if (!AltJitMethodSet.isInitialized()) {
char16_t *JitStr = getStringConfigValue(Context.JitInfo, UTF16("AltJit"));
// Move this to the UTIL code and ifdef it for platform
std::unique_ptr<std::string> JitUtf8 = Convert::utf16ToUtf8(JitStr);
AltJitMethodSet.init(std::move(JitUtf8));
freeStringConfigValue(Context.JitInfo, JitStr);
}
// Set up AltJit set to be use for AltJit test.
AltJit = &AltJitMethodSet;
}
#ifdef ALT_JIT
const char *ClassName = nullptr;
const char *MethodName = nullptr;
MethodName =
Context.JitInfo->getMethodName(Context.MethodInfo->ftn, &ClassName);
IsAlternateJit =
AltJit->contains(MethodName, ClassName, Context.MethodInfo->args.pSig);
#endif // ALT_JIT
#else
if (Context.Flags & CORJIT_FLG_PREJIT) {
char16_t *NgenStr =
getStringConfigValue(Context.JitInfo, UTF16("AltJitNgen"));
std::unique_ptr<std::string> NgenUtf8 = Convert::utf16ToUtf8(NgenStr);
if (NgenUtf8->compare("*") == 0) {
IsAlternateJit = true;
}
} else {
char16_t *JitStr = getStringConfigValue(Context.JitInfo, UTF16("AltJit"));
std::unique_ptr<std::string> JitUtf8 = Convert::utf16ToUtf8(JitStr);
if (JitUtf8->compare("*") == 0) {
IsAlternateJit = true;
}
}
#endif
return IsAlternateJit;
}
::DumpLevel JitOptions::queryDumpLevel(LLILCJitContext &Context) {
::DumpLevel JitDumpLevel = ::DumpLevel::NODUMP;
char16_t *LevelWStr =
getStringConfigValue(Context.JitInfo, UTF16("DUMPLLVMIR"));
if (LevelWStr) {
std::unique_ptr<std::string> Level = Convert::utf16ToUtf8(LevelWStr);
std::transform(Level->begin(), Level->end(), Level->begin(), ::toupper);
if (Level->compare("VERBOSE") == 0) {
JitDumpLevel = ::DumpLevel::VERBOSE;
} else if (Level->compare("SUMMARY") == 0) {
JitDumpLevel = ::DumpLevel::SUMMARY;
}
}
return JitDumpLevel;
}
bool JitOptions::queryIsExcludeMethod(LLILCJitContext &JitContext) {
return queryMethodSet(JitContext, ExcludeMethodSet,
(const char16_t *)UTF16("AltJitExclude"));
}
bool JitOptions::queryIsBreakMethod(LLILCJitContext &JitContext) {
return queryMethodSet(JitContext, BreakMethodSet,
(const char16_t *)UTF16("AltJitBreakAtJitStart"));
}
bool JitOptions::queryIsMSILDumpMethod(LLILCJitContext &JitContext) {
return queryMethodSet(JitContext, MSILMethodSet,
(const char16_t *)UTF16("AltJitMSILDump"));
}
bool JitOptions::queryIsLLVMDumpMethod(LLILCJitContext &JitContext) {
return queryMethodSet(JitContext, LLVMMethodSet,
(const char16_t *)UTF16("AltJitLLVMDump"));
}
bool JitOptions::queryIsCodeRangeMethod(LLILCJitContext &JitContext) {
return queryMethodSet(JitContext, CodeRangeMethodSet,
(const char16_t *)UTF16("AltJitCodeRangeDump"));
}
bool JitOptions::queryMethodSet(LLILCJitContext &JitContext, MethodSet &TheSet,
const char16_t *Name) {
if (!TheSet.isInitialized()) {
char16_t *ConfigStr = getStringConfigValue(JitContext.JitInfo, Name);
bool NeedFree = true;
if (ConfigStr == nullptr) {
ConfigStr = const_cast<char16_t *>((const char16_t *)UTF16(""));
NeedFree = false;
}
std::unique_ptr<std::string> ConfigUtf8 = Convert::utf16ToUtf8(ConfigStr);
TheSet.init(std::move(ConfigUtf8));
if (NeedFree) {
freeStringConfigValue(JitContext.JitInfo, ConfigStr);
}
}
const char *ClassName = nullptr;
const char *MethodName = nullptr;
MethodName =
JitContext.JitInfo->getMethodName(JitContext.MethodInfo->ftn, &ClassName);
bool IsInMethodSet =
TheSet.contains(MethodName, ClassName, JitContext.MethodInfo->args.pSig);
return IsInMethodSet;
}
bool JitOptions::queryNonNullNonEmpty(LLILCJitContext &JitContext,
const char16_t *Name) {
char16_t *ConfigStr = getStringConfigValue(JitContext.JitInfo, Name);
return (ConfigStr != nullptr) && (*ConfigStr != 0);
}
// Get the GC-Scheme used by the runtime -- conservative/precise
bool JitOptions::queryUseConservativeGC(LLILCJitContext &Context) {
return queryNonNullNonEmpty(Context,
(const char16_t *)UTF16("gcConservative"));
}
// Determine if GC statepoints should be inserted.
bool JitOptions::queryDoInsertStatepoints(LLILCJitContext &Context) {
return queryNonNullNonEmpty(Context,
(const char16_t *)UTF16("INSERTSTATEPOINTS"));
}
// Determine if GCInfo encoding logs should be emitted
bool JitOptions::queryLogGcInfo(LLILCJitContext &Context) {
return queryNonNullNonEmpty(Context,
(const char16_t *)UTF16("JitGCInfoLogging"));
}
// Determine if exception handlers should be executed.
bool JitOptions::queryExecuteHandlers(LLILCJitContext &Context) {
return queryNonNullNonEmpty(Context,
(const char16_t *)UTF16("ExecuteHandlers"));
}
// Determine if SIMD intrinsics should be used.
bool JitOptions::queryDoSIMDIntrinsic(LLILCJitContext &Context) {
return queryNonNullNonEmpty(Context,
(const char16_t *)UTF16("SIMDINTRINSIC"));
}
OptLevel JitOptions::queryOptLevel(LLILCJitContext &Context) {
::OptLevel JitOptLevel = ::OptLevel::BLENDED_CODE;
// Currently we only check for the debug flag but this will be extended
// to account for further opt levels as we move forward.
if ((Context.Flags & CORJIT_FLG_DEBUG_CODE) != 0) {
JitOptLevel = ::OptLevel::DEBUG_CODE;
}
return JitOptLevel;
}
JitOptions::~JitOptions() {}
| mit |
jianghaolu/azure-sdk-for-java | azure-mgmt-appservice/src/main/java/com/microsoft/azure/management/appservice/AutoHealActions.java | 2569 | /**
* 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.
*/
package com.microsoft.azure.management.appservice;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Actions which to take by the auto-heal module when a rule is triggered.
*/
public class AutoHealActions {
/**
* Predefined action to be taken. Possible values include: 'Recycle',
* 'LogEvent', 'CustomAction'.
*/
@JsonProperty(value = "actionType")
private AutoHealActionType actionType;
/**
* Custom action to be taken.
*/
@JsonProperty(value = "customAction")
private AutoHealCustomAction customAction;
/**
* Minimum time the process must execute
* before taking the action.
*/
@JsonProperty(value = "minProcessExecutionTime")
private String minProcessExecutionTime;
/**
* Get the actionType value.
*
* @return the actionType value
*/
public AutoHealActionType actionType() {
return this.actionType;
}
/**
* Set the actionType value.
*
* @param actionType the actionType value to set
* @return the AutoHealActions object itself.
*/
public AutoHealActions withActionType(AutoHealActionType actionType) {
this.actionType = actionType;
return this;
}
/**
* Get the customAction value.
*
* @return the customAction value
*/
public AutoHealCustomAction customAction() {
return this.customAction;
}
/**
* Set the customAction value.
*
* @param customAction the customAction value to set
* @return the AutoHealActions object itself.
*/
public AutoHealActions withCustomAction(AutoHealCustomAction customAction) {
this.customAction = customAction;
return this;
}
/**
* Get the minProcessExecutionTime value.
*
* @return the minProcessExecutionTime value
*/
public String minProcessExecutionTime() {
return this.minProcessExecutionTime;
}
/**
* Set the minProcessExecutionTime value.
*
* @param minProcessExecutionTime the minProcessExecutionTime value to set
* @return the AutoHealActions object itself.
*/
public AutoHealActions withMinProcessExecutionTime(String minProcessExecutionTime) {
this.minProcessExecutionTime = minProcessExecutionTime;
return this;
}
}
| mit |
idada/slua | Assets/Slua/LuaObject/Lua_UnityEngine_Bounds.cs | 8284 | using UnityEngine;
using System;
using LuaInterface;
using SLua;
using System.Collections.Generic;
public class Lua_UnityEngine_Bounds : LuaObject {
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int constructor(IntPtr l) {
LuaDLL.lua_remove(l,1);
UnityEngine.Bounds o;
if(matchType(l,1,typeof(UnityEngine.Vector3),typeof(UnityEngine.Vector3))){
UnityEngine.Vector3 a1;
checkType(l,1,out a1);
UnityEngine.Vector3 a2;
checkType(l,2,out a2);
o=new UnityEngine.Bounds(a1,a2);
pushObject(l,o);
return 1;
}
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int SetMinMax(IntPtr l) {
try{
UnityEngine.Bounds self=checkSelf<UnityEngine.Bounds>(l);
UnityEngine.Vector3 a1;
checkType(l,2,out a1);
UnityEngine.Vector3 a2;
checkType(l,3,out a2);
self.SetMinMax(a1,a2);
setBack(l,self);
return 0;
}
catch(Exception e) {
LuaDLL.luaL_error(l, e.ToString());
return 0;
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int Encapsulate(IntPtr l) {
try{
if(matchType(l,2,typeof(UnityEngine.Vector3))){
UnityEngine.Bounds self=checkSelf<UnityEngine.Bounds>(l);
UnityEngine.Vector3 a1;
checkType(l,2,out a1);
self.Encapsulate(a1);
setBack(l,self);
return 0;
}
else if(matchType(l,2,typeof(UnityEngine.Bounds))){
UnityEngine.Bounds self=checkSelf<UnityEngine.Bounds>(l);
UnityEngine.Bounds a1;
checkType(l,2,out a1);
self.Encapsulate(a1);
setBack(l,self);
return 0;
}
LuaDLL.luaL_error(l,"No matched override function to call");
return 0;
}
catch(Exception e) {
LuaDLL.luaL_error(l, e.ToString());
return 0;
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int Expand(IntPtr l) {
try{
if(matchType(l,2,typeof(System.Single))){
UnityEngine.Bounds self=checkSelf<UnityEngine.Bounds>(l);
System.Single a1;
checkType(l,2,out a1);
self.Expand(a1);
setBack(l,self);
return 0;
}
else if(matchType(l,2,typeof(UnityEngine.Vector3))){
UnityEngine.Bounds self=checkSelf<UnityEngine.Bounds>(l);
UnityEngine.Vector3 a1;
checkType(l,2,out a1);
self.Expand(a1);
setBack(l,self);
return 0;
}
LuaDLL.luaL_error(l,"No matched override function to call");
return 0;
}
catch(Exception e) {
LuaDLL.luaL_error(l, e.ToString());
return 0;
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int Intersects(IntPtr l) {
try{
UnityEngine.Bounds self=checkSelf<UnityEngine.Bounds>(l);
UnityEngine.Bounds a1;
checkType(l,2,out a1);
System.Boolean ret=self.Intersects(a1);
pushValue(l,ret);
return 1;
}
catch(Exception e) {
LuaDLL.luaL_error(l, e.ToString());
return 0;
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int Contains(IntPtr l) {
try{
UnityEngine.Bounds self=checkSelf<UnityEngine.Bounds>(l);
UnityEngine.Vector3 a1;
checkType(l,2,out a1);
System.Boolean ret=self.Contains(a1);
pushValue(l,ret);
return 1;
}
catch(Exception e) {
LuaDLL.luaL_error(l, e.ToString());
return 0;
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int SqrDistance(IntPtr l) {
try{
UnityEngine.Bounds self=checkSelf<UnityEngine.Bounds>(l);
UnityEngine.Vector3 a1;
checkType(l,2,out a1);
System.Single ret=self.SqrDistance(a1);
pushValue(l,ret);
return 1;
}
catch(Exception e) {
LuaDLL.luaL_error(l, e.ToString());
return 0;
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int IntersectRay(IntPtr l) {
try{
if(matchType(l,2,typeof(UnityEngine.Ray))){
UnityEngine.Bounds self=checkSelf<UnityEngine.Bounds>(l);
UnityEngine.Ray a1;
checkType(l,2,out a1);
System.Boolean ret=self.IntersectRay(a1);
pushValue(l,ret);
return 1;
}
else if(matchType(l,2,typeof(UnityEngine.Ray),typeof(System.Single))){
UnityEngine.Bounds self=checkSelf<UnityEngine.Bounds>(l);
UnityEngine.Ray a1;
checkType(l,2,out a1);
System.Single a2;
System.Boolean ret=self.IntersectRay(a1,out a2);
pushValue(l,ret);
pushValue(l,a2);
return 2;
}
LuaDLL.luaL_error(l,"No matched override function to call");
return 0;
}
catch(Exception e) {
LuaDLL.luaL_error(l, e.ToString());
return 0;
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int op_Equality(IntPtr l) {
try{
UnityEngine.Bounds a1;
checkType(l,1,out a1);
UnityEngine.Bounds a2;
checkType(l,2,out a2);
System.Boolean ret=(a1==a2);
pushValue(l,ret);
return 1;
}
catch(Exception e) {
LuaDLL.luaL_error(l, e.ToString());
return 0;
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int op_Inequality(IntPtr l) {
try{
UnityEngine.Bounds a1;
checkType(l,1,out a1);
UnityEngine.Bounds a2;
checkType(l,2,out a2);
System.Boolean ret=(a1!=a2);
pushValue(l,ret);
return 1;
}
catch(Exception e) {
LuaDLL.luaL_error(l, e.ToString());
return 0;
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int get_center(IntPtr l) {
UnityEngine.Bounds o = checkSelf<UnityEngine.Bounds>(l);
pushValue(l,o.center);
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int set_center(IntPtr l) {
UnityEngine.Bounds o = checkSelf<UnityEngine.Bounds>(l);
UnityEngine.Vector3 v;
checkType(l,2,out v);
o.center=v;
setBack(l,o);
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int get_size(IntPtr l) {
UnityEngine.Bounds o = checkSelf<UnityEngine.Bounds>(l);
pushValue(l,o.size);
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int set_size(IntPtr l) {
UnityEngine.Bounds o = checkSelf<UnityEngine.Bounds>(l);
UnityEngine.Vector3 v;
checkType(l,2,out v);
o.size=v;
setBack(l,o);
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int get_extents(IntPtr l) {
UnityEngine.Bounds o = checkSelf<UnityEngine.Bounds>(l);
pushValue(l,o.extents);
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int set_extents(IntPtr l) {
UnityEngine.Bounds o = checkSelf<UnityEngine.Bounds>(l);
UnityEngine.Vector3 v;
checkType(l,2,out v);
o.extents=v;
setBack(l,o);
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int get_min(IntPtr l) {
UnityEngine.Bounds o = checkSelf<UnityEngine.Bounds>(l);
pushValue(l,o.min);
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int set_min(IntPtr l) {
UnityEngine.Bounds o = checkSelf<UnityEngine.Bounds>(l);
UnityEngine.Vector3 v;
checkType(l,2,out v);
o.min=v;
setBack(l,o);
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int get_max(IntPtr l) {
UnityEngine.Bounds o = checkSelf<UnityEngine.Bounds>(l);
pushValue(l,o.max);
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int set_max(IntPtr l) {
UnityEngine.Bounds o = checkSelf<UnityEngine.Bounds>(l);
UnityEngine.Vector3 v;
checkType(l,2,out v);
o.max=v;
setBack(l,o);
return 0;
}
static public void reg(IntPtr l) {
getTypeTable(l,"UnityEngine.Bounds");
addMember(l,SetMinMax, "SetMinMax");
addMember(l,Encapsulate, "Encapsulate");
addMember(l,Expand, "Expand");
addMember(l,Intersects, "Intersects");
addMember(l,Contains, "Contains");
addMember(l,SqrDistance, "SqrDistance");
addMember(l,IntersectRay, "IntersectRay");
addMember(l,op_Equality, "op_Equality");
addMember(l,op_Inequality, "op_Inequality");
addMember(l,get_center, "get_center");
addMember(l,set_center, "set_center");
addMember(l,get_size, "get_size");
addMember(l,set_size, "set_size");
addMember(l,get_extents, "get_extents");
addMember(l,set_extents, "set_extents");
addMember(l,get_min, "get_min");
addMember(l,set_min, "set_min");
addMember(l,get_max, "get_max");
addMember(l,set_max, "set_max");
newType(l, constructor);
createTypeMetatable(l, typeof(UnityEngine.Bounds));
LuaDLL.lua_pop(l, 1);
}
}
| mit |
nakov/OpenJudgeSystem | Open Judge System/Tests/OJS.Workers.Checkers.Tests/CSharpCodeCheckerTests.cs | 5295 | namespace OJS.Workers.Checkers.Tests
{
using System;
using NUnit.Framework;
[TestFixture]
public class CSharpCodeCheckerTests
{
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void CallingCheckMethodBeforeSetParameterShouldThrowAnException()
{
var checker = new CSharpCodeChecker();
checker.Check(string.Empty, string.Empty, string.Empty, false);
}
[Test]
[ExpectedException(typeof(Exception))]
public void SetParameterThrowsExceptionWhenGivenInvalidCode()
{
var checker = new CSharpCodeChecker();
checker.SetParameter(@".");
}
[Test]
[ExpectedException(typeof(Exception))]
public void SetParameterThrowsExceptionWhenNotGivenICheckerImplementation()
{
var checker = new CSharpCodeChecker();
checker.SetParameter(@"public class MyChecker { }");
}
[Test]
[ExpectedException(typeof(Exception))]
public void SetParameterThrowsExceptionWhenGivenMoreThanOneICheckerImplementation()
{
var checker = new CSharpCodeChecker();
checker.SetParameter(@"
using OJS.Workers.Common;
public class MyChecker1 : IChecker
{
public CheckerResult Check(string inputData, string receivedOutput, string expectedOutput)
{
return new CheckerResult
{
IsCorrect = true,
ResultType = CheckerResultType.Ok,
CheckerDetails = new CheckerDetails(),
};
}
public void SetParameter(string parameter)
{
}
}
public class MyChecker2 : IChecker
{
public CheckerResult Check(string inputData, string receivedOutput, string expectedOutput)
{
return new CheckerResult
{
IsCorrect = true,
ResultType = CheckerResultType.Ok,
CheckerDetails = new CheckerDetails(),
};
}
public void SetParameter(string parameter)
{
}
}");
}
[Test]
public void CheckMethodWorksCorrectlyWithSomeCheckerCode()
{
var checker = new CSharpCodeChecker();
checker.SetParameter(@"
using OJS.Workers.Common;
public class MyChecker : IChecker
{
public CheckerResult Check(string inputData, string receivedOutput, string expectedOutput, bool isTrialTest)
{
return new CheckerResult
{
IsCorrect = true,
ResultType = CheckerResultType.Ok,
CheckerDetails = new CheckerDetails { Comment = ""It was me"" },
};
}
public void SetParameter(string parameter)
{
}
}");
var checkerResult = checker.Check(string.Empty, string.Empty, string.Empty, false);
Assert.IsNotNull(checkerResult);
Assert.IsTrue(checkerResult.IsCorrect);
Assert.AreEqual("It was me", checkerResult.CheckerDetails.Comment);
}
[Test]
public void CheckMethodReceivesCorrectParameters()
{
var checker = new CSharpCodeChecker();
checker.SetParameter(@"
using OJS.Workers.Common;
public class MyChecker : IChecker
{
public CheckerResult Check(string inputData, string receivedOutput, string expectedOutput, bool isTrialTest)
{
bool isCorrect = true;
if (inputData != ""One"") isCorrect = false;
if (receivedOutput != ""Two"") isCorrect = false;
if (expectedOutput != ""Three"") isCorrect = false;
return new CheckerResult
{
IsCorrect = isCorrect,
ResultType = CheckerResultType.Ok,
CheckerDetails = new CheckerDetails(),
};
}
public void SetParameter(string parameter)
{
}
}");
var checkerResult = checker.Check("One", "Two", "Three", false);
Assert.IsNotNull(checkerResult);
Assert.IsTrue(checkerResult.IsCorrect);
}
}
}
| mit |
quindar/quindar-ux | public/scripts/screenfull.js | 4129 | /*!
* screenfull
* v4.2.0 - 2019-04-01
* (c) Sindre Sorhus; MIT License
*/
(function () {
'use strict';
var document = typeof window !== 'undefined' && typeof window.document !== 'undefined' ? window.document : {};
var isCommonjs = typeof module !== 'undefined' && module.exports;
var keyboardAllowed = typeof Element !== 'undefined' && 'ALLOW_KEYBOARD_INPUT' in Element;
var fn = (function () {
var val;
var fnMap = [
[
'requestFullscreen',
'exitFullscreen',
'fullscreenElement',
'fullscreenEnabled',
'fullscreenchange',
'fullscreenerror'
],
// New WebKit
[
'webkitRequestFullscreen',
'webkitExitFullscreen',
'webkitFullscreenElement',
'webkitFullscreenEnabled',
'webkitfullscreenchange',
'webkitfullscreenerror'
],
// Old WebKit (Safari 5.1)
[
'webkitRequestFullScreen',
'webkitCancelFullScreen',
'webkitCurrentFullScreenElement',
'webkitCancelFullScreen',
'webkitfullscreenchange',
'webkitfullscreenerror'
],
[
'mozRequestFullScreen',
'mozCancelFullScreen',
'mozFullScreenElement',
'mozFullScreenEnabled',
'mozfullscreenchange',
'mozfullscreenerror'
],
[
'msRequestFullscreen',
'msExitFullscreen',
'msFullscreenElement',
'msFullscreenEnabled',
'MSFullscreenChange',
'MSFullscreenError'
]
];
var i = 0;
var l = fnMap.length;
var ret = {};
for (; i < l; i++) {
val = fnMap[i];
if (val && val[1] in document) {
for (i = 0; i < val.length; i++) {
ret[fnMap[0][i]] = val[i];
}
return ret;
}
}
return false;
})();
var eventNameMap = {
change: fn.fullscreenchange,
error: fn.fullscreenerror
};
var screenfull = {
request: function (elem) {
return new Promise(function (resolve) {
var request = fn.requestFullscreen;
var onFullScreenEntered = function () {
this.off('change', onFullScreenEntered);
resolve();
}.bind(this);
elem = elem || document.documentElement;
// Work around Safari 5.1 bug: reports support for
// keyboard in fullscreen even though it doesn't.
// Browser sniffing, since the alternative with
// setTimeout is even worse.
if (/ Version\/5\.1(?:\.\d+)? Safari\//.test(navigator.userAgent)) {
elem[request]();
} else {
elem[request](keyboardAllowed ? Element.ALLOW_KEYBOARD_INPUT : {});
}
this.on('change', onFullScreenEntered);
}.bind(this));
},
exit: function () {
return new Promise(function (resolve) {
if (!this.isFullscreen) {
resolve();
return;
}
var onFullScreenExit = function () {
this.off('change', onFullScreenExit);
resolve();
}.bind(this);
document[fn.exitFullscreen]();
this.on('change', onFullScreenExit);
}.bind(this));
},
toggle: function (elem) {
return this.isFullscreen ? this.exit() : this.request(elem);
},
onchange: function (callback) {
this.on('change', callback);
},
onerror: function (callback) {
this.on('error', callback);
},
on: function (event, callback) {
var eventName = eventNameMap[event];
if (eventName) {
document.addEventListener(eventName, callback, false);
}
},
off: function (event, callback) {
var eventName = eventNameMap[event];
if (eventName) {
document.removeEventListener(eventName, callback, false);
}
},
raw: fn
};
if (!fn) {
if (isCommonjs) {
module.exports = false;
} else {
window.screenfull = false;
}
return;
}
Object.defineProperties(screenfull, {
isFullscreen: {
get: function () {
return Boolean(document[fn.fullscreenElement]);
}
},
element: {
enumerable: true,
get: function () {
return document[fn.fullscreenElement];
}
},
enabled: {
enumerable: true,
get: function () {
// Coerce to boolean in case of old WebKit
return Boolean(document[fn.fullscreenEnabled]);
}
}
});
if (isCommonjs) {
module.exports = screenfull;
// TODO: remove this in the next major version
module.exports.default = screenfull;
} else {
window.screenfull = screenfull;
}
})();
| mit |
guileschool/beagleboard | u-boot/drivers/timer/omap-timer.c | 2818 | /*
* TI OMAP timer driver
*
* Copyright (C) 2015, Texas Instruments, Incorporated
*
* SPDX-License-Identifier: GPL-2.0+
*/
#include <common.h>
#include <dm.h>
#include <errno.h>
#include <timer.h>
#include <asm/io.h>
#include <asm/arch/clock.h>
DECLARE_GLOBAL_DATA_PTR;
/* Timer register bits */
#define TCLR_START BIT(0) /* Start=1 */
#define TCLR_AUTO_RELOAD BIT(1) /* Auto reload */
#define TCLR_PRE_EN BIT(5) /* Pre-scaler enable */
#define TCLR_PTV_SHIFT (2) /* Pre-scaler shift value */
#define TIMER_CLOCK (V_SCLK / (2 << CONFIG_SYS_PTV))
struct omap_gptimer_regs {
unsigned int tidr; /* offset 0x00 */
unsigned char res1[12];
unsigned int tiocp_cfg; /* offset 0x10 */
unsigned char res2[12];
unsigned int tier; /* offset 0x20 */
unsigned int tistatr; /* offset 0x24 */
unsigned int tistat; /* offset 0x28 */
unsigned int tisr; /* offset 0x2c */
unsigned int tcicr; /* offset 0x30 */
unsigned int twer; /* offset 0x34 */
unsigned int tclr; /* offset 0x38 */
unsigned int tcrr; /* offset 0x3c */
unsigned int tldr; /* offset 0x40 */
unsigned int ttgr; /* offset 0x44 */
unsigned int twpc; /* offset 0x48 */
unsigned int tmar; /* offset 0x4c */
unsigned int tcar1; /* offset 0x50 */
unsigned int tscir; /* offset 0x54 */
unsigned int tcar2; /* offset 0x58 */
};
/* Omap Timer Priv */
struct omap_timer_priv {
struct omap_gptimer_regs *regs;
};
static int omap_timer_get_count(struct udevice *dev, u64 *count)
{
struct omap_timer_priv *priv = dev_get_priv(dev);
*count = readl(&priv->regs->tcrr);
return 0;
}
static int omap_timer_probe(struct udevice *dev)
{
struct timer_dev_priv *uc_priv = dev_get_uclass_priv(dev);
struct omap_timer_priv *priv = dev_get_priv(dev);
uc_priv->clock_rate = TIMER_CLOCK;
/* start the counter ticking up, reload value on overflow */
writel(0, &priv->regs->tldr);
/* enable timer */
writel((CONFIG_SYS_PTV << 2) | TCLR_PRE_EN | TCLR_AUTO_RELOAD |
TCLR_START, &priv->regs->tclr);
return 0;
}
static int omap_timer_ofdata_to_platdata(struct udevice *dev)
{
struct omap_timer_priv *priv = dev_get_priv(dev);
priv->regs = map_physmem(devfdt_get_addr(dev),
sizeof(struct omap_gptimer_regs), MAP_NOCACHE);
return 0;
}
static const struct timer_ops omap_timer_ops = {
.get_count = omap_timer_get_count,
};
static const struct udevice_id omap_timer_ids[] = {
{ .compatible = "ti,am335x-timer" },
{ .compatible = "ti,am4372-timer" },
{ .compatible = "ti,omap5430-timer" },
{}
};
U_BOOT_DRIVER(omap_timer) = {
.name = "omap_timer",
.id = UCLASS_TIMER,
.of_match = omap_timer_ids,
.ofdata_to_platdata = omap_timer_ofdata_to_platdata,
.priv_auto_alloc_size = sizeof(struct omap_timer_priv),
.probe = omap_timer_probe,
.ops = &omap_timer_ops,
.flags = DM_FLAG_PRE_RELOC,
};
| mit |
john-mcnamara-intel/dpdk | examples/pipeline/obj.h | 2728 | /* SPDX-License-Identifier: BSD-3-Clause
* Copyright(c) 2020 Intel Corporation
*/
#ifndef _INCLUDE_OBJ_H_
#define _INCLUDE_OBJ_H_
#include <stdint.h>
#include <sys/queue.h>
#include <rte_mempool.h>
#include <rte_swx_pipeline.h>
#include <rte_swx_ctl.h>
#ifndef NAME_SIZE
#define NAME_SIZE 64
#endif
/*
* obj
*/
struct obj;
struct obj *
obj_init(void);
/*
* mempool
*/
struct mempool_params {
uint32_t buffer_size;
uint32_t pool_size;
uint32_t cache_size;
uint32_t cpu_id;
};
struct mempool {
TAILQ_ENTRY(mempool) node;
char name[NAME_SIZE];
struct rte_mempool *m;
uint32_t buffer_size;
};
struct mempool *
mempool_create(struct obj *obj,
const char *name,
struct mempool_params *params);
struct mempool *
mempool_find(struct obj *obj,
const char *name);
/*
* link
*/
#ifndef LINK_RXQ_RSS_MAX
#define LINK_RXQ_RSS_MAX 16
#endif
struct link_params_rss {
uint32_t queue_id[LINK_RXQ_RSS_MAX];
uint32_t n_queues;
};
struct link_params {
const char *dev_name;
uint16_t port_id; /**< Valid only when *dev_name* is NULL. */
struct {
uint32_t n_queues;
uint32_t queue_size;
const char *mempool_name;
struct link_params_rss *rss;
} rx;
struct {
uint32_t n_queues;
uint32_t queue_size;
} tx;
int promiscuous;
};
struct link {
TAILQ_ENTRY(link) node;
char name[NAME_SIZE];
char dev_name[NAME_SIZE];
uint16_t port_id;
uint32_t n_rxq;
uint32_t n_txq;
};
struct link *
link_create(struct obj *obj,
const char *name,
struct link_params *params);
int
link_is_up(struct obj *obj, const char *name);
struct link *
link_find(struct obj *obj, const char *name);
struct link *
link_next(struct obj *obj, struct link *link);
/*
* ring
*/
struct ring_params {
uint32_t size;
uint32_t numa_node;
};
struct ring {
TAILQ_ENTRY(ring) node;
char name[NAME_SIZE];
};
struct ring *
ring_create(struct obj *obj,
const char *name,
struct ring_params *params);
struct ring *
ring_find(struct obj *obj, const char *name);
/*
* tap
*/
struct tap {
TAILQ_ENTRY(tap) node;
char name[NAME_SIZE];
int fd;
};
struct tap *
tap_find(struct obj *obj, const char *name);
struct tap *
tap_next(struct obj *obj, struct tap *tap);
struct tap *
tap_create(struct obj *obj, const char *name);
/*
* pipeline
*/
struct pipeline {
TAILQ_ENTRY(pipeline) node;
char name[NAME_SIZE];
struct rte_swx_pipeline *p;
struct rte_swx_ctl_pipeline *ctl;
uint32_t timer_period_ms;
int enabled;
uint32_t thread_id;
uint32_t cpu_id;
};
struct pipeline *
pipeline_create(struct obj *obj,
const char *name,
int numa_node);
struct pipeline *
pipeline_find(struct obj *obj, const char *name);
#endif /* _INCLUDE_OBJ_H_ */
| mit |
DistributedOpenUnifiedGovernmentNetwork/mapwarper | coverage/app-controllers-passwords_controller_rb.html | 20975 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang='en' xml:lang='en' xmlns='http://www.w3.org/1999/xhtml'>
<head>
<title>
app/controllers/passwords_controller.rb - C0 code coverage information
</title>
<style type='text/css'>
body { background-color: rgb(240, 240, 245); }
</style>
<style type='text/css'>
span.cross-ref-title { font-size: 140%; } span.cross-ref a {
text-decoration: none; } span.cross-ref { background-color:#f3f7fa;
border: 1px dashed #333; margin: 1em; padding: 0.5em; overflow: hidden; }
a.crossref-toggle { text-decoration: none; } span.marked0 {
background-color: rgb(185, 210, 200); display: block; } span.marked1 {
background-color: rgb(190, 215, 205); display: block; } span.inferred0 {
background-color: rgb(175, 200, 200); display: block; } span.inferred1 {
background-color: rgb(180, 205, 205); display: block; } span.uncovered0 {
background-color: rgb(225, 110, 110); display: block; } span.uncovered1 {
background-color: rgb(235, 120, 120); display: block; } span.overview {
border-bottom: 8px solid black; } div.overview { border-bottom: 8px solid
black; } body { font-family: verdana, arial, helvetica; } div.footer {
font-size: 68%; margin-top: 1.5em; } h1, h2, h3, h4, h5, h6 {
margin-bottom: 0.5em; } h5 { margin-top: 0.5em; } .hidden { display: none;
} div.separator { height: 10px; } /* Commented out for better readability,
esp. on IE */ /* table tr td, table tr th { font-size: 68%; } td.value
table tr td { font-size: 11px; } */ table.percent_graph { height: 12px;
border: #808080 1px solid; empty-cells: show; } table.percent_graph
td.covered { height: 10px; background: #00f000; } table.percent_graph
td.uncovered { height: 10px; background: #e00000; } table.percent_graph
td.NA { height: 10px; background: #eaeaea; } table.report {
border-collapse: collapse; width: 100%; } table.report td.heading {
background: #dcecff; border: #d0d0d0 1px solid; font-weight: bold;
text-align: center; } table.report td.heading:hover { background: #c0ffc0;
} table.report td.text { border: #d0d0d0 1px solid; } table.report
td.value, table.report td.lines_total, table.report td.lines_code {
text-align: right; border: #d0d0d0 1px solid; } table.report tr.light {
background-color: rgb(240, 240, 245); } table.report tr.dark {
background-color: rgb(230, 230, 235); }
</style>
<script type='text/javascript'>
// <![CDATA[ function toggleCode( id ) { if ( document.getElementById )
elem = document.getElementById( id ); else if ( document.all ) elem =
eval( "document.all." + id ); else return false; elemStyle = elem.style;
if ( elemStyle.display != "block" ) { elemStyle.display = "block" } else {
elemStyle.display = "none" } return true; } // Make cross-references
hidden by default document.writeln( "<style
type=\"text/css\">span.cross-ref { display: none }</style>" ) // ]]>
</script>
<style type='text/css'>
span.run0 { background-color: rgb(178, 204, 255); display: block; }
span.run1 { background-color: rgb(178, 206, 255); display: block; }
span.run2 { background-color: rgb(178, 209, 255); display: block; }
span.run3 { background-color: rgb(178, 211, 255); display: block; }
span.run4 { background-color: rgb(178, 214, 255); display: block; }
span.run5 { background-color: rgb(178, 218, 255); display: block; }
span.run6 { background-color: rgb(178, 220, 255); display: block; }
span.run7 { background-color: rgb(178, 223, 255); display: block; }
span.run8 { background-color: rgb(178, 225, 255); display: block; }
span.run9 { background-color: rgb(178, 228, 255); display: block; }
span.run10 { background-color: rgb(178, 232, 255); display: block; }
span.run11 { background-color: rgb(178, 234, 255); display: block; }
span.run12 { background-color: rgb(178, 237, 255); display: block; }
span.run13 { background-color: rgb(178, 239, 255); display: block; }
span.run14 { background-color: rgb(178, 242, 255); display: block; }
span.run15 { background-color: rgb(178, 246, 255); display: block; }
span.run16 { background-color: rgb(178, 248, 255); display: block; }
span.run17 { background-color: rgb(178, 251, 255); display: block; }
span.run18 { background-color: rgb(178, 253, 255); display: block; }
span.run19 { background-color: rgb(178, 255, 253); display: block; }
span.run20 { background-color: rgb(178, 255, 249); display: block; }
span.run21 { background-color: rgb(178, 255, 247); display: block; }
span.run22 { background-color: rgb(178, 255, 244); display: block; }
span.run23 { background-color: rgb(178, 255, 242); display: block; }
span.run24 { background-color: rgb(178, 255, 239); display: block; }
span.run25 { background-color: rgb(178, 255, 235); display: block; }
span.run26 { background-color: rgb(178, 255, 233); display: block; }
span.run27 { background-color: rgb(178, 255, 230); display: block; }
span.run28 { background-color: rgb(178, 255, 228); display: block; }
span.run29 { background-color: rgb(178, 255, 225); display: block; }
span.run30 { background-color: rgb(178, 255, 221); display: block; }
span.run31 { background-color: rgb(178, 255, 219); display: block; }
span.run32 { background-color: rgb(178, 255, 216); display: block; }
span.run33 { background-color: rgb(178, 255, 214); display: block; }
span.run34 { background-color: rgb(178, 255, 211); display: block; }
span.run35 { background-color: rgb(178, 255, 207); display: block; }
span.run36 { background-color: rgb(178, 255, 205); display: block; }
span.run37 { background-color: rgb(178, 255, 202); display: block; }
span.run38 { background-color: rgb(178, 255, 200); display: block; }
span.run39 { background-color: rgb(178, 255, 197); display: block; }
span.run40 { background-color: rgb(178, 255, 193); display: block; }
span.run41 { background-color: rgb(178, 255, 191); display: block; }
span.run42 { background-color: rgb(178, 255, 188); display: block; }
span.run43 { background-color: rgb(178, 255, 186); display: block; }
span.run44 { background-color: rgb(178, 255, 183); display: block; }
span.run45 { background-color: rgb(178, 255, 179); display: block; }
span.run46 { background-color: rgb(179, 255, 178); display: block; }
span.run47 { background-color: rgb(182, 255, 178); display: block; }
span.run48 { background-color: rgb(184, 255, 178); display: block; }
span.run49 { background-color: rgb(187, 255, 178); display: block; }
span.run50 { background-color: rgb(191, 255, 178); display: block; }
span.run51 { background-color: rgb(193, 255, 178); display: block; }
span.run52 { background-color: rgb(196, 255, 178); display: block; }
span.run53 { background-color: rgb(198, 255, 178); display: block; }
span.run54 { background-color: rgb(201, 255, 178); display: block; }
span.run55 { background-color: rgb(205, 255, 178); display: block; }
span.run56 { background-color: rgb(207, 255, 178); display: block; }
span.run57 { background-color: rgb(210, 255, 178); display: block; }
span.run58 { background-color: rgb(212, 255, 178); display: block; }
span.run59 { background-color: rgb(215, 255, 178); display: block; }
span.run60 { background-color: rgb(219, 255, 178); display: block; }
span.run61 { background-color: rgb(221, 255, 178); display: block; }
span.run62 { background-color: rgb(224, 255, 178); display: block; }
span.run63 { background-color: rgb(226, 255, 178); display: block; }
span.run64 { background-color: rgb(229, 255, 178); display: block; }
span.run65 { background-color: rgb(233, 255, 178); display: block; }
span.run66 { background-color: rgb(235, 255, 178); display: block; }
span.run67 { background-color: rgb(238, 255, 178); display: block; }
span.run68 { background-color: rgb(240, 255, 178); display: block; }
span.run69 { background-color: rgb(243, 255, 178); display: block; }
span.run70 { background-color: rgb(247, 255, 178); display: block; }
span.run71 { background-color: rgb(249, 255, 178); display: block; }
span.run72 { background-color: rgb(252, 255, 178); display: block; }
span.run73 { background-color: rgb(255, 255, 178); display: block; }
span.run74 { background-color: rgb(255, 252, 178); display: block; }
span.run75 { background-color: rgb(255, 248, 178); display: block; }
span.run76 { background-color: rgb(255, 246, 178); display: block; }
span.run77 { background-color: rgb(255, 243, 178); display: block; }
span.run78 { background-color: rgb(255, 240, 178); display: block; }
span.run79 { background-color: rgb(255, 238, 178); display: block; }
span.run80 { background-color: rgb(255, 234, 178); display: block; }
span.run81 { background-color: rgb(255, 232, 178); display: block; }
span.run82 { background-color: rgb(255, 229, 178); display: block; }
span.run83 { background-color: rgb(255, 226, 178); display: block; }
span.run84 { background-color: rgb(255, 224, 178); display: block; }
span.run85 { background-color: rgb(255, 220, 178); display: block; }
span.run86 { background-color: rgb(255, 218, 178); display: block; }
span.run87 { background-color: rgb(255, 215, 178); display: block; }
span.run88 { background-color: rgb(255, 212, 178); display: block; }
span.run89 { background-color: rgb(255, 210, 178); display: block; }
span.run90 { background-color: rgb(255, 206, 178); display: block; }
span.run91 { background-color: rgb(255, 204, 178); display: block; }
span.run92 { background-color: rgb(255, 201, 178); display: block; }
span.run93 { background-color: rgb(255, 198, 178); display: block; }
span.run94 { background-color: rgb(255, 196, 178); display: block; }
span.run95 { background-color: rgb(255, 192, 178); display: block; }
span.run96 { background-color: rgb(255, 189, 178); display: block; }
span.run97 { background-color: rgb(255, 187, 178); display: block; }
span.run98 { background-color: rgb(255, 184, 178); display: block; }
span.run99 { background-color: rgb(255, 182, 178); display: block; }
span.run100 { background-color: rgb(255, 178, 178); display: block; }
</style>
</head>
<body>
<h3>
C0 code coverage information
</h3>
<p>
Generated on Mon Mar 02 12:22:13 +0000 2009 with
<a href='http://eigenclass.org/hiki/rcov'>
rcov 0.8.1.2
</a>
</p>
<hr />
<pre><span class='marked0'>Code reported as executed by Ruby looks like
this... </span><span class='marked1'>and this: this line is also marked as
covered. </span><span class='inferred0'>Lines considered as run by rcov, but
not reported by Ruby, look like this, </span><span class='inferred1'>and
this: these lines were inferred by rcov (using simple heuristics).
</span><span class='uncovered0'>Finally, here's a line marked as not
executed. </span></pre>
<table class='report'> <thead> <tr> <td class='heading'> Name </td> <td
class='heading'> Total lines </td> <td class='heading'> Lines of code </td>
<td class='heading'> Total coverage </td> <td class='heading'> Code coverage
</td> </tr> </thead> <tbody> <tr class='light'> <td> <a
href='app-controllers-passwords_controller_rb.html'>
app/controllers/passwords_controller.rb </a> </td> <td class='lines_total'>
<tt> 80 </tt> </td> <td class='lines_code'> <tt> 59 </tt> </td> <td> <table
cellspacing='0' align='right' cellpadding='0'> <tr> <td> <tt
class='coverage_total'> 26.2% </tt> </td> <td> <table
class='percent_graph' cellspacing='0' width='100' cellpadding='0'> <tr> <td
class='covered' width='26' /> <td class='uncovered' width='74' /> </tr>
</table> </td> </tr> </table> </td> <td> <table cellspacing='0'
align='right' cellpadding='0'> <tr> <td> <tt class='coverage_code'> 13.6%
</tt> </td> <td> <table class='percent_graph' cellspacing='0'
width='100' cellpadding='0'> <tr> <td class='covered' width='14' /> <td
class='uncovered' width='86' /> </tr> </table> </td> </tr> </table> </td>
</tr> </tbody> </table><pre><span class="marked1"><a name="line1"></a> 1
class PasswordsController < ApplicationController </span><span
class="marked0"><a name="line2"></a> 2 layout "application"
</span><span class="marked1"><a name="line3"></a> 3 before_filter
:not_logged_in_required, :only => [:new, :create] </span><span
class="inferred0"><a name="line4"></a> 4 </span><span class="inferred1"><a
name="line5"></a> 5 # Enter email address to recover password </span><span
class="marked0"><a name="line6"></a> 6 def new </span><span
class="inferred1"><a name="line7"></a> 7 end </span><span
class="inferred0"><a name="line8"></a> 8 </span><span class="inferred1"><a
name="line9"></a> 9 # Forgot password action </span><span class="marked0"><a
name="line10"></a>10 def create </span><span class="uncovered1"><a
name="line11"></a>11 return unless request.post? </span><span
class="uncovered0"><a name="line12"></a>12 if @user =
User.find_for_forget(params[:email]) </span><span class="uncovered1"><a
name="line13"></a>13 @user.forgot_password </span><span
class="uncovered0"><a name="line14"></a>14 @user.save </span><span
class="uncovered1"><a name="line15"></a>15 flash[:notice] = "A password
reset link has been sent to your email address." </span><span
class="uncovered0"><a name="line16"></a>16 redirect_to login_path
</span><span class="uncovered1"><a name="line17"></a>17 else </span><span
class="uncovered0"><a name="line18"></a>18 flash[:notice] = "Could not
find a user with that email address." </span><span
class="uncovered1"><a name="line19"></a>19 render :action =>
"new" </span><span class="uncovered0"><a name="line20"></a>20 end
</span><span class="uncovered1"><a name="line21"></a>21 end </span><span
class="inferred0"><a name="line22"></a>22 </span><span class="inferred1"><a
name="line23"></a>23 # Action triggered by clicking on the
/reset_password/:id link recieved via email </span><span
class="inferred0"><a name="line24"></a>24 # Makes sure the id code is
included </span><span class="inferred1"><a name="line25"></a>25 # Checks
that the id code matches a user in the database </span><span
class="inferred0"><a name="line26"></a>26 # Then if everything checks out,
shows the password reset fields </span><span class="marked1"><a
name="line27"></a>27 def edit </span><span class="uncovered0"><a
name="line28"></a>28 if params[:id].nil? </span><span class="uncovered1"><a
name="line29"></a>29 render :action => "new" </span><span
class="uncovered0"><a name="line30"></a>30 return </span><span
class="uncovered1"><a name="line31"></a>31 end </span><span
class="uncovered0"><a name="line32"></a>32 @user =
User.find_by_password_reset_code(params[:id]) if params[:id] </span><span
class="uncovered1"><a name="line33"></a>33 raise if @user.nil? </span><span
class="uncovered0"><a name="line34"></a>34 rescue </span><span
class="uncovered1"><a name="line35"></a>35 logger.error "Invalid Reset
Code entered." </span><span class="uncovered0"><a name="line36"></a>36
flash[:notice] = "Sorry - That is an invalid password reset code.
Please check your code and try again. (Perhaps your email client inserted a
carriage return?)" </span><span class="uncovered1"><a
name="line37"></a>37 </span><span class="uncovered0"><a name="line38"></a>38
redirect_to new_user_path </span><span class="uncovered1"><a
name="line39"></a>39 end </span><span class="inferred0"><a
name="line40"></a>40 </span><span class="inferred1"><a name="line41"></a>41
</span><span class="inferred0"><a name="line42"></a>42 # Reset password
action /reset_password/:id </span><span class="inferred1"><a
name="line43"></a>43 # Checks once again that an id is included and makes
sure that the password field isn’t blank </span><span class="marked0"><a
name="line44"></a>44 def update </span><span class="uncovered1"><a
name="line45"></a>45 if params[:id].nil? </span><span class="uncovered0"><a
name="line46"></a>46 render :action => "new" </span><span
class="uncovered1"><a name="line47"></a>47 return </span><span
class="uncovered0"><a name="line48"></a>48 end </span><span
class="uncovered1"><a name="line49"></a>49 if params[:password].blank?
</span><span class="uncovered0"><a name="line50"></a>50 flash[:notice] =
"Password field cannot be blank." </span><span
class="uncovered1"><a name="line51"></a>51 render :action =>
"edit", :id => params[:id] </span><span class="uncovered0"><a
name="line52"></a>52 return </span><span class="uncovered1"><a
name="line53"></a>53 end </span><span class="uncovered0"><a
name="line54"></a>54 @user = User.find_by_password_reset_code(params[:id])
if params[:id] </span><span class="uncovered1"><a name="line55"></a>55 raise
if @user.nil? </span><span class="uncovered0"><a name="line56"></a>56 return
if @user unless params[:password] </span><span class="uncovered1"><a
name="line57"></a>57 if (params[:password] ==
params[:password_confirmation]) </span><span class="uncovered0"><a
name="line58"></a>58 #Uncomment and comment lines with @user to have the
user logged in after reset - not recommended </span><span
class="uncovered1"><a name="line59"></a>59 #self.current_user = @user #for
the next two lines to work </span><span class="uncovered0"><a
name="line60"></a>60 #current_user.password_confirmation =
params[:password_confirmation] </span><span class="uncovered1"><a
name="line61"></a>61 #current_user.password = params[:password] </span><span
class="uncovered0"><a name="line62"></a>62 #@user.reset_password
</span><span class="uncovered1"><a name="line63"></a>63 #flash[:notice] =
current_user.save ? "Password reset" : "Password not
reset" </span><span class="uncovered0"><a name="line64"></a>64
@user.password_confirmation = params[:password_confirmation] </span><span
class="uncovered1"><a name="line65"></a>65 @user.password =
params[:password] </span><span class="uncovered0"><a name="line66"></a>66
@user.reset_password </span><span class="uncovered1"><a name="line67"></a>67
flash[:notice] = @user.save ? "Password reset." : "Password
not reset." </span><span class="uncovered0"><a name="line68"></a>68
else </span><span class="uncovered1"><a name="line69"></a>69 flash[:notice]
= "Password mismatch." </span><span class="uncovered0"><a
name="line70"></a>70 render :action => "edit", :id =>
params[:id] </span><span class="uncovered1"><a name="line71"></a>71 return
</span><span class="uncovered0"><a name="line72"></a>72 end </span><span
class="uncovered1"><a name="line73"></a>73 redirect_to login_path
</span><span class="uncovered0"><a name="line74"></a>74 rescue </span><span
class="uncovered1"><a name="line75"></a>75 logger.error "Invalid Reset
Code entered" </span><span class="uncovered0"><a name="line76"></a>76
flash[:notice] = "Sorry - That is an invalid password reset code.
Please check your code and try again. (Perhaps your email client inserted a
carriage return?)" </span><span class="uncovered1"><a
name="line77"></a>77 redirect_to new_user_path </span><span
class="uncovered0"><a name="line78"></a>78 end </span><span
class="uncovered1"><a name="line79"></a>79 </span><span
class="uncovered0"><a name="line80"></a>80 end </span></pre>
<hr />
<p> Generated using the <a href='http://eigenclass.org/hiki.rb?rcov'> rcov
code coverage analysis tool for Ruby </a> version 0.8.1.2. </p>
<p>
<a href='http://validator.w3.org/check/referer'>
<img src='http://www.w3.org/Icons/valid-xhtml10' height='31' alt='Valid XHTML 1.0!' width='88' />
</a>
<a href='http://jigsaw.w3.org/css-validator/check/referer'>
<img src='http://jigsaw.w3.org/css-validator/images/vcss' alt='Valid CSS!' style='border:0;width:88px;height:31px' />
</a>
</p>
</body>
</html>
| mit |
alkuzad/spinach | features/steps/exit_status.rb | 594 | class ExitStatus < Spinach::FeatureSteps
feature "Exit status"
include Integration::SpinachRunner
Given "I have a feature that has no error or failure" do
@feature = Integration::FeatureGenerator.success_feature
end
Given "I have a feature that has a failure" do
@feature = Integration::FeatureGenerator.failure_feature
end
When "I run it" do
run_feature @feature
end
Then "the exit status should be 0" do
@last_exit_status.success?.must_equal true
end
Then "the exit status should be 1" do
@last_exit_status.success?.must_equal false
end
end
| mit |
begriffs/strong_parameters | lib/generators/rails/strong_parameters_controller_generator.rb | 520 | require 'rails/version'
require 'rails/generators/rails/scaffold_controller/scaffold_controller_generator'
module Rails
module Generators
class StrongParametersControllerGenerator < ScaffoldControllerGenerator
argument :attributes, :type => :array, :default => [], :banner => "field:type field:type"
source_root File.expand_path("../templates", __FILE__)
if ::Rails::VERSION::STRING < '3.1'
def module_namespacing
yield if block_given?
end
end
end
end
end
| mit |
flavour/eden | static/styles/plugins/fancyzoom.css | 578 | #zoom { position: absolute; display: none; z-index: 499; -webkit-box-shadow: 0px 5px 25px #000; -moz-box-shadow: 0px 5px 25px #000; box-shadow: 0px 5px 25px #000; }
#zoom_img { display: block; cursor: pointer; width: 100%; border: 0; margin: 0; padding: 0; }
#zoom_close { position: absolute; display: none; cursor: pointer; left: -15px; top: -15px; width: 30px; height: 30px; background: url(../../img/zoom/closebox.png) no-repeat; }
#zoom_spin { position: absolute; display: none; z-index: 525; width: 50px; height: 50px; background: url(../../img/zoom/spin.png) no-repeat; }
| mit |
tobyclemson/msci-project | vendor/poi-3.6/src/java/org/apache/poi/hssf/usermodel/HSSFSimpleShape.java | 3641 | /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You 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 org.apache.poi.hssf.usermodel;
/**
* Represents a simple shape such as a line, rectangle or oval.
*
* @author Glen Stampoultzis (glens at apache.org)
*/
public class HSSFSimpleShape
extends HSSFShape
{
// The commented out ones haven't been tested yet or aren't supported
// by HSSFSimpleShape.
public final static short OBJECT_TYPE_LINE = 1;
public final static short OBJECT_TYPE_RECTANGLE = 2;
public final static short OBJECT_TYPE_OVAL = 3;
// public final static short OBJECT_TYPE_ARC = 4;
// public final static short OBJECT_TYPE_CHART = 5;
// public final static short OBJECT_TYPE_TEXT = 6;
// public final static short OBJECT_TYPE_BUTTON = 7;
public final static short OBJECT_TYPE_PICTURE = 8;
// public final static short OBJECT_TYPE_POLYGON = 9;
// public final static short OBJECT_TYPE_CHECKBOX = 11;
// public final static short OBJECT_TYPE_OPTION_BUTTON = 12;
// public final static short OBJECT_TYPE_EDIT_BOX = 13;
// public final static short OBJECT_TYPE_LABEL = 14;
// public final static short OBJECT_TYPE_DIALOG_BOX = 15;
// public final static short OBJECT_TYPE_SPINNER = 16;
// public final static short OBJECT_TYPE_SCROLL_BAR = 17;
// public final static short OBJECT_TYPE_LIST_BOX = 18;
// public final static short OBJECT_TYPE_GROUP_BOX = 19;
// public final static short OBJECT_TYPE_COMBO_BOX = 20;
public final static short OBJECT_TYPE_COMMENT = 25;
// public final static short OBJECT_TYPE_MICROSOFT_OFFICE_DRAWING = 30;
int shapeType = OBJECT_TYPE_LINE;
HSSFSimpleShape( HSSFShape parent, HSSFAnchor anchor )
{
super( parent, anchor );
}
/**
* Gets the shape type.
* @return One of the OBJECT_TYPE_* constants.
*
* @see #OBJECT_TYPE_LINE
* @see #OBJECT_TYPE_OVAL
* @see #OBJECT_TYPE_RECTANGLE
* @see #OBJECT_TYPE_PICTURE
* @see #OBJECT_TYPE_COMMENT
*/
public int getShapeType() { return shapeType; }
/**
* Sets the shape types.
*
* @param shapeType One of the OBJECT_TYPE_* constants.
*
* @see #OBJECT_TYPE_LINE
* @see #OBJECT_TYPE_OVAL
* @see #OBJECT_TYPE_RECTANGLE
* @see #OBJECT_TYPE_PICTURE
* @see #OBJECT_TYPE_COMMENT
*/
public void setShapeType( int shapeType ){ this.shapeType = shapeType; }
}
| mit |
nawawi/poedit | deps/boost/libs/test/doc/html/boost/unit_test/static_constant.html | 4236 | <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Struct template static_constant</title>
<link rel="stylesheet" href="../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../index.html" title="Boost.Test">
<link rel="up" href="../../header/boost/test/detail/global_typedef_hpp.html" title="Header <boost/test/detail/global_typedef.hpp>">
<link rel="prev" href="../../header/boost/test/detail/global_typedef_hpp.html" title="Header <boost/test/detail/global_typedef.hpp>">
<link rel="next" href="INV_TEST_UNIT_ID.html" title="Global INV_TEST_UNIT_ID">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../../header/boost/test/detail/global_typedef_hpp.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../header/boost/test/detail/global_typedef_hpp.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="INV_TEST_UNIT_ID.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.unit_test.static_constant"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Struct template static_constant</span></h2>
<p>boost::unit_test::static_constant</p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../header/boost/test/detail/global_typedef_hpp.html" title="Header <boost/test/detail/global_typedef.hpp>">boost/test/detail/global_typedef.hpp</a>>
</span><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> T<span class="special">></span>
<span class="keyword">struct</span> <a class="link" href="static_constant.html" title="Struct template static_constant">static_constant</a> <span class="special">{</span>
<span class="comment">// public data members</span>
<span class="keyword">static</span> <span class="identifier">T</span> <span class="identifier">value</span><span class="special">;</span>
<span class="special">}</span><span class="special">;</span></pre></div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2001-2018 Boost.Test contributors<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../../header/boost/test/detail/global_typedef_hpp.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../header/boost/test/detail/global_typedef_hpp.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="INV_TEST_UNIT_ID.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| mit |
jjz/Haraka | tests/utils.js | 12700 | var stub = require('./fixtures/stub'),
constants = require('./../constants'),
Logger = require('./fixtures/stub_logger'),
utils = require('./../utils');
// huge hack here, but plugin tests need constants
constants.import(global);
function _set_up(callback) {
this.backup = {};
callback();
}
function _tear_down(callback) {
callback();
}
exports.utils = {
setUp : _set_up,
tearDown : _tear_down,
'plain ascii should not be encoded' : function (test) {
test.expect(1);
test.equals(utils.encode_qp('quoted printable'), 'quoted printable');
test.done();
},
'8-bit chars should be encoded' : function (test) {
test.expect(1);
test.equals(
utils.encode_qp(
'v\xe5re kj\xe6re norske tegn b\xf8r \xe6res'
),
'v=E5re kj=E6re norske tegn b=F8r =E6res');
test.done();
},
'trailing space should be encoded' : function (test) {
test.expect(5);
test.equals(utils.encode_qp(' '), '=20=20');
test.equals(utils.encode_qp('\tt\t'), '\tt=09');
test.equals(
utils.encode_qp('test \ntest\n\t \t \n'),
'test=20=20\ntest\n=09=20=09=20\n'
);
test.equals(utils.encode_qp("foo \t "), "foo=20=09=20");
test.equals(utils.encode_qp("foo\t \n \t"), "foo=09=20\n=20=09");
test.done();
},
'trailing space should be decoded unless newline' : function (test) {
test.expect(2);
test.deepEqual(utils.decode_qp("foo "), new Buffer("foo "));
test.deepEqual(utils.decode_qp("foo \n"), new Buffer("foo\n"));
test.done();
},
'"=" is special and should be decoded' : function (test) {
test.expect(2);
test.equals(utils.encode_qp("=30\n"), "=3D30\n");
test.equals(utils.encode_qp("\0\xff0"), "=00=FF0");
test.done();
},
'Very long lines should be broken' : function (test) {
test.expect(1);
test.equals(utils.encode_qp("The Quoted-Printable encoding is intended to represent data that largly consists of octets that correspond to printable characters in the ASCII character set."), "The Quoted-Printable encoding is intended to represent data that largly con=\nsists of octets that correspond to printable characters in the ASCII charac=\nter set.");
test.done();
},
'multiple long lines' : function (test) {
test.expect(1);
test.equals(utils.encode_qp("College football is a game which would be much more interesting if the faculty played instead of the students, and even more interesting if the\ntrustees played. There would be a great increase in broken arms, legs, and necks, and simultaneously an appreciable diminution in the loss to humanity. -- H. L. Mencken"), "College football is a game which would be much more interesting if the facu=\nlty played instead of the students, and even more interesting if the\ntrustees played. There would be a great increase in broken arms, legs, and=\n necks, and simultaneously an appreciable diminution in the loss to humanit=\ny. -- H. L. Mencken");
test.done();
},
"Don't break a line that's near but not over 76 chars" : function (test) {
var buffer = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" +
"xxxxxxxxxxxxxxxxxx";
test.equals(utils.encode_qp(buffer+"123"), buffer+"123");
test.equals(utils.encode_qp(buffer+"1234"), buffer+"1234");
test.equals(utils.encode_qp(buffer+"12345"), buffer+"12345");
test.equals(utils.encode_qp(buffer+"123456"), buffer+"123456");
test.equals(utils.encode_qp(buffer+"1234567"), buffer+"12345=\n67");
test.equals(utils.encode_qp(buffer+"123456="), buffer+"12345=\n6=3D");
test.equals(utils.encode_qp(buffer+"123\n"), buffer+"123\n");
test.equals(utils.encode_qp(buffer+"1234\n"), buffer+"1234\n");
test.equals(utils.encode_qp(buffer+"12345\n"), buffer+"12345\n");
test.equals(utils.encode_qp(buffer+"123456\n"), buffer+"123456\n");
test.equals(utils.encode_qp(buffer+"1234567\n"), buffer+"12345=\n67\n");
test.equals(
utils.encode_qp(buffer+"123456=\n"), buffer+"12345=\n6=3D\n"
);
test.done();
},
'Not allowed to break =XX escapes using soft line break' : function (test) {
test.expect(10);
var buffer = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" +
"xxxxxxxxxxxxxxxxxx";
test.equals(
utils.encode_qp(buffer+"===xxxxx"), buffer+"=3D=\n=3D=3Dxxxxx"
);
test.equals(
utils.encode_qp(buffer+"1===xxxx"), buffer+"1=3D=\n=3D=3Dxxxx"
);
test.equals(
utils.encode_qp(buffer+"12===xxx"), buffer+"12=3D=\n=3D=3Dxxx"
);
test.equals(
utils.encode_qp(buffer+"123===xx"), buffer+"123=\n=3D=3D=3Dxx"
);
test.equals(
utils.encode_qp(buffer+"1234===x"), buffer+"1234=\n=3D=3D=3Dx"
);
test.equals(utils.encode_qp(buffer+"12=\n"), buffer+"12=3D\n");
test.equals(utils.encode_qp(buffer+"123=\n"), buffer+"123=\n=3D\n");
test.equals(utils.encode_qp(buffer+"1234=\n"), buffer+"1234=\n=3D\n");
test.equals(utils.encode_qp(buffer+"12345=\n"), buffer+"12345=\n=3D\n");
test.equals(
utils.encode_qp(buffer+"123456=\n"), buffer+"12345=\n6=3D\n"
);
test.done();
},
'some extra special cases we have had problems with' : function (test) {
test.expect(2);
var buffer = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" +
"xxxxxxxxxxxxxxxxxx";
test.equals(utils.encode_qp(buffer+"12=x=x"), buffer+"12=3D=\nx=3Dx");
test.equals(
utils.encode_qp(buffer+"12345"+buffer+"12345"+buffer+"123456\n"),
buffer+"12345=\n"+buffer+"12345=\n"+buffer+"123456\n"
);
test.done();
},
'regression test 01' : function (test) {
test.expect(1);
test.deepEqual(
utils.decode_qp("foo \n\nfoo =\n\nfoo=20\n\n"),
new Buffer("foo\n\nfoo \nfoo \n\n")
);
test.done();
},
'regression test 01 with CRLF' : function (test) {
test.expect(1);
test.deepEqual(
utils.decode_qp("foo \r\n\r\nfoo =\r\n\r\nfoo=20\r\n\r\n"),
new Buffer("foo\n\nfoo \nfoo \n\n")
);
test.done();
},
'regression test 02' : function (test) {
test.expect(1);
test.deepEqual(
utils.decode_qp("foo = \t\x20\nbar\t\x20\n"),
new Buffer("foo bar\n")
);
test.done();
},
'regression test 02 with CRLF' : function (test) {
test.expect(1);
test.deepEqual(
utils.decode_qp("foo = \t\x20\r\nbar\t\x20\r\n"),
new Buffer("foo bar\n")
);
test.done();
},
'regression test 03' : function (test) {
test.expect(1);
test.deepEqual(
utils.decode_qp("foo = \t\x20\n"), new Buffer("foo ")
);
test.done();
},
'regression test 03 with CRLF' : function (test) {
test.expect(1);
test.deepEqual(
utils.decode_qp("foo = \t\x20\r\n"), new Buffer("foo ")
);
test.done();
},
'regression test 04 from CRLF to LF' : function (test) {
test.expect(1);
test.deepEqual(
utils.decode_qp("foo = \t\x20y\r\n"), new Buffer("foo = \t\x20y\n")
);
test.done();
},
'regression test 05 should be the same' : function (test) {
test.expect(1);
test.deepEqual(
utils.decode_qp("foo =xy\n"), new Buffer("foo =xy\n")
);
test.done();
},
'spin encode_qp()' : function (test) {
var spin = 10000;
test.expect(spin);
for (var i = 0; i < spin; i++) {
test.equals(
utils.encode_qp("quoted printable"), "quoted printable"
);
}
test.done();
}
};
exports.valid_regexes = {
setUp : _set_up,
tearDown : _tear_down,
'two valid': function (test) {
var re_list = ['.*\.exam.ple','.*\.example.com'];
test.expect(1);
test.deepEqual(re_list, utils.valid_regexes(re_list));
test.done();
},
'one valid, one invalid': function (test) {
var re_list = ['*\.exam.ple','.*\.example.com'];
test.expect(1);
test.deepEqual(['.*\.example.com'], utils.valid_regexes(re_list));
test.done();
},
'one valid, two invalid': function (test) {
var re_list = ['[', '*\.exam.ple','.*\.example.com'];
test.expect(1);
test.deepEqual(['.*\.example.com'], utils.valid_regexes(re_list));
test.done();
},
};
exports.base64 = {
setUp : _set_up,
tearDown : _tear_down,
'base64': function (test) {
test.expect(1);
test.equal(utils.base64('matt the tester'), 'bWF0dCB0aGUgdGVzdGVy');
test.done();
},
'unbase64': function (test) {
test.expect(1);
test.equal(utils.unbase64('bWF0dCB0aGUgdGVzdGVy'), 'matt the tester');
test.done();
}
};
exports.to_object = {
setUp : _set_up,
tearDown : _tear_down,
'string': function (test) {
test.expect(1);
test.deepEqual(utils.to_object('matt,test'),
{ matt: true, test: true }
);
test.done();
},
'array': function (test) {
test.expect(1);
test.deepEqual(utils.to_object(['matt','test']),
{ matt: true, test: true }
);
test.done();
},
};
exports.extend = {
'copies properties from one object': function (test) {
test.expect(1);
var both = utils.extend({first: 'boo'}, {second: 'ger'});
test.deepEqual({first: 'boo', second: 'ger'}, both);
test.done();
},
'copies properties from multiple objects': function (test) {
test.expect(1);
test.deepEqual(
utils.extend(
{first: 'boo'}, {second: 'ger'}, {third: 'eat'}
),
{first: 'boo', second: 'ger', third: 'eat'}
);
test.done();
},
};
exports.node_min = {
'node is new enough': function (test) {
test.expect(6);
test.ok(utils.node_min('0.8.0', '0.10.0'));
test.ok(utils.node_min('0.10.0', '0.10.0'));
test.ok(utils.node_min('0.10.0', '0.10.1'));
test.ok(utils.node_min('0.10.0', '0.12.0'));
test.ok(utils.node_min('0.10.0', '1.0.0'));
test.ok(utils.node_min('0.10', '1.0'));
test.done();
},
'node is too old': function (test) {
test.expect(4);
test.ok(!utils.node_min('0.12.0', '0.10.0'));
test.ok(!utils.node_min('1.0.0', '0.8.0'));
test.ok(!utils.node_min('1.0.0', '0.10.0'));
test.ok(!utils.node_min('1.0.0', '0.12.0'));
test.done();
},
};
exports.elapsed = {
'returns 0 decimal places': function (test) {
test.expect(1);
var start = new Date();
start.setTime(start.getTime() - 3517); // 3.517 seconds ago
test.strictEqual(utils.elapsed(start, 0), '4');
test.done();
},
'returns 1 decimal place': function (test) {
test.expect(1);
var start = new Date();
start.setTime(start.getTime() - 3517); // 3.517 seconds ago
test.strictEqual(utils.elapsed(start, 1), '3.5');
test.done();
},
'returns 2 decimal places': function (test) {
test.expect(1);
var start = new Date();
start.setTime(start.getTime() - 3517); // 3.517 seconds ago
test.strictEqual(utils.elapsed(start, 2), '3.52');
test.done();
},
'default N > 5 has 0 decimal places': function (test) {
test.expect(1);
var start = new Date();
start.setTime(start.getTime() - 13517); // 3.517 seconds ago
test.strictEqual(utils.elapsed(start), '14');
test.done();
},
'default N > 2 has 1 decimal places': function (test) {
test.expect(1);
var start = new Date();
start.setTime(start.getTime() - 3517); // 3.517 seconds ago
test.strictEqual(utils.elapsed(start), '3.5');
test.done();
},
'default has 2 decimal places': function (test) {
test.expect(1);
var start = new Date();
start.setTime(start.getTime() - 1517); // 3.517 seconds ago
test.strictEqual(utils.elapsed(start), '1.52');
test.done();
},
};
| mit |
romainmnr/chatboteseo | node_modules/webworker-threads/src/load.js | 558 | // Generated by LiveScript 1.5.0
var onmessage, this$ = this;
function addEventListener(event, cb){
return this.thread.on(event, cb);
}
function close(){
return this.thread.emit('close');
}
function importScripts(){
var i$, len$, p, results$ = [];
for (i$ = 0, len$ = (arguments).length; i$ < len$; ++i$) {
p = (arguments)[i$];
results$.push(self.eval(native_fs_.readFileSync(p, 'utf8')));
}
return results$;
}
onmessage = null;
thread.on('message', function(args){
return typeof onmessage == 'function' ? onmessage(args) : void 8;
});
| mit |
phphatesme/LiveTest | src/lib/Zend/Form/Decorator/Captcha/Word.php | 2410 | <?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Form
* @subpackage Decorator
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
/**
* @namespace
*/
namespace Zend\Form\Decorator\Captcha;
use Zend\Form\Decorator\AbstractDecorator;
/**
* Word-based captcha decorator
*
* Adds hidden field for ID and text input field for captcha text
*
* @uses \Zend\Form\Decorator\AbstractDecorator
* @category Zend
* @package Zend_Form
* @subpackage Element
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Word extends AbstractDecorator
{
/**
* Render captcha
*
* @param string $content
* @return string
*/
public function render($content)
{
$element = $this->getElement();
$view = $element->getView();
if (null === $view) {
return $content;
}
$name = $element->getFullyQualifiedName();
$hiddenName = $name . '[id]';
$textName = $name . '[input]';
$label = $element->getDecorator("Label");
if($label) {
$label->setOption("id", $element->getId()."-input");
}
$placement = $this->getPlacement();
$separator = $this->getSeparator();
$hidden = $view->formHidden($hiddenName, $element->getValue(), $element->getAttribs());
$text = $view->formText($textName, '', $element->getAttribs());
switch ($placement) {
case 'PREPEND':
$content = $hidden . $separator . $text . $separator . $content;
break;
case 'APPEND':
default:
$content = $content . $separator . $hidden . $separator . $text;
}
return $content;
}
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.