prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>popup.service.ts<|end_file_name|><|fim▁begin|>import { ApplicationRef, ComponentFactoryResolver, Injectable, Injector } from '@angular/core';
import { NgElement, WithProperties } from '@angular/elements';
import { PopupComponent } from './popup.component';
@Injectable()
export class PopupService {
constructor(private injector: Injector,
private applicationRef: ApplicationRef,
private componentFactoryResolver: ComponentFactoryResolver) {}
// Previous dynamic-loading method required you to set up infrastructure<|fim▁hole|>
// Create the component and wire it up with the element
const factory = this.componentFactoryResolver.resolveComponentFactory(PopupComponent);
const popupComponentRef = factory.create(this.injector, [], popup);
// Attach to the view so that the change detector knows to run
this.applicationRef.attachView(popupComponentRef.hostView);
// Listen to the close event
popupComponentRef.instance.closed.subscribe(() => {
document.body.removeChild(popup);
this.applicationRef.detachView(popupComponentRef.hostView);
});
// Set the message
popupComponentRef.instance.message = message;
// Add to the DOM
document.body.appendChild(popup);
}
// This uses the new custom-element method to add the popup to the DOM.
showAsElement(message: string) {
// Create element
const popupEl: NgElement & WithProperties<PopupComponent> = document.createElement('popup-element') as any;
// Listen to the close event
popupEl.addEventListener('closed', () => document.body.removeChild(popupEl));
// Set the message
popupEl.message = message;
// Add to the DOM
document.body.appendChild(popupEl);
}
}<|fim▁end|> | // before adding the popup to the DOM.
showAsComponent(message: string) {
// Create element
const popup = document.createElement('popup-component'); |
<|file_name|>testCipher.py<|end_file_name|><|fim▁begin|>#Encryption algorithms transform their input data, or plaintext, in some way that
#is dependent on a variable key, producing ciphertext. This transformation can
#easily be reversed, if (and, hopefully, only if) one knows the key.
#The key can be varied by the user or application and chosen from some very large space of possible keys.
#Private key ciphers: the same key is used for both encryption and decryption, so all correspondents must know it.
#Block ciphers take multibyte inputs of a fixed size (frequently 8 or 16 bytes long) and encrypt them
#Electronic Code Book (ECB mode)
#Cipher Block Chaining (CBC mode)
#Cipher FeedBack (CFB mode)
<|fim▁hole|># ARC2 Variable/8 bytes
# Blowfish Variable/8 bytes
# CAST Variable/8 bytes
# DES 8 bytes/8 bytes
# DES3 (Triple DES) 16 bytes/8 bytes
# IDEA 16 bytes/8 bytes
# RC5 Variable/8 bytes
#Stream ciphers encrypt data bit-by-bit; practically, stream ciphers work on a character-by-character basis.
#Stream ciphers use exactly the same interface as block ciphers, with a block length that will always be 1;
#this is how block and stream ciphers can be distinguished. The only feedback mode available for stream ciphers is ECB mode.
# Cipher Key Size
# ARC4(Alleged RC4) Variable
#An all-or-nothing package transformation is one in which some text is transformed into message blocks, such that all blocks must be obtained before the reverse transformation can be applied. Thus, if any blocks are corrupted or lost, the original message cannot be reproduced. An all-or-nothing package transformation is not encryption, although a block cipher algorithm is used. The encryption key is randomly generated and is extractable from the message blocks.
#Winnowing and chaffing is a technique for enhancing privacy without requiring strong encryption. In short, the technique takes a set of authenticated message blocks (the wheat) and adds a number of chaff blocks which have randomly chosen data and MAC(message authentication code) fields. This means that to an adversary, the chaff blocks look as valid as the wheat blocks, and so the authentication would have to be performed on every block. By tailoring the number of chaff blocks added to the message, the sender can make breaking the message computationally infeasible. There are many other interesting properties of the winnow/chaff technique.
from Crypto.Cipher import DES
print DES.block_size, DES.key_size
obj=DES.new('abcdefgh', DES.MODE_ECB)
plain="Guido van Rossum is a space alien."
ciph=obj.encrypt(plain+'XXXXXX')
print ciph
print obj.decrypt(ciph)
#Public key cryptography
#In a public key system, there are two different keys: one for encryption and one for decryption. The encryption key can be made public by listing it in a directory or mailing it to your correspondent, while you keep the decryption key secret. Your correspondent then sends you data encrypted with your public key, and you use the private key to decrypt it.
#The currently available public key algorithms are listed in the following table:
# Algorithm Capabilities
# RSA Encryption, authentication/signatures
# ElGamal Encryption, authentication/signatures
# DSA Authentication/signatures
# qNEW Authentication/signatures
#An example of using the RSA module to sign a message:
from Crypto.Hash import MD5
from Crypto.PublicKey import RSA
from Crypto.Util.randpool import RandomPool
RSAkey=RSA.generate(384, RandomPool().get_bytes) # This will take a while...
hash=MD5.new(plain).digest()
signature=RSAkey.sign(hash, "")
print signature # Print what an RSA sig looks like--you don't really care.
RSAkey.verify(hash, signature) # This sig will check out<|fim▁end|> | #PGP mode
# Cipher Key Size/Block Size
|
<|file_name|>ping.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""
A pure python ping implementation using raw socket.
Note that ICMP messages can only be sent from processes running as root.
Derived from ping.c distributed in Linux's netkit. That code is
copyright (c) 1989 by The Regents of the University of California.
That code is in turn derived from code written by Mike Muuss of the
US Army Ballistic Research Laboratory in December, 1983 and
placed in the public domain. They have my thanks.
Bugs are naturally mine. I'd be glad to hear about them. There are
certainly word - size dependenceies here.
Copyright (c) Matthew Dixon Cowles, <http://www.visi.com/~mdc/>.
Distributable under the terms of the GNU General Public License
version 2. Provided with no warranties of any sort.
Original Version from Matthew Dixon Cowles:
-> ftp://ftp.visi.com/users/mdc/ping.py
Rewrite by Jens Diemer:
-> http://www.python-forum.de/post-69122.html#69122
Rewrite by George Notaras:
-> http://www.g-loaded.eu/2009/10/30/python-ping/
Revision history
~~~~~~~~~~~~~~~~
November 8, 2009
----------------
Improved compatibility with GNU/Linux systems.
Fixes by:
* George Notaras -- http://www.g-loaded.eu
Reported by:
* Chris Hallman -- http://cdhallman.blogspot.com
Changes in this release:
- Re-use time.time() instead of time.clock(). The 2007 implementation
worked only under Microsoft Windows. Failed on GNU/Linux.
time.clock() behaves differently under the two OSes[1].
[1] http://docs.python.org/library/time.html#time.clock
May 30, 2007
------------
little rewrite by Jens Diemer:
- change socket asterisk import to a normal import
- replace time.time() with time.clock()
- delete "return None" (or change to "return" only)
- in checksum() rename "str" to "source_string"
November 22, 1997
-----------------
Initial hack. Doesn't do much, but rather than try to guess
what features I (or others) will want in the future, I've only
put in what I need now.
December 16, 1997
-----------------
For some reason, the checksum bytes are in the wrong order when
this is run under Solaris 2.X for SPARC but it works right under
Linux x86. Since I don't know just what's wrong, I'll swap the
bytes always and then do an htons().
December 4, 2000
----------------
Changed the struct.pack() calls to pack the checksum and ID as
unsigned. My thanks to Jerome Poincheval for the fix.
Last commit info:
~~~~~~~~~~~~~~~~~
$LastChangedDate: $
$Rev: $
$Author: $
"""
import os, socket, struct, select, time
# From /usr/include/linux/icmp.h; your milage may vary.
ICMP_ECHO_REQUEST = 8 # Seems to be the same on Solaris.
def checksum(source_string):
"""
I'm not too confident that this is right but testing seems
to suggest that it gives the same answers as in_cksum in ping.c
"""
sum = 0
countTo = (len(source_string)/2)*2
count = 0
while count<countTo:
thisVal = ord(source_string[count + 1])*256 + ord(source_string[count])
sum = sum + thisVal
sum = sum & 0xffffffff # Necessary?
count = count + 2
if countTo<len(source_string):
sum = sum + ord(source_string[len(source_string) - 1])
sum = sum & 0xffffffff # Necessary?
sum = (sum >> 16) + (sum & 0xffff)
sum = sum + (sum >> 16)
answer = ~sum
answer = answer & 0xffff
# Swap bytes. Bugger me if I know why.
answer = answer >> 8 | (answer << 8 & 0xff00)
return answer
def receive_one_ping(my_socket, ID, timeout):
"""
receive the ping from the socket.
"""
timeLeft = timeout
while True:
startedSelect = time.time()
whatReady = select.select([my_socket], [], [], timeLeft)
howLongInSelect = (time.time() - startedSelect)
if whatReady[0] == []: # Timeout
return
timeReceived = time.time()
recPacket, addr = my_socket.recvfrom(1024)
icmpHeader = recPacket[20:28]
type, code, checksum, packetID, sequence = struct.unpack(
"bbHHh", icmpHeader
)
if packetID == ID:
bytesInDouble = struct.calcsize("d")
timeSent = struct.unpack("d", recPacket[28:28 + bytesInDouble])[0]
return timeReceived - timeSent
timeLeft = timeLeft - howLongInSelect
if timeLeft <= 0:
return
def send_one_ping(my_socket, dest_addr, ID):
"""
Send one ping to the given >dest_addr<.
"""
dest_addr = socket.gethostbyname(dest_addr)
# Header is type (8), code (8), checksum (16), id (16), sequence (16)
my_checksum = 0
# Make a dummy heder with a 0 checksum.
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, ID, 1)
bytesInDouble = struct.calcsize("d")
data = (192 - bytesInDouble) * "Q"
data = struct.pack("d", time.time()) + data
# Calculate the checksum on the data and the dummy header.
my_checksum = checksum(header + data)
# Now that we have the right checksum, we put that in. It's just easier
# to make up a new header than to stuff it into the dummy.
header = struct.pack(
"bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), ID, 1
)
packet = header + data
my_socket.sendto(packet, (dest_addr, 1)) # Don't know about the 1
def do_one(dest_addr, timeout):
"""
Returns either the delay (in seconds) or none on timeout.<|fim▁hole|> icmp = socket.getprotobyname("icmp")
try:
my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
except socket.error, (errno, msg):
if errno == 1:
# Operation not permitted
msg = msg + (
" - Note that ICMP messages can only be sent from processes"
" running as root."
)
raise socket.error(msg)
raise # raise the original error
my_ID = os.getpid() & 0xFFFF
send_one_ping(my_socket, dest_addr, my_ID)
delay = receive_one_ping(my_socket, my_ID, timeout)
my_socket.close()
return delay
def verbose_ping(dest_addr, timeout = 2, count = 4):
"""
Send >count< ping to >dest_addr< with the given >timeout< and display
the result.
"""
for i in xrange(count):
print "ping %s..." % dest_addr,
try:
delay = do_one(dest_addr, timeout)
except socket.gaierror, e:
print "failed. (socket error: '%s')" % e[1]
break
if delay == None:
print "failed. (timeout within %ssec.)" % timeout
else:
delay = delay * 1000
print "get ping in %0.4fms" % delay
print
if __name__ == '__main__':
#verbose_ping("192.168.0.4",timeout=0.1,count=1)
result=do_one("192.168.0.4", 0.1)
print result<|fim▁end|> | """ |
<|file_name|>htmllinkelement.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::Parser as CssParser;
use document_loader::LoadType;
use dom::attr::{Attr, AttrValue};
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTMLLinkElementBinding;
use dom::bindings::codegen::Bindings::HTMLLinkElementBinding::HTMLLinkElementMethods;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, MutNullableHeap, Root};
use dom::bindings::js::{RootedReference};
use dom::bindings::refcounted::Trusted;
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::domtokenlist::DOMTokenList;
use dom::element::{AttributeMutation, Element, ElementCreator};
use dom::eventtarget::EventTarget;
use dom::htmlelement::HTMLElement;
use dom::node::{Node, document_from_node, window_from_node};
use dom::virtualmethods::VirtualMethods;
use encoding::EncodingRef;
use encoding::all::UTF_8;
use hyper::header::ContentType;
use hyper::mime::{Mime, TopLevel, SubLevel};
use ipc_channel::ipc;
use ipc_channel::router::ROUTER;
use layout_interface::{LayoutChan, Msg};
use net_traits::{AsyncResponseListener, AsyncResponseTarget, Metadata, NetworkError};
use network_listener::{NetworkListener, PreInvoke};
use script_traits::{MozBrowserEvent, ScriptMsg as ConstellationMsg};
use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::cell::Cell;
use std::default::Default;
use std::mem;
use std::sync::{Arc, Mutex};
use string_cache::Atom;
use style::media_queries::{MediaQueryList, parse_media_query_list};
use style::parser::ParserContextExtraData;
use style::servo::Stylesheet;
use style::stylesheets::Origin;
use url::Url;
use util::str::HTML_SPACE_CHARACTERS;
no_jsmanaged_fields!(Stylesheet);
#[dom_struct]
pub struct HTMLLinkElement {
htmlelement: HTMLElement,
rel_list: MutNullableHeap<JS<DOMTokenList>>,
stylesheet: DOMRefCell<Option<Arc<Stylesheet>>>,
/// https://html.spec.whatwg.org/multipage/#a-style-sheet-that-is-blocking-scripts
parser_inserted: Cell<bool>,
}
impl HTMLLinkElement {
fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document,
creator: ElementCreator) -> HTMLLinkElement {
HTMLLinkElement {
htmlelement: HTMLElement::new_inherited(localName, prefix, document),
rel_list: Default::default(),
parser_inserted: Cell::new(creator == ElementCreator::ParserCreated),
stylesheet: DOMRefCell::new(None),
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: Atom,
prefix: Option<DOMString>,
document: &Document,
creator: ElementCreator) -> Root<HTMLLinkElement> {
let element = HTMLLinkElement::new_inherited(localName, prefix, document, creator);
Node::reflect_node(box element, document, HTMLLinkElementBinding::Wrap)
}
pub fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> {
self.stylesheet.borrow().clone()
}
}
fn get_attr(element: &Element, local_name: &Atom) -> Option<String> {
let elem = element.get_attribute(&ns!(), local_name);
elem.map(|e| {
let value = e.value();
(**value).to_owned()
})
}
fn string_is_stylesheet(value: &Option<String>) -> bool {
match *value {
Some(ref value) => {
let mut found_stylesheet = false;
for s in value.split(HTML_SPACE_CHARACTERS).into_iter() {
if s.eq_ignore_ascii_case("alternate") {
return false;
}
if s.eq_ignore_ascii_case("stylesheet") {
found_stylesheet = true;
}
}
found_stylesheet
},
None => false,
}
}
/// Favicon spec usage in accordance with CEF implementation:
/// only url of icon is required/used
/// https://html.spec.whatwg.org/multipage/#rel-icon
fn is_favicon(value: &Option<String>) -> bool {
match *value {
Some(ref value) => {
value.split(HTML_SPACE_CHARACTERS)
.any(|s| s.eq_ignore_ascii_case("icon") || s.eq_ignore_ascii_case("apple-touch-icon"))
},
None => false,
}
}
impl VirtualMethods for HTMLLinkElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
if !self.upcast::<Node>().is_in_doc() || mutation == AttributeMutation::Removed {
return;
}
let rel = get_attr(self.upcast(), &atom!("rel"));
match attr.local_name() {
&atom!("href") => {
if string_is_stylesheet(&rel) {
self.handle_stylesheet_url(&attr.value());
} else if is_favicon(&rel) {
let sizes = get_attr(self.upcast(), &atom!("sizes"));
self.handle_favicon_url(rel.as_ref().unwrap(), &attr.value(), &sizes);
}
},
&atom!("sizes") => {
if is_favicon(&rel) {
if let Some(ref href) = get_attr(self.upcast(), &atom!("href")) {
self.handle_favicon_url(rel.as_ref().unwrap(), href, &Some(attr.value().to_string()));
}
}
},
&atom!("media") => {
if string_is_stylesheet(&rel) {
self.handle_stylesheet_url(&attr.value());
}
},
_ => {},
}
}
fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue {
match name {
&atom!("rel") => AttrValue::from_serialized_tokenlist(value.into()),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.bind_to_tree(tree_in_doc);
}
if tree_in_doc {
let element = self.upcast();
let rel = get_attr(element, &atom!("rel"));
let href = get_attr(element, &atom!("href"));
let sizes = get_attr(self.upcast(), &atom!("sizes"));
match href {
Some(ref href) if string_is_stylesheet(&rel) => {
self.handle_stylesheet_url(href);
}
Some(ref href) if is_favicon(&rel) => {
self.handle_favicon_url(rel.as_ref().unwrap(), href, &sizes);
}
_ => {}
}
}
}
}
impl HTMLLinkElement {
fn handle_stylesheet_url(&self, href: &str) {
let document = document_from_node(self);
match document.base_url().join(href) {
Ok(url) => {
let element = self.upcast::<Element>();
let mq_attribute = element.get_attribute(&ns!(), &atom!("media"));
let value = mq_attribute.r().map(|a| a.value());
let mq_str = match value {
Some(ref value) => &***value,
None => "",
};
let mut css_parser = CssParser::new(&mq_str);
let media = parse_media_query_list(&mut css_parser);
// TODO: #8085 - Don't load external stylesheets if the node's mq doesn't match.
let elem = Trusted::new(self);
let context = Arc::new(Mutex::new(StylesheetContext {
elem: elem,
media: Some(media),
data: vec!(),
metadata: None,
url: url.clone(),
}));
let (action_sender, action_receiver) = ipc::channel().unwrap();
let listener = NetworkListener {
context: context,
script_chan: document.window().networking_task_source(),
};
let response_target = AsyncResponseTarget {
sender: action_sender,
};
ROUTER.add_route(action_receiver.to_opaque(), box move |message| {
listener.notify(message.to().unwrap());
});
if self.parser_inserted.get() {
document.increment_script_blocking_stylesheet_count();
}
document.load_async(LoadType::Stylesheet(url), response_target);
}
Err(e) => debug!("Parsing url {} failed: {}", href, e)
}
}
fn handle_favicon_url(&self, rel: &str, href: &str, sizes: &Option<String>) {
let document = document_from_node(self);
match document.base_url().join(href) {
Ok(url) => {
let event = ConstellationMsg::NewFavicon(url.clone());
document.window().constellation_chan().send(event).unwrap();
let mozbrowser_event = match *sizes {
Some(ref sizes) => MozBrowserEvent::IconChange(rel.to_owned(), url.to_string(), sizes.to_owned()),
None => MozBrowserEvent::IconChange(rel.to_owned(), url.to_string(), "".to_owned())
};
document.trigger_mozbrowser_event(mozbrowser_event);
}
Err(e) => debug!("Parsing url {} failed: {}", href, e)
}
}
}
/// The context required for asynchronously loading an external stylesheet.
struct StylesheetContext {
/// The element that initiated the request.
elem: Trusted<HTMLLinkElement>,
media: Option<MediaQueryList>,
/// The response body received to date.
data: Vec<u8>,
/// The response metadata received to date.
metadata: Option<Metadata>,
/// The initial URL requested.
url: Url,
}
impl PreInvoke for StylesheetContext {}
impl AsyncResponseListener for StylesheetContext {
fn headers_available(&mut self, metadata: Result<Metadata, NetworkError>) {
self.metadata = metadata.ok();
if let Some(ref meta) = self.metadata {
if let Some(ContentType(Mime(TopLevel::Text, SubLevel::Css, _))) = meta.content_type {
} else {
self.elem.root().upcast::<EventTarget>().fire_simple_event("error");
}
}
}
fn data_available(&mut self, payload: Vec<u8>) {
let mut payload = payload;
self.data.append(&mut payload);
}
fn response_complete(&mut self, status: Result<(), NetworkError>) {
if status.is_err() {
self.elem.root().upcast::<EventTarget>().fire_simple_event("error");
return;
}
let data = mem::replace(&mut self.data, vec!());
let metadata = match self.metadata.take() {
Some(meta) => meta,
None => return,
};
// TODO: Get the actual value. http://dev.w3.org/csswg/css-syntax/#environment-encoding
let environment_encoding = UTF_8 as EncodingRef;
let protocol_encoding_label = metadata.charset.as_ref().map(|s| &**s);
let final_url = metadata.final_url;
let elem = self.elem.root();
let win = window_from_node(&*elem);
let mut sheet = Stylesheet::from_bytes(&data, final_url, protocol_encoding_label,
Some(environment_encoding), Origin::Author,
win.css_error_reporter(),
ParserContextExtraData::default());
let media = self.media.take().unwrap();
sheet.set_media(Some(media));
let sheet = Arc::new(sheet);
let elem = elem.r();
let document = document_from_node(elem);
let document = document.r();
let win = window_from_node(elem);
let LayoutChan(ref layout_chan) = *win.layout_chan();
layout_chan.send(Msg::AddStylesheet(sheet.clone())).unwrap();
*elem.stylesheet.borrow_mut() = Some(sheet);
document.invalidate_stylesheets();
if elem.parser_inserted.get() {
document.decrement_script_blocking_stylesheet_count();
}
document.finish_load(LoadType::Stylesheet(self.url.clone()));
}
}
impl HTMLLinkElementMethods for HTMLLinkElement {
// https://html.spec.whatwg.org/multipage/#dom-link-href
make_url_getter!(Href, "href");
// https://html.spec.whatwg.org/multipage/#dom-link-href
make_setter!(SetHref, "href");
<|fim▁hole|> // https://html.spec.whatwg.org/multipage/#dom-link-rel
make_getter!(Rel, "rel");
// https://html.spec.whatwg.org/multipage/#dom-link-rel
make_setter!(SetRel, "rel");
// https://html.spec.whatwg.org/multipage/#dom-link-media
make_getter!(Media, "media");
// https://html.spec.whatwg.org/multipage/#dom-link-media
make_setter!(SetMedia, "media");
// https://html.spec.whatwg.org/multipage/#dom-link-hreflang
make_getter!(Hreflang, "hreflang");
// https://html.spec.whatwg.org/multipage/#dom-link-hreflang
make_setter!(SetHreflang, "hreflang");
// https://html.spec.whatwg.org/multipage/#dom-link-type
make_getter!(Type, "type");
// https://html.spec.whatwg.org/multipage/#dom-link-type
make_setter!(SetType, "type");
// https://html.spec.whatwg.org/multipage/#dom-link-rellist
fn RelList(&self) -> Root<DOMTokenList> {
self.rel_list.or_init(|| DOMTokenList::new(self.upcast(), &atom!("rel")))
}
// https://html.spec.whatwg.org/multipage/#dom-link-charset
make_getter!(Charset, "charset");
// https://html.spec.whatwg.org/multipage/#dom-link-charset
make_setter!(SetCharset, "charset");
// https://html.spec.whatwg.org/multipage/#dom-link-rev
make_getter!(Rev, "rev");
// https://html.spec.whatwg.org/multipage/#dom-link-rev
make_setter!(SetRev, "rev");
// https://html.spec.whatwg.org/multipage/#dom-link-target
make_getter!(Target, "target");
// https://html.spec.whatwg.org/multipage/#dom-link-target
make_setter!(SetTarget, "target");
}<|fim▁end|> | |
<|file_name|>JavaFormatterAlignmentTest.java<|end_file_name|><|fim▁begin|>// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.java.psi.formatter.java;
import com.intellij.ide.highlighter.JavaFileType;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
import com.intellij.util.IncorrectOperationException;
import static com.intellij.formatting.FormatterTestUtils.Action.REFORMAT_WITH_CONTEXT;
/**
* Is intended to hold specific java formatting tests for alignment settings (
* {@code Project Settings - Code Style - Alignment and Braces}).
*
* @author Denis Zhdanov
*/
public class JavaFormatterAlignmentTest extends AbstractJavaFormatterTest {
public void testChainedMethodsAlignment() {
// Inspired by IDEA-30369
getSettings().ALIGN_MULTILINE_CHAINED_METHODS = true;
getSettings().METHOD_CALL_CHAIN_WRAP = CommonCodeStyleSettings.WRAP_AS_NEEDED;
getSettings().getRootSettings().getIndentOptions(JavaFileType.INSTANCE).CONTINUATION_INDENT_SIZE = 8;
doTest();
}
public void testMethodAndChainedField() {
// Inspired by IDEA-79806
getSettings().ALIGN_MULTILINE_CHAINED_METHODS = true;
doMethodTest(
"Holder.INSTANCE\n" +
" .foo();",
"Holder.INSTANCE\n" +
" .foo();"
);
}
public void testChainedMethodWithComments() {
getSettings().ALIGN_MULTILINE_CHAINED_METHODS = true;
doMethodTest("AAAAA.b()\n" +
".c() // comment after line\n" +
".d()\n" +
".e();",
"AAAAA.b()\n" +
" .c() // comment after line\n" +
" .d()\n" +
" .e();");
}
public void testChainedMethodWithBlockComment() {
getSettings().ALIGN_MULTILINE_CHAINED_METHODS = true;
doTextTest("class X {\n" +
" public void test() {\n" +
" AAAAAA.b()\n" +
".c()\n" +
".d()\n" +
" /* simple block comment */\n" +
".e();\n" +
" }\n" +
"}",
"class X {\n" +
" public void test() {\n" +
" AAAAAA.b()\n" +
" .c()\n" +
" .d()\n" +
" /* simple block comment */\n" +
" .e();\n" +
" }\n" +
"}");
}
public void testMultipleMethodAnnotationsCommentedInTheMiddle() {
getSettings().BLANK_LINES_AFTER_CLASS_HEADER = 1;
getSettings().getRootSettings().getIndentOptions(JavaFileType.INSTANCE).INDENT_SIZE = 4;
// Inspired by IDEA-53942
doTextTest(
"public class Test {\n" +
" @Override\n" +
"// @XmlElement(name = \"Document\", required = true, type = DocumentType.class)\n" +
" @XmlTransient\n" +
" void foo() {\n" +
"}\n" +
"}",
"public class Test {\n" +
"\n" +
" @Override\n" +
"// @XmlElement(name = \"Document\", required = true, type = DocumentType.class)\n" +
" @XmlTransient\n" +
" void foo() {\n" +
" }\n" +
"}"
);
}
public void testTernaryOperator() {
// Inspired by IDEADEV-13018
getSettings().ALIGN_MULTILINE_TERNARY_OPERATION = true;
doMethodTest("int i = a ? x\n" + ": y;", "int i = a ? x\n" + " : y;");
}
public void testMethodCallArgumentsAndSmartTabs() throws IncorrectOperationException {
// Inspired by IDEADEV-20144.
getSettings().ALIGN_MULTILINE_PARAMETERS_IN_CALLS = true;
getSettings().getRootSettings().getIndentOptions(JavaFileType.INSTANCE).SMART_TABS = true;
getSettings().getRootSettings().getIndentOptions(JavaFileType.INSTANCE).USE_TAB_CHARACTER = true;
doTextTest("class Foo {\n" +
" void foo() {\n" +
" bar(new Object[] {\n" +
" \"hello1\",\n" +
" \"hello2\", add(\"hello3\",\n" +
" \"world\")\n" +
"});" +
" }}", "class Foo {\n" +
"\tvoid foo() {\n" +
"\t\tbar(new Object[]{\n" +
"\t\t\t\t\"hello1\",\n" +
"\t\t\t\t\"hello2\", add(\"hello3\",\n" +
"\t\t\t\t \"world\")\n" +
"\t\t});\n" +
"\t}\n" +
"}");
}
public void testArrayInitializer() throws IncorrectOperationException {
// Inspired by IDEADEV-16136
getSettings().ARRAY_INITIALIZER_WRAP = CommonCodeStyleSettings.WRAP_ALWAYS;
getSettings().ALIGN_MULTILINE_ARRAY_INITIALIZER_EXPRESSION = true;
doTextTest(
"@SuppressWarnings({\"UseOfSystemOutOrSystemErr\", \"AssignmentToCollectionOrArrayFieldFromParameter\", \"ReturnOfCollectionOrArrayField\"})\n" +
"public class Some {\n" +
"}",
"@SuppressWarnings({\"UseOfSystemOutOrSystemErr\",\n" +
" \"AssignmentToCollectionOrArrayFieldFromParameter\",\n" +
" \"ReturnOfCollectionOrArrayField\"})\n" +
"public class Some {\n" +
"}");
}
public void testMethodBrackets() {
// Inspired by IDEA-53013
getSettings().ALIGN_MULTILINE_METHOD_BRACKETS = true;
getSettings().ALIGN_MULTILINE_PARENTHESIZED_EXPRESSION = false;
getSettings().ALIGN_MULTILINE_PARAMETERS = true;
getSettings().ALIGN_MULTILINE_PARAMETERS_IN_CALLS = true;
getSettings().CALL_PARAMETERS_RPAREN_ON_NEXT_LINE = true;
getSettings().METHOD_PARAMETERS_RPAREN_ON_NEXT_LINE = true;
doClassTest(
"public void foo(int i,\n" +
" int j) {\n" +
"}\n" +
"\n" +
" public void bar() {\n" +
" foo(1,\n" +
" 2);\n" +
" }",
"public void foo(int i,\n" +
" int j\n" +
" ) {\n" +
"}\n" +
"\n" +
"public void bar() {\n" +
" foo(1,\n" +
" 2\n" +
" );\n" +
"}"
);
// Inspired by IDEA-55306
getSettings().ALIGN_MULTILINE_METHOD_BRACKETS = false;
getSettings().CALL_PARAMETERS_RPAREN_ON_NEXT_LINE = false;
String method =
"executeCommand(new Command<Boolean>() {\n" +
" public Boolean run() throws ExecutionException {\n" +
" return doInterrupt();\n" +
" }\n" +
"});";
doMethodTest(method, method);
}
public void testFieldInColumnsAlignment() {
// Inspired by IDEA-55147
getSettings().ALIGN_GROUP_FIELD_DECLARATIONS = true;
getSettings().FIELD_ANNOTATION_WRAP = CommonCodeStyleSettings.DO_NOT_WRAP;
getSettings().VARIABLE_ANNOTATION_WRAP = CommonCodeStyleSettings.DO_NOT_WRAP;
doTextTest(
"public class FormattingTest {\n" +
"\n" +
" int start = 1;\n" +
" double end = 2;\n" +
"\n" +
" int i2 = 1;\n" +
" double dd2,\n" +
" dd3 = 2;\n" +
"\n" +
" // asd\n" +
" char ccc3 = 'a';\n" +
" double ddd31, ddd32 = 1;\n" +
"\n" +
" private\n" +
" final String s4 = \"\";\n" +
" private\n" +
" transient int i4 = 1;\n" +
"\n" +
" private final String s5 = \"xxx\";\n" +
" private transient int iiii5 = 1;\n" +
" /*sdf*/\n" +
" @MyAnnotation(value = 1, text = 2) float f5 = 1;\n" +
"}",
"public class FormattingTest {\n" +
"\n" +
" int start = 1;\n" +
" double end = 2;\n" +
"\n" +
" int i2 = 1;\n" +
" double dd2,\n" +
" dd3 = 2;\n" +
"\n" +
" // asd\n" +
" char ccc3 = 'a';\n" +
" double ddd31, ddd32 = 1;\n" +
"\n" +
" private\n" +
" final String s4 = \"\";\n" +
" private\n" +
" transient int i4 = 1;\n" +
"\n" +
" private final String s5 = \"xxx\";\n" +
" private transient int iiii5 = 1;\n" +
" /*sdf*/\n" +
" @MyAnnotation(value = 1, text = 2) float f5 = 1;\n" +
"}"
);
}
public void testTabsAndFieldsInColumnsAlignment() {
// Inspired by IDEA-56242
getSettings().ALIGN_GROUP_FIELD_DECLARATIONS = true;
getIndentOptions().USE_TAB_CHARACTER = true;
doTextTest(
"public class Test {\n" +
"\tprivate Long field2 = null;\n" +
"\tprivate final Object field1 = null;\n" +
"\tprivate int i = 1;\n" +
"}",
"public class Test {\n" +
"\tprivate Long field2 = null;\n" +
"\tprivate final Object field1 = null;\n" +
"\tprivate int i = 1;\n" +
"}"
);
}
public void testDoNotAlignIfNotEnabled() {
getSettings().ALIGN_GROUP_FIELD_DECLARATIONS = false;
doTextTest(
"public class Test {\n" +
"private Long field2 = null;\n" +
"private final Object field1 = null;\n" +
"private int i = 1;\n" +
"}",
"public class Test {\n" +
" private Long field2 = null;\n" +
" private final Object field1 = null;\n" +
" private int i = 1;\n" +
"}"
);
}
public void testAnnotatedAndNonAnnotatedFieldsInColumnsAlignment() {
// Inspired by IDEA-60237
getSettings().ALIGN_GROUP_FIELD_DECLARATIONS = true;
doTextTest(
"public class Test {\n" +
" @Id\n" +
" private final String name;\n" +
" @Column(length = 2 * 1024 * 1024 /* 2 MB */)\n" +
" private String value;\n" +
" private boolean required;\n" +
" private String unsetValue;\n" +
"}",
"public class Test {\n" +
" @Id\n" +
" private final String name;\n" +
" @Column(length = 2 * 1024 * 1024 /* 2 MB */)\n" +
" private String value;\n" +
" private boolean required;\n" +
" private String unsetValue;\n" +
"}"
);
}
public void testAlignThrowsKeyword() {
// Inspired by IDEA-63820
getSettings().ALIGN_THROWS_KEYWORD = true;
doClassTest(
"public void test()\n" +
" throws Exception {}",
"public void test()\n" +
"throws Exception {\n" +
"}"
);
getSettings().ALIGN_THROWS_KEYWORD = false;
doClassTest(
"public void test()\n" +
" throws Exception {}",
"public void test()\n" +
" throws Exception {\n" +
"}"
);
}
public void testAlignResourceList() {
getSettings().KEEP_SIMPLE_BLOCKS_IN_ONE_LINE = true;
getSettings().ALIGN_MULTILINE_RESOURCES = true;
doMethodTest("try (MyResource r1 = null;\n" +
"MyResource r2 = null) { }",
"try (MyResource r1 = null;\n" +
" MyResource r2 = null) { }");
getSettings().ALIGN_MULTILINE_RESOURCES = false;
doMethodTest("try (MyResource r1 = null;\n" +
"MyResource r2 = null) { }",
"try (MyResource r1 = null;\n" +
" MyResource r2 = null) { }");
}
public void testChainedMethodCallsAfterFieldsChain_WithAlignment() {
getSettings().ALIGN_MULTILINE_CHAINED_METHODS = true;
getSettings().METHOD_CALL_CHAIN_WRAP = CommonCodeStyleSettings.WRAP_ALWAYS;
doMethodTest(
"a.current.current.current.getThis().getThis().getThis();",
"a.current.current.current.getThis()\n" +
" .getThis()\n" +
" .getThis();"
);
doMethodTest(
"a.current.current.current.getThis().getThis().getThis().current.getThis().getThis().getThis().getThis();",
"a.current.current.current.getThis()\n" +
" .getThis()\n" +
" .getThis().current.getThis()\n" +
" .getThis()\n" +
" .getThis()\n" +
" .getThis();"
);
String onlyMethodCalls = "getThis().getThis().getThis();";
String formatedMethodCalls = "getThis().getThis()\n" +
" .getThis();";
doMethodTest(onlyMethodCalls, formatedMethodCalls);
}
public void testChainedMethodCallsAfterFieldsChain_WithoutAlignment() {
getSettings().ALIGN_MULTILINE_CHAINED_METHODS = false;
getSettings().METHOD_CALL_CHAIN_WRAP = CommonCodeStyleSettings.WRAP_ALWAYS;
doMethodTest(
"a.current.current.current.getThis().getThis().getThis();",
"a.current.current.current.getThis()\n" +
" .getThis()\n" +
" .getThis();"
);
}
public void testChainedMethodCalls_WithChopDownIfLongOption() {
getSettings().ALIGN_MULTILINE_CHAINED_METHODS = true;
getSettings().METHOD_CALL_CHAIN_WRAP = CommonCodeStyleSettings.WRAP_ON_EVERY_ITEM; // it's equal to "Chop down if long"
getSettings().RIGHT_MARGIN = 50;
String before = "a.current.current.getThis().getThis().getThis().getThis().getThis();";
doMethodTest(
before,
"a.current.current.getThis()\n" +
" .getThis()\n" +
" .getThis()\n" +
" .getThis()\n" +
" .getThis();"
);
getSettings().RIGHT_MARGIN = 80;
doMethodTest(before, before);
}
public void testChainedMethodCalls_WithWrapIfNeededOption() {
getSettings().ALIGN_MULTILINE_CHAINED_METHODS = false;
getSettings().METHOD_CALL_CHAIN_WRAP = CommonCodeStyleSettings.WRAP_AS_NEEDED;
getSettings().RIGHT_MARGIN = 50;
String before = "a.current.current.getThis().getThis().getThis().getThis();";
doMethodTest(
before,
"a.current.current.getThis().getThis()\n" +
" .getThis().getThis();"
);
getSettings().ALIGN_MULTILINE_CHAINED_METHODS = true;
doMethodTest(
before,
"a.current.current.getThis().getThis()\n" +
" .getThis().getThis();"
);
getSettings().RIGHT_MARGIN = 75;
doMethodTest(before, before);
}
public void testAlignMethodCalls_PassedAsParameters_InMethodCall() {
getSettings().ALIGN_MULTILINE_PARAMETERS_IN_CALLS = true;
doMethodTest(
"test(call1(),\n" +
" call2(),\n" +
" call3());\n",
"test(call1(),\n" +
" call2(),\n" +
" call3());\n"
);
}
public void testLocalVariablesAlignment() {
getSettings().ALIGN_CONSECUTIVE_VARIABLE_DECLARATIONS = true;
doMethodTest(
"int a = 2;\n" +
"String myString = \"my string\"",
"int a = 2;\n" +
"String myString = \"my string\""
);
}
public void testAlignOnlyDeclarationStatements() {
getSettings().ALIGN_CONSECUTIVE_VARIABLE_DECLARATIONS = true;
doMethodTest(
" String s;\n" +
" int a = 2;\n" +
"s = \"abs\";\n" +
"long stamp = 12;",
"String s;\n" +
"int a = 2;\n" +
"s = \"abs\";\n" +
"long stamp = 12;"
);
}
public void testAlignFieldDeclarations() {
getSettings().ALIGN_GROUP_FIELD_DECLARATIONS = true;
doClassTest(
"char a = '2';\n" +
"int aaaaa = 3;\n" +
"String b;",
"char a = '2';\n" +
"int aaaaa = 3;\n" +
"String b;");
}
public void testAlignVarDeclarations() {
getSettings().ALIGN_CONSECUTIVE_VARIABLE_DECLARATIONS = true;
doMethodTest(
"char a = '2';\n" +
"int aaaaa = 3;\n" +
"String b;",
"char a = '2';\n" +
"int aaaaa = 3;\n" +
"String b;");
}
public void testDoNotAlignWhenBlankLine() {
getSettings().ALIGN_CONSECUTIVE_VARIABLE_DECLARATIONS = true;
doMethodTest(
"int a = 2;\n" +
"\n" +
"String myString = \"my string\"",
"int a = 2;\n" +
"\n" +
"String myString = \"my string\""
);
}
public void testDoNotAlignWhenGroupInterrupted() {
getSettings().ALIGN_CONSECUTIVE_VARIABLE_DECLARATIONS = true;
doMethodTest(
"int a = 2;\n" +
"System.out.println(\"hi!\")\n" +
"String myString = \"my string\"",
"int a = 2;\n" +
"System.out.println(\"hi!\")\n" +
"String myString = \"my string\""
);
}
public void testDoNotAlignMultiDeclarations() {
getSettings().ALIGN_CONSECUTIVE_VARIABLE_DECLARATIONS = true;
doMethodTest(
" int a, b = 2;\n" +
"String myString = \"my string\"",
"int a, b = 2;\n" +
"String myString = \"my string\""
);
}
public void testDoNotAlignMultilineParams() {
getSettings().ALIGN_CONSECUTIVE_VARIABLE_DECLARATIONS = true;
doMethodTest(
"int a = 12;\n" +
" Runnable runnable = new Runnable() {\n" +
" @Override\n" +
" public void run() {\n" +
" System.out.println(\"AAA!\");\n" +
" }\n" +
"};",
"int a = 12;\n" +
"Runnable runnable = new Runnable() {\n" +
" @Override\n" +
" public void run() {\n" +
" System.out.println(\"AAA!\");\n" +
" }\n" +
"};"
);
doMethodTest(
" Runnable runnable = new Runnable() {\n" +
" @Override\n" +
" public void run() {\n" +
" System.out.println(\"AAA!\");\n" +
" }\n" +
"};\n" +
"int c = 12;",<|fim▁hole|>
"Runnable runnable = new Runnable() {\n" +
" @Override\n" +
" public void run() {\n" +
" System.out.println(\"AAA!\");\n" +
" }\n" +
"};\n" +
"int c = 12;"
);
doMethodTest(
" int ac = 99;\n" +
"Runnable runnable = new Runnable() {\n" +
" @Override\n" +
" public void run() {\n" +
" System.out.println(\"AAA!\");\n" +
" }\n" +
"};\n" +
"int c = 12;",
"int ac = 99;\n" +
"Runnable runnable = new Runnable() {\n" +
" @Override\n" +
" public void run() {\n" +
" System.out.println(\"AAA!\");\n" +
" }\n" +
"};\n" +
"int c = 12;"
);
}
public void testDoNotAlign_IfFirstMultiline() {
getSettings().ALIGN_CONSECUTIVE_VARIABLE_DECLARATIONS = true;
doMethodTest(
"int\n" +
" i = 0;\n" +
"int[] a = new int[]{1, 2, 0x0052, 0x0053, 0x0054};\n" +
"int var1 = 1;\n" +
"int var2 = 2;",
"int\n" +
" i = 0;\n" +
"int[] a = new int[]{1, 2, 0x0052, 0x0053, 0x0054};\n" +
"int var1 = 1;\n" +
"int var2 = 2;"
);
}
public void testAlign_InMethod() {
getSettings().ALIGN_CONSECUTIVE_VARIABLE_DECLARATIONS = true;
doClassTest(
"public void run() {\n" +
"\n" +
" int a = 2;\n" +
" String superString = \"\";\n" +
"\n" +
" test(call1(), call2(), call3());\n" +
" }",
"public void run() {\n" +
"\n" +
" int a = 2;\n" +
" String superString = \"\";\n" +
"\n" +
" test(call1(), call2(), call3());\n" +
"}"
);
doClassTest(
"public void run() {\n" +
"\n" +
" test(call1(), call2(), call3());\n" +
"\n" +
" int a = 2;\n" +
" String superString = \"\";\n" +
"}",
"public void run() {\n" +
"\n" +
" test(call1(), call2(), call3());\n" +
"\n" +
" int a = 2;\n" +
" String superString = \"\";\n" +
"}");
}
public void test_Shift_All_AlignedParameters() {
myLineRange = new TextRange(2, 2);
getSettings().ALIGN_MULTILINE_PARAMETERS_IN_CALLS = true;
doTextTest(
REFORMAT_WITH_CONTEXT,
"public class Test {\n" +
"\n" +
" public void fooooo(String foo,\n" +
" String booo,\n" +
" String kakadoo) {\n" +
"\n" +
" }\n" +
"\n" +
"}",
"public class Test {\n" +
"\n" +
" public void fooooo(String foo,\n" +
" String booo,\n" +
" String kakadoo) {\n" +
"\n" +
" }\n" +
"\n" +
"}"
);
}
public void test_Align_UnselectedField_IfNeeded() {
myLineRange = new TextRange(2, 2);
getSettings().ALIGN_GROUP_FIELD_DECLARATIONS = true;
doTextTest(
REFORMAT_WITH_CONTEXT,
"public class Test {\n" +
" public int i = 1;\n" +
" public String iiiiiiiiii = 2;\n" +
"}",
"public class Test {\n" +
" public int i = 1;\n" +
" public String iiiiiiiiii = 2;\n" +
"}"
);
}
public void test_Align_UnselectedVariable_IfNeeded() {
myLineRange = new TextRange(3, 3);
getSettings().ALIGN_CONSECUTIVE_VARIABLE_DECLARATIONS = true;
doTextTest(
REFORMAT_WITH_CONTEXT,
"public class Test {\n" +
" public void test() {\n" +
" int s = 2;\n" +
" String sssss = 3;\n" +
" }\n" +
"}",
"public class Test {\n" +
" public void test() {\n" +
" int s = 2;\n" +
" String sssss = 3;\n" +
" }\n" +
"}"
);
}
public void test_Align_ConsecutiveVars_InsideIfBlock() {
getSettings().ALIGN_CONSECUTIVE_VARIABLE_DECLARATIONS = true;
doMethodTest(
"if (a > 2) {\n" +
"int a=2;\n" +
"String name=\"Yarik\";\n" +
"}\n",
"if (a > 2) {\n" +
" int a = 2;\n" +
" String name = \"Yarik\";\n" +
"}\n"
);
}
public void test_Align_ConsecutiveVars_InsideForBlock() {
getSettings().ALIGN_CONSECUTIVE_VARIABLE_DECLARATIONS = true;
doMethodTest(
" for (int i = 0; i < 10; i++) {\n" +
" int a=2;\n" +
" String name=\"Xa\";\n" +
" }\n",
"for (int i = 0; i < 10; i++) {\n" +
" int a = 2;\n" +
" String name = \"Xa\";\n" +
"}\n"
);
}
public void test_Align_ConsecutiveVars_InsideTryBlock() {
getSettings().ALIGN_CONSECUTIVE_VARIABLE_DECLARATIONS = true;
doMethodTest(
" try {\n" +
" int x = getX();\n" +
" String name = \"Ha\";\n" +
" }\n" +
" catch (IOException exception) {\n" +
" int y = 12;\n" +
" String test = \"Test\";\n" +
" }\n" +
" finally {\n" +
" int z = 12;\n" +
" String zzzz = \"pnmhd\";\n" +
" }\n",
"try {\n" +
" int x = getX();\n" +
" String name = \"Ha\";\n" +
"} catch (IOException exception) {\n" +
" int y = 12;\n" +
" String test = \"Test\";\n" +
"} finally {\n" +
" int z = 12;\n" +
" String zzzz = \"pnmhd\";\n" +
"}\n"
);
}
public void test_Align_ConsecutiveVars_InsideCodeBlock() {
getSettings().ALIGN_CONSECUTIVE_VARIABLE_DECLARATIONS = true;
doMethodTest(
" System.out.println(\"AAAA\");\n" +
" int a = 2;\n" +
" \n" +
" {\n" +
" int x=2;\n" +
" String name=3;\n" +
" }\n",
"System.out.println(\"AAAA\");\n" +
"int a = 2;\n" +
"\n" +
"{\n" +
" int x = 2;\n" +
" String name = 3;\n" +
"}\n"
);
}
public void test_AlignComments_BetweenChainedMethodCalls() {
getSettings().ALIGN_MULTILINE_CHAINED_METHODS = true;
doMethodTest(
"ActionBarPullToRefresh.from(getActivity())\n" +
" // Mark the ListView as pullable\n" +
" .theseChildrenArePullable(eventsListView)\n" +
" // Set the OnRefreshListener\n" +
" .listener(this)\n" +
" // Use the AbsListView delegate for StickyListHeadersListView\n" +
" .useViewDelegate(StickyListHeadersListView.class, new AbsListViewDelegate())\n" +
" // Finally commit the setup to our PullToRefreshLayout\n" +
" .setup(mPullToRefreshLayout);",
"ActionBarPullToRefresh.from(getActivity())\n" +
" // Mark the ListView as pullable\n" +
" .theseChildrenArePullable(eventsListView)\n" +
" // Set the OnRefreshListener\n" +
" .listener(this)\n" +
" // Use the AbsListView delegate for StickyListHeadersListView\n" +
" .useViewDelegate(StickyListHeadersListView.class, new AbsListViewDelegate())\n" +
" // Finally commit the setup to our PullToRefreshLayout\n" +
" .setup(mPullToRefreshLayout);"
);
}
public void test_AlignComments_2() {
getSettings().ALIGN_MULTILINE_CHAINED_METHODS = true;
doClassTest(
"public String returnWithBuilder2() {\n" +
" return MoreObjects\n" +
" .toStringHelper(this)\n" +
" .add(\"value\", value)\n" +
" // comment\n" +
" .toString();\n" +
" }",
"public String returnWithBuilder2() {\n" +
" return MoreObjects\n" +
" .toStringHelper(this)\n" +
" .add(\"value\", value)\n" +
" // comment\n" +
" .toString();\n" +
"}"
);
}
public void test_AlignSubsequentOneLineMethods() {
getSettings().KEEP_SIMPLE_METHODS_IN_ONE_LINE = true;
getSettings().ALIGN_SUBSEQUENT_SIMPLE_METHODS = true;
doTextTest(
"public class Test {\n" +
"\n" +
" public void testSuperDuperFuckerMother() { System.out.println(\"AAA\"); }\n" +
"\n" +
" public void testCounterMounter() { System.out.println(\"XXXX\"); }\n" +
"\n" +
"}",
"public class Test {\n" +
"\n" +
" public void testSuperDuperFuckerMother() { System.out.println(\"AAA\"); }\n" +
"\n" +
" public void testCounterMounter() { System.out.println(\"XXXX\"); }\n" +
"\n" +
"}"
);
}
public void test_alignAssignments() {
getSettings().ALIGN_CONSECUTIVE_ASSIGNMENTS = true;
doTextTest(
"public class Test {\n" +
" void foo(int a, int xyz) {\n" +
" a = 9999;\n" +
" xyz = 1;\n" +
" }\n" +
"}",
"public class Test {\n" +
" void foo(int a, int xyz) {\n" +
" a = 9999;\n" +
" xyz = 1;\n" +
" }\n" +
"}"
);
}
public void test_alignMultilineAssignments() {
getSettings().ALIGN_CONSECUTIVE_ASSIGNMENTS = true;
getSettings().ALIGN_MULTILINE_ASSIGNMENT = true;
doTextTest(
"public class Test {\n" +
" void foo(int a, int xyz) {\n" +
" a = 9999;\n" +
" xyz = a = \n" +
" a = 12;\n" +
" }\n" +
"}",
"public class Test {\n" +
" void foo(int a, int xyz) {\n" +
" a = 9999;\n" +
" xyz = a =\n" +
" a = 12;\n" +
" }\n" +
"}"
);
}
public void test_alignMultilineAssignmentsMixedWithDeclaration() {
getSettings().ALIGN_CONSECUTIVE_ASSIGNMENTS = true;
getSettings().ALIGN_MULTILINE_ASSIGNMENT = true;
getSettings().ALIGN_CONSECUTIVE_VARIABLE_DECLARATIONS = true;
doTextTest(
"public class Test {\n" +
" void foo(int a, int xyz, int bc) {\n" +
" bc = 9999;\n" +
" a = 9999;\n" +
" int basdf = 1234;\n" +
" int as = 3;\n" +
" xyz = a = \n" +
" a = 12;\n" +
" }\n" +
"}",
"public class Test {\n" +
" void foo(int a, int xyz, int bc) {\n" +
" bc = 9999;\n" +
" a = 9999;\n" +
" int basdf = 1234;\n" +
" int as = 3;\n" +
" xyz = a =\n" +
" a = 12;\n" +
" }\n" +
"}"
);
}
public void test_alignAssignmentsFields() {
getSettings().ALIGN_CONSECUTIVE_ASSIGNMENTS = true;
doTextTest(
"public class Test {\n" +
" void foo(A a, int xyz) {\n" +
" a.bar = 9999;\n" +
" xyz = 1;\n" +
" }\n" +
"}",
"public class Test {\n" +
" void foo(A a, int xyz) {\n" +
" a.bar = 9999;\n" +
" xyz = 1;\n" +
" }\n" +
"}"
);
}
public void test_alignMultilineTextBlock() {
getJavaSettings().ALIGN_MULTILINE_TEXT_BLOCKS = true;
doTextTest(
"public class Test {\n" +
" void foo() {\n" +
" String block = \"\"\"\n" +
" text\n" +
" block\n" +
" \"\"\";\n" +
" }\n" +
"}",
"public class Test {\n" +
" void foo() {\n" +
" String block = \"\"\"\n" +
" text\n" +
" block\n" +
" \"\"\";\n" +
" }\n" +
"}"
);
}
@SuppressWarnings("unused")
public void _testIdea199677() {
getSettings().ALIGN_CONSECUTIVE_VARIABLE_DECLARATIONS = true;
getSettings().CALL_PARAMETERS_WRAP = 2;
getSettings().CALL_PARAMETERS_LPAREN_ON_NEXT_LINE = true;
getSettings().CALL_PARAMETERS_RPAREN_ON_NEXT_LINE = true;
doTextTest(
"public class Main {\n" +
"\n" +
" public static void main(String[] args) {\n" +
" int one = 1;\n" +
" int a_million_dollars = 1000000;\n" +
"\n" +
" doSomething(one, a_million_dollars);\n" +
" }\n" +
"\n" +
" private static void doSomething(int one, int two) {\n" +
" }\n" +
"\n" +
"}",
"public class Main {\n" +
"\n" +
" public static void main(String[] args) {\n" +
" int one = 1;\n" +
" int a_million_dollars = 1000000;\n" +
"\n" +
" doSomething(\n" +
" one,\n" +
" a_million_dollars\n" +
" );\n" +
" }\n" +
"\n" +
" private static void doSomething(int one, int two) {\n" +
" }\n" +
"\n" +
"}"
);
}
}<|fim▁end|> | |
<|file_name|>index.ts<|end_file_name|><|fim▁begin|>import classDisplayNameHandler from './classDisplayNameHandler'
import classMethodHandler from './classMethodHandler'
import classPropHandler from './classPropHandler'
import componentHandler from './componentHandler'
import displayNameHandler from './displayNameHandler'
import eventHandler from './eventHandler'
import extendsHandler from './extendsHandler'
import methodHandler from './methodHandler'
import mixinsHandler from './mixinsHandler'
// import oldEventsHandler from './oldEventsHandler'
import propHandler from './propHandler'
import slotHandler from './slotHandler'
export default [
// have to be first if they can be overridden
extendsHandler,
// have to be second as they can be overridden too
mixinsHandler,
componentHandler,<|fim▁hole|> eventHandler,
slotHandler,
classDisplayNameHandler,
classMethodHandler,
classPropHandler,
// at the end extract events from comments
// oldEventsHandler,
]<|fim▁end|> | displayNameHandler,
methodHandler,
propHandler, |
<|file_name|>InputEqualsAvoidNull.java<|end_file_name|><|fim▁begin|>package com.puppycrawl.tools.checkstyle.coding;
public class InputEqualsAvoidNull {
public boolean equals(Object o) {
return false;
}
/**
* methods that should get flagged
* @return
*/
public void flagForEquals() {
Object o = new Object();
String s = "pizza";
o.equals("hot pizza");
o.equals(s = "cold pizza");
o.equals(((s = "cold pizza")));
o.equals("cheese" + "ham" + "sauce");
o.equals(("cheese" + "ham") + "sauce");
o.equals((("cheese" + "ham")) + "sauce");
}
/**
* methods that should get flagged
*/
public void flagForEqualsIgnoreCase() {
String s = "pizza";
s.equalsIgnoreCase("hot pizza");
s.equalsIgnoreCase(s = "cold pizza");
s.equalsIgnoreCase(((s = "cold pizza")));
s.equalsIgnoreCase("cheese" + "ham" + "sauce");
s.equalsIgnoreCase(("cheese" + "ham") + "sauce");
s.equalsIgnoreCase((("cheese" + "ham")) + "sauce");
}
/**
* methods that should get flagged
*/
public void flagForBoth() {
Object o = new Object();
String s = "pizza";
o.equals("hot pizza");
o.equals(s = "cold pizza");
o.equals(((s = "cold pizza")));
o.equals("cheese" + "ham" + "sauce");
o.equals(("cheese" + "ham") + "sauce");
o.equals((("cheese" + "ham")) + "sauce");
s.equalsIgnoreCase("hot pizza");
s.equalsIgnoreCase(s = "cold pizza");
s.equalsIgnoreCase(((s = "cold pizza")));
s.equalsIgnoreCase("cheese" + "ham" + "sauce");
s.equalsIgnoreCase(("cheese" + "ham") + "sauce");
s.equalsIgnoreCase((("cheese" + "ham")) + "sauce");
}
/**
* methods that should not get flagged
*
* @return
*/
public void noFlagForEquals() {
Object o = new Object();
String s = "peperoni";
o.equals(s += "mushrooms");
(s = "thin crust").equals("thick crust");
(s += "garlic").equals("basil");
("Chicago Style" + "NY Style").equals("California Style" + "Any Style");
equals("peppers");
"onions".equals(o);
o.equals(new Object());
o.equals(equals(o));
equals("yummy");
new Object().equals("more cheese");
InputEqualsAvoidNullOutter outter = new InputEqualsAvoidNullOutter();
outter.new InputEqualsAvoidNullInner().equals("eat pizza and enjoy inner classes");
}
/**
* methods that should not get flagged
*/
public void noFlagForEqualsIgnoreCase() {
String s = "peperoni";
String s1 = "tasty";
s.equalsIgnoreCase(s += "mushrooms");
s1.equalsIgnoreCase(s += "mushrooms");
(s = "thin crust").equalsIgnoreCase("thick crust");
(s += "garlic").equalsIgnoreCase("basil");
("Chicago Style" + "NY Style").equalsIgnoreCase("California Style" + "Any Style");
"onions".equalsIgnoreCase(s);
s.equalsIgnoreCase(new String());
s.equals(s1);
new String().equalsIgnoreCase("more cheese");
}
public void noFlagForBoth() {
Object o = new Object();
String s = "peperoni";
String s1 = "tasty";
o.equals(s += "mushrooms");
(s = "thin crust").equals("thick crust");
(s += "garlic").equals("basil");
("Chicago Style" + "NY Style").equals("California Style" + "Any Style");
equals("peppers");
"onions".equals(o);
o.equals(new Object());
o.equals(equals(o));
equals("yummy");
new Object().equals("more cheese");
InputEqualsAvoidNullOutter outter = new InputEqualsAvoidNullOutter();
outter.new InputEqualsAvoidNullInner().equals("eat pizza and enjoy inner classes");
s.equalsIgnoreCase(s += "mushrooms");
s1.equalsIgnoreCase(s += "mushrooms");
<|fim▁hole|> (s = "thin crust").equalsIgnoreCase("thick crust");
(s += "garlic").equalsIgnoreCase("basil");
("Chicago Style" + "NY Style").equalsIgnoreCase("California Style" + "Any Style");
"onions".equalsIgnoreCase(s);
s.equalsIgnoreCase(new String());
s.equals(s1);
new String().equalsIgnoreCase("more cheese");
}
}
class InputEqualsAvoidNullOutter {
public class InputEqualsAvoidNullInner {
public boolean equals(Object o) {
return true;
}
}
}<|fim▁end|> | |
<|file_name|>main.js<|end_file_name|><|fim▁begin|>window.onload = function() {
document.getElementById('smile').innerHTML = ":)";<|fim▁hole|><|fim▁end|> | }; |
<|file_name|>PartnerSendQuestion.java<|end_file_name|><|fim▁begin|>package unagoclient.partner;
import unagoclient.Global;
import unagoclient.gui.*;
import javax.swing.*;
/**
* Displays a send dialog, when the partner presses "Send" in the GoFrame. The
* message is appended to the PartnerFrame.
*/
public class PartnerSendQuestion extends CloseDialog {
/**
*
*/
private static final long serialVersionUID = 1L;
PartnerGoFrame F;
JTextField T;
PartnerFrame PF;
public PartnerSendQuestion(PartnerGoFrame f, PartnerFrame pf) {
super(f, Global.resourceString("Send"), false);
this.F = f;
this.PF = pf;
<|fim▁hole|> this.add("Center", this.T = new GrayTextField(25));
final JPanel p = new MyPanel();
p.add(new ButtonAction(this, Global.resourceString("Say")));
p.add(new ButtonAction(this, Global.resourceString("Cancel")));
this.add("South", new Panel3D(p));
Global.setpacked(this, "partnersend", 200, 150);
this.validate();
this.setVisible(true);
}
@Override
public void doAction(String o) {
Global.notewindow(this, "partnersend");
if (Global.resourceString("Say").equals(o)) {
if (!this.T.getText().equals("")) {
this.PF.out(this.T.getText());
this.F.addComment(Global.resourceString("Said__")
+ this.T.getText());
}
this.setVisible(false);
this.dispose();
} else if (Global.resourceString(Global.resourceString("Cancel"))
.equals(o)) {
this.setVisible(false);
this.dispose();
} else {
super.doAction(o);
}
}
}<|fim▁end|> | this.add("North", new MyLabel(Global.resourceString("Message_")));
|
<|file_name|>buildConfig.js<|end_file_name|><|fim▁begin|><|fim▁hole|> webpack_config: {
entry: './assets/src/app.js',
},
};<|fim▁end|> | module.exports = {
bundle_id: 'app', |
<|file_name|>multi_threaded_cert_verifier_unittest.cc<|end_file_name|><|fim▁begin|>// 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 "net/base/multi_threaded_cert_verifier.h"
#include "base/bind.h"
#include "base/files/file_path.h"
#include "base/format_macros.h"
#include "base/stringprintf.h"
#include "net/base/cert_test_util.h"
#include "net/base/cert_trust_anchor_provider.h"
#include "net/base/cert_verify_proc.h"
#include "net/base/cert_verify_result.h"
#include "net/base/net_errors.h"
#include "net/base/net_log.h"
#include "net/base/test_completion_callback.h"
#include "net/base/test_data_directory.h"
#include "net/base/x509_certificate.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using testing::Mock;
using testing::ReturnRef;
namespace net {
namespace {
void FailTest(int /* result */) {
FAIL();
}
class MockCertVerifyProc : public CertVerifyProc {
public:
MockCertVerifyProc() {}
private:
virtual ~MockCertVerifyProc() {}
// CertVerifyProc implementation
virtual bool SupportsAdditionalTrustAnchors() const OVERRIDE {
return false;
}
virtual int VerifyInternal(X509Certificate* cert,
const std::string& hostname,
int flags,
CRLSet* crl_set,
const CertificateList& additional_trust_anchors,
CertVerifyResult* verify_result) OVERRIDE {
verify_result->Reset();
verify_result->verified_cert = cert;
verify_result->cert_status = CERT_STATUS_COMMON_NAME_INVALID;
return ERR_CERT_COMMON_NAME_INVALID;
}
};
class MockCertTrustAnchorProvider : public CertTrustAnchorProvider {
public:
MockCertTrustAnchorProvider() {}
virtual ~MockCertTrustAnchorProvider() {}
MOCK_METHOD0(GetAdditionalTrustAnchors, const CertificateList&());
};
} // namespace
class MultiThreadedCertVerifierTest : public ::testing::Test {
public:
MultiThreadedCertVerifierTest() : verifier_(new MockCertVerifyProc()) {}
virtual ~MultiThreadedCertVerifierTest() {}
protected:
MultiThreadedCertVerifier verifier_;
};
TEST_F(MultiThreadedCertVerifierTest, CacheHit) {
base::FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<X509Certificate> test_cert(
ImportCertFromFile(certs_dir, "ok_cert.pem"));
ASSERT_NE(static_cast<X509Certificate*>(NULL), test_cert);
int error;
CertVerifyResult verify_result;
TestCompletionCallback callback;
CertVerifier::RequestHandle request_handle;
error = verifier_.Verify(test_cert, "www.example.com", 0, NULL,
&verify_result, callback.callback(),
&request_handle, BoundNetLog());
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle != NULL);
error = callback.WaitForResult();
ASSERT_TRUE(IsCertificateError(error));
ASSERT_EQ(1u, verifier_.requests());
ASSERT_EQ(0u, verifier_.cache_hits());
ASSERT_EQ(0u, verifier_.inflight_joins());
ASSERT_EQ(1u, verifier_.GetCacheSize());
error = verifier_.Verify(test_cert, "www.example.com", 0, NULL,
&verify_result, callback.callback(),
&request_handle, BoundNetLog());
// Synchronous completion.
ASSERT_NE(ERR_IO_PENDING, error);
ASSERT_TRUE(IsCertificateError(error));
ASSERT_TRUE(request_handle == NULL);
ASSERT_EQ(2u, verifier_.requests());
ASSERT_EQ(1u, verifier_.cache_hits());
ASSERT_EQ(0u, verifier_.inflight_joins());
ASSERT_EQ(1u, verifier_.GetCacheSize());
}
// Tests the same server certificate with different intermediate CA
// certificates. These should be treated as different certificate chains even
// though the two X509Certificate objects contain the same server certificate.
TEST_F(MultiThreadedCertVerifierTest, DifferentCACerts) {
base::FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<X509Certificate> server_cert =
ImportCertFromFile(certs_dir, "salesforce_com_test.pem");
ASSERT_NE(static_cast<X509Certificate*>(NULL), server_cert);
scoped_refptr<X509Certificate> intermediate_cert1 =
ImportCertFromFile(certs_dir, "verisign_intermediate_ca_2011.pem");
ASSERT_NE(static_cast<X509Certificate*>(NULL), intermediate_cert1);
scoped_refptr<X509Certificate> intermediate_cert2 =
ImportCertFromFile(certs_dir, "verisign_intermediate_ca_2016.pem");
ASSERT_NE(static_cast<X509Certificate*>(NULL), intermediate_cert2);
X509Certificate::OSCertHandles intermediates;
intermediates.push_back(intermediate_cert1->os_cert_handle());
scoped_refptr<X509Certificate> cert_chain1 =
X509Certificate::CreateFromHandle(server_cert->os_cert_handle(),
intermediates);
intermediates.clear();
intermediates.push_back(intermediate_cert2->os_cert_handle());
scoped_refptr<X509Certificate> cert_chain2 =
X509Certificate::CreateFromHandle(server_cert->os_cert_handle(),
intermediates);
int error;
CertVerifyResult verify_result;
TestCompletionCallback callback;
CertVerifier::RequestHandle request_handle;
error = verifier_.Verify(cert_chain1, "www.example.com", 0, NULL,
&verify_result, callback.callback(),
&request_handle, BoundNetLog());
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle != NULL);
error = callback.WaitForResult();
ASSERT_TRUE(IsCertificateError(error));
ASSERT_EQ(1u, verifier_.requests());
ASSERT_EQ(0u, verifier_.cache_hits());
ASSERT_EQ(0u, verifier_.inflight_joins());
ASSERT_EQ(1u, verifier_.GetCacheSize());
error = verifier_.Verify(cert_chain2, "www.example.com", 0, NULL,
&verify_result, callback.callback(),
&request_handle, BoundNetLog());
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle != NULL);
error = callback.WaitForResult();
ASSERT_TRUE(IsCertificateError(error));
ASSERT_EQ(2u, verifier_.requests());
ASSERT_EQ(0u, verifier_.cache_hits());
ASSERT_EQ(0u, verifier_.inflight_joins());
ASSERT_EQ(2u, verifier_.GetCacheSize());
}
// Tests an inflight join.
TEST_F(MultiThreadedCertVerifierTest, InflightJoin) {
base::FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<X509Certificate> test_cert(
ImportCertFromFile(certs_dir, "ok_cert.pem"));
ASSERT_NE(static_cast<X509Certificate*>(NULL), test_cert);
int error;
CertVerifyResult verify_result;
TestCompletionCallback callback;
CertVerifier::RequestHandle request_handle;
CertVerifyResult verify_result2;
TestCompletionCallback callback2;
CertVerifier::RequestHandle request_handle2;
error = verifier_.Verify(test_cert, "www.example.com", 0, NULL,
&verify_result, callback.callback(),
&request_handle, BoundNetLog());
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle != NULL);
error = verifier_.Verify(
test_cert, "www.example.com", 0, NULL, &verify_result2,
callback2.callback(), &request_handle2, BoundNetLog());
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle2 != NULL);
error = callback.WaitForResult();
ASSERT_TRUE(IsCertificateError(error));
error = callback2.WaitForResult();
ASSERT_TRUE(IsCertificateError(error));
ASSERT_EQ(2u, verifier_.requests());
ASSERT_EQ(0u, verifier_.cache_hits());
ASSERT_EQ(1u, verifier_.inflight_joins());
}
// Tests that the callback of a canceled request is never made.
TEST_F(MultiThreadedCertVerifierTest, CancelRequest) {
base::FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<X509Certificate> test_cert(
ImportCertFromFile(certs_dir, "ok_cert.pem"));
ASSERT_NE(static_cast<X509Certificate*>(NULL), test_cert);
int error;
CertVerifyResult verify_result;
CertVerifier::RequestHandle request_handle;
error = verifier_.Verify(
test_cert, "www.example.com", 0, NULL, &verify_result,
base::Bind(&FailTest), &request_handle, BoundNetLog());
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle != NULL);
verifier_.CancelRequest(request_handle);
// Issue a few more requests to the worker pool and wait for their
// completion, so that the task of the canceled request (which runs on a
// worker thread) is likely to complete by the end of this test.
TestCompletionCallback callback;
for (int i = 0; i < 5; ++i) {
error = verifier_.Verify(
test_cert, "www2.example.com", 0, NULL, &verify_result,
callback.callback(), &request_handle, BoundNetLog());
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle != NULL);
error = callback.WaitForResult();
verifier_.ClearCache();
}
}
// Tests that a canceled request is not leaked.
TEST_F(MultiThreadedCertVerifierTest, CancelRequestThenQuit) {
base::FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<X509Certificate> test_cert(
ImportCertFromFile(certs_dir, "ok_cert.pem"));
ASSERT_NE(static_cast<X509Certificate*>(NULL), test_cert);
int error;
CertVerifyResult verify_result;
TestCompletionCallback callback;
CertVerifier::RequestHandle request_handle;
error = verifier_.Verify(test_cert, "www.example.com", 0, NULL,
&verify_result, callback.callback(),
&request_handle, BoundNetLog());
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle != NULL);
verifier_.CancelRequest(request_handle);
// Destroy |verifier| by going out of scope.
}
TEST_F(MultiThreadedCertVerifierTest, RequestParamsComparators) {
SHA1HashValue a_key;
memset(a_key.data, 'a', sizeof(a_key.data));
SHA1HashValue z_key;
memset(z_key.data, 'z', sizeof(z_key.data));
const CertificateList empty_list;
CertificateList test_list;
test_list.push_back(
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"));
struct {
// Keys to test
MultiThreadedCertVerifier::RequestParams key1;
MultiThreadedCertVerifier::RequestParams key2;
// Expectation:
// -1 means key1 is less than key2<|fim▁hole|> { // Test for basic equivalence.
MultiThreadedCertVerifier::RequestParams(a_key, a_key, "www.example.test",
0, test_list),
MultiThreadedCertVerifier::RequestParams(a_key, a_key, "www.example.test",
0, test_list),
0,
},
{ // Test that different certificates but with the same CA and for
// the same host are different validation keys.
MultiThreadedCertVerifier::RequestParams(a_key, a_key, "www.example.test",
0, test_list),
MultiThreadedCertVerifier::RequestParams(z_key, a_key, "www.example.test",
0, test_list),
-1,
},
{ // Test that the same EE certificate for the same host, but with
// different chains are different validation keys.
MultiThreadedCertVerifier::RequestParams(a_key, z_key, "www.example.test",
0, test_list),
MultiThreadedCertVerifier::RequestParams(a_key, a_key, "www.example.test",
0, test_list),
1,
},
{ // The same certificate, with the same chain, but for different
// hosts are different validation keys.
MultiThreadedCertVerifier::RequestParams(a_key, a_key,
"www1.example.test", 0,
test_list),
MultiThreadedCertVerifier::RequestParams(a_key, a_key,
"www2.example.test", 0,
test_list),
-1,
},
{ // The same certificate, chain, and host, but with different flags
// are different validation keys.
MultiThreadedCertVerifier::RequestParams(a_key, a_key, "www.example.test",
CertVerifier::VERIFY_EV_CERT,
test_list),
MultiThreadedCertVerifier::RequestParams(a_key, a_key, "www.example.test",
0, test_list),
1,
},
{ // Different additional_trust_anchors.
MultiThreadedCertVerifier::RequestParams(a_key, a_key, "www.example.test",
0, empty_list),
MultiThreadedCertVerifier::RequestParams(a_key, a_key, "www.example.test",
0, test_list),
-1,
},
};
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]", i));
const MultiThreadedCertVerifier::RequestParams& key1 = tests[i].key1;
const MultiThreadedCertVerifier::RequestParams& key2 = tests[i].key2;
switch (tests[i].expected_result) {
case -1:
EXPECT_TRUE(key1 < key2);
EXPECT_FALSE(key2 < key1);
break;
case 0:
EXPECT_FALSE(key1 < key2);
EXPECT_FALSE(key2 < key1);
break;
case 1:
EXPECT_FALSE(key1 < key2);
EXPECT_TRUE(key2 < key1);
break;
default:
FAIL() << "Invalid expectation. Can be only -1, 0, 1";
}
}
}
TEST_F(MultiThreadedCertVerifierTest, CertTrustAnchorProvider) {
MockCertTrustAnchorProvider trust_provider;
verifier_.SetCertTrustAnchorProvider(&trust_provider);
scoped_refptr<X509Certificate> test_cert(
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"));
ASSERT_TRUE(test_cert);
const CertificateList empty_cert_list;
CertificateList cert_list;
cert_list.push_back(test_cert);
// Check that Verify() asks the |trust_provider| for the current list of
// additional trust anchors.
int error;
CertVerifyResult verify_result;
TestCompletionCallback callback;
CertVerifier::RequestHandle request_handle;
EXPECT_CALL(trust_provider, GetAdditionalTrustAnchors())
.WillOnce(ReturnRef(empty_cert_list));
error = verifier_.Verify(test_cert, "www.example.com", 0, NULL,
&verify_result, callback.callback(),
&request_handle, BoundNetLog());
Mock::VerifyAndClearExpectations(&trust_provider);
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle);
error = callback.WaitForResult();
EXPECT_EQ(ERR_CERT_COMMON_NAME_INVALID, error);
ASSERT_EQ(1u, verifier_.requests());
ASSERT_EQ(0u, verifier_.cache_hits());
// The next Verify() uses the cached result.
EXPECT_CALL(trust_provider, GetAdditionalTrustAnchors())
.WillOnce(ReturnRef(empty_cert_list));
error = verifier_.Verify(test_cert, "www.example.com", 0, NULL,
&verify_result, callback.callback(),
&request_handle, BoundNetLog());
Mock::VerifyAndClearExpectations(&trust_provider);
EXPECT_EQ(ERR_CERT_COMMON_NAME_INVALID, error);
EXPECT_FALSE(request_handle);
ASSERT_EQ(2u, verifier_.requests());
ASSERT_EQ(1u, verifier_.cache_hits());
// Another Verify() for the same certificate but with a different list of
// trust anchors will not reuse the cache.
EXPECT_CALL(trust_provider, GetAdditionalTrustAnchors())
.WillOnce(ReturnRef(cert_list));
error = verifier_.Verify(test_cert, "www.example.com", 0, NULL,
&verify_result, callback.callback(),
&request_handle, BoundNetLog());
Mock::VerifyAndClearExpectations(&trust_provider);
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle != NULL);
error = callback.WaitForResult();
EXPECT_EQ(ERR_CERT_COMMON_NAME_INVALID, error);
ASSERT_EQ(3u, verifier_.requests());
ASSERT_EQ(1u, verifier_.cache_hits());
}
} // namespace net<|fim▁end|> | // 0 means key1 equals key2
// 1 means key1 is greater than key2
int expected_result;
} tests[] = { |
<|file_name|>filters.py<|end_file_name|><|fim▁begin|>import django_filters
from dal import autocomplete
from .models import SkosConcept, SkosConceptScheme
django_filters.filters.LOOKUP_TYPES = [
('', '---------'),
('exact', 'Is equal to'),
('iexact', 'Is equal to (case insensitive)'),
('not_exact', 'Is not equal to'),
('lt', 'Lesser than/before'),
('gt', 'Greater than/after'),
('gte', 'Greater than or equal to'),
('lte', 'Lesser than or equal to'),
('startswith', 'Starts with'),
('endswith', 'Ends with'),
('contains', 'Contains'),
('icontains', 'Contains (case insensitive)'),
('not_contains', 'Does not contain'),<|fim▁hole|>
class SkosConceptFilter(django_filters.FilterSet):
pref_label = django_filters.ModelMultipleChoiceFilter(
widget=autocomplete.Select2Multiple(url='vocabs-ac:skosconcept-autocomplete'),
queryset=SkosConcept.objects.all(),
lookup_expr='icontains',
label='PrefLabel',
help_text=False,
)
scheme = django_filters.ModelMultipleChoiceFilter(
queryset=SkosConceptScheme.objects.all(),
lookup_expr='icontains',
label='in SkosConceptScheme',
help_text=False,
)
class Meta:
model = SkosConcept
fields = '__all__'<|fim▁end|> | ] |
<|file_name|>saltfpringfilter.py<|end_file_name|><|fim▁begin|>################################# LICENSE ##################################
# Copyright (c) 2009, South African Astronomical Observatory (SAAO) #
# All rights reserved. #
# #
# Redistribution and use in source and binary forms, with or without #
# modification, are permitted provided that the following conditions #
# are met: #
# #
# * Redistributions of source code must retain the above copyright #
# notice, this list of conditions and the following disclaimer. #
# * Redistributions in binary form must reproduce the above copyright #
# notice, this list of conditions and the following disclaimer #
# in the documentation and/or other materials provided with the #
# distribution. #
# * Neither the name of the South African Astronomical Observatory #
# (SAAO) 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 SAAO ''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 SAAO 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. #
############################################################################
"""
RINGFILTER determines the center coordinates of a ring, bins the ring radially and computes its power spectrum, and allows the user to select a smoothing filter for the ring. It uses T. Williams code. The code assumes all the files are in the same directory. Also assumes that if there is a config file, it is also in the same directory as the data. Note that this config file is in the original FORTRAN code format so that the user does not have to write another file.<|fim▁hole|>
20100706
* First wrote the code
"""
# Ensure python 2.5 compatibility
from __future__ import with_statement
import os
import sys
import numpy as np
#import pyfits
from pyraf import iraf
from pyraf.iraf import pysalt
import saltsafekey
import saltsafeio
import fpsafeio
from saltsafelog import logging
from salterror import SaltIOError
# This reads the FORTRAN config file if it exists
from fortranfp import ringfilter_wrapper
from fortranfp.ringfilter_wrapper import getpfp
debug=True
def saltfpringfilter(axc,ayc,arad,rxc,ryc,filterfreq,filterwidth,itmax,conv, fitwidth,image,logfile,useconfig,configfile,verbose):
""" Determines the center coordinates of a ring, bins the ring radially and computes its power spectrum, and allows the user to select a smoothing filter for the ring. """
# default parameter values are set up in the pyraf .par file. The values used are then changed if a FORTRAN config file exists and the user elects to override the pyraf .par file.
# Is the input FORTRAN config file specified?
# If it is blank, then it will be ignored.
if useconfig:
configfile = configfile.strip()
if len(configfile) > 0:
#check exists
saltsafeio.fileexists(configfile)
# read updated parameters from the file
array=getpfp(configfile,"axc")
s=len(array)
flag = array[s-1]
if flag == 1:
axc=float(array[0])
array=getpfp(configfile,"ayc")
s=len(array)
flag = array[s-1]
if flag == 1:
ayc=float(array[0])
array=getpfp(configfile,"arad")
s=len(array)
flag = array[s-1]
if flag == 1:
arad=float(array[0])
array=getpfp(configfile,"rxc")
s=len(array)
flag = array[s-1]
if flag == 1:
rxc=float(array[0])
array=getpfp(configfile,"ryc")
s=len(array)
flag = array[s-1]
if flag == 1:
ryc=float(array[0])
array=getpfp(configfile,"calring_filter_width")
s=len(array)
flag = array[s-1]
if flag == 1:
filterwidth=int(array[0])
array=getpfp(configfile,"calring_filter_freq")
s=len(array)
flag = array[s-1]
if flag == 1:
filterfreq=int(array[0])
array=getpfp(configfile,"calring_itmax")
s=len(array)
flag = array[s-1]
if flag == 1:
itmax=int(array[0])
array=getpfp(configfile,"calring_conv")
s=len(array)
flag = array[s-1]
if flag == 1:
conv=float(array[0])
array=getpfp(configfile,"calring_fitwidth")
s=len(array)
flag = array[s-1]
if flag == 1:
fitwidth=float(array[0])
# getting paths for filenames
pathin = os.path.dirname(image)
basein = os.path.basename(image)
pathlog = os.path.dirname(logfile)
baselog = os.path.basename(logfile)
# forcing logfiles to be created in the same directory as the input data
# (we change to this directory once starting the fortran code)
if len(pathin) > 0:
logfile = baselog
# start log now that all parameter are set up
with logging(logfile, debug) as log:
# Some basic checks, many tests are done in the FORTRAN code itself
# is the input file specified?
saltsafeio.filedefined('Input',image)
# if the input file is a file, does it exist?
if basein[0] != '@':
saltsafeio.fileexists(image)
infile = image
# if the input file is a list, throw an error
if basein[0] == '@':
raise SaltIOError(basein + ' list input instead of a file' )
# optionally update the FORTRAN config file with new values - not implemented currently
# If all looks OK, run the FORTRAN code
if len(pathin) > 0:
dir = pathin
else:
dir = './'
infile = basein
print dir, infile, 'input directory and input file'
# Get current working directory as the Fortran code changes dir
startdir = os.getcwd()
ringfilter_wrapper.ringfilter(dir,axc, ayc,arad, rxc,ryc,filterfreq,filterwidth,itmax,conv,fitwidth,infile)
# go back to starting directory
os.chdir(startdir)
# -----------------------------------------------------------
# main code
parfile = iraf.osfn("saltfp$saltfpringfilter.par")
t = iraf.IrafTaskFactory(taskname="saltfpringfilter",value=parfile,function=saltfpringfilter,pkgname='saltfp')<|fim▁end|> |
Updates: |
<|file_name|>scimpinyin.cpp<|end_file_name|><|fim▁begin|>#define Uses_STL_AUTOPTR
#define Uses_STL_FUNCTIONAL
#define Uses_STL_VECTOR
#define Uses_STL_IOSTREAM
#define Uses_STL_FSTREAM
#define Uses_STL_ALGORITHM
#define Uses_STL_MAP
#define Uses_STL_UTILITY
#define Uses_STL_IOMANIP
#define Uses_C_STDIO
#define Uses_SCIM_UTILITY
#define Uses_SCIM_SERVER
#define Uses_SCIM_ICONV
#define Uses_SCIM_CONFIG_BASE
#define Uses_SCIM_CONFIG_PATH
#define Uses_SCIM_LOOKUP_TABLE
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include "scim/pinyin.hpp"
/*
* Sample implementation from Unicode home page.
* http://www.stonehand.com/unicode/standard/fss-utf.html
*/
struct utf8_table {
int cmask;
int cval;
int shift;
long lmask;
long lval;
};
static struct utf8_table utf8_table[] =
{
{0x80, 0x00, 0*6, 0x7F, 0, /* 1 byte sequence */},
{0xE0, 0xC0, 1*6, 0x7FF, 0x80, /* 2 byte sequence */},
{0xF0, 0xE0, 2*6, 0xFFFF, 0x800, /* 3 byte sequence */},
{0xF8, 0xF0, 3*6, 0x1FFFFF, 0x10000, /* 4 byte sequence */},
{0xFC, 0xF8, 4*6, 0x3FFFFFF, 0x200000, /* 5 byte sequence */},
{0xFE, 0xFC, 5*6, 0x7FFFFFFF, 0x4000000, /* 6 byte sequence */},
{0, /* end of table */}
};
int
utf8_mbtowc(ucs4_t *p, const __u8 *s, int n)
{
long l;
int c0, c, nc;
struct utf8_table *t;
nc = 0;
c0 = *s;
l = c0;
for (t = utf8_table; t->cmask; t++) {
nc++;
if ((c0 & t->cmask) == t->cval) {
l &= t->lmask;
if (l < t->lval)
return -1;
*p = l;
return nc;
}
if (n <= nc)
return -1;
s++;
c = (*s ^ 0x80) & 0xFF;
if (c & 0xC0)
return -1;
l = (l << 6) | c;
}
return -1;
}
int
utf8_wctomb(__u8 *s, ucs4_t wc, int maxlen)
{
long l;
int c, nc;
struct utf8_table *t;
if (s == 0)
return 0;
l = wc;
nc = 0;
for (t = utf8_table; t->cmask && maxlen; t++, maxlen--) {
nc++;
if (l <= t->lmask) {
c = t->shift;
*s = t->cval | (l >> c);
while (c > 0) {
c -= 6;
s++;
*s = 0x80 | ((l >> c) & 0x3F);
}
return nc;
}
}
return -1;
}
std::ostream &
utf8_write_wchar (std::ostream &os, ucs4_t wc)
{
unsigned char utf8[6];
int count = 0;
if ((count=utf8_wctomb (utf8, wc, 6)) > 0)
os.write ((char*)utf8, count * sizeof (unsigned char));
return os;
}
/*
// Internal functions
static int
__scim_pinyin_compare_initial (const PinyinCustomSettings &custom,
PinyinInitial lhs,
PinyinInitial rhs);
static int
__scim_pinyin_compare_final (const PinyinCustomSettings &custom,
PinyinFinal lhs,
PinyinFinal rhs);
static int
__scim_pinyin_compare_tone (const PinyinCustomSettings &custom,
PinyinTone lhs,
PinyinTone rhs);
*/
// Data definition
static const char scim_pinyin_table_text_header [] = "SCIM_Pinyin_Table_TEXT";
static const char scim_pinyin_table_binary_header [] = "SCIM_Pinyin_Table_BINARY";
static const char scim_pinyin_table_version [] = "VERSION_0_4";
/*
const PinyinCustomSettings scim_default_custom_settings =
{
true, false, true,
{false, false, false, false, false, false, false, false, false, false}
};
*/
const PinyinValidator scim_default_pinyin_validator;
const PinyinToken scim_pinyin_initials[] =
{
{"", {0}, 0, 0},
{"b", {0x3105,0}, 1, 1},
{"c", {0x3118,0}, 1, 1},
{"ch",{0x3114,0}, 2, 1},
{"d", {0x3109,0}, 1, 1},
{"f", {0x3108,0}, 1, 1},
{"g", {0x310d,0}, 1, 1},
{"h", {0x310f,0}, 1, 1},
{"j", {0x3110,0}, 1, 1},
{"k", {0x310e,0}, 1, 1},
{"l", {0x310c,0}, 1, 1},
{"m", {0x3107,0}, 1, 1},
{"n", {0x310b,0}, 1, 1},
{"p", {0x3106,0}, 1, 1},
{"q", {0x3111,0}, 1, 1},
{"r", {0x3116,0}, 1, 1},
{"s", {0x3119,0}, 1, 1},
{"sh",{0x3115,0}, 2, 1},
{"t", {0x310a,0}, 1, 1},
{"w", {0x3128,0}, 1, 1},
{"x", {0x3112,0}, 1, 1},
{"y", {0x3129,0}, 1, 1},
{"z", {0x3117,0}, 1, 1},
{"zh",{0x3113,0}, 2, 1}
};
const PinyinToken scim_pinyin_finals[] =
{
{"", {0}, 0, 0},
{"a", {0x311a,0}, 1, 1},
{"ai", {0x311e,0}, 2, 1},
{"an", {0x3122,0}, 2, 1},
{"ang", {0x3124,0}, 3, 1},
{"ao", {0x3120,0}, 2, 1},
{"e", {0x311c,0}, 1, 1},
{"ei", {0x311f,0}, 2, 1},
{"en", {0x3123,0}, 2, 1},
{"eng", {0x3125,0}, 3, 1},
{"er", {0x3126,0}, 2, 1},
{"i", {0x3127,0}, 1, 1},
{"ia", {0x3127,0x311a,0}, 2, 2},
{"ian", {0x3127,0x3122,0}, 3, 2},
{"iang",{0x3127,0x3124,0}, 4, 2},
{"iao", {0x3127,0x3120,0}, 3, 2},
{"ie", {0x3127,0x311c,0}, 2, 2},
{"in", {0x3127,0x3123,0}, 2, 2},
{"ing", {0x3127,0x3125,0}, 3, 2},
{"iong",{0x3129,0x3125,0}, 4, 2},
{"iou", {0x3127,0x3121,0}, 3, 2},
{"iu", {0x3127,0x3121,0}, 2, 2},
{"ng", {0x312b,0}, 2, 1},
{"o", {0x311b,0}, 1, 1},
{"ong", {0x3128,0x3123,0}, 3, 2},
{"ou", {0x3121,0}, 2, 1},
{"u", {0x3128,0}, 1, 1},
{"ua", {0x3128,0x311a,0}, 2, 2},
{"uai", {0x3128,0x311e,0}, 3, 2},
{"uan", {0x3128,0x3122,0}, 3, 2},
{"uang",{0x3128,0x3124,0}, 4, 2},
{"ue", {0x3129,0x311c,0}, 2, 2},
{"uei", {0x3128,0x311f,0}, 3, 2},
{"uen", {0x3128,0x3123,0}, 3, 2},
{"ueng",{0x3128,0x3125,0}, 4, 2},
{"ui", {0x3128,0x311f,0}, 2, 2},
{"un", {0x3128,0x3123,0}, 2, 2},
{"uo", {0x3128,0x311b,0}, 2, 2},
{"v", {0x3129,0}, 1, 1},
{"van", {0x3129,0x3122,0}, 3, 2},
{"ve", {0x3129,0x311c,0}, 2, 2},
{"vn", {0x3129,0x3123,0}, 2, 2}
};
const int scim_number_of_initials = sizeof (scim_pinyin_initials) / sizeof (PinyinToken);
const int scim_number_of_finals = sizeof (scim_pinyin_finals) / sizeof (PinyinToken);
//////////////////////////////////////////////////////////////////////////////
// implementation of PinyinKey
std::ostream&
PinyinKey::output_text (std::ostream &os) const
{
return os << get_key_string();
}
std::istream&
PinyinKey::input_text(const PinyinValidator &validator, std::istream &is)
{
std::string key;
is >> key;
this->setKey(validator, key);
return is;
}
/*
std::ostream&
PinyinKey::output_binary (std::ostream &os) const
{
unsigned char key [2];
combine_to_bytes (key);
os.write ((const char*) key, sizeof (char) * 2);
return os;
}
std::istream&
PinyinKey::input_binary (const PinyinValidator &validator, std::istream &is)
{
unsigned char key [2];
is.read ((char*) key, sizeof (char) * 2);
extract_from_bytes (key [0], key [1]);
if (!validator (*this)) {
m_tone = SCIM_PINYIN_ZeroTone;
if (!validator (*this)) {
m_final = SCIM_PINYIN_ZeroFinal;
if (!validator (*this))
m_initial = SCIM_PINYIN_ZeroInitial;
}
}
return is;
}
*/
int
PinyinKey::parse_initial (PinyinInitial &initial,
const char *key,
int keylen)
{
int lastlen = 0;
for (int i=0; i<scim_number_of_initials; i++) {
if (keylen >= scim_pinyin_initials [i].len
&& scim_pinyin_initials [i].len >= lastlen
&& strncmp (scim_pinyin_initials [i].str, key,
scim_pinyin_initials [i].len) == 0) {
initial = static_cast<PinyinInitial>(i);
lastlen = scim_pinyin_initials [i].len;
}
}
return lastlen;
}
int
PinyinKey::parse_final (PinyinFinal &final,
const char *key,
int keylen)
{
int lastlen = 0;
for (int i=0; i<scim_number_of_finals; i++) {
if (keylen >= scim_pinyin_finals[i].len
&& scim_pinyin_finals[i].len >= lastlen
&& strncmp (scim_pinyin_finals [i].str, key, scim_pinyin_finals[i].len) == 0) {
final = static_cast<PinyinFinal>(i);
lastlen = scim_pinyin_finals[i].len;
}
}
return lastlen;
}
int
PinyinKey::parse_tone (PinyinTone &tone,
const char *key)
{
int kt = (*key) - '0';
if (kt >= SCIM_PINYIN_First && kt <= SCIM_PINYIN_LastTone) {
tone = static_cast<PinyinTone>(kt);
return 1;
}
return 0;
}
int
PinyinKey::parse_key (PinyinInitial &initial,
PinyinFinal &final,
PinyinTone &tone,
const char *key,
int keylen)
{
if (keylen <= 0) return 0;
initial = SCIM_PINYIN_ZeroInitial;
final = SCIM_PINYIN_ZeroFinal;
tone = SCIM_PINYIN_ZeroTone;
int initial_len = 0, final_len = 0, tone_len = 0;
final_len = parse_final (final, key, keylen);
key += final_len;
keylen -= final_len;
// An initial is present
if (final == SCIM_PINYIN_ZeroFinal) {
initial_len = parse_initial (initial, key, keylen);
key += initial_len;
keylen -= initial_len;
if (keylen){
final_len = parse_final (final, key, keylen);
key += final_len;
keylen -= final_len;
}
}
if (keylen)
tone_len = parse_tone (tone, key);
apply_additional_rules(initial, final);
return initial_len + final_len + tone_len;
}
long PinyinKey::setKey(
const PinyinValidator& validator,
const std::string& key,
const long kL)
{
const long keyLen0 = key.length();
if (keyLen0 <= 0) {
return 0;
}
m_initial = SCIM_PINYIN_ZeroInitial;
m_final = SCIM_PINYIN_ZeroFinal;
m_tone = SCIM_PINYIN_ZeroTone;
PinyinInitial initial = SCIM_PINYIN_ZeroInitial;
PinyinFinal final = SCIM_PINYIN_ZeroFinal;
PinyinTone tone = SCIM_PINYIN_ZeroTone;
long keylen;
if (kL < 0) {
keylen = keyLen0;
} else {
keylen = kL;
}
keylen = parse_key(initial, final, tone, key.c_str(), keylen);
while (keylen > 0 && !validator (PinyinKey (initial, final, tone))) {
keylen = parse_key (initial, final, tone, key.c_str(), keylen-1);
}
if (keylen) {
m_initial = initial;
m_final = final;
m_tone = tone;
}
return keylen;
}
std::string PinyinKey::get_key_string(void) const
{
char key[16];
if (m_tone) {
snprintf(key, sizeof(key),
"%s%s%d", get_initial_string(), get_final_string(), m_tone);
} else {
snprintf(key, sizeof(key),
"%s%s", get_initial_string(), get_final_string());
}
key[sizeof(key) - 1] = 0;
return key;
}
/*
WideString
PinyinKey::get_key_wide_string () const
{
return WideString (get_initial_wide_string ()) + WideString (get_final_wide_string());
}
*/
void
PinyinKey::apply_additional_rules (PinyinInitial &initial, PinyinFinal &final)
{
static struct ReplaceRulePair {
PinyinInitial initial;
PinyinFinal final;
PinyinInitial new_initial;
PinyinFinal new_final;
} rules [] =
{
/*
{SCIM_PINYIN_ZeroInitial, SCIM_PINYIN_I, SCIM_PINYIN_Yi, SCIM_PINYIN_I},
{SCIM_PINYIN_ZeroInitial, SCIM_PINYIN_Ia, SCIM_PINYIN_Yi, SCIM_PINYIN_A},
{SCIM_PINYIN_ZeroInitial, SCIM_PINYIN_Ian, SCIM_PINYIN_Yi, SCIM_PINYIN_An},
{SCIM_PINYIN_ZeroInitial, SCIM_PINYIN_Iang, SCIM_PINYIN_Yi, SCIM_PINYIN_Ang},
{SCIM_PINYIN_ZeroInitial, SCIM_PINYIN_Iao, SCIM_PINYIN_Yi, SCIM_PINYIN_Ao},
{SCIM_PINYIN_ZeroInitial, SCIM_PINYIN_Ie, SCIM_PINYIN_Yi, SCIM_PINYIN_E},
{SCIM_PINYIN_ZeroInitial, SCIM_PINYIN_In, SCIM_PINYIN_Yi, SCIM_PINYIN_In},
{SCIM_PINYIN_ZeroInitial, SCIM_PINYIN_Ing, SCIM_PINYIN_Yi, SCIM_PINYIN_Ing},
{SCIM_PINYIN_ZeroInitial, SCIM_PINYIN_Iong, SCIM_PINYIN_Yi, SCIM_PINYIN_Ong},
{SCIM_PINYIN_ZeroInitial, SCIM_PINYIN_Iou, SCIM_PINYIN_Yi, SCIM_PINYIN_Ou},
{SCIM_PINYIN_ZeroInitial, SCIM_PINYIN_Iu, SCIM_PINYIN_Yi, SCIM_PINYIN_U},
{SCIM_PINYIN_ZeroInitial, SCIM_PINYIN_U, SCIM_PINYIN_Wo, SCIM_PINYIN_U},
{SCIM_PINYIN_ZeroInitial, SCIM_PINYIN_Ua, SCIM_PINYIN_Wo, SCIM_PINYIN_A},
{SCIM_PINYIN_ZeroInitial, SCIM_PINYIN_Uai, SCIM_PINYIN_Wo, SCIM_PINYIN_Ai},
{SCIM_PINYIN_ZeroInitial, SCIM_PINYIN_Uan, SCIM_PINYIN_Wo, SCIM_PINYIN_An},
{SCIM_PINYIN_ZeroInitial, SCIM_PINYIN_Uang, SCIM_PINYIN_Wo, SCIM_PINYIN_Ang},
{SCIM_PINYIN_ZeroInitial, SCIM_PINYIN_Uei, SCIM_PINYIN_Wo, SCIM_PINYIN_Ei},
{SCIM_PINYIN_ZeroInitial, SCIM_PINYIN_Uen, SCIM_PINYIN_Wo, SCIM_PINYIN_En},
{SCIM_PINYIN_ZeroInitial, SCIM_PINYIN_Ueng, SCIM_PINYIN_Wo, SCIM_PINYIN_Eng},
{SCIM_PINYIN_ZeroInitial, SCIM_PINYIN_Ui, SCIM_PINYIN_Wo, SCIM_PINYIN_Ei},
{SCIM_PINYIN_ZeroInitial, SCIM_PINYIN_Un, SCIM_PINYIN_Wo, SCIM_PINYIN_En},
{SCIM_PINYIN_ZeroInitial, SCIM_PINYIN_Uo, SCIM_PINYIN_Wo, SCIM_PINYIN_O},
{SCIM_PINYIN_ZeroInitial, SCIM_PINYIN_Ue, SCIM_PINYIN_Yi, SCIM_PINYIN_Ue},
{SCIM_PINYIN_ZeroInitial, SCIM_PINYIN_V, SCIM_PINYIN_Yi, SCIM_PINYIN_U},
{SCIM_PINYIN_ZeroInitial, SCIM_PINYIN_Van, SCIM_PINYIN_Yi, SCIM_PINYIN_Uan},
{SCIM_PINYIN_ZeroInitial, SCIM_PINYIN_Ve, SCIM_PINYIN_Yi, SCIM_PINYIN_Ue},
{SCIM_PINYIN_ZeroInitial, SCIM_PINYIN_Vn, SCIM_PINYIN_Yi, SCIM_PINYIN_Un},
*/
{SCIM_PINYIN_Ne, SCIM_PINYIN_Ve, SCIM_PINYIN_Ne, SCIM_PINYIN_Ue},
{SCIM_PINYIN_Le, SCIM_PINYIN_Ve, SCIM_PINYIN_Le, SCIM_PINYIN_Ue},
{SCIM_PINYIN_Ji, SCIM_PINYIN_V, SCIM_PINYIN_Ji, SCIM_PINYIN_U},
{SCIM_PINYIN_Ji, SCIM_PINYIN_Van, SCIM_PINYIN_Ji, SCIM_PINYIN_Uan},
{SCIM_PINYIN_Ji, SCIM_PINYIN_Ve, SCIM_PINYIN_Ji, SCIM_PINYIN_Ue},
{SCIM_PINYIN_Ji, SCIM_PINYIN_Vn, SCIM_PINYIN_Ji, SCIM_PINYIN_Un},
{SCIM_PINYIN_Qi, SCIM_PINYIN_V, SCIM_PINYIN_Qi, SCIM_PINYIN_U},
{SCIM_PINYIN_Qi, SCIM_PINYIN_Van, SCIM_PINYIN_Qi, SCIM_PINYIN_Uan},
{SCIM_PINYIN_Qi, SCIM_PINYIN_Ve, SCIM_PINYIN_Qi, SCIM_PINYIN_Ue},
{SCIM_PINYIN_Qi, SCIM_PINYIN_Vn, SCIM_PINYIN_Qi, SCIM_PINYIN_Un},
{SCIM_PINYIN_Xi, SCIM_PINYIN_V, SCIM_PINYIN_Xi, SCIM_PINYIN_U},
{SCIM_PINYIN_Xi, SCIM_PINYIN_Van, SCIM_PINYIN_Xi, SCIM_PINYIN_Uan},
{SCIM_PINYIN_Xi, SCIM_PINYIN_Ve, SCIM_PINYIN_Xi, SCIM_PINYIN_Ue},
{SCIM_PINYIN_Xi, SCIM_PINYIN_Vn, SCIM_PINYIN_Xi, SCIM_PINYIN_Un}
};
for (unsigned int i=0; i<sizeof(rules)/sizeof(ReplaceRulePair); i++) {
if (rules[i].initial == initial && rules[i].final == final) {
initial = rules[i].new_initial;
final = rules[i].new_final;
break;
}
}
if (initial != SCIM_PINYIN_ZeroInitial && final == SCIM_PINYIN_Iou)
final = SCIM_PINYIN_Iu;
if (initial != SCIM_PINYIN_ZeroInitial && final == SCIM_PINYIN_Uei)
final = SCIM_PINYIN_Ui;
if (initial != SCIM_PINYIN_ZeroInitial && final == SCIM_PINYIN_Uen)
final = SCIM_PINYIN_Un;
}
int
PinyinKey::parse_pinyin_key (const PinyinValidator &validator,
PinyinParsedKeyVector &vec,
const char *key)
{
#if 0
vec.clear ();
int usedlen = 0;
int keylen = strlen (key);
if (keylen <= 0) return 0;
PinyinParsedKey aKey;
while (usedlen < keylen) {
if (!isalpha (*key)) {
key ++;
usedlen ++;
continue;
}
int len = aKey.set_key (validator, key);
if (len) {
aKey.set_pos (usedlen);
aKey.set_length (len);
vec.push_back (aKey);
} else {
break;
}
key += len;
usedlen += len;
}
return usedlen;
#else
vec.clear ();
int keylen = strlen (key);
if (keylen <= 0) return 0;
PinyinParsedKey aKey;
int usedlen = 0;
int len;
bool found;
const char *key_start, *key_end;
key_end = key + keylen;
while (key_end > key) {
if (*(key_end-1) == '\'') {
--key_end;
--keylen;
if (keylen == 0) break;
}
key_start = std::max (key_end - SCIM_PINYIN_KEY_MAXLEN, key);
found = false;
while (key_start < key_end) {
if (isalpha (*key_start)) {
len = aKey.setKey(validator, key_start, key_end - key_start);
if (len == key_end - key_start) {
found = true;
aKey.set_pos (key_start - key);
aKey.set_length (len);
usedlen += len;
key_end = key_start;
vec.push_back (aKey);
break;
}
}
++ key_start;
}
if (!found) {
-- keylen;
key_end = key + keylen;
usedlen = 0;
vec.clear ();
}
}
std::reverse (vec.begin (), vec.end ());
return usedlen;
#endif
}
int
PinyinKey::parse_pinyin_key(
const PinyinValidator &validator,
PinyinKeyVector &vec,
const char *key)
{
#if 0
vec.clear ();
int usedlen = 0;
int keylen = strlen (key);
if (keylen <= 0) return 0;
PinyinKey aKey;
while (usedlen < keylen) {
if (!isalpha (*key)) {
key ++;
usedlen ++;
continue;
}
int len = aKey.set_key (validator, key);
if (len && validator (aKey)) {
vec.push_back (aKey);
} else if (!len) break;
key += len;
usedlen += len;
}
return usedlen;
#else
vec.clear ();
int keylen = strlen (key);
if (keylen <= 0) return 0;
PinyinKey aKey;
int usedlen = 0;
int len;
bool found;
const char *key_start, *key_end;
key_end = key + keylen;
while (key_end > key) {
if (*(key_end-1) == '\'') {
--key_end;
--keylen;
if (keylen == 0) break;
}
key_start = std::max (key_end - SCIM_PINYIN_KEY_MAXLEN, key);
found = false;
while (key_start < key_end) {
if (isalpha (*key_start)) {
len = aKey.setKey(validator, key_start, key_end - key_start);
if (len == key_end - key_start) {
found = true;
usedlen += len;
key_end = key_start;
vec.push_back (aKey);
break;
}<|fim▁hole|> if (!found) {
-- keylen;
key_end = key + keylen;
usedlen = 0;
vec.clear ();
}
}
std::reverse (vec.begin (), vec.end ());
return usedlen;
#endif
}
//////////////////////////////////////////////////////////////////////////////
// implementation of PinyinValidator
PinyinValidator::PinyinValidator(
/*const PinyinCustomSettings &custom,(*/
const PinyinTable * table)
{
this->initialize(/*custom, */table);
}
void
PinyinValidator::initialize (/*const PinyinCustomSettings &custom,*/
const PinyinTable *table)
{
memset (m_bitmap, 0, PinyinValidatorBitmapSize);
if (!table || table->size() <=0) return;
for (int i=0; i<SCIM_PINYIN_InitialNumber; i++) {
for (int j=0; j<SCIM_PINYIN_FinalNumber; j++) {
for (int k=0; k<SCIM_PINYIN_ToneNumber; k++) {
PinyinKey key(static_cast<PinyinInitial>(i),
static_cast<PinyinFinal>(j),
static_cast<PinyinTone>(k));
if (!table->has_key (key)) {
int val = (k * SCIM_PINYIN_FinalNumber + j) * SCIM_PINYIN_InitialNumber + i;
m_bitmap [val >> 3] |= (1 << (val % 8));
}
}
}
}
}
bool
PinyinValidator::operator () (PinyinKey key) const
{
if (key.get_initial () == SCIM_PINYIN_ZeroInitial && key.get_final () == SCIM_PINYIN_ZeroFinal)
return false;
int val = (key.get_tone () * SCIM_PINYIN_FinalNumber + key.get_final ()) *
SCIM_PINYIN_InitialNumber + key.get_initial ();
return (m_bitmap [ val >> 3 ] & (1 << (val % 8))) == 0;
}
/*
//////////////////////////////////////////////////////////////////////////////
// implementation of PinyinKey comparision classes
static int
__scim_pinyin_compare_initial (const PinyinCustomSettings &custom,
PinyinInitial lhs,
PinyinInitial rhs)
{
// Ambiguity LeRi, NeLe, FoHe will break binary search
// we treat them as special cases
if (custom.use_ambiguities [SCIM_PINYIN_AmbLeRi]) {
if (lhs == SCIM_PINYIN_Ri) lhs = SCIM_PINYIN_Le;
if (rhs == SCIM_PINYIN_Ri) rhs = SCIM_PINYIN_Le;
}
if (custom.use_ambiguities [SCIM_PINYIN_AmbNeLe]) {
if (lhs == SCIM_PINYIN_Ne) lhs = SCIM_PINYIN_Le;
if (rhs == SCIM_PINYIN_Ne) rhs = SCIM_PINYIN_Le;
}
if (custom.use_ambiguities [SCIM_PINYIN_AmbFoHe]) {
if (lhs == SCIM_PINYIN_He) lhs = SCIM_PINYIN_Fo;
if (rhs == SCIM_PINYIN_He) rhs = SCIM_PINYIN_Fo;
}
if ((lhs == rhs) ||
(custom.use_ambiguities [SCIM_PINYIN_AmbZhiZi] &&
((lhs == SCIM_PINYIN_Zhi && rhs == SCIM_PINYIN_Zi) ||
(lhs == SCIM_PINYIN_Zi && rhs == SCIM_PINYIN_Zhi))) ||
(custom.use_ambiguities [SCIM_PINYIN_AmbChiCi] &&
((lhs == SCIM_PINYIN_Chi && rhs == SCIM_PINYIN_Ci) ||
(lhs == SCIM_PINYIN_Ci && rhs == SCIM_PINYIN_Chi))) ||
(custom.use_ambiguities [SCIM_PINYIN_AmbShiSi] &&
((lhs == SCIM_PINYIN_Shi && rhs == SCIM_PINYIN_Si) ||
(lhs == SCIM_PINYIN_Si && rhs == SCIM_PINYIN_Shi))))
return 0;
else if (lhs < rhs) return -1;
return 1;
}
static int
__scim_pinyin_compare_final (const PinyinCustomSettings &custom,
PinyinFinal lhs,
PinyinFinal rhs)
{
if(((lhs == rhs) ||
(custom.use_ambiguities [SCIM_PINYIN_AmbAnAng] &&
((lhs == SCIM_PINYIN_An && rhs == SCIM_PINYIN_Ang) ||
(lhs == SCIM_PINYIN_Ang && rhs == SCIM_PINYIN_An))) ||
(custom.use_ambiguities [SCIM_PINYIN_AmbEnEng] &&
((lhs == SCIM_PINYIN_En && rhs == SCIM_PINYIN_Eng) ||
(lhs == SCIM_PINYIN_Eng && rhs == SCIM_PINYIN_En))) ||
(custom.use_ambiguities [SCIM_PINYIN_AmbInIng] &&
((lhs == SCIM_PINYIN_In && rhs == SCIM_PINYIN_Ing) ||
(lhs == SCIM_PINYIN_Ing && rhs == SCIM_PINYIN_In)))))
return 0;
else if (custom.use_incomplete && (lhs == SCIM_PINYIN_ZeroFinal || rhs == SCIM_PINYIN_ZeroFinal))
return 0;
else if (lhs < rhs) return -1;
return 1;
}
static int
__scim_pinyin_compare_tone (const PinyinCustomSettings &custom,
PinyinTone lhs,
PinyinTone rhs)
{
if(lhs == rhs || lhs == SCIM_PINYIN_ZeroTone || rhs == SCIM_PINYIN_ZeroTone || !custom.use_tone)
return 0;
else if (lhs < rhs) return -1;
return 1;
}
bool
PinyinKeyLessThan::operator () (PinyinKey lhs, PinyinKey rhs) const
{
switch (__scim_pinyin_compare_initial (m_custom,
static_cast<PinyinInitial>(lhs.m_initial),
static_cast<PinyinInitial>(rhs.m_initial))) {
case 0:
switch (__scim_pinyin_compare_final (m_custom,
static_cast<PinyinFinal>(lhs.m_final),
static_cast<PinyinFinal>(rhs.m_final))) {
case 0:
switch (__scim_pinyin_compare_tone (m_custom,
static_cast<PinyinTone>(lhs.m_tone),
static_cast<PinyinTone>(rhs.m_tone))) {
case -1:
return true;
default:
return false;
}
case -1:
return true;
default:
return false;
}
case -1:
return true;
default:
return false;
}
return false;
}
bool
PinyinKeyEqualTo::operator () (PinyinKey lhs, PinyinKey rhs) const
{
if (!__scim_pinyin_compare_initial (m_custom,
static_cast<PinyinInitial>(lhs.m_initial),
static_cast<PinyinInitial>(rhs.m_initial)) &&
!__scim_pinyin_compare_final (m_custom,
static_cast<PinyinFinal>(lhs.m_final),
static_cast<PinyinFinal>(rhs.m_final)) &&
!__scim_pinyin_compare_tone (m_custom,
static_cast<PinyinTone>(lhs.m_tone),
static_cast<PinyinTone>(rhs.m_tone)))
return true;
return false;
}
*/
//////////////////////////////////////////////////////////////////////////////
// implementation of PinyinEntry
std::ostream&
PinyinEntry::output_text (std::ostream &os) const
{
m_key.output_text (os) << "\t" << size() << "\t";
for (std::vector<CharFrequencyPair>::const_iterator i = m_chars.begin(); i != m_chars.end(); i++) {
utf8_write_wchar (os, i->first);
os << i->second << ' ';
}
os << '\n';
return os;
}
/*
std::ostream&
PinyinEntry::output_binary (std::ostream &os) const
{
unsigned char bytes [8];
m_key.output_binary (os);
scim_uint32tobytes (bytes, (uint32) size());
os.write ((char*)bytes, sizeof (unsigned char) * 4);
for (std::vector<CharFrequencyPair>::const_iterator i = m_chars.begin(); i != m_chars.end(); i++) {
utf8_write_wchar (os, i->first);
scim_uint32tobytes (bytes, i->second);
os.write ((char*)bytes, sizeof (unsigned char) * 4);
}
return os;
}
*/
std::istream&
PinyinEntry::input_text (const PinyinValidator &validator, std::istream &is)
{
m_chars.clear();
std::string value;
uint32 n, len, freq;
ucs4_t wc;
m_key.input_text (validator, is);
is >> n;
m_chars.reserve (n+1);
for (uint32 i=0; i<n; i++) {
is >> value;
if(strcmp(value.c_str(),"0")==0){
continue;
}
if ((len = utf8_mbtowc (&wc, (const unsigned char*)(value.c_str()), value.length())) > 0) {
if (value.length () > len)
freq = atoi (value.c_str() + len);
else
freq = 0;
m_chars.push_back (CharFrequencyPair (wc,freq));
}
}
sort ();
std::vector <CharFrequencyPair> (m_chars).swap (m_chars);
return is;
}
/*
std::istream&
PinyinEntry::input_binary (const PinyinValidator &validator, std::istream &is)
{
m_chars.clear();
uint32 n, freq;
ucs4_t wc;
unsigned char bytes [8];
m_key.input_binary (validator, is);
is.read ((char*)bytes, sizeof (unsigned char) * 4);
n = scim_bytestouint32 (bytes);
m_chars.reserve (n+1);
for (uint32 i=0; i<n; i++) {
if ((wc = utf8_read_wchar (is)) > 0) {
is.read ((char*)bytes, sizeof (unsigned char) * 4);
freq = scim_bytestouint32 (bytes);
m_chars.push_back (CharFrequencyPair (wc, freq));
}
}
sort ();
std::vector <CharFrequencyPair> (m_chars).swap (m_chars);
return is;
}
*/
PinyinTable::PinyinTable(void): m_validator(0)
{
}
PinyinTable::PinyinTable(
/*const PinyinCustomSettings& custom,*/
const PinyinValidator * validator,
std::istream& is):
/*revmap_ok (false),
pinyin_key_less (custom),
pinyin_key_equal (custom),*/
m_validator (validator)
/* custom (custom) */
{
if (!m_validator) m_validator = &scim_default_pinyin_validator;
input (is);
}
PinyinTable::PinyinTable(
/*(const PinyinCustomSettings &custom,*/
const PinyinValidator * validator,
const std::string& tablefile):
/*
revmap_ok(false),
pinyin_key_less(custom),
pinyin_key_equal(custom),
*/
m_validator(validator)
/* custom(custom) */
{
if (!this->m_validator) {
this->m_validator = &scim_default_pinyin_validator;
}
if (tablefile.length() > 0) {
this->loadTable(tablefile);
}
}
/**
* @brief init
* @todo deinit first
*/
void PinyinTable::init(
const PinyinValidator * validator,
const std::string& tablefile)
{
this->m_validator = validator;
if (!this->m_validator) {
this->m_validator = &scim_default_pinyin_validator;
}
if (tablefile.length() > 0) {
this->loadTable(tablefile);
}
}
bool
PinyinTable::output (std::ostream &os, bool binary) const
{
unsigned char bytes [8];
if (!binary) {
os << scim_pinyin_table_text_header << "\n";
os << scim_pinyin_table_version << "\n";
os << m_table.size () << "\n";
for (
PinyinEntryVector::const_iterator i = m_table.begin();
i != m_table.end();
++i) {
i->output_text(os);
}
}/* else {
os << scim_pinyin_table_binary_header << "\n";
os << scim_pinyin_table_version << "\n";
scim_uint32tobytes (bytes, (uint32) m_table.size ());
os.write ((char*)bytes, sizeof (unsigned char) * 4);
for (PinyinEntryVector::const_iterator i = m_table.begin(); i!=m_table.end(); i++)
i->output_binary (os);
}*/
return true;
}
bool
PinyinTable::input (std::istream &is)
{
char header [40];
bool binary;
if (!is) return false;
is.getline (header, 40);
if (strncmp (header,
scim_pinyin_table_text_header,
strlen (scim_pinyin_table_text_header)) == 0) {
binary = false;
} else if (strncmp (header,
scim_pinyin_table_binary_header,
strlen (scim_pinyin_table_binary_header)) == 0) {
binary = true;
} else {
return false;
}
is.getline (header, 40);
if (strncmp (header, scim_pinyin_table_version, strlen (scim_pinyin_table_version)) != 0)
return false;
uint32 i;
uint32 n;
PinyinEntryVector::iterator ev;
if (!binary) {
is >> n;
// load pinyin table
for (i=0; i<n; i++) {
PinyinEntry entry (*m_validator, is/*, false*/);
//if (!m_custom.use_tone) {
entry.set_key (PinyinKey (entry.get_key ().get_initial (),
entry.get_key ().get_final (),
SCIM_PINYIN_ZeroTone));
//}
if (entry.get_key().get_final() == SCIM_PINYIN_ZeroFinal) {
std::cerr << "Invalid entry: " << entry << "\n";
} else {
if ((ev = find_exact_entry (entry)) == m_table.end())
m_table.push_back (entry);
else {
for (uint32 i=0; i<entry.size(); i++) {
ev->insert (entry.get_char_with_frequency_by_index (i));
}
}
}
}
/*
} else {
unsigned char bytes [8];
is.read ((char*) bytes, sizeof (unsigned char) * 4);
n = scim_bytestouint32 (bytes);
// load pinyin table
for (i=0; i<n; i++) {
PinyinEntry entry (*m_validator, is, true);
if (!m_custom.use_tone) {
entry.set_key (PinyinKey (entry.get_key ().get_initial (),
entry.get_key ().get_final (),
SCIM_PINYIN_ZeroTone));
}
if (entry.get_key().get_final() == SCIM_PINYIN_ZeroFinal) {
std::cerr << "Invalid entry: " << entry << "\n";
} else {
if ((ev = find_exact_entry (entry)) == m_table.end())
m_table.push_back (entry);
else {
for (uint32 i=0; i<entry.size(); i++) {
ev->insert (entry.get_char_with_frequency_by_index (i));
}
}
}
}*/
}
sort ();
return true;
}
/**
* @brief load table
*/
bool PinyinTable::loadTable(const std::string& tablefile)
{
# if (__cplusplus >= 201103L)
std::ifstream ifs(tablefile);
# else
std::ifstream ifs(tablefile.c_str());
# endif /* if (__cplusplus >= 201103L) else */
if (!ifs) {
return false;
}
bool ret;
if (input(ifs) && m_table.size () != 0) {
ret = true;
} else {
ret = false;
}
ifs.close();
return ret;
}
/**
* @brief save table
*/
bool PinyinTable::saveTable(const std::string& tablefile, bool binary) const
{
# if (__cplusplus >= 201103L)
std::ofstream ofs(tablefile);
# else
std::ofstream ofs(tablefile.c_str());
# endif /* if (__cplusplus >= 201103L) else */
if (!ofs) {
return false;
}
if (this->output(ofs, binary)) {
return true;
}
return false;
}
/*
void
PinyinTable::update_custom_settings (const PinyinCustomSettings &custom,
const PinyinValidator *validator)
{
m_pinyin_key_less = PinyinKeyLessThan (custom);
m_pinyin_key_equal = PinyinKeyEqualTo (custom);
m_validator = validator;
if (!m_validator)
m_validator = &scim_default_pinyin_validator;
m_custom = custom;
sort ();
}
int
PinyinTable::get_all_chars (std::vector<ucs4_t> &vec) const
{
std::vector<CharFrequencyPair> all;
vec.clear ();
get_all_chars_with_frequencies (all);
for (std::vector<CharFrequencyPair>::const_iterator i = all.begin ();
i != all.end (); ++i)
vec.push_back (i->first);
return vec.size ();
}
int
PinyinTable::get_all_chars_with_frequencies (std::vector<CharFrequencyPair> &vec) const
{
vec.clear ();
for (PinyinEntryVector::const_iterator i = m_table.begin (); i!= m_table.end (); i++)
i->get_all_chars_with_frequencies (vec);
if (!vec.size ()) return 0;
std::sort (vec.begin (), vec.end (), CharFrequencyPairGreaterThanByCharAndFrequency ());
vec.erase (std::unique (vec.begin (), vec.end (), CharFrequencyPairEqualToByChar ()), vec.end ());
std::sort (vec.begin (), vec.end (), CharFrequencyPairGreaterThanByFrequency ());
return vec.size ();
}
*/
int
PinyinTable::find_chars (std::vector <ucs4_t> &vec, PinyinKey key) const
{
std::vector<CharFrequencyPair> all;
vec.clear ();
find_chars_with_frequencies (all, key);
for (std::vector<CharFrequencyPair>::const_iterator i = all.begin ();
i != all.end (); ++i)
vec.push_back (i->first);
return vec.size ();
}
int
PinyinTable::find_chars_with_frequencies (std::vector <CharFrequencyPair> &vec, PinyinKey key) const
{
vec.clear ();
std::pair<PinyinEntryVector::const_iterator, PinyinEntryVector::const_iterator> range =
std::equal_range(m_table.begin(), m_table.end(), key, m_pinyin_key_less);
for (PinyinEntryVector::const_iterator i = range.first; i!= range.second; i++) {
i->get_all_chars_with_frequencies (vec);
}
if (!vec.size ()) return 0;
std::sort (vec.begin (), vec.end (), CharFrequencyPairGreaterThanByCharAndFrequency ());
vec.erase (std::unique (vec.begin (), vec.end (), CharFrequencyPairEqualToByChar ()), vec.end ());
std::sort (vec.begin (), vec.end (), CharFrequencyPairGreaterThanByFrequency ());
return vec.size ();
}
void
PinyinTable::erase (ucs4_t hz, const char *key)
{
erase (hz, PinyinKey (*m_validator, key));
}
void
PinyinTable::erase (ucs4_t hz, PinyinKey key)
{
if (key.zero()) {
for (PinyinEntryVector::iterator i = m_table.begin(); i != m_table.end(); i++)
i->erase (hz);
} else {
std::pair<PinyinEntryVector::iterator, PinyinEntryVector::iterator> range =
std::equal_range(m_table.begin(), m_table.end(), key, m_pinyin_key_less);
for (PinyinEntryVector::iterator i = range.first; i!= range.second; i++)
i->erase (hz);
}
//erase_from_reverse_map (hz, key);
}
uint32
PinyinTable::get_char_frequency (ucs4_t ch, PinyinKey key)
{
PinyinKeyVector keyvec;
uint32 freq = 0;
if (key.zero ())
find_keys (keyvec, ch);
else
keyvec.push_back (key);
for (PinyinKeyVector::iterator i = keyvec.begin (); i != keyvec.end (); ++i) {
std::pair<PinyinEntryVector::iterator, PinyinEntryVector::iterator> range =
std::equal_range(m_table.begin(), m_table.end(), *i, m_pinyin_key_less);
for (PinyinEntryVector::iterator vi = range.first; vi!= range.second; ++vi) {
freq += vi->get_char_frequency (ch);
}
}
return freq;
}
void
PinyinTable::set_char_frequency (ucs4_t ch, uint32 freq, PinyinKey key)
{
PinyinKeyVector keyvec;
if (key.zero ())
find_keys (keyvec, ch);
else
keyvec.push_back (key);
for (PinyinKeyVector::iterator i = keyvec.begin (); i != keyvec.end (); ++i) {
std::pair<PinyinEntryVector::iterator, PinyinEntryVector::iterator> range =
std::equal_range(m_table.begin(), m_table.end(), *i, m_pinyin_key_less);
for (PinyinEntryVector::iterator vi = range.first; vi != range.second; ++vi) {
vi->set_char_frequency (ch, freq / (keyvec.size () * (range.second - range.first)));
}
}
}
void
PinyinTable::refresh (ucs4_t hz, uint32 shift, PinyinKey key)
{
if (!hz) return;
PinyinKeyVector keyvec;
uint32 freq, delta;
if (key.zero ())
find_keys (keyvec, hz);
else
keyvec.push_back (key);
for (PinyinKeyVector::iterator i = keyvec.begin (); i != keyvec.end (); ++i) {
std::pair<PinyinEntryVector::iterator, PinyinEntryVector::iterator> range =
std::equal_range(m_table.begin(), m_table.end(), *i, m_pinyin_key_less);
for (PinyinEntryVector::iterator vi = range.first; vi!= range.second; ++vi) {
vi->refresh_char_frequency (hz, shift);
}
}
}
void
PinyinTable::insert (ucs4_t hz, const char *key)
{
insert (hz, PinyinKey (*m_validator, key));
}
void
PinyinTable::insert (ucs4_t hz, PinyinKey key)
{
PinyinEntryVector::iterator i =
std::lower_bound (m_table.begin(), m_table.end(), key, m_pinyin_key_less);
if (i != m_table.end() && m_pinyin_key_equal (*i, key)) {
i->insert (CharFrequencyPair (hz,0));
} else {
PinyinEntry entry (key);
entry.insert (CharFrequencyPair (hz,0));
m_table.insert (i, entry);
}
//insert_to_reverse_map (hz, key);
}
size_t
PinyinTable::size () const
{
size_t num = 0;
for (PinyinEntryVector::const_iterator i = m_table.begin(); i!= m_table.end(); i++)
num += i->size ();
return num;
}
int
PinyinTable::find_keys (PinyinKeyVector &vec, ucs4_t code)
{
// if (!m_revmap_ok) create_reverse_map ();
vec.clear ();
/*
std::pair<ReversePinyinMap::const_iterator, ReversePinyinMap::const_iterator> result =
m_revmap.equal_range (code);
for (ReversePinyinMap::const_iterator i = result.first; i != result.second; i++)
vec.push_back (i->second);
*/
return vec.size ();
}
int
PinyinTable::find_key_strings (std::vector<PinyinKeyVector> &vec, const WideString & str)
{
vec.clear ();
PinyinKeyVector *key_vectors = new PinyinKeyVector [str.size()];
for (uint32 i=0; i<str.length (); i++)
find_keys (key_vectors[i], str [i]);
PinyinKeyVector key_buffer;
create_pinyin_key_vector_vector (vec, key_buffer, key_vectors, 0, str.size());
delete [] key_vectors;
return vec.size ();
}
bool
PinyinTable::has_key (const char *key) const
{
return has_key (PinyinKey (*m_validator, key));
}
bool
PinyinTable::has_key (PinyinKey key) const
{
return std::binary_search (m_table.begin(), m_table.end(), key, m_pinyin_key_less);
}
void
PinyinTable::sort ()
{
std::sort (m_table.begin(), m_table.end(), m_pinyin_key_less);
}
/*
void
PinyinTable::create_reverse_map ()
{
m_revmap.clear();
PinyinKey key;
for (PinyinEntryVector::iterator i = m_table.begin(); i != m_table.end(); i++) {
key = i->get_key();
for (unsigned int j = 0; j < i->size (); j++) {
m_revmap.insert (ReversePinyinPair (i->get_char_by_index (j), key));
}
}
m_revmap_ok = true;
}
void
PinyinTable::insert_to_reverse_map (ucs4_t code, PinyinKey key)
{
if (key.zero())
return;
std::pair<ReversePinyinMap::iterator, ReversePinyinMap::iterator> result =
m_revmap.equal_range (code);
for (ReversePinyinMap::iterator i = result.first; i != result.second; i++)
if (m_pinyin_key_equal (i->second, key)) return;
m_revmap.insert (ReversePinyinPair (code, key));
}
void
PinyinTable::erase_from_reverse_map (ucs4_t code, PinyinKey key)
{
if (key.zero()) {
m_revmap.erase (code);
} else {
std::pair<ReversePinyinMap::iterator, ReversePinyinMap::iterator> result =
m_revmap.equal_range (code);
for (ReversePinyinMap::iterator i = result.first; i != result.second; i++)
if (m_pinyin_key_equal (i->second, key)) {
m_revmap.erase (i);
break;
}
}
}
*/
PinyinTable::PinyinEntryVector::iterator
PinyinTable::find_exact_entry (PinyinKey key)
{
PinyinKeyExactEqualTo eq;
for (PinyinEntryVector::iterator i=m_table.begin (); i!=m_table.end (); i++)
if (eq (*i, key)) return i;
return m_table.end ();
}
void
PinyinTable::create_pinyin_key_vector_vector (std::vector<PinyinKeyVector> &vv,
PinyinKeyVector &key_buffer,
PinyinKeyVector *key_vectors,
int index,
int len)
{
for (unsigned int i=0; i< key_vectors[index].size(); i++) {
key_buffer.push_back ((key_vectors[index])[i]);
if (index == len-1) {
vv.push_back (key_buffer);
} else {
create_pinyin_key_vector_vector (vv, key_buffer, key_vectors, index+1, len);
}
key_buffer.pop_back ();
}
}
/*
vi:ts=4:nowrap:ai
*/<|fim▁end|> | }
++ key_start;
} |
<|file_name|>test_playbookrunner.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (C) 2016 Matthias Luescher
#
# Authors:
# Matthias Luescher
#
# This file is part of edi.
#
# edi is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# edi is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with edi. If not, see <http://www.gnu.org/licenses/>.
from edi.lib.configurationparser import ConfigurationParser
from edi.lib.playbookrunner import PlaybookRunner
from tests.libtesting.fixtures.configfiles import config_files
from tests.libtesting.helpers import get_command_parameter
from edi.lib import mockablerun
import shutil
import subprocess
from codecs import open
import yaml
def verify_inventory(file):
with open(file, encoding='utf-8') as f:
assert 'fake-container' in f.read()
def verify_extra_vars(file):
print(file)
with open(file, encoding='utf-8') as f:
extra_vars = yaml.load(f)
assert extra_vars['edi_config_management_user_name'] == 'edicfgmgmt'
mountpoints = extra_vars['edi_shared_folder_mountpoints']
assert len(mountpoints) == 2
assert mountpoints[0] == '/foo/bar/target_mountpoint'
def test_lxd_connection(config_files, monkeypatch):
def fake_ansible_playbook_run(*popenargs, **kwargs):
command = popenargs[0]
if command[0] == 'ansible-playbook':
assert 'lxd' == get_command_parameter(command, '--connection')
verify_inventory(get_command_parameter(command, '--inventory'))
verify_extra_vars(get_command_parameter(command, '--extra-vars').lstrip('@'))
# TODO: verify --user for ssh connection
return subprocess.CompletedProcess("fakerun", 0, '')
else:
return subprocess.run(*popenargs, **kwargs)
monkeypatch.setattr(mockablerun, 'run_mockable', fake_ansible_playbook_run)
<|fim▁hole|> def fakechown(*_):
pass
monkeypatch.setattr(shutil, 'chown', fakechown)
with open(config_files, "r") as main_file:
parser = ConfigurationParser(main_file)
runner = PlaybookRunner(parser, "fake-container", "lxd")
playbooks = runner.run_all()
expected_playbooks = ['10_base_system', '20_networking', '30_foo']
assert playbooks == expected_playbooks<|fim▁end|> | |
<|file_name|>bitcoin_de.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="de" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About ELcoin</source>
<translation>Über ELcoin</translation>
</message>
<message>
<location line="+39"/>
<source><b>ELcoin</b> version</source>
<translation><b>ELcoin</b> Version</translation>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2014 The ELcoin developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation>
Dies ist experimentelle Software.
Veröffentlicht unter der MIT/X11-Softwarelizenz, siehe beiligende Datei COPYING oder http://www.opensource.org/licenses/mit-license.php.
Dieses Produkt enthält Software, die vom OpenSSL-Projekt zur Verwendung im OpenSSL-Toolkit (http://www.openssl.org/) entwickelt wurde, sowie kryptographische Software geschrieben von Eric Young ([email protected]) und UPnP-Software geschrieben von Thomas Bernard.</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Adressbuch</translation>
</message>
<message>
<location line="+22"/>
<source>Double-click to edit address or label</source>
<translation>Doppelklicken, um die Adresse oder die Bezeichnung zu bearbeiten</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Eine neue Adresse erstellen</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Ausgewählte Adresse in die Zwischenablage kopieren</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Neue Adresse</translation>
</message>
<message>
<location line="-46"/>
<source>These are your ELcoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation>Das sind Ihre ELcoin Adressen um Zahlungen zu erhalten. Sie werden vielleicht verschiedene an jeden Sender vergeben, damit Sie im Auge behalten können wer sie bezahlt.</translation>
</message>
<message>
<location line="+60"/>
<source>&Copy Address</source>
<translation>Adresse &kopieren</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>&QR Code anzeigen</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a ELcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>Ausgewählte Adresse aus der Liste entfernen</translation>
</message>
<message>
<location line="-14"/>
<source>Verify a message to ensure it was signed with a specified ELcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Löschen</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+65"/>
<source>Copy &Label</source>
<translation>&Bezeichnung kopieren</translation>
</message>
<message>
<location line="+2"/>
<source>&Edit</source>
<translation>&Editieren</translation>
</message>
<message>
<location line="+250"/>
<source>Export Address Book Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Kommagetrennte-Datei (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Bezeichnung</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(keine Bezeichnung)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Passphrasendialog</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Passphrase eingeben</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Neue Passphrase</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Neue Passphrase wiederholen</translation>
</message>
<message>
<location line="+33"/>
<source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>For staking only</source>
<translation>Anteil der im Netz reift und nur Zinsen kreiert.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+35"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Geben Sie die neue Passphrase für die Wallet ein.<br>Bitte benutzen Sie eine Passphrase bestehend aus <b>10 oder mehr zufälligen Zeichen</b> oder <b>8 oder mehr Wörtern</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Wallet verschlüsseln</translation>
</message>
<message>
<location line="+7"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Dieser Vorgang benötigt ihre Passphrase, um die Wallet zu entsperren.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Wallet entsperren</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Dieser Vorgang benötigt ihre Passphrase, um die Wallet zu entschlüsseln.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Wallet entschlüsseln</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Passphrase ändern</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Geben Sie die alte und neue Wallet-Passphrase ein.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Wallet-Verschlüsselung bestätigen</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Sind Sie sich sicher, dass Sie ihre Wallet verschlüsseln möchten?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>WICHTIG: Alle vorherigen Wallet-Sicherungen sollten durch die neu erzeugte, verschlüsselte Wallet ersetzt werden. Aus Sicherheitsgründen werden vorherige Sicherungen der unverschlüsselten Wallet nutzlos, sobald Sie die neue, verschlüsselte Wallet verwenden.</translation>
</message>
<message>
<location line="+103"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Warnung: Die Feststelltaste ist aktiviert!</translation>
</message>
<message>
<location line="-133"/>
<location line="+60"/>
<source>Wallet encrypted</source>
<translation>Wallet verschlüsselt</translation>
</message>
<message>
<location line="-58"/>
<source>ELcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+44"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Wallet-Verschlüsselung fehlgeschlagen</translation>
</message>
<message>
<location line="-56"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Die Wallet-Verschlüsselung ist aufgrund eines internen Fehlers fehlgeschlagen. Ihre Wallet wurde nicht verschlüsselt.</translation>
</message>
<message>
<location line="+7"/>
<location line="+50"/>
<source>The supplied passphrases do not match.</source>
<translation>Die eingegebenen Passphrasen stimmen nicht überein.</translation>
</message>
<message>
<location line="-38"/>
<source>Wallet unlock failed</source>
<translation>Wallet-Entsperrung fehlgeschlagen</translation>
</message>
<message>
<location line="+1"/>
<location line="+12"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Die eingegebene Passphrase zur Wallet-Entschlüsselung war nicht korrekt.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Wallet-Entschlüsselung fehlgeschlagen</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Die Wallet-Passphrase wurde erfolgreich geändert.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+280"/>
<source>Sign &message...</source>
<translation>Nachricht &signieren...</translation>
</message>
<message>
<location line="+242"/>
<source>Synchronizing with network...</source>
<translation>Synchronisiere mit Netzwerk...</translation>
</message>
<message>
<location line="-308"/>
<source>&Overview</source>
<translation>&Übersicht</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Allgemeine Wallet-Übersicht anzeigen</translation>
</message>
<message>
<location line="+17"/>
<source>&Transactions</source>
<translation>&Transaktionen</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Transaktionsverlauf durchsehen</translation>
</message>
<message>
<location line="+5"/>
<source>&Address Book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit the list of stored addresses and labels</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-13"/>
<source>&Receive coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show the list of addresses for receiving payments</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-7"/>
<source>&Send coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>E&xit</source>
<translation>&Beenden</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Anwendung beenden</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about ELcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Über &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Informationen über Qt anzeigen</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Konfiguration...</translation>
</message>
<message>
<location line="+4"/>
<source>&Encrypt Wallet...</source>
<translation>Wallet &verschlüsseln...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>Wallet &sichern...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>Passphrase &ändern...</translation>
</message>
<message numerus="yes">
<location line="+250"/>
<source>~%n block(s) remaining</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-247"/>
<source>&Export...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-62"/>
<source>Send coins to a ELcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+45"/>
<source>Modify configuration options for ELcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-14"/>
<source>Encrypt or decrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup wallet to another location</source>
<translation>Eine Wallet-Sicherungskopie erstellen und abspeichern</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Ändert die Passphrase, die für die Wallet-Verschlüsselung benutzt wird</translation>
</message>
<message>
<location line="+10"/>
<source>&Debug window</source>
<translation>&Debugfenster</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Debugging- und Diagnosekonsole öffnen</translation>
</message>
<message>
<location line="-5"/>
<source>&Verify message...</source>
<translation>Nachricht &verifizieren...</translation>
</message>
<message>
<location line="-200"/>
<source>ELcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet</source>
<translation>Wallet</translation>
</message>
<message>
<location line="+178"/>
<source>&About ELcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Anzeigen / Verstecken</translation>
</message>
<message>
<location line="+9"/>
<source>Unlock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>&File</source>
<translation>&Datei</translation>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation>&Einstellungen</translation>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation>&Hilfe</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Registerkartenleiste</translation>
</message>
<message>
<location line="+8"/>
<source>Actions toolbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+9"/>
<source>[testnet]</source>
<translation>[Testnetz]</translation>
</message>
<message>
<location line="+0"/>
<location line="+60"/>
<source>ELcoin client</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+70"/>
<source>%n active connection(s) to ELcoin network</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+40"/>
<source>Downloaded %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+413"/>
<source>Staking.<br>Your weight is %1<br>Network weight is %2<br>Expected time to earn reward is %3</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Not staking because wallet is locked</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is syncing</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because you don't have mature coins</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-403"/>
<source>%n second(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="-284"/>
<source>&Unlock Wallet...</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+288"/>
<source>%n minute(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Up to date</source>
<translation>Auf aktuellem Stand</translation>
</message>
<message>
<location line="+7"/>
<source>Catching up...</source>
<translation>Hole auf...</translation>
</message>
<message>
<location line="+10"/>
<source>Last received block was generated %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Sent transaction</source>
<translation>Gesendete Transaktion</translation>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation>Eingehende Transaktion</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Datum: %1
Betrag: %2
Typ: %3
Adresse: %4</translation>
</message>
<message>
<location line="+100"/>
<location line="+15"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<location line="+15"/>
<source>URI can not be parsed! This can be caused by an invalid ELcoin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Wallet ist <b>verschlüsselt</b> und aktuell <b>entsperrt</b></translation>
</message>
<message>
<location line="+10"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Wallet ist <b>verschlüsselt</b> und aktuell <b>gesperrt</b></translation>
</message>
<message>
<location line="+25"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+76"/>
<source>%n second(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s)</source>
<translation><numerusform>%n Stunde</numerusform><numerusform>%n Stunden</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation><numerusform>%n Tag</numerusform><numerusform>%n Tage</numerusform></translation><|fim▁hole|> <source>Not staking</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoin.cpp" line="+109"/>
<source>A fatal error occurred. ELcoin can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+90"/>
<source>Network Alert</source>
<translation>Netzwerkalarm</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation>Anzahl:</translation>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation>Byte:</translation>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation>Betrag:</translation>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation>Priorität:</translation>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation>Gebühr:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Zu geringer Ausgabebetrag:</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+551"/>
<source>no</source>
<translation>nein</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation>Abzüglich Gebühr:</translation>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation>Wechselgeld:</translation>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation>Alles (de)selektieren</translation>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation>Baumansicht</translation>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation>Listenansicht</translation>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation>Betrag</translation>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation>Bezeichnung</translation>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation>Bestätigungen</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation>Bestätigt</translation>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation>Priorität</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-515"/>
<source>Copy address</source>
<translation>Adresse kopieren</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Bezeichnung kopieren</translation>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation>Betrag kopieren</translation>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation>Transaktions-ID kopieren</translation>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation>Anzahl kopieren</translation>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation>Gebühr kopieren</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Abzüglich Gebühr kopieren</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>Byte kopieren</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Priorität kopieren</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>Zu geringen Ausgabebetrag kopieren</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Wechselgeld kopieren</translation>
</message>
<message>
<location line="+317"/>
<source>highest</source>
<translation>am höchsten</translation>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation>hoch</translation>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation>mittel-hoch</translation>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation>mittel</translation>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation>niedrig-mittel</translation>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation>niedrig</translation>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation>am niedrigsten</translation>
</message>
<message>
<location line="+155"/>
<source>DUST</source>
<translation>STAUB</translation>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation>ja</translation>
</message>
<message>
<location line="+10"/>
<source>This label turns red, if the transaction size is bigger than 10000 bytes.
This means a fee of at least %1 per kb is required.
Can vary +/- 1 Byte per input.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transactions with higher priority get more likely into a block.
This label turns red, if the priority is smaller than "medium".
This means a fee of at least %1 per kb is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.
This means a fee of at least %2 is required.
Amounts below 0.546 times the minimum relay fee are shown as DUST.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the change is smaller than %1.
This means a fee of at least %2 is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+66"/>
<source>(no label)</source>
<translation>(keine Bezeichnung)</translation>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation>Wechselgeld von %1 (%2)</translation>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation>(Wechselgeld)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Adresse bearbeiten</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Bezeichnung</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>Die Kennzeichnung verbunden mit diesem Adressbucheintrag.</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Adresse</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>Die Adresse verknüpft mit diesem Adressbucheintrag. Kann nur bei Ausgangsadressen verändert werden.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+20"/>
<source>New receiving address</source>
<translation>Neue Empfangsadresse</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Neue Zahlungsadresse</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Empfangsadresse bearbeiten</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Zahlungsadresse bearbeiten</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Die eingegebene Adresse "%1" befindet sich bereits im Adressbuch.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid ELcoin address.</source>
<translation>Die eingegebene Adresse "%1" ist keine gültige ELcoin Adresse.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Wallet konnte nicht entsperrt werden.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Generierung eines neuen Schlüssels fehlgeschlagen.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+420"/>
<location line="+12"/>
<source>ELcoin-Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>version</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Benutzung:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>Kommandozeilen optionen</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Minimiert starten</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Erweiterte Einstellungen</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Allgemein</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Transaktions&gebühr bezahlen</translation>
</message>
<message>
<location line="+31"/>
<source>Reserved amount does not participate in staking and is therefore spendable at any time.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Reserve</source>
<translation>Reserviert</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start ELcoin after logging in to the system.</source>
<translation>Automatisch ELcoin starten beim Einloggen in das System.</translation>
</message>
<message>
<location line="+3"/>
<source>&Start ELcoin on system login</source>
<translation>&Starte ELcoin bei Systemstart</translation>
</message>
<message>
<location line="+7"/>
<source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Detach databases at shutdown</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Network</source>
<translation>&Netzwerk</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the ELcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Automatisch den ELcoin client port auf dem Router öffnen. Das funktioniert nur wenn der Router UPnP unterstützt und UPnP aktiviert ist.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Portweiterleitung via &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the ELcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>Proxy-&IP:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>IP Adresse des Proxy (z.B. 127.0.01)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Port:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Port des Proxies (z.B. 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>SOCKS-&Version:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>SOCKS-Version des Proxies (z.B. 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Programmfenster</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Nur ein Symbol im Infobereich anzeigen, nachdem das Programmfenster minimiert wurde.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>In den Infobereich anstatt in die Taskleiste &minimieren</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Minimiert die Anwendung anstatt sie zu beenden wenn das Fenster geschlossen wird. Wenn dies aktiviert ist, müssen Sie das Programm über "Beenden" im Menü schließen.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>Beim Schließen m&inimieren</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Anzeige</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>&Sprache der Benutzeroberfläche:</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting ELcoin.</source>
<translation>Die Sprache der GUI kann hier verändert werden. Die Einstellung wird nach einem Neustart übernommen.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Einheit der Beträge:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Wählen Sie die Standarduntereinheit, die in der Benutzeroberfläche und beim Überweisen von Bitcoins angezeigt werden soll.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show ELcoin addresses in the transaction list or not.</source>
<translation>ELcoin Adressen in der Überweisung anzeigen oder nicht.</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>Adressen in der Transaktionsliste &anzeigen</translation>
</message>
<message>
<location line="+7"/>
<source>Whether to show coin control features or not.</source>
<translation>Legt fest, ob die "Coin Control"-Funktionen angezeigt werden.</translation>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only!)</source>
<translation>Coin &control features anzeigen (nur experten!)</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&OK</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Abbrechen</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Anwenden</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+55"/>
<source>default</source>
<translation>Standard</translation>
</message>
<message>
<location line="+149"/>
<location line="+9"/>
<source>Warning</source>
<translation>Warnung</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting ELcoin.</source>
<translation>Diese Einstellung wird nach einem Neustart übernommen.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Die eingegebene Proxyadresse ist ungültig.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Formular</translation>
</message>
<message>
<location line="+33"/>
<location line="+231"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the ELcoin network after a connection is established, but this process has not completed yet.</source>
<translation>Die angezeigte Information kann falsch sein. Die Brieftasche synchronisiert automatisch mit dem ELcoin Netzwerk nachdem eine Verbindung zustande gekommen ist, aber dieser Prozess ist nicht abgeschlossen.</translation>
</message>
<message>
<location line="-160"/>
<source>Stake:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Unbestätigt:</translation>
</message>
<message>
<location line="-107"/>
<source>Wallet</source>
<translation>Wallet</translation>
</message>
<message>
<location line="+49"/>
<source>Spendable:</source>
<translation>Ausgabebereit:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation>Ihr aktuell verfügbarer Kontostand</translation>
</message>
<message>
<location line="+71"/>
<source>Immature:</source>
<translation>Unreif:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Erarbeiteter Betrag der noch nicht gereift ist</translation>
</message>
<message>
<location line="+20"/>
<source>Total:</source>
<translation>Gesamtbetrag:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation>Aktueller Gesamtbetrag aus obigen Kategorien</translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Letzte Transaktionen</b></translation>
</message>
<message>
<location line="-108"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Anzahl der unbestätigten Transaktionen die somit noch nicht zum aktuellen Kontostand zählen.</translation>
</message>
<message>
<location line="-29"/>
<source>Total of coins that was staked, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../overviewpage.cpp" line="+113"/>
<location line="+1"/>
<source>out of sync</source>
<translation>nicht synchron</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>QR Code Dialog</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Zahlung anfordern</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Betrag:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Bezeichnung:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Nachricht:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>& Speichern als...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Fehler beim Kodieren der URI in den QR-Code.</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>Der eingegebene Betrag ist ungültig, bitte überprüfen.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>Resultierende URI zu lang, bitte den Text für Bezeichnung / Nachricht kürzen.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>QR Code Speichern</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>PNG Grafik (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Clientname</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+348"/>
<source>N/A</source>
<translation>k.A.</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Clientversion</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Information</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Verwendete OpenSSL-Version</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Startzeit</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Netzwerk</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Anzahl Verbindungen</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>Am Testnetz</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Block kette</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Aktuelle Anzahl Blöcke</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Geschätzte Gesamtzahl Blöcke</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Letzte Blockzeit</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Öffnen</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Kommandozeilen Optionen:</translation>
</message>
<message>
<location line="+7"/>
<source>Show the ELcoin-Qt help message to get a list with possible ELcoin command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Zeigen</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Konsole</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Erstellungsdatum</translation>
</message>
<message>
<location line="-104"/>
<source>ELcoin - Debug window</source>
<translation>ELcoin - Debug Fenster</translation>
</message>
<message>
<location line="+25"/>
<source>ELcoin Core</source>
<translation>ELcoin Kern</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Debugprotokolldatei</translation>
</message>
<message>
<location line="+7"/>
<source>Open the ELcoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Konsole zurücksetzen</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-33"/>
<source>Welcome to the ELcoin RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Pfeiltaste hoch und runter, um den Verlauf durchzublättern und <b>Strg-L</b>, um die Konsole zurückzusetzen.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Bitte <b>help</b> eingeben, um eine Übersicht verfügbarer Befehle zu erhalten.</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+182"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Bitcoins überweisen</translation>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation>"Coin Control"-Funktionen</translation>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation>Eingaben...</translation>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation>automatisch ausgewählt</translation>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation>Unzureichender Kontostand!</translation>
</message>
<message>
<location line="+77"/>
<source>Quantity:</source>
<translation>Anzahl:</translation>
</message>
<message>
<location line="+22"/>
<location line="+35"/>
<source>0</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-19"/>
<source>Bytes:</source>
<translation>Byte:</translation>
</message>
<message>
<location line="+51"/>
<source>Amount:</source>
<translation>Betrag:</translation>
</message>
<message>
<location line="+22"/>
<location line="+86"/>
<location line="+86"/>
<location line="+32"/>
<source>0.00 BC</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-191"/>
<source>Priority:</source>
<translation>Priorität:</translation>
</message>
<message>
<location line="+19"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Fee:</source>
<translation>Gebühr:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Zu geringer Ausgabebetrag:</translation>
</message>
<message>
<location line="+19"/>
<source>no</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>After Fee:</source>
<translation>Abzüglich Gebühr:</translation>
</message>
<message>
<location line="+35"/>
<source>Change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<source>custom change address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+106"/>
<source>Send to multiple recipients at once</source>
<translation>In einer Transaktion an mehrere Empfänger auf einmal überweisen</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>Empfänger &hinzufügen</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>&Zurücksetzen</translation>
</message>
<message>
<location line="+28"/>
<source>Balance:</source>
<translation>Kontostand:</translation>
</message>
<message>
<location line="+16"/>
<source>123.456 BC</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Überweisung bestätigen</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>&Überweisen</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-173"/>
<source>Enter a ELcoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Copy quantity</source>
<translation>Anzahl kopieren</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Betrag kopieren</translation>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation>Gebühr kopieren</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Abzüglich Gebühr kopieren</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>Byte kopieren</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Priorität kopieren</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>Zu geringen Ausgabebetrag kopieren</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Wechselgeld kopieren</translation>
</message>
<message>
<location line="+86"/>
<source><b>%1</b> to %2 (%3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Überweisung bestätigen</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Die Zahlungsadresse ist ungültig, bitte nochmals überprüfen.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Der zu zahlende Betrag muss größer als 0 sein.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Der angegebene Betrag übersteigt ihren Kontostand.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Der angegebene Betrag übersteigt aufgrund der Transaktionsgebühr in Höhe von %1 ihren Kontostand.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Doppelte Adresse gefunden, pro Überweisung kann an jede Adresse nur einmalig etwas überwiesen werden.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+251"/>
<source>WARNING: Invalid ELcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>(no label)</source>
<translation>(keine Bezeichnung)</translation>
</message>
<message>
<location line="+4"/>
<source>WARNING: unknown change address</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>&Betrag:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>&Empfänger:</translation>
</message>
<message>
<location line="+24"/>
<location filename="../sendcoinsentry.cpp" line="+25"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Adressbezeichnung eingeben (diese wird zusammen mit der Adresse dem Adressbuch hinzugefügt)</translation>
</message>
<message>
<location line="+9"/>
<source>&Label:</source>
<translation>&Bezeichnung:</translation>
</message>
<message>
<location line="+18"/>
<source>The address to send the payment to (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation>Empfängeradresse (z.b. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</translation>
</message>
<message>
<location line="+10"/>
<source>Choose address from address book</source>
<translation>Adresse aus dem Adressbuch auswählen</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Adresse aus der Zwischenablage einfügen</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a ELcoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Signaturen - eine Nachricht signieren / verifizieren</translation>
</message>
<message>
<location line="+13"/>
<location line="+124"/>
<source>&Sign Message</source>
<translation>Nachricht &signieren</translation>
</message>
<message>
<location line="-118"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>Sie können Nachrichten mit ihren Adressen signieren, um den Besitz dieser Adressen zu beweisen. Bitte nutzen Sie diese Funktion mit Vorsicht und nehmen Sie sich vor Phishingangriffen in Acht. Signieren Sie nur Nachrichten, mit denen Sie vollständig einverstanden sind.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+203"/>
<source>Choose an address from the address book</source>
<translation>Eine Adresse aus dem Adressbuch wählen</translation>
</message>
<message>
<location line="-193"/>
<location line="+203"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-193"/>
<source>Paste address from clipboard</source>
<translation>Adresse aus der Zwischenablage einfügen</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>Zu signierende Nachricht hier eingeben</translation>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Aktuelle Signatur in die Zwischenablage kopieren</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this ELcoin address</source>
<translation>Signiere die Nachricht um zu beweisen das du Besitzer dieser ELcoin Adresse bist.</translation>
</message>
<message>
<location line="+17"/>
<source>Reset all sign message fields</source>
<translation>Alle "Nachricht signieren"-Felder zurücksetzen</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>&Zurücksetzen</translation>
</message>
<message>
<location line="-87"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation>Nachricht &verifizieren</translation>
</message>
<message>
<location line="-64"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>Geben Sie die signierende Adresse, Nachricht (achten Sie darauf Zeilenumbrüche, Leerzeichen, Tabulatoren usw. exakt zu kopieren) und Signatur unten ein, um die Nachricht zu verifizieren. Vorsicht, interpretieren Sie nicht mehr in die Signatur, als in der signierten Nachricht selber enthalten ist, um nicht von einem Man-in-the-middle-Angriff hinters Licht geführt zu werden.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified ELcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all verify message fields</source>
<translation>Alle "Nachricht verifizieren"-Felder zurücksetzen</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a ELcoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Auf "Nachricht signieren" klicken, um die Signatur zu erzeugen</translation>
</message>
<message>
<location line="+3"/>
<source>Enter ELcoin signature</source>
<translation>ELcoin Signatur eingeben</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Die eingegebene Adresse ist ungültig.</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Bitte überprüfen Sie die Adresse und versuchen Sie es erneut.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>Die eingegebene Adresse verweist nicht auf einen Schlüssel.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Wallet-Entsperrung wurde abgebrochen.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>Privater Schlüssel zur eingegebenen Adresse ist nicht verfügbar.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Signierung der Nachricht fehlgeschlagen.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Nachricht signiert.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>Die Signatur konnte nicht dekodiert werden.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Bitte überprüfen Sie die Signatur und versuchen Sie es erneut.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>Die Signatur entspricht nicht dem Message Digest.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Verifikation der Nachricht fehlgeschlagen.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Nachricht verifiziert.</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+19"/>
<source>Open until %1</source>
<translation>Offen bis %1</translation>
</message>
<message numerus="yes">
<location line="-2"/>
<source>Open for %n block(s)</source>
<translation><numerusform>Offen für %n weitere Blöcke</numerusform><numerusform>Offen für %n weitere Blöcke</numerusform></translation>
</message>
<message>
<location line="+8"/>
<source>conflicted</source>
<translation>kollidiert</translation>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation>%1/offline</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/unbestätigt</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 Bestätigungen</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Status</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, über %n Knoten übertragen</numerusform><numerusform>, über %n Knoten übertragen</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Quelle</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Generiert</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>Von</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>An</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>eigene Adresse</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>Bezeichnung</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Gutschrift</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>reift noch %n weiteren Block</numerusform><numerusform>reift noch %n weitere Blöcke</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>nicht angenommen</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Belastung</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Transaktionsgebühr</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Nettobetrag</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Nachricht signieren</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Kommentar</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>Transaktions-ID</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 30 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Generierte Coins müssen 30 Bestätigungen erhalten bevor sie verfügbar sind. Dieser Block wurde ans Netzwerk gesendet und der Blockkette angehängt als der Block generiert wurde. Wenn er der Blockkette nicht erfolgreich angehängt werden konnte, wird er den Status in "nicht Akzeptiert" ändern und wird nicht verfügbar sein. Das kann zufällig geschehen wenn eine andere Leitung den Block innerhalb von ein paar Sekunden generiert.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Debuginformationen</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transaktion</translation>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation>Eingaben</translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Betrag</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>wahr</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>falsch</translation>
</message>
<message>
<location line="-211"/>
<source>, has not been successfully broadcast yet</source>
<translation>, wurde noch nicht erfolgreich übertragen</translation>
</message>
<message>
<location line="+35"/>
<source>unknown</source>
<translation>unbekannt</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Transaktionsdetails</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Dieser Bereich zeigt eine detaillierte Beschreibung der Transaktion an</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+226"/>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Typ</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Betrag</translation>
</message>
<message>
<location line="+60"/>
<source>Open until %1</source>
<translation>Offen bis %1</translation>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Bestätigt (%1 Bestätigungen)</translation>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Offen für %n weiteren Block</numerusform><numerusform>Offen für %n weitere Blöcke</numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation>Unbestätigt:</translation>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation>wird Bestätigt (%1 von %2 Bestätigungen)</translation>
</message>
<message>
<location line="+6"/>
<source>Conflicted</source>
<translation>Konflikt</translation>
</message>
<message>
<location line="+3"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation>Unreif (%1 Bestätigungen, wird verfügbar sein nach %2)</translation>
</message>
<message>
<location line="+3"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Dieser Block wurde von keinem anderen Knoten empfangen und wird wahrscheinlich nicht angenommen werden!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Generiert, jedoch nicht angenommen</translation>
</message>
<message>
<location line="+42"/>
<source>Received with</source>
<translation>Empfangen über</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Empfangen von</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Überwiesen an</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Eigenüberweisung</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Erarbeitet</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(k.A.)</translation>
</message>
<message>
<location line="+190"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Transaktionsstatus. Fahren Sie mit der Maus über dieses Feld, um die Anzahl der Bestätigungen zu sehen.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Datum und Uhrzeit als die Transaktion empfangen wurde.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Art der Transaktion</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Zieladresse der Transaktion</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Der Betrag, der dem Kontostand abgezogen oder hinzugefügt wurde.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+55"/>
<location line="+16"/>
<source>All</source>
<translation>Alle</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Heute</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Diese Woche</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Diesen Monat</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Letzten Monat</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Dieses Jahr</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Zeitraum...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Empfangen über</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Überwiesen an</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Eigenüberweisung</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Erarbeitet</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Andere</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Zu suchende Adresse oder Bezeichnung eingeben</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Minimaler Betrag</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Adresse kopieren</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Bezeichnung kopieren</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Betrag kopieren</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Transaktions-ID kopieren</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Bezeichnung bearbeiten</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Transaktionsdetails anzeigen</translation>
</message>
<message>
<location line="+144"/>
<source>Export Transaction Data</source>
<translation>Exportiere Transaktionsdaten</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Kommagetrennte-Datei (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Bestätigt</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Typ</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Bezeichnung</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Betrag</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Fehler beim Exportieren</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Kann Datei nicht schreiben %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Zeitraum:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>bis</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+206"/>
<source>Sending...</source>
<translation>Wird gesendet...</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+33"/>
<source>ELcoin version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation>Benutzung:</translation>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or elcoind</source>
<translation>Kommando versenden an -server oder elcoind </translation>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation>Befehle auflisten</translation>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation>Hilfe zu einem Befehl erhalten</translation>
</message>
<message>
<location line="+2"/>
<source>Options:</source>
<translation>Optionen:</translation>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: elcoin.conf)</source>
<translation>Konfigurationsdatei angeben (Standard: elcoin.conf)</translation>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: elcoind.pid)</source>
<translation>PID Datei angeben (Standard: elcoin.pid)</translation>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation>Wallet-Datei festlegen (innerhalb des Datenverzeichnisses)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Datenverzeichnis festlegen</translation>
</message>
<message>
<location line="+2"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Größe des Datenbankcaches in MB festlegen (Standard: 25)</translation>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Listen for connections on <port> (default: 6079 or testnet: 16079)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Maximal <n> Verbindungen zu Gegenstellen aufrechterhalten (Standard: 125)</translation>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Mit dem Knoten verbinden um Adressen von Gegenstellen abzufragen, danach trennen</translation>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation>Die eigene öffentliche Adresse angeben</translation>
</message>
<message>
<location line="+5"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Stake your coins to support network and gain reward (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Schwellenwert, um Verbindungen zu sich nicht konform verhaltenden Gegenstellen zu beenden (Standard: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Anzahl Sekunden, während denen sich nicht konform verhaltenden Gegenstellen die Wiederverbindung verweigert wird (Standard: 86400)</translation>
</message>
<message>
<location line="-44"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>Beim Einrichten des abzuhörenden RPC-Ports %u für IPv4 ist ein Fehler aufgetreten: %s</translation>
</message>
<message>
<location line="+51"/>
<source>Detach block and address databases. Increases shutdown time (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+109"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Fehler: Transaktion wurde abgelehnt. Das kann geschehen wenn einige Coins in der Brieftasche bereits ausgegeben wurden, wenn von einer Kopie der wallet.dat Coins ausgegeben wurden werden sie hier nicht als Ausgabe aufgeführt.</translation>
</message>
<message>
<location line="-5"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source>
<translation>Fehler: Diese Transaktion benötigt eine Transaktionsgebühr von mindestens %s wegen der Anzahl, Komplexität oder Benutzung von neuerlich erhaltenen Beträgen.</translation>
</message>
<message>
<location line="-87"/>
<source>Listen for JSON-RPC connections on <port> (default: 6080 or testnet: 16080)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-11"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Kommandozeilenbefehle und JSON-RPC-Befehle annehmen</translation>
</message>
<message>
<location line="+101"/>
<source>Error: Transaction creation failed </source>
<translation>Fehler: Erstellung der Transaktion fehlgeschlagen</translation>
</message>
<message>
<location line="-5"/>
<source>Error: Wallet locked, unable to create transaction </source>
<translation>Fehler: Brieftasche verschlüsselt, unfähig Transaktion zu erstellen</translation>
</message>
<message>
<location line="-8"/>
<source>Importing blockchain data file.</source>
<translation>Importiere Block Kette aus Datei</translation>
</message>
<message>
<location line="+1"/>
<source>Importing bootstrap blockchain data file.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-88"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Als Hintergrunddienst starten und Befehle annehmen</translation>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation>Das Testnetz verwenden</translation>
</message>
<message>
<location line="-24"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Eingehende Verbindungen annehmen (Standard: 1, wenn nicht -proxy oder -connect)</translation>
</message>
<message>
<location line="-38"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>Beim Einrichten des abzuhörenden RPC-Ports %u für IPv6 ist ein Fehler aufgetreten, es wird auf IPv4 zurückgegriffen: %s</translation>
</message>
<message>
<location line="+117"/>
<source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Warnung: -paytxfee ist auf einen sehr hohen Wert festgelegt! Dies ist die Gebühr die beim Senden einer Transaktion fällig wird.</translation>
</message>
<message>
<location line="+61"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong ELcoin will not work properly.</source>
<translation>Wanung : Bitte prüfen Sie ob Datum und Uhrzeit richtig eingestellt sind. Wenn das Datum falsch ist ELcoin nicht richtig funktionieren.</translation>
</message>
<message>
<location line="-31"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Warnung: Lesen von wallet.dat fehlgeschlagen! Alle Schlüssel wurden korrekt gelesen, Transaktionsdaten bzw. Adressbucheinträge fehlen aber möglicherweise oder sind inkorrekt.</translation>
</message>
<message>
<location line="-18"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>Warnung: wallet.dat beschädigt, Rettung erfolgreich! Original wallet.dat wurde als wallet.{Zeitstempel}.dat in %s gespeichert. Falls ihr Kontostand oder Transaktionen nicht korrekt sind, sollten Sie von einer Datensicherung wiederherstellen.</translation>
</message>
<message>
<location line="-30"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Versucht private Schlüssel aus einer beschädigten wallet.dat wiederherzustellen</translation>
</message>
<message>
<location line="+4"/>
<source>Block creation options:</source>
<translation>Blockerzeugungsoptionen:</translation>
</message>
<message>
<location line="-62"/>
<source>Connect only to the specified node(s)</source>
<translation>Nur mit dem/den angegebenen Knoten verbinden</translation>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Eigene IP-Adresse erkennen (Standard: 1, wenn abgehört wird und nicht -externalip)</translation>
</message>
<message>
<location line="+94"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Fehler, es konnte kein Port abgehört werden. Wenn dies so gewünscht wird -listen=0 verwenden.</translation>
</message>
<message>
<location line="-90"/>
<source>Find peers using DNS lookup (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Sync checkpoints policy (default: strict)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+83"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation type="unfinished"/>
</message>
<message>
<location line="-82"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Maximale Größe, <n> * 1000 Byte, des Empfangspuffers pro Verbindung (Standard: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Maximale Größe, <n> * 1000 Byte, des Sendepuffers pro Verbindung (Standard: 1000)</translation>
</message>
<message>
<location line="-16"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Verbinde nur zu Knoten des Netztyps <net> (IPv4, IPv6 oder Tor)</translation>
</message>
<message>
<location line="+28"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation>SSL-Optionen: (siehe Bitcoin-Wiki für SSL-Installationsanweisungen)</translation>
</message>
<message>
<location line="-74"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Rückverfolgungs- und Debuginformationen an die Konsole senden anstatt sie in die Datei debug.log zu schreiben</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Minimale Blockgröße in Byte festlegen (Standard: 0)</translation>
</message>
<message>
<location line="-29"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Verkleinere Datei debug.log beim Starten des Clients (Standard: 1, wenn kein -debug)</translation>
</message>
<message>
<location line="-42"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Verbindungstimeout in Millisekunden festlegen (Standard: 5000)</translation>
</message>
<message>
<location line="+109"/>
<source>Unable to sign checkpoint, wrong checkpointkey?
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>UPnP verwenden, um die Portweiterleitung einzurichten (Standard: 0)</translation>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>UPnP verwenden, um die Portweiterleitung einzurichten (Standard: 1, wenn abgehört wird)</translation>
</message>
<message>
<location line="-25"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>Proxy benutzen um versteckte Services zu erreichen (Standard: selbe Einstellung wie Proxy)</translation>
</message>
<message>
<location line="+42"/>
<source>Username for JSON-RPC connections</source>
<translation>Benutzername für JSON-RPC-Verbindungen</translation>
</message>
<message>
<location line="+47"/>
<source>Verifying database integrity...</source>
<translation>Überprüfe Datenbank Integrität...</translation>
</message>
<message>
<location line="+57"/>
<source>WARNING: syncronized checkpoint violation detected, but skipped!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: Disk space is low!</source>
<translation>Warnung: Festplatte hat wenig freien Speicher</translation>
</message>
<message>
<location line="-2"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Warnung: Diese Version is veraltet, Aktualisierung erforderlich!</translation>
</message>
<message>
<location line="-48"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat beschädigt, Rettung fehlgeschlagen</translation>
</message>
<message>
<location line="-54"/>
<source>Password for JSON-RPC connections</source>
<translation>Passwort für JSON-RPC-Verbindungen</translation>
</message>
<message>
<location line="-84"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=elcoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "ELcoin Alert" [email protected]
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Find peers using internet relay chat (default: 0)</source>
<translation>Knoten die IRC Chat nutzen auffinden (Standard: 1) (0)?)</translation>
</message>
<message>
<location line="+5"/>
<source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source>
<translation>Beim erstellen einer Transaktion werden eingaben kleiner als dieser Wert ignoriert (Standard 0,01)</translation>
</message>
<message>
<location line="+16"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>JSON-RPC-Verbindungen von der angegebenen IP-Adresse erlauben</translation>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Sende Befehle an Knoten <ip> (Standard: 127.0.0.1)</translation>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Kommando ausführen wenn der beste Block wechselt (%s im Kommando wird durch den Hash des Blocks ersetzt)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Kommando ausführen wenn sich eine Wallet-Transaktion verändert (%s im Kommando wird durch die TxID ersetzt)</translation>
</message>
<message>
<location line="+3"/>
<source>Require a confirmations for change (default: 0)</source>
<translation>Benötigt eine Bestätigung zur Änderung (Standard: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation>Kommando ausführen wenn eine relevante Meldung eingeht (%s in cmd wird von der Meldung ausgetauscht)</translation>
</message>
<message>
<location line="+3"/>
<source>Upgrade wallet to latest format</source>
<translation>Wallet auf das neueste Format aktualisieren</translation>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Größe des Schlüsselpools festlegen auf <n> (Standard: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Blockkette erneut nach fehlenden Wallet-Transaktionen durchsuchen</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 2500, 0 = all)</source>
<translation>Anzahl der zu prüfenden Blöcke bei Programmstart (Standard: 2500, 0 = alle)</translation>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation>Importiere Blöcke aus externer blk000?.dat Datei.</translation>
</message>
<message>
<location line="+8"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>OpenSSL (https) für JSON-RPC-Verbindungen verwenden</translation>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Serverzertifikat (Standard: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Privater Serverschlüssel (Standard: server.pem)</translation>
</message>
<message>
<location line="+1"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+53"/>
<source>Error: Wallet unlocked for staking only, unable to create transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source>
<translation>WARNUNG : Ungültiger Checkpunkt gefunden! Angezeigte Transaktionen können falsch sein! Du musst vielleicht updaten oder die Entwickler benachrichtigen.</translation>
</message>
<message>
<location line="-158"/>
<source>This help message</source>
<translation>Dieser Hilfetext</translation>
</message>
<message>
<location line="+95"/>
<source>Wallet %s resides outside data directory %s.</source>
<translation>Wallet %s liegt außerhalb des Daten Verzeichnisses %s.</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot obtain a lock on data directory %s. ELcoin is probably already running.</source>
<translation>Kann das Verzeichniss nicht einbinden %s. ELcoin Brieftasche läuft wahrscheinlich bereits.</translation>
</message>
<message>
<location line="-98"/>
<source>ELcoin</source>
<translation>ELcoin</translation>
</message>
<message>
<location line="+140"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Kann auf diesem Computer nicht an %s binden (von bind zurückgegebener Fehler %d, %s)</translation>
</message>
<message>
<location line="-130"/>
<source>Connect through socks proxy</source>
<translation>Verbinde über socks proxy</translation>
</message>
<message>
<location line="+3"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Erlaube DNS-Namensauflösung für -addnode, -seednode und -connect</translation>
</message>
<message>
<location line="+122"/>
<source>Loading addresses...</source>
<translation>Lade Adressen...</translation>
</message>
<message>
<location line="-15"/>
<source>Error loading blkindex.dat</source>
<translation>Fehler beim laden von blkindex.dat</translation>
</message>
<message>
<location line="+2"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Fehler beim Laden von wallet.dat: Wallet beschädigt</translation>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of ELcoin</source>
<translation>Fehler beim Laden wallet.dat. Brieftasche benötigt neuere Version der ELcoin Brieftasche.</translation>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart ELcoin to complete</source>
<translation>Brieftasche muss neu geschrieben werden. Starte die ELcoin Brieftasche neu zum komplettieren.</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation>Fehler beim Laden von wallet.dat</translation>
</message>
<message>
<location line="-16"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Ungültige Adresse in -proxy: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Unbekannter Netztyp in -onlynet angegeben: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Unbekannte Proxyversion in -socks angefordert: %i</translation>
</message>
<message>
<location line="+4"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Kann Adresse in -bind nicht auflösen: '%s'</translation>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Kann Adresse in -externalip nicht auflösen: '%s'</translation>
</message>
<message>
<location line="-24"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Ungültiger Betrag für -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Error: could not start node</source>
<translation>Fehler: Node konnte nicht gestartet werden</translation>
</message>
<message>
<location line="+11"/>
<source>Sending...</source>
<translation>Wird gesendet...</translation>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation>Ungültiger Betrag</translation>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation>Unzureichender Kontostand</translation>
</message>
<message>
<location line="-34"/>
<source>Loading block index...</source>
<translation>Lade Blockindex...</translation>
</message>
<message>
<location line="-103"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Mit dem Knoten verbinden und versuchen die Verbindung aufrecht zu halten</translation>
</message>
<message>
<location line="+122"/>
<source>Unable to bind to %s on this computer. ELcoin is probably already running.</source>
<translation>Fehler beim anbinden %s auf diesem Computer. BlaclCoin Client läuft wahrscheinlich bereits.</translation>
</message>
<message>
<location line="-97"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Gebühr pro KB, zusätzlich zur ausgehenden Transaktion</translation>
</message>
<message>
<location line="+55"/>
<source>Invalid amount for -mininput=<amount>: '%s'</source>
<translation>Ungültiger Betrag für -mininput=<amount>:'%s'</translation>
</message>
<message>
<location line="+25"/>
<source>Loading wallet...</source>
<translation>Lade Wallet...</translation>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation>Wallet kann nicht auf eine ältere Version herabgestuft werden</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot initialize keypool</source>
<translation>Keypool kann nicht initialisiert werden</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation>Standardadresse kann nicht geschrieben werden</translation>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation>Durchsuche erneut...</translation>
</message>
<message>
<location line="+5"/>
<source>Done loading</source>
<translation>Laden abgeschlossen</translation>
</message>
<message>
<location line="-167"/>
<source>To use the %s option</source>
<translation>Zur Nutzung der %s Option</translation>
</message>
<message>
<location line="+14"/>
<source>Error</source>
<translation>Fehler</translation>
</message>
<message>
<location line="+6"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>Sie müssen den Wert rpcpassword=<passwort> in der Konfigurationsdatei angeben:
%s
Falls die Konfigurationsdatei nicht existiert, erzeugen Sie diese bitte mit Leserechten nur für den Dateibesitzer.</translation>
</message>
</context>
</TS><|fim▁end|> | </message>
<message>
<location line="+18"/> |
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>extern crate indy_api_types;
#[macro_use]
extern crate indy_utils;
#[macro_use]
extern crate log;
extern crate serde;
#[macro_use]
extern crate serde_derive;
use std::cell::RefCell;
use std::collections::HashMap;
use std::fs;
use std::io::BufReader;
use std::path::PathBuf;
use std::rc::Rc;
use serde_json::Value as SValue;
use indy_api_types::wallet::*;
use indy_api_types::domain::wallet::{Config, Credentials, ExportConfig, Tags};
use indy_api_types::errors::prelude::*;
pub use crate::encryption::KeyDerivationData;
use indy_utils::crypto::chacha20poly1305_ietf;
use indy_utils::crypto::chacha20poly1305_ietf::Key as MasterKey;
use self::export_import::{export_continue, finish_import, preparse_file_to_import};
use self::storage::{WalletStorage, WalletStorageType};
use self::storage::default::SQLiteStorageType;
use self::storage::plugged::PluggedStorageType;
use self::wallet::{Keys, Wallet};
use indy_api_types::{WalletHandle};
mod storage;
mod encryption;
mod query_encryption;
mod iterator;
// TODO: Remove query language out of wallet module
pub mod language;
mod export_import;
mod wallet;
pub struct WalletService {
storage_types: RefCell<HashMap<String, Box<dyn WalletStorageType>>>,
wallets: RefCell<HashMap<WalletHandle, Box<Wallet>>>,
pending_for_open: RefCell<HashMap<WalletHandle, (String /* id */, Box<dyn WalletStorage>, Metadata, Option<KeyDerivationData>)>>,
pending_for_import: RefCell<HashMap<WalletHandle, (BufReader<::std::fs::File>, chacha20poly1305_ietf::Nonce, usize, Vec<u8>, KeyDerivationData)>>,
}
impl WalletService {
pub fn new() -> WalletService {
let storage_types = {
let mut map: HashMap<String, Box<dyn WalletStorageType>> = HashMap::new();
map.insert("default".to_string(), Box::new(SQLiteStorageType::new()));
RefCell::new(map)
};
WalletService {
storage_types,
wallets: RefCell::new(HashMap::new()),
pending_for_open: RefCell::new(HashMap::new()),
pending_for_import: RefCell::new(HashMap::new()),
}
}
pub fn register_wallet_storage(&self,
type_: &str,
create: WalletCreate,
open: WalletOpen,
close: WalletClose,
delete: WalletDelete,
add_record: WalletAddRecord,
update_record_value: WalletUpdateRecordValue,
update_record_tags: WalletUpdateRecordTags,
add_record_tags: WalletAddRecordTags,
delete_record_tags: WalletDeleteRecordTags,
delete_record: WalletDeleteRecord,
get_record: WalletGetRecord,
get_record_id: WalletGetRecordId,
get_record_type: WalletGetRecordType,
get_record_value: WalletGetRecordValue,
get_record_tags: WalletGetRecordTags,
free_record: WalletFreeRecord,
get_storage_metadata: WalletGetStorageMetadata,
set_storage_metadata: WalletSetStorageMetadata,
free_storage_metadata: WalletFreeStorageMetadata,
search_records: WalletSearchRecords,
search_all_records: WalletSearchAllRecords,
get_search_total_count: WalletGetSearchTotalCount,
fetch_search_next_record: WalletFetchSearchNextRecord,
free_search: WalletFreeSearch) -> IndyResult<()> {
trace!("register_wallet_storage >>> type_: {:?}", type_);
let mut storage_types = self.storage_types.borrow_mut();
if storage_types.contains_key(type_) {
return Err(err_msg(IndyErrorKind::WalletStorageTypeAlreadyRegistered, format!("Wallet storage is already registered for type: {}", type_)));
}
storage_types.insert(type_.to_string(),
Box::new(
PluggedStorageType::new(create, open, close, delete,
add_record, update_record_value,
update_record_tags, add_record_tags, delete_record_tags,
delete_record, get_record, get_record_id,
get_record_type, get_record_value, get_record_tags, free_record,
get_storage_metadata, set_storage_metadata, free_storage_metadata,
search_records, search_all_records,
get_search_total_count,
fetch_search_next_record, free_search)));
trace!("register_wallet_storage <<<");
Ok(())
}
pub fn create_wallet(&self,
config: &Config,
credentials: &Credentials,
key: (&KeyDerivationData, &MasterKey)) -> IndyResult<()> {
self._create_wallet(config, credentials, key).map(|_| ())
}
fn _create_wallet(&self,
config: &Config,
credentials: &Credentials,
(key_data, master_key): (&KeyDerivationData, &MasterKey)) -> IndyResult<Keys> {
trace!("create_wallet >>> config: {:?}, credentials: {:?}", config, secret!(credentials));
let storage_types = self.storage_types.borrow();
let (storage_type, storage_config, storage_credentials) = WalletService::_get_config_and_cred_for_storage(config, credentials, &storage_types)?;
let keys = Keys::new();
let metadata = self._prepare_metadata(master_key, key_data, &keys)?;
storage_type.create_storage(&config.id,
storage_config
.as_ref()
.map(String::as_str),
storage_credentials
.as_ref()
.map(String::as_str),
&metadata)?;
Ok(keys)
}
pub fn delete_wallet_prepare(&self, config: &Config, credentials: &Credentials) -> IndyResult<(Metadata, KeyDerivationData)> {
trace!("delete_wallet >>> config: {:?}, credentials: {:?}", config, secret!(credentials));
if self.wallets.borrow_mut().values().any(|ref wallet| wallet.get_id() == WalletService::_get_wallet_id(config)) {
return Err(err_msg(IndyErrorKind::InvalidState, format!("Wallet has to be closed before deleting: {:?}", WalletService::_get_wallet_id(config))));
}
// check credentials and close connection before deleting wallet
let (_, metadata, key_derivation_data) = self._open_storage_and_fetch_metadata(config, &credentials)?;
Ok((metadata, key_derivation_data))
}
pub fn delete_wallet_continue(&self, config: &Config, credentials: &Credentials, metadata: &Metadata, master_key: &MasterKey) -> IndyResult<()> {
trace!("delete_wallet >>> config: {:?}, credentials: {:?}", config, secret!(credentials));
{
self._restore_keys(metadata, &master_key)?;
}
let storage_types = self.storage_types.borrow();
let (storage_type, storage_config, storage_credentials) = WalletService::_get_config_and_cred_for_storage(config, credentials, &storage_types)?;
storage_type.delete_storage(&config.id,
storage_config
.as_ref()
.map(String::as_str),
storage_credentials
.as_ref()
.map(String::as_str))?;
trace!("delete_wallet <<<");
Ok(())
}
pub fn open_wallet_prepare(&self, config: &Config, credentials: &Credentials) -> IndyResult<(WalletHandle, KeyDerivationData, Option<KeyDerivationData>)> {
trace!("open_wallet >>> config: {:?}, credentials: {:?}", config, secret!(&credentials));
self._is_id_from_config_not_used(config)?;
let (storage, metadata, key_derivation_data) = self._open_storage_and_fetch_metadata(config, credentials)?;
let wallet_handle = indy_utils::next_wallet_handle();
let rekey_data: Option<KeyDerivationData> = credentials.rekey.as_ref().map(|ref rekey|
KeyDerivationData::from_passphrase_with_new_salt(rekey, &credentials.rekey_derivation_method));
self.pending_for_open.borrow_mut().insert(wallet_handle, (WalletService::_get_wallet_id(config), storage, metadata, rekey_data.clone()));
Ok((wallet_handle, key_derivation_data, rekey_data))
}
pub fn open_wallet_continue(&self, wallet_handle: WalletHandle, master_key: (&MasterKey, Option<&MasterKey>)) -> IndyResult<WalletHandle> {
let (id, storage, metadata, rekey_data) = self.pending_for_open.borrow_mut().remove(&wallet_handle)
.ok_or_else(|| err_msg(IndyErrorKind::InvalidState, "Open data not found"))?;
let (master_key, rekey) = master_key;
let keys = self._restore_keys(&metadata, &master_key)?;
// Rotate master key
if let (Some(rekey), Some(rekey_data)) = (rekey, rekey_data) {
let metadata = self._prepare_metadata(rekey, &rekey_data, &keys)?;
storage.set_storage_metadata(&metadata)?;
}
let wallet = Wallet::new(id, storage, Rc::new(keys));
let mut wallets = self.wallets.borrow_mut();
wallets.insert(wallet_handle, Box::new(wallet));
trace!("open_wallet <<< res: {:?}", wallet_handle);
Ok(wallet_handle)
}
fn _open_storage_and_fetch_metadata(&self, config: &Config, credentials: &Credentials) -> IndyResult<(Box<dyn WalletStorage>, Metadata, KeyDerivationData)> {
let storage = self._open_storage(config, credentials)?;
let metadata: Metadata = {
let metadata = storage.get_storage_metadata()?;
serde_json::from_slice(&metadata)
.to_indy(IndyErrorKind::InvalidState, "Cannot deserialize metadata")?
};
let key_derivation_data = KeyDerivationData::from_passphrase_and_metadata(&credentials.key, &metadata, &credentials.key_derivation_method)?;
Ok((storage, metadata, key_derivation_data))
}
pub fn close_wallet(&self, handle: WalletHandle) -> IndyResult<()> {
trace!("close_wallet >>> handle: {:?}", handle);
match self.wallets.borrow_mut().remove(&handle) {
Some(mut wallet) => wallet.close(),
None => Err(err_msg(IndyErrorKind::InvalidWalletHandle, "Unknown wallet handle"))
}?;
trace!("close_wallet <<<");
Ok(())
}
fn _map_wallet_storage_error(err: IndyError, type_: &str, name: &str) -> IndyError {
match err.kind() {
IndyErrorKind::WalletItemAlreadyExists => err_msg(IndyErrorKind::WalletItemAlreadyExists, format!("Wallet item already exists with type: {}, id: {}", type_, name)),
IndyErrorKind::WalletItemNotFound => err_msg(IndyErrorKind::WalletItemNotFound, format!("Wallet item not found with type: {}, id: {}", type_, name)),
_ => err
}
}
pub fn add_record(&self, wallet_handle: WalletHandle, type_: &str, name: &str, value: &str, tags: &Tags) -> IndyResult<()> {
match self.wallets.borrow_mut().get_mut(&wallet_handle) {
Some(wallet) => wallet.add(type_, name, value, tags)
.map_err(|err| WalletService::_map_wallet_storage_error(err, type_, name)),
None => Err(err_msg(IndyErrorKind::InvalidWalletHandle, "Unknown wallet handle"))
}
}
pub fn add_indy_record<T>(&self, wallet_handle: WalletHandle, name: &str, value: &str, tags: &Tags)
-> IndyResult<()> where T: Sized {
self.add_record(wallet_handle, &self.add_prefix(short_type_name::<T>()), name, value,tags)
}
pub fn add_indy_object<T>(&self, wallet_handle: WalletHandle, name: &str, object: &T, tags: &Tags)
-> IndyResult<String> where T: ::serde::Serialize + Sized {
let object_json = serde_json::to_string(object)
.to_indy(IndyErrorKind::InvalidState, format!("Cannot serialize {:?}", short_type_name::<T>()))?;
self.add_indy_record::<T>(wallet_handle, name, &object_json, tags)?;
Ok(object_json)
}
pub fn update_record_value(&self, wallet_handle: WalletHandle, type_: &str, name: &str, value: &str) -> IndyResult<()> {
match self.wallets.borrow().get(&wallet_handle) {
Some(wallet) =>
wallet.update(type_, name, value)
.map_err(|err| WalletService::_map_wallet_storage_error(err, type_, name)),
None => Err(err_msg(IndyErrorKind::InvalidWalletHandle, "Unknown wallet handle"))
}
}
pub fn update_indy_object<T>(&self, wallet_handle: WalletHandle, name: &str, object: &T) -> IndyResult<String> where T: ::serde::Serialize + Sized {
let type_ = short_type_name::<T>();
match self.wallets.borrow().get(&wallet_handle) {
Some(wallet) => {
let object_json = serde_json::to_string(object)
.to_indy(IndyErrorKind::InvalidState, format!("Cannot serialize {:?}", type_))?;
wallet.update(&self.add_prefix(type_), name, &object_json)?;
Ok(object_json)
}
None => Err(err_msg(IndyErrorKind::InvalidWalletHandle, "Unknown wallet handle"))
}
}
pub fn add_record_tags(&self, wallet_handle: WalletHandle, type_: &str, name: &str, tags: &Tags) -> IndyResult<()> {
match self.wallets.borrow_mut().get_mut(&wallet_handle) {
Some(wallet) => wallet.add_tags(type_, name, tags)
.map_err(|err| WalletService::_map_wallet_storage_error(err, type_, name)),
None => Err(err_msg(IndyErrorKind::InvalidWalletHandle, "Unknown wallet handle"))
}
}
pub fn update_record_tags(&self, wallet_handle: WalletHandle, type_: &str, name: &str, tags: &Tags) -> IndyResult<()> {
match self.wallets.borrow_mut().get_mut(&wallet_handle) {
Some(wallet) => wallet.update_tags(type_, name, tags)
.map_err(|err| WalletService::_map_wallet_storage_error(err, type_, name)),
None => Err(err_msg(IndyErrorKind::InvalidWalletHandle, "Unknown wallet handle"))
}
}
pub fn delete_record_tags(&self, wallet_handle: WalletHandle, type_: &str, name: &str, tag_names: &[&str]) -> IndyResult<()> {
match self.wallets.borrow().get(&wallet_handle) {
Some(wallet) => wallet.delete_tags(type_, name, tag_names)
.map_err(|err| WalletService::_map_wallet_storage_error(err, type_, name)),
None => Err(err_msg(IndyErrorKind::InvalidWalletHandle, "Unknown wallet handle"))
}
}
pub fn delete_record(&self, wallet_handle: WalletHandle, type_: &str, name: &str) -> IndyResult<()> {
match self.wallets.borrow().get(&wallet_handle) {
Some(wallet) => wallet.delete(type_, name)
.map_err(|err| WalletService::_map_wallet_storage_error(err, type_, name)),
None => Err(err_msg(IndyErrorKind::InvalidWalletHandle, "Unknown wallet handle"))
}
}
pub fn delete_indy_record<T>(&self, wallet_handle: WalletHandle, name: &str) -> IndyResult<()> where T: Sized {
self.delete_record(wallet_handle, &self.add_prefix(short_type_name::<T>()), name)
}
pub fn get_record(&self, wallet_handle: WalletHandle, type_: &str, name: &str, options_json: &str) -> IndyResult<WalletRecord> {
match self.wallets.borrow().get(&wallet_handle) {
Some(wallet) =>
wallet.get(type_, name, options_json)
.map_err(|err| WalletService::_map_wallet_storage_error(err, type_, name)),
None => Err(err_msg(IndyErrorKind::InvalidWalletHandle, "Unknown wallet handle"))
}
}
pub fn get_indy_record<T>(&self, wallet_handle: WalletHandle, name: &str, options_json: &str) -> IndyResult<WalletRecord> where T: Sized {
self.get_record(wallet_handle, &self.add_prefix(short_type_name::<T>()), name, options_json)
}
pub fn get_indy_record_value<T>(&self, wallet_handle: WalletHandle, name: &str, options_json: &str) -> IndyResult<String> where T: Sized {
let type_ = short_type_name::<T>();
let record: WalletRecord = match self.wallets.borrow().get(&wallet_handle) {
Some(wallet) => wallet.get(&self.add_prefix(type_), name, options_json),
None => Err(err_msg(IndyErrorKind::InvalidWalletHandle, "Unknown wallet handle"))
}?;
let record_value = record.get_value()
.ok_or_else(||err_msg(IndyErrorKind::InvalidState, format!("{} not found for id: {:?}", type_, name)))?.to_string();
Ok(record_value)
}
// Dirty hack. json must live longer then result T
pub fn get_indy_object<T>(&self, wallet_handle: WalletHandle, name: &str, options_json: &str) -> IndyResult<T> where T: ::serde::de::DeserializeOwned + Sized {
let record_value = self.get_indy_record_value::<T>(wallet_handle, name, options_json)?;
serde_json::from_str(&record_value)
.to_indy(IndyErrorKind::InvalidState, format!("Cannot deserialize {:?}", short_type_name::<T>()))
}
// Dirty hack. json must live longer then result T
pub fn get_indy_opt_object<T>(&self, wallet_handle: WalletHandle, name: &str, options_json: &str) -> IndyResult<Option<T>> where T: ::serde::de::DeserializeOwned + Sized {
match self.get_indy_object::<T>(wallet_handle, name, options_json) {
Ok(res) => Ok(Some(res)),
Err(ref err) if err.kind() == IndyErrorKind::WalletItemNotFound => Ok(None),
Err(err) => Err(err)
}
}
pub fn search_records(&self, wallet_handle: WalletHandle, type_: &str, query_json: &str, options_json: &str) -> IndyResult<WalletSearch> {
match self.wallets.borrow().get(&wallet_handle) {
Some(wallet) => Ok(WalletSearch { iter: wallet.search(type_, query_json, Some(options_json))? }),
None => Err(err_msg(IndyErrorKind::InvalidWalletHandle, "Unknown wallet handle"))
}
}
pub fn search_indy_records<T>(&self, wallet_handle: WalletHandle, query_json: &str, options_json: &str) -> IndyResult<WalletSearch> where T: Sized {
self.search_records(wallet_handle, &self.add_prefix(short_type_name::<T>()), query_json, options_json)
}
#[allow(dead_code)] // TODO: Should we implement getting all records or delete everywhere?
pub fn search_all_records(&self, _wallet_handle: WalletHandle) -> IndyResult<WalletSearch> {
// match self.wallets.borrow().get(&wallet_handle) {
// Some(wallet) => wallet.search_all_records(),
// None => Err(IndyError::InvalidHandle(wallet_handle.to_string()))
// }
unimplemented!()
}
pub fn upsert_indy_object<T>(&self, wallet_handle: WalletHandle, name: &str, object: &T) -> IndyResult<String>
where T: ::serde::Serialize + Sized {
if self.record_exists::<T>(wallet_handle, name)? {
self.update_indy_object::<T>(wallet_handle, name, object)
} else {
self.add_indy_object::<T>(wallet_handle, name, object, &HashMap::new())
}
}
pub fn record_exists<T>(&self, wallet_handle: WalletHandle, name: &str) -> IndyResult<bool> where T: Sized {
match self.wallets.borrow().get(&wallet_handle) {
Some(wallet) =>
match wallet.get(&self.add_prefix(short_type_name::<T>()), name, &RecordOptions::id()) {
Ok(_) => Ok(true),
Err(ref err) if err.kind() == IndyErrorKind::WalletItemNotFound => Ok(false),
Err(err) => Err(err),
}
None => Err(err_msg(IndyErrorKind::InvalidWalletHandle, "Unknown wallet handle"))
}
}
pub fn check(&self, handle: WalletHandle) -> IndyResult<()> {
match self.wallets.borrow().get(&handle) {
Some(_) => Ok(()),
None => Err(err_msg(IndyErrorKind::InvalidWalletHandle, "Unknown wallet handle"))
}
}
pub fn export_wallet(&self, wallet_handle: WalletHandle, export_config: &ExportConfig, version: u32, key: (&KeyDerivationData, &MasterKey)) -> IndyResult<()> {
trace!("export_wallet >>> wallet_handle: {:?}, export_config: {:?}, version: {:?}", wallet_handle, secret!(export_config), version);
if version != 0 {
return Err(err_msg(IndyErrorKind::InvalidState, "Unsupported version"));
}
let (key_data, key) = key;
let wallets = self.wallets.borrow();
let wallet = wallets
.get(&wallet_handle)
.ok_or_else(|| err_msg(IndyErrorKind::InvalidWalletHandle, "Unknown wallet handle"))?;
let path = PathBuf::from(&export_config.path);
if let Some(parent_path) = path.parent() {
fs::DirBuilder::new()
.recursive(true)
.create(parent_path)?;
}
let mut export_file =
fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(export_config.path.clone())?;
let res = export_continue(wallet, &mut export_file, version, key.clone(), key_data);
trace!("export_wallet <<<");
res
}
pub fn import_wallet_prepare(&self,
config: &Config,
credentials: &Credentials,
export_config: &ExportConfig) -> IndyResult<(WalletHandle, KeyDerivationData, KeyDerivationData)> {
trace!("import_wallet_prepare >>> config: {:?}, credentials: {:?}, export_config: {:?}", config, secret!(export_config), secret!(export_config));
let exported_file_to_import =
fs::OpenOptions::new()
.read(true)
.open(&export_config.path)?;
let (reader, import_key_derivation_data, nonce, chunk_size, header_bytes) = preparse_file_to_import(exported_file_to_import, &export_config.key)?;
let key_data = KeyDerivationData::from_passphrase_with_new_salt(&credentials.key, &credentials.key_derivation_method);
let wallet_handle = indy_utils::next_wallet_handle();
let stashed_key_data = key_data.clone();
self.pending_for_import.borrow_mut().insert(wallet_handle, (reader, nonce, chunk_size, header_bytes, stashed_key_data));
Ok((wallet_handle, key_data, import_key_derivation_data))
}
pub fn import_wallet_continue(&self, wallet_handle: WalletHandle, config: &Config, credentials: &Credentials, key: (MasterKey, MasterKey)) -> IndyResult<()> {
let (reader, nonce, chunk_size, header_bytes, key_data) = self.pending_for_import.borrow_mut().remove(&wallet_handle).unwrap();
let (import_key, master_key) = key;
let keys = self._create_wallet(config, credentials, (&key_data, &master_key))?;
self._is_id_from_config_not_used(config)?;
let storage = self._open_storage(config, credentials)?;
let metadata = storage.get_storage_metadata()?;
let res = {
let wallet = Wallet::new(WalletService::_get_wallet_id(&config), storage, Rc::new(keys));
finish_import(&wallet, reader, import_key, nonce, chunk_size, header_bytes)
};
if res.is_err() {
let metadata: Metadata = serde_json::from_slice(&metadata)
.to_indy(IndyErrorKind::InvalidState, "Cannot deserialize metadata")?;
self.delete_wallet_continue(config, credentials, &metadata, &master_key)?;
}
// self.close_wallet(wallet_handle)?;
trace!("import_wallet <<<");
res
}
fn _get_config_and_cred_for_storage<'a>(config: &Config, credentials: &Credentials, storage_types: &'a HashMap<String, Box<dyn WalletStorageType>>) -> IndyResult<(&'a Box<dyn WalletStorageType>, Option<String>, Option<String>)> {
let storage_type = {
let storage_type = config.storage_type
.as_ref()
.map(String::as_str)
.unwrap_or("default");
storage_types
.get(storage_type)
.ok_or_else(|| err_msg(IndyErrorKind::UnknownWalletStorageType, "Unknown wallet storage type"))?
};
let storage_config = config.storage_config.as_ref().map(SValue::to_string);
let storage_credentials = credentials.storage_credentials.as_ref().map(SValue::to_string);
Ok((storage_type, storage_config, storage_credentials))
}
fn _is_id_from_config_not_used(&self, config: &Config) -> IndyResult<()> {
if self.wallets.borrow_mut().values().any(|ref wallet| wallet.get_id() == WalletService::_get_wallet_id(config)) {
return Err(err_msg(IndyErrorKind::WalletAlreadyOpened, format!("Wallet {} already opened", WalletService::_get_wallet_id(config))));
}
Ok(())
}
fn _get_wallet_id(config: &Config) -> String {
let wallet_path = config.storage_config.as_ref().and_then(|storage_config| storage_config["path"].as_str()).unwrap_or("");
let wallet_id = format!("{}{}", config.id, wallet_path);
wallet_id
}
fn _open_storage(&self, config: &Config, credentials: &Credentials) -> IndyResult<Box<dyn WalletStorage>> {
let storage_types = self.storage_types.borrow();
let (storage_type, storage_config, storage_credentials) =
WalletService::_get_config_and_cred_for_storage(config, credentials, &storage_types)?;
let storage = storage_type.open_storage(&config.id,
storage_config.as_ref().map(String::as_str),
storage_credentials.as_ref().map(String::as_str))?;
Ok(storage)
}
fn _prepare_metadata(&self, master_key: &chacha20poly1305_ietf::Key, key_data: &KeyDerivationData, keys: &Keys) -> IndyResult<Vec<u8>> {
let encrypted_keys = keys.serialize_encrypted(master_key)?;
let metadata = match key_data {
KeyDerivationData::Raw(_) => {
Metadata::MetadataRaw(
MetadataRaw { keys: encrypted_keys }
)
}
KeyDerivationData::Argon2iInt(_, salt) | KeyDerivationData::Argon2iMod(_, salt) => {
Metadata::MetadataArgon(
MetadataArgon {
keys: encrypted_keys,
master_key_salt: salt[..].to_vec(),
}
)
}
};
let res = serde_json::to_vec(&metadata)
.to_indy(IndyErrorKind::InvalidState, "Cannot serialize wallet metadata")?;
Ok(res)
}
fn _restore_keys(&self, metadata: &Metadata, master_key: &MasterKey) -> IndyResult<Keys> {
let metadata_keys = metadata.get_keys();
let res = Keys::deserialize_encrypted(&metadata_keys, master_key)
.map_err(|err| err.map(IndyErrorKind::WalletAccessFailed, "Invalid master key provided"))?;
Ok(res)
}
pub const PREFIX: &'static str = "Indy";
pub fn add_prefix(&self, type_: &str) -> String {
format!("{}::{}", WalletService::PREFIX, type_)
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(untagged)]
pub enum Metadata {
MetadataArgon(MetadataArgon),
MetadataRaw(MetadataRaw),
}
impl Metadata {
pub fn get_keys(&self) -> &Vec<u8> {
match *self {
Metadata::MetadataArgon(ref metadata) => &metadata.keys,
Metadata::MetadataRaw(ref metadata) => &metadata.keys,
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct MetadataArgon {
pub keys: Vec<u8>,
pub master_key_salt: Vec<u8>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct MetadataRaw {
pub keys: Vec<u8>
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct WalletRecord {
#[serde(rename = "type")]
type_: Option<String>,
id: String,
value: Option<String>,
tags: Option<Tags>,
}
impl Ord for WalletRecord {
fn cmp(&self, other: &Self) -> ::std::cmp::Ordering {
(&self.type_, &self.id).cmp(&(&other.type_, &other.id))
}
}
impl PartialOrd for WalletRecord {
fn partial_cmp(&self, other: &Self) -> Option<::std::cmp::Ordering> {
(&self.type_, &self.id).partial_cmp(&(&other.type_, &other.id))
}
}
impl WalletRecord {
pub fn new(name: String, type_: Option<String>, value: Option<String>, tags: Option<Tags>) -> WalletRecord {
WalletRecord {
id: name,
type_,
value,
tags,
}
}
pub fn get_id(&self) -> &str {
self.id.as_str()
}
#[allow(dead_code)]
pub fn get_type(&self) -> Option<&str> {
self.type_.as_ref().map(String::as_str)
}
pub fn get_value(&self) -> Option<&str> {
self.value.as_ref().map(String::as_str)
}
#[allow(dead_code)]
pub fn get_tags(&self) -> Option<&Tags> {
self.tags.as_ref()
}
}
fn default_true() -> bool { true }
fn default_false() -> bool { false }
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct RecordOptions {
#[serde(default = "default_false")]
retrieve_type: bool,
#[serde(default = "default_true")]
retrieve_value: bool,
#[serde(default = "default_false")]
retrieve_tags: bool,
}
impl RecordOptions {
pub fn id() -> String {
let options = RecordOptions {
retrieve_type: false,
retrieve_value: false,
retrieve_tags: false,
};
serde_json::to_string(&options).unwrap()
}
pub fn id_value() -> String {
let options = RecordOptions {
retrieve_type: false,
retrieve_value: true,
retrieve_tags: false,
};
serde_json::to_string(&options).unwrap()
}
}
impl Default for RecordOptions {
fn default() -> RecordOptions {
RecordOptions {
retrieve_type: false,
retrieve_value: true,
retrieve_tags: false,
}
}
}
pub struct WalletSearch {
iter: iterator::WalletIterator,
}
impl WalletSearch {
pub fn get_total_count(&self) -> IndyResult<Option<usize>> {
self.iter.get_total_count()
}
pub fn fetch_next_record(&mut self) -> IndyResult<Option<WalletRecord>> {
self.iter.next()
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SearchOptions {
#[serde(default = "default_true")]
retrieve_records: bool,
#[serde(default = "default_false")]
retrieve_total_count: bool,
#[serde(default = "default_false")]
retrieve_type: bool,
#[serde(default = "default_true")]
retrieve_value: bool,
#[serde(default = "default_false")]
retrieve_tags: bool,
}
impl SearchOptions {
pub fn id_value() -> String {
let options = SearchOptions {
retrieve_records: true,
retrieve_total_count: true,
retrieve_type: true,
retrieve_value: true,
retrieve_tags: false,
};
serde_json::to_string(&options).unwrap()
}
}
impl Default for SearchOptions {
fn default() -> SearchOptions {
SearchOptions {
retrieve_records: true,
retrieve_total_count: false,
retrieve_type: false,
retrieve_value: true,
retrieve_tags: false,
}
}
}
fn short_type_name<T>() -> &'static str {
let type_name = std::any::type_name::<T>();
type_name.rsplitn(2, "::").next().unwrap_or(type_name)
}
#[cfg(test)]
#[macro_use]
extern crate lazy_static;
#[cfg(test)]
#[macro_use]
extern crate serde_json;
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use indy_api_types::INVALID_WALLET_HANDLE;
use indy_api_types::domain::wallet::KeyDerivationMethod;
use indy_utils::environment;
use indy_utils::inmem_wallet::InmemWallet;
use indy_utils::test;
use indy_utils::next_wallet_handle;
use super::*;
impl WalletService {
fn open_wallet(&self, config: &Config, credentials: &Credentials) -> IndyResult<WalletHandle> {
self._is_id_from_config_not_used(config)?;
let (storage, metadata, key_derivation_data) = self._open_storage_and_fetch_metadata(config, credentials)?;
let wallet_handle = next_wallet_handle();
let rekey_data: Option<KeyDerivationData> = credentials.rekey.as_ref().map(|ref rekey|
KeyDerivationData::from_passphrase_with_new_salt(rekey, &credentials.rekey_derivation_method));
self.pending_for_open.borrow_mut().insert(wallet_handle, (WalletService::_get_wallet_id(config), storage, metadata, rekey_data.clone()));
let key = key_derivation_data.calc_master_key()?;
let rekey = match rekey_data {
Some(rekey_data) => {
let rekey_result = rekey_data.calc_master_key()?;
Some(rekey_result)
}
None => None
};
self.open_wallet_continue(wallet_handle, (&key, rekey.as_ref()))
}
pub fn import_wallet(&self,
config: &Config,
credentials: &Credentials,
export_config: &ExportConfig) -> IndyResult<()> {
trace!("import_wallet_prepare >>> config: {:?}, credentials: {:?}, export_config: {:?}", config, secret!(export_config), secret!(export_config));
let exported_file_to_import =
fs::OpenOptions::new()
.read(true)
.open(&export_config.path)?;
let (reader, import_key_derivation_data, nonce, chunk_size, header_bytes) = preparse_file_to_import(exported_file_to_import, &export_config.key)?;
let key_data = KeyDerivationData::from_passphrase_with_new_salt(&credentials.key, &credentials.key_derivation_method);
let wallet_handle = next_wallet_handle();
let import_key = import_key_derivation_data.calc_master_key()?;
let master_key = key_data.calc_master_key()?;
self.pending_for_import.borrow_mut().insert(wallet_handle, (reader, nonce, chunk_size, header_bytes, key_data));
self.import_wallet_continue(wallet_handle, config, credentials, (import_key, master_key))
}
pub fn delete_wallet(&self, config: &Config, credentials: &Credentials) -> IndyResult<()> {
if self.wallets.borrow_mut().values().any(|ref wallet| wallet.get_id() == WalletService::_get_wallet_id(config)) {
return Err(err_msg(IndyErrorKind::InvalidState, format!("Wallet has to be closed before deleting: {:?}", WalletService::_get_wallet_id(config))))?;
}
let (_, metadata, key_derivation_data) = self._open_storage_and_fetch_metadata(config, credentials)?;
let master_key = key_derivation_data.calc_master_key()?;
self.delete_wallet_continue(config, credentials, &metadata, &master_key)
}
}
#[test]
fn wallet_service_new_works() {
WalletService::new();
}
#[test]
fn wallet_service_register_type_works() {
_cleanup("wallet_service_register_type_works");
let wallet_service = WalletService::new();
_register_inmem_wallet(&wallet_service);
_cleanup("wallet_service_register_type_works");
}
#[test]
fn wallet_service_create_wallet_works() {
test::cleanup_wallet("wallet_service_create_wallet_works");
{
let wallet_service = WalletService::new();
wallet_service.create_wallet(&_config_default("wallet_service_create_wallet_works"), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
}
test::cleanup_wallet("wallet_service_create_wallet_works");
}
#[test]
fn wallet_service_create_wallet_works_for_interactive_key_derivation() {
test::cleanup_wallet("wallet_service_create_wallet_works_for_interactive_key_derivation");
{
let wallet_service = WalletService::new();
wallet_service.create_wallet(&_config_default("wallet_service_create_wallet_works_for_interactive_key_derivation"), &ARGON_INT_CREDENTIAL, (&INTERACTIVE_KDD, &INTERACTIVE_MASTER_KEY)).unwrap();
}
test::cleanup_wallet("wallet_service_create_wallet_works_for_interactive_key_derivation");
}
#[test]
fn wallet_service_create_wallet_works_for_moderate_key_derivation() {
test::cleanup_wallet("wallet_service_create_wallet_works_for_moderate_key_derivation");
{
let wallet_service = WalletService::new();
wallet_service.create_wallet(&_config_default("wallet_service_create_wallet_works_for_moderate_key_derivation"), &ARGON_MOD_CREDENTIAL, (&MODERATE_KDD, &MODERATE_MASTER_KEY)).unwrap();
}
test::cleanup_wallet("wallet_service_create_wallet_works_for_moderate_key_derivation");
}
#[test]
#[ignore]
fn wallet_service_create_wallet_works_for_comparision_time_of_different_key_types() {
use std::time::Instant;
test::cleanup_wallet("wallet_service_create_wallet_works_for_comparision_time_of_different_key_types");
{
let wallet_service = WalletService::new();
let config = _config_default("wallet_service_create_wallet_works_for_comparision_time_of_different_key_types");
let time = Instant::now();
wallet_service.create_wallet(&config, &ARGON_MOD_CREDENTIAL, (&MODERATE_KDD, &MODERATE_MASTER_KEY)).unwrap();
let time_diff_moderate_key = time.elapsed();
wallet_service.delete_wallet(&config, &ARGON_MOD_CREDENTIAL).unwrap();
_cleanup("wallet_service_create_wallet_works_for_comparision_time_of_different_key_types");
let time = Instant::now();
wallet_service.create_wallet(&config, &ARGON_INT_CREDENTIAL, (&INTERACTIVE_KDD, &INTERACTIVE_MASTER_KEY)).unwrap();
let time_diff_interactive_key = time.elapsed();
wallet_service.delete_wallet(&config, &ARGON_INT_CREDENTIAL).unwrap();
assert!(time_diff_interactive_key < time_diff_moderate_key);
}
test::cleanup_wallet("wallet_service_create_wallet_works_for_comparision_time_of_different_key_types");
}
#[test]
fn wallet_service_create_works_for_plugged() {
_cleanup("wallet_service_create_works_for_plugged");
{
let wallet_service = WalletService::new();
_register_inmem_wallet(&wallet_service);
wallet_service.create_wallet(&_config_inmem(), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
}
_cleanup("wallet_service_create_works_for_plugged");
}
#[test]
fn wallet_service_create_wallet_works_for_none_type() {
test::cleanup_wallet("wallet_service_create_wallet_works_for_none_type");
{
let wallet_service = WalletService::new();
wallet_service.create_wallet(&_config("wallet_service_create_wallet_works_for_none_type"), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
}
test::cleanup_wallet("wallet_service_create_wallet_works_for_none_type");
}
#[test]
fn wallet_service_create_wallet_works_for_unknown_type() {
test::cleanup_wallet("wallet_service_create_wallet_works_for_unknown_type");
{
let wallet_service = WalletService::new();
let res = wallet_service.create_wallet(&_config_unknown("wallet_service_create_wallet_works_for_unknown_type"), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY));
assert_kind!(IndyErrorKind::UnknownWalletStorageType, res);
}
}
#[test]
fn wallet_service_create_wallet_works_for_twice() {
test::cleanup_wallet("wallet_service_create_wallet_works_for_twice");
{
let wallet_service = WalletService::new();
wallet_service.create_wallet(&_config("wallet_service_create_wallet_works_for_twice"), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let res = wallet_service.create_wallet(&_config("wallet_service_create_wallet_works_for_twice"), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY));
assert_kind!(IndyErrorKind::WalletAlreadyExists, res);
}
test::cleanup_wallet("wallet_service_create_wallet_works_for_twice");
}
/*
#[test]
fn wallet_service_create_wallet_works_for_invalid_raw_key() {
_cleanup("wallet_service_create_wallet_works_for_invalid_raw_key");
let wallet_service = WalletService::new();
wallet_service.create_wallet(&_config("wallet_service_create_wallet_works_for_invalid_raw_key"), &_credentials()).unwrap();
let res = wallet_service.create_wallet(&_config("wallet_service_create_wallet_works_for_invalid_raw_key"), &_credentials_invalid_raw());
assert_match!(Err(IndyError::CommonError(CommonError::InvalidStructure(_))), res);
}
*/
#[test]
fn wallet_service_delete_wallet_works() {
test::cleanup_wallet("wallet_service_delete_wallet_works");
{
let config: &Config = &_config("wallet_service_delete_wallet_works");
let wallet_service = WalletService::new();
wallet_service.create_wallet(config, &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
wallet_service.delete_wallet(config, &RAW_CREDENTIAL).unwrap();
wallet_service.create_wallet(config, &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
}
test::cleanup_wallet("wallet_service_delete_wallet_works");
}
#[test]
fn wallet_service_delete_wallet_works_for_interactive_key_derivation() {
test::cleanup_wallet("wallet_service_delete_wallet_works_for_interactive_key_derivation");
{
let config: &Config = &_config("wallet_service_delete_wallet_works_for_interactive_key_derivation");
let wallet_service = WalletService::new();
wallet_service.create_wallet(config, &ARGON_INT_CREDENTIAL, (&INTERACTIVE_KDD, &INTERACTIVE_MASTER_KEY)).unwrap();
wallet_service.delete_wallet(config, &ARGON_INT_CREDENTIAL).unwrap();
wallet_service.create_wallet(config, &ARGON_INT_CREDENTIAL, (&INTERACTIVE_KDD, &INTERACTIVE_MASTER_KEY)).unwrap();
}
test::cleanup_wallet("wallet_service_delete_wallet_works_for_interactive_key_derivation");
}
#[test]
fn wallet_service_delete_wallet_works_for_moderate_key_derivation() {
test::cleanup_wallet("wallet_service_delete_wallet_works_for_moderate_key_derivation");
{
let config: &Config = &_config("wallet_service_delete_wallet_works_for_moderate_key_derivation");
let wallet_service = WalletService::new();
wallet_service.create_wallet(config, &ARGON_MOD_CREDENTIAL, (&MODERATE_KDD, &MODERATE_MASTER_KEY)).unwrap();
wallet_service.delete_wallet(config, &ARGON_MOD_CREDENTIAL).unwrap();
wallet_service.create_wallet(config, &ARGON_MOD_CREDENTIAL, (&MODERATE_KDD, &MODERATE_MASTER_KEY)).unwrap();
}
test::cleanup_wallet("wallet_service_delete_wallet_works_for_moderate_key_derivation");
}
#[test]
fn wallet_service_delete_works_for_plugged() {
test::cleanup_wallet("wallet_service_delete_works_for_plugged");
let wallet_service = WalletService::new();
_register_inmem_wallet(&wallet_service);
wallet_service.create_wallet(&_config_inmem(), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
wallet_service.delete_wallet(&_config_inmem(), &RAW_CREDENTIAL).unwrap();
wallet_service.create_wallet(&_config_inmem(), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
}
#[test]
fn wallet_service_delete_wallet_returns_error_if_wallet_opened() {
test::cleanup_wallet("wallet_service_delete_wallet_returns_error_if_wallet_opened");
{
let config: &Config = &_config("wallet_service_delete_wallet_returns_error_if_wallet_opened");
let wallet_service = WalletService::new();
wallet_service.create_wallet(config, &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
wallet_service.open_wallet(config, &RAW_CREDENTIAL).unwrap();
let res = wallet_service.delete_wallet(config, &RAW_CREDENTIAL);
assert_eq!(IndyErrorKind::InvalidState, res.unwrap_err().kind());
}
test::cleanup_wallet("wallet_service_delete_wallet_returns_error_if_wallet_opened");
}
#[test]
fn wallet_service_delete_wallet_returns_error_if_passed_different_value_for_interactive_method() {
test::cleanup_wallet("wallet_service_delete_wallet_returns_error_if_passed_different_value_for_interactive_method");
{
let config: &Config = &_config("wallet_service_delete_wallet_returns_error_if_passed_different_value_for_interactive_method");
let wallet_service = WalletService::new();
wallet_service.create_wallet(config, &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let res = wallet_service.delete_wallet(config, &ARGON_INT_CREDENTIAL);
assert_eq!(IndyErrorKind::WalletAccessFailed, res.unwrap_err().kind());
}
test::cleanup_wallet("wallet_service_delete_wallet_returns_error_if_passed_different_value_for_interactive_method");
}
#[test]
fn wallet_service_delete_wallet_returns_error_for_nonexistant_wallet() {
test::cleanup_wallet("wallet_service_delete_wallet_returns_error_for_nonexistant_wallet");
let wallet_service = WalletService::new();
let res = wallet_service.delete_wallet(&_config("wallet_service_delete_wallet_returns_error_for_nonexistant_wallet"), &RAW_CREDENTIAL);
assert_eq!(IndyErrorKind::WalletNotFound, res.unwrap_err().kind());
}
#[test]
fn wallet_service_open_wallet_works() {
test::cleanup_wallet("wallet_service_open_wallet_works");
{
let wallet_service = WalletService::new();
wallet_service.create_wallet(&_config("wallet_service_open_wallet_works"), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let handle = wallet_service.open_wallet(&_config("wallet_service_open_wallet_works"), &RAW_CREDENTIAL).unwrap();
// cleanup
wallet_service.close_wallet(handle).unwrap();
}
test::cleanup_wallet("wallet_service_open_wallet_works");
}
#[test]
fn wallet_service_open_wallet_works_for_interactive_key_derivation() {
test::cleanup_wallet("wallet_service_open_wallet_works_for_interactive_key_derivation");
{
let wallet_service = WalletService::new();
wallet_service.create_wallet(&_config("wallet_service_open_wallet_works_for_interactive_key_derivation"), &ARGON_INT_CREDENTIAL, (&INTERACTIVE_KDD, &INTERACTIVE_MASTER_KEY)).unwrap();
let handle = wallet_service.open_wallet(&_config("wallet_service_open_wallet_works_for_interactive_key_derivation"), &ARGON_INT_CREDENTIAL).unwrap();
// cleanup
wallet_service.close_wallet(handle).unwrap();
}
test::cleanup_wallet("wallet_service_open_wallet_works_for_interactive_key_derivation");
}
#[test]
fn wallet_service_open_wallet_works_for_moderate_key_derivation() {
test::cleanup_wallet("wallet_service_open_wallet_works_for_moderate_key_derivation");
{
let wallet_service = WalletService::new();
wallet_service.create_wallet(&_config("wallet_service_open_wallet_works_for_moderate_key_derivation"), &ARGON_MOD_CREDENTIAL, (&MODERATE_KDD, &MODERATE_MASTER_KEY)).unwrap();
let handle = wallet_service.open_wallet(&_config("wallet_service_open_wallet_works_for_moderate_key_derivation"), &ARGON_MOD_CREDENTIAL).unwrap();
// cleanup
wallet_service.close_wallet(handle).unwrap();
}
test::cleanup_wallet("wallet_service_open_wallet_works_for_moderate_key_derivation");
}
#[test]
fn wallet_service_open_wallet_works_for_two_wallets_with_same_ids_but_different_paths() {
_cleanup("wallet_service_open_wallet_works_for_two_wallets_with_same_ids_but_different_paths");
let wallet_service = WalletService::new();
let config_1 = Config {
id: String::from("same_id"),
storage_type: None,
storage_config: None,
};
wallet_service.create_wallet(&config_1, &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let handle_1 = wallet_service.open_wallet(&config_1, &RAW_CREDENTIAL).unwrap();
let config_2 = Config {
id: String::from("same_id"),
storage_type: None,
storage_config: Some(json!({
"path": _custom_path("wallet_service_open_wallet_works_for_two_wallets_with_same_ids_but_different_paths")
})),
};
wallet_service.create_wallet(&config_2, &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let handle_2 = wallet_service.open_wallet(&config_2, &RAW_CREDENTIAL).unwrap();
// cleanup
wallet_service.close_wallet(handle_1).unwrap();
wallet_service.close_wallet(handle_2).unwrap();
wallet_service.delete_wallet(&config_1, &RAW_CREDENTIAL).unwrap();
wallet_service.delete_wallet(&config_2, &RAW_CREDENTIAL).unwrap();
_cleanup("wallet_service_open_wallet_works_for_two_wallets_with_same_ids_but_different_paths");
}
#[test]
fn wallet_service_open_unknown_wallet() {
test::cleanup_wallet("wallet_service_open_unknown_wallet");
let wallet_service = WalletService::new();
let res = wallet_service.open_wallet(&_config("wallet_service_open_unknown_wallet"), &RAW_CREDENTIAL);
assert_eq!(IndyErrorKind::WalletNotFound, res.unwrap_err().kind());
}
#[test]
fn wallet_service_open_wallet_returns_appropriate_error_if_already_opened() {
test::cleanup_wallet("wallet_service_open_wallet_returns_appropriate_error_if_already_opened");
{
let config: &Config = &_config("wallet_service_open_wallet_returns_appropriate_error_if_already_opened");
let wallet_service = WalletService::new();
wallet_service.create_wallet(config, &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
wallet_service.open_wallet(config, &RAW_CREDENTIAL).unwrap();
let res = wallet_service.open_wallet(config, &RAW_CREDENTIAL);
assert_eq!(IndyErrorKind::WalletAlreadyOpened, res.unwrap_err().kind());
}
test::cleanup_wallet("wallet_service_open_wallet_returns_appropriate_error_if_already_opened");
}
#[test]
fn wallet_service_open_works_for_plugged() {
_cleanup("wallet_service_open_works_for_plugged");
let wallet_service = WalletService::new();
_register_inmem_wallet(&wallet_service);
wallet_service.create_wallet(&_config_inmem(), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
wallet_service.open_wallet(&_config_inmem(), &RAW_CREDENTIAL).unwrap();
}
#[test]
fn wallet_service_open_wallet_returns_error_if_used_different_methods_for_creating_and_opening() {
test::cleanup_wallet("wallet_service_open_wallet_returns_error_if_used_different_methods_for_creating_and_opening");
{
let wallet_service = WalletService::new();
wallet_service.create_wallet(&_config("wallet_service_open_wallet_returns_error_if_used_different_methods_for_creating_and_opening"), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let res = wallet_service.open_wallet(&_config("wallet_service_open_wallet_returns_error_if_used_different_methods_for_creating_and_opening"), &ARGON_INT_CREDENTIAL);
assert_kind!(IndyErrorKind::WalletAccessFailed, res);
}
test::cleanup_wallet("wallet_service_open_wallet_returns_error_if_used_different_methods_for_creating_and_opening");
}
#[test]
fn wallet_service_close_wallet_works() {
test::cleanup_wallet("wallet_service_close_wallet_works");
{
let config: &Config = &_config("wallet_service_close_wallet_works");
let wallet_service = WalletService::new();
wallet_service.create_wallet(config, &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(config, &RAW_CREDENTIAL).unwrap();
wallet_service.close_wallet(wallet_handle).unwrap();
let wallet_handle = wallet_service.open_wallet(config, &RAW_CREDENTIAL).unwrap();
wallet_service.close_wallet(wallet_handle).unwrap();
}
test::cleanup_wallet("wallet_service_close_wallet_works");
}
#[test]
fn wallet_service_close_works_for_plugged() {
_cleanup("wallet_service_close_works_for_plugged");
let wallet_service = WalletService::new();
_register_inmem_wallet(&wallet_service);
wallet_service.create_wallet(&_config_inmem(), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config_inmem(), &RAW_CREDENTIAL).unwrap();
wallet_service.close_wallet(wallet_handle).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config_inmem(), &RAW_CREDENTIAL).unwrap();
wallet_service.close_wallet(wallet_handle).unwrap();
}
#[test]
fn wallet_service_close_wallet_returns_appropriate_error_if_wrong_handle() {
test::cleanup_wallet("wallet_service_close_wallet_returns_appropriate_error_if_wrong_handle");
{
let wallet_service = WalletService::new();
wallet_service.create_wallet(&_config("wallet_service_close_wallet_returns_appropriate_error_if_wrong_handle"), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config("wallet_service_close_wallet_returns_appropriate_error_if_wrong_handle"), &RAW_CREDENTIAL).unwrap();
let res = wallet_service.close_wallet(INVALID_WALLET_HANDLE);
assert_kind!(IndyErrorKind::InvalidWalletHandle, res);
wallet_service.close_wallet(wallet_handle).unwrap();
}
test::cleanup_wallet("wallet_service_close_wallet_returns_appropriate_error_if_wrong_handle");
}
#[test]
fn wallet_service_add_record_works() {
test::cleanup_wallet("wallet_service_add_record_works");
{
let wallet_service = WalletService::new();
wallet_service.create_wallet(&_config("wallet_service_add_record_works"), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config("wallet_service_add_record_works"), &RAW_CREDENTIAL).unwrap();
wallet_service.add_record(wallet_handle, "type", "key1", "value1", &HashMap::new()).unwrap();
wallet_service.get_record(wallet_handle, "type", "key1", "{}").unwrap();
}
test::cleanup_wallet("wallet_service_add_record_works");
}
#[test]
fn wallet_service_add_record_works_for_plugged() {
_cleanup("wallet_service_add_record_works_for_plugged");
let wallet_service = WalletService::new();
_register_inmem_wallet(&wallet_service);
wallet_service.create_wallet(&_config_inmem(), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config_inmem(), &RAW_CREDENTIAL).unwrap();
wallet_service.add_record(wallet_handle, "type", "key1", "value1", &HashMap::new()).unwrap();
wallet_service.get_record(wallet_handle, "type", "key1", "{}").unwrap();
}
#[test]
fn wallet_service_get_record_works_for_id_only() {
test::cleanup_wallet("wallet_service_get_record_works_for_id_only");
{
let wallet_service = WalletService::new();
wallet_service.create_wallet(&_config("wallet_service_get_record_works_for_id_only"), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config("wallet_service_get_record_works_for_id_only"), &RAW_CREDENTIAL).unwrap();
wallet_service.add_record(wallet_handle, "type", "key1", "value1", &HashMap::new()).unwrap();
let record = wallet_service.get_record(wallet_handle, "type", "key1", &_fetch_options(false, false, false)).unwrap();
assert!(record.get_value().is_none());
assert!(record.get_type().is_none());
assert!(record.get_tags().is_none());
}
test::cleanup_wallet("wallet_service_get_record_works_for_id_only");
}
#[test]
fn wallet_service_get_record_works_for_plugged_for_id_only() {
test::cleanup_indy_home("wallet_service_get_record_works_for_plugged_for_id_only");
InmemWallet::cleanup();
let wallet_service = WalletService::new();
_register_inmem_wallet(&wallet_service);
wallet_service.create_wallet(&_config_inmem(), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config_inmem(), &RAW_CREDENTIAL).unwrap();
wallet_service.add_record(wallet_handle, "type", "key1", "value1", &HashMap::new()).unwrap();
let record = wallet_service.get_record(wallet_handle, "type", "key1", &_fetch_options(false, false, false)).unwrap();
assert!(record.get_value().is_none());
assert!(record.get_type().is_none());
assert!(record.get_tags().is_none());
}
#[test]
fn wallet_service_get_record_works_for_id_value() {
test::cleanup_wallet("wallet_service_get_record_works_for_id_value");
{
let wallet_service = WalletService::new();
wallet_service.create_wallet(&_config("wallet_service_get_record_works_for_id_value"), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config("wallet_service_get_record_works_for_id_value"), &RAW_CREDENTIAL).unwrap();
wallet_service.add_record(wallet_handle, "type", "key1", "value1", &HashMap::new()).unwrap();
let record = wallet_service.get_record(wallet_handle, "type", "key1", &_fetch_options(false, true, false)).unwrap();
assert_eq!("value1", record.get_value().unwrap());
assert!(record.get_type().is_none());
assert!(record.get_tags().is_none());
}
test::cleanup_wallet("wallet_service_get_record_works_for_id_value");
}
#[test]
fn wallet_service_get_record_works_for_plugged_for_id_value() {
_cleanup("wallet_service_get_record_works_for_plugged_for_id_value");
let wallet_service = WalletService::new();
_register_inmem_wallet(&wallet_service);
wallet_service.create_wallet(&_config_inmem(), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config_inmem(), &RAW_CREDENTIAL).unwrap();
wallet_service.add_record(wallet_handle, "type", "key1", "value1", &HashMap::new()).unwrap();
let record = wallet_service.get_record(wallet_handle, "type", "key1", &_fetch_options(false, true, false)).unwrap();
assert_eq!("value1", record.get_value().unwrap());
assert!(record.get_type().is_none());
assert!(record.get_tags().is_none());
}
#[test]
fn wallet_service_get_record_works_for_all_fields() {
test::cleanup_wallet("wallet_service_get_record_works_for_all_fields");
{
let wallet_service = WalletService::new();
wallet_service.create_wallet(&_config("wallet_service_get_record_works_for_all_fields"), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config("wallet_service_get_record_works_for_all_fields"), &RAW_CREDENTIAL).unwrap();
let mut tags = HashMap::new();
tags.insert(String::from("1"), String::from("some"));
wallet_service.add_record(wallet_handle, "type", "key1", "value1", &tags).unwrap();
let record = wallet_service.get_record(wallet_handle, "type", "key1", &_fetch_options(true, true, true)).unwrap();
assert_eq!("type", record.get_type().unwrap());
assert_eq!("value1", record.get_value().unwrap());
assert_eq!(&tags, record.get_tags().unwrap());
}
test::cleanup_wallet("wallet_service_get_record_works_for_all_fields");
}
#[test]
fn wallet_service_get_record_works_for_plugged_for_for_all_fields() {
_cleanup("wallet_service_get_record_works_for_plugged_for_for_all_fields");
let wallet_service = WalletService::new();
_register_inmem_wallet(&wallet_service);
wallet_service.create_wallet(&_config_inmem(), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config_inmem(), &RAW_CREDENTIAL).unwrap();
let tags = serde_json::from_str(r#"{"1":"some"}"#).unwrap();
wallet_service.add_record(wallet_handle, "type", "key1", "value1", &tags).unwrap();
let record = wallet_service.get_record(wallet_handle, "type", "key1", &_fetch_options(true, true, true)).unwrap();
assert_eq!("type", record.get_type().unwrap());
assert_eq!("value1", record.get_value().unwrap());
assert_eq!(tags, record.get_tags().unwrap().clone());
}
#[test]
fn wallet_service_add_get_works_for_reopen() {
test::cleanup_wallet("wallet_service_add_get_works_for_reopen");
{
let wallet_service = WalletService::new();
wallet_service.create_wallet(&_config("wallet_service_add_get_works_for_reopen"), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config("wallet_service_add_get_works_for_reopen"), &RAW_CREDENTIAL).unwrap();
wallet_service.add_record(wallet_handle, "type", "key1", "value1", &HashMap::new()).unwrap();
wallet_service.close_wallet(wallet_handle).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config("wallet_service_add_get_works_for_reopen"), &RAW_CREDENTIAL).unwrap();
let record = wallet_service.get_record(wallet_handle, "type", "key1", &_fetch_options(false, true, false)).unwrap();<|fim▁hole|> }
test::cleanup_wallet("wallet_service_add_get_works_for_reopen");
}
#[test]
fn wallet_service_get_works_for_unknown() {
test::cleanup_wallet("wallet_service_get_works_for_unknown");
{
let wallet_service = WalletService::new();
wallet_service.create_wallet(&_config("wallet_service_get_works_for_unknown"), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config("wallet_service_get_works_for_unknown"), &RAW_CREDENTIAL).unwrap();
let res = wallet_service.get_record(wallet_handle, "type", "key1", &_fetch_options(false, true, false));
assert_kind!(IndyErrorKind::WalletItemNotFound, res);
}
test::cleanup_wallet("wallet_service_get_works_for_unknown");
}
#[test]
fn wallet_service_get_works_for_plugged_and_unknown() {
_cleanup("wallet_service_get_works_for_plugged_and_unknown");
let wallet_service = WalletService::new();
_register_inmem_wallet(&wallet_service);
wallet_service.create_wallet(&_config_inmem(), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config_inmem(), &RAW_CREDENTIAL).unwrap();
let res = wallet_service.get_record(wallet_handle, "type", "key1", &_fetch_options(false, true, false));
assert_kind!(IndyErrorKind::WalletItemNotFound, res);
}
/**
* Update tests
*/
#[test]
fn wallet_service_update() {
test::cleanup_wallet("wallet_service_update");
{
let type_ = "type";
let name = "name";
let value = "value";
let new_value = "new_value";
let wallet_service = WalletService::new();
wallet_service.create_wallet(&_config("wallet_service_update"), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config("wallet_service_update"), &RAW_CREDENTIAL).unwrap();
wallet_service.add_record(wallet_handle, type_, name, value, &HashMap::new()).unwrap();
let record = wallet_service.get_record(wallet_handle, type_, name, &_fetch_options(false, true, false)).unwrap();
assert_eq!(value, record.get_value().unwrap());
wallet_service.update_record_value(wallet_handle, type_, name, new_value).unwrap();
let record = wallet_service.get_record(wallet_handle, type_, name, &_fetch_options(false, true, false)).unwrap();
assert_eq!(new_value, record.get_value().unwrap());
}
test::cleanup_wallet("wallet_service_update");
}
#[test]
fn wallet_service_update_for_plugged() {
_cleanup("wallet_service_update_for_plugged");
let type_ = "type";
let name = "name";
let value = "value";
let new_value = "new_value";
let wallet_service = WalletService::new();
_register_inmem_wallet(&wallet_service);
wallet_service.create_wallet(&_config_inmem(), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config_inmem(), &RAW_CREDENTIAL).unwrap();
wallet_service.add_record(wallet_handle, type_, name, value, &HashMap::new()).unwrap();
let record = wallet_service.get_record(wallet_handle, type_, name, &_fetch_options(false, true, false)).unwrap();
assert_eq!(value, record.get_value().unwrap());
wallet_service.update_record_value(wallet_handle, type_, name, new_value).unwrap();
let record = wallet_service.get_record(wallet_handle, type_, name, &_fetch_options(false, true, false)).unwrap();
assert_eq!(new_value, record.get_value().unwrap());
}
/**
* Delete tests
*/
#[test]
fn wallet_service_delete_record() {
test::cleanup_wallet("wallet_service_delete_record");
{
let type_ = "type";
let name = "name";
let value = "value";
let wallet_service = WalletService::new();
wallet_service.create_wallet(&_config("wallet_service_delete_record"), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config("wallet_service_delete_record"), &RAW_CREDENTIAL).unwrap();
wallet_service.add_record(wallet_handle, type_, name, value, &HashMap::new()).unwrap();
let record = wallet_service.get_record(wallet_handle, type_, name, &_fetch_options(false, true, false)).unwrap();
assert_eq!(value, record.get_value().unwrap());
wallet_service.delete_record(wallet_handle, type_, name).unwrap();
let res = wallet_service.get_record(wallet_handle, type_, name, &_fetch_options(false, true, false));
assert_kind!(IndyErrorKind::WalletItemNotFound, res);
}
test::cleanup_wallet("wallet_service_delete_record");
}
#[test]
fn wallet_service_delete_record_for_plugged() {
_cleanup("wallet_service_delete_record_for_plugged");
let type_ = "type";
let name = "name";
let value = "value";
let wallet_service = WalletService::new();
_register_inmem_wallet(&wallet_service);
wallet_service.create_wallet(&_config_inmem(), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config_inmem(), &RAW_CREDENTIAL).unwrap();
wallet_service.add_record(wallet_handle, type_, name, value, &HashMap::new()).unwrap();
let record = wallet_service.get_record(wallet_handle, type_, name, &_fetch_options(false, true, false)).unwrap();
assert_eq!(value, record.get_value().unwrap());
wallet_service.delete_record(wallet_handle, type_, name).unwrap();
let res = wallet_service.get_record(wallet_handle, type_, name, &_fetch_options(false, true, false));
assert_kind!(IndyErrorKind::WalletItemNotFound, res);
}
/**
* Add tags tests
*/
#[test]
fn wallet_service_add_tags() {
test::cleanup_wallet("wallet_service_add_tags");
{
let type_ = "type";
let name = "name";
let value = "value";
let tags = serde_json::from_str(r#"{"tag_name_1":"tag_value_1"}"#).unwrap();
let wallet_service = WalletService::new();
wallet_service.create_wallet(&_config("wallet_service_add_tags"), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config("wallet_service_add_tags"), &RAW_CREDENTIAL).unwrap();
wallet_service.add_record(wallet_handle, type_, name, value, &tags).unwrap();
let new_tags = serde_json::from_str(r#"{"tag_name_2":"tag_value_2", "~tag_name_3":"tag_value_3"}"#).unwrap();
wallet_service.add_record_tags(wallet_handle, type_, name, &new_tags).unwrap();
let item = wallet_service.get_record(wallet_handle, type_, name, &_fetch_options(true, true, true)).unwrap();
let expected_tags: Tags = serde_json::from_str(r#"{"tag_name_1":"tag_value_1", "tag_name_2":"tag_value_2", "~tag_name_3":"tag_value_3"}"#).unwrap();
let retrieved_tags = item.tags.unwrap();
assert_eq!(expected_tags, retrieved_tags);
}
test::cleanup_wallet("wallet_service_add_tags");
}
#[test]
fn wallet_service_add_tags_for_plugged() {
_cleanup("wallet_service_add_tags_for_plugged");
let type_ = "type";
let name = "name";
let value = "value";
let tags = serde_json::from_str(r#"{"tag_name_1":"tag_value_1"}"#).unwrap();
let wallet_service = WalletService::new();
_register_inmem_wallet(&wallet_service);
wallet_service.create_wallet(&_config_inmem(), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config_inmem(), &RAW_CREDENTIAL).unwrap();
wallet_service.add_record(wallet_handle, type_, name, value, &tags).unwrap();
let new_tags = serde_json::from_str(r#"{"tag_name_2":"tag_value_2", "~tag_name_3":"tag_value_3"}"#).unwrap();
wallet_service.add_record_tags(wallet_handle, type_, name, &new_tags).unwrap();
let item = wallet_service.get_record(wallet_handle, type_, name, &_fetch_options(true, true, true)).unwrap();
let expected_tags: Tags = serde_json::from_str(r#"{"tag_name_1":"tag_value_1", "tag_name_2":"tag_value_2", "~tag_name_3":"tag_value_3"}"#).unwrap();
let retrieved_tags = item.tags.unwrap();
assert_eq!(expected_tags, retrieved_tags);
}
/**
* Update tags tests
*/
#[test]
fn wallet_service_update_tags() {
test::cleanup_wallet("wallet_service_update_tags");
{
let type_ = "type";
let name = "name";
let value = "value";
let tags = serde_json::from_str(r#"{"tag_name_1":"tag_value_1", "tag_name_2":"tag_value_2", "~tag_name_3":"tag_value_3"}"#).unwrap();
let wallet_service = WalletService::new();
wallet_service.create_wallet(&_config("wallet_service_update_tags"), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config("wallet_service_update_tags"), &RAW_CREDENTIAL).unwrap();
wallet_service.add_record(wallet_handle, type_, name, value, &tags).unwrap();
let new_tags = serde_json::from_str(r#"{"tag_name_1":"tag_value_1", "tag_name_2":"new_tag_value_2", "~tag_name_3":"new_tag_value_3"}"#).unwrap();
wallet_service.update_record_tags(wallet_handle, type_, name, &new_tags).unwrap();
let item = wallet_service.get_record(wallet_handle, type_, name, &_fetch_options(true, true, true)).unwrap();
let retrieved_tags = item.tags.unwrap();
assert_eq!(new_tags, retrieved_tags);
}
test::cleanup_wallet("wallet_service_update_tags");
}
#[test]
fn wallet_service_update_tags_for_plugged() {
_cleanup("wallet_service_update_tags_for_plugged");
{
let type_ = "type";
let name = "name";
let value = "value";
let tags = serde_json::from_str(r#"{"tag_name_1":"tag_value_1", "tag_name_2":"tag_value_2", "~tag_name_3":"tag_value_3"}"#).unwrap();
let wallet_service = WalletService::new();
_register_inmem_wallet(&wallet_service);
wallet_service.create_wallet(&_config_inmem(), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config_inmem(), &RAW_CREDENTIAL).unwrap();
wallet_service.add_record(wallet_handle, type_, name, value, &tags).unwrap();
let new_tags = serde_json::from_str(r#"{"tag_name_1":"tag_value_1", "tag_name_2":"new_tag_value_2", "~tag_name_3":"new_tag_value_3"}"#).unwrap();
wallet_service.update_record_tags(wallet_handle, type_, name, &new_tags).unwrap();
let item = wallet_service.get_record(wallet_handle, type_, name, &_fetch_options(true, true, true)).unwrap();
let retrieved_tags = item.tags.unwrap();
assert_eq!(new_tags, retrieved_tags);
}
_cleanup("wallet_service_update_tags_for_plugged");
}
/**
* Delete tags tests
*/
#[test]
fn wallet_service_delete_tags() {
test::cleanup_wallet("wallet_service_delete_tags");
{
let type_ = "type";
let name = "name";
let value = "value";
let tags = serde_json::from_str(r#"{"tag_name_1":"tag_value_1", "tag_name_2":"new_tag_value_2", "~tag_name_3":"new_tag_value_3"}"#).unwrap();
let wallet_service = WalletService::new();
wallet_service.create_wallet(&_config("wallet_service_delete_tags"), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config("wallet_service_delete_tags"), &RAW_CREDENTIAL).unwrap();
wallet_service.add_record(wallet_handle, type_, name, value, &tags).unwrap();
let tag_names = vec!["tag_name_1", "~tag_name_3"];
wallet_service.delete_record_tags(wallet_handle, type_, name, &tag_names).unwrap();
let item = wallet_service.get_record(wallet_handle, type_, name, &_fetch_options(true, true, true)).unwrap();
let expected_tags: Tags = serde_json::from_str(r#"{"tag_name_2":"new_tag_value_2"}"#).unwrap();
let retrieved_tags = item.tags.unwrap();
assert_eq!(expected_tags, retrieved_tags);
}
test::cleanup_wallet("wallet_service_delete_tags");
}
#[test]
fn wallet_service_delete_tags_for_plugged() {
_cleanup("wallet_service_delete_tags_for_plugged");
{
let type_ = "type";
let name = "name";
let value = "value";
let tags = serde_json::from_str(r#"{"tag_name_1":"tag_value_1", "tag_name_2":"new_tag_value_2", "~tag_name_3":"new_tag_value_3"}"#).unwrap();
let wallet_service = WalletService::new();
_register_inmem_wallet(&wallet_service);
wallet_service.create_wallet(&_config_inmem(), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config_inmem(), &RAW_CREDENTIAL).unwrap();
wallet_service.add_record(wallet_handle, type_, name, value, &tags).unwrap();
let tag_names = vec!["tag_name_1", "~tag_name_3"];
wallet_service.delete_record_tags(wallet_handle, type_, name, &tag_names).unwrap();
let item = wallet_service.get_record(wallet_handle, type_, name, &_fetch_options(true, true, true)).unwrap();
let expected_tags: Tags = serde_json::from_str(r#"{"tag_name_2":"new_tag_value_2"}"#).unwrap();
let retrieved_tags = item.tags.unwrap();
assert_eq!(expected_tags, retrieved_tags);
}
_cleanup("wallet_service_delete_tags_for_plugged");
}
#[test]
fn wallet_service_search_records_works() {
test::cleanup_wallet("wallet_service_search_records_works");
{
let wallet_service = WalletService::new();
wallet_service.create_wallet(&_config("wallet_service_search_records_works"), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config("wallet_service_search_records_works"), &RAW_CREDENTIAL).unwrap();
wallet_service.add_record(wallet_handle, "type", "key1", "value1", &HashMap::new()).unwrap();
wallet_service.add_record(wallet_handle, "type", "key2", "value2", &HashMap::new()).unwrap();
wallet_service.add_record(wallet_handle, "type3", "key3", "value3", &HashMap::new()).unwrap();
let mut search = wallet_service.search_records(wallet_handle, "type3", "{}", &_fetch_options(true, true, true)).unwrap();
let record = search.fetch_next_record().unwrap().unwrap();
assert_eq!("value3", record.get_value().unwrap());
assert_eq!(HashMap::new(), record.get_tags().unwrap().clone());
assert!(search.fetch_next_record().unwrap().is_none());
}
test::cleanup_wallet("wallet_service_search_records_works");
}
#[test]
fn wallet_service_search_records_works_for_plugged_wallet() {
_cleanup("wallet_service_search_records_works_for_plugged_wallet");
let wallet_service = WalletService::new();
_register_inmem_wallet(&wallet_service);
wallet_service.create_wallet(&_config_inmem(), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config_inmem(), &RAW_CREDENTIAL).unwrap();
wallet_service.add_record(wallet_handle, "type", "key1", "value1", &HashMap::new()).unwrap();
wallet_service.add_record(wallet_handle, "type", "key2", "value2", &HashMap::new()).unwrap();
wallet_service.add_record(wallet_handle, "type3", "key3", "value3", &HashMap::new()).unwrap();
let mut search = wallet_service.search_records(wallet_handle, "type3", "{}", &_fetch_options(true, true, true)).unwrap();
let record = search.fetch_next_record().unwrap().unwrap();
assert_eq!("value3", record.get_value().unwrap());
assert_eq!(HashMap::new(), record.get_tags().unwrap().clone());
assert!(search.fetch_next_record().unwrap().is_none());
}
/**
Key rotation test
*/
#[test]
fn wallet_service_key_rotation() {
test::cleanup_wallet("wallet_service_key_rotation");
{
let config: &Config = &_config("wallet_service_key_rotation");
let wallet_service = WalletService::new();
wallet_service.create_wallet(config, &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(config, &RAW_CREDENTIAL).unwrap();
wallet_service.add_record(wallet_handle, "type", "key1", "value1", &HashMap::new()).unwrap();
let record = wallet_service.get_record(wallet_handle, "type", "key1", &_fetch_options(true, true, true)).unwrap();
assert_eq!("type", record.get_type().unwrap());
assert_eq!("value1", record.get_value().unwrap());
wallet_service.close_wallet(wallet_handle).unwrap();
let wallet_handle = wallet_service.open_wallet(config, &_rekey_credentials_moderate()).unwrap();
let record = wallet_service.get_record(wallet_handle, "type", "key1", &_fetch_options(true, true, true)).unwrap();
assert_eq!("type", record.get_type().unwrap());
assert_eq!("value1", record.get_value().unwrap());
wallet_service.close_wallet(wallet_handle).unwrap();
// Access failed for old key
let res = wallet_service.open_wallet(config, &RAW_CREDENTIAL);
assert_kind!(IndyErrorKind::WalletAccessFailed, res);
// Works ok with new key when reopening
let wallet_handle = wallet_service.open_wallet(config, &_credentials_for_new_key_moderate()).unwrap();
let record = wallet_service.get_record(wallet_handle, "type", "key1", &_fetch_options(true, true, true)).unwrap();
assert_eq!("type", record.get_type().unwrap());
assert_eq!("value1", record.get_value().unwrap());
}
test::cleanup_wallet("wallet_service_key_rotation");
}
#[test]
fn wallet_service_key_rotation_for_rekey_interactive_method() {
test::cleanup_wallet("wallet_service_key_rotation_for_rekey_interactive_method");
{
let config: &Config = &_config("wallet_service_key_rotation_for_rekey_interactive_method");
let wallet_service = WalletService::new();
wallet_service.create_wallet(config, &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(config, &RAW_CREDENTIAL).unwrap();
wallet_service.add_record(wallet_handle, "type", "key1", "value1", &HashMap::new()).unwrap();
let record = wallet_service.get_record(wallet_handle, "type", "key1", &_fetch_options(true, true, true)).unwrap();
assert_eq!("type", record.get_type().unwrap());
assert_eq!("value1", record.get_value().unwrap());
wallet_service.close_wallet(wallet_handle).unwrap();
let wallet_handle = wallet_service.open_wallet(config, &_rekey_credentials_interactive()).unwrap();
let record = wallet_service.get_record(wallet_handle, "type", "key1", &_fetch_options(true, true, true)).unwrap();
assert_eq!("type", record.get_type().unwrap());
assert_eq!("value1", record.get_value().unwrap());
wallet_service.close_wallet(wallet_handle).unwrap();
// Access failed for old key
let res = wallet_service.open_wallet(config, &RAW_CREDENTIAL);
assert_kind!(IndyErrorKind::WalletAccessFailed, res);
// Works ok with new key when reopening
let wallet_handle = wallet_service.open_wallet(config, &_credentials_for_new_key_interactive()).unwrap();
let record = wallet_service.get_record(wallet_handle, "type", "key1", &_fetch_options(true, true, true)).unwrap();
assert_eq!("type", record.get_type().unwrap());
assert_eq!("value1", record.get_value().unwrap());
}
test::cleanup_wallet("wallet_service_key_rotation_for_rekey_interactive_method");
}
#[test]
fn wallet_service_key_rotation_for_rekey_raw_method() {
test::cleanup_wallet("wallet_service_key_rotation_for_rekey_raw_method");
{
let config: &Config = &_config("wallet_service_key_rotation_for_rekey_raw_method");
let wallet_service = WalletService::new();
wallet_service.create_wallet(config, &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(config, &RAW_CREDENTIAL).unwrap();
wallet_service.add_record(wallet_handle, "type", "key1", "value1", &HashMap::new()).unwrap();
let record = wallet_service.get_record(wallet_handle, "type", "key1", &_fetch_options(true, true, true)).unwrap();
assert_eq!("type", record.get_type().unwrap());
assert_eq!("value1", record.get_value().unwrap());
wallet_service.close_wallet(wallet_handle).unwrap();
let wallet_handle = wallet_service.open_wallet(config, &_rekey_credentials_raw()).unwrap();
let record = wallet_service.get_record(wallet_handle, "type", "key1", &_fetch_options(true, true, true)).unwrap();
assert_eq!("type", record.get_type().unwrap());
assert_eq!("value1", record.get_value().unwrap());
wallet_service.close_wallet(wallet_handle).unwrap();
// Access failed for old key
let res = wallet_service.open_wallet(config, &RAW_CREDENTIAL);
assert_kind!(IndyErrorKind::WalletAccessFailed, res);
// Works ok with new key when reopening
let wallet_handle = wallet_service.open_wallet(config, &_credentials_for_new_key_raw()).unwrap();
let record = wallet_service.get_record(wallet_handle, "type", "key1", &_fetch_options(true, true, true)).unwrap();
assert_eq!("type", record.get_type().unwrap());
assert_eq!("value1", record.get_value().unwrap());
}
test::cleanup_wallet("wallet_service_key_rotation_for_rekey_raw_method");
}
fn remove_exported_wallet(export_config: &ExportConfig) -> &Path {
let export_path = Path::new(&export_config.path);
if export_path.exists() {
fs::remove_file(export_path).unwrap();
}
export_path
}
#[test]
fn wallet_service_export_wallet_when_empty() {
test::cleanup_wallet("wallet_service_export_wallet_when_empty");
let export_config = _export_config_raw("export_wallet_service_export_wallet_when_empty");
{
let wallet_service = WalletService::new();
let wallet_config = _config("wallet_service_export_wallet_when_empty");
wallet_service.create_wallet(&wallet_config, &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config("wallet_service_export_wallet_when_empty"), &RAW_CREDENTIAL).unwrap();
let export_path = remove_exported_wallet(&export_config);
let (kdd, master_key) = _export_key_raw("key_wallet_service_export_wallet_when_empty");
wallet_service.export_wallet(wallet_handle, &export_config, 0, (&kdd, &master_key)).unwrap();
assert!(export_path.exists());
}
remove_exported_wallet(&export_config);
test::cleanup_wallet("wallet_service_export_wallet_when_empty");
}
#[test]
fn wallet_service_export_wallet_1_item() {
test::cleanup_wallet("wallet_service_export_wallet_1_item");
let export_config = _export_config_raw("export_config_wallet_service_export_wallet_1_item");
{
let wallet_service = WalletService::new();
wallet_service.create_wallet(&_config("wallet_service_export_wallet_1_item"), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config("wallet_service_export_wallet_1_item"), &RAW_CREDENTIAL).unwrap();
wallet_service.add_record(wallet_handle, "type", "key1", "value1", &HashMap::new()).unwrap();
wallet_service.get_record(wallet_handle, "type", "key1", "{}").unwrap();
let export_path = remove_exported_wallet(&export_config);
let (kdd, master_key) = _export_key_raw("key_wallet_service_export_wallet_1_item");
wallet_service.export_wallet(wallet_handle, &export_config, 0, (&kdd, &master_key)).unwrap();
assert!(export_path.exists());
}
let _export_path = remove_exported_wallet(&export_config);
test::cleanup_wallet("wallet_service_export_wallet_1_item");
}
#[test]
fn wallet_service_export_wallet_1_item_interactive_method() {
test::cleanup_wallet("wallet_service_export_wallet_1_item_interactive_method");
let export_config = _export_config_interactive("wallet_service_export_wallet_1_item_interactive_method");
{
let wallet_service = WalletService::new();
wallet_service.create_wallet(&_config("wallet_service_export_wallet_1_item_interactive_method"), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config("wallet_service_export_wallet_1_item_interactive_method"), &RAW_CREDENTIAL).unwrap();
wallet_service.add_record(wallet_handle, "type", "key1", "value1", &HashMap::new()).unwrap();
wallet_service.get_record(wallet_handle, "type", "key1", "{}").unwrap();
let export_path = remove_exported_wallet(&export_config);
let (kdd, master_key) = _export_key_interactive("wallet_service_export_wallet_1_item_interactive_method");
wallet_service.export_wallet(wallet_handle, &export_config, 0, (&kdd, &master_key)).unwrap();
assert!(export_path.exists());
}
let _export_path = remove_exported_wallet(&export_config);
test::cleanup_wallet("wallet_service_export_wallet_1_item_interactive_method");
}
#[test]
fn wallet_service_export_wallet_1_item_raw_method() {
test::cleanup_wallet("wallet_service_export_wallet_1_item_raw_method");
let export_config = _export_config_raw("wallet_service_export_wallet_1_item_raw_method");
{
let wallet_service = WalletService::new();
wallet_service.create_wallet(&_config("wallet_service_export_wallet_1_item_raw_method"), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config("wallet_service_export_wallet_1_item_raw_method"), &RAW_CREDENTIAL).unwrap();
wallet_service.add_record(wallet_handle, "type", "key1", "value1", &HashMap::new()).unwrap();
wallet_service.get_record(wallet_handle, "type", "key1", "{}").unwrap();
let export_path = remove_exported_wallet(&export_config);
let (kdd, master_key) = _export_key("wallet_service_export_wallet_1_item_raw_method");
wallet_service.export_wallet(wallet_handle, &export_config, 0, (&kdd, &master_key)).unwrap();
assert!(&export_path.exists());
}
let _export_path = remove_exported_wallet(&export_config);
test::cleanup_wallet("wallet_service_export_wallet_1_item_raw_method");
}
#[test]
fn wallet_service_export_wallet_returns_error_if_file_exists() {
test::cleanup_wallet("wallet_service_export_wallet_returns_error_if_file_exists");
{
fs::create_dir_all(_export_file_path("wallet_service_export_wallet_returns_error_if_file_exists").parent().unwrap()).unwrap();
fs::File::create(_export_file_path("wallet_service_export_wallet_returns_error_if_file_exists")).unwrap();
}
assert!(_export_file_path("wallet_service_export_wallet_returns_error_if_file_exists").exists());
let export_config = _export_config_raw("wallet_service_export_wallet_returns_error_if_file_exists");
{
let wallet_service = WalletService::new();
wallet_service.create_wallet(&_config("wallet_service_export_wallet_returns_error_if_file_exists"), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config("wallet_service_export_wallet_returns_error_if_file_exists"), &RAW_CREDENTIAL).unwrap();
let (kdd, master_key) = _export_key_raw("key_wallet_service_export_wallet_returns_error_if_file_exists");
let res = wallet_service.export_wallet(wallet_handle, &export_config, 0, (&kdd, &master_key));
assert_eq!(IndyErrorKind::IOError, res.unwrap_err().kind());
}
let _export_path = remove_exported_wallet(&export_config);
test::cleanup_wallet("wallet_service_export_wallet_returns_error_if_file_exists");
}
#[test]
fn wallet_service_export_wallet_returns_error_if_wrong_handle() {
test::cleanup_wallet("wallet_service_export_wallet_returns_error_if_wrong_handle");
{
let wallet_service = WalletService::new();
wallet_service.create_wallet(&_config("wallet_service_export_wallet_returns_error_if_wrong_handle"), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let _wallet_handle = wallet_service.open_wallet(&_config("wallet_service_export_wallet_returns_error_if_wrong_handle"), &RAW_CREDENTIAL).unwrap();
let (kdd, master_key) = _export_key_raw("key_wallet_service_export_wallet_returns_error_if_wrong_handle");
let export_config = _export_config_raw("wallet_service_export_wallet_returns_error_if_wrong_handle");
let export_path = remove_exported_wallet(&export_config);
let res = wallet_service.export_wallet(INVALID_WALLET_HANDLE, &export_config, 0, (&kdd, &master_key));
assert_kind!(IndyErrorKind::InvalidWalletHandle, res);
assert!(!export_path.exists());
}
test::cleanup_wallet("wallet_service_export_wallet_returns_error_if_wrong_handle");
}
#[test]
fn wallet_service_export_import_wallet_1_item() {
test::cleanup_wallet("wallet_service_export_import_wallet_1_item");
let export_config = _export_config_raw("wallet_service_export_import_wallet_1_item");
{
let wallet_service = WalletService::new();
wallet_service.create_wallet(&_config("wallet_service_export_import_wallet_1_item"), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config("wallet_service_export_import_wallet_1_item"), &RAW_CREDENTIAL).unwrap();
wallet_service.add_record(wallet_handle, "type", "key1", "value1", &HashMap::new()).unwrap();
wallet_service.get_record(wallet_handle, "type", "key1", "{}").unwrap();
let (kdd, master_key) = _export_key_raw("key_wallet_service_export_import_wallet_1_item");
let export_path = remove_exported_wallet(&export_config);
wallet_service.export_wallet(wallet_handle, &export_config, 0, (&kdd, &master_key)).unwrap();
assert!(export_path.exists());
wallet_service.close_wallet(wallet_handle).unwrap();
wallet_service.delete_wallet(&_config("wallet_service_export_import_wallet_1_item"), &RAW_CREDENTIAL).unwrap();
let export_config = _export_config_raw("wallet_service_export_import_wallet_1_item");
wallet_service.import_wallet(&_config("wallet_service_export_import_wallet_1_item"), &RAW_CREDENTIAL, &export_config).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config("wallet_service_export_import_wallet_1_item"), &RAW_CREDENTIAL).unwrap();
wallet_service.get_record(wallet_handle, "type", "key1", "{}").unwrap();
}
let _export_path = remove_exported_wallet(&export_config);
test::cleanup_wallet("wallet_service_export_import_wallet_1_item");
}
#[test]
fn wallet_service_export_import_wallet_1_item_for_interactive_method() {
test::cleanup_wallet("wallet_service_export_import_wallet_1_item_for_interactive_method");
let export_config = _export_config_interactive("wallet_service_export_import_wallet_1_item_for_interactive_method");
{
let wallet_service = WalletService::new();
wallet_service.create_wallet(&_config("wallet_service_export_import_wallet_1_item_for_interactive_method"), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config("wallet_service_export_import_wallet_1_item_for_interactive_method"), &RAW_CREDENTIAL).unwrap();
wallet_service.add_record(wallet_handle, "type", "key1", "value1", &HashMap::new()).unwrap();
wallet_service.get_record(wallet_handle, "type", "key1", "{}").unwrap();
let (kdd, master_key) = _export_key_interactive("wallet_service_export_import_wallet_1_item_for_interactive_method");
let export_path = remove_exported_wallet(&export_config);
wallet_service.export_wallet(wallet_handle, &export_config, 0, (&kdd, &master_key)).unwrap();
assert!(export_path.exists());
wallet_service.close_wallet(wallet_handle).unwrap();
wallet_service.delete_wallet(&_config("wallet_service_export_import_wallet_1_item_for_interactive_method"), &RAW_CREDENTIAL).unwrap();
wallet_service.import_wallet(&_config("wallet_service_export_import_wallet_1_item_for_interactive_method"), &RAW_CREDENTIAL, &_export_config_interactive("wallet_service_export_import_wallet_1_item_for_interactive_method")).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config("wallet_service_export_import_wallet_1_item_for_interactive_method"), &RAW_CREDENTIAL).unwrap();
wallet_service.get_record(wallet_handle, "type", "key1", "{}").unwrap();
}
let _export_path = remove_exported_wallet(&export_config);
test::cleanup_wallet("wallet_service_export_import_wallet_1_item_for_interactive_method");
}
#[test]
fn wallet_service_export_import_wallet_1_item_for_moderate_method() {
test::cleanup_wallet("wallet_service_export_import_wallet_1_item_for_moderate_method");
let export_config = _export_config_raw("wallet_service_export_import_wallet_1_item_for_moderate_method");
{
let wallet_service = WalletService::new();
wallet_service.create_wallet(&_config("wallet_service_export_import_wallet_1_item_for_moderate_method"), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config("wallet_service_export_import_wallet_1_item_for_moderate_method"), &RAW_CREDENTIAL).unwrap();
wallet_service.add_record(wallet_handle, "type", "key1", "value1", &HashMap::new()).unwrap();
wallet_service.get_record(wallet_handle, "type", "key1", "{}").unwrap();
let (kdd, master_key) = _export_key_raw("key_wallet_service_export_import_wallet_1_item_for_moderate_method");
let export_path = remove_exported_wallet(&export_config);
wallet_service.export_wallet(wallet_handle, &export_config, 0, (&kdd, &master_key)).unwrap();
assert!(export_path.exists());
wallet_service.close_wallet(wallet_handle).unwrap();
wallet_service.delete_wallet(&_config("wallet_service_export_import_wallet_1_item_for_moderate_method"), &RAW_CREDENTIAL).unwrap();
wallet_service.import_wallet(&_config("wallet_service_export_import_wallet_1_item_for_moderate_method"), &ARGON_MOD_CREDENTIAL, &export_config).unwrap();
let wallet_handle = wallet_service.open_wallet(&_config("wallet_service_export_import_wallet_1_item_for_moderate_method"), &ARGON_MOD_CREDENTIAL).unwrap();
wallet_service.get_record(wallet_handle, "type", "key1", "{}").unwrap();
}
let _export_path = remove_exported_wallet(&export_config);
test::cleanup_wallet("wallet_service_export_import_wallet_1_item_for_moderate_method");
}
#[test]
fn wallet_service_export_import_wallet_1_item_for_export_interactive_import_as_raw() {
test::cleanup_wallet("wallet_service_export_import_wallet_1_item_for_export_interactive_import_as_raw");
let export_config = _export_config_raw("wallet_service_export_import_wallet_1_item_for_export_interactive_import_as_raw");
{
let wallet_service = WalletService::new();
let config: &Config = &_config("wallet_service_export_import_wallet_1_item_for_export_interactive_import_as_raw");
wallet_service.create_wallet(config, &ARGON_INT_CREDENTIAL, (&INTERACTIVE_KDD, &INTERACTIVE_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(config, &ARGON_INT_CREDENTIAL).unwrap();
wallet_service.add_record(wallet_handle, "type", "key1", "value1", &HashMap::new()).unwrap();
wallet_service.get_record(wallet_handle, "type", "key1", "{}").unwrap();
let (kdd, master_key) = _export_key_interactive("wallet_service_export_import_wallet_1_item_for_export_interactive_import_as_raw");
let export_path = remove_exported_wallet(&export_config);
wallet_service.export_wallet(wallet_handle, &export_config, 0, (&kdd, &master_key)).unwrap();
assert!(export_path.exists());
wallet_service.close_wallet(wallet_handle).unwrap();
wallet_service.delete_wallet(config, &ARGON_INT_CREDENTIAL).unwrap();
wallet_service.import_wallet(config, &ARGON_MOD_CREDENTIAL, &_export_config_moderate("wallet_service_export_import_wallet_1_item_for_export_interactive_import_as_raw")).unwrap();
let wallet_handle = wallet_service.open_wallet(config, &ARGON_MOD_CREDENTIAL).unwrap();
wallet_service.get_record(wallet_handle, "type", "key1", "{}").unwrap();
}
let _export_path = remove_exported_wallet(&export_config);
test::cleanup_wallet("wallet_service_export_import_wallet_1_item_for_export_interactive_import_as_raw");
}
#[test]
fn wallet_service_export_import_wallet_1_item_for_export_raw_import_as_interactive() {
test::cleanup_wallet("wallet_service_export_import_wallet_1_item_for_export_raw_import_as_interactive");
let export_config = _export_config_interactive("wallet_service_export_import_wallet_1_item_for_export_raw_import_as_interactive");
{
let wallet_service = WalletService::new();
let config: &Config = &_config("wallet_service_export_import_wallet_1_item_for_export_raw_import_as_interactive");
wallet_service.create_wallet(config, &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(config, &RAW_CREDENTIAL).unwrap();
wallet_service.add_record(wallet_handle, "type", "key1", "value1", &HashMap::new()).unwrap();
wallet_service.get_record(wallet_handle, "type", "key1", "{}").unwrap();
let (kdd, master_key) = _export_key_interactive("wallet_service_export_import_wallet_1_item_for_export_raw_import_as_interactive");
let export_path = remove_exported_wallet(&export_config);
wallet_service.export_wallet(wallet_handle, &export_config, 0, (&kdd, &master_key)).unwrap();
assert!(export_path.exists());
wallet_service.close_wallet(wallet_handle).unwrap();
wallet_service.delete_wallet(config, &RAW_CREDENTIAL).unwrap();
wallet_service.import_wallet(config, &ARGON_INT_CREDENTIAL, &export_config).unwrap();
let wallet_handle = wallet_service.open_wallet(config, &ARGON_INT_CREDENTIAL).unwrap();
wallet_service.get_record(wallet_handle, "type", "key1", "{}").unwrap();
}
let _export_path = remove_exported_wallet(&export_config);
test::cleanup_wallet("wallet_service_export_import_wallet_1_item_for_export_raw_import_as_interactive");
}
#[test]
fn wallet_service_export_import_wallet_if_empty() {
test::cleanup_wallet("wallet_service_export_import_wallet_if_empty");
let export_config = _export_config_raw("wallet_service_export_import_wallet_if_empty");
{
let wallet_service = WalletService::new();
let config: &Config = &_config("wallet_service_export_import_wallet_if_empty");
wallet_service.create_wallet(config, &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap();
let wallet_handle = wallet_service.open_wallet(config, &RAW_CREDENTIAL).unwrap();
let (kdd, master_key) = _export_key("wallet_service_export_import_wallet_if_empty");
let export_path = remove_exported_wallet(&export_config);
wallet_service.export_wallet(wallet_handle, &export_config, 0, (&kdd, &master_key)).unwrap();
assert!(export_path.exists());
wallet_service.close_wallet(wallet_handle).unwrap();
wallet_service.delete_wallet(config, &RAW_CREDENTIAL).unwrap();
wallet_service.import_wallet(config, &RAW_CREDENTIAL, &export_config).unwrap();
wallet_service.open_wallet(config, &RAW_CREDENTIAL).unwrap();
}
let _export_path = remove_exported_wallet(&export_config);
test::cleanup_wallet("wallet_service_export_import_wallet_if_empty");
}
#[test]
fn wallet_service_export_import_returns_error_if_path_missing() {
_cleanup("wallet_service_export_import_returns_error_if_path_missing");
let wallet_service = WalletService::new();
let config: &Config = &_config("wallet_service_export_import_returns_error_if_path_missing");
let export_config = _export_config_raw("wallet_service_export_import_returns_error_if_path_missing");
let res = wallet_service.import_wallet(config, &RAW_CREDENTIAL, &export_config);
assert_eq!(IndyErrorKind::IOError, res.unwrap_err().kind());
let res = wallet_service.open_wallet(config, &RAW_CREDENTIAL);
assert_match!(Err(_), res);
_cleanup("wallet_service_export_import_returns_error_if_path_missing");
}
fn _fetch_options(type_: bool, value: bool, tags: bool) -> String {
json!({
"retrieveType": type_,
"retrieveValue": value,
"retrieveTags": tags,
}).to_string()
}
fn _config(name: &str) -> Config {
Config {
id: name.to_string(),
storage_type: None,
storage_config: None,
}
}
fn _config_default(name: &str) -> Config {
Config {
id: name.to_string(),
storage_type: Some("default".to_string()),
storage_config: None,
}
}
fn _config_inmem() -> Config {
Config {
id: "w1".to_string(),
storage_type: Some("inmem".to_string()),
storage_config: None,
}
}
fn _config_unknown(name: &str) -> Config {
Config {
id: name.to_string(),
storage_type: Some("unknown".to_string()),
storage_config: None,
}
}
#[allow(non_upper_case_globals)]
lazy_static! {
static ref ARGON_MOD_CREDENTIAL: Credentials = Credentials {
key: "my_key".to_string(),
rekey: None,
storage_credentials: None,
key_derivation_method: KeyDerivationMethod::ARGON2I_MOD,
rekey_derivation_method: KeyDerivationMethod::ARGON2I_MOD,
};
}
#[allow(non_upper_case_globals)]
lazy_static! {
static ref ARGON_INT_CREDENTIAL: Credentials = Credentials {
key: "my_key".to_string(),
rekey: None,
storage_credentials: None,
key_derivation_method: KeyDerivationMethod::ARGON2I_INT,
rekey_derivation_method: KeyDerivationMethod::ARGON2I_INT,
};
}
#[allow(non_upper_case_globals)]
lazy_static! {
static ref RAW_CREDENTIAL: Credentials = Credentials {
key: "6nxtSiXFvBd593Y2DCed2dYvRY1PGK9WMtxCBjLzKgbw".to_string(),
rekey: None,
storage_credentials: None,
key_derivation_method: KeyDerivationMethod::RAW,
rekey_derivation_method: KeyDerivationMethod::RAW,
};
}
#[allow(non_upper_case_globals)]
lazy_static! {
static ref MODERATE_KDD: KeyDerivationData = KeyDerivationData::from_passphrase_with_new_salt("my_key", &KeyDerivationMethod::ARGON2I_MOD);
}
#[allow(non_upper_case_globals)]
lazy_static! {
static ref MODERATE_MASTER_KEY: MasterKey = MODERATE_KDD.calc_master_key().unwrap();
}
#[allow(non_upper_case_globals)]
lazy_static! {
static ref INTERACTIVE_KDD: KeyDerivationData = KeyDerivationData::from_passphrase_with_new_salt("my_key", &KeyDerivationMethod::ARGON2I_INT);
}
#[allow(non_upper_case_globals)]
lazy_static! {
static ref INTERACTIVE_MASTER_KEY: MasterKey = INTERACTIVE_KDD.calc_master_key().unwrap();
}
#[allow(non_upper_case_globals)]
lazy_static! {
static ref RAW_KDD: KeyDerivationData = KeyDerivationData::from_passphrase_with_new_salt("6nxtSiXFvBd593Y2DCed2dYvRY1PGK9WMtxCBjLzKgbw", &KeyDerivationMethod::RAW);
}
#[allow(non_upper_case_globals)]
lazy_static! {
static ref RAW_MASTER_KEY: MasterKey = RAW_KDD.calc_master_key().unwrap();
}
fn _credentials_invalid_raw() -> Credentials {
Credentials {
key: "key".to_string(),
rekey: None,
storage_credentials: None,
key_derivation_method: KeyDerivationMethod::RAW,
rekey_derivation_method: KeyDerivationMethod::RAW,
}
}
fn _rekey_credentials_moderate() -> Credentials {
Credentials {
key: "6nxtSiXFvBd593Y2DCed2dYvRY1PGK9WMtxCBjLzKgbw".to_string(),
rekey: Some("my_new_key".to_string()),
storage_credentials: None,
key_derivation_method: KeyDerivationMethod::RAW,
rekey_derivation_method: KeyDerivationMethod::ARGON2I_MOD,
}
}
fn _rekey_credentials_interactive() -> Credentials {
Credentials {
key: "6nxtSiXFvBd593Y2DCed2dYvRY1PGK9WMtxCBjLzKgbw".to_string(),
rekey: Some("my_new_key".to_string()),
storage_credentials: None,
key_derivation_method: KeyDerivationMethod::RAW,
rekey_derivation_method: KeyDerivationMethod::ARGON2I_INT,
}
}
fn _rekey_credentials_raw() -> Credentials {
Credentials {
key: "6nxtSiXFvBd593Y2DCed2dYvRY1PGK9WMtxCBjLzKgbw".to_string(),
rekey: Some("7nxtSiXFvBd593Y2DCed2dYvRY1PGK9WMtxCBjLzKgbw".to_string()),
storage_credentials: None,
key_derivation_method: KeyDerivationMethod::RAW,
rekey_derivation_method: KeyDerivationMethod::RAW,
}
}
fn _credentials_for_new_key_moderate() -> Credentials {
Credentials {
key: "my_new_key".to_string(),
rekey: None,
storage_credentials: None,
key_derivation_method: KeyDerivationMethod::ARGON2I_MOD,
rekey_derivation_method: KeyDerivationMethod::ARGON2I_MOD,
}
}
fn _credentials_for_new_key_interactive() -> Credentials {
Credentials {
key: "my_new_key".to_string(),
rekey: None,
storage_credentials: None,
key_derivation_method: KeyDerivationMethod::ARGON2I_INT,
rekey_derivation_method: KeyDerivationMethod::ARGON2I_INT,
}
}
fn _credentials_for_new_key_raw() -> Credentials {
Credentials {
key: "7nxtSiXFvBd593Y2DCed2dYvRY1PGK9WMtxCBjLzKgbw".to_string(),
rekey: None,
storage_credentials: None,
key_derivation_method: KeyDerivationMethod::RAW,
rekey_derivation_method: KeyDerivationMethod::RAW,
}
}
fn _export_file_path(name: &str) -> PathBuf {
let mut path = environment::tmp_path();
path.push(name);
path
}
fn _export_config_moderate(name: &str) -> ExportConfig {
ExportConfig {
key: "export_key".to_string(),
path: _export_file_path(name).to_str().unwrap().to_string(),
key_derivation_method: KeyDerivationMethod::ARGON2I_MOD,
}
}
fn _calc_key(export_config: &ExportConfig) -> (KeyDerivationData, MasterKey) {
let kdd = KeyDerivationData::from_passphrase_with_new_salt(&export_config.key, &export_config.key_derivation_method);
let master_key = kdd.calc_master_key().unwrap();
(kdd, master_key)
}
fn _export_key(name: &str) -> (KeyDerivationData, MasterKey) {
_calc_key(&_export_config_raw(name))
}
fn _export_config_interactive(name: &str) -> ExportConfig {
ExportConfig {
key: "export_key".to_string(),
path: _export_file_path(name).to_str().unwrap().to_string(),
key_derivation_method: KeyDerivationMethod::ARGON2I_INT,
}
}
fn _export_key_interactive(name: &str) -> (KeyDerivationData, MasterKey) {
_calc_key(&_export_config_interactive(name))
}
fn _export_config_raw(name: &str) -> ExportConfig {
ExportConfig {
key: "6nxtSiXFvBd593Y2DCed2dYvRY1PGK9WMtxCBjLzKgbw".to_string(),
path: _export_file_path(name).to_str().unwrap().to_string(),
key_derivation_method: KeyDerivationMethod::RAW,
}
}
fn _export_key_raw(name: &str) -> (KeyDerivationData, MasterKey) {
_calc_key(&_export_config_raw(name))
}
fn _cleanup(name: &str) {
test::cleanup_storage(name);
InmemWallet::cleanup();
}
fn _register_inmem_wallet(wallet_service: &WalletService) {
wallet_service
.register_wallet_storage(
"inmem",
InmemWallet::create,
InmemWallet::open,
InmemWallet::close,
InmemWallet::delete,
InmemWallet::add_record,
InmemWallet::update_record_value,
InmemWallet::update_record_tags,
InmemWallet::add_record_tags,
InmemWallet::delete_record_tags,
InmemWallet::delete_record,
InmemWallet::get_record,
InmemWallet::get_record_id,
InmemWallet::get_record_type,
InmemWallet::get_record_value,
InmemWallet::get_record_tags,
InmemWallet::free_record,
InmemWallet::get_storage_metadata,
InmemWallet::set_storage_metadata,
InmemWallet::free_storage_metadata,
InmemWallet::search_records,
InmemWallet::search_all_records,
InmemWallet::get_search_total_count,
InmemWallet::fetch_search_next_record,
InmemWallet::free_search,
)
.unwrap();
}
fn _custom_path(name: &str) -> String {
let mut path = environment::tmp_path();
path.push(name);
path.to_str().unwrap().to_owned()
}
#[test]
fn short_type_name_works() {
assert_eq!("WalletRecord", short_type_name::<WalletRecord>());
}
}<|fim▁end|> | assert_eq!("value1", record.get_value().unwrap()); |
<|file_name|>DataPairMgr.py<|end_file_name|><|fim▁begin|>'''
read the input data, parse to int list;
create mappings of (user,item) -> review int list
@author: roseck
@date Mar 15, 2017
'''
from __builtin__ import dict
import gzip
class DataPairMgr():
def _int_list(self,int_str):
'''utility fn for converting an int string to a list of int
'''
return [int(w) for w in int_str.split()]
def __init__(self, filename):
'''
filename: inits the UBRR data from the input file
'''
ub_map = dict()
ub_ratings = dict()
cnt = 0
#read the file<|fim▁hole|> if filename.endswith('.gz'):
f = gzip.open(filename, 'r')
else:
f = open(filename, 'r')
for line in f:
vals = line.split("\t")
if len(vals) == 0:
continue
u = vals[0]
b = vals[1]
r = float(vals[2])
d = vals[3].strip()
ub_map[(u,b)] = self._int_list(d)
ub_ratings[(u,b)] = r
cnt += 1
self.user_item_map = ub_map
self.user_item_rating = ub_ratings
f.close()
print 'Data Pair Manager Initialized with ', cnt, ' reviews'
def get_int_review(self, user, item):
if (user,item) in self.user_item_map:
return self.user_item_map[(user,item)]
else:
return [0]
def get_int_review_rating(self, user, item):
if (user,item) in self.user_item_map:
return self.user_item_map[(user,item)], self.user_item_rating[(user,item)]
else:
return [0], 3.0 #average rating<|fim▁end|> | |
<|file_name|>test_saferef.py<|end_file_name|><|fim▁begin|>import unittest
from django.dispatch.saferef import safeRef
from django.utils.six.moves import xrange
class Test1(object):
def x(self):
pass
def test2(obj):
pass
class Test2(object):
def __call__(self, obj):
pass
class SaferefTests(unittest.TestCase):
def setUp(self):
ts = []
ss = []
for x in xrange(5000):
t = Test1()
ts.append(t)
s = safeRef(t.x, self._closure)
ss.append(s)
ts.append(test2)
ss.append(safeRef(test2, self._closure))
for x in xrange(30):
t = Test2()
ts.append(t)
s = safeRef(t, self._closure)
ss.append(s)
self.ts = ts
self.ss = ss
self.closureCount = 0
def tearDown(self):
del self.ts
del self.ss
def testIn(self):<|fim▁hole|> """Test the "in" operator for safe references (cmp)"""
for t in self.ts[:50]:
self.assertTrue(safeRef(t.x) in self.ss)
def testValid(self):
"""Test that the references are valid (return instance methods)"""
for s in self.ss:
self.assertTrue(s())
def testShortCircuit(self):
"""Test that creation short-circuits to reuse existing references"""
sd = {}
for s in self.ss:
sd[s] = 1
for t in self.ts:
if hasattr(t, 'x'):
self.assertTrue(safeRef(t.x) in sd)
else:
self.assertTrue(safeRef(t) in sd)
def testRepresentation(self):
"""Test that the reference object's representation works
XXX Doesn't currently check the results, just that no error
is raised
"""
repr(self.ss[-1])
def _closure(self, ref):
"""Dumb utility mechanism to increment deletion counter"""
self.closureCount += 1<|fim▁end|> | |
<|file_name|>problem11.rs<|end_file_name|><|fim▁begin|>// In the 20×20 grid below, four numbers along a diagonal line have been marked in red.
// The product of these numbers is 26 × 63 × 78 × 14 = 1788696.
//
// What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid?
fn main() {
let range = 4;
let val = [[08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91, 08],
[49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 04, 56, 62, 00],
[81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 03, 49, 13, 36, 65],
[52, 70, 95, 23, 04, 60, 11, 42, 69, 24, 68, 56, 01, 32, 56, 71, 37, 02, 36, 91],
[22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80],
[24, 47, 32, 60, 99, 03, 45, 02, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50],
[32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70],
[67, 26, 20, 68, 02, 62, 12, 20, 95, 63, 94, 39, 63, 08, 40, 91, 66, 49, 94, 21],
[24, 55, 58, 05, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72],
[21, 36, 23, 09, 75, 00, 76, 44, 20, 45, 35, 14, 00, 61, 33, 97, 34, 31, 33, 95],
[78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 03, 80, 04, 62, 16, 14, 09, 53, 56, 92],
[16, 39, 05, 42, 96, 35, 31, 47, 55, 58, 88, 24, 00, 17, 54, 24, 36, 29, 85, 57],
[86, 56, 00, 48, 35, 71, 89, 07, 05, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58],
[19, 80, 81, 68, 05, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 04, 89, 55, 40],
[04, 52, 08, 83, 97, 35, 99, 16, 07, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66],
[88, 36, 68, 87, 57, 62, 20, 72, 03, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69],
[04, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 08, 46, 29, 32, 40, 62, 76, 36],
[20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 04, 36, 16],
[20, 73, 35, 29, 78, 31, 90, 01, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 05, 54],
[01, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 01, 89, 19, 67, 48]];
println!("Solution: {}", solve(&val, &range));
}
fn solve(vals: &[[i64; 20]; 20], range: &usize) -> (i64){
let mut max: i64 = 0;
for col in 0..vals.len() {
for row in 0..vals[col].len() {
check_vertical(&vals, row, col, *range, &mut max);
check_horizontal(&vals, row, col, *range, &mut max);
check_diagonal_left(&vals, row, col, *range, &mut max);
check_diagonal_right(&vals, row, col, *range, &mut max);
}
}
return max;
}
fn check_vertical(vals: &[[i64; 20]; 20], row: usize, col: usize, range: usize, curr_max: &mut i64) {
if row <= vals.len() - range {
let mut product: i64 = 1;
for i in 0..range {
product *= vals[col][row + i];
}
if product > *curr_max {
*curr_max = product;
}
}
}
fn check_horizontal(vals: &[[i64; 20]; 20], row: usize, col: usize, range: usize, curr_max: &mut i64) {
if col <= vals[row].len() - range {
let mut product: i64 = 1;
for i in 0..range {
product *= vals[col + i][row];
}
if product > *curr_max {
*curr_max = product;
}
}
}
fn check_diagonal_left(vals: &[[i64; 20]; 20], row: usize, col: usize, range: usize, curr_max: &mut i64) {<|fim▁hole|> }
if product > *curr_max {
*curr_max = product;
}
}
}
fn check_diagonal_right(vals: &[[i64; 20]; 20], row: usize, col: usize, range: usize, curr_max: &mut i64) {
if row <= vals[col].len() - range && col <= vals.len() - range {
let mut product: i64 = 1;
for i in 0..range {
product *= vals[col + i][row + i];
}
if product > *curr_max {
*curr_max = product;
}
}
}<|fim▁end|> | if col <= vals.len() - range && row >= range {
let mut product: i64 = 1;
for i in 0..range {
product *= vals[col + i][row - i]; |
<|file_name|>installer.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
import sys, os
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../../master'))
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../../master/wkpf'))
print os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../../master/wkpf')
from wkpf.pynvc import *
from wkpf.wkpfcomm import *
comm = getComm()
print "node ids", comm.getNodeIds()
comm.setFeature(2, WKPF_FEATURE_LIGHT_SENSOR, 0)
comm.setFeature(2, WKPF_FEATURE_LIGHT_ACTUATOR, 1)
comm.setFeature(2, WKPF_FEATURE_NUMERIC_CONTROLLER, 0)
comm.setFeature(2, WKPF_FEATURE_NATIVE_THRESHOLD, 0)
comm.setLocation(2, "WuKong")
comm.setFeature(7, WKPF_FEATURE_LIGHT_SENSOR, 1)
comm.setFeature(7, WKPF_FEATURE_LIGHT_ACTUATOR, 1)
comm.setFeature(7, WKPF_FEATURE_NUMERIC_CONTROLLER, 0)
comm.setFeature(7, WKPF_FEATURE_NATIVE_THRESHOLD, 0)
comm.setLocation(7, "WuKong")
comm.setFeature(4, WKPF_FEATURE_LIGHT_SENSOR, 1)
comm.setFeature(4, WKPF_FEATURE_LIGHT_ACTUATOR, 0)
comm.setFeature(4, WKPF_FEATURE_NUMERIC_CONTROLLER, 1)
comm.setFeature(4, WKPF_FEATURE_NATIVE_THRESHOLD, 1)
comm.setLocation(4, "WuKong")
comm.setFeature(5, WKPF_FEATURE_LIGHT_SENSOR, 0)
comm.setFeature(5, WKPF_FEATURE_LIGHT_ACTUATOR, 1)
comm.setFeature(5, WKPF_FEATURE_NUMERIC_CONTROLLER, 0)
comm.setFeature(5, WKPF_FEATURE_NATIVE_THRESHOLD, 0)
comm.setLocation(5, "WuKong")
comm.setFeature(6, WKPF_FEATURE_LIGHT_SENSOR, 0)
comm.setFeature(6, WKPF_FEATURE_LIGHT_ACTUATOR, 1)
comm.setFeature(6, WKPF_FEATURE_NUMERIC_CONTROLLER, 0)
comm.setFeature(6, WKPF_FEATURE_NATIVE_THRESHOLD, 0)
comm.setLocation(6, "WuKong")
comm.setFeature(13, WKPF_FEATURE_LIGHT_SENSOR, 0)
comm.setFeature(13, WKPF_FEATURE_LIGHT_ACTUATOR, 1)
comm.setFeature(13, WKPF_FEATURE_NUMERIC_CONTROLLER, 0)
comm.setFeature(13, WKPF_FEATURE_NATIVE_THRESHOLD, 0)
comm.setLocation(13, "WuKong")
comm.setFeature(14, WKPF_FEATURE_LIGHT_SENSOR, 0)
comm.setFeature(14, WKPF_FEATURE_LIGHT_ACTUATOR, 1)
comm.setFeature(14, WKPF_FEATURE_NUMERIC_CONTROLLER, 0)
comm.setFeature(14, WKPF_FEATURE_NATIVE_THRESHOLD, 0)
comm.setLocation(14, "WuKong")
comm.setFeature(15, WKPF_FEATURE_LIGHT_SENSOR, 0)
comm.setFeature(15, WKPF_FEATURE_LIGHT_ACTUATOR, 1)
comm.setFeature(15, WKPF_FEATURE_NUMERIC_CONTROLLER, 0)<|fim▁hole|>comm.setFeature(10, WKPF_FEATURE_LIGHT_SENSOR, 0)
comm.setFeature(10, WKPF_FEATURE_LIGHT_ACTUATOR, 1)
comm.setFeature(10, WKPF_FEATURE_NUMERIC_CONTROLLER, 0)
comm.setFeature(10, WKPF_FEATURE_NATIVE_THRESHOLD, 0)
comm.setLocation(10, "WuKong")
comm.setFeature(12, WKPF_FEATURE_LIGHT_SENSOR, 0)
comm.setFeature(12, WKPF_FEATURE_LIGHT_ACTUATOR, 1)
comm.setFeature(12, WKPF_FEATURE_NUMERIC_CONTROLLER, 0)
comm.setFeature(12, WKPF_FEATURE_NATIVE_THRESHOLD, 0)
comm.setLocation(12, "WuKong")<|fim▁end|> | comm.setFeature(15, WKPF_FEATURE_NATIVE_THRESHOLD, 0)
comm.setLocation(15, "WuKong")
|
<|file_name|>bigquery.py<|end_file_name|><|fim▁begin|>from datetime import timedelta, datetime
from airflow import DAG
from airflow.contrib.operators.bigquery_operator import BigQueryOperator
from airflow.contrib.operators.bigquery_to_gcs import BigQueryToCloudStorageOperator
from airflow.contrib.operators.gcs_to_bq import GoogleCloudStorageToBigQueryOperator
from dags.support import schemas
seven_days_ago = datetime.combine(datetime.today() - timedelta(7),
datetime.min.time())
default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': seven_days_ago,
'email': ['[email protected]'],
'email_on_failure': False,
'email_on_retry': False,
'retries': 1,
'retry_delay': timedelta(minutes=30),
}
with DAG('v1_8_bigquery', schedule_interval=timedelta(days=1),
default_args=default_args) as dag:
bq_extract_one_day = BigQueryOperator(
task_id='bq_extract_one_day',
bql='gcp_smoke/gsob_extract_day.sql',
destination_dataset_table=
'{{var.value.gcq_dataset}}.gsod_partition{{ ds_nodash }}',
write_disposition='WRITE_TRUNCATE',
bigquery_conn_id='gcp_smoke',
use_legacy_sql=False
)
bq2gcp_avro = BigQueryToCloudStorageOperator(
task_id='bq2gcp_avro',
source_project_dataset_table='{{var.value.gcq_dataset}}.gsod_partition{{ ds_nodash }}',
destination_cloud_storage_uris=[
'gs://{{var.value.gcs_bucket}}/{{var.value.gcs_root}}/gcp_smoke_bq/bq_to_gcp_avro/{{ ds_nodash }}/part-*.avro'
],
export_format='AVRO',
bigquery_conn_id='gcp_smoke',
)
bq2gcp_override = BigQueryToCloudStorageOperator(<|fim▁hole|> task_id='bq2gcp_override',
source_project_dataset_table='{{var.value.gcq_dataset}}.gsod_partition{{ ds_nodash }}',
destination_cloud_storage_uris=[
'gs://{{var.value.gcs_bucket}}/{{var.value.gcs_root}}/gcp_smoke_bq/bq_to_gcp_avro/99999999/part-*.avro'
],
export_format='AVRO',
bigquery_conn_id='gcp_smoke',
)
gcs2bq_avro_auto_schema = GoogleCloudStorageToBigQueryOperator(
task_id='gcs2bq_avro_auto_schema',
bucket='{{var.value.gcs_bucket}}',
source_objects=[
'{{var.value.gcs_root}}/gcp_smoke_bq/bq_to_gcp_avro/{{ ds_nodash }}/part-*'
],
destination_project_dataset_table='{{var.value.gcq_tempset}}.avro_auto_schema{{ ds_nodash }}',
source_format='AVRO',
create_disposition='CREATE_IF_NEEDED',
write_disposition='WRITE_TRUNCATE',
google_cloud_storage_conn_id='gcp_smoke',
bigquery_conn_id='gcp_smoke'
)
gcs2bq_avro_with_schema = GoogleCloudStorageToBigQueryOperator(
task_id='gcs2bq_avro_with_schema',
bucket='{{var.value.gcs_bucket}}',
source_objects=[
'{{var.value.gcs_root}}/gcp_smoke_bq/bq_to_gcp_avro/{{ ds_nodash }}/part-*'
],
destination_project_dataset_table='{{var.value.gcq_tempset}}.avro_with_schema{{ ds_nodash }}',
source_format='AVRO',
schema_fields=schemas.gsob(),
create_disposition='CREATE_IF_NEEDED',
write_disposition='WRITE_TRUNCATE',
google_cloud_storage_conn_id='gcp_smoke',
bigquery_conn_id='gcp_smoke'
)
bq_extract_one_day >> bq2gcp_avro >> bq2gcp_override
bq2gcp_avro >> gcs2bq_avro_auto_schema
bq2gcp_avro >> gcs2bq_avro_with_schema<|fim▁end|> | |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|>__all__ = ['pwnedapi', 'utils']
from .pwnedapi import HaveIBeenPwnedApi<|fim▁end|> | |
<|file_name|>versions.js<|end_file_name|><|fim▁begin|>const React = require('react');
const CompLibrary = require('../../core/CompLibrary');
const Container = CompLibrary.Container;
const GridBlock = CompLibrary.GridBlock;
const CWD = process.cwd();
const translate = require('../../server/translate.js').translate;
const siteConfig = require(`${CWD}/siteConfig.js`);
// versions post docusaurus
const versions = require(`${CWD}/versions.json`);
// versions pre docusaurus
const oldversions = require(`${CWD}/oldversions.json`);
function Versions(props) {
const latestStableVersion = versions[0];
const repoUrl = `https://github.com/${siteConfig.organizationName}/${
siteConfig.projectName
}`;
return (
<div className="pageContainer">
<Container className="mainContainer documentContainer postContainer">
<div className="post">
<header className="postHeader">
<h1>{siteConfig.title} <translate>Versions</translate></h1>
</header>
<h3 id="latest"><translate>Latest Stable Version</translate></h3>
<p><translate>Latest stable release of Apache Pulsar.</translate></p>
<table className="versions">
<tbody>
<tr>
<th>{latestStableVersion}</th>
<td>
<a
href={`${siteConfig.baseUrl}docs/${props.language}/standalone`}>
<translate>
Documentation
</translate>
</a>
</td>
<td>
<a href={`${siteConfig.baseUrl}release-notes#${latestStableVersion}`}>
<translate>
Release Notes
</translate>
</a>
</td>
</tr>
</tbody>
</table>
<h3 id="rc"><translate>Latest Version</translate></h3>
<translate>
Here you can find the latest documentation and unreleased code.
</translate>
<table className="versions">
<tbody>
<tr>
<th>master</th>
<td>
<a
href={`${siteConfig.baseUrl}docs/${props.language}/next/standalone`}>
<translate>Documentation</translate>
</a>
</td>
<td>
<a href={repoUrl}><translate>Source Code</translate></a>
</td>
</tr>
</tbody>
</table>
<h3 id="archive"><translate>Past Versions</translate></h3>
<p>
<translate>
Here you can find documentation for previous versions of Apache Pulsar.
</translate>
</p>
<table className="versions">
<tbody>
{versions.map(
version =>
version !== latestStableVersion && (
<tr key={version}>
<th>{version}</th>
<td>
<a
href={`${siteConfig.baseUrl}docs/${props.language}/${version}/standalone`}>
<translate>Documentation</translate>
</a>
</td>
<td>
<a href={`${siteConfig.baseUrl}release-notes#${version}`}>
<translate>Release Notes</translate>
</a>
</td>
</tr>
)
)}
{oldversions.map(
version =>
version !== latestStableVersion && (
<tr key={version}>
<th>{version}</th>
<td>
<a
href={`${siteConfig.baseUrl}docs/v${version}/getting-started/LocalCluster/`}>
<translate>Documentation</translate>
</a>
</td>
<td>
<a href={`${siteConfig.baseUrl}release-notes#${version}`}>
<translate>Release Notes</translate>
</a>
</td>
</tr>
)
)}
</tbody>
</table>
<p>
<translate>
You can find past versions of this project on{' '}
<a href={`${repoUrl}/releases`}>GitHub</a> or download from{' '}
<a href={`${siteConfig.baseUrl}download`}>Apache</a>.
</translate>
</p>
</div>
</Container><|fim▁hole|>
Versions.title = 'Versions';
module.exports = Versions;<|fim▁end|> | </div>
);
} |
<|file_name|>BazelVariableSubstitutorTest.java<|end_file_name|><|fim▁begin|>package com.blackducksoftware.integration.hub.detect.tool.bazel;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
public class BazelVariableSubstitutorTest {
@Test
public void testTargetOnly() {
BazelVariableSubstitutor substitutor = new BazelVariableSubstitutor("//foo:foolib");
final List<String> origArgs = new ArrayList<>();
origArgs.add("query");
origArgs.add("filter(\"@.*:jar\", deps(${detect.bazel.target}))");
final List<String> adjustedArgs = substitutor.substitute(origArgs);
assertEquals(2, adjustedArgs.size());
assertEquals("query", adjustedArgs.get(0));
assertEquals("filter(\"@.*:jar\", deps(//foo:foolib))", adjustedArgs.get(1));<|fim▁hole|>
@Test
public void testBoth() {
BazelVariableSubstitutor substitutor = new BazelVariableSubstitutor("//foo:foolib", "//external:org_apache_commons_commons_io");
final List<String> origArgs = new ArrayList<>();
origArgs.add("query");
origArgs.add("filter(\"@.*:jar\", deps(${detect.bazel.target}))");
origArgs.add("kind(maven_jar, ${detect.bazel.target.dependency})");
final List<String> adjustedArgs = substitutor.substitute(origArgs);
assertEquals(3, adjustedArgs.size());
assertEquals("query", adjustedArgs.get(0));
assertEquals("filter(\"@.*:jar\", deps(//foo:foolib))", adjustedArgs.get(1));
assertEquals("kind(maven_jar, //external:org_apache_commons_commons_io)", adjustedArgs.get(2));
}
}<|fim▁end|> | } |
<|file_name|>aws_sqs.go<|end_file_name|><|fim▁begin|>package output
import (
"github.com/Jeffail/benthos/v3/internal/batch/policy"
"github.com/Jeffail/benthos/v3/internal/component/metrics"
"github.com/Jeffail/benthos/v3/internal/component/output"
"github.com/Jeffail/benthos/v3/internal/docs"
"github.com/Jeffail/benthos/v3/internal/impl/aws/session"
"github.com/Jeffail/benthos/v3/internal/interop"
"github.com/Jeffail/benthos/v3/internal/log"
"github.com/Jeffail/benthos/v3/internal/metadata"
"github.com/Jeffail/benthos/v3/internal/old/output/writer"
"github.com/Jeffail/benthos/v3/internal/old/util/retries"
)
//------------------------------------------------------------------------------
func init() {
Constructors[TypeAWSSQS] = TypeSpec{
constructor: fromSimpleConstructor(func(conf Config, mgr interop.Manager, log log.Modular, stats metrics.Type) (output.Streamed, error) {
return newAmazonSQS(TypeAWSSQS, conf.AWSSQS, mgr, log, stats)
}),
Version: "3.36.0",
Summary: `
Sends messages to an SQS queue.`,
Description: `
Metadata values are sent along with the payload as attributes with the data type
String. If the number of metadata values in a message exceeds the message
attribute limit (10) then the top ten keys ordered alphabetically will be
selected.
The fields ` + "`message_group_id` and `message_deduplication_id`" + ` can be<|fim▁hole|>
### Credentials
By default Benthos will use a shared credentials file when connecting to AWS
services. It's also possible to set them explicitly at the component level,
allowing you to transfer data across accounts. You can find out more
[in this document](/docs/guides/cloud/aws).`,
Async: true,
Batches: true,
FieldSpecs: docs.FieldSpecs{
docs.FieldCommon("url", "The URL of the target SQS queue."),
docs.FieldCommon("message_group_id", "An optional group ID to set for messages.").IsInterpolated(),
docs.FieldCommon("message_deduplication_id", "An optional deduplication ID to set for messages.").IsInterpolated(),
docs.FieldCommon("max_in_flight", "The maximum number of messages to have in flight at a given time. Increase this to improve throughput."),
docs.FieldCommon("metadata", "Specify criteria for which metadata values are sent as headers.").WithChildren(metadata.ExcludeFilterFields()...),
policy.FieldSpec(),
}.Merge(session.FieldSpecs()).Merge(retries.FieldSpecs()),
Categories: []Category{
CategoryServices,
CategoryAWS,
},
}
}
//------------------------------------------------------------------------------
func newAmazonSQS(name string, conf writer.AmazonSQSConfig, mgr interop.Manager, log log.Modular, stats metrics.Type) (output.Streamed, error) {
s, err := writer.NewAmazonSQSV2(conf, mgr, log, stats)
if err != nil {
return nil, err
}
w, err := NewAsyncWriter(name, conf.MaxInFlight, s, log, stats)
if err != nil {
return w, err
}
return NewBatcherFromConfig(conf.Batching, w, mgr, log, stats)
}
//------------------------------------------------------------------------------<|fim▁end|> | set dynamically using
[function interpolations](/docs/configuration/interpolation#bloblang-queries), which are
resolved individually for each message of a batch. |
<|file_name|>ordering.spec.ts<|end_file_name|><|fim▁begin|>/// <reference path="../typings/main.d.ts" />
/// <reference path="../../../src/script/sums/ordering.ts" />
<|fim▁hole|> describe("to text", function() {
it("converts values to human readable text", function() {
expect(Sums.orderingToText(Sums.Ordering.AscendingOperand1)).toBe("ascending");
expect(Sums.orderingToText(Sums.Ordering.AscendingOperand2)).toBe("ascending");
expect(Sums.orderingToText(Sums.Ordering.DescendingOperand1)).toBe("descending");
expect(Sums.orderingToText(Sums.Ordering.DescendingOperand2)).toBe("descending");
expect(Sums.orderingToText(Sums.Ordering.Random)).toBe("random");
});
});
describe("sorting by operand 1", function() {
it("orders by operand 1 ascending", function() {
const sums: Sums.Sum[] = [
new Sums.Sum(Sums.Operator.Add, new Sums.Operand(2), new Sums.Operand(0)),
new Sums.Sum(Sums.Operator.Add, new Sums.Operand(0), new Sums.Operand(1)),
new Sums.Sum(Sums.Operator.Add, new Sums.Operand(1), new Sums.Operand(2)),
];
Sums.orderSums(sums, Sums.Ordering.AscendingOperand1);
expect(sums[0].operand1.toString()).toBe("0");
expect(sums[1].operand1.toString()).toBe("1");
expect(sums[2].operand1.toString()).toBe("2");
});
it("falls back to operand 2 when sorting by operand 1 ascending", function() {
const sums: Sums.Sum[] = [
new Sums.Sum(Sums.Operator.Add, new Sums.Operand(1), new Sums.Operand(2)),
new Sums.Sum(Sums.Operator.Add, new Sums.Operand(1), new Sums.Operand(0)),
new Sums.Sum(Sums.Operator.Add, new Sums.Operand(1), new Sums.Operand(1)),
];
Sums.orderSums(sums, Sums.Ordering.AscendingOperand1);
expect(sums[0].operand2.toString()).toBe("0");
expect(sums[1].operand2.toString()).toBe("1");
expect(sums[2].operand2.toString()).toBe("2");
});
it("orders by operand 1 descending", function() {
const sums: Sums.Sum[] = [
new Sums.Sum(Sums.Operator.Add, new Sums.Operand(2), new Sums.Operand(0)),
new Sums.Sum(Sums.Operator.Add, new Sums.Operand(0), new Sums.Operand(1)),
new Sums.Sum(Sums.Operator.Add, new Sums.Operand(1), new Sums.Operand(2)),
];
Sums.orderSums(sums, Sums.Ordering.DescendingOperand1);
expect(sums[0].operand1.toString()).toBe("2");
expect(sums[1].operand1.toString()).toBe("1");
expect(sums[2].operand1.toString()).toBe("0");
});
it("falls back to operand 2 when sorting by operand 1 descending", function() {
const sums: Sums.Sum[] = [
new Sums.Sum(Sums.Operator.Add, new Sums.Operand(1), new Sums.Operand(2)),
new Sums.Sum(Sums.Operator.Add, new Sums.Operand(1), new Sums.Operand(0)),
new Sums.Sum(Sums.Operator.Add, new Sums.Operand(1), new Sums.Operand(1)),
];
Sums.orderSums(sums, Sums.Ordering.DescendingOperand1);
expect(sums[0].operand2.toString()).toBe("2");
expect(sums[1].operand2.toString()).toBe("1");
expect(sums[2].operand2.toString()).toBe("0");
});
});
describe("sorting by operand 2", function() {
it("orders by operand 2 ascending", function() {
const sums: Sums.Sum[] = [
new Sums.Sum(Sums.Operator.Add, new Sums.Operand(0), new Sums.Operand(2)),
new Sums.Sum(Sums.Operator.Add, new Sums.Operand(1), new Sums.Operand(0)),
new Sums.Sum(Sums.Operator.Add, new Sums.Operand(2), new Sums.Operand(1)),
];
Sums.orderSums(sums, Sums.Ordering.AscendingOperand2);
expect(sums[0].operand2.toString()).toBe("0");
expect(sums[1].operand2.toString()).toBe("1");
expect(sums[2].operand2.toString()).toBe("2");
});
it("falls back to operand 2 when sorting by operand 1 ascending", function() {
const sums: Sums.Sum[] = [
new Sums.Sum(Sums.Operator.Add, new Sums.Operand(2), new Sums.Operand(1)),
new Sums.Sum(Sums.Operator.Add, new Sums.Operand(0), new Sums.Operand(1)),
new Sums.Sum(Sums.Operator.Add, new Sums.Operand(1), new Sums.Operand(1)),
];
Sums.orderSums(sums, Sums.Ordering.AscendingOperand2);
expect(sums[0].operand1.toString()).toBe("0");
expect(sums[1].operand1.toString()).toBe("1");
expect(sums[2].operand1.toString()).toBe("2");
});
it("orders by operand 2 descending", function() {
const sums: Sums.Sum[] = [
new Sums.Sum(Sums.Operator.Add, new Sums.Operand(0), new Sums.Operand(2)),
new Sums.Sum(Sums.Operator.Add, new Sums.Operand(1), new Sums.Operand(0)),
new Sums.Sum(Sums.Operator.Add, new Sums.Operand(2), new Sums.Operand(1)),
];
Sums.orderSums(sums, Sums.Ordering.DescendingOperand2);
expect(sums[0].operand2.toString()).toBe("2");
expect(sums[1].operand2.toString()).toBe("1");
expect(sums[2].operand2.toString()).toBe("0");
});
it("falls back to operand 1 when sorting by operand 2 descending", function() {
const sums: Sums.Sum[] = [
new Sums.Sum(Sums.Operator.Add, new Sums.Operand(2), new Sums.Operand(1)),
new Sums.Sum(Sums.Operator.Add, new Sums.Operand(0), new Sums.Operand(1)),
new Sums.Sum(Sums.Operator.Add, new Sums.Operand(1), new Sums.Operand(1)),
];
Sums.orderSums(sums, Sums.Ordering.DescendingOperand2);
expect(sums[0].operand1.toString()).toBe("2");
expect(sums[1].operand1.toString()).toBe("1");
expect(sums[2].operand1.toString()).toBe("0");
});
});
it("shuffles the sums", function() {
const sums: Sums.Sum[] = [];
for (let i = 0; i < 100; i++) {
sums.push(new Sums.Sum(Sums.Operator.Add, new Sums.Operand(i), new Sums.Operand(i)));
}
Sums.orderSums(sums, Sums.Ordering.Random);
// Shuffling is random so do this test up to two times.
let passCaseFound = false;
for (let i = 0; i < 2; i++) {
// Check that 0 + 0 isn't the first or last sum
if ((sums[0].operand1.getDigitAt(0) !== 0 || sums[0].operand2.getDigitAt(0) !== 0) &&
(sums[99].operand1.getDigitAt(0) !== 0 || sums[99].operand2.getDigitAt(0) !== 0)) {
passCaseFound = true;
break;
}
}
expect(passCaseFound).toBeTruthy();
});
});<|fim▁end|> | describe("ordering", function() { |
<|file_name|>tee.rs<|end_file_name|><|fim▁begin|>#![crate_name = "uu_tee"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Aleksander Bielawski <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
#[macro_use]
extern crate uucore;
use std::fs::OpenOptions;
use std::io::{copy, Error, ErrorKind, Read, Result, sink, stdin, stdout, Write};
use std::path::{Path, PathBuf};
static NAME: &'static str = "tee";
static VERSION: &'static str = env!("CARGO_PKG_VERSION");
pub fn uumain(args: Vec<String>) -> i32 {
match options(&args).and_then(exec) {
Ok(_) => 0,
Err(_) => 1
}
}
#[allow(dead_code)]
struct Options {
program: String,
append: bool,
ignore_interrupts: bool,
print_and_exit: Option<String>,
files: Vec<String>
}
fn options(args: &[String]) -> Result<Options> {
let mut opts = getopts::Options::new();
opts.optflag("a", "append", "append to the given FILEs, do not overwrite");
opts.optflag("i", "ignore-interrupts", "ignore interrupt signals");
opts.optflag("h", "help", "display this help and exit");
opts.optflag("V", "version", "output version information and exit");
opts.parse(&args[1..]).map_err(|e| Error::new(ErrorKind::Other, format!("{}", e))).and_then(|m| {
let version = format!("{} {}", NAME, VERSION);
let arguments = "[OPTION]... [FILE]...";
let brief = "Copy standard input to each FILE, and also to standard output.";
let comment = "If a FILE is -, copy again to standard output.";
let help = format!("{}\n\nUsage:\n {} {}\n\n{}\n{}",
version, NAME, arguments, opts.usage(brief),
comment);
let mut names: Vec<String> = m.free.clone().into_iter().collect();
names.push("-".to_owned());
let to_print = if m.opt_present("help") { Some(help) }
else if m.opt_present("version") { Some(version) }
else { None };
Ok(Options {
program: NAME.to_owned(),
append: m.opt_present("append"),
ignore_interrupts: m.opt_present("ignore-interrupts"),
print_and_exit: to_print,
files: names
})
}).map_err(|message| warn(format!("{}", message).as_ref()))
}
fn exec(options: Options) -> Result<()> {
match options.print_and_exit {
Some(text) => Ok(println!("{}", text)),
None => tee(options)
}
}
fn tee(options: Options) -> Result<()> {
let writers: Vec<Box<Write>> = options.files.clone().into_iter().map(|file| open(file, options.append)).collect();
let output = &mut MultiWriter { writers: writers };
let input = &mut NamedReader { inner: Box::new(stdin()) as Box<Read> };
if copy(input, output).is_err() || output.flush().is_err() {
Err(Error::new(ErrorKind::Other, ""))
} else {
Ok(())
}
}
fn open(name: String, append: bool) -> Box<Write> {
let is_stdout = name == "-";
let path = PathBuf::from(name);
let inner: Box<Write> = if is_stdout {
Box::new(stdout())
} else {
let mut options = OpenOptions::new();
let mode = if append { options.append(true) } else { options.truncate(true) };
match mode.write(true).create(true).open(path.as_path()) {
Ok(file) => Box::new(file),
Err(_) => Box::new(sink())
}
};
Box::new(NamedWriter { inner: inner, path: path }) as Box<Write>
}
struct MultiWriter {
writers: Vec<Box<Write>>
}
impl Write for MultiWriter {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
for writer in &mut self.writers {
try!(writer.write_all(buf));
}
Ok(buf.len())
}
fn flush(&mut self) -> Result<()> {<|fim▁hole|> try!(writer.flush());
}
Ok(())
}
}
struct NamedWriter {
inner: Box<Write>,
path: PathBuf
}
impl Write for NamedWriter {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
match self.inner.write(buf) {
Err(f) => {
self.inner = Box::new(sink()) as Box<Write>;
warn(format!("{}: {}", self.path.display(), f.to_string()).as_ref());
Err(f)
}
okay => okay
}
}
fn flush(&mut self) -> Result<()> {
match self.inner.flush() {
Err(f) => {
self.inner = Box::new(sink()) as Box<Write>;
warn(format!("{}: {}", self.path.display(), f.to_string()).as_ref());
Err(f)
}
okay => okay
}
}
}
struct NamedReader {
inner: Box<Read>
}
impl Read for NamedReader {
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
match self.inner.read(buf) {
Err(f) => {
warn(format!("{}: {}", Path::new("stdin").display(), f.to_string()).as_ref());
Err(f)
}
okay => okay
}
}
}
fn warn(message: &str) -> Error {
eprintln!("{}: {}", NAME, message);
Error::new(ErrorKind::Other, format!("{}: {}", NAME, message))
}<|fim▁end|> | for writer in &mut self.writers { |
<|file_name|>git-archive.js<|end_file_name|><|fim▁begin|>var util = require("util"),
Super = require("./super");
function GitArchive() {
};
module.exports = GitArchive;
util.inherits(GitArchive, Super);
GitArchive.prototype.format = "zip";
GitArchive.prototype.tree = "master";<|fim▁hole|>
GitArchive.prototype.exec = function()
{
return this.doExec(this.getCommand());
};
GitArchive.prototype.getCommand = function()
{
return [
"git archive",
" --format=",
this.format,
" --output ",
this.getOutput(),
" ",
this.tree
].join("");
};
GitArchive.prototype.getOutput = function()
{
return this.output;
};
GitArchive.prototype.onExecCallback = function(error, stdout, stderr)
{
this.fileCreated = (error === null);
this.emit("exec", this.fileCreated);
};<|fim▁end|> |
GitArchive.prototype.fileCreated = false; |
<|file_name|>run_gpu_test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Copyright 2014 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.
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__),
os.pardir, os.pardir, os.pardir, 'tools', 'telemetry'))
from telemetry import test_runner
<|fim▁hole|> sys.exit(test_runner.Main())<|fim▁end|> | if __name__ == '__main__': |
<|file_name|>canvasgradient.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::RGBA;
use canvas_traits::{CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, RadialGradientStyle};
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::CanvasGradientBinding;
use dom::bindings::codegen::Bindings::CanvasGradientBinding::CanvasGradientMethods;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::num::Finite;
use dom::bindings::utils::{Reflector, reflect_dom_object};
use dom::canvasrenderingcontext2d::parse_color;
<|fim▁hole|>pub struct CanvasGradient {
reflector_: Reflector,
style: CanvasGradientStyle,
stops: DOMRefCell<Vec<CanvasGradientStop>>,
}
#[jstraceable]
pub enum CanvasGradientStyle {
Linear(LinearGradientStyle),
Radial(RadialGradientStyle),
}
impl CanvasGradient {
fn new_inherited(style: CanvasGradientStyle) -> CanvasGradient {
CanvasGradient {
reflector_: Reflector::new(),
style: style,
stops: DOMRefCell::new(Vec::new()),
}
}
pub fn new(global: GlobalRef, style: CanvasGradientStyle) -> Temporary<CanvasGradient> {
reflect_dom_object(box CanvasGradient::new_inherited(style),
global, CanvasGradientBinding::Wrap)
}
}
impl<'a> CanvasGradientMethods for JSRef<'a, CanvasGradient> {
// https://html.spec.whatwg.org/multipage/#dom-canvasgradient-addcolorstop
fn AddColorStop(self, offset: Finite<f64>, color: String) {
let default_black = RGBA {
red: 0.0,
green: 0.0,
blue: 0.0,
alpha: 1.0,
};
self.stops.borrow_mut().push(CanvasGradientStop {
offset: (*offset) as f64,
color: parse_color(&color).unwrap_or(default_black),
});
}
}
pub trait ToFillOrStrokeStyle {
fn to_fill_or_stroke_style(&self) -> FillOrStrokeStyle;
}
impl<'a> ToFillOrStrokeStyle for JSRef<'a, CanvasGradient> {
fn to_fill_or_stroke_style(&self) -> FillOrStrokeStyle {
let gradient_stops = self.stops.borrow().clone();
match self.style {
CanvasGradientStyle::Linear(ref gradient) => {
FillOrStrokeStyle::LinearGradient(
LinearGradientStyle::new(gradient.x0, gradient.y0,
gradient.x1, gradient.y1,
gradient_stops))
},
CanvasGradientStyle::Radial(ref gradient) => {
FillOrStrokeStyle::RadialGradient(
RadialGradientStyle::new(gradient.x0, gradient.y0, gradient.r0,
gradient.x1, gradient.y1, gradient.r1,
gradient_stops))
}
}
}
}<|fim▁end|> | // https://html.spec.whatwg.org/multipage/#canvasgradient
#[dom_struct] |
<|file_name|>app.module.ts<|end_file_name|><|fim▁begin|>/**
* @author Damien Dell'Amico <[email protected]>
* @copyright Copyright (c) 2017
* @license GPL-3.0
*/
import { NgModule } from '@angular/core';
import { IonicApp, IonicModule } from 'ionic-angular';
import { TaxiApp } from './app.component';
import { AboutPage } from '../pages/about/about';
import { HomePage } from '../pages/home/home';
import { RideListPage } from '../pages/ride-list/ride-list';
import { ConfirmationPage } from '../pages/confirmation/confirmation';<|fim▁hole|>import { MapComponent } from '../components/map/map';
import { SearchPage } from '../pages/search/search';
import { RideService } from '../providers/ride/ride.service';
import { GeocoderService } from '../providers/map/geocoder.service';
import { MapService } from '../providers/map/map.service';
@NgModule({
declarations: [
TaxiApp,
AboutPage,
HomePage,
RideListPage,
MapComponent,
SearchPage,
ConfirmationPage
],
imports: [
IonicModule.forRoot(TaxiApp),
],
bootstrap: [IonicApp],
entryComponents: [
TaxiApp,
AboutPage,
HomePage,
RideListPage,
SearchPage,
ConfirmationPage
],
providers: [RideService, GeocoderService, MapService],
})
export class AppModule {
}<|fim▁end|> | |
<|file_name|>common.rs<|end_file_name|><|fim▁begin|>use ring::digest;
#[derive(Debug)]
pub struct Log {
pub description: String,
pub url: String,
pub is_google: bool,
}
pub fn sha256_hex(data: &[u8]) -> String {<|fim▁hole|>}<|fim▁end|> | hex::encode(digest::digest(&digest::SHA256, data).as_ref()) |
<|file_name|>test_connection.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright 2009-2013 Glencoe Software, Inc. All rights reserved.
Use is subject to license terms supplied in LICENSE.txt
pytest fixtures used as defined in conftest.py:
- gatewaywrapper
- author_testimg
"""
import omero
import Ice
from omero.gateway.scripts import dbhelpers
import pytest
class TestConnectionMethods(object):
def testMultiProcessSession(self, gatewaywrapper):
# 120 amongst other things trying to getSession() twice for the same
# session dies. Also in separate processes.
# we mimic this by calling setGroupForSession, which calls
# sessionservice.getSession, 2 times on cloned connections
gatewaywrapper.loginAsAuthor()
assert gatewaywrapper.gateway.getSession() is not None
c2 = gatewaywrapper.gateway.clone()
assert c2.connect(sUuid=gatewaywrapper.gateway._sessionUuid)
assert c2.getSession() is not None
a = c2.getAdminService()
g = omero.gateway.ExperimenterGroupWrapper(
c2, a.containedGroups(c2.getUserId())[-1])<|fim▁hole|> assert c3.connect(sUuid=gatewaywrapper.gateway._sessionUuid)
assert c3.getSession() is not None
a = c3.getAdminService()
g = omero.gateway.ExperimenterGroupWrapper(
c3, a.containedGroups(c3.getUserId())[1])
c3.setGroupForSession(g)
def testSeppuku(self, gatewaywrapper, author_testimg):
# author_testimg in args to make sure the image has been imported
gatewaywrapper.loginAsAuthor()
assert gatewaywrapper.getTestImage() is not None
gatewaywrapper.gateway.seppuku()
pytest.raises(Ice.ConnectionLostException, gatewaywrapper.getTestImage)
gatewaywrapper._has_connected = False
gatewaywrapper.doDisconnect()
gatewaywrapper.loginAsAuthor()
assert gatewaywrapper.getTestImage() is not None
gatewaywrapper.gateway.seppuku(softclose=False)
pytest.raises(Ice.ConnectionLostException, gatewaywrapper.getTestImage)
gatewaywrapper._has_connected = False
gatewaywrapper.doDisconnect()
# Also make sure softclose does the right thing
gatewaywrapper.loginAsAuthor()
g2 = gatewaywrapper.gateway.clone()
def g2_getTestImage():
return dbhelpers.getImage(g2, 'testimg1')
assert g2.connect(gatewaywrapper.gateway._sessionUuid)
assert gatewaywrapper.getTestImage() is not None
assert g2_getTestImage() is not None
g2.seppuku(softclose=True)
pytest.raises(Ice.ConnectionLostException, g2_getTestImage)
assert gatewaywrapper.getTestImage() is not None
g2 = gatewaywrapper.gateway.clone()
assert g2.connect(gatewaywrapper.gateway._sessionUuid)
assert gatewaywrapper.getTestImage() is not None
assert g2_getTestImage() is not None
g2.seppuku(softclose=False)
pytest.raises(Ice.ConnectionLostException, g2_getTestImage)
pytest.raises(Ice.ObjectNotExistException, gatewaywrapper.getTestImage)
gatewaywrapper._has_connected = False
gatewaywrapper.doDisconnect()
def testTopLevelObjects(self, gatewaywrapper, author_testimg):
##
# Test listProjects as root (sees, does not own)
parents = author_testimg.getAncestry()
project_id = parents[-1].getId()
# Original (4.1) test fails since 'admin' is logged into group 0, but
# the project created above is in new group.
# gatewaywrapper.loginAsAdmin()
# test passes if we remain logged in as Author
ids = map(lambda x: x.getId(), gatewaywrapper.gateway.listProjects())
assert project_id in ids
# test passes if we NOW log in as Admin (different group)
gatewaywrapper.loginAsAdmin()
ids = map(lambda x: x.getId(), gatewaywrapper.gateway.listProjects())
assert project_id not in ids
##
# Test listProjects as author (sees, owns)
gatewaywrapper.loginAsAuthor()
ids = map(lambda x: x.getId(), gatewaywrapper.gateway.listProjects())
assert project_id in ids
ids = map(lambda x: x.getId(), gatewaywrapper.gateway.listProjects())
assert project_id in ids
##
# Test listProjects as guest (does not see, does not own)
gatewaywrapper.doLogin(gatewaywrapper.USER)
ids = map(lambda x: x.getId(), gatewaywrapper.gateway.listProjects())
assert project_id not in ids
ids = map(lambda x: x.getId(), gatewaywrapper.gateway.listProjects())
assert project_id not in ids
##
# Test getProject
gatewaywrapper.loginAsAuthor()
assert gatewaywrapper.gateway.getObject(
"Project", project_id).getId() == project_id
##
# Test getDataset
dataset_id = parents[0].getId()
assert gatewaywrapper.gateway.getObject(
"Dataset", dataset_id).getId() == dataset_id
##
# Test listExperimenters
# exps = map(lambda x: x.omeName,
# gatewaywrapper.gateway.listExperimenters()) # removed from blitz
# gateway
exps = map(lambda x: x.omeName,
gatewaywrapper.gateway.getObjects("Experimenter"))
for omeName in (gatewaywrapper.USER.name, gatewaywrapper.AUTHOR.name,
gatewaywrapper.ADMIN.name.decode('utf-8')):
assert omeName in exps
assert len(list(gatewaywrapper.gateway.getObjects(
"Experimenter", attributes={'omeName': omeName}))) > 0
comboName = gatewaywrapper.USER.name + \
gatewaywrapper.AUTHOR.name + gatewaywrapper.ADMIN.name
assert len(list(gatewaywrapper.gateway.getObjects(
"Experimenter", attributes={'omeName': comboName}))) == 0
##
# Test lookupExperimenter
assert gatewaywrapper.gateway.getObject(
"Experimenter",
attributes={'omeName': gatewaywrapper.USER.name}).omeName == \
gatewaywrapper.USER.name
assert gatewaywrapper.gateway.getObject(
"Experimenter", attributes={'omeName': comboName}) is None
##
# still logged in as Author, test listImages(ns)
def listImages(ns=None):
imageAnnLinks = gatewaywrapper.gateway.getAnnotationLinks("Image",
ns=ns)
return [omero.gateway.ImageWrapper(gatewaywrapper.gateway,
link.parent) for link in imageAnnLinks]
ns = 'weblitz.test_annotation'
obj = gatewaywrapper.getTestImage()
# Make sure it doesn't yet exist
obj.removeAnnotations(ns)
assert obj.getAnnotation(ns) is None
# Check without the ann
assert len(listImages(ns=ns)) == 0
annclass = omero.gateway.CommentAnnotationWrapper
# createAndLink
annclass.createAndLink(target=obj, ns=ns, val='foo')
imgs = listImages(ns=ns)
assert len(imgs) == 1
assert imgs[0] == obj
# and clean up
obj.removeAnnotations(ns)
assert obj.getAnnotation(ns) is None
def testCloseSession(self, gatewaywrapper):
# 74 the failed connection for a user not in the system group does not
# get closed
gatewaywrapper.gateway.setIdentity(
gatewaywrapper.USER.name, gatewaywrapper.USER.passwd)
setprop = gatewaywrapper.gateway.c.ic.getProperties().setProperty
map(lambda x: setprop(x[0], str(x[1])),
gatewaywrapper.gateway._ic_props.items())
gatewaywrapper.gateway.c.ic.getImplicitContext().put(
omero.constants.GROUP, gatewaywrapper.gateway.group)
# I'm not certain the following assertion is as intended.
# This should be reviewed, see ticket #6037
# assert gatewaywrapper.gateway._sessionUuid == None
pytest.raises(omero.ClientError, gatewaywrapper.gateway._createSession)
assert gatewaywrapper.gateway._sessionUuid is not None
# 74 bug found while fixing this, the uuid passed to closeSession was
# not wrapped in rtypes, so logout didn't
gatewaywrapper.gateway._closeSession() # was raising ValueError
gatewaywrapper.gateway = None
def testMiscellaneous(self, gatewaywrapper):
gatewaywrapper.loginAsUser()
assert gatewaywrapper.gateway.getUser().omeName == \
gatewaywrapper.USER.name<|fim▁end|> | c2.setGroupForSession(g)
c3 = gatewaywrapper.gateway.clone() |
<|file_name|>device_user_defined.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement
__license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <[email protected]>'
__docformat__ = 'restructuredtext en'
from PyQt5.Qt import QDialog, QVBoxLayout, QPlainTextEdit, QTimer, \
QDialogButtonBox, QPushButton, QApplication, QIcon, QMessageBox
def step_dialog(parent, title, msg, det_msg=''):
d = QMessageBox(parent)
d.setWindowTitle(title)
d.setText(msg)
d.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
return d.exec_() & QMessageBox.Cancel
class UserDefinedDevice(QDialog):
def __init__(self, parent=None):
QDialog.__init__(self, parent)<|fim▁hole|> self.setLayout(self._layout)
self.log = QPlainTextEdit(self)
self._layout.addWidget(self.log)
self.log.setPlainText(_('Getting device information')+'...')
self.copy = QPushButton(_('Copy to &clipboard'))
self.copy.setDefault(True)
self.setWindowTitle(_('User-defined device information'))
self.setWindowIcon(QIcon(I('debug.png')))
self.copy.clicked.connect(self.copy_to_clipboard)
self.ok = QPushButton('&OK')
self.ok.setAutoDefault(False)
self.ok.clicked.connect(self.accept)
self.bbox = QDialogButtonBox(self)
self.bbox.addButton(self.copy, QDialogButtonBox.ActionRole)
self.bbox.addButton(self.ok, QDialogButtonBox.AcceptRole)
self._layout.addWidget(self.bbox)
self.resize(750, 500)
self.bbox.setEnabled(False)
QTimer.singleShot(1000, self.device_info)
def device_info(self):
try:
from calibre.devices import device_info
r = step_dialog(self.parent(), _('Device Detection'),
_('Ensure your device is disconnected, then press OK'))
if r:
self.close()
return
before = device_info()
r = step_dialog(self.parent(), _('Device Detection'),
_('Ensure your device is connected, then press OK'))
if r:
self.close()
return
after = device_info()
new_devices = after['device_set'] - before['device_set']
res = ''
if len(new_devices) == 1:
def fmtid(x):
if isinstance(x, (int, long)):
x = hex(x)
if not x.startswith('0x'):
x = '0x' + x
return x
for d in new_devices:
res = _('USB Vendor ID (in hex)') + ': ' + \
fmtid(after['device_details'][d][0]) + '\n'
res += _('USB Product ID (in hex)') + ': ' + \
fmtid(after['device_details'][d][1]) + '\n'
res += _('USB Revision ID (in hex)') + ': ' + \
fmtid(after['device_details'][d][2]) + '\n'
trailer = _(
'Copy these values to the clipboard, paste them into an '
'editor, then enter them into the USER_DEVICE by '
'customizing the device plugin in Preferences->Advanced->Plugins. '
'Remember to also enter the folders where you want the books to '
'be put. You must restart calibre for your changes '
'to take effect.\n')
self.log.setPlainText(res + '\n\n' + trailer)
finally:
self.bbox.setEnabled(True)
def copy_to_clipboard(self):
QApplication.clipboard().setText(self.log.toPlainText())
if __name__ == '__main__':
app = QApplication([])
d = UserDefinedDevice()
d.exec_()<|fim▁end|> | self._layout = QVBoxLayout(self) |
<|file_name|>shipvelocitybonusmi.py<|end_file_name|><|fim▁begin|># shipVelocityBonusMI
#
# Used by:
# Variations of ship: Mammoth (2 of 2)
# Ship: Hoarder
# Ship: Prowler<|fim▁hole|>def handler(fit, ship, context):
fit.ship.boostItemAttr("maxVelocity", ship.getModifiedItemAttr("shipBonusMI"), skill="Minmatar Industrial")<|fim▁end|> | type = "passive"
|
<|file_name|>NoteItem.js<|end_file_name|><|fim▁begin|>import React from 'react'
export default class NoteItem extends React.Component {
render () {
return (
<div>
<p>Category = {this.props.note.category}</p>
<p>The Note = {this.props.note.noteText}</p><|fim▁hole|> )
}
}<|fim▁end|> |
<hr />
</div> |
<|file_name|>AuthDataAccessor.java<|end_file_name|><|fim▁begin|>/*
* 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.syncope.core.spring.security;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.security.auth.login.AccountNotFoundException;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple;
import org.apache.syncope.common.keymaster.client.api.ConfParamOps;
import org.apache.syncope.common.lib.SyncopeConstants;
import org.apache.syncope.common.lib.types.AnyTypeKind;
import org.apache.syncope.common.lib.types.AuditElements;
import org.apache.syncope.common.lib.types.EntitlementsHolder;
import org.apache.syncope.common.lib.types.IdRepoEntitlement;
import org.apache.syncope.core.persistence.api.ImplementationLookup;
import org.apache.syncope.core.persistence.api.dao.AccessTokenDAO;
import org.apache.syncope.core.persistence.api.dao.AnySearchDAO;
import org.apache.syncope.core.persistence.api.entity.AnyType;
import org.apache.syncope.core.persistence.api.entity.resource.Provision;
import org.apache.syncope.core.provisioning.api.utils.RealmUtils;
import org.apache.syncope.core.persistence.api.dao.AnyTypeDAO;
import org.apache.syncope.core.persistence.api.dao.DelegationDAO;
import org.apache.syncope.core.persistence.api.dao.GroupDAO;
import org.apache.syncope.core.persistence.api.dao.RealmDAO;
import org.apache.syncope.core.persistence.api.dao.RoleDAO;
import org.apache.syncope.core.persistence.api.dao.UserDAO;
import org.apache.syncope.core.persistence.api.dao.search.AttrCond;
import org.apache.syncope.core.persistence.api.dao.search.SearchCond;
import org.apache.syncope.core.persistence.api.entity.AccessToken;
import org.apache.syncope.core.persistence.api.entity.Delegation;
import org.apache.syncope.core.persistence.api.entity.DynRealm;
import org.apache.syncope.core.persistence.api.entity.Realm;
import org.apache.syncope.core.persistence.api.entity.Role;
import org.apache.syncope.core.persistence.api.entity.resource.ExternalResource;
import org.apache.syncope.core.persistence.api.entity.user.User;
import org.apache.syncope.core.provisioning.api.AuditManager;
import org.apache.syncope.core.provisioning.api.ConnectorManager;
import org.apache.syncope.core.provisioning.api.MappingManager;
import org.apache.syncope.core.spring.ApplicationContextProvider;
import org.identityconnectors.framework.common.objects.Uid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.transaction.annotation.Transactional;
/**
* Domain-sensible (via {@code @Transactional}) access to authentication / authorization data.
*
* @see JWTAuthenticationProvider
* @see UsernamePasswordAuthenticationProvider
* @see SyncopeAuthenticationDetails
*/
public class AuthDataAccessor {
protected static final Logger LOG = LoggerFactory.getLogger(AuthDataAccessor.class);
public static final String GROUP_OWNER_ROLE = "GROUP_OWNER";
protected static final Encryptor ENCRYPTOR = Encryptor.getInstance();
protected static final Set<SyncopeGrantedAuthority> ANONYMOUS_AUTHORITIES =
Set.of(new SyncopeGrantedAuthority(IdRepoEntitlement.ANONYMOUS));
protected static final Set<SyncopeGrantedAuthority> MUST_CHANGE_PASSWORD_AUTHORITIES =
Set.of(new SyncopeGrantedAuthority(IdRepoEntitlement.MUST_CHANGE_PASSWORD));
protected final SecurityProperties securityProperties;
protected final RealmDAO realmDAO;
protected final UserDAO userDAO;
protected final GroupDAO groupDAO;
protected final AnyTypeDAO anyTypeDAO;
protected final AnySearchDAO anySearchDAO;
protected final AccessTokenDAO accessTokenDAO;
protected final ConfParamOps confParamOps;
protected final RoleDAO roleDAO;
protected final DelegationDAO delegationDAO;
protected final ConnectorManager connectorManager;
protected final AuditManager auditManager;
protected final MappingManager mappingManager;
protected final ImplementationLookup implementationLookup;
private Map<String, JWTSSOProvider> jwtSSOProviders;
public AuthDataAccessor(
final SecurityProperties securityProperties,
final RealmDAO realmDAO,
final UserDAO userDAO,
final GroupDAO groupDAO,
final AnyTypeDAO anyTypeDAO,
final AnySearchDAO anySearchDAO,
final AccessTokenDAO accessTokenDAO,
final ConfParamOps confParamOps,
final RoleDAO roleDAO,
final DelegationDAO delegationDAO,
final ConnectorManager connectorManager,
final AuditManager auditManager,
final MappingManager mappingManager,
final ImplementationLookup implementationLookup) {
this.securityProperties = securityProperties;
this.realmDAO = realmDAO;
this.userDAO = userDAO;
this.groupDAO = groupDAO;
this.anyTypeDAO = anyTypeDAO;
this.anySearchDAO = anySearchDAO;
this.accessTokenDAO = accessTokenDAO;
this.confParamOps = confParamOps;
this.roleDAO = roleDAO;
this.delegationDAO = delegationDAO;
this.connectorManager = connectorManager;
this.auditManager = auditManager;
this.mappingManager = mappingManager;
this.implementationLookup = implementationLookup;
}
public JWTSSOProvider getJWTSSOProvider(final String issuer) {
synchronized (this) {
if (jwtSSOProviders == null) {
jwtSSOProviders = new HashMap<>();
implementationLookup.getJWTSSOProviderClasses().stream().
map(clazz -> (JWTSSOProvider) ApplicationContextProvider.getBeanFactory().
createBean(clazz, AbstractBeanDefinition.AUTOWIRE_BY_TYPE, true)).
forEach(jwtSSOProvider -> jwtSSOProviders.put(jwtSSOProvider.getIssuer(), jwtSSOProvider));
}
}
<|fim▁hole|> if (issuer == null) {
throw new AuthenticationCredentialsNotFoundException("A null issuer is not permitted");
}
JWTSSOProvider provider = jwtSSOProviders.get(issuer);
if (provider == null) {
throw new AuthenticationCredentialsNotFoundException(
"Could not find any registered JWTSSOProvider for issuer " + issuer);
}
return provider;
}
protected String getDelegationKey(final SyncopeAuthenticationDetails details, final String delegatedKey) {
if (details.getDelegatedBy() == null) {
return null;
}
String delegatingKey = SyncopeConstants.UUID_PATTERN.matcher(details.getDelegatedBy()).matches()
? details.getDelegatedBy()
: userDAO.findKey(details.getDelegatedBy());
if (delegatingKey == null) {
throw new SessionAuthenticationException(
"Delegating user " + details.getDelegatedBy() + " cannot be found");
}
LOG.debug("Delegation request: delegating:{}, delegated:{}", delegatingKey, delegatedKey);
return delegationDAO.findValidFor(delegatingKey, delegatedKey).
orElseThrow(() -> new SessionAuthenticationException(
"Delegation by " + delegatingKey + " was requested but none found"));
}
/**
* Attempts to authenticate the given credentials against internal storage and pass-through resources (if
* configured): the first succeeding causes global success.
*
* @param domain domain
* @param authentication given credentials
* @return {@code null} if no matching user was found, authentication result otherwise
*/
@Transactional(noRollbackFor = DisabledException.class)
public Triple<User, Boolean, String> authenticate(final String domain, final Authentication authentication) {
User user = null;
String[] authAttrValues = confParamOps.get(
domain, "authentication.attributes", new String[] { "username" }, String[].class);
for (int i = 0; user == null && i < authAttrValues.length; i++) {
if ("username".equals(authAttrValues[i])) {
user = userDAO.findByUsername(authentication.getName());
} else {
AttrCond attrCond = new AttrCond(AttrCond.Type.EQ);
attrCond.setSchema(authAttrValues[i]);
attrCond.setExpression(authentication.getName());
try {
List<User> users = anySearchDAO.search(SearchCond.getLeaf(attrCond), AnyTypeKind.USER);
if (users.size() == 1) {
user = users.get(0);
} else {
LOG.warn("Search condition {} does not uniquely match a user", attrCond);
}
} catch (IllegalArgumentException e) {
LOG.error("While searching user for authentication via {}", attrCond, e);
}
}
}
Boolean authenticated = null;
String delegationKey = null;
if (user != null) {
authenticated = false;
if (user.isSuspended() != null && user.isSuspended()) {
throw new DisabledException("User " + user.getUsername() + " is suspended");
}
String[] authStatuses = confParamOps.get(
domain, "authentication.statuses", new String[] {}, String[].class);
if (!ArrayUtils.contains(authStatuses, user.getStatus())) {
throw new DisabledException("User " + user.getUsername() + " not allowed to authenticate");
}
boolean userModified = false;
authenticated = authenticate(user, authentication.getCredentials().toString());
if (authenticated) {
delegationKey = getDelegationKey(
SyncopeAuthenticationDetails.class.cast(authentication.getDetails()), user.getKey());
if (confParamOps.get(domain, "log.lastlogindate", true, Boolean.class)) {
user.setLastLoginDate(new Date());
userModified = true;
}
if (user.getFailedLogins() != 0) {
user.setFailedLogins(0);
userModified = true;
}
} else {
user.setFailedLogins(user.getFailedLogins() + 1);
userModified = true;
}
if (userModified) {
userDAO.save(user);
}
}
return Triple.of(user, authenticated, delegationKey);
}
protected boolean authenticate(final User user, final String password) {
boolean authenticated = ENCRYPTOR.verify(password, user.getCipherAlgorithm(), user.getPassword());
LOG.debug("{} authenticated on internal storage: {}", user.getUsername(), authenticated);
for (Iterator<? extends ExternalResource> itor = getPassthroughResources(user).iterator();
itor.hasNext() && !authenticated;) {
ExternalResource resource = itor.next();
String connObjectKey = null;
try {
AnyType userType = anyTypeDAO.findUser();
Provision provision = resource.getProvision(userType).
orElseThrow(() -> new AccountNotFoundException(
"Unable to locate provision for user type " + userType.getKey()));
connObjectKey = mappingManager.getConnObjectKeyValue(user, provision).
orElseThrow(() -> new AccountNotFoundException(
"Unable to locate conn object key value for " + userType.getKey()));
Uid uid = connectorManager.getConnector(resource).authenticate(connObjectKey, password, null);
if (uid != null) {
authenticated = true;
}
} catch (Exception e) {
LOG.debug("Could not authenticate {} on {}", user.getUsername(), resource.getKey(), e);
}
LOG.debug("{} authenticated on {} as {}: {}",
user.getUsername(), resource.getKey(), connObjectKey, authenticated);
}
return authenticated;
}
protected Set<? extends ExternalResource> getPassthroughResources(final User user) {
Set<? extends ExternalResource> result = null;
// 1. look for assigned resources, pick the ones whose account policy has authentication resources
for (ExternalResource resource : userDAO.findAllResources(user)) {
if (resource.getAccountPolicy() != null && !resource.getAccountPolicy().getResources().isEmpty()) {
if (result == null) {
result = resource.getAccountPolicy().getResources();
} else {
result.retainAll(resource.getAccountPolicy().getResources());
}
}
}
// 2. look for realms, pick the ones whose account policy has authentication resources
for (Realm realm : realmDAO.findAncestors(user.getRealm())) {
if (realm.getAccountPolicy() != null && !realm.getAccountPolicy().getResources().isEmpty()) {
if (result == null) {
result = realm.getAccountPolicy().getResources();
} else {
result.retainAll(realm.getAccountPolicy().getResources());
}
}
}
return result == null ? Set.of() : result;
}
protected Set<SyncopeGrantedAuthority> getAdminAuthorities() {
return EntitlementsHolder.getInstance().getValues().stream().
map(entitlement -> new SyncopeGrantedAuthority(entitlement, SyncopeConstants.ROOT_REALM)).
collect(Collectors.toSet());
}
protected Set<SyncopeGrantedAuthority> buildAuthorities(final Map<String, Set<String>> entForRealms) {
Set<SyncopeGrantedAuthority> authorities = new HashSet<>();
entForRealms.forEach((entitlement, realms) -> {
Pair<Set<String>, Set<String>> normalized = RealmUtils.normalize(realms);
SyncopeGrantedAuthority authority = new SyncopeGrantedAuthority(entitlement);
authority.addRealms(normalized.getLeft());
authority.addRealms(normalized.getRight());
authorities.add(authority);
});
return authorities;
}
protected Set<SyncopeGrantedAuthority> getUserAuthorities(final User user) {
if (user.isMustChangePassword()) {
return MUST_CHANGE_PASSWORD_AUTHORITIES;
}
Map<String, Set<String>> entForRealms = new HashMap<>();
// Give entitlements as assigned by roles (with static or dynamic realms, where applicable) - assigned
// either statically and dynamically
userDAO.findAllRoles(user).stream().
filter(role -> !GROUP_OWNER_ROLE.equals(role.getKey())).
forEach(role -> role.getEntitlements().forEach(entitlement -> {
Set<String> realms = Optional.ofNullable(entForRealms.get(entitlement)).orElseGet(() -> {
Set<String> r = new HashSet<>();
entForRealms.put(entitlement, r);
return r;
});
realms.addAll(role.getRealms().stream().map(Realm::getFullPath).collect(Collectors.toSet()));
if (!entitlement.endsWith("_CREATE") && !entitlement.endsWith("_DELETE")) {
realms.addAll(role.getDynRealms().stream().map(DynRealm::getKey).collect(Collectors.toList()));
}
}));
// Give group entitlements for owned groups
groupDAO.findOwnedByUser(user.getKey()).forEach(group -> {
Role groupOwnerRole = roleDAO.find(GROUP_OWNER_ROLE);
if (groupOwnerRole == null) {
LOG.warn("Role {} was not found", GROUP_OWNER_ROLE);
} else {
groupOwnerRole.getEntitlements().forEach(entitlement -> {
Set<String> realms = Optional.ofNullable(entForRealms.get(entitlement)).orElseGet(() -> {
HashSet<String> r = new HashSet<>();
entForRealms.put(entitlement, r);
return r;
});
realms.add(RealmUtils.getGroupOwnerRealm(group.getRealm().getFullPath(), group.getKey()));
});
}
});
return buildAuthorities(entForRealms);
}
protected Set<SyncopeGrantedAuthority> getDelegatedAuthorities(final Delegation delegation) {
Map<String, Set<String>> entForRealms = new HashMap<>();
delegation.getRoles().stream().filter(role -> !GROUP_OWNER_ROLE.equals(role.getKey())).
forEach(role -> role.getEntitlements().forEach(entitlement -> {
Set<String> realms = Optional.ofNullable(entForRealms.get(entitlement)).orElseGet(() -> {
HashSet<String> r = new HashSet<>();
entForRealms.put(entitlement, r);
return r;
});
realms.addAll(role.getRealms().stream().map(Realm::getFullPath).collect(Collectors.toSet()));
if (!entitlement.endsWith("_CREATE") && !entitlement.endsWith("_DELETE")) {
realms.addAll(role.getDynRealms().stream().map(DynRealm::getKey).collect(Collectors.toList()));
}
}));
return buildAuthorities(entForRealms);
}
@Transactional
public Set<SyncopeGrantedAuthority> getAuthorities(final String username, final String delegationKey) {
Set<SyncopeGrantedAuthority> authorities;
if (securityProperties.getAnonymousUser().equals(username)) {
authorities = ANONYMOUS_AUTHORITIES;
} else if (securityProperties.getAdminUser().equals(username)) {
authorities = getAdminAuthorities();
} else if (delegationKey != null) {
Delegation delegation = Optional.ofNullable(delegationDAO.find(delegationKey)).
orElseThrow(() -> new UsernameNotFoundException(
"Could not find delegation " + delegationKey));
authorities = delegation.getRoles().isEmpty()
? getUserAuthorities(delegation.getDelegating())
: getDelegatedAuthorities(delegation);
} else {
User user = Optional.ofNullable(userDAO.findByUsername(username)).
orElseThrow(() -> new UsernameNotFoundException(
"Could not find any user with username " + username));
authorities = getUserAuthorities(user);
}
return authorities;
}
@Transactional
public Pair<String, Set<SyncopeGrantedAuthority>> authenticate(final JWTAuthentication authentication) {
String username;
Set<SyncopeGrantedAuthority> authorities;
if (securityProperties.getAdminUser().equals(authentication.getClaims().getSubject())) {
AccessToken accessToken = accessTokenDAO.find(authentication.getClaims().getJWTID());
if (accessToken == null) {
throw new AuthenticationCredentialsNotFoundException(
"Could not find an Access Token for JWT " + authentication.getClaims().getJWTID());
}
username = securityProperties.getAdminUser();
authorities = getAdminAuthorities();
} else {
JWTSSOProvider jwtSSOProvider = getJWTSSOProvider(authentication.getClaims().getIssuer());
Pair<User, Set<SyncopeGrantedAuthority>> resolved = jwtSSOProvider.resolve(authentication.getClaims());
if (resolved == null || resolved.getLeft() == null) {
throw new AuthenticationCredentialsNotFoundException(
"Could not find User " + authentication.getClaims().getSubject()
+ " for JWT " + authentication.getClaims().getJWTID());
}
User user = resolved.getLeft();
String delegationKey = getDelegationKey(authentication.getDetails(), user.getKey());
username = user.getUsername();
authorities = resolved.getRight() == null
? Set.of()
: delegationKey == null
? resolved.getRight()
: getAuthorities(username, delegationKey);
LOG.debug("JWT {} issued by {} resolved to User {} with authorities {}",
authentication.getClaims().getJWTID(),
authentication.getClaims().getIssuer(),
username + Optional.ofNullable(delegationKey).
map(d -> " [under delegation " + delegationKey + "]").orElse(StringUtils.EMPTY),
authorities);
if (BooleanUtils.isTrue(user.isSuspended())) {
throw new DisabledException("User " + username + " is suspended");
}
List<String> authStatuses = List.of(confParamOps.get(authentication.getDetails().getDomain(),
"authentication.statuses", new String[] {}, String[].class));
if (!authStatuses.contains(user.getStatus())) {
throw new DisabledException("User " + username + " not allowed to authenticate");
}
if (BooleanUtils.isTrue(user.isMustChangePassword())) {
LOG.debug("User {} must change password, resetting authorities", username);
authorities = MUST_CHANGE_PASSWORD_AUTHORITIES;
}
}
return Pair.of(username, authorities);
}
@Transactional
public void removeExpired(final String tokenKey) {
accessTokenDAO.delete(tokenKey);
}
@Transactional(readOnly = true)
public void audit(
final String username,
final String delegationKey,
final AuditElements.Result result,
final Object output,
final Object... input) {
auditManager.audit(
username + Optional.ofNullable(delegationKey).
map(d -> " [under delegation " + delegationKey + "]").orElse(StringUtils.EMPTY),
AuditElements.EventCategoryType.LOGIC, AuditElements.AUTHENTICATION_CATEGORY, null,
AuditElements.LOGIN_EVENT, result, null, output, input);
}
}<|fim▁end|> | |
<|file_name|>fptree.py<|end_file_name|><|fim▁begin|>""" in this file, we describe the data type of fp-tree nodes and present
an algorithm to build a fp-tree from existing datasets """
import fpgrowth
import Queue
def supfilter(dataset, minsup):
"""
supfilter : scan the items and drop the infrequent elements
:param dataset: dataset could be in two available types: list(data) and list((data, support))
:param minsup:
:return:
"""
rec = {}
for item in dataset:
for elem in item:
# counting the number of existance for all elements
if elem not in rec:
rec[elem] = 0
rec[elem] += 1
# filter: find the infrequent keywords
if '' in rec:
del rec['']
inf = filter(lambda i: i[1] >= minsup, rec.items())
inf = map(lambda i: i[0], inf)
# remove the infrequent elements from the dataset
dataset = map(
lambda i: filter(lambda ele: ele in inf, i),
dataset
)
# remove the empty items
dataset = filter(lambda i: len(i) > 0, dataset)
# sort by the support of items
dataset = map(
lambda i: sorted(
i,
# we use support of elements as sorting keys
key=lambda ele: rec[ele],
reverse=True
),
dataset
)
return dataset
class Node:
def __init__(self, name=None, parent=None, headertable=None):
self.name = name
self.sup = 0
self.children = {}
self.parent = parent
if headertable is not None:
# the node will be appended to the header table if such
# such a table is provided
if name not in headertable:
headertable[name] = []
headertable[name].append(self)
def appenditem(self, item, headertable):
self.sup += 1
if len(item) == 0:
return<|fim▁hole|> self.children[item[0]].appenditem(item[1:], headertable)
class fptree:
def __init__(self, dataset, minsup):
""" dataset should be a list of data items, in form of
[
['apple', 'milk', 'wtf'],
['banana'],
....
]
data items can be any strings
NOTE: once a fptree is created, it should never be modified
(at least in this scenario)
"""
# minimum support
self.minsup = minsup
items = supfilter(dataset, minsup)
""" the root node of a fp-tree """
self.root = Node()
""" header table """
self.headertable = {}
for item in items:
self.root.appenditem(item, self.headertable)
# check if the tree contains only a single prefix
# todo
def growth(self):
"""
important!! this function is not thread-safe, so never try to execute it
parallelly
:return:
"""
# initialize the queue
fpgrowth.patterns = Queue.Queue()
fpgrowth.fpgrowth(self, [], self.minsup)
fpgrowth.wait()
result = []
while not fpgrowth.patterns.empty():
patt = fpgrowth.patterns.get()
result.append(patt)
return result<|fim▁end|> | if item[0] not in self.children:
self.children[item[0]] = Node(item[0], self, headertable) |
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>extern crate getopts;
extern crate regex;
use std::os;
fn main() {
let args = os::args();
let program = args[0].clone();
let opt_matches = match getopts::getopts(args.tail(), options().as_slice()) {
Ok(m) => { m }
Err(f) => {
println!("{}\n", f.to_string());
print_usage(program.as_slice());
return;
}<|fim▁hole|> }
}
struct CmdContext {
cmd_args: Vec<String>,
in_delim: Vec<regex::Regex>,
out_delim: Vec<regex::Regex>,
nprocs: u32,
empty: String,
}
fn shape(args: Vec<String>) {
}
fn reshape(args: Vec<String>) {
}
fn map(args: Vec<String>) {
}
fn agg(args: Vec<String>) {
}
fn options() -> Vec<getopts::OptGroup> {
vec![
getopts::optflag("h", "help", "Print this help message"),
getopts::optopt("d", "delim", "Specify axis delimiters. [Default:\\n/\\s]", "DELIM"),
getopts::optopt("l", "odelim", "Specify axis delimiters. [Default:\\n/\\s]", "ODELIM"),
getopts::optopt("e", "empty", "Specify the string that should be used to represent empty cells", "EMPTY"),
getopts::optopt("", "nprocs", "Maximum number of subprocesses or threads that can be spawned. [Default:16]", "NPROCS"),
]
}
fn print_usage(program: &str) {
let opts = options();
let commands = "Commands:
shape Get the shape of this matrix
reshape <new_shape> Reshape this matrix into a new one
map <cmd> Map a command on each selected cell
agg <axes> <cmd> Aggregate a matrix along the specified axes
using a command.";
let brief = format!("USAGE:\n {} [options] <selector> [<cmd>] [<input_file>...]\n\n{}", program, commands);
print!("{}", getopts::usage(brief.as_slice(), opts.as_slice()));
}<|fim▁end|> | };
if opt_matches.opt_present("h") {
print_usage(program.as_slice());
return; |
<|file_name|>dropck_tarena_cycle_checked.rs<|end_file_name|><|fim▁begin|>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Reject mixing cyclic structure and Drop when using TypedArena.
//
// (Compare against compile-fail/dropck_vec_cycle_checked.rs)
//
// (Also compare against compile-fail/dropck_tarena_unsound_drop.rs,
// which is a reduction of this code to more directly show the reason
// for the error message we see here.)
#![allow(unstable)]
#![feature(const_fn)]
extern crate arena;
use arena::TypedArena;
use std::cell::Cell;
use id::Id;
mod s {
#![allow(unstable)]
use std::sync::atomic::{AtomicUsize, Ordering};
static S_COUNT: AtomicUsize = AtomicUsize::new(0);
pub fn next_count() -> usize {
S_COUNT.fetch_add(1, Ordering::SeqCst) + 1
}
}
mod id {
use s;
#[derive(Debug)]
pub struct Id {
orig_count: usize,
count: usize,
}
impl Id {
pub fn new() -> Id {
let c = s::next_count();
println!("building Id {}", c);
Id { orig_count: c, count: c }
}
pub fn count(&self) -> usize {
println!("Id::count on {} returns {}", self.orig_count, self.count);
self.count
}
}
impl Drop for Id {
fn drop(&mut self) {
println!("dropping Id {}", self.count);
self.count = 0;
}
}
}
trait HasId {
fn count(&self) -> usize;
}
#[derive(Debug)]
struct CheckId<T:HasId> {<|fim▁hole|>
#[allow(non_snake_case)]
fn CheckId<T:HasId>(t: T) -> CheckId<T> { CheckId{ v: t } }
impl<T:HasId> Drop for CheckId<T> {
fn drop(&mut self) {
assert!(self.v.count() > 0);
}
}
#[derive(Debug)]
struct C<'a> {
id: Id,
v: Vec<CheckId<Cell<Option<&'a C<'a>>>>>,
}
impl<'a> HasId for Cell<Option<&'a C<'a>>> {
fn count(&self) -> usize {
match self.get() {
None => 1,
Some(c) => c.id.count(),
}
}
}
impl<'a> C<'a> {
fn new() -> C<'a> {
C { id: Id::new(), v: Vec::new() }
}
}
fn f<'a>(arena: &'a TypedArena<C<'a>>) {
let c1 = arena.alloc(C::new());
let c2 = arena.alloc(C::new());
let c3 = arena.alloc(C::new());
c1.v.push(CheckId(Cell::new(None)));
c1.v.push(CheckId(Cell::new(None)));
c2.v.push(CheckId(Cell::new(None)));
c2.v.push(CheckId(Cell::new(None)));
c3.v.push(CheckId(Cell::new(None)));
c3.v.push(CheckId(Cell::new(None)));
c1.v[0].v.set(Some(c2));
c1.v[1].v.set(Some(c3));
c2.v[0].v.set(Some(c2));
c2.v[1].v.set(Some(c3));
c3.v[0].v.set(Some(c1));
c3.v[1].v.set(Some(c2));
}
fn main() {
let arena = TypedArena::new();
f(&arena); //~ ERROR `arena` does not live long enough
}<|fim▁end|> | v: T
} |
<|file_name|>CheckerBase.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python3
import contextlib
import threading
import mwparserfromhell
import ws.ArchWiki.lang as lang
from ws.utils import LazyProperty
from ws.parser_helpers.title import canonicalize
from ws.parser_helpers.wikicode import get_parent_wikicode, get_adjacent_node
__all__ = ["get_edit_summary_tracker", "localize_flag", "CheckerBase"]
# WARNING: using the context manager is not thread-safe
def get_edit_summary_tracker(wikicode, summary_parts):
@contextlib.contextmanager
def checker(summary):
text = str(wikicode)
try:
yield
finally:
if text != str(wikicode):
summary_parts.append(summary)
return checker
def localize_flag(wikicode, node, template_name):
"""
If a ``node`` in ``wikicode`` is followed by a template with the same base
name as ``template_name``, this function changes the adjacent template's
name to ``template_name``.
:param wikicode: a :py:class:`mwparserfromhell.wikicode.Wikicode` object
:param node: a :py:class:`mwparserfromhell.nodes.Node` object
:param str template_name: the name of the template flag, potentially
including a language name
"""
parent = get_parent_wikicode(wikicode, node)
adjacent = get_adjacent_node(parent, node, ignore_whitespace=True)
if isinstance(adjacent, mwparserfromhell.nodes.Template):
adjname = lang.detect_language(str(adjacent.name))[0]
basename = lang.detect_language(template_name)[0]
if canonicalize(adjname) == canonicalize(basename):
adjacent.name = template_name
class CheckerBase:
def __init__(self, api, db, *, interactive=False, **kwargs):
self.api = api
self.db = db
self.interactive = interactive
# lock used for synchronizing access to the wikicode AST
# FIXME: the lock should not be an attribute of the checker, but of the wikicode<|fim▁hole|> # (we would still have to manually lock for wrapper functions and longer parts in the checkers)
self.lock_wikicode = threading.RLock()
@LazyProperty
def _alltemplates(self):
result = self.api.generator(generator="allpages", gapnamespace=10, gaplimit="max", gapfilterredir="nonredirects")
return {page["title"].split(":", maxsplit=1)[1] for page in result}
def get_localized_template(self, template, language="English"):
assert(canonicalize(template) in self._alltemplates)
localized = lang.format_title(template, language)
if canonicalize(localized) in self._alltemplates:
return localized
# fall back to English
return template
def handle_node(self, src_title, wikicode, node, summary_parts):
raise NotImplementedError("the handle_node method was not implemented in the derived class")<|fim▁end|> | # maybe we can create a wrapper class (e.g. ThreadSafeWikicode) which would transparently synchronize all method calls: https://stackoverflow.com/a/17494777 |
<|file_name|>test_errors.py<|end_file_name|><|fim▁begin|># Copyright 2015-2017 ProfitBricks GmbH
#
# 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.
import unittest
from profitbricks.client import ProfitBricksService, Datacenter, Volume
from profitbricks.errors import PBError, PBNotAuthorizedError, PBNotFoundError, PBValidationError
from helpers import configuration
from helpers.resources import resource
class TestErrors(unittest.TestCase):
@classmethod
def setUpClass(self):
self.resource = resource()
self.client = ProfitBricksService(
username=configuration.USERNAME,
password=configuration.PASSWORD,
headers=configuration.HEADERS)
self.datacenter = self.client.create_datacenter(
datacenter=Datacenter(**self.resource['datacenter']))
@classmethod
def tearDownClass(self):
self.client.delete_datacenter(datacenter_id=self.datacenter['id'])
def test_pb_not_found(self):
try:
self.client.get_datacenter("fake_id")
except PBError as err:
self.assertTrue(isinstance(err, PBNotFoundError))
def test_pb_unauthorized_error(self):
try:
self.client = ProfitBricksService(
username=configuration.USERNAME + "1",
password=configuration.PASSWORD,
headers=configuration.HEADERS)
self.client.list_datacenters()
except PBError as err:
self.assertTrue(isinstance(err, PBNotAuthorizedError))
def test_pb_validation_error(self):
try:
i = Volume(
name='Explicitly created volume',
size=5,
disk_type='HDD',
image='fake_image_id',<|fim▁hole|> except PBError as err:
self.assertTrue(isinstance(err, PBValidationError))
if __name__ == '__main__':
unittest.main()<|fim▁end|> | bus='VIRTIO')
self.client.create_volume(datacenter_id=self.datacenter['id'], volume=i) |
<|file_name|>file_tasks.js<|end_file_name|><|fim▁begin|>// 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.
'use strict';
/**
* This object encapsulates everything related to tasks execution.
*
* TODO(hirono): Pass each component instead of the entire FileManager.
* @param {FileManager} fileManager FileManager instance.
* @param {Object=} opt_params File manager load parameters.
* @constructor
*/
function FileTasks(fileManager, opt_params) {
this.fileManager_ = fileManager;
this.params_ = opt_params;
this.tasks_ = null;
this.defaultTask_ = null;
this.entries_ = null;
/**
* List of invocations to be called once tasks are available.
*
* @private
* @type {Array.<Object>}
*/
this.pendingInvocations_ = [];
}
/**
* Location of the Chrome Web Store.
*
* @const
* @type {string}
*/
FileTasks.CHROME_WEB_STORE_URL = 'https://chrome.google.com/webstore';
/**
* Base URL of apps list in the Chrome Web Store. This constant is used in
* FileTasks.createWebStoreLink().
*
* @const
* @type {string}
*/
FileTasks.WEB_STORE_HANDLER_BASE_URL =
'https://chrome.google.com/webstore/category/collection/file_handlers';
/**
* The app ID of the video player app.
* @const
* @type {string}
*/
FileTasks.VIDEO_PLAYER_ID = 'jcgeabjmjgoblfofpppfkcoakmfobdko';
/**
* Returns URL of the Chrome Web Store which show apps supporting the given
* file-extension and mime-type.
*
* @param {string} extension Extension of the file (with the first dot).
* @param {string} mimeType Mime type of the file.
* @return {string} URL
*/
FileTasks.createWebStoreLink = function(extension, mimeType) {
if (!extension)
return FileTasks.CHROME_WEB_STORE_URL;
if (extension[0] === '.')
extension = extension.substr(1);
else
console.warn('Please pass an extension with a dot to createWebStoreLink.');
var url = FileTasks.WEB_STORE_HANDLER_BASE_URL;
url += '?_fe=' + extension.toLowerCase().replace(/[^\w]/g, '');
// If a mime is given, add it into the URL.
if (mimeType)
url += '&_fmt=' + mimeType.replace(/[^-\w\/]/g, '');
return url;
};
/**
* Complete the initialization.
*
* @param {Array.<Entry>} entries List of file entries.
* @param {Array.<string>=} opt_mimeTypes List of MIME types for each
* of the files.
*/
FileTasks.prototype.init = function(entries, opt_mimeTypes) {
this.entries_ = entries;
this.mimeTypes_ = opt_mimeTypes || [];
// TODO(mtomasz): Move conversion from entry to url to custom bindings.
var urls = util.entriesToURLs(entries);
if (urls.length > 0) {
chrome.fileBrowserPrivate.getFileTasks(urls, this.mimeTypes_,
this.onTasks_.bind(this));
}
};
/**
* Returns amount of tasks.
*
* @return {number} amount of tasks.
*/
FileTasks.prototype.size = function() {
return (this.tasks_ && this.tasks_.length) || 0;
};
/**
* Callback when tasks found.
*
* @param {Array.<Object>} tasks The tasks.
* @private
*/
FileTasks.prototype.onTasks_ = function(tasks) {
this.processTasks_(tasks);
for (var index = 0; index < this.pendingInvocations_.length; index++) {
var name = this.pendingInvocations_[index][0];
var args = this.pendingInvocations_[index][1];
this[name].apply(this, args);
}
this.pendingInvocations_ = [];
};
/**
* The list of known extensions to record UMA.
* Note: Because the data is recorded by the index, so new item shouldn't be
* inserted.
*
* @const
* @type {Array.<string>}
* @private
*/
FileTasks.UMA_INDEX_KNOWN_EXTENSIONS_ = Object.freeze([
'other', '.3ga', '.3gp', '.aac', '.alac', '.asf', '.avi', '.bmp', '.csv',
'.doc', '.docx', '.flac', '.gif', '.jpeg', '.jpg', '.log', '.m3u', '.m3u8',
'.m4a', '.m4v', '.mid', '.mkv', '.mov', '.mp3', '.mp4', '.mpg', '.odf',
'.odp', '.ods', '.odt', '.oga', '.ogg', '.ogv', '.pdf', '.png', '.ppt',
'.pptx', '.ra', '.ram', '.rar', '.rm', '.rtf', '.wav', '.webm', '.webp',
'.wma', '.wmv', '.xls', '.xlsx',
]);
/**
* The list of executable file extensions.
*
* @const
* @type {Array.<string>}
*/
FileTasks.EXECUTABLE_EXTENSIONS = Object.freeze([
'.exe', '.lnk', '.deb', '.dmg', '.jar', '.msi',
]);
/**
* The list of extensions to skip the suggest app dialog.
* @const
* @type {Array.<string>}
* @private
*/
FileTasks.EXTENSIONS_TO_SKIP_SUGGEST_APPS_ = Object.freeze([
'.crdownload', '.dsc', '.inf', '.crx',
]);
/**
* Records trial of opening file grouped by extensions.
*
* @param {Array.<Entry>} entries The entries to be opened.
* @private
*/
FileTasks.recordViewingFileTypeUMA_ = function(entries) {
for (var i = 0; i < entries.length; i++) {
var entry = entries[i];
var extension = FileType.getExtension(entry).toLowerCase();
if (FileTasks.UMA_INDEX_KNOWN_EXTENSIONS_.indexOf(extension) < 0) {
extension = 'other';
}
metrics.recordEnum(
'ViewingFileType', extension, FileTasks.UMA_INDEX_KNOWN_EXTENSIONS_);
}
};
/**
* Returns true if the taskId is for an internal task.
*
* @param {string} taskId Task identifier.
* @return {boolean} True if the task ID is for an internal task.
* @private
*/
FileTasks.isInternalTask_ = function(taskId) {
var taskParts = taskId.split('|');
var appId = taskParts[0];
var taskType = taskParts[1];
var actionId = taskParts[2];
// The action IDs here should match ones used in executeInternalTask_().
return (appId === chrome.runtime.id &&
taskType === 'file' &&
(actionId === 'play' ||
actionId === 'mount-archive' ||
actionId === 'gallery' ||
actionId === 'gallery-video'));
};
/**
* Processes internal tasks.
*
* @param {Array.<Object>} tasks The tasks.
* @private
*/
FileTasks.prototype.processTasks_ = function(tasks) {
this.tasks_ = [];
var id = chrome.runtime.id;
var isOnDrive = false;
var fm = this.fileManager_;
for (var index = 0; index < this.entries_.length; ++index) {
var locationInfo = fm.volumeManager.getLocationInfo(this.entries_[index]);
if (locationInfo && locationInfo.isDriveBased) {
isOnDrive = true;
break;
}
}
for (var i = 0; i < tasks.length; i++) {
var task = tasks[i];
var taskParts = task.taskId.split('|');
// Skip internal Files.app's handlers.
if (taskParts[0] === id && (taskParts[2] === 'auto-open' ||
taskParts[2] === 'select' || taskParts[2] === 'open')) {
continue;
}
// Tweak images, titles of internal tasks.
if (taskParts[0] === id && taskParts[1] === 'file') {
if (taskParts[2] === 'play') {
// TODO(serya): This hack needed until task.iconUrl is working
// (see GetFileTasksFileBrowserFunction::RunImpl).
task.iconType = 'audio';
task.title = loadTimeData.getString('ACTION_LISTEN');
} else if (taskParts[2] === 'mount-archive') {
task.iconType = 'archive';
task.title = loadTimeData.getString('MOUNT_ARCHIVE');
} else if (taskParts[2] === 'gallery' ||
taskParts[2] === 'gallery-video') {
task.iconType = 'image';
task.title = loadTimeData.getString('ACTION_OPEN');
} else if (taskParts[2] === 'open-hosted-generic') {
if (this.entries_.length > 1)
task.iconType = 'generic';
else // Use specific icon.
task.iconType = FileType.getIcon(this.entries_[0]);
task.title = loadTimeData.getString('ACTION_OPEN');
} else if (taskParts[2] === 'open-hosted-gdoc') {
task.iconType = 'gdoc';
task.title = loadTimeData.getString('ACTION_OPEN_GDOC');
} else if (taskParts[2] === 'open-hosted-gsheet') {
task.iconType = 'gsheet';
task.title = loadTimeData.getString('ACTION_OPEN_GSHEET');
} else if (taskParts[2] === 'open-hosted-gslides') {
task.iconType = 'gslides';
task.title = loadTimeData.getString('ACTION_OPEN_GSLIDES');
} else if (taskParts[2] === 'view-swf') {
// Do not render this task if disabled.
if (!loadTimeData.getBoolean('SWF_VIEW_ENABLED'))
continue;
task.iconType = 'generic';
task.title = loadTimeData.getString('ACTION_VIEW');
} else if (taskParts[2] === 'view-pdf') {
// Do not render this task if disabled.
if (!loadTimeData.getBoolean('PDF_VIEW_ENABLED'))<|fim▁hole|> task.title = loadTimeData.getString('ACTION_VIEW');
} else if (taskParts[2] === 'view-in-browser') {
task.iconType = 'generic';
task.title = loadTimeData.getString('ACTION_VIEW');
}
}
if (!task.iconType && taskParts[1] === 'web-intent') {
task.iconType = 'generic';
}
this.tasks_.push(task);
if (this.defaultTask_ === null && task.isDefault) {
this.defaultTask_ = task;
}
}
if (!this.defaultTask_ && this.tasks_.length > 0) {
// If we haven't picked a default task yet, then just pick the first one.
// This is not the preferred way we want to pick this, but better this than
// no default at all if the C++ code didn't set one.
this.defaultTask_ = this.tasks_[0];
}
};
/**
* Executes default task.
*
* @param {function(boolean, Array.<string>)=} opt_callback Called when the
* default task is executed, or the error is occurred.
* @private
*/
FileTasks.prototype.executeDefault_ = function(opt_callback) {
FileTasks.recordViewingFileTypeUMA_(this.entries_);
this.executeDefaultInternal_(this.entries_, opt_callback);
};
/**
* Executes default task.
*
* @param {Array.<Entry>} entries Entries to execute.
* @param {function(boolean, Array.<Entry>)=} opt_callback Called when the
* default task is executed, or the error is occurred.
* @private
*/
FileTasks.prototype.executeDefaultInternal_ = function(entries, opt_callback) {
var callback = opt_callback || function(arg1, arg2) {};
if (this.defaultTask_ !== null) {
this.executeInternal_(this.defaultTask_.taskId, entries);
callback(true, entries);
return;
}
// We don't have tasks, so try to show a file in a browser tab.
// We only do that for single selection to avoid confusion.
if (entries.length !== 1 || !entries[0])
return;
var filename = entries[0].name;
var extension = util.splitExtension(filename)[1];
var mimeType = this.mimeTypes_[0];
var showAlert = function() {
var textMessageId;
var titleMessageId;
switch (extension) {
case '.exe':
textMessageId = 'NO_ACTION_FOR_EXECUTABLE';
break;
case '.crx':
textMessageId = 'NO_ACTION_FOR_CRX';
titleMessageId = 'NO_ACTION_FOR_CRX_TITLE';
break;
default:
textMessageId = 'NO_ACTION_FOR_FILE';
}
var webStoreUrl = FileTasks.createWebStoreLink(extension, mimeType);
var text = strf(textMessageId, webStoreUrl, str('NO_ACTION_FOR_FILE_URL'));
var title = titleMessageId ? str(titleMessageId) : filename;
this.fileManager_.alert.showHtml(title, text, function() {});
callback(false, entries);
}.bind(this);
var onViewFilesFailure = function() {
var fm = this.fileManager_;
if (!fm.isOnDrive() ||
!entries[0] ||
FileTasks.EXTENSIONS_TO_SKIP_SUGGEST_APPS_.indexOf(extension) !== -1) {
showAlert();
return;
}
fm.openSuggestAppsDialog(
entries[0],
function() {
var newTasks = new FileTasks(fm);
newTasks.init(entries, this.mimeTypes_);
newTasks.executeDefault();
callback(true, entries);
}.bind(this),
// Cancelled callback.
function() {
callback(false, entries);
},
showAlert);
}.bind(this);
var onViewFiles = function(result) {
switch (result) {
case 'opened':
callback(success, entries);
break;
case 'message_sent':
util.isTeleported(window).then(function(teleported) {
if (teleported) {
util.showOpenInOtherDesktopAlert(
this.fileManager_.ui.alertDialog, entries);
}
}.bind(this));
callback(success, entries);
break;
case 'empty':
callback(success, entries);
break;
case 'failed':
onViewFilesFailure();
break;
}
}.bind(this);
this.checkAvailability_(function() {
// TODO(mtomasz): Pass entries instead.
var urls = util.entriesToURLs(entries);
var taskId = chrome.runtime.id + '|file|view-in-browser';
chrome.fileBrowserPrivate.executeTask(taskId, urls, onViewFiles);
}.bind(this));
};
/**
* Executes a single task.
*
* @param {string} taskId Task identifier.
* @param {Array.<Entry>=} opt_entries Entries to xecute on instead of
* this.entries_|.
* @private
*/
FileTasks.prototype.execute_ = function(taskId, opt_entries) {
var entries = opt_entries || this.entries_;
FileTasks.recordViewingFileTypeUMA_(entries);
this.executeInternal_(taskId, entries);
};
/**
* The core implementation to execute a single task.
*
* @param {string} taskId Task identifier.
* @param {Array.<Entry>} entries Entries to execute.
* @private
*/
FileTasks.prototype.executeInternal_ = function(taskId, entries) {
this.checkAvailability_(function() {
if (FileTasks.isInternalTask_(taskId)) {
var taskParts = taskId.split('|');
this.executeInternalTask_(taskParts[2], entries);
} else {
// TODO(mtomasz): Pass entries instead.
var urls = util.entriesToURLs(entries);
chrome.fileBrowserPrivate.executeTask(taskId, urls, function(result) {
if (result !== 'message_sent')
return;
util.isTeleported(window).then(function(teleported) {
if (teleported) {
util.showOpenInOtherDesktopAlert(
this.fileManager_.ui.alertDialog, entries);
}
}.bind(this));
}.bind(this));
}
}.bind(this));
};
/**
* Checks whether the remote files are available right now.
*
* @param {function} callback The callback.
* @private
*/
FileTasks.prototype.checkAvailability_ = function(callback) {
var areAll = function(props, name) {
var isOne = function(e) {
// If got no properties, we safely assume that item is unavailable.
return e && e[name];
};
return props.filter(isOne).length === props.length;
};
var fm = this.fileManager_;
var entries = this.entries_;
var isDriveOffline = fm.volumeManager.getDriveConnectionState().type ===
VolumeManagerCommon.DriveConnectionType.OFFLINE;
if (fm.isOnDrive() && isDriveOffline) {
fm.metadataCache_.get(entries, 'drive', function(props) {
if (areAll(props, 'availableOffline')) {
callback();
return;
}
fm.alert.showHtml(
loadTimeData.getString('OFFLINE_HEADER'),
props[0].hosted ?
loadTimeData.getStringF(
entries.length === 1 ?
'HOSTED_OFFLINE_MESSAGE' :
'HOSTED_OFFLINE_MESSAGE_PLURAL') :
loadTimeData.getStringF(
entries.length === 1 ?
'OFFLINE_MESSAGE' :
'OFFLINE_MESSAGE_PLURAL',
loadTimeData.getString('OFFLINE_COLUMN_LABEL')));
});
return;
}
var isOnMetered = fm.volumeManager.getDriveConnectionState().type ===
VolumeManagerCommon.DriveConnectionType.METERED;
if (fm.isOnDrive() && isOnMetered) {
fm.metadataCache_.get(entries, 'drive', function(driveProps) {
if (areAll(driveProps, 'availableWhenMetered')) {
callback();
return;
}
fm.metadataCache_.get(entries, 'filesystem', function(fileProps) {
var sizeToDownload = 0;
for (var i = 0; i !== entries.length; i++) {
if (!driveProps[i].availableWhenMetered)
sizeToDownload += fileProps[i].size;
}
fm.confirm.show(
loadTimeData.getStringF(
entries.length === 1 ?
'CONFIRM_MOBILE_DATA_USE' :
'CONFIRM_MOBILE_DATA_USE_PLURAL',
util.bytesToString(sizeToDownload)),
callback);
});
});
return;
}
callback();
};
/**
* Executes an internal task.
*
* @param {string} id The short task id.
* @param {Array.<Entry>} entries The entries to execute on.
* @private
*/
FileTasks.prototype.executeInternalTask_ = function(id, entries) {
var fm = this.fileManager_;
if (id === 'play') {
var selectedEntry = entries[0];
if (entries.length === 1) {
// If just a single audio file is selected pass along every audio file
// in the directory.
entries = fm.getAllEntriesInCurrentDirectory().filter(FileType.isAudio);
}
// TODO(mtomasz): Pass entries instead.
var urls = util.entriesToURLs(entries);
var position = urls.indexOf(selectedEntry.toURL());
chrome.fileBrowserPrivate.getProfiles(function(profiles,
currentId,
displayedId) {
fm.backgroundPage.launchAudioPlayer({items: urls, position: position},
displayedId);
});
return;
}
if (id === 'mount-archive') {
this.mountArchivesInternal_(entries);
return;
}
if (id === 'gallery' || id === 'gallery-video') {
this.openGalleryInternal_(entries);
return;
}
console.error('Unexpected action ID: ' + id);
};
/**
* Mounts archives.
*
* @param {Array.<Entry>} entries Mount file entries list.
*/
FileTasks.prototype.mountArchives = function(entries) {
FileTasks.recordViewingFileTypeUMA_(entries);
this.mountArchivesInternal_(entries);
};
/**
* The core implementation of mounts archives.
*
* @param {Array.<Entry>} entries Mount file entries list.
* @private
*/
FileTasks.prototype.mountArchivesInternal_ = function(entries) {
var fm = this.fileManager_;
var tracker = fm.directoryModel.createDirectoryChangeTracker();
tracker.start();
// TODO(mtomasz): Pass Entries instead of URLs.
var urls = util.entriesToURLs(entries);
fm.resolveSelectResults_(urls, function(resolvedURLs) {
for (var index = 0; index < resolvedURLs.length; ++index) {
// TODO(mtomasz): Pass Entry instead of URL.
fm.volumeManager.mountArchive(resolvedURLs[index],
function(volumeInfo) {
if (tracker.hasChanged) {
tracker.stop();
return;
}
volumeInfo.resolveDisplayRoot(function(displayRoot) {
if (tracker.hasChanged) {
tracker.stop();
return;
}
fm.directoryModel.changeDirectoryEntry(displayRoot);
}, function() {
console.warn('Failed to resolve the display root after mounting.');
tracker.stop();
});
}, function(url, error) {
tracker.stop();
var path = util.extractFilePath(url);
var namePos = path.lastIndexOf('/');
fm.alert.show(strf('ARCHIVE_MOUNT_FAILED',
path.substr(namePos + 1), error));
}.bind(null, resolvedURLs[index]));
}
});
};
/**
* Open the Gallery.
*
* @param {Array.<Entry>} entries List of selected entries.
*/
FileTasks.prototype.openGallery = function(entries) {
FileTasks.recordViewingFileTypeUMA_(entries);
this.openGalleryInternal_(entries);
};
/**
* The core implementation to open the Gallery.
*
* @param {Array.<Entry>} entries List of selected entries.
* @private
*/
FileTasks.prototype.openGalleryInternal_ = function(entries) {
var fm = this.fileManager_;
var allEntries =
fm.getAllEntriesInCurrentDirectory().filter(FileType.isImageOrVideo);
var galleryFrame = fm.document_.createElement('iframe');
galleryFrame.className = 'overlay-pane';
galleryFrame.scrolling = 'no';
galleryFrame.setAttribute('webkitallowfullscreen', true);
if (this.params_ && this.params_.gallery) {
// Remove the Gallery state from the location, we do not need it any more.
// TODO(mtomasz): Consider keeping the selection path.
util.updateAppState(
null, /* keep current directory */
'', /* remove current selection */
'' /* remove search. */);
}
var savedAppState = JSON.parse(JSON.stringify(window.appState));
var savedTitle = document.title;
// Push a temporary state which will be replaced every time the selection
// changes in the Gallery and popped when the Gallery is closed.
util.updateAppState();
var onBack = function(selectedEntries) {
fm.directoryModel.selectEntries(selectedEntries);
fm.closeFilePopup(); // Will call Gallery.unload.
window.appState = savedAppState;
util.saveAppState();
document.title = savedTitle;
};
var onAppRegionChanged = function(visible) {
fm.onFilePopupAppRegionChanged(visible);
};
galleryFrame.onload = function() {
galleryFrame.contentWindow.ImageUtil.metrics = metrics;
// TODO(haruki): isOnReadonlyDirectory() only checks the permission for the
// root. We should check more granular permission to know whether the file
// is writable or not.
var readonly = fm.isOnReadonlyDirectory();
var currentDir = fm.getCurrentDirectoryEntry();
var downloadsVolume = fm.volumeManager.getCurrentProfileVolumeInfo(
VolumeManagerCommon.RootType.DOWNLOADS);
var downloadsDir = downloadsVolume && downloadsVolume.fileSystem.root;
// TODO(mtomasz): Pass Entry instead of localized name. Conversion to a
// display string should be done in gallery.js.
var readonlyDirName = null;
if (readonly && currentDir)
readonlyDirName = util.getEntryLabel(fm.volumeManager, currentDir);
var context = {
// We show the root label in readonly warning (e.g. archive name).
readonlyDirName: readonlyDirName,
curDirEntry: currentDir,
saveDirEntry: readonly ? downloadsDir : null,
searchResults: fm.directoryModel.isSearching(),
metadataCache: fm.metadataCache_,
pageState: this.params_,
appWindow: chrome.app.window.current(),
onBack: onBack,
onClose: fm.onClose.bind(fm),
onMaximize: fm.onMaximize.bind(fm),
onMinimize: fm.onMinimize.bind(fm),
onAppRegionChanged: onAppRegionChanged,
loadTimeData: fm.backgroundPage.background.stringData
};
galleryFrame.contentWindow.Gallery.open(
context, fm.volumeManager, allEntries, entries);
}.bind(this);
galleryFrame.src = 'gallery.html';
fm.openFilePopup(galleryFrame, fm.updateTitle_.bind(fm));
};
/**
* Displays the list of tasks in a task picker combobutton.
*
* @param {cr.ui.ComboButton} combobutton The task picker element.
* @private
*/
FileTasks.prototype.display_ = function(combobutton) {
if (this.tasks_.length === 0) {
combobutton.hidden = true;
return;
}
combobutton.clear();
combobutton.hidden = false;
combobutton.defaultItem = this.createCombobuttonItem_(this.defaultTask_);
var items = this.createItems_();
if (items.length > 1) {
var defaultIdx = 0;
for (var j = 0; j < items.length; j++) {
combobutton.addDropDownItem(items[j]);
if (items[j].task.taskId === this.defaultTask_.taskId)
defaultIdx = j;
}
combobutton.addSeparator();
var changeDefaultMenuItem = combobutton.addDropDownItem({
label: loadTimeData.getString('CHANGE_DEFAULT_MENU_ITEM')
});
changeDefaultMenuItem.classList.add('change-default');
}
};
/**
* Creates sorted array of available task descriptions such as title and icon.
*
* @return {Array} created array can be used to feed combobox, menus and so on.
* @private
*/
FileTasks.prototype.createItems_ = function() {
var items = [];
var title = this.defaultTask_.title + ' ' +
loadTimeData.getString('DEFAULT_ACTION_LABEL');
items.push(this.createCombobuttonItem_(this.defaultTask_, title, true));
for (var index = 0; index < this.tasks_.length; index++) {
var task = this.tasks_[index];
if (task !== this.defaultTask_)
items.push(this.createCombobuttonItem_(task));
}
items.sort(function(a, b) {
return a.label.localeCompare(b.label);
});
return items;
};
/**
* Updates context menu with default item.
* @private
*/
FileTasks.prototype.updateMenuItem_ = function() {
this.fileManager_.updateContextMenuActionItems(this.defaultTask_,
this.tasks_.length > 1);
};
/**
* Creates combobutton item based on task.
*
* @param {Object} task Task to convert.
* @param {string=} opt_title Title.
* @param {boolean=} opt_bold Make a menu item bold.
* @return {Object} Item appendable to combobutton drop-down list.
* @private
*/
FileTasks.prototype.createCombobuttonItem_ = function(task, opt_title,
opt_bold) {
return {
label: opt_title || task.title,
iconUrl: task.iconUrl,
iconType: task.iconType,
task: task,
bold: opt_bold || false
};
};
/**
* Shows modal action picker dialog with currently available list of tasks.
*
* @param {DefaultActionDialog} actionDialog Action dialog to show and update.
* @param {string} title Title to use.
* @param {string} message Message to use.
* @param {function(Object)} onSuccess Callback to pass selected task.
*/
FileTasks.prototype.showTaskPicker = function(actionDialog, title, message,
onSuccess) {
var items = this.createItems_();
var defaultIdx = 0;
for (var j = 0; j < items.length; j++) {
if (items[j].task.taskId === this.defaultTask_.taskId)
defaultIdx = j;
}
actionDialog.show(
title,
message,
items, defaultIdx,
function(item) {
onSuccess(item.task);
});
};
/**
* Decorates a FileTasks method, so it will be actually executed after the tasks
* are available.
* This decorator expects an implementation called |method + '_'|.
*
* @param {string} method The method name.
*/
FileTasks.decorate = function(method) {
var privateMethod = method + '_';
FileTasks.prototype[method] = function() {
if (this.tasks_) {
this[privateMethod].apply(this, arguments);
} else {
this.pendingInvocations_.push([privateMethod, arguments]);
}
return this;
};
};
FileTasks.decorate('display');
FileTasks.decorate('updateMenuItem');
FileTasks.decorate('execute');
FileTasks.decorate('executeDefault');<|fim▁end|> | continue;
task.iconType = 'pdf'; |
<|file_name|>20170323200721_expense_items.js<|end_file_name|><|fim▁begin|>let allExpenses
exports.up = (knex, Promise) => {
return knex('expenses').select('*')
.then(expenses => {
allExpenses = expenses
return knex.schema.createTable('expense_items', (table) => {
table.increments('id').primary().notNullable()
table.integer('expense_id').notNullable().references('id').inTable('expenses')
table.integer('position').notNullable()
table.decimal('preTaxAmount').notNullable()
table.decimal('taxrate').notNullable()
table.text('description')
table.index('expense_id')
})
})
.then(() => {
// this is necessary BEFORE creating the expense items because knex
// drops the expenses table and then recreates it (foreign key problem).
console.log('Dropping "preTaxAmount" and "taxrate" columns in expenses')
return knex.schema.table('expenses', table => {
table.dropColumn('preTaxAmount')
table.dropColumn('taxrate')
})
})
.then(() => {
console.log('Migrating ' + allExpenses.length + ' expenses to items')
return Promise.all(
allExpenses.map(expense => createExpenseItem(knex, expense))
)
})
}
exports.down = (knex, Promise) => {
return knex.schema.dropTableIfExists('expense_items')
}<|fim▁hole|> expense_id: expense.id,
position: 0,
preTaxAmount: expense.preTaxAmount,
taxrate: expense.taxrate,
description: ''
})
}<|fim▁end|> |
function createExpenseItem(knex, expense) {
return knex('expense_items')
.insert({ |
<|file_name|>findScriptUrls.js<|end_file_name|><|fim▁begin|>define('findScriptUrls', [], function () {
return function(pattern) {
var type = typeof pattern, i, tags = document.querySelectorAll("script"), matches = [], src;
for (i = 0; i < tags.length; i++) {
src = tags[i].src || "";
if (type === "string") {
if (src.indexOf(pattern) !== -1) {
matches.push(src);
}
} else if (pattern.test(src)) {
matches.push(src);
}
}
return matches;<|fim▁hole|><|fim▁end|> | };
}); |
<|file_name|>setup_fast_likelihood.py<|end_file_name|><|fim▁begin|>from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy as np
import os
<|fim▁hole|> sourcefiles,
include_dirs = [np.get_include()],
extra_compile_args=['-O3', '-fopenmp', '-lc++'],
extra_link_args=['-fopenmp'],
language='c++')]
setup(
name = 'fastgmm',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules
)<|fim▁end|> | sourcefiles = [ 'fast_likelihood.pyx']
ext_modules = [Extension("fast_likelihood", |
<|file_name|>730.cpp<|end_file_name|><|fim▁begin|>// Copyright 2015 Adam Grandquist<|fim▁hole|>
#include "./catch.hpp"
#include "./ReQL.hpp"
using namespace ReQL;
TEST_CASE("cpp Regression tests for issue 106", "[cpp][ast]") {
}<|fim▁end|> | |
<|file_name|>ramda.js<|end_file_name|><|fim▁begin|>// ramda.js
// https://github.com/CrossEye/ramda
// (c) 2013-2014 Scott Sauyet and Michael Hurley
// Ramda may be freely distributed under the MIT license.
// Ramda
// -----
// A practical functional library for Javascript programmers. Ramda is a collection of tools to make it easier to
// use Javascript as a functional programming language. (The name is just a silly play on `lambda`.)
// Basic Setup
// -----------
// Uses a technique from the [Universal Module Definition][umd] to wrap this up for use in Node.js or in the browser,
// with or without an AMD-style loader.
//
// [umd]: https://github.com/umdjs/umd/blob/master/returnExports.js
(function(factory) {
if (typeof exports === 'object') {
module.exports = factory(this);
} else if (typeof define === 'function' && define.amd) {
define(factory);
} else {
this.R = this.ramda = factory(this);
}
}(function() {
'use strict';
// This object is what is actually returned, with all the exposed functions attached as properties.
/**
* A practical functional library for Javascript programmers.
*
* @namespace R
*/
// jscs:disable disallowQuotedKeysInObjects
var R = {'version': '0.5.0'};
// jscs:enable disallowQuotedKeysInObjects
// Internal Functions and Properties
// ---------------------------------
/**
* An optimized, private array `slice` implementation.
*
* @private
* @category Internal
* @param {Arguments|Array} args The array or arguments object to consider.
* @param {number} [from=0] The array index to slice from, inclusive.
* @param {number} [to=args.length] The array index to slice to, exclusive.
* @return {Array} A new, sliced array.
* @example
*
* _slice([1, 2, 3, 4, 5], 1, 3); //=> [2, 3]
*
* var firstThreeArgs = function(a, b, c, d) {
* return _slice(arguments, 0, 3);
* };
* firstThreeArgs(1, 2, 3, 4); //=> [1, 2, 3]
*/
function _slice(args, from, to) {
switch (arguments.length) {
case 0: throw NO_ARGS_EXCEPTION;
case 1: return _slice(args, 0, args.length);
case 2: return _slice(args, from, args.length);
default:
var length = to - from, list = new Array(length), idx = -1;
while (++idx < length) {
list[idx] = args[from + idx];
}
return list;
}
}
/**
* Private `concat` function to merge two array-like objects.
*
* @private
* @category Internal
* @param {Array|Arguments} [set1=[]] An array-like object.
* @param {Array|Arguments} [set2=[]] An array-like object.
* @return {Array} A new, merged array.
* @example
*
* concat([4, 5, 6], [1, 2, 3]); //=> [4, 5, 6, 1, 2, 3]
*/
var concat = function _concat(set1, set2) {
set1 = set1 || [];
set2 = set2 || [];
var length1 = set1.length,
length2 = set2.length,
result = new Array(length1 + length2);
for (var idx = 0; idx < length1; idx++) {
result[idx] = set1[idx];
}
for (idx = 0; idx < length2; idx++) {
result[idx + length1] = set2[idx];
}
return result;
};
// Private reference to toString function.
var toString = Object.prototype.toString;
/**
* Tests whether or not an object is an array.
*
* @private
* @category Internal
* @param {*} val The object to test.
* @return {boolean} `true` if `val` is an array, `false` otherwise.
* @example
*
* isArray([]); //=> true
* isArray(true); //=> false
* isArray({}); //=> false
*/
var isArray = Array.isArray || function _isArray(val) {
return val && val.length >= 0 && toString.call(val) === '[object Array]';
};
/**
* Tests whether or not an object is similar to an array.
*
* @func
* @category Type
* @category List
* @param {*} val The object to test.
* @return {boolean} `true` if `val` has a numeric length property; `false` otherwise.
* @example
*
* R.isArrayLike([]); //=> true
* R.isArrayLike(true); //=> false
* R.isArrayLike({}); //=> false
* R.isArrayLike({length: 10}); //=> true
*/
R.isArrayLike = function isArrayLike(x) {
return isArray(x) || (
!!x &&
typeof x === 'object' &&
!(x instanceof String) &&
(
!!(x.nodeType === 1 && x.length) ||
x.length >= 0
)
);
};
var NO_ARGS_EXCEPTION = new TypeError('Function called with no arguments');
/**
* Optimized internal two-arity curry function.
*
* @private
* @category Function
* @param {Function} fn The function to curry.
* @return {Function} curried function
* @example
*
* var addTwo = function(a, b) {
* return a + b;
* };
*
* var curriedAddTwo = curry2(addTwo);
*/
function curry2(fn) {
return function(a, b) {
switch (arguments.length) {
case 0:
throw NO_ARGS_EXCEPTION;
case 1:
return function(b) {
return fn(a, b);
};
default:
return fn(a, b);
}
};
}
/**
* Optimized internal three-arity curry function.
*
* @private
* @category Function
* @param {Function} fn The function to curry.
* @return {Function} curried function
* @example
*
* var addThree = function(a, b, c) {
* return a + b + c;
* };
*
* var curriedAddThree = curry3(addThree);
*/
function curry3(fn) {
return function(a, b, c) {
switch (arguments.length) {
case 0:
throw NO_ARGS_EXCEPTION;
case 1:
return curry2(function(b, c) {
return fn(a, b, c);
});
case 2:
return function(c) {
return fn(a, b, c);
};
default:
return fn(a, b, c);
}
};
}
if (typeof Object.defineProperty === 'function') {
try {
Object.defineProperty(R, '_', {writable: false, value: void 0});
} catch (e) {}
}
var _ = R._; void _;// This intentionally left `undefined`.
/**
* Converts a function into something like an infix operation, meaning that
* when called with a single argument, that argument is applied to the
* second position, sort of a curry-right. This allows for more natural
* processing of functions which are really binary operators.
*
* @memberOf R
* @category Functions
* @param {function} fn The operation to adjust
* @return {function} A new function that acts somewhat like an infix operator.
* @example
*
* var div = R.op(function (a, b) {
* return a / b;
* });
*
* div(6, 3); //=> 2
* div(6, _)(3); //=> 2 // note: `_` here is just an `undefined` value. You could use `void 0` instead
* div(3)(6); //=> 2
*/
var op = R.op = function op(fn) {
var length = fn.length;
if (length < 2) {throw new Error('Expected binary function.');}
var left = curry(fn), right = curry(R.flip(fn));
return function(a, b) {
switch (arguments.length) {
case 0: throw NO_ARGS_EXCEPTION;
case 1: return right(a);
case 2: return (b === R._) ? left(a) : left.apply(null, arguments);
default: return left.apply(null, arguments);
}
};
};
/**
* Creates a new version of `fn` with given arity that, when invoked,
* will return either:
* - A new function ready to accept one or more of `fn`'s remaining arguments, if all of
* `fn`'s expected arguments have not yet been provided
* - `fn`'s result if all of its expected arguments have been provided
*
* This function is useful in place of `curry`, when the arity of the
* function to curry cannot be determined from its signature, e.g. if it's
* a variadic function.
*
* @func
* @memberOf R
* @category Function
* @sig Number -> (* -> a) -> (* -> a)
* @param {number} fnArity The arity for the returned function.
* @param {Function} fn The function to curry.
* @return {Function} A new, curried function.
* @see R.curry
* @example
*
* var addFourNumbers = function() {
* return R.sum([].slice.call(arguments, 0, 4));
* };
*
* var curriedAddFourNumbers = R.curryN(4, addFourNumbers);
* var f = curriedAddFourNumbers(1, 2);
* var g = f(3);
* g(4);//=> 10
*/
var curryN = R.curryN = function curryN(length, fn) {
return (function recurry(args) {
return arity(Math.max(length - (args && args.length || 0), 0), function() {
if (arguments.length === 0) { throw NO_ARGS_EXCEPTION; }
var newArgs = concat(args, arguments);
if (newArgs.length >= length) {
return fn.apply(this, newArgs);
} else {
return recurry(newArgs);
}
});
}([]));
};
/**
* Creates a new version of `fn` that, when invoked, will return either:
* - A new function ready to accept one or more of `fn`'s remaining arguments, if all of
* `fn`'s expected arguments have not yet been provided
* - `fn`'s result if all of its expected arguments have been provided
*
* @func
* @memberOf R
* @category Function
* @sig (* -> a) -> (* -> a)
* @param {Function} fn The function to curry.
* @return {Function} A new, curried function.
* @see R.curryN
* @example
*
* var addFourNumbers = function(a, b, c, d) {
* return a + b + c + d;
* };
*
* var curriedAddFourNumbers = R.curry(addFourNumbers);
* var f = curriedAddFourNumbers(1, 2);
* var g = f(3);
* g(4);//=> 10
*/
var curry = R.curry = function curry(fn) {
return curryN(fn.length, fn);
};
/**
* Private function that determines whether or not a provided object has a given method.
* Does not ignore methods stored on the object's prototype chain. Used for dynamically
* dispatching Ramda methods to non-Array objects.
*
* @private
* @category Internal
* @param {string} methodName The name of the method to check for.
* @param {Object} obj The object to test.
* @return {boolean} `true` has a given method, `false` otherwise.
* @example
*
* var person = { name: 'John' };
* person.shout = function() { alert(this.name); };
*
* hasMethod('shout', person); //=> true
* hasMethod('foo', person); //=> false
*/
var hasMethod = function _hasMethod(methodName, obj) {
return obj && !isArray(obj) && typeof obj[methodName] === 'function';
};
/**
* Similar to hasMethod, this checks whether a function has a [methodname]
* function. If it isn't an array it will execute that function otherwise it will
* default to the ramda implementation.
*
* @private
* @category Internal
* @param {Function} fn ramda implemtation
* @param {String} methodname property to check for a custom implementation
* @return {Object} whatever the return value of the method is
*/
function checkForMethod(methodname, fn) {
return function(a, b, c) {
var length = arguments.length;
var obj = arguments[length - 1],
callBound = obj && !isArray(obj) && typeof obj[methodname] === 'function';
switch (arguments.length) {
case 0: return fn();
case 1: return callBound ? obj[methodname]() : fn(a);
case 2: return callBound ? obj[methodname](a) : fn(a, b);
case 3: return callBound ? obj[methodname](a, b) : fn(a, b, c);
}
};
}
/**
* Wraps a function of any arity (including nullary) in a function that accepts exactly `n`
* parameters. Any extraneous parameters will not be passed to the supplied function.
*
* @func
* @memberOf R
* @category Function
* @sig Number -> (* -> a) -> (* -> a)
* @param {number} n The desired arity of the new function.
* @param {Function} fn The function to wrap.
* @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of
* arity `n`.
* @example
*
* var takesTwoArgs = function(a, b) {
* return [a, b];
* };
* takesTwoArgs.length; //=> 2
* takesTwoArgs(1, 2); //=> [1, 2]
*
* var takesOneArg = R.nAry(1, takesTwoArgs);
* takesOneArg.length; //=> 1
* // Only `n` arguments are passed to the wrapped function
* takesOneArg(1, 2); //=> [1, undefined]
*/
var nAry = R.nAry = function(n, fn) {
switch (n) {
case 0: return function() {return fn.call(this);};
case 1: return function(a0) {return fn.call(this, a0);};
case 2: return function(a0, a1) {return fn.call(this, a0, a1);};
case 3: return function(a0, a1, a2) {return fn.call(this, a0, a1, a2);};
case 4: return function(a0, a1, a2, a3) {return fn.call(this, a0, a1, a2, a3);};
case 5: return function(a0, a1, a2, a3, a4) {return fn.call(this, a0, a1, a2, a3, a4);};
case 6: return function(a0, a1, a2, a3, a4, a5) {return fn.call(this, a0, a1, a2, a3, a4, a5);};
case 7: return function(a0, a1, a2, a3, a4, a5, a6) {return fn.call(this, a0, a1, a2, a3, a4, a5, a6);};
case 8: return function(a0, a1, a2, a3, a4, a5, a6, a7) {return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7);};
case 9: return function(a0, a1, a2, a3, a4, a5, a6, a7, a8) {return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7, a8);};
case 10: return function(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) {return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9);};
default: return fn; // TODO: or throw?
}
};
/**
* Wraps a function of any arity (including nullary) in a function that accepts exactly 1
* parameter. Any extraneous parameters will not be passed to the supplied function.
*
* @func
* @memberOf R
* @category Function
* @sig (* -> b) -> (a -> b)
* @param {Function} fn The function to wrap.
* @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of
* arity 1.
* @example
*
* var takesTwoArgs = function(a, b) {
* return [a, b];
* };
* takesTwoArgs.length; //=> 2
* takesTwoArgs(1, 2); //=> [1, 2]
*
* var takesOneArg = R.unary(takesTwoArgs);
* takesOneArg.length; //=> 1
* // Only 1 argument is passed to the wrapped function
* takesOneArg(1, 2); //=> [1, undefined]
*/
R.unary = function _unary(fn) {
return nAry(1, fn);
};
/**
* Wraps a function of any arity (including nullary) in a function that accepts exactly 2
* parameters. Any extraneous parameters will not be passed to the supplied function.
*
* @func
* @memberOf R
* @category Function
* @sig (* -> c) -> (a, b -> c)
* @param {Function} fn The function to wrap.
* @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of
* arity 2.
* @example
*
* var takesThreeArgs = function(a, b, c) {
* return [a, b, c];
* };
* takesThreeArgs.length; //=> 3
* takesThreeArgs(1, 2, 3); //=> [1, 2, 3]
*
* var takesTwoArgs = R.binary(takesThreeArgs);
* takesTwoArgs.length; //=> 2
* // Only 2 arguments are passed to the wrapped function
* takesTwoArgs(1, 2, 3); //=> [1, 2, undefined]
*/
var binary = R.binary = function _binary(fn) {
return nAry(2, fn);
};
/**
* Wraps a function of any arity (including nullary) in a function that accepts exactly `n`
* parameters. Unlike `nAry`, which passes only `n` arguments to the wrapped function,
* functions produced by `arity` will pass all provided arguments to the wrapped function.
*
* @func
* @memberOf R
* @sig (Number, (* -> *)) -> (* -> *)
* @category Function
* @param {number} n The desired arity of the returned function.
* @param {Function} fn The function to wrap.
* @return {Function} A new function wrapping `fn`. The new function is
* guaranteed to be of arity `n`.
* @example
*
* var takesTwoArgs = function(a, b) {
* return [a, b];
* };
* takesTwoArgs.length; //=> 2
* takesTwoArgs(1, 2); //=> [1, 2]
*
* var takesOneArg = R.arity(1, takesTwoArgs);
* takesOneArg.length; //=> 1
* // All arguments are passed through to the wrapped function
* takesOneArg(1, 2); //=> [1, 2]
*/
var arity = R.arity = function(n, fn) {
switch (n) {
case 0: return function() {return fn.apply(this, arguments);};
case 1: return function(a0) {void a0; return fn.apply(this, arguments);};
case 2: return function(a0, a1) {void a1; return fn.apply(this, arguments);};
case 3: return function(a0, a1, a2) {void a2; return fn.apply(this, arguments);};
case 4: return function(a0, a1, a2, a3) {void a3; return fn.apply(this, arguments);};
case 5: return function(a0, a1, a2, a3, a4) {void a4; return fn.apply(this, arguments);};
case 6: return function(a0, a1, a2, a3, a4, a5) {void a5; return fn.apply(this, arguments);};
case 7: return function(a0, a1, a2, a3, a4, a5, a6) {void a6; return fn.apply(this, arguments);};
case 8: return function(a0, a1, a2, a3, a4, a5, a6, a7) {void a7; return fn.apply(this, arguments);};
case 9: return function(a0, a1, a2, a3, a4, a5, a6, a7, a8) {void a8; return fn.apply(this, arguments);};
case 10: return function(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) {void a9; return fn.apply(this, arguments);};
default: return fn; // TODO: or throw?
}
};
/**
* Turns a named method of an object (or object prototype) into a function that can be
* called directly. Passing the optional `len` parameter restricts the returned function to
* the initial `len` parameters of the method.
*
* The returned function is curried and accepts `len + 1` parameters (or `method.length + 1`
* when `len` is not specified), and the final parameter is the target object.
*
* @func
* @memberOf R
* @category Function
* @sig (String, Object, Number) -> (* -> *)
* @param {string} name The name of the method to wrap.
* @param {Object} obj The object to search for the `name` method.
* @param [len] The desired arity of the wrapped method.
* @return {Function} A new function or `undefined` if the specified method is not found.
* @example
*
* var charAt = R.invoker('charAt', String.prototype);
* charAt(6, 'abcdefghijklm'); //=> 'g'
*
* var join = R.invoker('join', Array.prototype);
* var firstChar = charAt(0);
* join('', R.map(firstChar, ['light', 'ampliifed', 'stimulated', 'emission', 'radiation']));
* //=> 'laser'
*/
var invoker = R.invoker = function _invoker(name, obj, len) {
var method = obj[name];
var length = len === void 0 ? method.length : len;
return method && curryN(length + 1, function() {
if (arguments.length) {
var target = Array.prototype.pop.call(arguments);
var targetMethod = target[name];
if (targetMethod == method) {
return targetMethod.apply(target, arguments);
}
}
});
};
/**
* Accepts a function `fn` and any number of transformer functions and returns a new
* function. When the new function is invoked, it calls the function `fn` with parameters
* consisting of the result of calling each supplied handler on successive arguments to the
* new function. For example:
*
* ```javascript
* var useWithExample = R.useWith(someFn, transformerFn1, transformerFn2);
*
* // This invocation:
* useWithExample('x', 'y');
* // Is functionally equivalent to:
* someFn(transformerFn1('x'), transformerFn2('y'))
* ```
*
* If more arguments are passed to the returned function than transformer functions, those
* arguments are passed directly to `fn` as additional parameters. If you expect additional
* arguments that don't need to be transformed, although you can ignore them, it's best to
* pass an identity function so that the new function reports the correct arity.
*
* @func
* @memberOf R
* @category Function
* @sig ((* -> *), (* -> *)...) -> (* -> *)
* @param {Function} fn The function to wrap.
* @param {...Function} transformers A variable number of transformer functions
* @return {Function} The wrapped function.
* @example
*
* var double = function(y) { return y * 2; };
* var square = function(x) { return x * x; };
* var add = function(a, b) { return a + b; };
* // Adds any number of arguments together
* var addAll = function() {
* return R.reduce(add, 0, arguments);
* };
*
* // Basic example
* var addDoubleAndSquare = R.useWith(addAll, double, square);
*
* //≅ addAll(double(10), square(5));
* addDoubleAndSquare(10, 5); //=> 45
*
* // Example of passing more arguments than transformers
* //≅ addAll(double(10), square(5), 100);
* addDoubleAndSquare(10, 5, 100); //=> 145
*
* // But if you're expecting additional arguments that don't need transformation, it's best
* // to pass transformer functions so the resulting function has the correct arity
* var addDoubleAndSquareWithExtraParams = R.useWith(addAll, double, square, R.identity);
* //≅ addAll(double(10), square(5), R.identity(100));
* addDoubleAndSquare(10, 5, 100); //=> 145
*/
var useWith = R.useWith = function _useWith(fn /*, transformers */) {
var transformers = _slice(arguments, 1);
var tlen = transformers.length;
return curry(arity(tlen, function() {
var args = [], idx = -1;
while (++idx < tlen) {
args.push(transformers[idx](arguments[idx]));
}
return fn.apply(this, args.concat(_slice(arguments, tlen)));
}));
};
/**
* Iterate over an input `list`, calling a provided function `fn` for each element in the
* list.
*
* `fn` receives one argument: *(value)*.
*
* Note: `R.forEach` does not skip deleted or unassigned indices (sparse arrays), unlike
* the native `Array.prototype.forEach` method. For more details on this behavior, see:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Description
*
* Also note that, unlike `Array.prototype.forEach`, Ramda's `forEach` returns the original
* array. In some libraries this function is named `each`.
*
* @func
* @memberOf R
* @category List
* @sig (a -> *) -> [a] -> [a]
* @param {Function} fn The function to invoke. Receives one argument, `value`.
* @param {Array} list The list to iterate over.
* @return {Array} The original list.
* @example
*
* var printXPlusFive = function(x) { console.log(x + 5); };
* R.forEach(printXPlusFive, [1, 2, 3]); //=> [1, 2, 3]
* //-> 6
* //-> 7
* //-> 8
*/
function forEach(fn, list) {
var idx = -1, len = list.length;
while (++idx < len) {
fn(list[idx]);
}
// i can't bear not to return *something*
return list;
}
R.forEach = curry2(forEach);
/**
* Like `forEach`, but but passes additional parameters to the predicate function.
*
* `fn` receives three arguments: *(value, index, list)*.
*
* Note: `R.forEach.idx` does not skip deleted or unassigned indices (sparse arrays),
* unlike the native `Array.prototype.forEach` method. For more details on this behavior,
* see:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Description
*
* Also note that, unlike `Array.prototype.forEach`, Ramda's `forEach` returns the original
* array. In some libraries this function is named `each`.
*
* @func
* @memberOf R
* @category List
* @sig (a, i, [a] -> ) -> [a] -> [a]
* @param {Function} fn The function to invoke. Receives three arguments:
* (`value`, `index`, `list`).
* @param {Array} list The list to iterate over.
* @return {Array} The original list.
* @alias forEach.idx
* @example
*
* // Note that having access to the original `list` allows for
* // mutation. While you *can* do this, it's very un-functional behavior:
* var plusFive = function(num, idx, list) { list[idx] = num + 5 };
* R.forEach.idx(plusFive, [1, 2, 3]); //=> [6, 7, 8]
*/
R.forEach.idx = curry2(function forEachIdx(fn, list) {
var idx = -1, len = list.length;
while (++idx < len) {
fn(list[idx], idx, list);
}
// i can't bear not to return *something*
return list;
});
/**
* Creates a shallow copy of an array.
*
* @func
* @memberOf R
* @category Array
* @sig [a] -> [a]
* @param {Array} list The list to clone.
* @return {Array} A new copy of the original list.
* @example
*
* var numbers = [1, 2, 3];
* var numbersClone = R.clone(numbers); //=> [1, 2, 3]
* numbers === numbersClone; //=> false
*
* // Note that this is a shallow clone--it does not clone complex values:
* var objects = [{}, {}, {}];
* var objectsClone = R.clone(objects);
* objects[0] === objectsClone[0]; //=> true
*/
var clone = R.clone = function _clone(list) {
return _slice(list);
};
// Core Functions
// --------------
//
/**
* Reports whether an array is empty.
*
* @func
* @memberOf R
* @category Array
* @sig [a] -> Boolean
* @param {Array} list The array to consider.
* @return {boolean} `true` if the `list` argument has a length of 0 or
* if `list` is a falsy value (e.g. undefined).
* @example
*
* R.isEmpty([1, 2, 3]); //=> false
* R.isEmpty([]); //=> true
* R.isEmpty(); //=> true
* R.isEmpty(null); //=> true
*/
function isEmpty(list) {
return !list || !list.length;
}
R.isEmpty = isEmpty;
/**
* Returns a new list with the given element at the front, followed by the contents of the
* list.
*
* @func
* @memberOf R
* @category Array
* @sig a -> [a] -> [a]
* @param {*} el The item to add to the head of the output list.
* @param {Array} list The array to add to the tail of the output list.
* @return {Array} A new array.
* @example
*
* R.prepend('fee', ['fi', 'fo', 'fum']); //=> ['fee', 'fi', 'fo', 'fum']
*/
R.prepend = curry2(function prepend(el, list) {
return concat([el], list);
});
/**
* @func
* @memberOf R
* @category Array
* @see R.prepend
*/
R.cons = R.prepend;
/**
* Returns the first element in a list.
* In some libraries this function is named `first`.
*
* @func
* @memberOf R
* @category Array
* @sig [a] -> a
* @param {Array} [list=[]] The array to consider.
* @return {*} The first element of the list, or `undefined` if the list is empty.
* @example
*
* R.head(['fi', 'fo', 'fum']); //=> 'fi'
*/
R.head = function head(list) {
list = list || [];
return list[0];
};
/**
* @func
* @memberOf R
* @category Array
* @see R.head
*/
R.car = R.head;
/**
* Returns the last element from a list.
*
* @func
* @memberOf R
* @category Array
* @sig [a] -> a
* @param {Array} [list=[]] The array to consider.
* @return {*} The last element of the list, or `undefined` if the list is empty.
* @example
*
* R.last(['fi', 'fo', 'fum']); //=> 'fum'
*/
R.last = function _last(list) {
list = list || [];
return list[list.length - 1];
};
/**
* Returns all but the first element of a list. If the list provided has the `tail` method,
* it will instead return `list.tail()`.
*
* @func
* @memberOf R
* @category Array
* @sig [a] -> [a]
* @param {Array} [list=[]] The array to consider.
* @return {Array} A new array containing all but the first element of the input list, or an
* empty list if the input list is a falsy value (e.g. `undefined`).
* @example
*
* R.tail(['fi', 'fo', 'fum']); //=> ['fo', 'fum']
*/
R.tail = checkForMethod('tail', function(list) {
list = list || [];
return (list.length > 1) ? _slice(list, 1) : [];
});
/**
* @func
* @memberOf R
* @category Array
* @see R.tail
*/
R.cdr = R.tail;
/**
* Returns a new list containing the contents of the given list, followed by the given
* element.
*
* @func
* @memberOf R
* @category Array
* @sig a -> [a] -> [a]
* @param {*} el The element to add to the end of the new list.
* @param {Array} list The list whose contents will be added to the beginning of the output
* list.
* @return {Array} A new list containing the contents of the old list followed by `el`.
* @example
*
* R.append('tests', ['write', 'more']); //=> ['write', 'more', 'tests']
* R.append('tests', []); //=> ['tests']
* R.append(['tests'], ['write', 'more']); //=> ['write', 'more', ['tests']]
*/
var append = R.append = curry2(function _append(el, list) {
return concat(list, [el]);
});
/**
* @func
* @memberOf R
* @category Array
* @see R.append
*/
R.push = R.append;
/**
* Returns a new list consisting of the elements of the first list followed by the elements
* of the second.
*
* @func
* @memberOf R
* @category Array
* @sig [a] -> [a] -> [a]
* @param {Array} list1 The first list to merge.
* @param {Array} list2 The second set to merge.
* @return {Array} A new array consisting of the contents of `list1` followed by the
* contents of `list2`. If, instead of an {Array} for `list1`, you pass an
* object with a `concat` method on it, `concat` will call `list1.concat`
* and it the value of `list2`.
* @example
*
* R.concat([], []); //=> []
* R.concat([4, 5, 6], [1, 2, 3]); //=> [4, 5, 6, 1, 2, 3]
* R.concat('ABC', 'DEF'); // 'ABCDEF'
*/
R.concat = curry2(function(set1, set2) {
if (isArray(set2)) {
return concat(set1, set2);
} else if (R.is(String, set1)) {
return set1.concat(set2);
} else if (hasMethod('concat', set2)) {
return set2.concat(set1);
} else {
throw new TypeError("can't concat " + typeof set2);
}
});
/**
* A function that does nothing but return the parameter supplied to it. Good as a default
* or placeholder function.
*
* @func
* @memberOf R
* @category Core
* @sig a -> a
* @param {*} x The value to return.
* @return {*} The input value, `x`.
* @example
*
* R.identity(1); //=> 1
*
* var obj = {};
* R.identity(obj) === obj; //=> true
*/
var identity = R.identity = function _I(x) {
return x;
};
/**
* @func
* @memberOf R
* @category Core
* @see R.identity
*/
R.I = R.identity;
/**
* Calls an input function `n` times, returning an array containing the results of those
* function calls.
*
* `fn` is passed one argument: The current value of `n`, which begins at `0` and is
* gradually incremented to `n - 1`.
*
* @func
* @memberOf R
* @category List
* @sig (i -> a) -> i -> [a]
* @param {Function} fn The function to invoke. Passed one argument, the current value of `n`.
* @param {number} n A value between `0` and `n - 1`. Increments after each function call.
* @return {Array} An array containing the return values of all calls to `fn`.
* @example
*
* R.times(R.identity, 5); //=> [0, 1, 2, 3, 4]
*/
R.times = curry2(function _times(fn, n) {
var list = new Array(n);
var idx = -1;
while (++idx < n) {
list[idx] = fn(idx);
}
return list;
});
/**
* Returns a fixed list of size `n` containing a specified identical value.
*
* @func
* @memberOf R
* @category Array
* @sig a -> n -> [a]
* @param {*} value The value to repeat.
* @param {number} n The desired size of the output list.
* @return {Array} A new array containing `n` `value`s.
* @example
*
* R.repeatN('hi', 5); //=> ['hi', 'hi', 'hi', 'hi', 'hi']
*
* var obj = {};
* var repeatedObjs = R.repeatN(obj, 5); //=> [{}, {}, {}, {}, {}]
* repeatedObjs[0] === repeatedObjs[1]; //=> true
*/
R.repeatN = curry2(function _repeatN(value, n) {
return R.times(R.always(value), n);
});
// Function functions :-)
// ----------------------
//
// These functions make new functions out of old ones.
// --------
/**
* Basic, right-associative composition function. Accepts two functions and returns the
* composite function; this composite function represents the operation `var h = f(g(x))`,
* where `f` is the first argument, `g` is the second argument, and `x` is whatever
* argument(s) are passed to `h`.
*
* This function's main use is to build the more general `compose` function, which accepts
* any number of functions.
*
* @private
* @category Function
* @param {Function} f A function.
* @param {Function} g A function.
* @return {Function} A new function that is the equivalent of `f(g(x))`.
* @example
*
* var double = function(x) { return x * 2; };
* var square = function(x) { return x * x; };
* var squareThenDouble = internalCompose(double, square);
*
* squareThenDouble(5); //≅ double(square(5)) => 50
*/
function internalCompose(f, g) {
return function() {
return f.call(this, g.apply(this, arguments));
};
}
/**
* Creates a new function that runs each of the functions supplied as parameters in turn,
* passing the return value of each function invocation to the next function invocation,
* beginning with whatever arguments were passed to the initial invocation.
*
* Note that `compose` is a right-associative function, which means the functions provided
* will be invoked in order from right to left. In the example `var h = compose(f, g)`,
* the function `h` is equivalent to `f( g(x) )`, where `x` represents the arguments
* originally passed to `h`.
*
* @func
* @memberOf R
* @category Function
* @sig ((y -> z), (x -> y), ..., (b -> c), (a... -> b)) -> (a... -> z)
* @param {...Function} functions A variable number of functions.
* @return {Function} A new function which represents the result of calling each of the
* input `functions`, passing the result of each function call to the next, from
* right to left.
* @example
*
* var triple = function(x) { return x * 3; };
* var double = function(x) { return x * 2; };
* var square = function(x) { return x * x; };
* var squareThenDoubleThenTriple = R.compose(triple, double, square);
*
* //≅ triple(double(square(5)))
* squareThenDoubleThenTriple(5); //=> 150
*/
var compose = R.compose = function _compose() {
switch (arguments.length) {
case 0: throw NO_ARGS_EXCEPTION;
case 1: return arguments[0];
default:
var idx = arguments.length - 1, fn = arguments[idx], length = fn.length;
while (idx--) {
fn = internalCompose(arguments[idx], fn);
}
return arity(length, fn);
}
};
/**
* Creates a new function that runs each of the functions supplied as parameters in turn,
* passing the return value of each function invocation to the next function invocation,
* beginning with whatever arguments were passed to the initial invocation.
*
* `pipe` is the mirror version of `compose`. `pipe` is left-associative, which means that
* each of the functions provided is executed in order from left to right.
*
* In some libraries this function is named `sequence`.
* @func
* @memberOf R
* @category Function
* @sig ((a... -> b), (b -> c), ..., (x -> y), (y -> z)) -> (a... -> z)
* @param {...Function} functions A variable number of functions.
* @return {Function} A new function which represents the result of calling each of the
* input `functions`, passing the result of each function call to the next, from
* right to left.
* @example
*
* var triple = function(x) { return x * 3; };
* var double = function(x) { return x * 2; };
* var square = function(x) { return x * x; };
* var squareThenDoubleThenTriple = R.pipe(square, double, triple);
*
* //≅ triple(double(square(5)))
* squareThenDoubleThenTriple(5); //=> 150
*/
R.pipe = function _pipe() {
return compose.apply(this, _slice(arguments).reverse());
};
/**
* Returns a new function much like the supplied one, except that the first two arguments'
* order is reversed.
*
* @func
* @memberOf R
* @category Function
* @sig (a -> b -> c -> ... -> z) -> (b -> a -> c -> ... -> z)
* @param {Function} fn The function to invoke with its first two parameters reversed.
* @return {*} The result of invoking `fn` with its first two parameters' order reversed.
* @example
*
* var mergeThree = function(a, b, c) {
* return ([]).concat(a, b, c);
* };
*
* mergeThree(1, 2, 3); //=> [1, 2, 3]
*
* R.flip(mergeThree)(1, 2, 3); //=> [2, 1, 3]
*/
var flip = R.flip = function _flip(fn) {
return function(a, b) {
switch (arguments.length) {
case 0: throw NO_ARGS_EXCEPTION;
case 1: return function(b) { return fn.apply(this, [b, a].concat(_slice(arguments, 1))); };
default: return fn.apply(this, concat([b, a], _slice(arguments, 2)));
}
};
};
/**
* Accepts as its arguments a function and any number of values and returns a function that,
* when invoked, calls the original function with all of the values prepended to the
* original function's arguments list. In some libraries this function is named `applyLeft`.
*
* @func
* @memberOf R
* @category Function
* @sig (a -> b -> ... -> i -> j -> ... -> m -> n) -> a -> b-> ... -> i -> (j -> ... -> m -> n)
* @param {Function} fn The function to invoke.
* @param {...*} [args] Arguments to prepend to `fn` when the returned function is invoked.
* @return {Function} A new function wrapping `fn`. When invoked, it will call `fn`
* with `args` prepended to `fn`'s arguments list.
* @example
*
* var multiply = function(a, b) { return a * b; };
* var double = R.lPartial(multiply, 2);
* double(2); //=> 4
*
* var greet = function(salutation, title, firstName, lastName) {
* return salutation + ', ' + title + ' ' + firstName + ' ' + lastName + '!';
* };
* var sayHello = R.lPartial(greet, 'Hello');
* var sayHelloToMs = R.lPartial(sayHello, 'Ms.');
* sayHelloToMs('Jane', 'Jones'); //=> 'Hello, Ms. Jane Jones!'
*/
R.lPartial = function _lPartial(fn /*, args */) {
var args = _slice(arguments, 1);
return arity(Math.max(fn.length - args.length, 0), function() {
return fn.apply(this, concat(args, arguments));
});
};
/**
* Accepts as its arguments a function and any number of values and returns a function that,
* when invoked, calls the original function with all of the values appended to the original
* function's arguments list.
*
* Note that `rPartial` is the opposite of `lPartial`: `rPartial` fills `fn`'s arguments
* from the right to the left. In some libraries this function is named `applyRight`.
*
* @func
* @memberOf R
* @category Function
* @sig (a -> b-> ... -> i -> j -> ... -> m -> n) -> j -> ... -> m -> n -> (a -> b-> ... -> i)
* @param {Function} fn The function to invoke.
* @param {...*} [args] Arguments to append to `fn` when the returned function is invoked.
* @return {Function} A new function wrapping `fn`. When invoked, it will call `fn` with
* `args` appended to `fn`'s arguments list.
* @example
*
* var greet = function(salutation, title, firstName, lastName) {
* return salutation + ', ' + title + ' ' + firstName + ' ' + lastName + '!';
* };
* var greetMsJaneJones = R.rPartial(greet, 'Ms.', 'Jane', 'Jones');
*
* greetMsJaneJones('Hello'); //=> 'Hello, Ms. Jane Jones!'
*/
R.rPartial = function _rPartial(fn) {
var args = _slice(arguments, 1);
return arity(Math.max(fn.length - args.length, 0), function() {
return fn.apply(this, concat(arguments, args));
});
};
/**
* Creates a new function that, when invoked, caches the result of calling `fn` for a given
* argument set and returns the result. Subsequent calls to the memoized `fn` with the same
* argument set will not result in an additional call to `fn`; instead, the cached result
* for that set of arguments will be returned.
*
* Note that this version of `memoize` effectively handles only string and number
* parameters. Also note that it does not work on variadic functions.
*
* @func
* @memberOf R
* @category Function
* @sig (a... -> b) -> (a... -> b)
* @param {Function} fn The function to be wrapped by `memoize`.
* @return {Function} Returns a memoized version of `fn`.
* @example
*
* var numberOfCalls = 0;
* var trackedAdd = function(a, b) {
* numberOfCalls += 1;
* return a + b;
* };
* var memoTrackedAdd = R.memoize(trackedAdd);
*
* memoTrackedAdd(1, 2); //=> 3
* numberOfCalls; //=> 1
* memoTrackedAdd(1, 2); //=> 3
* numberOfCalls; //=> 1
* memoTrackedAdd(2, 3); //=> 5
* numberOfCalls; //=> 2
*
* // Note that argument order matters
* memoTrackedAdd(2, 1); //=> 3
* numberOfCalls; //=> 3
*/
R.memoize = function _memoize(fn) {
if (!fn.length) {
return once(fn);
}
var cache = {};
return function() {
if (!arguments.length) {return;}
var position = foldl(function(cache, arg) {
return cache[arg] || (cache[arg] = {});
}, cache, _slice(arguments, 0, arguments.length - 1));
var arg = arguments[arguments.length - 1];
return (position[arg] || (position[arg] = fn.apply(this, arguments)));
};
};
/**
* Accepts a function `fn` and returns a function that guards invocation of `fn` such that
* `fn` can only ever be called once, no matter how many times the returned function is
* invoked.
*
* @func
* @memberOf R
* @category Function
* @sig (a... -> b) -> (a... -> b)
* @param {Function} fn The function to wrap in a call-only-once wrapper.
* @return {Function} The wrapped function.
* @example
*
* var addOneOnce = R.once(function(x){ return x + 1; });
* addOneOnce(10); //=> 11
* addOneOnce(addOneOnce(50)); //=> 11
*/
var once = R.once = function _once(fn) {
var called = false, result;
return function() {
if (called) {
return result;
}
called = true;
result = fn.apply(this, arguments);
return result;
};
};
/**
* Wrap a function inside another to allow you to make adjustments to the parameters, or do
* other processing either before the internal function is called or with its results.
*
* @func
* @memberOf R
* @category Function
* ((* -> *) -> ((* -> *), a...) -> (*, a... -> *)
* @param {Function} fn The function to wrap.
* @param {Function} wrapper The wrapper function.
* @return {Function} The wrapped function.
* @example
*
* var slashify = R.wrap(R.flip(add)('/'), function(f, x) {
* return R.match(/\/$/, x) ? x : f(x);
* });
*
* slashify('a'); //=> 'a/'
* slashify('a/'); //=> 'a/'
*/
R.wrap = function _wrap(fn, wrapper) {
return function() {
return wrapper.apply(this, concat([fn], arguments));
};
};
/**
* Wraps a constructor function inside a curried function that can be called with the same
* arguments and returns the same type. The arity of the function returned is specified
* to allow using variadic constructor functions.
*
* NOTE: Does not work with some built-in objects such as Date.
*
* @func
* @memberOf R
* @category Function
* @sig Number -> (* -> {*}) -> (* -> {*})
* @param {number} n The arity of the constructor function.
* @param {Function} Fn The constructor function to wrap.
* @return {Function} A wrapped, curried constructor function.
* @example
*
* // Variadic constructor function
* var Widget = function() {
* this.children = Array.prototype.slice.call(arguments);
* // ...
* };
* Widget.prototype = {
* // ...
* };
* var allConfigs = {
* // ...
* };
* R.map(R.constructN(1, Widget), allConfigs); // a list of Widgets
*/
var constructN = R.constructN = curry2(function _constructN(n, Fn) {
var f = function() {
var Temp = function() {}, inst, ret;
Temp.prototype = Fn.prototype;
inst = new Temp();
ret = Fn.apply(inst, arguments);
return Object(ret) === ret ? ret : inst;
};
return n > 1 ? curry(nAry(n, f)) : f;
});
/**
* Wraps a constructor function inside a curried function that can be called with the same
* arguments and returns the same type.
*
* NOTE: Does not work with some built-in objects such as Date.
*
* @func
* @memberOf R
* @category Function
* @sig (* -> {*}) -> (* -> {*})
* @param {Function} Fn The constructor function to wrap.
* @return {Function} A wrapped, curried constructor function.
* @example
*
* // Constructor function
* var Widget = function(config) {
* // ...
* };
* Widget.prototype = {
* // ...
* };
* var allConfigs = {
* // ...
* };
* R.map(R.construct(Widget), allConfigs); // a list of Widgets
*/
R.construct = function _construct(Fn) {
return constructN(Fn.length, Fn);
};
/**
* Accepts three functions and returns a new function. When invoked, this new function will
* invoke the first function, `after`, passing as its arguments the results of invoking the
* second and third functions with whatever arguments are passed to the new function.
*
* For example, a function produced by `converge` is equivalent to:
*
* ```javascript
* var h = R.converge(e, f, g);
* h(1, 2); //≅ e( f(1, 2), g(1, 2) )
* ```
*
* @func
* @memberOf R
* @category Function
* @sig ((a, b -> c) -> (((* -> a), (* -> b), ...) -> c)
* @param {Function} after A function. `after` will be invoked with the return values of
* `fn1` and `fn2` as its arguments.
* @param {Function} fn1 A function. It will be invoked with the arguments passed to the
* returned function. Afterward, its resulting value will be passed to `after` as
* its first argument.
* @param {Function} fn2 A function. It will be invoked with the arguments passed to the
* returned function. Afterward, its resulting value will be passed to `after` as
* its second argument.
* @return {Function} A new function.
* @example
*
* var add = function(a, b) { return a + b; };
* var multiply = function(a, b) { return a * b; };
* var subtract = function(a, b) { return a - b; };
*
* //≅ multiply( add(1, 2), subtract(1, 2) );
* R.converge(multiply, add, subtract)(1, 2); //=> -3
*/
R.converge = function(after) {
var fns = _slice(arguments, 1);
return function() {
var args = arguments;
return after.apply(this, map(function(fn) {
return fn.apply(this, args);
}, fns));
};
};
// List Functions
// --------------
//
// These functions operate on logical lists, here plain arrays. Almost all of these are curried, and the list
// parameter comes last, so you can create a new function by supplying the preceding arguments, leaving the
// list parameter off. For instance:
//
// // skip third parameter
// var checkAllPredicates = reduce(andFn, alwaysTrue);
// // ... given suitable definitions of odd, lt20, gt5
// var test = checkAllPredicates([odd, lt20, gt5]);
// // test(7) => true, test(9) => true, test(10) => false,
// // test(3) => false, test(21) => false,
// --------
/**
* Returns a single item by iterating through the list, successively calling the iterator
* function and passing it an accumulator value and the current value from the array, and
* then passing the result to the next call.
*
* The iterator function receives two values: *(acc, value)*
*
* Note: `R.reduce` does not skip deleted or unassigned indices (sparse arrays), unlike
* the native `Array.prototype.reduce` method. For more details on this behavior, see:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Description
*
* @func
* @memberOf R
* @category List
* @sig (a,b -> a) -> a -> [b] -> a
* @param {Function} fn The iterator function. Receives two values, the accumulator and the
* current element from the array.
* @param {*} acc The accumulator value.
* @param {Array} list The list to iterate over.
* @return {*} The final, accumulated value.
* @example
*
* var numbers = [1, 2, 3];
* var add = function(a, b) {
* return a + b;
* };
*
* R.reduce(add, 10, numbers); //=> 16
*/
R.reduce = curry3(function _reduce(fn, acc, list) {
var idx = -1, len = list.length;
while (++idx < len) {
acc = fn(acc, list[idx]);
}
return acc;
});
/**
* @func
* @memberOf R
* @category List
* @see R.reduce
*/
var foldl = R.foldl = R.reduce;
/**
* Like `reduce`, but passes additional parameters to the predicate function.
*
* The iterator function receives four values: *(acc, value, index, list)*
*
* Note: `R.reduce.idx` does not skip deleted or unassigned indices (sparse arrays),
* unlike the native `Array.prototype.reduce` method. For more details on this behavior,
* see:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Description
*
* @func
* @memberOf R
* @category List
* @sig (a,b,i,[b] -> a) -> a -> [b] -> a
* @param {Function} fn The iterator function. Receives four values: the accumulator, the
* current element from `list`, that element's index, and the entire `list` itself.
* @param {*} acc The accumulator value.
* @param {Array} list The list to iterate over.
* @return {*} The final, accumulated value.
* @alias reduce.idx
* @example
*
* var letters = ['a', 'b', 'c'];
* var objectify = function(accObject, elem, idx, list) {
* accObject[elem] = idx;
* return accObject;
* };
*
* R.reduce.idx(objectify, {}, letters); //=> { 'a': 0, 'b': 1, 'c': 2 }
*/
R.reduce.idx = curry3(function _reduceIdx(fn, acc, list) {
var idx = -1, len = list.length;
while (++idx < len) {
acc = fn(acc, list[idx], idx, list);
}
return acc;
});
/**
* @func
* @memberOf R
* @category List
* @alias foldl.idx
* @see R.reduce.idx
*/
R.foldl.idx = R.reduce.idx;
/**
* Returns a single item by iterating through the list, successively calling the iterator
* function and passing it an accumulator value and the current value from the array, and
* then passing the result to the next call.
*
* Similar to `reduce`, except moves through the input list from the right to the left.
*
* The iterator function receives two values: *(acc, value)*
*
* Note: `R.reduce` does not skip deleted or unassigned indices (sparse arrays), unlike
* the native `Array.prototype.reduce` method. For more details on this behavior, see:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Description
*
* @func
* @memberOf R
* @category List
* @sig (a,b -> a) -> a -> [b] -> a
* @param {Function} fn The iterator function. Receives two values, the accumulator and the
* current element from the array.
* @param {*} acc The accumulator value.
* @param {Array} list The list to iterate over.
* @return {*} The final, accumulated value.
* @example
*
* var pairs = [ ['a', 1], ['b', 2], ['c', 3] ];
* var flattenPairs = function(acc, pair) {
* return acc.concat(pair);
* };
*
* R.reduceRight(flattenPairs, [], pairs); //=> [ 'c', 3, 'b', 2, 'a', 1 ]
*/
R.reduceRight = curry3(checkForMethod('reduceRight', function _reduceRight(fn, acc, list) {
var idx = list.length;
while (idx--) {
acc = fn(acc, list[idx]);
}
return acc;
}));
/**
* @func
* @memberOf R
* @category List
* @see R.reduceRight
*/
R.foldr = R.reduceRight;
/**
* Like `reduceRight`, but passes additional parameters to the predicate function. Moves through
* the input list from the right to the left.
*
* The iterator function receives four values: *(acc, value, index, list)*.
*
* Note: `R.reduceRight.idx` does not skip deleted or unassigned indices (sparse arrays),
* unlike the native `Array.prototype.reduce` method. For more details on this behavior,
* see:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Description
*
* @func
* @memberOf R
* @category List
* @sig (a,b,i,[b] -> a -> [b] -> a
* @param {Function} fn The iterator function. Receives four values: the accumulator, the
* current element from `list`, that element's index, and the entire `list` itself.
* @param {*} acc The accumulator value.
* @param {Array} list The list to iterate over.
* @return {*} The final, accumulated value.
* @alias reduceRight.idx
* @example
*
* var letters = ['a', 'b', 'c'];
* var objectify = function(accObject, elem, idx, list) {
* accObject[elem] = idx;
* return accObject;
* };
*
* R.reduceRight.idx(objectify, {}, letters); //=> { 'c': 2, 'b': 1, 'a': 0 }
*/
R.reduceRight.idx = curry3(function _reduceRightIdx(fn, acc, list) {
var idx = list.length;
while (idx--) {
acc = fn(acc, list[idx], idx, list);
}
return acc;
});
/**
* @func
* @memberOf R
* @category List
* @alias foldr.idx
* @see R.reduceRight.idx
*/
R.foldr.idx = R.reduceRight.idx;
/**
* Builds a list from a seed value. Accepts an iterator function, which returns either false
* to stop iteration or an array of length 2 containing the value to add to the resulting
* list and the seed to be used in the next call to the iterator function.
*
* The iterator function receives one argument: *(seed)*.
*
* @func
* @memberOf R
* @category List
* @sig (a -> [b]) -> * -> [b]
* @param {Function} fn The iterator function. receives one argument, `seed`, and returns
* either false to quit iteration or an array of length two to proceed. The element
* at index 0 of this array will be added to the resulting array, and the element
* at index 1 will be passed to the next call to `fn`.
* @param {*} seed The seed value.
* @return {Array} The final list.
* @example
*
* var f = function(n) { return n > 50 ? false : [-n, n + 10] };
* R.unfoldr(f, 10); //=> [-10, -20, -30, -40, -50]
*/
R.unfoldr = curry2(function _unfoldr(fn, seed) {
var pair = fn(seed);
var result = [];
while (pair && pair.length) {
result.push(pair[0]);
pair = fn(pair[1]);
}
return result;
});
/**
* Returns a new list, constructed by applying the supplied function to every element of the
* supplied list.
*
* Note: `R.map` does not skip deleted or unassigned indices (sparse arrays), unlike the
* native `Array.prototype.map` method. For more details on this behavior, see:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Description
*
* @func
* @memberOf R
* @category List
* @sig (a -> b) -> [a] -> [b]
* @param {Function} fn The function to be called on every element of the input `list`.
* @param {Array} list The list to be iterated over.
* @return {Array} The new list.
* @example
*
* var double = function(x) {
* return x * 2;
* };
*
* R.map(double, [1, 2, 3]); //=> [2, 4, 6]
*/
function map(fn, list) {
var idx = -1, len = list.length, result = new Array(len);
while (++idx < len) {
result[idx] = fn(list[idx]);
}
return result;
}
R.map = curry2(checkForMethod('map', map));
/**
* Like `map`, but but passes additional parameters to the mapping function.
* `fn` receives three arguments: *(value, index, list)*.
*
* Note: `R.map.idx` does not skip deleted or unassigned indices (sparse arrays), unlike
* the native `Array.prototype.map` method. For more details on this behavior, see:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Description
*
* @func
* @memberOf R
* @category List
* @sig (a,i,[b] -> b) -> [a] -> [b]
* @param {Function} fn The function to be called on every element of the input `list`.
* @param {Array} list The list to be iterated over.
* @return {Array} The new list.
* @alias map.idx
* @example
*
* var squareEnds = function(elt, idx, list) {
* if (idx === 0 || idx === list.length - 1) {
* return elt * elt;
* }
* return elt;
* };
*
* R.map.idx(squareEnds, [8, 5, 3, 0, 9]); //=> [64, 5, 3, 0, 81]
*/
R.map.idx = curry2(function _mapIdx(fn, list) {
var idx = -1, len = list.length, result = new Array(len);
while (++idx < len) {
result[idx] = fn(list[idx], idx, list);
}
return result;
});
/**
* Map, but for objects. Creates an object with the same keys as `obj` and values
* generated by running each property of `obj` through `fn`. `fn` is passed one argument:
* *(value)*.
*
* @func
* @memberOf R
* @category List
* @sig (v -> v) -> {k: v} -> {k: v}
* @param {Function} fn A function called for each property in `obj`. Its return value will
* become a new property on the return object.
* @param {Object} obj The object to iterate over.
* @return {Object} A new object with the same keys as `obj` and values that are the result
* of running each property through `fn`.
* @example
*
* var values = { x: 1, y: 2, z: 3 };
* var double = function(num) {
* return num * 2;
* };
*
* R.mapObj(double, values); //=> { x: 2, y: 4, z: 6 }
*/
// TODO: consider mapObj.key in parallel with mapObj.idx. Also consider folding together with `map` implementation.
R.mapObj = curry2(function _mapObject(fn, obj) {
return foldl(function(acc, key) {
acc[key] = fn(obj[key]);
return acc;
}, {}, keys(obj));
});
/**
* Like `mapObj`, but but passes additional arguments to the predicate function. The
* predicate function is passed three arguments: *(value, key, obj)*.
*
* @func
* @memberOf R
* @category List
* @sig (v, k, {k: v} -> v) -> {k: v} -> {k: v}
* @param {Function} fn A function called for each property in `obj`. Its return value will
* become a new property on the return object.
* @param {Object} obj The object to iterate over.
* @return {Object} A new object with the same keys as `obj` and values that are the result
* of running each property through `fn`.
* @alias mapObj.idx
* @example
*
* var values = { x: 1, y: 2, z: 3 };
* var prependKeyAndDouble = function(num, key, obj) {
* return key + (num * 2);
* };
*
* R.mapObj.idx(prependKeyAndDouble, values); //=> { x: 'x2', y: 'y4', z: 'z6' }
*/
R.mapObj.idx = curry2(function mapObjectIdx(fn, obj) {
return foldl(function(acc, key) {
acc[key] = fn(obj[key], key, obj);
return acc;
}, {}, keys(obj));
});
/**
* ap applies a list of functions to a list of values.
*
* @func
* @memberOf R
* @category Function
* @sig [f] -> [a] -> [f a]
* @param {Array} fns An array of functions
* @param {Array} vs An array of values
* @return the value of applying each the function `fns` to each value in `vs`
* @example
*
* R.ap([R.multiply(2), R.add(3)], [1,2,3]); //=> [2, 4, 6, 4, 5, 6]
*/
R.ap = curry2(function _ap(fns, vs) {
return hasMethod('ap', fns) ? fns.ap(vs) : foldl(function(acc, fn) {
return concat(acc, map(fn, vs));
}, [], fns);
});
/**
*
* `of` wraps any object in an Array. This implementation is compatible with the
* Fantasy-land Applicative spec, and will work with types that implement that spec.
* Note this `of` is different from the ES6 `of`; See
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/of
*
* @func
* @memberOf R
* @category Function
* @sig a -> [a]
* @param {*} x any value
* @return [x]
* @example
*
* R.of(1); //=> [1]
* R.of([2]); //=> [[2]]
* R.of({}); //=> [{}]
*/
R.of = function _of(x, container) {
return (hasMethod('of', container)) ? container.of(x) : [x];
};
/**
* `empty` wraps any object in an array. This implementation is compatible with the
* Fantasy-land Monoid spec, and will work with types that implement that spec.
*
* @func
* @memberOf R
* @category Function
* @sig * -> []
* @return {Array} an empty array
* @example
*
* R.empty([1,2,3,4,5]); //=> []
*/
R.empty = function _empty(x) {
return (hasMethod('empty', x)) ? x.empty() : [];
};
/**
* `chain` maps a function over a list and concatenates the results.
* This implementation is compatible with the
* Fantasy-land Chain spec, and will work with types that implement that spec.
* `chain` is also known as `flatMap` in some libraries
*
* @func
* @memberOf R
* @category List
* @sig (a -> [b]) -> [a] -> [b]
* @param {Function} fn
* @param {Array} list
* @return {Array}
* @example
*
* var duplicate = function(n) {
* return [n, n];
* };
* R.chain(duplicate, [1, 2, 3]); //=> [1, 1, 2, 2, 3, 3]
*
*/
R.chain = curry2(checkForMethod('chain', function _chain(f, list) {
return unnest(map(f, list));
}));
/**
* Returns the number of elements in the array by returning `list.length`.
*
* @func
* @memberOf R
* @category List
* @sig [a] -> Number
* @param {Array} list The array to inspect.
* @return {number} The size of the array.
* @example
*
* R.size([]); //=> 0
* R.size([1, 2, 3]); //=> 3
*/
R.size = function _size(list) {
return list.length;
};
/**
* @func
* @memberOf R
* @category List
* @see R.size
*/
R.length = R.size;
/**
* Returns a new list containing only those items that match a given predicate function.
* The predicate function is passed one argument: *(value)*.
*
* Note that `R.filter` does not skip deleted or unassigned indices, unlike the native
* `Array.prototype.filter` method. For more details on this behavior, see:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#Description
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> [a]
* @param {Function} fn The function called per iteration.
* @param {Array} list The collection to iterate over.
* @return {Array} The new filtered array.
* @example
*
* var isEven = function(n) {
* return n % 2 === 0;
* };
* R.filter(isEven, [1, 2, 3, 4]); //=> [2, 4]
*/
var filter = function _filter(fn, list) {
var idx = -1, len = list.length, result = [];
while (++idx < len) {
if (fn(list[idx])) {
result.push(list[idx]);
}
}
return result;
};
R.filter = curry2(checkForMethod('filter', filter));
/**
* Like `filter`, but passes additional parameters to the predicate function. The predicate
* function is passed three arguments: *(value, index, list)*.
*
* @func
* @memberOf R
* @category List
* @sig (a, i, [a] -> Boolean) -> [a] -> [a]
* @param {Function} fn The function called per iteration.
* @param {Array} list The collection to iterate over.
* @return {Array} The new filtered array.
* @alias filter.idx
* @example
*
* var lastTwo = function(val, idx, list) {
* return list.length - idx <= 2;
* };
* R.filter.idx(lastTwo, [8, 6, 7, 5, 3, 0, 9]); //=> [0, 9]
*/
function filterIdx(fn, list) {
var idx = -1, len = list.length, result = [];
while (++idx < len) {
if (fn(list[idx], idx, list)) {
result.push(list[idx]);
}
}
return result;
}
R.filter.idx = curry2(filterIdx);
/**
* Similar to `filter`, except that it keeps only values for which the given predicate
* function returns falsy. The predicate function is passed one argument: *(value)*.
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> [a]
* @param {Function} fn The function called per iteration.
* @param {Array} list The collection to iterate over.
* @return {Array} The new filtered array.
* @example
*
* var isOdd = function(n) {
* return n % 2 === 1;
* };
* R.reject(isOdd, [1, 2, 3, 4]); //=> [2, 4]
*/
var reject = function _reject(fn, list) {
return filter(not(fn), list);
};
R.reject = curry2(reject);
/**
* Like `reject`, but passes additional parameters to the predicate function. The predicate
* function is passed three arguments: *(value, index, list)*.
*
* @func
* @memberOf R
* @category List
* @sig (a, i, [a] -> Boolean) -> [a] -> [a]
* @param {Function} fn The function called per iteration.
* @param {Array} list The collection to iterate over.
* @return {Array} The new filtered array.
* @alias reject.idx
* @example
*
* var lastTwo = function(val, idx, list) {
* return list.length - idx <= 2;
* };
*
* R.reject.idx(lastTwo, [8, 6, 7, 5, 3, 0, 9]); //=> [8, 6, 7, 5, 3]
*/
R.reject.idx = curry2(function _rejectIdx(fn, list) {
return filterIdx(not(fn), list);
});
/**
* Returns a new list containing the first `n` elements of a given list, passing each value
* to the supplied predicate function, and terminating when the predicate function returns
* `false`. Excludes the element that caused the predicate function to fail. The predicate
* function is passed one argument: *(value)*.
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> [a]
* @param {Function} fn The function called per iteration.
* @param {Array} list The collection to iterate over.
* @return {Array} A new array.
* @example
*
* var isNotFour = function(x) {
* return !(x === 4);
* };
*
* R.takeWhile(isNotFour, [1, 2, 3, 4]); //=> [1, 2, 3]
*/
R.takeWhile = curry2(checkForMethod('takeWhile', function(fn, list) {
var idx = -1, len = list.length;
while (++idx < len && fn(list[idx])) {}
return _slice(list, 0, idx);
}));
/**
* Returns a new list containing the first `n` elements of the given list. If
* `n > * list.length`, returns a list of `list.length` elements.
*
* @func
* @memberOf R
* @category List
* @sig Number -> [a] -> [a]
* @param {number} n The number of elements to return.
* @param {Array} list The array to query.
* @return {Array} A new array containing the first elements of `list`.
*/
R.take = curry2(checkForMethod('take', function(n, list) {
return _slice(list, 0, Math.min(n, list.length));
}));
/**
* Returns a new list containing the last `n` elements of a given list, passing each value
* to the supplied predicate function, beginning when the predicate function returns
* `true`. Excludes the element that caused the predicate function to fail. The predicate
* function is passed one argument: *(value)*.
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> [a]
* @param {Function} fn The function called per iteration.
* @param {Array} list The collection to iterate over.
* @return {Array} A new array.
* @example
*
* var isTwo = function(x) {
* return x === 2;
* };
*
* R.skipUntil(isTwo, [1, 2, 3, 4]); //=> [2, 3, 4]
*/
R.skipUntil = curry2(function _skipUntil(fn, list) {
var idx = -1, len = list.length;
while (++idx < len && !fn(list[idx])) {}
return _slice(list, idx);
});
/**
* Returns a new list containing all but the first `n` elements of the given `list`.
*
* @func
* @memberOf R
* @category List
* @sig Number -> [a] -> [a]
* @param {number} n The number of elements of `list` to skip.
* @param {Array} list The array to consider.
* @return {Array} The last `n` elements of `list`.
* @example
*
* R.skip(3, [1,2,3,4,5,6,7]); //=> [4,5,6,7]
*/
R.skip = curry2(checkForMethod('skip', function _skip(n, list) {
if (n < list.length) {
return _slice(list, n);
} else {
return [];
}
}));
/**
* Returns the first element of the list which matches the predicate, or `undefined` if no
* element matches.
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> a | undefined
* @param {Function} fn The predicate function used to determine if the element is the
* desired one.
* @param {Array} list The array to consider.
* @return {Object} The element found, or `undefined`.
* @example
*
* var xs = [{a: 1}, {a: 2}, {a: 3}];
* R.find(R.propEq('a', 2))(xs); //=> {a: 2}
* R.find(R.propEq('a', 4))(xs); //=> undefined
*/
R.find = curry2(function find(fn, list) {
var idx = -1;
var len = list.length;
while (++idx < len) {
if (fn(list[idx])) {
return list[idx];
}
}
});
/**
* Returns the index of the first element of the list which matches the predicate, or `-1`
* if no element matches.
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> Number
* @param {Function} fn The predicate function used to determine if the element is the
* desired one.
* @param {Array} list The array to consider.
* @return {number} The index of the element found, or `-1`.
* @example
*
* var xs = [{a: 1}, {a: 2}, {a: 3}];
* R.findIndex(R.propEq('a', 2))(xs); //=> 1
* R.findIndex(R.propEq('a', 4))(xs); //=> -1
*/
R.findIndex = curry2(function _findIndex(fn, list) {
var idx = -1;
var len = list.length;
while (++idx < len) {
if (fn(list[idx])) {
return idx;
}
}
return -1;
});
/**
* Returns the last element of the list which matches the predicate, or `undefined` if no
* element matches.
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> a | undefined
* @param {Function} fn The predicate function used to determine if the element is the
* desired one.
* @param {Array} list The array to consider.
* @return {Object} The element found, or `undefined`.
* @example
*
* var xs = [{a: 1, b: 0}, {a:1, b: 1}];
* R.findLast(R.propEq('a', 1))(xs); //=> {a: 1, b: 1}
* R.findLast(R.propEq('a', 4))(xs); //=> undefined
*/
R.findLast = curry2(function _findLast(fn, list) {
var idx = list.length;
while (idx--) {
if (fn(list[idx])) {
return list[idx];
}
}
});
/**
* Returns the index of the last element of the list which matches the predicate, or
* `-1` if no element matches.
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> Number
* @param {Function} fn The predicate function used to determine if the element is the
* desired one.
* @param {Array} list The array to consider.
* @return {number} The index of the element found, or `-1`.
* @example
*
* var xs = [{a: 1, b: 0}, {a:1, b: 1}];
* R.findLastIndex(R.propEq('a', 1))(xs); //=> 1
* R.findLastIndex(R.propEq('a', 4))(xs); //=> -1
*/
R.findLastIndex = curry2(function _findLastIndex(fn, list) {
var idx = list.length;
while (idx--) {
if (fn(list[idx])) {
return idx;
}
}
return -1;
});
/**
* Returns `true` if all elements of the list match the predicate, `false` if there are any
* that don't.
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> Boolean
* @param {Function} fn The predicate function.
* @param {Array} list The array to consider.
* @return {boolean} `true` if the predicate is satisfied by every element, `false`
* otherwise
* @example
*
* var lessThan2 = R.flip(R.lt)(2);
* var lessThan3 = R.flip(R.lt)(3);
* var xs = R.range(1, 3);
* xs; //=> [1, 2]
* R.every(lessThan2)(xs); //=> false
* R.every(lessThan3)(xs); //=> true
*/
function every(fn, list) {
var idx = -1;
while (++idx < list.length) {
if (!fn(list[idx])) {
return false;
}
}
return true;
}
R.every = curry2(every);
/**
* Returns `true` if at least one of elements of the list match the predicate, `false`
* otherwise.
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> Boolean
* @param {Function} fn The predicate function.
* @param {Array} list The array to consider.
* @return {boolean} `true` if the predicate is satisfied by at least one element, `false`
* otherwise
* @example
*
* var lessThan0 = R.flip(R.lt)(0);
* var lessThan2 = R.flip(R.lt)(2);
* var xs = R.range(1, 3);
* xs; //=> [1, 2]
* R.some(lessThan0)(xs); //=> false
* R.some(lessThan2)(xs); //=> true
*/
function some(fn, list) {
var idx = -1;
while (++idx < list.length) {
if (fn(list[idx])) {
return true;
}
}
return false;
}
R.some = curry2(some);
/**
* Internal implementation of `indexOf`.
* Returns the position of the first occurrence of an item in an array
* (by strict equality),
* or -1 if the item is not included in the array.
*
* @private
* @category Internal
* @param {Array} The array to search
* @param {*} item the item to find in the Array
* @param {Number} from (optional) the index to start searching the Array
* @return {Number} the index of the found item, or -1
*
*/
var indexOf = function _indexOf(list, item, from) {
var idx = 0, length = list.length;
if (typeof from == 'number') {
idx = from < 0 ? Math.max(0, length + from) : from;
}
for (; idx < length; idx++) {
if (list[idx] === item) {
return idx;
}
}
return -1;
};
/**
* Internal implementation of `lastIndexOf`.
* Returns the position of the last occurrence of an item in an array
* (by strict equality),
* or -1 if the item is not included in the array.
*
* @private
* @category Internal
* @param {Array} The array to search
* @param {*} item the item to find in the Array
* @param {Number} from (optional) the index to start searching the Array
* @return {Number} the index of the found item, or -1
*
*/
var lastIndexOf = function _lastIndexOf(list, item, from) {
var idx = list.length;
if (typeof from == 'number') {
idx = from < 0 ? idx + from + 1 : Math.min(idx, from + 1);
}
while (--idx >= 0) {
if (list[idx] === item) {
return idx;
}
}
return -1;
};
/**
* Returns the position of the first occurrence of an item in an array
* (by strict equality),
* or -1 if the item is not included in the array.
*
* @func
* @memberOf R
* @category List
* @sig a -> [a] -> Number
* @param {*} target The item to find.
* @param {Array} list The array to search in.
* @return {Number} the index of the target, or -1 if the target is not found.
*
* @example
*
* R.indexOf(3, [1,2,3,4]); //=> 2
* R.indexOf(10, [1,2,3,4]); //=> -1
*/
R.indexOf = curry2(function _indexOf(target, list) {
return indexOf(list, target);
});
/**
* Returns the position of the first occurrence of an item (by strict equality) in
* an array, or -1 if the item is not included in the array. However,
* `indexOf.from` will only search the tail of the array, starting from the
* `fromIdx` parameter.
*
* @func
* @memberOf R
* @category List
* @sig a -> Number -> [a] -> Number
* @param {*} target The item to find.
* @param {Array} list The array to search in.
* @param {Number} fromIdx the index to start searching from
* @return {Number} the index of the target, or -1 if the target is not found.
*
* @example
*
* R.indexOf.from(3, 2, [-1,0,1,2,3,4]); //=> 4
* R.indexOf.from(10, 2, [1,2,3,4]); //=> -1
*/
R.indexOf.from = curry3(function indexOfFrom(target, fromIdx, list) {
return indexOf(list, target, fromIdx);
});
/**
* Returns the position of the last occurrence of an item (by strict equality) in
* an array, or -1 if the item is not included in the array.
*
* @func
* @memberOf R
* @category List
* @sig a -> [a] -> Number
* @param {*} target The item to find.
* @param {Array} list The array to search in.
* @return {Number} the index of the target, or -1 if the target is not found.
*
* @example
*
* R.lastIndexOf(3, [-1,3,3,0,1,2,3,4]); //=> 6
* R.lastIndexOf(10, [1,2,3,4]); //=> -1
*/
R.lastIndexOf = curry2(function _lastIndexOf(target, list) {
return lastIndexOf(list, target);
});
/**
* Returns the position of the last occurrence of an item (by strict equality) in
* an array, or -1 if the item is not included in the array. However,
* `lastIndexOf.from` will only search the tail of the array, starting from the
* `fromIdx` parameter.
*
* @func
* @memberOf R
* @category List
* @sig a -> Number -> [a] -> Number
* @param {*} target The item to find.
* @param {Array} list The array to search in.
* @param {Number} fromIdx the index to start searching from
* @return {Number} the index of the target, or -1 if the target is not found.
*
* @example
*
* R.lastIndexOf.from(3, 2, [-1,3,3,0,1,2,3,4]); //=> 2
* R.lastIndexOf.from(10, 2, [1,2,3,4]); //=> -1
*/
R.lastIndexOf.from = curry3(function lastIndexOfFrom(target, fromIdx, list) {
return lastIndexOf(list, target, fromIdx);
});
/**
* Returns `true` if the specified item is somewhere in the list, `false` otherwise.
* Equivalent to `indexOf(a)(list) > -1`. Uses strict (`===`) equality checking.
*
* @func
* @memberOf R
* @category List
* @sig a -> [a] -> Boolean
* @param {Object} a The item to compare against.
* @param {Array} list The array to consider.
* @return {boolean} `true` if the item is in the list, `false` otherwise.
* @example
*
* R.contains(3)([1, 2, 3]); //=> true
* R.contains(4)([1, 2, 3]); //=> false
* R.contains({})([{}, {}]); //=> false
* var obj = {};
* R.contains(obj)([{}, obj, {}]); //=> true
*/
function contains(a, list) {
return indexOf(list, a) > -1;
}
R.contains = curry2(contains);
/**
* Returns `true` if the `x` is found in the `list`, using `pred` as an
* equality predicate for `x`.
*
* @func
* @memberOf R
* @category List
* @sig (x, a -> Boolean) -> x -> [a] -> Boolean
* @param {Function} pred :: x -> x -> Bool
* @param {*} x the item to find
* @param {Array} list the list to iterate over
* @return {Boolean} `true` if `x` is in `list`, else `false`
* @example
*
* var xs = [{x: 12}, {x: 11}, {x: 10}];
* R.containsWith(function(a, b) { return a.x === b.x; }, {x: 10}, xs); //=> true
* R.containsWith(function(a, b) { return a.x === b.x; }, {x: 1}, xs); //=> false
*/
function containsWith(pred, x, list) {
var idx = -1, len = list.length;
while (++idx < len) {
if (pred(x, list[idx])) {
return true;
}
}
return false;
}
R.containsWith = curry3(containsWith);
/**
* Returns a new list containing only one copy of each element in the original list.
* Equality is strict here, meaning reference equality for objects and non-coercing equality
* for primitives.
*
* @func
* @memberOf R
* @category List
* @sig [a] -> [a]
* @param {Array} list The array to consider.
* @return {Array} The list of unique items.
* @example
*
* R.uniq([1, 1, 2, 1]); //=> [1, 2]
* R.uniq([{}, {}]); //=> [{}, {}]
* R.uniq([1, '1']); //=> [1, '1']
*/
var uniq = R.uniq = function uniq(list) {
var idx = -1, len = list.length;
var result = [], item;
while (++idx < len) {
item = list[idx];
if (!contains(item, result)) {
result.push(item);
}
}
return result;
};
/**
* Returns `true` if all elements are unique, otherwise `false`.
* Uniqueness is determined using strict equality (`===`).
*
* @func
* @memberOf R
* @category List
* @sig [a] -> Boolean
* @param {Array} list The array to consider.
* @return {boolean} `true` if all elements are unique, else `false`.
* @example
*
* R.isSet(['1', 1]); //=> true
* R.isSet([1, 1]); //=> false
* R.isSet([{}, {}]); //=> true
*/
R.isSet = function _isSet(list) {
var len = list.length;
var idx = -1;
while (++idx < len) {
if (indexOf(list, list[idx], idx + 1) >= 0) {
return false;
}
}
return true;
};
/**
* Returns a new list containing only one copy of each element in the original list, based
* upon the value returned by applying the supplied predicate to two list elements. Prefers
* the first item if two items compare equal based on the predicate.
*
* @func
* @memberOf R
* @category List
* @sig (x, a -> Boolean) -> [a] -> [a]
* @param {Function} pred :: x -> x -> Bool
* @param {Array} list The array to consider.
* @return {Array} The list of unique items.
* @example
*
* var strEq = function(a, b) { return ('' + a) === ('' + b) };
* R.uniqWith(strEq)([1, '1', 2, 1]); //=> [1, 2]
* R.uniqWith(strEq)([{}, {}]); //=> [{}]
* R.uniqWith(strEq)([1, '1', 1]); //=> [1]
* R.uniqWith(strEq)(['1', 1, 1]); //=> ['1']
*/
var uniqWith = R.uniqWith = curry2(function _uniqWith(pred, list) {
var idx = -1, len = list.length;
var result = [], item;
while (++idx < len) {
item = list[idx];
if (!containsWith(pred, item, result)) {
result.push(item);
}
}
return result;
});
/**
* Returns a new list by plucking the same named property off all objects in the list supplied.
*
* @func
* @memberOf R
* @category List
* @sig String -> {*} -> [*]
* @param {string|number} key The key name to pluck off of each object.
* @param {Array} list The array to consider.
* @return {Array} The list of values for the given key.
* @example
*
* R.pluck('a')([{a: 1}, {a: 2}]); //=> [1, 2]
* R.pluck(0)([[1, 2], [3, 4]]); //=> [1, 3]
*/
var pluck = R.pluck = curry2(function _pluck(p, list) {
return map(prop(p), list);
});
/**
* `makeFlat` is a helper function that returns a one-level or fully recursive function
* based on the flag passed in.
*
* @private
*/
// TODO: document, even for internals...
var makeFlat = function _makeFlat(recursive) {
return function __flatt(list) {
var value, result = [], idx = -1, j, ilen = list.length, jlen;
while (++idx < ilen) {
if (R.isArrayLike(list[idx])) {
value = (recursive) ? __flatt(list[idx]) : list[idx];
j = -1;
jlen = value.length;
while (++j < jlen) {
result.push(value[j]);
}
} else {
result.push(list[idx]);
}
}
return result;
};
};
/**
* Returns a new list by pulling every item out of it (and all its sub-arrays) and putting
* them in a new array, depth-first.
*
* @func
* @memberOf R
* @category List
* @sig [a] -> [b]
* @param {Array} list The array to consider.
* @return {Array} The flattened list.
* @example
*
* R.flatten([1, 2, [3, 4], 5, [6, [7, 8, [9, [10, 11], 12]]]]);
* //=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
*/
R.flatten = makeFlat(true);
/**
* Returns a new list by pulling every item at the first level of nesting out, and putting
* them in a new array.
*
* @func
* @memberOf R
* @category List
* @sig [a] -> [b]
* @param {Array} list The array to consider.
* @return {Array} The flattened list.
* @example
*
* R.unnest([1, [2], [[3]]]); //=> [1, 2, [3]]
* R.unnest([[1, 2], [3, 4], [5, 6]]); //=> [1, 2, 3, 4, 5, 6]
*/
var unnest = R.unnest = makeFlat(false);
/**
* Creates a new list out of the two supplied by applying the function to
* each equally-positioned pair in the lists. The returned list is
* truncated to the length of the shorter of the two input lists.
*
* @function
* @memberOf R
* @category List
* @sig (a,b -> c) -> a -> b -> [c]
* @param {Function} fn The function used to combine the two elements into one value.
* @param {Array} list1 The first array to consider.
* @param {Array} list2 The second array to consider.
* @return {Array} The list made by combining same-indexed elements of `list1` and `list2`
* using `fn`.
* @example
*
* var f = function(x, y) {
* // ...
* };
* R.zipWith(f, [1, 2, 3], ['a', 'b', 'c']);
* //=> [f(1, 'a'), f(2, 'b'), f(3, 'c')]
*/
R.zipWith = curry3(function _zipWith(fn, a, b) {
var rv = [], idx = -1, len = Math.min(a.length, b.length);
while (++idx < len) {
rv[idx] = fn(a[idx], b[idx]);
}
return rv;
});
/**
* Creates a new list out of the two supplied by pairing up
* equally-positioned items from both lists. The returned list is
* truncated to the length of the shorter of the two input lists.
* Note: `zip` is equivalent to `zipWith(function(a, b) { return [a, b] })`.
*
* @func
* @memberOf R
* @category List
* @sig a -> b -> [[a,b]]
* @param {Array} list1 The first array to consider.
* @param {Array} list2 The second array to consider.
* @return {Array} The list made by pairing up same-indexed elements of `list1` and `list2`.
* @example
*
* R.zip([1, 2, 3], ['a', 'b', 'c']); //=> [[1, 'a'], [2, 'b'], [3, 'c']]
*/
R.zip = curry2(function _zip(a, b) {
var rv = [];
var idx = -1;
var len = Math.min(a.length, b.length);
while (++idx < len) {
rv[idx] = [a[idx], b[idx]];
}
return rv;
});
/**
* Creates a new object out of a list of keys and a list of values.
*
* @func
* @memberOf R
* @category List
* @sig k -> v -> {k: v}
* @param {Array} keys The array that will be properties on the output object.
* @param {Array} values The list of values on the output object.
* @return {Object} The object made by pairing up same-indexed elements of `keys` and `values`.
* @example
*
* R.zipObj(['a', 'b', 'c'], [1, 2, 3]); //=> {a: 1, b: 2, c: 3}
*/
R.zipObj = curry2(function _zipObj(keys, values) {
var idx = -1, len = keys.length, out = {};
while (++idx < len) {
out[keys[idx]] = values[idx];
}
return out;
});
/**
* Creates a new object out of a list key-value pairs.
*
* @func
* @memberOf R
* @category List
* @sig [[k,v]] -> {k: v}
* @param {Array} An array of two-element arrays that will be the keys and values of the ouput object.
* @return {Object} The object made by pairing up `keys` and `values`.
* @example
*
* R.fromPairs([['a', 1], ['b', 2], ['c', 3]]); //=> {a: 1, b: 2, c: 3}
*/
R.fromPairs = function _fromPairs(pairs) {
var idx = -1, len = pairs.length, out = {};
while (++idx < len) {
if (isArray(pairs[idx]) && pairs[idx].length) {
out[pairs[idx][0]] = pairs[idx][1];
}
}
return out;
};
/**
* Creates a new list out of the two supplied by applying the function
* to each possible pair in the lists.
*
* @see R.xprod
* @func
* @memberOf R
* @category List
* @sig (a,b -> c) -> a -> b -> [c]
* @param {Function} fn The function to join pairs with.
* @param {Array} as The first list.
* @param {Array} bs The second list.
* @return {Array} The list made by combining each possible pair from
* `as` and `bs` using `fn`.
* @example
*
* var f = function(x, y) {
* // ...
* };
* R.xprodWith(f, [1, 2], ['a', 'b']);
* // [f(1, 'a'), f(1, 'b'), f(2, 'a'), f(2, 'b')];
*/
R.xprodWith = curry3(function _xprodWith(fn, a, b) {
if (isEmpty(a) || isEmpty(b)) {
return [];
}
// Better to push them all or to do `new Array(ilen * jlen)` and
// calculate indices?
var idx = -1, ilen = a.length, j, jlen = b.length, result = [];
while (++idx < ilen) {
j = -1;
while (++j < jlen) {
result.push(fn(a[idx], b[j]));
}
}
return result;
});
/**
* Creates a new list out of the two supplied by creating each possible
* pair from the lists.
*
* @func
* @memberOf R
* @category List
* @sig a -> b -> [[a,b]]
* @param {Array} as The first list.
* @param {Array} bs The second list.
* @return {Array} The list made by combining each possible pair from
* `as` and `bs` into pairs (`[a, b]`).
* @example
*
* R.xprod([1, 2], ['a', 'b']); //=> [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]
*/
R.xprod = curry2(function _xprod(a, b) { // = xprodWith(prepend); (takes about 3 times as long...)
if (isEmpty(a) || isEmpty(b)) {
return [];
}
var idx = -1;
var ilen = a.length;
var j;
var jlen = b.length;
// Better to push them all or to do `new Array(ilen * jlen)` and calculate indices?
var result = [];
while (++idx < ilen) {
j = -1;
while (++j < jlen) {
result.push([a[idx], b[j]]);
}
}
return result;
});
/**
* Returns a new list with the same elements as the original list, just
* in the reverse order.
*
* @func
* @memberOf R
* @category List
* @sig [a] -> [a]
* @param {Array} list The list to reverse.
* @return {Array} A copy of the list in reverse order.
* @example
*
* R.reverse([1, 2, 3]); //=> [3, 2, 1]
* R.reverse([1, 2]); //=> [2, 1]
* R.reverse([1]); //=> [1]
* R.reverse([]); //=> []
*/
R.reverse = function _reverse(list) {
return clone(list || []).reverse();
};
/**
* Returns a list of numbers from `from` (inclusive) to `to`
* (exclusive).
*
* @func
* @memberOf R
* @category List
* @sig Number -> Number -> [Number]
* @param {number} from The first number in the list.
* @param {number} to One more than the last number in the list.
* @return {Array} The list of numbers in tthe set `[a, b)`.
* @example
*
* R.range(1, 5); //=> [1, 2, 3, 4]
* R.range(50, 53); //=> [50, 51, 52]
*/
R.range = curry2(function _range(from, to) {
if (from >= to) {
return [];
}
var idx = 0, result = new Array(Math.floor(to) - Math.ceil(from));
for (; from < to; idx++, from++) {
result[idx] = from;
}
return result;
});
/**
* Returns a string made by inserting the `separator` between each
* element and concatenating all the elements into a single string.
*
* @func
* @memberOf R
* @category List
* @sig String -> [a] -> String
* @param {string|number} separator The string used to separate the elements.
* @param {Array} xs The elements to join into a string.
* @return {string} The string made by concatenating `xs` with `separator`.
* @example
*
* var spacer = R.join(' ');
* spacer(['a', 2, 3.4]); //=> 'a 2 3.4'
* R.join('|', [1, 2, 3]); //=> '1|2|3'
*/
R.join = invoker('join', Array.prototype);
/**
* Returns the elements from `xs` starting at `a` and ending at `b - 1`.
*
* @func
* @memberOf R
* @category List
* @sig Number -> Number -> [a] -> [a]
* @param {number} a The starting index.
* @param {number} b One more than the ending index.
* @param {Array} xs The list to take elements from.
* @return {Array} The items from `a` to `b - 1` from `xs`.
* @example
*
* var xs = R.range(0, 10);
* R.slice(2, 5)(xs); //=> [2, 3, 4]
*/
R.slice = invoker('slice', Array.prototype);
/**
* Returns the elements from `xs` starting at `a` going to the end of `xs`.
*
* @func
* @memberOf R
* @category List
* @sig Number -> [a] -> [a]
* @param {number} a The starting index.
* @param {Array} xs The list to take elements from.
* @return {Array} The items from `a` to the end of `xs`.
* @example
*
* var xs = R.range(0, 10);
* R.slice.from(2)(xs); //=> [2, 3, 4, 5, 6, 7, 8, 9]
*
* var ys = R.range(4, 8);
* var tail = R.slice.from(1);
* tail(ys); //=> [5, 6, 7]
*/
R.slice.from = curry2(function(a, xs) {
return xs.slice(a, xs.length);
});
/**
* Removes the sub-list of `list` starting at index `start` and containing
* `count` elements. _Note that this is not destructive_: it returns a
* copy of the list with the changes.
* <small>No lists have been harmed in the application of this function.</small>
*
* @func
* @memberOf R
* @category List
* @sig Number -> Number -> [a] -> [a]
* @param {Number} start The position to start removing elements
* @param {Number} count The number of elements to remove
* @param {Array} list The list to remove from
* @return {Array} a new Array with `count` elements from `start` removed
* @example
*
* R.remove(2, 3, [1,2,3,4,5,6,7,8]); //=> [1,2,6,7,8]
*/
R.remove = curry3(function _remove(start, count, list) {
return concat(_slice(list, 0, Math.min(start, list.length)), _slice(list, Math.min(list.length, start + count)));
});
/**
* Inserts the supplied element into the list, at index `index`. _Note
* that this is not destructive_: it returns a copy of the list with the changes.
* <small>No lists have been harmed in the application of this function.</small>
*
* @func
* @memberOf R
* @category List
* @sig Number -> a -> [a] -> [a]
* @param {Number} index The position to insert the element
* @param {*} elt The element to insert into the Array
* @param {Array} list The list to insert into
* @return {Array} a new Array with `elt` inserted at `index`
* @example
*
* R.insert(2, 'x', [1,2,3,4]); //=> [1,2,'x',3,4]
*/
R.insert = curry3(function _insert(idx, elt, list) {
idx = idx < list.length && idx >= 0 ? idx : list.length;
return concat(append(elt, _slice(list, 0, idx)), _slice(list, idx));
});
/**
* Inserts the sub-list into the list, at index `index`. _Note that this
* is not destructive_: it returns a copy of the list with the changes.
* <small>No lists have been harmed in the application of this function.</small>
*
* @func
* @memberOf R
* @category List
* @sig Number -> [a] -> [a] -> [a]
* @param {Number} index The position to insert the sublist
* @param {Array} elts The sub-list to insert into the Array
* @param {Array} list The list to insert the sub-list into
* @return {Array} a new Array with `elts` inserted starting at `index`
* @example
*
* R.insert.all(2, ['x','y','z'], [1,2,3,4]); //=> [1,2,'x','y','z',3,4]
*/
R.insert.all = curry3(function _insertAll(idx, elts, list) {
idx = idx < list.length && idx >= 0 ? idx : list.length;
return concat(concat(_slice(list, 0, idx), elts), _slice(list, idx));
});
/**
* Makes a comparator function out of a function that reports whether the first element is less than the second.
*
* @func
* @memberOf R
* @category Function
* @sig (a, b -> Boolean) -> (a, b -> Number)
* @param {Function} pred A predicate function of arity two.
* @return {Function} a Function :: a -> b -> Int that returns `-1` if a < b, `1` if b < a, otherwise `0`
* @example
*
* var cmp = R.comparator(function(a, b) {
* return a.age < b.age;
* });
* var people = [
* // ...
* ];
* R.sort(cmp, people);
*/
var comparator = R.comparator = function _comparator(pred) {
return function(a, b) {
return pred(a, b) ? -1 : pred(b, a) ? 1 : 0;
};
};
/**
* Returns a copy of the list, sorted according to the comparator function, which should accept two values at a
* time and return a negative number if the first value is smaller, a positive number if it's larger, and zero
* if they are equal. Please note that this is a **copy** of the list. It does not modify the original.
*
* @func
* @memberOf R
* @category List
* @sig (a,a -> Number) -> [a] -> [a]
* @param {Function} comparator A sorting function :: a -> b -> Int
* @param {Array} list The list to sort
* @return {Array} a new array with its elements sorted by the comparator function.
* @example
*
* var diff = function(a, b) { return a - b; };
* R.sort(diff, [4,2,7,5]); //=> [2, 4, 5, 7]
*/
R.sort = curry2(function sort(comparator, list) {
return clone(list).sort(comparator);
});
/**
* Splits a list into sublists stored in an object, based on the result of calling a String-returning function
* on each element, and grouping the results according to values returned.
*
* @func
* @memberOf R
* @category List
* @sig (a -> s) -> [a] -> {s: a}
* @param {Function} fn Function :: a -> String
* @param {Array} list The array to group
* @return {Object} An object with the output of `fn` for keys, mapped to arrays of elements
* that produced that key when passed to `fn`.
* @example
*
* var byGrade = R.groupBy(function(student) {
* var score = student.score;
* return (score < 65) ? 'F' : (score < 70) ? 'D' :
* (score < 80) ? 'C' : (score < 90) ? 'B' : 'A';
* });
* var students = [{name: 'Abby', score: 84},
* {name: 'Eddy', score: 58},
* // ...
* {name: 'Jack', score: 69}];
* byGrade(students);
* // {
* // 'A': [{name: 'Dianne', score: 99}],
* // 'B': [{name: 'Abby', score: 84}]
* // // ...,
* // 'F': [{name: 'Eddy', score: 58}]
* // }
*/
R.groupBy = curry2(function _groupBy(fn, list) {
return foldl(function(acc, elt) {
var key = fn(elt);
acc[key] = append(elt, acc[key] || (acc[key] = []));
return acc;
}, {}, list);
});
/**
* Takes a predicate and a list and returns the pair of lists of
* elements which do and do not satisfy the predicate, respectively.
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> [[a],[a]]
* @param {Function} pred Function :: a -> Boolean
* @param {Array} list The array to partition
* @return {Array} A nested array, containing first an array of elements that satisfied the predicate,
* and second an array of elements that did not satisfy.
* @example
*
* R.partition(R.contains('s'), ['sss', 'ttt', 'foo', 'bars']);
* //=> [ [ 'sss', 'bars' ], [ 'ttt', 'foo' ] ]
*/
R.partition = curry2(function _partition(pred, list) {
return foldl(function(acc, elt) {
acc[pred(elt) ? 0 : 1].push(elt);
return acc;
}, [[], []], list);
});
// Object Functions
// ----------------
//
// These functions operate on plain Javascript object, adding simple functions to test properties on these
// objects. Many of these are of most use in conjunction with the list functions, operating on lists of
// objects.
// --------
/**
* Runs the given function with the supplied object, then returns the object.
*
* @func
* @memberOf R
* @category Function
* @sig a -> (a -> *) -> a
* @param {*} x
* @param {Function} fn The function to call with `x`. The return value of `fn` will be thrown away.
* @return {*} x
* @example
*
* var sayX = function(x) { console.log('x is ' + x); };
* R.tap(100, sayX); //=> 100
* //-> 'x is 100')
*/
R.tap = curry2(function _tap(x, fn) {
if (typeof fn === 'function') { fn(x); }
return x;
});
/**
* Tests if two items are equal. Equality is strict here, meaning reference equality for objects and
* non-coercing equality for primitives.
*
* @func
* @memberOf R
* @category Relation
* @sig a -> b -> Boolean
* @param {*} a
* @param {*} b
* @return {Boolean}
* @example
*
* var o = {};
* R.eq(o, o); //=> true
* R.eq(o, {}); //=> false
* R.eq(1, 1); //=> true
* R.eq(1, '1'); //=> false
*/
R.eq = curry2(function _eq(a, b) { return a === b; });
/**
* Returns a function that when supplied an object returns the indicated property of that object, if it exists.
*
* @func
* @memberOf R
* @category Object
* @sig s -> {s: a} -> a
* @param {String} p The property name
* @param {Object} obj The object to query
* @return {*} The value at obj.p
* @example
*
* R.prop('x', {x: 100}); //=> 100
* R.prop('x', {}); //=> undefined
*
* var fifth = R.prop(4); // indexed from 0, remember
* fifth(['Bashful', 'Doc', 'Dopey', 'Grumpy', 'Happy', 'Sleepy', 'Sneezy']);
* //=> 'Happy'
*/
var prop = R.prop = function prop(p, obj) {
switch (arguments.length) {
case 0: throw NO_ARGS_EXCEPTION;
case 1: return function _prop(obj) { return obj[p]; };
}
return obj[p];
};
/**
* @func
* @memberOf R
* @category Object
* @see R.prop
*/
R.get = R.prop;
/**
* Returns the value at the specified property.
* The only difference from `prop` is the parameter order.
*
* @func
* @memberOf R
* @see R.prop
* @category Object
* @sig {s: a} -> s -> a
* @param {Object} obj The object to query
* @param {String} prop The property name
* @return {*} The value at obj.p
* @example
*
* R.props({x: 100}, 'x'); //=> 100
*/
R.props = flip(R.prop);
/**
* An internal reference to `Object.prototype.hasOwnProperty`
* @private
*/
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* If the given object has an own property with the specified name,
* returns the value of that property.
* Otherwise returns the provided default value.
*
* @func
* @memberOf R
* @category Object
* @sig s -> v -> {s: x} -> x | v
* @param {String} p The name of the property to return.
* @param {*} val The default value.
* @returns {*} The value of given property or default value.
* @example
*
* var alice = {
* name: 'ALICE',
* age: 101
* };
* var favorite = R.prop('favoriteLibrary');
* var favoriteWithDefault = R.propOrDefault('favoriteLibrary', 'Ramda');
*
* favorite(alice); //=> undefined
* favoriteWithDefault(alice); //=> 'Ramda'
*/
R.propOrDefault = curry3(function _propOrDefault(p, val, obj) {
return hasOwnProperty.call(obj, p) ? obj[p] : val;
});
/**
* Calls the specified function on the supplied object. Any additional arguments
* after `fn` and `obj` are passed in to `fn`. If no additional arguments are passed to `func`,
* `fn` is invoked with no arguments.
*
* @func
* @memberOf R
* @category Object
* @sig k -> {k : v} -> v(*)
* @param {String} fn The name of the property mapped to the function to invoke
* @param {Object} obj The object
* @return {*} The value of invoking `obj.fn`
* @example
*
* R.func('add', R, 1, 2); //=> 3
*
* var obj = { f: function() { return 'f called'; } };
* R.func('f', obj); //=> 'f called'
*/
R.func = function _func(funcName, obj) {
switch (arguments.length) {
case 0: throw NO_ARGS_EXCEPTION;
case 1: return function(obj) { return obj[funcName].apply(obj, _slice(arguments, 1)); };
default: return obj[funcName].apply(obj, _slice(arguments, 2));
}
};
/**
* Returns a function that always returns the given value.
*
* @func
* @memberOf R
* @category Function
* @sig a -> (* -> a)
* @param {*} val The value to wrap in a function
* @return {Function} A Function :: * -> val
* @example
*
* var t = R.always('Tee');
* t(); //=> 'Tee'
*/
var always = R.always = function _always(val) {
return function() {
return val;
};
};
/**
* Internal reference to Object.keys
*
* @private
* @param {Object}
* @return {Array}
*/
var nativeKeys = Object.keys;
/**
* Returns a list containing the names of all the enumerable own
* properties of the supplied object.
* Note that the order of the output array is not guaranteed to be
* consistent across different JS platforms.
*
* @func
* @memberOf R
* @category Object
* @sig {k: v} -> [k]
* @param {Object} obj The object to extract properties from
* @return {Array} An array of the object's own properties
* @example
*
* R.keys({a: 1, b: 2, c: 3}); //=> ['a', 'b', 'c']
*/
var keys = R.keys = (function() {
// cover IE < 9 keys issues
var hasEnumBug = !({toString: null}).propertyIsEnumerable('toString');
var nonEnumerableProps = ['constructor', 'valueOf', 'isPrototypeOf', 'toString',
'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
return function _keys(obj) {
if (!R.is(Object, obj)) {
return [];
}
if (nativeKeys) {
return nativeKeys(Object(obj));
}
var prop, ks = [], nIdx;
for (prop in obj) {
if (hasOwnProperty.call(obj, prop)) {
ks.push(prop);
}
}
if (hasEnumBug) {
nIdx = nonEnumerableProps.length;
while (nIdx--) {
prop = nonEnumerableProps[nIdx];
if (hasOwnProperty.call(obj, prop) && !R.contains(prop, ks)) {
ks.push(prop);
}
}
}
return ks;
};
}());
/**
* Returns a list containing the names of all the
* properties of the supplied object, including prototype properties.
* Note that the order of the output array is not guaranteed to be
* consistent across different JS platforms.
*
* @func
* @memberOf R
* @category Object
* @sig {k: v} -> [k]
* @param {Object} obj The object to extract properties from
* @return {Array} An array of the object's own and prototype properties
* @example
*
* var F = function() { this.x = 'X'; };
* F.prototype.y = 'Y';
* var f = new F();
* R.keysIn(f); //=> ['x', 'y']
*/
R.keysIn = function _keysIn(obj) {
var prop, ks = [];
for (prop in obj) {
ks.push(prop);
}
return ks;
};
/**
* @private
* @param {Function} fn The strategy for extracting keys from an object
* @return {Function} A function that takes an object and returns an array of
* key-value arrays.
*/
var pairWith = function(fn) {
return function(obj) {
return R.map(function(key) { return [key, obj[key]]; }, fn(obj));
};
};
/**
* Converts an object into an array of key, value arrays.
* Only the object's own properties are used.
* Note that the order of the output array is not guaranteed to be
* consistent across different JS platforms.
*
* @func
* @memberOf R
* @category Object
* @sig {k: v} -> [[k,v]]
* @param {Object} obj The object to extract from
* @return {Array} An array of key, value arrays from the object's own properties
* @example
*
* R.toPairs({a: 1, b: 2, c: 3}); //=> [['a', 1], ['b', 2], ['c', 3]]
*/
R.toPairs = pairWith(R.keys);
/**
* Converts an object into an array of key, value arrays.
* The object's own properties and prototype properties are used.
* Note that the order of the output array is not guaranteed to be
* consistent across different JS platforms.
*
* @func
* @memberOf R
* @category Object
* @sig {k: v} -> [[k,v]]
* @param {Object} obj The object to extract from
* @return {Array} An array of key, value arrays from the object's own
* and prototype properties
* @example
*
* var F = function() { this.x = 'X'; };
* F.prototype.y = 'Y';
* var f = new F();
* R.toPairsIn(f); //=> [['x','X'], ['y','Y']]
*/
R.toPairsIn = pairWith(R.keysIn);
/**
* Returns a list of all the enumerable own properties of the supplied object.
* Note that the order of the output array is not guaranteed across
* different JS platforms.
*
* @func
* @memberOf R
* @category Object
* @sig {k: v} -> [v]
* @param {Object} obj The object to extract values from
* @return {Array} An array of the values of the object's own properties
* @example
*
* R.values({a: 1, b: 2, c: 3}); //=> [1, 2, 3]
*/
R.values = function _values(obj) {
var props = keys(obj),
length = props.length,
vals = new Array(length);
for (var idx = 0; idx < length; idx++) {
vals[idx] = obj[props[idx]];
}
return vals;
};
/**
* Returns a list of all the properties, including prototype properties,
* of the supplied object.
* Note that the order of the output array is not guaranteed to be
* consistent across different JS platforms.
*
* @func
* @memberOf R
* @category Object
* @sig {k: v} -> [v]
* @param {Object} obj The object to extract values from
* @return {Array} An array of the values of the object's own and prototype properties
* @example
*
* var F = function() { this.x = 'X'; };
* F.prototype.y = 'Y';
* var f = new F();
* R.valuesIn(f); //=> ['X', 'Y']
*/
R.valuesIn = function _valuesIn(obj) {
var prop, vs = [];
for (prop in obj) {
vs.push(obj[prop]);
}
return vs;
};
/**
* Internal helper function for making a partial copy of an object
*
* @private
*
*/
// TODO: document, even for internals...
function pickWith(test, obj) {
var copy = {},
props = keys(obj), prop, val;
for (var idx = 0, len = props.length; idx < len; idx++) {
prop = props[idx];
val = obj[prop];
if (test(val, prop, obj)) {
copy[prop] = val;
}
}
return copy;
}
/**
* Returns a partial copy of an object containing only the keys specified. If the key does not exist, the
* property is ignored.
*
* @func
* @memberOf R
* @category Object
* @sig [k] -> {k: v} -> {k: v}
* @param {Array} names an array of String propery names to copy onto a new object
* @param {Object} obj The object to copy from
* @return {Object} A new object with only properties from `names` on it.
* @example
*
* R.pick(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4}
* R.pick(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1}
*/
R.pick = curry2(function pick(names, obj) {
return pickWith(function(val, key) {
return contains(key, names);
}, obj);
});
/**
* Returns a partial copy of an object omitting the keys specified.
*
* @func
* @memberOf R
* @category Object
* @sig [k] -> {k: v} -> {k: v}
* @param {Array} names an array of String propery names to omit from the new object
* @param {Object} obj The object to copy from
* @return {Object} A new object with properties from `names` not on it.
* @example
*
* R.omit(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, c: 3}
*/
R.omit = curry2(function omit(names, obj) {
return pickWith(function(val, key) {
return !contains(key, names);
}, obj);
});
/**
* Returns a partial copy of an object containing only the keys that
* satisfy the supplied predicate.
*
* @func
* @memberOf R
* @category Object
* @sig (v, k -> Boolean) -> {k: v} -> {k: v}
* @param {Function} pred A predicate to determine whether or not a key
* should be included on the output object.
* @param {Object} obj The object to copy from
* @return {Object} A new object with only properties that satisfy `pred`
* on it.
* @see R.pick
* @example
*
* var isUpperCase = function(val, key) { return key.toUpperCase() === key; }
* R.pickWith(isUpperCase, {a: 1, b: 2, A: 3, B: 4}); //=> {A: 3, B: 4}
*/
R.pickWith = curry2(pickWith);
/**
* Internal implementation of `pickAll`
*
* @private
* @see R.pickAll
*/
// TODO: document, even for internals...
var pickAll = function _pickAll(names, obj) {
var copy = {};
forEach(function(name) {
copy[name] = obj[name];
}, names);
return copy;
};
/**
* Similar to `pick` except that this one includes a `key: undefined` pair for properties that don't exist.
*
* @func
* @memberOf R
* @category Object
* @sig [k] -> {k: v} -> {k: v}
* @param {Array} names an array of String propery names to copy onto a new object
* @param {Object} obj The object to copy from
* @return {Object} A new object with only properties from `names` on it.
* @see R.pick
* @example
*
* R.pickAll(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4}
* R.pickAll(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, e: undefined, f: undefined}
*/
R.pickAll = curry2(pickAll);
/**
* Assigns own enumerable properties of the other object to the destination
* object prefering items in other.
*
* @private
* @memberOf R
* @category Object
* @param {Object} object The destination object.
* @param {Object} other The other object to merge with destination.
* @returns {Object} Returns the destination object.
* @example
*
* extend({ 'name': 'fred', 'age': 10 }, { 'age': 40 });
* //=> { 'name': 'fred', 'age': 40 }
*/
function extend(destination, other) {
var props = keys(other),
idx = -1, length = props.length;
while (++idx < length) {
destination[props[idx]] = other[props[idx]];
}
return destination;
}
/**
* Create a new object with the own properties of a
* merged with the own properties of object b.
* This function will *not* mutate passed-in objects.
*
* @func
* @memberOf R
* @category Object
* @sig {k: v} -> {k: v} -> {k: v}
* @param {Object} a source object
* @param {Object} b object with higher precendence in output
* @returns {Object} Returns the destination object.
* @example
*
* R.mixin({ 'name': 'fred', 'age': 10 }, { 'age': 40 });
* //=> { 'name': 'fred', 'age': 40 }
*/
R.mixin = curry2(function _mixin(a, b) {
return extend(extend({}, a), b);
});
/**
* Creates a shallow copy of an object's own properties.
*
* @func
* @memberOf R
* @category Object
* @sig {*} -> {*}
* @param {Object} obj The object to clone
* @returns {Object} A new object
* @example
*
* R.cloneObj({a: 1, b: 2, c: [1, 2, 3]}); // {a: 1, b: 2, c: [1, 2, 3]}
*/
R.cloneObj = function(obj) {
return extend({}, obj);
};
/**
* Reports whether two functions have the same value for the specified property. Useful as a curried predicate.
*
* @func
* @memberOf R
* @category Object
* @sig k -> {k: v} -> {k: v} -> Boolean
* @param {String} prop The name of the property to compare
* @param {Object} obj1
* @param {Object} obj2
* @return {Boolean}
*
* @example
*
* var o1 = { a: 1, b: 2, c: 3, d: 4 };
* var o2 = { a: 10, b: 20, c: 3, d: 40 };
* R.eqProps('a', o1, o2); //=> false
* R.eqProps('c', o1, o2); //=> true
*/
R.eqProps = curry3(function eqProps(prop, obj1, obj2) {
return obj1[prop] === obj2[prop];
});
/**
* internal helper for `where`
*
* @private
* @see R.where
*/
function satisfiesSpec(spec, parsedSpec, testObj) {
if (spec === testObj) { return true; }
if (testObj == null) { return false; }
parsedSpec.fn = parsedSpec.fn || [];
parsedSpec.obj = parsedSpec.obj || [];
var key, val, idx = -1, fnLen = parsedSpec.fn.length, j = -1, objLen = parsedSpec.obj.length;
while (++idx < fnLen) {
key = parsedSpec.fn[idx];
val = spec[key];
// if (!hasOwnProperty.call(testObj, key)) {
// return false;
// }
if (!(key in testObj)) {
return false;
}
if (!val(testObj[key], testObj)) {
return false;
}
}
while (++j < objLen) {
key = parsedSpec.obj[j];
if (spec[key] !== testObj[key]) {
return false;
}
}
return true;
}
/**
* Takes a spec object and a test object and returns true if the test satisfies the spec.
* Any property on the spec that is not a function is interpreted as an equality
* relation.
*
* If the spec has a property mapped to a function, then `where` evaluates the function, passing in
* the test object's value for the property in question, as well as the whole test object.
*
* `where` is well suited to declarativley expressing constraints for other functions, e.g.,
* `filter`, `find`, `pickWith`, etc.
*
* @func
* @memberOf R
* @category Object
* @sig {k: v} -> {k: v} -> Boolean
* @param {Object} spec
* @param {Object} testObj
* @return {Boolean}
* @example
*
* var spec = {x: 2};
* R.where(spec, {w: 10, x: 2, y: 300}); //=> true
* R.where(spec, {x: 1, y: 'moo', z: true}); //=> false
*
* var spec2 = {x: function(val, obj) { return val + obj.y > 10; }};
* R.where(spec2, {x: 2, y: 7}); //=> false
* R.where(spec2, {x: 3, y: 8}); //=> true
*
* var xs = [{x: 2, y: 1}, {x: 10, y: 2}, {x: 8, y: 3}, {x: 10, y: 4}];
* R.filter(R.where({x: 10}), xs); // ==> [{x: 10, y: 2}, {x: 10, y: 4}]
*/
R.where = function where(spec, testObj) {
var parsedSpec = R.groupBy(function(key) {
return typeof spec[key] === 'function' ? 'fn' : 'obj';
}, keys(spec));
switch (arguments.length) {
case 0: throw NO_ARGS_EXCEPTION;
case 1:
return function(testObj) {
return satisfiesSpec(spec, parsedSpec, testObj);
};
}
return satisfiesSpec(spec, parsedSpec, testObj);
};
// Miscellaneous Functions
// -----------------------
//
// A few functions in need of a good home.
// --------
/**
* Expose the functions from ramda as properties of another object.
* If the provided object is the global object then the ramda
* functions become global functions.
* Warning: This function *will* mutate the object provided.
*
* @func
* @memberOf R
* @category Object
* @sig -> {*} -> {*}
* @param {Object} obj The object to attach ramda functions
* @return {Object} a reference to the mutated object
* @example
*
* var x = {}
* R.installTo(x); // x now contains ramda functions
* R.installTo(this); // add ramda functions to `this` object
*/
R.installTo = function(obj) {
return extend(obj, R);
};
/**
* See if an object (`val`) is an instance of the supplied constructor.
* This function will check up the inheritance chain, if any.
*
* @func
* @memberOf R
* @category type
* @sig (* -> {*}) -> a -> Boolean
* @param {Object} ctor A constructor
* @param {*} val The value to test
* @return {Boolean}
* @example
*
* R.is(Object, {}); //=> true
* R.is(Number, 1); //=> true
* R.is(Object, 1); //=> false
* R.is(String, 's'); //=> true
* R.is(String, new String('')); //=> true
* R.is(Object, new String('')); //=> true
* R.is(Object, 's'); //=> false
* R.is(Number, {}); //=> false
*/
R.is = curry2(function is(ctor, val) {
return val != null && val.constructor === ctor || val instanceof ctor;
});
/**
* A function that always returns `0`. Any passed in parameters are ignored.
*
* @func
* @memberOf R
* @category function
* @sig * -> 0
* @see R.always
* @return {Number} 0. Always zero.
* @example
*
* R.alwaysZero(); //=> 0
*/
R.alwaysZero = always(0);
/**
* A function that always returns `false`. Any passed in parameters are ignored.
*
* @func
* @memberOf R
* @category function
* @sig * -> false
* @see R.always
* @return {Boolean} false
* @example
*
* R.alwaysFalse(); //=> false
*/
R.alwaysFalse = always(false);
/**
* A function that always returns `true`. Any passed in parameters are ignored.
*
* @func
* @memberOf R
* @category function
* @sig * -> true
* @see R.always
* @return {Boolean} true
* @example
*
* R.alwaysTrue(); //=> true
*/
R.alwaysTrue = always(true);
// Logic Functions
// ---------------
//
// These functions are very simple wrappers around the built-in logical operators, useful in building up
// more complex functional forms.
// --------
/**
*
* A function wrapping calls to the two functions in an `&&` operation, returning `true` or `false`. Note that
* this is short-circuited, meaning that the second function will not be invoked if the first returns a false-y
* value.
*
* @func
* @memberOf R
* @category logic
* @sig (*... -> Boolean) -> (*... -> Boolean) -> (*... -> Boolean)
* @param {Function} f a predicate
* @param {Function} g another predicate
* @return {Function} a function that applies its arguments to `f` and `g` and ANDs their outputs together.
* @example
*
* var gt10 = function(x) { return x > 10; };
* var even = function(x) { return x % 2 === 0 };
* var f = R.and(gt10, even);
* f(100); //=> true
* f(101); //=> false
*/
R.and = curry2(function and(f, g) {
return function _and() {
return !!(f.apply(this, arguments) && g.apply(this, arguments));
};
});
/**
* A function wrapping calls to the two functions in an `||` operation, returning `true` or `false`. Note that
* this is short-circuited, meaning that the second function will not be invoked if the first returns a truth-y
* value.
*
* @func
* @memberOf R
* @category logic
* @sig (*... -> Boolean) -> (*... -> Boolean) -> (*... -> Boolean)
* @param {Function} f a predicate
* @param {Function} g another predicate
* @return {Function} a function that applies its arguments to `f` and `g` and ORs their outputs together.
* @example
*
* var gt10 = function(x) { return x > 10; };
* var even = function(x) { return x % 2 === 0 };
* var f = R.or(gt10, even);
* f(101); //=> true
* f(8); //=> true
*/
R.or = curry2(function or(f, g) {
return function _or() {
return !!(f.apply(this, arguments) || g.apply(this, arguments));
};
});
/**
* A function wrapping a call to the given function in a `!` operation. It will return `true` when the
* underlying function would return a false-y value, and `false` when it would return a truth-y one.
*
* @func
* @memberOf R
* @category logic
* @sig (*... -> Boolean) -> (*... -> Boolean)
* @param {Function} f a predicate
* @return {Function} a function that applies its arguments to `f` and logically inverts its output.
* @example
*
* var gt10 = function(x) { return x > 10; };
* var f = R.not(gt10);
* f(11); //=> false
* f(9); //=> true
*/
var not = R.not = function _not(f) {
return function() {return !f.apply(this, arguments);};
};
/**
* Create a predicate wrapper which will call a pick function (all/any) for each predicate
*
* @private
* @see R.every
* @see R.some
*/
// TODO: document, even for internals...
var predicateWrap = function _predicateWrap(predPicker) {
return function(preds /* , args */) {
var predIterator = function() {
var args = arguments;
return predPicker(function(predicate) {
return predicate.apply(null, args);
}, preds);
};
return arguments.length > 1 ?
// Call function imediately if given arguments
predIterator.apply(null, _slice(arguments, 1)) :
// Return a function which will call the predicates with the provided arguments
arity(max(pluck('length', preds)), predIterator);
};
};
/**
* Given a list of predicates, returns a new predicate that will be true exactly when all of them are.
*
* @func
* @memberOf R
* @category logic
* @sig [(*... -> Boolean)] -> (*... -> Boolean)
* @param {Array} list An array of predicate functions
* @param {*} optional Any arguments to pass into the predicates
* @return {Function} a function that applies its arguments to each of
* the predicates, returning `true` if all are satisfied.
* @example
*
* var gt10 = function(x) { return x > 10; };
* var even = function(x) { return x % 2 === 0};
* var f = R.allPredicates([gt10, even]);
* f(11); //=> false
* f(12); //=> true
*/
R.allPredicates = predicateWrap(every);
/**
* Given a list of predicates returns a new predicate that will be true exactly when any one of them is.
*
* @func
* @memberOf R
* @category logic
* @sig [(*... -> Boolean)] -> (*... -> Boolean)
* @param {Array} list An array of predicate functions
* @param {*} optional Any arguments to pass into the predicates
* @return {Function} a function that applies its arguments to each of the predicates, returning
* `true` if all are satisfied..
* @example
*
* var gt10 = function(x) { return x > 10; };
* var even = function(x) { return x % 2 === 0};
* var f = R.anyPredicates([gt10, even]);
* f(11); //=> true
* f(8); //=> true
* f(9); //=> false
*/
R.anyPredicates = predicateWrap(some);
// Arithmetic Functions
// --------------------
//
// These functions wrap up the certain core arithmetic operators
// --------
/**
* Adds two numbers (or strings). Equivalent to `a + b` but curried.
*
* @func
* @memberOf R
* @category math
* @sig Number -> Number -> Number
* @sig String -> String -> String
* @param {number|string} a The first value.
* @param {number|string} b The second value.
* @return {number|string} The result of `a + b`.
* @example
*
* var increment = R.add(1);
* increment(10); //=> 11
* R.add(2, 3); //=> 5
* R.add(7)(10); //=> 17
*/
var add = R.add = curry2(function _add(a, b) { return a + b; });
/**
* Multiplies two numbers. Equivalent to `a * b` but curried.
*
* @func
* @memberOf R
* @category math
* @sig Number -> Number -> Number
* @param {number} a The first value.
* @param {number} b The second value.
* @return {number} The result of `a * b`.
* @example
*
* var double = R.multiply(2);
* var triple = R.multiply(3);
* double(3); //=> 6
* triple(4); //=> 12
* R.multiply(2, 5); //=> 10
*/
var multiply = R.multiply = curry2(function _multiply(a, b) { return a * b; });
/**
* Subtracts two numbers. Equivalent to `a - b` but curried.
*
* @func
* @memberOf R
* @category math
* @sig Number -> Number -> Number
* @param {number} a The first value.
* @param {number} b The second value.
* @return {number} The result of `a - b`.
* @note Operator: this is right-curried by default, but can be called via sections
* @example
*
* R.subtract(10, 8); //=> 2
*
* var minus5 = R.subtract(5);
* minus5(17); //=> 12
*
* // note: In this example, `_` is just an `undefined` value. You could use `void 0` instead
* var complementaryAngle = R.subtract(90, _);
* complementaryAngle(30); //=> 60
* complementaryAngle(72); //=> 18
*/
R.subtract = op(function _subtract(a, b) { return a - b; });
/**
* Divides two numbers. Equivalent to `a / b`.
* While at times the curried version of `divide` might be useful,
* probably the curried version of `divideBy` will be more useful.
*
* @func
* @memberOf R
* @category math
* @sig Number -> Number -> Number
* @param {number} a The first value.
* @param {number} b The second value.
* @return {number} The result of `a / b`.
* @note Operator: this is right-curried by default, but can be called via sections
* @example
*
* R.divide(71, 100); //=> 0.71
*
* // note: In this example, `_` is just an `undefined` value. You could use `void 0` instead
* var half = R.divide(2);
* half(42); //=> 21
*
* var reciprocal = R.divide(1, _);
* reciprocal(4); //=> 0.25
*/
R.divide = op(function _divide(a, b) { return a / b; });
/**
* Divides the second parameter by the first and returns the remainder.
* Note that this functions preserves the JavaScript-style behavior for
* modulo. For mathematical modulo see `mathMod`
*
* @func
* @memberOf R
* @category math
* @sig Number -> Number -> Number
* @param {number} a The value to the divide.
* @param {number} b The pseudo-modulus
* @return {number} The result of `b % a`.
* @note Operator: this is right-curried by default, but can be called via sections
* @see R.mathMod
* @example
*
* R.modulo(17, 3); //=> 2
* // JS behavior:
* R.modulo(-17, 3); //=> -2
* R.modulo(17, -3); //=> 2
*
* var isOdd = R.modulo(2);
* isOdd(42); //=> 0
* isOdd(21); //=> 1
*/
R.modulo = op(function _modulo(a, b) { return a % b; });
/**
* Determine if the passed argument is an integer.
*
* @private
* @param {*} n
* @category type
* @return {Boolean}
*/
// TODO: document, even for internals...
var isInteger = Number.isInteger || function isInteger(n) {
return (n << 0) === n;
};
/**
* mathMod behaves like the modulo operator should mathematically, unlike the `%`
* operator (and by extension, R.modulo). So while "-17 % 5" is -2,
* mathMod(-17, 5) is 3. mathMod requires Integer arguments, and returns NaN
* when the modulus is zero or negative.
*
* @func
* @memberOf R
* @category math
* @sig Number -> Number -> Number
* @param {number} m The dividend.
* @param {number} p the modulus.
* @return {number} The result of `b mod a`.
* @see R.moduloBy
* @example
*
* R.mathMod(-17, 5); //=> 3
* R.mathMod(17, 5); //=> 2
* R.mathMod(17, -5); //=> NaN
* R.mathMod(17, 0); //=> NaN
* R.mathMod(17.2, 5); //=> NaN
* R.mathMod(17, 5.3); //=> NaN
*
* var clock = R.mathMod(12);
* clock(15); //=> 3
* clock(24); //=> 0
*
* // note: In this example, `_` is just an `undefined` value. You could use `void 0` instead
* var seventeenMod = R.mathMod(17, _);
* seventeenMod(3); //=> 2
* seventeenMod(4); //=> 1
* seventeenMod(10); //=> 7
*/
R.mathMod = op(function _mathMod(m, p) {
if (!isInteger(m)) { return NaN; }
if (!isInteger(p) || p < 1) { return NaN; }
return ((m % p) + p) % p;
});
/**
* Adds together all the elements of a list.
*
* @func
* @memberOf R
* @category math
* @sig [Number] -> Number
* @param {Array} list An array of numbers
* @return {number} The sum of all the numbers in the list.
* @see reduce
* @example
*
* R.sum([2,4,6,8,100,1]); //=> 121
*/
R.sum = foldl(add, 0);
/**
* Multiplies together all the elements of a list.
*
* @func
* @memberOf R
* @category math
* @sig [Number] -> Number
* @param {Array} list An array of numbers
* @return {number} The product of all the numbers in the list.
* @see reduce
* @example
*
* R.product([2,4,6,8,100,1]); //=> 38400
*/
R.product = foldl(multiply, 1);
/**
* Returns true if the first parameter is less than the second.
*
* @func
* @memberOf R
* @category math
* @sig Number -> Number -> Boolean
* @param {Number} a
* @param {Number} b
* @return {Boolean} a < b
* @note Operator: this is right-curried by default, but can be called via sections
* @example
*
* R.lt(2, 6); //=> true
* R.lt(2, 0); //=> false
* R.lt(2, 2); //=> false
* R.lt(5)(10); //=> false // default currying is right-sectioned
* R.lt(5, _)(10); //=> true // left-sectioned currying
*/
R.lt = op(function _lt(a, b) { return a < b; });
/**
* Returns true if the first parameter is less than or equal to the second.
*
* @func
* @memberOf R
* @category math
* @sig Number -> Number -> Boolean
* @param {Number} a
* @param {Number} b
* @return {Boolean} a <= b
* @note Operator: this is right-curried by default, but can be called via sections
* @example
*
* R.lte(2, 6); //=> true
* R.lte(2, 0); //=> false
* R.lte(2, 2); //=> true
*/
R.lte = op(function _lte(a, b) { return a <= b; });
/**
* Returns true if the first parameter is greater than the second.
*
* @func
* @memberOf R
* @category math
* @sig Number -> Number -> Boolean
* @param {Number} a
* @param {Number} b
* @return {Boolean} a > b
* @note Operator: this is right-curried by default, but can be called via sections
* @example
*
* R.gt(2, 6); //=> false
* R.gt(2, 0); //=> true
* R.gt(2, 2); //=> false
*/
R.gt = op(function _gt(a, b) { return a > b; });
/**
* Returns true if the first parameter is greater than or equal to the second.
*
* @func
* @memberOf R
* @category math
* @sig Number -> Number -> Boolean
* @param {Number} a
* @param {Number} b
* @return {Boolean} a >= b
* @note Operator: this is right-curried by default, but can be called via sections
* @example
*
* R.gte(2, 6); //=> false
* R.gte(2, 0); //=> true
* R.gte(2, 2); //=> true
*/
R.gte = op(function _gte(a, b) { return a >= b; });
/**
* Determines the largest of a list of numbers (or elements that can be cast to numbers)
*
* @func
* @memberOf R
* @category math
* @sig [Number] -> Number<|fim▁hole|> * @see R.maxWith
* @param {Array} list A list of numbers
* @return {Number} The greatest number in the list
* @example
*
* R.max([7, 3, 9, 2, 4, 9, 3]); //=> 9
*/
var max = R.max = function _max(list) {
return foldl(binary(Math.max), -Infinity, list);
};
/**
* Determines the largest of a list of items as determined by pairwise comparisons from the supplied comparator
*
* @func
* @memberOf R
* @category math
* @sig (a -> Number) -> [a] -> a
* @param {Function} keyFn A comparator function for elements in the list
* @param {Array} list A list of comparable elements
* @return {*} The greatest element in the list. `undefined` if the list is empty.
* @see R.max
* @example
*
* function cmp(obj) { return obj.x; }
* var a = {x: 1}, b = {x: 2}, c = {x: 3};
* R.maxWith(cmp, [a, b, c]); //=> {x: 3}
*/
R.maxWith = curry2(function _maxWith(keyFn, list) {
if (!(list && list.length > 0)) {
return;
}
var idx = 0, winner = list[idx], max = keyFn(winner), testKey;
while (++idx < list.length) {
testKey = keyFn(list[idx]);
if (testKey > max) {
max = testKey;
winner = list[idx];
}
}
return winner;
});
/**
* Determines the smallest of a list of numbers (or elements that can be cast to numbers)
*
* @func
* @memberOf R
* @category math
* @sig [Number] -> Number
* @param {Array} list A list of numbers
* @return {Number} The greatest number in the list
* @see R.minWith
* @example
*
* R.min([7, 3, 9, 2, 4, 9, 3]); //=> 2
*/
R.min = function _min(list) {
return foldl(binary(Math.min), Infinity, list);
};
/**
* Determines the smallest of a list of items as determined by pairwise comparisons from the supplied comparator
*
* @func
* @memberOf R
* @category math
* @sig (a -> Number) -> [a] -> a
* @param {Function} keyFn A comparator function for elements in the list
* @param {Array} list A list of comparable elements
* @see R.min
* @return {*} The greatest element in the list. `undefined` if the list is empty.
* @example
*
* function cmp(obj) { return obj.x; }
* var a = {x: 1}, b = {x: 2}, c = {x: 3};
* R.minWith(cmp, [a, b, c]); //=> {x: 1}
*/
// TODO: combine this with maxWith?
R.minWith = curry2(function _minWith(keyFn, list) {
if (!(list && list.length > 0)) {
return;
}
var idx = 0, winner = list[idx], min = keyFn(list[idx]), testKey;
while (++idx < list.length) {
testKey = keyFn(list[idx]);
if (testKey < min) {
min = testKey;
winner = list[idx];
}
}
return winner;
});
// String Functions
// ----------------
//
// Much of the String.prototype API exposed as simple functions.
// --------
/**
* returns a subset of a string between one index and another.
*
* @func
* @memberOf R
* @category string
* @sig Number -> Number -> String -> String
* @param {Number} indexA An integer between 0 and the length of the string.
* @param {Number} indexB An integer between 0 and the length of the string.
* @param {String} The string to extract from
* @return {String} the extracted substring
* @see R.invoker
* @example
*
* R.substring(2, 5, 'abcdefghijklm'); //=> 'cde'
*/
var substring = R.substring = invoker('substring', String.prototype);
/**
* The trailing substring of a String starting with the nth character:
*
* @func
* @memberOf R
* @category string
* @sig Number -> String -> String
* @param {Number} indexA An integer between 0 and the length of the string.
* @param {String} The string to extract from
* @return {String} the extracted substring
* @see R.invoker
* @example
*
* R.substringFrom(8, 'abcdefghijklm'); //=> 'ijklm'
*/
R.substringFrom = flip(substring)(void 0);
/**
* The leading substring of a String ending before the nth character:
*
* @func
* @memberOf R
* @category string
* @sig Number -> String -> String
* @param {Number} indexA An integer between 0 and the length of the string.
* @param {String} The string to extract from
* @return {String} the extracted substring
* @see R.invoker
* @example
*
* R.substringTo(8, 'abcdefghijklm'); //=> 'abcdefgh'
*/
R.substringTo = substring(0);
/**
* The character at the nth position in a String:
*
* @func
* @memberOf R
* @category string
* @sig Number -> String -> String
* @param {Number} index An integer between 0 and the length of the string.
* @param {String} str The string to extract a char from
* @return {String} the character at `index` of `str`
* @see R.invoker
* @example
*
* R.charAt(8, 'abcdefghijklm'); //=> 'i'
*/
R.charAt = invoker('charAt', String.prototype);
/**
* The ascii code of the character at the nth position in a String:
*
* @func
* @memberOf R
* @category string
* @sig Number -> String -> Number
* @param {Number} index An integer between 0 and the length of the string.
* @param {String} str The string to extract a charCode from
* @return {Number} the code of the character at `index` of `str`
* @see R.invoker
* @example
*
* R.charCodeAt(8, 'abcdefghijklm'); //=> 105
* // (... 'a' ~ 97, 'b' ~ 98, ... 'i' ~ 105)
*/
R.charCodeAt = invoker('charCodeAt', String.prototype);
/**
* Tests a regular expression agains a String
*
* @func
* @memberOf R
* @category string
* @sig RegExp -> String -> [String] | null
* @param {RegExp} rx A regular expression.
* @param {String} str The string to match against
* @return {Array} The list of matches, or null if no matches found
* @see R.invoker
* @example
*
* R.match(/([a-z]a)/g, 'bananas'); //=> ['ba', 'na', 'na']
*/
R.match = invoker('match', String.prototype);
/**
* Finds the first index of a substring in a string, returning -1 if it's not present
*
* @func
* @memberOf R
* @category string
* @sig String -> String -> Number
* @param {String} c A string to find.
* @param {String} str The string to search in
* @return {Number} The first index of `c` or -1 if not found
* @see R.invoker
* @example
*
* R.strIndexOf('c', 'abcdefg'); //=> 2
*/
R.strIndexOf = curry2(function _strIndexOf(c, str) {
return str.indexOf(c);
});
/**
*
* Finds the last index of a substring in a string, returning -1 if it's not present
*
* @func
* @memberOf R
* @category string
* @sig String -> String -> Number
* @param {String} c A string to find.
* @param {String} str The string to search in
* @return {Number} The last index of `c` or -1 if not found
* @see R.invoker
* @example
*
* R.strLastIndexOf('a', 'banana split'); //=> 5
*/
R.strLastIndexOf = curry2(function(c, str) {
return str.lastIndexOf(c);
});
/**
* The upper case version of a string.
*
* @func
* @memberOf R
* @category string
* @sig String -> String
* @param {string} str The string to upper case.
* @return {string} The upper case version of `str`.
* @example
*
* R.toUpperCase('abc'); //=> 'ABC'
*/
R.toUpperCase = invoker('toUpperCase', String.prototype);
/**
* The lower case version of a string.
*
* @func
* @memberOf R
* @category string
* @sig String -> String
* @param {string} str The string to lower case.
* @return {string} The lower case version of `str`.
* @example
*
* R.toLowerCase('XYZ'); //=> 'xyz'
*/
R.toLowerCase = invoker('toLowerCase', String.prototype);
/**
* Splits a string into an array of strings based on the given
* separator.
*
* @func
* @memberOf R
* @category string
* @sig String -> String -> [String]
* @param {string} sep The separator string.
* @param {string} str The string to separate into an array.
* @return {Array} The array of strings from `str` separated by `str`.
* @example
*
* var pathComponents = R.split('/');
* R.tail(pathComponents('/usr/local/bin/node')); //=> ['usr', 'local', 'bin', 'node']
*
* R.split('.', 'a.b.c.xyz.d'); //=> ['a', 'b', 'c', 'xyz', 'd']
*/
R.split = invoker('split', String.prototype, 1);
/**
* internal path function
* Takes an array, paths, indicating the deep set of keys
* to find.
*
* @private
* @memberOf R
* @category string
* @param {Array} paths An array of strings to map to object properties
* @param {Object} obj The object to find the path in
* @return {Array} The value at the end of the path or `undefined`.
* @example
*
* path(['a', 'b'], {a: {b: 2}}); //=> 2
*/
function path(paths, obj) {
var idx = -1, length = paths.length, val;
if (obj == null) { return; }
val = obj;
while (val != null && ++idx < length) {
val = val[paths[idx]];
}
return val;
}
/**
* Retrieve a nested path on an object seperated by the specified
* separator value.
*
* @func
* @memberOf R
* @category string
* @sig String -> String -> {*} -> *
* @param {string} sep The separator to use in `path`.
* @param {string} path The path to use.
* @return {*} The data at `path`.
* @example
*
* R.pathOn('/', 'a/b/c', {a: {b: {c: 3}}}); //=> 3
*/
R.pathOn = curry3(function pathOn(sep, str, obj) {
return path(str.split(sep), obj);
});
/**
* Retrieve a nested path on an object seperated by periods
*
* @func
* @memberOf R
* @category string
* @sig String -> {*} -> *
* @param {string} path The dot path to use.
* @return {*} The data at `path`.
* @example
*
* R.path('a.b', {a: {b: 2}}); //=> 2
*/
R.path = R.pathOn('.');
// Data Analysis and Grouping Functions
// ------------------------------------
//
// Functions performing SQL-like actions on lists of objects. These do
// not have any SQL-like optimizations performed on them, however.
// --------
/**
* Reasonable analog to SQL `select` statement.
*
* @func
* @memberOf R
* @category object
* @category relation
* @string [k] -> [{k: v}] -> [{k: v}]
* @param {Array} props The property names to project
* @param {Array} objs The objects to query
* @return {Array} An array of objects with just the `props` properties.
* @example
*
* var abby = {name: 'Abby', age: 7, hair: 'blond', grade: 2};
* var fred = {name: 'Fred', age: 12, hair: 'brown', grade: 7};
* var kids = [abby, fred];
* R.project(['name', 'grade'], kids); //=> [{name: 'Abby', grade: 2}, {name: 'Fred', grade: 7}]
*/
R.project = useWith(map, R.pickAll, identity); // passing `identity` gives correct arity
/**
* Determines whether the given property of an object has a specific
* value according to strict equality (`===`). Most likely used to
* filter a list:
*
* @func
* @memberOf R
* @category relation
* @sig k -> v -> {k: v} -> Boolean
* @param {string|number} name The property name (or index) to use.
* @param {*} val The value to compare the property with.
* @return {boolean} `true` if the properties are equal, `false` otherwise.
* @example
*
* var abby = {name: 'Abby', age: 7, hair: 'blond'};
* var fred = {name: 'Fred', age: 12, hair: 'brown'};
* var rusty = {name: 'Rusty', age: 10, hair: 'brown'};
* var alois = {name: 'Alois', age: 15, disposition: 'surly'};
* var kids = [abby, fred, rusty, alois];
* var hasBrownHair = R.propEq('hair', 'brown');
* R.filter(hasBrownHair, kids); //=> [fred, rusty]
*/
R.propEq = curry3(function propEq(name, val, obj) {
return obj[name] === val;
});
/**
* Combines two lists into a set (i.e. no duplicates) composed of the
* elements of each list.
*
* @func
* @memberOf R
* @category relation
* @sig [a] -> [a] -> [a]
* @param {Array} as The first list.
* @param {Array} bs The second list.
* @return {Array} The first and second lists concatenated, with
* duplicates removed.
* @example
*
* R.union([1, 2, 3], [2, 3, 4]); //=> [1, 2, 3, 4]
*/
R.union = compose(uniq, R.concat);
/**
* Combines two lists into a set (i.e. no duplicates) composed of the elements of each list. Duplication is
* determined according to the value returned by applying the supplied predicate to two list elements.
*
* @func
* @memberOf R
* @category relation
* @sig (a,a -> Boolean) -> [a] -> [a] -> [a]
* @param {Function} pred
* @param {Array} list1 The first list.
* @param {Array} list2 The second list.
* @return {Array} The first and second lists concatenated, with
* duplicates removed.
* @see R.union
* @example
*
* function cmp(x, y) { return x.a === y.a; }
* var l1 = [{a: 1}, {a: 2}];
* var l2 = [{a: 1}, {a: 4}];
* R.unionWith(cmp, l1, l2); //=> [{a: 1}, {a: 2}, {a: 4}]
*/
R.unionWith = curry3(function _unionWith(pred, list1, list2) {
return uniqWith(pred, concat(list1, list2));
});
/**
* Finds the set (i.e. no duplicates) of all elements in the first list not contained in the second list.
*
* @func
* @memberOf R
* @category relation
* @sig [a] -> [a] -> [a]
* @param {Array} list1 The first list.
* @param {Array} list2 The second list.
* @return {Array} The elements in `list1` that are not in `list2`
* @see R.differenceWith
* @example
*
* R.difference([1,2,3,4], [7,6,5,4,3]); //=> [1,2]
* R.difference([7,6,5,4,3], [1,2,3,4]); //=> [7,6,5]
*/
R.difference = curry2(function _difference(first, second) {
return uniq(reject(flip(contains)(second), first));
});
/**
* Finds the set (i.e. no duplicates) of all elements in the first list not contained in the second list.
* Duplication is determined according to the value returned by applying the supplied predicate to two list
* elements.
*
* @func
* @memberOf R
* @category relation
* @sig (a,a -> Boolean) -> [a] -> [a] -> [a]
* @param {Function} pred
* @param {Array} list1 The first list.
* @param {Array} list2 The second list.
* @see R.difference
* @return {Array} The elements in `list1` that are not in `list2`
* @example
*
* function cmp(x, y) { return x.a === y.a; }
* var l1 = [{a: 1}, {a: 2}, {a: 3}];
* var l2 = [{a: 3}, {a: 4}];
* R.differenceWith(cmp, l1, l2); //=> [{a: 1}, {a: 2}]
*
*/
R.differenceWith = curry3(function differenceWith(pred, first, second) {
return uniqWith(pred)(reject(flip(R.containsWith(pred))(second), first));
});
/**
* Combines two lists into a set (i.e. no duplicates) composed of those elements common to both lists.
*
* @func
* @memberOf R
* @category relation
* @sig [a] -> [a] -> [a]
* @param {Array} list1 The first list.
* @param {Array} list2 The second list.
* @see R.intersectionWith
* @return {Array} The list of elements found in both `list1` and `list2`
* @example
*
* R.intersection([1,2,3,4], [7,6,5,4,3]); //=> [4, 3]
*/
R.intersection = curry2(function intersection(list1, list2) {
return uniq(filter(flip(contains)(list1), list2));
});
/**
* Combines two lists into a set (i.e. no duplicates) composed of those
* elements common to both lists. Duplication is determined according
* to the value returned by applying the supplied predicate to two list
* elements.
*
* @func
* @memberOf R
* @category relation
* @sig (a,a -> Boolean) -> [a] -> [a] -> [a]
* @param {Function} pred A predicate function that determines whether
* the two supplied elements are equal.
* Signatrue: a -> a -> Boolean
* @param {Array} list1 One list of items to compare
* @param {Array} list2 A second list of items to compare
* @see R.intersection
* @return {Array} A new list containing those elements common to both lists.
* @example
*
* var buffaloSpringfield = [
* {id: 824, name: 'Richie Furay'},
* {id: 956, name: 'Dewey Martin'},
* {id: 313, name: 'Bruce Palmer'},
* {id: 456, name: 'Stephen Stills'},
* {id: 177, name: 'Neil Young'}
* ];
* var csny = [
* {id: 204, name: 'David Crosby'},
* {id: 456, name: 'Stephen Stills'},
* {id: 539, name: 'Graham Nash'},
* {id: 177, name: 'Neil Young'}
* ];
*
* var sameId = function(o1, o2) {return o1.id === o2.id;};
*
* R.intersectionWith(sameId, buffaloSpringfield, csny);
* //=> [{id: 456, name: 'Stephen Stills'}, {id: 177, name: 'Neil Young'}]
*/
R.intersectionWith = curry3(function intersectionWith(pred, list1, list2) {
var results = [], idx = -1;
while (++idx < list1.length) {
if (containsWith(pred, list1[idx], list2)) {
results[results.length] = list1[idx];
}
}
return uniqWith(pred, results);
});
/**
* Creates a new list whose elements each have two properties: `val` is
* the value of the corresponding item in the list supplied, and `key`
* is the result of applying the supplied function to that item.
*
* @private
* @func
* @memberOf R
* @category relation
* @param {Function} fn An arbitrary unary function returning a potential
* object key. Signature: Any -> String
* @param {Array} list The list of items to process
* @return {Array} A new list with the described structure.
* @example
*
* var people = [
* {first: 'Fred', last: 'Flintstone', age: 23},
* {first: 'Betty', last: 'Rubble', age: 21},
* {first: 'George', last: 'Jetson', age: 29}
* ];
*
* var fullName = function(p) {return p.first + ' ' + p.last;};
*
* keyValue(fullName, people); //=>
* // [
* // {
* // key: 'Fred Flintstone',
* // val: {first: 'Fred', last: 'Flintstone', age: 23}
* // }, {
* // key: 'Betty Rubble',
* // val: {first: 'Betty', last: 'Rubble', age: 21}
* // }, {
* // key: 'George Jetson',
* // val: {first: 'George', last: 'Jetson', age: 29}
* // }
* // ];
*/
function keyValue(fn, list) { // TODO: Should this be made public?
return map(function(item) {return {key: fn(item), val: item};}, list);
}
/**
* Sorts the list according to a key generated by the supplied function.
*
* @func
* @memberOf R
* @category relation
* @sig (a -> String) -> [a] -> [a]
* @param {Function} fn The function mapping `list` items to keys.
* @param {Array} list The list to sort.
* @return {Array} A new list sorted by the keys generated by `fn`.
* @example
*
* var sortByFirstItem = R.sortBy(prop(0));
* var sortByNameCaseInsensitive = R.sortBy(compose(R.toLowerCase, prop('name')));
* var pairs = [[-1, 1], [-2, 2], [-3, 3]];
* sortByFirstItem(pairs); //=> [[-3, 3], [-2, 2], [-1, 1]]
* var alice = {
* name: 'ALICE',
* age: 101
* };
* var bob = {
* name: 'Bob',
* age: -10
* };
* var clara = {
* name: 'clara',
* age: 314.159
* };
* var people = [clara, bob, alice];
* sortByNameCaseInsensitive(people); //=> [alice, bob, clara]
*/
R.sortBy = curry2(function sortBy(fn, list) {
return pluck('val', keyValue(fn, list).sort(comparator(function(a, b) {return a.key < b.key;})));
});
/**
* Counts the elements of a list according to how many match each value
* of a key generated by the supplied function. Returns an object
* mapping the keys produced by `fn` to the number of occurrences in
* the list. Note that all keys are coerced to strings because of how
* JavaScript objects work.
*
* @func
* @memberOf R
* @category relation
* @sig (a -> String) -> [a] -> {*}
* @param {Function} fn The function used to map values to keys.
* @param {Array} list The list to count elements from.
* @return {Object} An object mapping keys to number of occurrences in the list.
* @example
*
* var numbers = [1.0, 1.1, 1.2, 2.0, 3.0, 2.2];
* var letters = R.split('', 'abcABCaaaBBc');
* R.countBy(Math.floor)(numbers); //=> {'1': 3, '2': 2, '3': 1}
* R.countBy(R.toLowerCase)(letters); //=> {'a': 5, 'b': 4, 'c': 3}
*/
R.countBy = curry2(function countBy(fn, list) {
return foldl(function(counts, obj) {
counts[obj.key] = (counts[obj.key] || 0) + 1;
return counts;
}, {}, keyValue(fn, list));
});
/**
* @private
* @param {Function} fn The strategy for extracting function names from an object
* @return {Function} A function that takes an object and returns an array of function names
*
*/
var functionsWith = function(fn) {
return function(obj) {
return R.filter(function(key) { return typeof obj[key] === 'function'; }, fn(obj));
};
};
/**
* Returns a list of function names of object's own functions
*
* @func
* @memberOf R
* @category Object
* @sig {*} -> [String]
* @param {Object} obj The objects with functions in it
* @return {Array} returns a list of the object's own properites that map to functions
* @example
*
* R.functions(R); // returns list of ramda's own function names
*
* var F = function() { this.x = function(){}; this.y = 1; }
* F.prototype.z = function() {};
* F.prototype.a = 100;
* R.functions(new F()); //=> ["x"]
*/
R.functions = functionsWith(R.keys);
/**
* Returns a list of function names of object's own and prototype functions
*
* @func
* @memberOf R
* @category Object
* @sig {*} -> [String]
* @param {Object} obj The objects with functions in it
* @return {Array} returns a list of the object's own properites and prototype
* properties that map to functions
* @example
*
* R.functionsIn(R); // returns list of ramda's own and prototype function names
*
* var F = function() { this.x = function(){}; this.y = 1; }
* F.prototype.z = function() {};
* F.prototype.a = 100;
* R.functionsIn(new F()); //=> ["x", "z"]
*/
R.functionsIn = functionsWith(R.keysIn);
// All the functional goodness, wrapped in a nice little package, just for you!
return R;
}));<|fim▁end|> | |
<|file_name|>minicircuits.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3.4
#
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""<|fim▁hole|>
See http://www.minicircuits.com/softwaredownload/Prog_Manual-6-Programmable_Attenuator.pdf
"""
from mobly.controllers import attenuator
from mobly.controllers.attenuator_lib import telnet_client
class AttenuatorDevice(object):
"""This provides a specific telnet-controlled implementation of
AttenuatorDevice for Mini-Circuits RC-DAT attenuators.
Attributes:
path_count: The number of signal attenuation path this device has.
"""
def __init__(self, path_count=1):
self.path_count = path_count
# The telnet client used to communicate with the attenuator device.
self._telnet_client = telnet_client.TelnetClient(
tx_cmd_separator="\r\n", rx_cmd_separator="\r\n", prompt="")
@property
def is_open(self):
"""This function returns the state of the telnet connection to the
underlying AttenuatorDevice.
Returns:
True if there is a successfully open connection to the
AttenuatorDevice.
"""
return bool(self._telnet_client.is_open)
def open(self, host, port=23):
"""Opens a telnet connection to the desired AttenuatorDevice and
queries basic information.
Args::
host: A valid hostname (IP address or DNS-resolvable name) to an
MC-DAT attenuator instrument.
port: An optional port number (defaults to telnet default 23)
"""
self._telnet_client.open(host, port)
config_str = self._telnet_client.cmd("MN?")
if config_str.startswith("MN="):
config_str = config_str[len("MN="):]
self.properties = dict(
zip(['model', 'max_freq', 'max_atten'], config_str.split("-", 2)))
self.max_atten = float(self.properties['max_atten'])
def close(self):
"""Closes a telnet connection to the desired attenuator device.
This should be called as part of any teardown procedure prior to the
attenuator instrument leaving scope.
"""
if self.is_open:
self._telnet_client.close()
def set_atten(self, idx, value):
"""Sets the attenuation value for a particular signal path.
Args:
idx: Zero-based index int which is the identifier for a particular
signal path in an instrument. For instruments that only has one
channel, this is ignored by the device.
value: A float that is the attenuation value to set.
Raises:
Error is raised if the underlying telnet connection to the
instrument is not open.
IndexError is raised if the index of the attenuator is greater than
the maximum index of the underlying instrument.
ValueError is raised if the requested set value is greater than the
maximum attenuation value.
"""
if not self.is_open:
raise attenuator.Error(
"Connection to attenuator at %s is not open!" %
self._telnet_client.host)
if idx + 1 > self.path_count:
raise IndexError("Attenuator index out of range!", self.path_count,
idx)
if value > self.max_atten:
raise ValueError("Attenuator value out of range!", self.max_atten,
value)
# The actual device uses one-based index for channel numbers.
self._telnet_client.cmd("CHAN:%s:SETATT:%s" % (idx + 1, value))
def get_atten(self, idx=0):
"""This function returns the current attenuation from an attenuator at a
given index in the instrument.
Args:
idx: This zero-based index is the identifier for a particular
attenuator in an instrument.
Raises:
Error is raised if the underlying telnet connection to the
instrument is not open.
Returns:
A float that is the current attenuation value.
"""
if not self.is_open:
raise attenuator.Error(
"Connection to attenuator at %s is not open!" %
self._telnet_client.host)
if idx + 1 > self.path_count or idx < 0:
raise IndexError("Attenuator index out of range!", self.path_count,
idx)
atten_val_str = self._telnet_client.cmd("CHAN:%s:ATT?" % (idx + 1))
atten_val = float(atten_val_str)
return atten_val<|fim▁end|> | This module has the class for controlling Mini-Circuits RCDAT series
attenuators over Telnet. |
<|file_name|>divisible_by_power_of_2.rs<|end_file_name|><|fim▁begin|>use integer::Integer;
use malachite_base::num::arithmetic::traits::DivisibleByPowerOf2;
impl<'a> DivisibleByPowerOf2 for &'a Integer {
/// Returns whether `self` is divisible by 2<sup>`pow`</sup>. If `self` is 0, the result is
/// always true; otherwise, it is equivalent to `self.trailing_zeros().unwrap() <= pow`, but
/// more efficient.
///
/// Time: worst case O(n)
///
/// Additional memory: worst case O(1)
///
/// where n = `self.significant_bits`
///
/// # Examples
/// ```
/// extern crate malachite_base;
/// extern crate malachite_nz;
///
/// use malachite_base::num::arithmetic::traits::DivisibleByPowerOf2;
/// use malachite_base::num::basic::traits::Zero;
/// use malachite_nz::integer::Integer;
///
/// assert_eq!(Integer::ZERO.divisible_by_power_of_2(100), true);
/// assert_eq!(Integer::from(-100).divisible_by_power_of_2(2), true);
/// assert_eq!(Integer::from(100u32).divisible_by_power_of_2(3), false);
/// assert_eq!((-Integer::trillion()).divisible_by_power_of_2(12), true);
/// assert_eq!((-Integer::trillion()).divisible_by_power_of_2(13), false);
/// ```
fn divisible_by_power_of_2(self, pow: u64) -> bool {
self.abs.divisible_by_power_of_2(pow)
}<|fim▁hole|><|fim▁end|> | } |
<|file_name|>tracing_controller.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Copyright 2016 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.
'''Tracing controller class. This class manages
multiple tracing agents and collects data from all of them. It also
manages the clock sync process.
'''
from __future__ import print_function
import ast
import json
import sys
import tempfile
import uuid
import py_utils
from systrace import trace_result
from systrace import tracing_agents
from py_trace_event import trace_event
TRACE_DATA_CONTROLLER_NAME = 'systraceController'
def ControllerAgentClockSync(issue_ts, name):
"""Record the clock sync marker for controller tracing agent.
Unlike with the other tracing agents, the tracing controller should not
call this directly. Rather, it is called via callback from the other
tracing agents when they write a trace.
"""
trace_event.clock_sync(name, issue_ts=issue_ts)
class TracingControllerAgent(tracing_agents.TracingAgent):
def __init__(self):
# TODO(https://crbug.com/1262296): Update this after Python2 trybots retire.
# pylint: disable=super-with-arguments
super(TracingControllerAgent, self).__init__()
self._log_path = None
@py_utils.Timeout(tracing_agents.START_STOP_TIMEOUT)
def StartAgentTracing(self, config, timeout=None):
"""Start tracing for the controller tracing agent.
Start tracing for the controller tracing agent. Note that
the tracing controller records the "controller side"
of the clock sync records, and nothing else.
"""
del config
if not trace_event.trace_can_enable():
raise RuntimeError('Cannot enable trace_event;'
' ensure py_utils is in PYTHONPATH')
controller_log_file = tempfile.NamedTemporaryFile(delete=False)
self._log_path = controller_log_file.name
controller_log_file.close()
trace_event.trace_enable(self._log_path)
return True
@py_utils.Timeout(tracing_agents.START_STOP_TIMEOUT)
def StopAgentTracing(self, timeout=None):
"""Stops tracing for the controller tracing agent.
"""
# pylint: disable=no-self-use
# This function doesn't use self, but making it a member function
# for consistency with the other TracingAgents
trace_event.trace_disable()
return True
@py_utils.Timeout(tracing_agents.GET_RESULTS_TIMEOUT)
def GetResults(self, timeout=None):
"""Gets the log output from the controller tracing agent.
This output only contains the "controller side" of the clock sync records.
"""
with open(self._log_path, 'r') as outfile:
data = ast.literal_eval(outfile.read() + ']')
# Explicitly set its own clock domain. This will stop the Systrace clock
# domain from incorrectly being collapsed into the on device clock domain.
formatted_data = {
'traceEvents': data,
'metadata': {
'clock-domain': 'SYSTRACE',
}
}
return trace_result.TraceResult(TRACE_DATA_CONTROLLER_NAME,
json.dumps(formatted_data))
def SupportsExplicitClockSync(self):
"""Returns whether this supports explicit clock sync.
Although the tracing controller conceptually supports explicit clock
sync, it is not an agent controlled by other controllers so it does not
define RecordClockSyncMarker (rather, the recording of the "controller
side" of the clock sync marker is done in _IssueClockSyncMarker). Thus,
SupportsExplicitClockSync must return false.
"""
return False
# TODO(https://crbug.com/1262296): Update this after Python2 trybots retire.
# pylint: disable=arguments-differ
# pylint: disable=unused-argument
def RecordClockSyncMarker(self, sync_id, callback):
raise NotImplementedError
# TODO(https://crbug.com/1262296): Update this after Python2 trybots retire.
# pylint: disable=useless-object-inheritance
class TracingController(object):
def __init__(self, agents_with_config, controller_config):
"""Create tracing controller.
Create a tracing controller object. Note that the tracing
controller is also a tracing agent.
Args:
agents_with_config: List of tracing agents for this controller with the
corresponding tracing configuration objects.
controller_config: Configuration options for the tracing controller.
"""
self._child_agents = None
self._child_agents_with_config = agents_with_config
self._controller_agent = TracingControllerAgent()
self._controller_config = controller_config
self._trace_in_progress = False
self.all_results = None
@property
def get_child_agents(self):
return self._child_agents
def StartTracing(self):
"""Start tracing for all tracing agents.
This function starts tracing for both the controller tracing agent
and the child tracing agents.
Returns:
Boolean indicating whether or not the start tracing succeeded.
Start tracing is considered successful if at least the
controller tracing agent was started.
"""
assert not self._trace_in_progress, 'Trace already in progress.'
self._trace_in_progress = True
# Start the controller tracing agents. Controller tracing agent
# must be started successfully to proceed.
if not self._controller_agent.StartAgentTracing(
self._controller_config,<|fim▁hole|> timeout=self._controller_config.timeout):
print('Unable to start controller tracing agent.')
return False
# Start the child tracing agents.
succ_agents = []
for agent_and_config in self._child_agents_with_config:
agent = agent_and_config.agent
config = agent_and_config.config
if agent.StartAgentTracing(config,
timeout=self._controller_config.timeout):
succ_agents.append(agent)
else:
print('Agent %s not started.' % str(agent))
# Print warning if all agents not started.
na = len(self._child_agents_with_config)
ns = len(succ_agents)
if ns < na:
print('Warning: Only %d of %d tracing agents started.' % (ns, na))
self._child_agents = succ_agents
return True
def StopTracing(self):
"""Issue clock sync marker and stop tracing for all tracing agents.
This function stops both the controller tracing agent
and the child tracing agents. It issues a clock sync marker prior
to stopping tracing.
Returns:
Boolean indicating whether or not the stop tracing succeeded
for all agents.
"""
assert self._trace_in_progress, 'No trace in progress.'
self._trace_in_progress = False
# Issue the clock sync marker and stop the child tracing agents.
self._IssueClockSyncMarker()
succ_agents = []
for agent in self._child_agents:
if agent.StopAgentTracing(timeout=self._controller_config.timeout):
succ_agents.append(agent)
else:
print('Agent %s not stopped.' % str(agent))
# Stop the controller tracing agent. Controller tracing agent
# must be stopped successfully to proceed.
if not self._controller_agent.StopAgentTracing(
timeout=self._controller_config.timeout):
print('Unable to stop controller tracing agent.')
return False
# Print warning if all agents not stopped.
na = len(self._child_agents)
ns = len(succ_agents)
if ns < na:
print('Warning: Only %d of %d tracing agents stopped.' % (ns, na))
self._child_agents = succ_agents
# Collect the results from all the stopped tracing agents.
all_results = []
for agent in self._child_agents + [self._controller_agent]:
try:
result = agent.GetResults(
timeout=self._controller_config.collection_timeout)
if not result:
print('Warning: Timeout when getting results from %s.' % str(agent))
continue
if result.source_name in [r.source_name for r in all_results]:
print ('Warning: Duplicate tracing agents named %s.' %
result.source_name)
all_results.append(result)
# Check for exceptions. If any exceptions are seen, reraise and abort.
# Note that a timeout exception will be swalloed by the timeout
# mechanism and will not get to that point (it will return False instead
# of the trace result, which will be dealt with above)
except:
print('Warning: Exception getting results from %s:' % str(agent))
print('Try checking android device storage permissions for chrome')
print(sys.exc_info()[0])
raise
self.all_results = all_results
return all_results
def GetTraceType(self):
"""Return a string representing the child agents that are being traced."""
sorted_agents = sorted(map(str, self._child_agents))
return ' + '.join(sorted_agents)
def _IssueClockSyncMarker(self):
"""Issue clock sync markers to all the child tracing agents."""
for agent in self._child_agents:
if agent.SupportsExplicitClockSync():
sync_id = GetUniqueSyncID()
agent.RecordClockSyncMarker(sync_id, ControllerAgentClockSync)
def GetUniqueSyncID():
"""Get a unique sync ID.
Gets a unique sync ID by generating a UUID and converting it to a string
(since UUIDs are not JSON serializable)
"""
return str(uuid.uuid4())
# TODO(https://crbug.com/1262296): Update this after Python2 trybots retire.
# pylint: disable=useless-object-inheritance
class AgentWithConfig(object):
def __init__(self, agent, config):
self.agent = agent
self.config = config
def CreateAgentsWithConfig(options, modules):
"""Create tracing agents.
This function will determine which tracing agents are valid given the
options and create those agents along with their corresponding configuration
object.
Args:
options: The command-line options.
modules: The modules for either Systrace or profile_chrome.
TODO(washingtonp): After all profile_chrome agents are in
Systrace, this parameter will no longer be valid.
Returns:
A list of AgentWithConfig options containing agents and their corresponding
configuration object.
"""
result = []
for module in modules:
config = module.get_config(options)
agent = module.try_create_agent(config)
if agent and config:
result.append(AgentWithConfig(agent, config))
return [x for x in result if x and x.agent]
class TracingControllerConfig(tracing_agents.TracingConfig):
def __init__(self, output_file, trace_time, write_json,
link_assets, asset_dir, timeout, collection_timeout,
device_serial_number, target, trace_buf_size):
tracing_agents.TracingConfig.__init__(self)
self.output_file = output_file
self.trace_time = trace_time
self.write_json = write_json
self.link_assets = link_assets
self.asset_dir = asset_dir
self.timeout = timeout
self.collection_timeout = collection_timeout
self.device_serial_number = device_serial_number
self.target = target
self.trace_buf_size = trace_buf_size
def GetControllerConfig(options):
return TracingControllerConfig(options.output_file, options.trace_time,
options.write_json,
options.link_assets, options.asset_dir,
options.timeout, options.collection_timeout,
options.device_serial_number, options.target,
options.trace_buf_size)
def GetChromeStartupControllerConfig(options):
return TracingControllerConfig(None, options.trace_time,
options.write_json, None, None, None, None,
None, None, options.trace_buf_size)<|fim▁end|> | |
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter,
OAuth2LoginView,
OAuth2CallbackView)
from allauth.socialaccount import requests
from allauth.socialaccount.models import SocialLogin, SocialAccount
from allauth.utils import get_user_model
from provider import GoogleProvider
User = get_user_model()
class GoogleOAuth2Adapter(OAuth2Adapter):
provider_id = GoogleProvider.id
access_token_url = 'https://accounts.google.com/o/oauth2/token'
authorize_url = 'https://accounts.google.com/o/oauth2/auth'
profile_url = 'https://www.googleapis.com/oauth2/v1/userinfo'
def complete_login(self, request, app, token):
resp = requests.get(self.profile_url,
{ 'access_token': token.token,
'alt': 'json' })
extra_data = resp.json
# extra_data is something of the form:
#
# {u'family_name': u'Penners', u'name': u'Raymond Penners',
# u'picture': u'https://lh5.googleusercontent.com/-GOFYGBVOdBQ/AAAAAAAAAAI/AAAAAAAAAGM/WzRfPkv4xbo/photo.jpg',
# u'locale': u'nl', u'gender': u'male',
# u'email': u'[email protected]',
# u'link': u'https://plus.google.com/108204268033311374519',
# u'given_name': u'Raymond', u'id': u'108204268033311374519',
# u'verified_email': True}
#
# TODO: We could use verified_email to bypass allauth email verification
uid = str(extra_data['id'])
user = User(email=extra_data.get('email', ''),
last_name=extra_data.get('family_name', ''),
first_name=extra_data.get('given_name', ''))
account = SocialAccount(extra_data=extra_data,<|fim▁hole|> uid=uid,
provider=self.provider_id,
user=user)
return SocialLogin(account)
oauth2_login = OAuth2LoginView.adapter_view(GoogleOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(GoogleOAuth2Adapter)<|fim▁end|> | |
<|file_name|>solution.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# SPDX-License-Identifier: AGPL-3.0-or-later
#
# snippy - software development and maintenance notes manager.
# Copyright 2017-2020 Heikki J. Laaksonen <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""solution: Default solutions for testing."""
from tests.lib.helper import Helper
class Solution(object): # pylint: disable=too-few-public-methods
"""Default solutions for testing."""
_BEATS = 0
_NGINX = 1
_KAFKA = 2
_KAFKA_MKDN = 3
# Default time is same for the default content. See 'Test case layouts and
# data structures' for more information.
DEFAULT_TIME = '2017-10-20T11:11:19.000001+00:00'
# Default content must be always set so that it reflects content stored
# into database. For example the tags must be sorted in correct order.
# This forces defining erroneous content in each test case. This improves
# the readability and maintainability of failure testing.
_DEFAULTS = ({
'category': 'solution',
'data':('################################################################################',
'## Description',
'################################################################################',
'',
' # Debug Elastic Beats',
'',
'################################################################################',
'## References',
'################################################################################',
'',
' # Enable logs from Filebeat',
' > https://www.elastic.co/guide/en/beats/filebeat/master/enable-filebeat-debugging.html',
'',
'################################################################################',
'## Commands',
'################################################################################',
'',
' # Run Filebeat with full log level',
' $ ./filebeat -e -c config/filebeat.yml -d "*"',
'',
'################################################################################',
'## Solutions',
'################################################################################',
'',
'################################################################################',
'## Configurations',
'################################################################################',
'',
'################################################################################',
'## Whiteboard',
'################################################################################',
''),
'brief': 'Debugging Elastic Beats',
'description': 'Debug Elastic Beats',
'name': '',
'groups': ('beats',),
'tags': ('Elastic', 'beats', 'debug', 'filebeat', 'howto'),
'links': ('https://www.elastic.co/guide/en/beats/filebeat/master/enable-filebeat-debugging.html',),
'source': '',
'versions': (),
'languages': (),
'filename': 'howto-debug-elastic-beats.txt',
'created': DEFAULT_TIME,
'updated': DEFAULT_TIME,
'uuid': '21cd5827-b6ef-4067-b5ac-3ceac07dde9f',
'digest': '4346ba4c792474308bc66bd16d747875bef9b431044824987e302b726c1d298e'
}, {
'category': 'solution',
'data':('################################################################################',
'## Description',
'################################################################################',
'',
' # Instructions how to debug nginx.',
'',
'################################################################################',
'## References',
'################################################################################',
'',
' # Official nginx debugging',
' > https://www.nginx.com/resources/admin-guide/debug/',
'',
'################################################################################',
'## Commands',
'################################################################################',
'',
' # Test if nginx is configured with --with-debug',
" $ nginx -V 2>&1 | grep -- '--with-debug'",
'',
' # Check the logs are forwarded to stdout/stderr and remove links',
' $ ls -al /var/log/nginx/',
' $ unlink /var/log/nginx/access.log',
' $ unlink /var/log/nginx/error.log',
'',
' # Reloading nginx configuration',
' $ nginx -s reload',
'',
'################################################################################',
'## Solutions',
'################################################################################',
'',
'################################################################################',
'## Configurations',
'################################################################################',
'',
' # Configuring nginx default.conf',
' $ vi conf.d/default.conf',
' upstream kibana_servers {',
' server kibana:5601;',
' }',
' upstream elasticsearch_servers {',
' server elasticsearch:9200;',
' }',
'',
'################################################################################',
'## Whiteboard',
'################################################################################',
'',
' # Change nginx configuration',
" $ docker exec -i -t $(docker ps | egrep -m 1 'petelk/nginx' | awk '{print $1}') /bin/bash",
''),
'brief': 'Debugging nginx',
'description': 'Instructions how to debug nginx.',
'name': '',
'groups': ('nginx',),
'tags': ('debug', 'howto', 'logging', 'nginx'),
'links': ('https://www.nginx.com/resources/admin-guide/debug/', ),
'source': '',
'versions': (),
'languages': (),
'filename': 'howto-debug-nginx.txt',
'created': DEFAULT_TIME,
'updated': DEFAULT_TIME,
'uuid': '22cd5827-b6ef-4067-b5ac-3ceac07dde9f',
'digest': '6cfe47a8880a8f81b66ff6bd71e795069ed1dfdd259c9fd181133f683c7697eb'
}, {
'category': 'solution',
'data':('################################################################################',
'## Description',
'################################################################################',
'',
' # Investigating docker log driver and especially the Kafka plugin.',
'',
'################################################################################',
'## References',
'################################################################################',
'',
' # Kube Kafka log driver',
' > https://github.com/MickayG/moby-kafka-logdriver',
'',
' # Logs2Kafka',
' > https://groups.google.com/forum/#!topic/kubernetes-users/iLDsG85exRQ',
' > https://github.com/garo/logs2kafka',
'',
'################################################################################',
'## Commands',
'################################################################################',
'',
' # Get logs from pods',
' $ kubectl get pods',
' $ kubectl logs kafka-0',
'',
' # Install docker log driver for Kafka',
' $ docker ps --format "{{.Names}}" | grep -E \'kafka|logstash\'',
' $ docker inspect k8s_POD_kafka-0...',
" $ docker inspect --format '{{ .NetworkSettings.IPAddress }}' k8s_POD_kafka-0...",
' $ docker plugin install --disable mickyg/kafka-logdriver:latest',
' $ docker plugin set mickyg/kafka-logdriver:latest KAFKA_BROKER_ADDR="10.2.28.10:9092"',
' $ docker plugin inspect mickyg/kafka-logdriver',
' $ docker plugin enable mickyg/kafka-logdriver:latest',
' $ docker run --log-driver mickyg/kafka-logdriver:latest hello-world',
' $ docker plugin disable mickyg/kafka-logdriver:latest',
'',
' # Get current docker log driver',
" $ docker info |grep 'Logging Driver' # Default driver",
' $ docker ps --format "{{.Names}}" | grep -E \'kafka|logstash\'',
' $ docker inspect k8s_POD_kafka-0...',
" $ docker inspect --format '{{ .NetworkSettings.IPAddress }}' k8s_POD_logstash...",
" $ docker inspect --format '{{ .NetworkSettings.IPAddress }}' k8s_POD_kafka-0...",
' $ docker inspect $(docker ps | grep POD | awk \'{print $1}\') | grep -E "Hostname|NetworkID',
' $ docker inspect $(docker ps | grep POD | awk \'{print $1}\') | while read line ; do egrep -E ' +
'\'"Hostname"|"IPAddress"\' ; done | while read line ; do echo $line ; done',
'',
'################################################################################',
'## Solutions',
'################################################################################',
'',
'################################################################################',
'## Configurations',
'################################################################################',
'',
' # Logstash configuration',
' $ vi elk-stack/logstash/build/pipeline/kafka.conf',
' input {',
' gelf {}',
' }',
'',
' output {',
' elasticsearch {',
' hosts => ["elasticsearch"]',
' }',
' stdout {}',
' }',
'',
' # Kafka configuration',
' $ vi elk-stack/logstash/build/pipeline/kafka.conf',
' kafka {',<|fim▁hole|> ' codec => "plain"',
' bootstrap_servers => "kafka:9092"',
' consumer_threads => 1',
' }',
'',
'################################################################################',
'## Whiteboard',
'################################################################################',
''),
'brief': 'Testing docker log drivers',
'description': 'Investigating docker log driver and especially the Kafka plugin.',
'name': '',
'groups': ('docker',),
'tags': ('docker', 'driver', 'kafka', 'kubernetes', 'logging', 'logs2kafka', 'moby', 'plugin'),
'links': ('https://github.com/MickayG/moby-kafka-logdriver',
'https://github.com/garo/logs2kafka',
'https://groups.google.com/forum/#!topic/kubernetes-users/iLDsG85exRQ'),
'source': '',
'versions': (),
'languages': (),
'filename': 'kubernetes-docker-log-driver-kafka.txt',
'created': '2017-10-20T06:16:27.000001+00:00',
'updated': '2017-10-20T06:16:27.000001+00:00',
'uuid': '23cd5827-b6ef-4067-b5ac-3ceac07dde9f',
'digest': 'ee3f2ab7c63d6965ac2531003807f00caee178f6e1cbb870105c7df86e6d5be2'
}, {
'category': 'solution',
'data':('## Description',
'',
'Investigate docker log drivers and the logs2kafka log plugin.',
'',
'## References',
'',
' ```',
' # Kube Kafka log driver',
' > https://github.com/MickayG/moby-kafka-logdriver',
' ```',
'',
' ```',
' # Logs2Kafka',
' > https://groups.google.com/forum/#!topic/kubernetes-users/iLDsG85exRQ',
' > https://github.com/garo/logs2kafka',
' ```',
'',
'## Commands',
'',
' ```',
' # Get logs from pods',
' $ kubectl get pods',
' $ kubectl logs kafka-0',
' ```',
'',
' ```',
' # Install docker log driver for Kafka',
' $ docker ps --format "{{.Names}}" | grep -E \'kafka|logstash\'',
' $ docker inspect k8s_POD_kafka-0...',
' $ docker inspect --format \'{{ .NetworkSettings.IPAddress }}\' k8s_POD_kafka-0...',
' $ docker plugin install --disable mickyg/kafka-logdriver:latest',
' $ docker plugin set mickyg/kafka-logdriver:latest KAFKA_BROKER_ADDR="10.2.28.10:9092"',
' $ docker plugin inspect mickyg/kafka-logdriver',
' $ docker plugin enable mickyg/kafka-logdriver:latest',
' $ docker run --log-driver mickyg/kafka-logdriver:latest hello-world',
' $ docker plugin disable mickyg/kafka-logdriver:latest',
' ```',
'',
' ```',
' # Get current docker log driver',
' $ docker info |grep \'Logging Driver\' # Default driver',
' $ docker ps --format "{{.Names}}" | grep -E \'kafka|logstash\'',
' $ docker inspect k8s_POD_kafka-0...',
' $ docker inspect --format \'{{ .NetworkSettings.IPAddress }}\' k8s_POD_logstash...',
' $ docker inspect --format \'{{ .NetworkSettings.IPAddress }}\' k8s_POD_kafka-0...',
' $ docker inspect $(docker ps | grep POD | awk \'{print $1}\') | grep -E "Hostname|NetworkID',
' $ docker inspect $(docker ps | grep POD | awk \'{print $1}\') | while read line ; do egrep -E \'"Hostname"|"IPAddress"\' ; done | while read line ; do echo $line ; done', # noqa pylint: disable=line-too-long
' ```',
'',
'## Configurations',
'',
' ```',
' # Logstash configuration',
' $ vi elk-stack/logstash/build/pipeline/kafka.conf',
' input {',
' gelf {}',
' }',
'',
' output {',
' elasticsearch {',
' hosts => ["elasticsearch"]',
' }',
' stdout {}',
' }',
' ```',
'',
' ```',
' # Kafka configuration',
' $ vi elk-stack/logstash/build/pipeline/kafka.conf',
' kafka {',
' type => "argus.docker"',
' topics => ["dockerlogs"]',
' codec => "plain"',
' bootstrap_servers => "kafka:9092"',
' consumer_threads => 1',
' }',
' ```',
'',
'## Solutions',
'',
'## Whiteboard',
''),
'brief': 'Testing docker log drivers',
'description': 'Investigate docker log drivers and the logs2kafka log plugin.',
'name': '',
'groups': ('docker',),
'tags': ('docker', 'driver', 'kafka', 'kubernetes', 'logging', 'logs2kafka', 'moby', 'plugin'),
'links': ('https://github.com/MickayG/moby-kafka-logdriver',
'https://github.com/garo/logs2kafka',
'https://groups.google.com/forum/#!topic/kubernetes-users/iLDsG85exRQ'),
'source': '',
'versions': (),
'languages': (),
'filename': 'kubernetes-docker-log-driver-kafka.mkdn',
'created': '2019-01-04T10:54:49.265512+00:00',
'updated': '2019-01-05T10:54:49.265512+00:00',
'uuid': '24cd5827-b6ef-4067-b5ac-3ceac07dde9f',
'digest': 'c54c8a896b94ea35edf6c798879957419d26268bd835328d74b19a6e9ce2324d'
})
BEATS_CREATED = _DEFAULTS[_BEATS]['created']
BEATS_UPDATED = _DEFAULTS[_BEATS]['updated']
NGINX_CREATED = _DEFAULTS[_NGINX]['created']
NGINX_UPDATED = _DEFAULTS[_NGINX]['updated']
KAFKA_CREATED = _DEFAULTS[_KAFKA]['created']
KAFKA_UPDATED = _DEFAULTS[_KAFKA]['updated']
KAFKA_MKDN_CREATED = _DEFAULTS[_KAFKA_MKDN]['created']
KAFKA_MKDN_UPDATED = _DEFAULTS[_KAFKA_MKDN]['updated']
if not DEFAULT_TIME == BEATS_CREATED == BEATS_UPDATED == NGINX_CREATED == NGINX_UPDATED:
raise Exception('default content timestamps must be same - see \'Test case layouts and data structures\'')
BEATS_DIGEST = _DEFAULTS[_BEATS]['digest']
NGINX_DIGEST = _DEFAULTS[_NGINX]['digest']
KAFKA_DIGEST = _DEFAULTS[_KAFKA]['digest']
KAFKA_MKDN_DIGEST = _DEFAULTS[_KAFKA_MKDN]['digest']
BEATS_UUID = _DEFAULTS[_BEATS]['uuid']
NGINX_UUID = _DEFAULTS[_NGINX]['uuid']
KAFKA_UUID = _DEFAULTS[_KAFKA]['uuid']
KAFKA_MKDN_UUID = _DEFAULTS[_KAFKA_MKDN]['uuid']
BEATS = _DEFAULTS[_BEATS]
NGINX = _DEFAULTS[_NGINX]
KAFKA = _DEFAULTS[_KAFKA]
KAFKA_MKDN = _DEFAULTS[_KAFKA_MKDN]
DEFAULT_SOLUTIONS = (BEATS, NGINX)
TEMPLATE = Helper.read_template('solution.txt').split('\n')
TEMPLATE_DIGEST_TEXT = 'be2ec3ade0e984463c1d3346910a05625897abd8d3feae4b2e54bfd6aecbde2d'
TEMPLATE_DIGEST_MKDN = '073ea152d867cf06b2ee993fb1aded4c8ccbc618972db5c18158b5b68a5da6e4'
TEMPLATE_TEXT = (
'################################################################################',
'## BRIEF : Add brief title for content',
'##',
'## GROUPS : groups',
'## TAGS : example,tags',
'## FILE : example-content.md',
'################################################################################',
'',
'',
'################################################################################',
'## Description',
'################################################################################',
'',
'################################################################################',
'## References',
'################################################################################',
'',
'################################################################################',
'## Commands',
'################################################################################',
'',
'################################################################################',
'## Configurations',
'################################################################################',
'',
'################################################################################',
'## Solutions',
'################################################################################',
'',
'################################################################################',
'## Whiteboard',
'################################################################################',
'',
'################################################################################',
'## Meta',
'################################################################################',
'',
'category : solution',
'created : 2017-10-14T19:56:31.000001+00:00',
'digest : 50c37862816a197c63b2ae72c511586c3463814509c0d5c7ebde534ce0209935',
'languages : example-language',
'name : example content handle',
'source : https://www.example.com/source.md',
'updated : 2017-10-14T19:56:31.000001+00:00',
'uuid : a1cd5827-b6ef-4067-b5ac-3ceac07dde9f',
'versions : example=3.9.0,python>=3',
''
)
TEMPLATE_MKDN = (
'# Add brief title for content @groups',
'',
'> Add a description that defines the content in one chapter.',
'',
'> ',
'',
'## Description',
'',
'## References',
'',
'## Commands',
'',
'## Configurations',
'',
'## Solutions',
'',
'## Whiteboard',
'',
'## Meta',
'',
'> category : solution ',
'created : 2017-10-14T19:56:31.000001+00:00 ',
'digest : 5facdc16dc81851c2f65b112a0921eb2f2db206c7756714efb45ba0026471f11 ',
'filename : example-content.md ',
'languages : example-language ',
'name : example content handle ',
'source : https://www.example.com/source.md ',
'tags : example,tags ',
'updated : 2017-10-14T19:56:31.000001+00:00 ',
'uuid : a1cd5827-b6ef-4067-b5ac-3ceac07dde9f ',
'versions : example=3.9.0,python>=3 ',
''
)
_OUTPUTS = [(
'',
' # Elastic,beats,debug,filebeat,howto',
' > https://www.elastic.co/guide/en/beats/filebeat/master/enable-filebeat-debugging.html',
'',
' : ################################################################################',
' : ## Description',
' : ################################################################################',
' : ',
' : # Debug Elastic Beats',
' : ',
' : ################################################################################',
' : ## References',
' : ################################################################################',
' : ',
' : # Enable logs from Filebeat',
' : > https://www.elastic.co/guide/en/beats/filebeat/master/enable-filebeat-debugging.html',
' : ',
' : ################################################################################',
' : ## Commands',
' : ################################################################################',
' : ',
' : # Run Filebeat with full log level',
' : $ ./filebeat -e -c config/filebeat.yml -d "*"',
' : ',
' : ################################################################################',
' : ## Solutions',
' : ################################################################################',
' : ',
' : ################################################################################',
' : ## Configurations',
' : ################################################################################',
' : ',
' : ################################################################################',
' : ## Whiteboard',
' : ################################################################################'
)]
BEATS_OUTPUT = _OUTPUTS[_BEATS]<|fim▁end|> | ' type => "argus.docker"',
' topics => ["dockerlogs"]', |
<|file_name|>importstates.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import simplejson
from django.core.management.base import BaseCommand
from django.contrib.gis.geos import MultiPolygon, Polygon
from ...models import State
class Command(BaseCommand):
args = 'filename'
help = 'Import states from a GeoJSON file'
def handle(self, *args, **options):
for filename in args:
data_json = open(filename, 'r').read()
data = simplejson.loads(data_json)
for feature in data['features']:
state = State(
name=feature['properties'].get('name'),
code=feature['properties'].get('code'),
)
if feature['geometry'].get('type') == 'MultiPolygon':
state.geom = MultiPolygon(
[Polygon(poly) for poly in feature['geometry'].get('coordinates')[0]]
)
else:<|fim▁hole|><|fim▁end|> | state.geom = MultiPolygon(Polygon(feature['geometry'].get('coordinates')[0]))
state.save() |
<|file_name|>settings.py<|end_file_name|><|fim▁begin|>URL = {
3304557: {
"production": "https://notacarioca.rio.gov.br/WSNacional/nfse.asmx?wsdl",
"sandbox": "https://homologacao.notacarioca.rio.gov.br/WSNacional/nfse.asmx?wsdl"
}<|fim▁hole|> 'status': "ConsultarNfseEnvio.xml",
'get_nfse': "ConsultarNfseEnvio.xml",
'cancel': "CancelarNfseEnvio.xml"
}<|fim▁end|> | }
TEMPLATES = {
'send_rps': "GerarNfseEnvio.xml", |
<|file_name|>run.py<|end_file_name|><|fim▁begin|><|fim▁hole|>if __name__ == '__main__':
app.run()<|fim▁end|> | from mosaic import app
|
<|file_name|>policy_gradient.py<|end_file_name|><|fim▁begin|>import numpy as np
import numpy.linalg as la
import collections
import IPython
import tensorflow as tf
from utils import *
import time
from collections import defaultdict
class PolicyGradient(Utils):
"""
Calculates policy gradient
for given input state/actions.
Users should primarily be calling main
PolicyGradient class methods.
"""
def __init__(self, net_dims, filepath=None, q_net_dims=None, output_function=None, seed=0, seed_state=None):
"""
Initializes PolicyGradient class.
Parameters:
net_dims: array-like
1D list corresponding to dimensions
of each layer in the net.
output_function: string
Non-linearity function applied to output of
neural network.
Options are: 'tanh', 'sigmoid', 'relu', 'softmax'.
"""
self.q_dict = defaultdict(lambda: defaultdict(float))
self.prev_weight_grad = self.prev_bias_grad = self.prev_weight_update_vals = \
self.prev_bias_update_vals = self.prev_weight_inverse_hess = self.prev_bias_inverse_hess = \
self.total_weight_grad = self.total_bias_grad = None
self.init_action_neural_net(net_dims, output_function, filepath)
if seed_state is not None:
np.random.set_state(seed_state)
tf.set_random_seed(seed)
def train_agent(self, dynamics_func, reward_func, update_method, initial_state, num_iters, batch_size, traj_len, step_size=0.1, momentum=0.5, normalize=True):
"""
Trains agent using input dynamics and rewards functions.
Parameters:
dynamics_func: function
User-provided function that takes in
a state and action, and returns the next state.
reward_func: function
User-provided function that takes in
a state and action, and returns the associated reward.
initial_state: array-like
Initial state that each trajectory starts at.
Must be 1-dimensional NumPy array.
num_iters: int
Number of iterations to run gradient updates.
batch_size: int
Number of trajectories to run in a single iteration.
traj_len: int
Number of state-action pairs in a trajectory.
Output:
mean_rewards: array-like
Mean ending rewards of all iterations.
"""
mean_rewards = []
ending_states = []
for i in range(num_iters):
traj_states = []
traj_actions = []
rewards = []
for j in range(batch_size):
states = []
actions = []
curr_rewards = []
curr_state = initial_state
# Rolls out single trajectory
for k in range(traj_len):
# Get action from learner
curr_action = self.get_action(curr_state)
# Update values
states.append(curr_state)
curr_rewards.append(reward_func(curr_state, curr_action))
actions.append(curr_action)
# Update state
curr_state = dynamics_func(curr_state, curr_action)
# Append trajectory/rewards
traj_states.append(states)
traj_actions.append(actions)
rewards.append(curr_rewards)
# Apply policy gradient iteration
self.gradient_update(np.array(traj_states), np.array(traj_actions), np.array(rewards), \
update_method, step_size, momentum, normalize)
mean_rewards.append(np.mean([np.sum(reward_list) for reward_list in rewards]))
ending_states.append([traj[-1] for traj in traj_states])
return np.array(mean_rewards), ending_states
def gradient_update(self, traj_states, traj_actions, rewards, update_method='sgd', step_size=1.0, momentum=0.5, normalize=True):
"""
Estimates and applies gradient update according to a policy.
States, actions, rewards must be lists of lists; first dimension indexes
the ith trajectory, second dimension indexes the jth state-action-reward of that
trajectory.
Parameters:
traj_states: array-like
List of list of states.
traj_actions: array-like
List of list of actions.
rewards: array-like
List of list of rewards.
step_size: float
Step size.
momentum: float
Momentum value.
normalize: boolean
Determines whether to normalize gradient update.
Recommended if running into NaN/infinite value errors.
"""
assert update_method in ['sgd', 'momentum', 'lbfgs', 'adagrad', 'rmsprop', 'adam']
# Calculate updates and create update pairs
curr_weight_grad = 0
curr_bias_grad = 0
curr_weight_update_vals = []
curr_bias_update_vals = []
curr_weight_inverse_hess = []
curr_bias_inverse_hess = []
iters = traj_states.shape[0]
q_vals = self.estimate_q(traj_states, traj_actions, rewards)
assert traj_states.shape[0] == traj_actions.shape[0] == rewards.shape[0]
assert q_vals.shape[0] == iters
# Update for each example
for i in range(iters):
# Estimate q-values and extract gradients
curr_traj_states = traj_states[i]
curr_traj_actions = traj_actions[i]
curr_q_val_list = q_vals[i]
curr_traj_states = curr_traj_states.reshape(curr_traj_states.shape[0], curr_traj_states.shape[1] * curr_traj_states.shape[2])
curr_traj_actions = curr_traj_actions.reshape(curr_traj_actions.shape[0], curr_traj_actions.shape[1] * curr_traj_actions.shape[2])
curr_q_val_list = curr_q_val_list.reshape(curr_q_val_list.shape[0], 1)
curr_weight_grad_vals = self.sess.run(self.weight_grads, \
feed_dict={self.input_state: curr_traj_states, self.observed_action: curr_traj_actions, self.q_val: curr_q_val_list})
curr_bias_grad_vals = self.sess.run(self.bias_grads, \
feed_dict={self.input_state: curr_traj_states, self.observed_action: curr_traj_actions, self.q_val: curr_q_val_list})
curr_weight_grad += np.array(curr_weight_grad_vals) / np.float(iters)
curr_bias_grad += np.array(curr_bias_grad_vals) / np.float(iters)
# Update weights
for j in range(len(self.weights)):
if update_method == 'sgd':
update_val = step_size * curr_weight_grad[j]
elif update_method == 'momentum':
if self.prev_weight_grad is None:
update_val = step_size * curr_weight_grad[j]
else:
update_val = momentum * self.prev_weight_grad[j] + step_size * curr_weight_grad[j]
elif update_method == 'lbfgs':
if self.prev_weight_inverse_hess is None:
curr_inverse_hess = np.eye(curr_weight_grad[j].shape[0])
update_val = curr_weight_grad[j]
else:
update_val, curr_inverse_hess = \
self.bfgs_update(self.prev_inverse_hess[j], self.prev_update_val[j], self.prev_weight_grad[j], update_val)
update_val = update_val * step_size
curr_weight_inverse_hess.append(curr_inverse_hess)
elif update_method == 'adagrad':
if self.total_weight_grad is None:
self.total_weight_grad = curr_weight_grad
else:
self.total_weight_grad[j] += np.square(curr_weight_grad[j])
update_val = step_size * curr_weight_grad[j] / (np.sqrt(np.abs(self.total_weight_grad[j])) + 1e-8)
elif update_method == 'rmsprop':
decay = 0.99
if self.total_weight_grad is None:
self.total_weight_grad = curr_weight_grad
else:
self.total_weight_grad[j] = decay * self.total_weight_grad[j] + (1 - decay) * np.square(curr_weight_grad[j])
update_val = step_size * curr_weight_grad[j] / (np.sqrt(np.abs(self.total_weight_grad[j])) + 1e-8)
elif update_method == 'adam':
beta1, beta2 = 0.9, 0.999
if self.total_weight_grad is None:
self.total_weight_grad = curr_weight_grad
self.total_sq_weight_grad = np.square(curr_weight_grad)
else:
self.total_weight_grad[j] = beta1 * self.total_weight_grad[j] + (1 - beta1) * curr_weight_grad[j]
self.total_sq_weight_grad[j] = beta2 * self.total_sq_weight_grad[j] + (1 - beta2) * np.sqrt(np.abs(self.total_weight_grad[j]))
update_val = np.divide(step_size * self.total_weight_grad[j], (np.sqrt(np.abs(self.total_sq_weight_grad[j])) + 1e-8))
if normalize:
norm = la.norm(update_val)
if norm != 0:
update_val = update_val / norm
curr_weight_update_vals.append(update_val)
update = tf.assign(self.weights[j], self.weights[j] + update_val)
self.sess.run(update)
# Update biases
for j in range(len(self.biases)):
if update_method == 'sgd':
update_val = step_size * curr_bias_grad[j]
elif update_method == 'momentum':
if self.prev_bias_grad is None:
update_val = step_size * curr_bias_grad[j]
else:
update_val = momentum * self.prev_bias_grad[j] + step_size * curr_bias_grad[j]
elif update_method == 'lbfgs':
if self.prev_bias_inverse_hess is None:
curr_inverse_hess = np.eye(curr_bias_grad[j].shape[0])
update_val = curr_bias_grad[j]
else:
update_val, curr_inverse_hess = \
self.bfgs_update(self.prev_inverse_hess[j], self.prev_update_val[j], self.prev_bias_grad[j], update_val)
update_val = update_val * step_size
curr_bias_inverse_hess.append(curr_inverse_hess)
elif update_method == 'adagrad':
if self.total_bias_grad is None:
self.total_bias_grad = curr_bias_grad
else:
self.total_bias_grad[j] += np.square(curr_bias_grad[j])
update_val = step_size * curr_bias_grad[j] / (np.sqrt(np.abs(self.total_bias_grad[j])) + 1e-8)
elif update_method == 'rmsprop':
decay = 0.99
if self.total_bias_grad is None:
self.total_bias_grad = curr_bias_grad
else:
self.total_bias_grad[j] = decay * self.total_bias_grad[j] + (1 - decay) * np.square(curr_bias_grad[j])
update_val = step_size * curr_bias_grad[j] / (np.sqrt(np.abs(self.total_bias_grad[j])) + 1e-8)
elif update_method == 'adam':
beta1, beta2 = 0.9, 0.999
if self.total_bias_grad is None:<|fim▁hole|> self.total_bias_grad[j] = beta1 * self.total_bias_grad[j] + (1 - beta1) * curr_bias_grad[j]
self.total_sq_bias_grad[j] = beta2 * self.total_sq_bias_grad[j] + (1 - beta2) * np.sqrt(np.abs(self.total_bias_grad[j]))
update_val = np.divide(step_size * self.total_bias_grad[j], (np.sqrt(np.abs(self.total_sq_bias_grad[j])) + 1e-8))
if normalize:
norm = la.norm(update_val)
if norm != 0:
update_val = update_val / norm
curr_bias_update_vals.append(update_val)
update = tf.assign(self.biases[j], self.biases[j] + update_val)
self.sess.run(update)
self.prev_weight_grad = curr_weight_grad
self.prev_bias_grad = curr_bias_grad
self.prev_weight_update_vals = curr_weight_update_vals
self.prev_bias_update_vals = curr_weight_update_vals
def get_action(self, state):
"""
Returns action based on input state.
Input:
state: array-like
Input state.
Output:
action: array-like
Predicted action.
"""
state = state.T
curr_output_mean = self.sess.run(self.output_mean, feed_dict={self.input_state: state})
action = self.meanstd_sample(curr_output_mean)
return action<|fim▁end|> | self.total_bias_grad = curr_bias_grad
self.total_sq_bias_grad = np.square(curr_bias_grad)
else: |
<|file_name|>all_tests.py<|end_file_name|><|fim▁begin|>import unittest
from gremlin_rest import GremlinClient
class TestClient(unittest.TestCase):
def setUp(self):
self.client = GremlinClient('http://172.17.0.248:8182')
def tearDown(self):
for v in self.client.V().run():
self.client.delete_vertex(vertex_id = v.vertex_id)
def test_add_vertex(self):
init_cnt = len(self.client.V().run())
v = self.client.addVertex(label = "a", a = 123, b = 'qweq').first()
print repr(v)
vs = self.client.V().run()
print repr(vs)
self.assertEqual(len(vs) - init_cnt, 1)
self.client.delete_vertex(vertex_id = v.vertex_id)
self.assertEqual(len(self.client.V().run()), init_cnt)
def test_query_vertices(self):
print 'before', repr(self.client.V().run())
v1 = self.client.addVertex(a = 123, b = 'qwe').first()
v2 = self.client.addVertex(a = 1234, b = 'qwe').first()
print 'all', repr(self.client.V().run())
print '12', repr(self.client.V().has('a', 12).run())
print '123', repr(self.client.V().has('a', 123).run())
print '1234', repr(self.client.V().has('a', 1234).run())
print 'qwe', repr(self.client.V().has('b', 'qwe').run())
self.assertEqual(len(self.client.V().has('a', 12).run()), 0)
self.assertEqual(len(self.client.V().has('a', 123).run()), 1)
self.assertEqual(len(self.client.V().has('a', 1234).run()), 1)
self.assertEqual(len(self.client.V().has('b', 'qwe').run()), 2)<|fim▁hole|> self.client.delete_vertex(vertex_id = v2.vertex_id)
if __name__ == '__main__':
unittest.main()<|fim▁end|> | self.client.delete_vertex(vertex_id = v1.vertex_id) |
<|file_name|>events.tsx<|end_file_name|><|fim▁begin|>import React from "react";
import Dropzone from "../../";
export class Events extends React.Component {
render() {
return (
<section>
<div className="dropzone">
<Dropzone
onDrop={(acceptedFiles, fileRejections, event) =>
console.log(acceptedFiles, fileRejections, event)}
onDragEnter={event => console.log(event)}
onDragOver={event => console.log(event)}
onDragLeave={event => console.log(event)}
>
{({getRootProps, getInputProps}) => (
<div {...getRootProps()}>
<input {...getInputProps()} />
<p>
Try dropping some files here, or click to select files to upload.
</p>
</div>
)}
</Dropzone>
</div>
</section>
);<|fim▁hole|>}<|fim▁end|> | } |
<|file_name|>networking.go<|end_file_name|><|fim▁begin|>// Copyright 2015-2016 Canonical Ltd.<|fim▁hole|>package rackspace
import (
"gopkg.in/goose.v2/nova"
"github.com/juju/juju/provider/openstack"
)
type rackspaceNetworkingDecorator struct{}
// DecorateNetworking is part of the openstack.NetworkingDecorator interface.
func (d rackspaceNetworkingDecorator) DecorateNetworking(n openstack.Networking) (openstack.Networking, error) {
return rackspaceNetworking{n}, nil
}
type rackspaceNetworking struct {
openstack.Networking
}
// DefaultNetworks is part of the openstack.Networking interface.
func (rackspaceNetworking) DefaultNetworks() ([]nova.ServerNetworks, error) {
// These are the default rackspace networks, see:
// http://docs.rackspace.com/servers/api/v2/cs-devguide/content/provision_server_with_networks.html
return []nova.ServerNetworks{
{NetworkId: "00000000-0000-0000-0000-000000000000"}, //Racksapce PublicNet
{NetworkId: "11111111-1111-1111-1111-111111111111"}, //Rackspace ServiceNet
}, nil
}<|fim▁end|> | // Licensed under the AGPLv3, see LICENCE file for details.
|
<|file_name|>common.py<|end_file_name|><|fim▁begin|># -*- mode: python; coding: utf-8; -*-
import os
APP_NAME = "SLog"
VERSION = "0.9.4"
WEBSITE = "http://vialinx.org"
<|fim▁hole|>SLog is a PyGTK-based GUI for the LightLang SL dictionary.
Copyright 2007 Nasyrov Renat <[email protected]>
This file is part of SLog.
SLog is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
SLog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with SLog; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
INSTALL_PREFIX = "@prefix@"
PIXMAP_DIR = os.path.join(INSTALL_PREFIX, "share", "pixmaps")
LOCALE_DIR = os.path.join(INSTALL_PREFIX, "share", "locale")
DATA_DIR = os.path.join(INSTALL_PREFIX, "share", "slog")
LOGO_ICON = "slog.png"
LOGO_ICON_SPY = "slog_spy.png"
#FTP_LL_URL = "ftp://ftp.lightlang.org.ru/dicts"
FTP_LL_URL = "ftp://etc.edu.ru/pub/soft/for_linux/lightlang"
FTP_DICTS_URL = FTP_LL_URL + "/dicts"
FTP_REPO_URL = FTP_DICTS_URL + "/repodata/primary.xml"
REPO_FILE = os.path.expanduser("~/.config/slog/primary.xml")
SL_TMP_DIR = "/tmp/sl"
def get_icon(filename):
return os.path.join(PIXMAP_DIR, filename)<|fim▁end|> | LICENSE = """ |
<|file_name|>geniblocks-rsrc-task.js<|end_file_name|><|fim▁begin|>var gulp = require('gulp');
var blocksConfig = require('../config').geniblocksRsrc;
var gvConfig = require('../config').geniverseRsrc;
// Copy files directly simple
exports.geniblocksRsrc = function geniblocksRsrc() {
return gulp.src(blocksConfig.src)
.pipe(gulp.dest(blocksConfig.dest));
};
exports.geniverseRsrc = function geniverseRsrc() {
gulp.src(gvConfig.index)
.pipe(gulp.dest(gvConfig.destIndex));<|fim▁hole|>
return gulp.src(gvConfig.src)
.pipe(gulp.dest(gvConfig.dest));
};<|fim▁end|> | |
<|file_name|>infinity.py<|end_file_name|><|fim▁begin|>my_inf = float('Inf')<|fim▁hole|>print my_neg_inf < -99999999
# True<|fim▁end|> | print 99999999 > my_inf
# False
my_neg_inf = float('-Inf') |
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>//#[feature(phase)];
#![crate_id = "freescale"]<|fim▁hole|>extern crate rustusb = "usb";
pub mod sim;
pub mod usb;<|fim▁end|> | #![crate_type = "rlib"]
#![license = "MIT"]
extern crate cortex; |
<|file_name|>test_adcpt_acfgm_dcl_pd8.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""
@package mi.dataset.parser.test.test_adcpt_acfgm
@fid marine-integrations/mi/dataset/parser/test/test_adcpt_acfgm.py
@author Ronald Ronquillo
@brief Test code for a Adcpt_Acfgm_Dcl data parser
"""
from nose.plugins.attrib import attr
import os
from mi.core.log import get_logger
from mi.dataset.parser.utilities import particle_to_yml
log = get_logger()
from mi.core.exceptions import RecoverableSampleException
from mi.dataset.test.test_parser import ParserUnitTestCase
from mi.dataset.dataset_parser import DataSetDriverConfigKeys<|fim▁hole|>from mi.dataset.driver.adcpt_acfgm.dcl.pd8.adcpt_acfgm_dcl_pd8_driver_common import \
AdcptAcfgmPd8Parser, MODULE_NAME, ADCPT_ACFGM_DCL_PD8_RECOVERED_PARTICLE_CLASS, \
ADCPT_ACFGM_DCL_PD8_TELEMETERED_PARTICLE_CLASS
from mi.dataset.driver.adcpt_acfgm.dcl.pd8.resource import RESOURCE_PATH
@attr('UNIT', group='mi')
class AdcptAcfgmPd8ParserUnitTestCase(ParserUnitTestCase):
"""
Adcpt_Acfgm_Dcl Parser unit test suite
"""
def create_parser(self, particle_class, file_handle):
"""
This function creates a AdcptAcfgmDcl parser for recovered data.
"""
parser = AdcptAcfgmPd8Parser(
{DataSetDriverConfigKeys.PARTICLE_MODULE: MODULE_NAME,
DataSetDriverConfigKeys.PARTICLE_CLASS: particle_class},
file_handle,
self.exception_callback)
return parser
def open_file(self, filename):
my_file = open(os.path.join(RESOURCE_PATH, filename), mode='rU')
return my_file
def setUp(self):
ParserUnitTestCase.setUp(self)
def create_yml(self, particles, filename):
particle_to_yml(particles, os.path.join(RESOURCE_PATH, filename))
def test_parse_input(self):
"""
Read a large file and verify that all expected particles can be read.
Verification is not done at this time, but will be done in the
tests below.
"""
in_file = self.open_file('20131201.adcp_mod.log')
parser = self.create_parser(ADCPT_ACFGM_DCL_PD8_RECOVERED_PARTICLE_CLASS, in_file)
# In a single read, get all particles in this file.
result = parser.get_records(23)
self.assertEqual(len(result), 23)
in_file.close()
self.assertListEqual(self.exception_callback_value, [])
def test_recov(self):
"""
Read a file and pull out multiple data particles at one time.
Verify that the results are those we expected.
"""
in_file = self.open_file('20131201.adcp_mod.log')
parser = self.create_parser(ADCPT_ACFGM_DCL_PD8_RECOVERED_PARTICLE_CLASS, in_file)
# In a single read, get all particles for this file.
result = parser.get_records(23)
self.assertEqual(len(result), 23)
self.assert_particles(result, '20131201.adcp_mod_recov.yml', RESOURCE_PATH)
self.assertListEqual(self.exception_callback_value, [])
in_file.close()
def test_telem(self):
"""
Read a file and pull out multiple data particles at one time.
Verify that the results are those we expected.
"""
in_file = self.open_file('20131201.adcp_mod.log')
parser = self.create_parser(ADCPT_ACFGM_DCL_PD8_TELEMETERED_PARTICLE_CLASS, in_file)
# In a single read, get all particles for this file.
result = parser.get_records(23)
self.assertEqual(len(result), 23)
self.assert_particles(result, '20131201.adcp_mod.yml', RESOURCE_PATH)
self.assertListEqual(self.exception_callback_value, [])
in_file.close()
def test_bad_data(self):
"""
Ensure that bad data is skipped when it exists.
"""
# Line 1: DCL Log missing opening square bracket
# Line 40: Timestamp day has a float
# Line 79: Heading is not a float
# Line 118: Temp is not a float
# Line 119: Header typo
# Line 158: Timestamp has non digit
# Line 197: Timestamp missing milliseconds
# Line 234: Bin missing
# Line 272: Dir missing
# Line 310: Mag missing
# Line 348: E/W missing
# Line 386: N/S missing
# Line 424: Vert missing
# Line 462: Err missing
# Line 500: Echo1 missing
# Line 538: Echo2 missing
# Line 576: Echo3 missing
# Line 614: Echo4 missing
# Line 652: Dir is not a float
# Line 690: Dir has a non digit
# Line 728: Mag is not a float
# Line 766: Mag has a non digit
# Line 804: E/W is a float
# Line 842: E/W has a non digit
# Line 880: N/S is a float
# Line 918: N/S is a non digit
# Line 956: Vert is a float
# Line 994: Vert is a non digit
# Line 1032: Err is a float
# Line 1070: Err has a non digit
# Line 1108: Echo1 is a float
# Line 1146: Echo1 has a non digit
# Line 1184: Echo2 is a float
# Line 1222: Echo2 has a non digit
# Line 1260: Echo3 is negative
# Line 1298: Timestamp missing secconds
# Line 1331: DCL Logging missing closing square bracket
# Line 1384: Ensemble number is a float
# Line 1409: Pitch is not a float
# Line 1448: Speed of sound is a float
# Line 1485: Roll is not a float
# Line 1523: Heading has a non digit
# Line 1561: Pitch has a non digit
# Line 1599: Roll has a non digit
fid = open(os.path.join(RESOURCE_PATH, '20131201.adcp_corrupt.log'), 'rb')
parser = self.create_parser(ADCPT_ACFGM_DCL_PD8_RECOVERED_PARTICLE_CLASS, fid)
parser.get_records(66)
for i in range(len(self.exception_callback_value)):
self.assert_(isinstance(self.exception_callback_value[i], RecoverableSampleException))
log.debug('Exception: %s', self.exception_callback_value[i])
self.assert_(isinstance(self.exception_callback_value[0], RecoverableSampleException))
fid.close()
def test_telem_3021(self):
"""
Read a file and pull out multiple data particles at one time.
Verify that the results are those we expected.
This test uses a real file from a deployment.
Used to verify fixes in responses to Redmine # 3021
"""
in_file = self.open_file('20141208.adcp.log')
parser = self.create_parser(ADCPT_ACFGM_DCL_PD8_TELEMETERED_PARTICLE_CLASS, in_file)
# In a single read, get all particles for this file.
result = parser.get_records(23)
self.assertEqual(len(result), 14)
self.assert_particles(result, '20141208.adcp.yml', RESOURCE_PATH)
self.assertListEqual(self.exception_callback_value, [])
in_file.close()
def test_telem_9692(self):
"""
Test to verify change made to dcl_file_common.py works with DCL
timestamps containing seconds >59
"""
in_file = self.open_file('20131201.adcpA.log')
parser = self.create_parser(ADCPT_ACFGM_DCL_PD8_TELEMETERED_PARTICLE_CLASS, in_file)
# In a single read, get all particles for this file.
result = parser.get_records(20)
self.assertEqual(len(result), 1)
self.assertListEqual(self.exception_callback_value, [])
in_file.close()<|fim▁end|> | |
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>use binaryninja::architecture::Architecture;
use binaryninja::binaryview::{BinaryViewBase, BinaryViewExt};
fn main() {
println!("Loading plugins..."); // This loads all the core architecture, platform, etc plugins
binaryninja::headless::init();
println!("Loading binary...");
let bv = binaryninja::open_view("/bin/cat").expect("Couldn't open `/bin/cat`");
println!("Filename: `{}`", bv.metadata().filename());
println!("File size: `{:#x}`", bv.len());
println!("Function count: {}", bv.functions().len());
for func in &bv.functions() {
println!(" `{}`:", func.symbol().full_name());
for basic_block in &func.basic_blocks() {
// TODO : This is intended to be refactored to be more nice to work with soon(TM)
for addr in basic_block.as_ref() {
print!(" {} ", addr);
match func.arch().instruction_text(
bv.read_buffer(addr, func.arch().max_instr_len())
.unwrap()<|fim▁hole|> Some((_, tokens)) => {
tokens
.iter()
.for_each(|token| print!("{}", token.text().to_str().unwrap()));
println!("")
}
_ => (),
}
}
}
}
// Important! You need to call shutdown or your script will hang forever
binaryninja::headless::shutdown();
}<|fim▁end|> | .get_data(),
addr,
) { |
<|file_name|>testscript.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 3.0.0.11832 (http://hl7.org/fhir/StructureDefinition/TestScript) on 2017-03-22.
# 2017, SMART Health IT.
from . import domainresource
class TestScript(domainresource.DomainResource):
""" Describes a set of tests.
A structured set of tests against a FHIR server implementation to determine
compliance against the FHIR specification.
"""
resource_type = "TestScript"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.contact = None
""" Contact details for the publisher.
List of `ContactDetail` items (represented as `dict` in JSON). """
self.copyright = None
""" Use and/or publishing restrictions.
Type `str`. """
self.date = None
""" Date this was last changed.
Type `FHIRDate` (represented as `str` in JSON). """
self.description = None
""" Natural language description of the test script.
Type `str`. """
self.destination = None
""" An abstract server representing a destination or receiver in a
message exchange.
List of `TestScriptDestination` items (represented as `dict` in JSON). """
self.experimental = None
""" For testing purposes, not real usage.
Type `bool`. """
self.fixture = None
""" Fixture in the test script - by reference (uri).
List of `TestScriptFixture` items (represented as `dict` in JSON). """
self.identifier = None
""" Additional identifier for the test script.
Type `Identifier` (represented as `dict` in JSON). """
self.jurisdiction = None
""" Intended jurisdiction for test script (if applicable).
List of `CodeableConcept` items (represented as `dict` in JSON). """
self.metadata = None
""" Required capability that is assumed to function correctly on the
FHIR server being tested.
Type `TestScriptMetadata` (represented as `dict` in JSON). """
self.name = None
""" Name for this test script (computer friendly).
Type `str`. """
self.origin = None
""" An abstract server representing a client or sender in a message
exchange.
List of `TestScriptOrigin` items (represented as `dict` in JSON). """
self.profile = None
""" Reference of the validation profile.
List of `FHIRReference` items referencing `Resource` (represented as `dict` in JSON). """
self.publisher = None
""" Name of the publisher (organization or individual).
Type `str`. """
self.purpose = None
""" Why this test script is defined.
Type `str`. """
self.rule = None
""" Assert rule used within the test script.
List of `TestScriptRule` items (represented as `dict` in JSON). """
self.ruleset = None
""" Assert ruleset used within the test script.
List of `TestScriptRuleset` items (represented as `dict` in JSON). """
self.setup = None
""" A series of required setup operations before tests are executed.
Type `TestScriptSetup` (represented as `dict` in JSON). """
self.status = None
""" draft | active | retired | unknown.
Type `str`. """
self.teardown = None
""" A series of required clean up steps.
Type `TestScriptTeardown` (represented as `dict` in JSON). """
self.test = None
""" A test in this script.
List of `TestScriptTest` items (represented as `dict` in JSON). """
self.title = None
""" Name for this test script (human friendly).
Type `str`. """
self.url = None
""" Logical URI to reference this test script (globally unique).
Type `str`. """
self.useContext = None
""" Context the content is intended to support.
List of `UsageContext` items (represented as `dict` in JSON). """
self.variable = None
""" Placeholder for evaluated elements.
List of `TestScriptVariable` items (represented as `dict` in JSON). """
self.version = None
""" Business version of the test script.
Type `str`. """
super(TestScript, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(TestScript, self).elementProperties()
js.extend([
("contact", "contact", contactdetail.ContactDetail, True, None, False),
("copyright", "copyright", str, False, None, False),
("date", "date", fhirdate.FHIRDate, False, None, False),
("description", "description", str, False, None, False),
("destination", "destination", TestScriptDestination, True, None, False),
("experimental", "experimental", bool, False, None, False),
("fixture", "fixture", TestScriptFixture, True, None, False),
("identifier", "identifier", identifier.Identifier, False, None, False),
("jurisdiction", "jurisdiction", codeableconcept.CodeableConcept, True, None, False),
("metadata", "metadata", TestScriptMetadata, False, None, False),
("name", "name", str, False, None, True),
("origin", "origin", TestScriptOrigin, True, None, False),
("profile", "profile", fhirreference.FHIRReference, True, None, False),
("publisher", "publisher", str, False, None, False),
("purpose", "purpose", str, False, None, False),
("rule", "rule", TestScriptRule, True, None, False),
("ruleset", "ruleset", TestScriptRuleset, True, None, False),
("setup", "setup", TestScriptSetup, False, None, False),
("status", "status", str, False, None, True),
("teardown", "teardown", TestScriptTeardown, False, None, False),
("test", "test", TestScriptTest, True, None, False),
("title", "title", str, False, None, False),
("url", "url", str, False, None, True),
("useContext", "useContext", usagecontext.UsageContext, True, None, False),
("variable", "variable", TestScriptVariable, True, None, False),
("version", "version", str, False, None, False),
])
return js
from . import backboneelement
class TestScriptDestination(backboneelement.BackboneElement):
""" An abstract server representing a destination or receiver in a message
exchange.
An abstract server used in operations within this test script in the
destination element.
"""
resource_type = "TestScriptDestination"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.index = None
""" The index of the abstract destination server starting at 1.
Type `int`. """
self.profile = None
""" FHIR-Server | FHIR-SDC-FormManager | FHIR-SDC-FormReceiver | FHIR-
SDC-FormProcessor.
Type `Coding` (represented as `dict` in JSON). """
super(TestScriptDestination, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(TestScriptDestination, self).elementProperties()
js.extend([
("index", "index", int, False, None, True),
("profile", "profile", coding.Coding, False, None, True),
])
return js
class TestScriptFixture(backboneelement.BackboneElement):
""" Fixture in the test script - by reference (uri).
Fixture in the test script - by reference (uri). All fixtures are required
for the test script to execute.
"""
resource_type = "TestScriptFixture"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.autocreate = None
""" Whether or not to implicitly create the fixture during setup.
Type `bool`. """
self.autodelete = None
""" Whether or not to implicitly delete the fixture during teardown.
Type `bool`. """
self.resource = None
""" Reference of the resource.
Type `FHIRReference` referencing `Resource` (represented as `dict` in JSON). """
super(TestScriptFixture, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(TestScriptFixture, self).elementProperties()
js.extend([
("autocreate", "autocreate", bool, False, None, False),
("autodelete", "autodelete", bool, False, None, False),
("resource", "resource", fhirreference.FHIRReference, False, None, False),
])
return js
class TestScriptMetadata(backboneelement.BackboneElement):
""" Required capability that is assumed to function correctly on the FHIR
server being tested.
The required capability must exist and are assumed to function correctly on
the FHIR server being tested.
"""
resource_type = "TestScriptMetadata"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.capability = None
""" Capabilities that are assumed to function correctly on the FHIR
server being tested.
List of `TestScriptMetadataCapability` items (represented as `dict` in JSON). """
self.link = None
""" Links to the FHIR specification.
List of `TestScriptMetadataLink` items (represented as `dict` in JSON). """
super(TestScriptMetadata, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(TestScriptMetadata, self).elementProperties()
js.extend([
("capability", "capability", TestScriptMetadataCapability, True, None, True),
("link", "link", TestScriptMetadataLink, True, None, False),
])
return js
class TestScriptMetadataCapability(backboneelement.BackboneElement):
""" Capabilities that are assumed to function correctly on the FHIR server
being tested.
Capabilities that must exist and are assumed to function correctly on the
FHIR server being tested.
"""
resource_type = "TestScriptMetadataCapability"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.capabilities = None
""" Required Capability Statement.
Type `FHIRReference` referencing `CapabilityStatement` (represented as `dict` in JSON). """
self.description = None
""" The expected capabilities of the server.
Type `str`. """
self.destination = None
""" Which server these requirements apply to.
Type `int`. """
self.link = None
""" Links to the FHIR specification.
List of `str` items. """
self.origin = None
""" Which origin server these requirements apply to.
List of `int` items. """
self.required = None
""" Are the capabilities required?.
Type `bool`. """
self.validated = None
""" Are the capabilities validated?.
Type `bool`. """
super(TestScriptMetadataCapability, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(TestScriptMetadataCapability, self).elementProperties()
js.extend([
("capabilities", "capabilities", fhirreference.FHIRReference, False, None, True),
("description", "description", str, False, None, False),
("destination", "destination", int, False, None, False),
("link", "link", str, True, None, False),
("origin", "origin", int, True, None, False),
("required", "required", bool, False, None, False),
("validated", "validated", bool, False, None, False),
])
return js
class TestScriptMetadataLink(backboneelement.BackboneElement):
""" Links to the FHIR specification.
A link to the FHIR specification that this test is covering.
"""
resource_type = "TestScriptMetadataLink"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.description = None
""" Short description.
Type `str`. """
self.url = None
""" URL to the specification.
Type `str`. """
super(TestScriptMetadataLink, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(TestScriptMetadataLink, self).elementProperties()
js.extend([
("description", "description", str, False, None, False),
("url", "url", str, False, None, True),
])
return js
class TestScriptOrigin(backboneelement.BackboneElement):
""" An abstract server representing a client or sender in a message exchange.
An abstract server used in operations within this test script in the origin
element.
"""
resource_type = "TestScriptOrigin"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.index = None
""" The index of the abstract origin server starting at 1.
Type `int`. """
self.profile = None
""" FHIR-Client | FHIR-SDC-FormFiller.
Type `Coding` (represented as `dict` in JSON). """
super(TestScriptOrigin, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(TestScriptOrigin, self).elementProperties()
js.extend([
("index", "index", int, False, None, True),
("profile", "profile", coding.Coding, False, None, True),
])
return js
class TestScriptRule(backboneelement.BackboneElement):
""" Assert rule used within the test script.
Assert rule to be used in one or more asserts within the test script.
"""
resource_type = "TestScriptRule"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.param = None
""" Rule parameter template.
List of `TestScriptRuleParam` items (represented as `dict` in JSON). """
self.resource = None
""" Assert rule resource reference.
Type `FHIRReference` referencing `Resource` (represented as `dict` in JSON). """
super(TestScriptRule, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(TestScriptRule, self).elementProperties()
js.extend([
("param", "param", TestScriptRuleParam, True, None, False),
("resource", "resource", fhirreference.FHIRReference, False, None, True),
])
return js
class TestScriptRuleParam(backboneelement.BackboneElement):
""" Rule parameter template.
Each rule template can take one or more parameters for rule evaluation.
"""
resource_type = "TestScriptRuleParam"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.name = None
""" Parameter name matching external assert rule parameter.
Type `str`. """
self.value = None
""" Parameter value defined either explicitly or dynamically.
Type `str`. """
super(TestScriptRuleParam, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(TestScriptRuleParam, self).elementProperties()
js.extend([
("name", "name", str, False, None, True),
("value", "value", str, False, None, False),
])
return js
class TestScriptRuleset(backboneelement.BackboneElement):
""" Assert ruleset used within the test script.
Contains one or more rules. Offers a way to group rules so assertions
could reference the group of rules and have them all applied.
"""
resource_type = "TestScriptRuleset"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.resource = None
""" Assert ruleset resource reference.
Type `FHIRReference` referencing `Resource` (represented as `dict` in JSON). """
self.rule = None
""" The referenced rule within the ruleset.
List of `TestScriptRulesetRule` items (represented as `dict` in JSON). """
super(TestScriptRuleset, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(TestScriptRuleset, self).elementProperties()
js.extend([
("resource", "resource", fhirreference.FHIRReference, False, None, True),
("rule", "rule", TestScriptRulesetRule, True, None, True),
])
return js
class TestScriptRulesetRule(backboneelement.BackboneElement):
""" The referenced rule within the ruleset.
The referenced rule within the external ruleset template.
"""
resource_type = "TestScriptRulesetRule"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.param = None
""" Ruleset rule parameter template.
List of `TestScriptRulesetRuleParam` items (represented as `dict` in JSON). """
self.ruleId = None
""" Id of referenced rule within the ruleset.
Type `str`. """
super(TestScriptRulesetRule, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(TestScriptRulesetRule, self).elementProperties()
js.extend([
("param", "param", TestScriptRulesetRuleParam, True, None, False),
("ruleId", "ruleId", str, False, None, True),
])
return js
class TestScriptRulesetRuleParam(backboneelement.BackboneElement):
""" Ruleset rule parameter template.
Each rule template can take one or more parameters for rule evaluation.
"""
resource_type = "TestScriptRulesetRuleParam"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.name = None
""" Parameter name matching external assert ruleset rule parameter.
Type `str`. """
self.value = None
""" Parameter value defined either explicitly or dynamically.
Type `str`. """
super(TestScriptRulesetRuleParam, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(TestScriptRulesetRuleParam, self).elementProperties()
js.extend([
("name", "name", str, False, None, True),
("value", "value", str, False, None, False),
])
return js
class TestScriptSetup(backboneelement.BackboneElement):
""" A series of required setup operations before tests are executed.
"""
resource_type = "TestScriptSetup"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.action = None
""" A setup operation or assert to perform.
List of `TestScriptSetupAction` items (represented as `dict` in JSON). """
super(TestScriptSetup, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(TestScriptSetup, self).elementProperties()
js.extend([
("action", "action", TestScriptSetupAction, True, None, True),
])
return js
class TestScriptSetupAction(backboneelement.BackboneElement):
""" A setup operation or assert to perform.
Action would contain either an operation or an assertion.
"""
resource_type = "TestScriptSetupAction"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.assert_fhir = None
""" The assertion to perform.
Type `TestScriptSetupActionAssert` (represented as `dict` in JSON). """
self.operation = None
""" The setup operation to perform.
Type `TestScriptSetupActionOperation` (represented as `dict` in JSON). """
super(TestScriptSetupAction, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(TestScriptSetupAction, self).elementProperties()
js.extend([
("assert_fhir", "assert", TestScriptSetupActionAssert, False, None, False),
("operation", "operation", TestScriptSetupActionOperation, False, None, False),
])
return js
class TestScriptSetupActionAssert(backboneelement.BackboneElement):
""" The assertion to perform.
Evaluates the results of previous operations to determine if the server
under test behaves appropriately.
"""
resource_type = "TestScriptSetupActionAssert"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.compareToSourceExpression = None
""" The fluentpath expression to evaluate against the source fixture.
Type `str`. """
self.compareToSourceId = None
""" Id of the source fixture to be evaluated.
Type `str`. """
self.compareToSourcePath = None
""" XPath or JSONPath expression to evaluate against the source fixture.
Type `str`. """
self.contentType = None
""" xml | json | ttl | none.
Type `str`. """
self.description = None
""" Tracking/reporting assertion description.
Type `str`. """
self.direction = None
""" response | request.
Type `str`. """
self.expression = None
""" The fluentpath expression to be evaluated.
Type `str`. """
self.headerField = None
""" HTTP header field name.
Type `str`. """
self.label = None
""" Tracking/logging assertion label.
Type `str`. """
self.minimumId = None
""" Fixture Id of minimum content resource.
Type `str`. """
self.navigationLinks = None
""" Perform validation on navigation links?.
Type `bool`. """
self.operator = None
""" equals | notEquals | in | notIn | greaterThan | lessThan | empty |
notEmpty | contains | notContains | eval.
Type `str`. """
self.path = None
""" XPath or JSONPath expression.
Type `str`. """
self.requestMethod = None
""" delete | get | options | patch | post | put.
Type `str`. """
self.requestURL = None
""" Request URL comparison value.
Type `str`. """
self.resource = None
""" Resource type.
Type `str`. """
self.response = None
""" okay | created | noContent | notModified | bad | forbidden |
notFound | methodNotAllowed | conflict | gone | preconditionFailed
| unprocessable.
Type `str`. """
self.responseCode = None
""" HTTP response code to test.
Type `str`. """
self.rule = None
""" The reference to a TestScript.rule.
Type `TestScriptSetupActionAssertRule` (represented as `dict` in JSON). """
self.ruleset = None
""" The reference to a TestScript.ruleset.
Type `TestScriptSetupActionAssertRuleset` (represented as `dict` in JSON). """
self.sourceId = None
""" Fixture Id of source expression or headerField.
Type `str`. """
self.validateProfileId = None
""" Profile Id of validation profile reference.
Type `str`. """
self.value = None
""" The value to compare to.
Type `str`. """
self.warningOnly = None
""" Will this assert produce a warning only on error?.
Type `bool`. """
super(TestScriptSetupActionAssert, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(TestScriptSetupActionAssert, self).elementProperties()
js.extend([
("compareToSourceExpression", "compareToSourceExpression", str, False, None, False),
("compareToSourceId", "compareToSourceId", str, False, None, False),
("compareToSourcePath", "compareToSourcePath", str, False, None, False),
("contentType", "contentType", str, False, None, False),
("description", "description", str, False, None, False),
("direction", "direction", str, False, None, False),
("expression", "expression", str, False, None, False),
("headerField", "headerField", str, False, None, False),
("label", "label", str, False, None, False),
("minimumId", "minimumId", str, False, None, False),
("navigationLinks", "navigationLinks", bool, False, None, False),
("operator", "operator", str, False, None, False),
("path", "path", str, False, None, False),
("requestMethod", "requestMethod", str, False, None, False),
("requestURL", "requestURL", str, False, None, False),
("resource", "resource", str, False, None, False),
("response", "response", str, False, None, False),
("responseCode", "responseCode", str, False, None, False),
("rule", "rule", TestScriptSetupActionAssertRule, False, None, False),
("ruleset", "ruleset", TestScriptSetupActionAssertRuleset, False, None, False),
("sourceId", "sourceId", str, False, None, False),
("validateProfileId", "validateProfileId", str, False, None, False),
("value", "value", str, False, None, False),
("warningOnly", "warningOnly", bool, False, None, False),
])
return js
class TestScriptSetupActionAssertRule(backboneelement.BackboneElement):
""" The reference to a TestScript.rule.
The TestScript.rule this assert will evaluate.
"""
resource_type = "TestScriptSetupActionAssertRule"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.param = None
""" Rule parameter template.
List of `TestScriptSetupActionAssertRuleParam` items (represented as `dict` in JSON). """
self.ruleId = None
""" Id of the TestScript.rule.
Type `str`. """
super(TestScriptSetupActionAssertRule, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(TestScriptSetupActionAssertRule, self).elementProperties()
js.extend([
("param", "param", TestScriptSetupActionAssertRuleParam, True, None, False),
("ruleId", "ruleId", str, False, None, True),
])
return js
class TestScriptSetupActionAssertRuleParam(backboneelement.BackboneElement):
""" Rule parameter template.
Each rule template can take one or more parameters for rule evaluation.
"""
<|fim▁hole|> """ Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.name = None
""" Parameter name matching external assert rule parameter.
Type `str`. """
self.value = None
""" Parameter value defined either explicitly or dynamically.
Type `str`. """
super(TestScriptSetupActionAssertRuleParam, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(TestScriptSetupActionAssertRuleParam, self).elementProperties()
js.extend([
("name", "name", str, False, None, True),
("value", "value", str, False, None, True),
])
return js
class TestScriptSetupActionAssertRuleset(backboneelement.BackboneElement):
""" The reference to a TestScript.ruleset.
The TestScript.ruleset this assert will evaluate.
"""
resource_type = "TestScriptSetupActionAssertRuleset"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.rule = None
""" The referenced rule within the ruleset.
List of `TestScriptSetupActionAssertRulesetRule` items (represented as `dict` in JSON). """
self.rulesetId = None
""" Id of the TestScript.ruleset.
Type `str`. """
super(TestScriptSetupActionAssertRuleset, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(TestScriptSetupActionAssertRuleset, self).elementProperties()
js.extend([
("rule", "rule", TestScriptSetupActionAssertRulesetRule, True, None, False),
("rulesetId", "rulesetId", str, False, None, True),
])
return js
class TestScriptSetupActionAssertRulesetRule(backboneelement.BackboneElement):
""" The referenced rule within the ruleset.
The referenced rule within the external ruleset template.
"""
resource_type = "TestScriptSetupActionAssertRulesetRule"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.param = None
""" Rule parameter template.
List of `TestScriptSetupActionAssertRulesetRuleParam` items (represented as `dict` in JSON). """
self.ruleId = None
""" Id of referenced rule within the ruleset.
Type `str`. """
super(TestScriptSetupActionAssertRulesetRule, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(TestScriptSetupActionAssertRulesetRule, self).elementProperties()
js.extend([
("param", "param", TestScriptSetupActionAssertRulesetRuleParam, True, None, False),
("ruleId", "ruleId", str, False, None, True),
])
return js
class TestScriptSetupActionAssertRulesetRuleParam(backboneelement.BackboneElement):
""" Rule parameter template.
Each rule template can take one or more parameters for rule evaluation.
"""
resource_type = "TestScriptSetupActionAssertRulesetRuleParam"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.name = None
""" Parameter name matching external assert ruleset rule parameter.
Type `str`. """
self.value = None
""" Parameter value defined either explicitly or dynamically.
Type `str`. """
super(TestScriptSetupActionAssertRulesetRuleParam, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(TestScriptSetupActionAssertRulesetRuleParam, self).elementProperties()
js.extend([
("name", "name", str, False, None, True),
("value", "value", str, False, None, True),
])
return js
class TestScriptSetupActionOperation(backboneelement.BackboneElement):
""" The setup operation to perform.
The operation to perform.
"""
resource_type = "TestScriptSetupActionOperation"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.accept = None
""" xml | json | ttl | none.
Type `str`. """
self.contentType = None
""" xml | json | ttl | none.
Type `str`. """
self.description = None
""" Tracking/reporting operation description.
Type `str`. """
self.destination = None
""" Server responding to the request.
Type `int`. """
self.encodeRequestUrl = None
""" Whether or not to send the request url in encoded format.
Type `bool`. """
self.label = None
""" Tracking/logging operation label.
Type `str`. """
self.origin = None
""" Server initiating the request.
Type `int`. """
self.params = None
""" Explicitly defined path parameters.
Type `str`. """
self.requestHeader = None
""" Each operation can have one or more header elements.
List of `TestScriptSetupActionOperationRequestHeader` items (represented as `dict` in JSON). """
self.requestId = None
""" Fixture Id of mapped request.
Type `str`. """
self.resource = None
""" Resource type.
Type `str`. """
self.responseId = None
""" Fixture Id of mapped response.
Type `str`. """
self.sourceId = None
""" Fixture Id of body for PUT and POST requests.
Type `str`. """
self.targetId = None
""" Id of fixture used for extracting the [id], [type], and [vid] for
GET requests.
Type `str`. """
self.type = None
""" The operation code type that will be executed.
Type `Coding` (represented as `dict` in JSON). """
self.url = None
""" Request URL.
Type `str`. """
super(TestScriptSetupActionOperation, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(TestScriptSetupActionOperation, self).elementProperties()
js.extend([
("accept", "accept", str, False, None, False),
("contentType", "contentType", str, False, None, False),
("description", "description", str, False, None, False),
("destination", "destination", int, False, None, False),
("encodeRequestUrl", "encodeRequestUrl", bool, False, None, False),
("label", "label", str, False, None, False),
("origin", "origin", int, False, None, False),
("params", "params", str, False, None, False),
("requestHeader", "requestHeader", TestScriptSetupActionOperationRequestHeader, True, None, False),
("requestId", "requestId", str, False, None, False),
("resource", "resource", str, False, None, False),
("responseId", "responseId", str, False, None, False),
("sourceId", "sourceId", str, False, None, False),
("targetId", "targetId", str, False, None, False),
("type", "type", coding.Coding, False, None, False),
("url", "url", str, False, None, False),
])
return js
class TestScriptSetupActionOperationRequestHeader(backboneelement.BackboneElement):
""" Each operation can have one or more header elements.
Header elements would be used to set HTTP headers.
"""
resource_type = "TestScriptSetupActionOperationRequestHeader"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.field = None
""" HTTP header field name.
Type `str`. """
self.value = None
""" HTTP headerfield value.
Type `str`. """
super(TestScriptSetupActionOperationRequestHeader, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(TestScriptSetupActionOperationRequestHeader, self).elementProperties()
js.extend([
("field", "field", str, False, None, True),
("value", "value", str, False, None, True),
])
return js
class TestScriptTeardown(backboneelement.BackboneElement):
""" A series of required clean up steps.
A series of operations required to clean up after the all the tests are
executed (successfully or otherwise).
"""
resource_type = "TestScriptTeardown"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.action = None
""" One or more teardown operations to perform.
List of `TestScriptTeardownAction` items (represented as `dict` in JSON). """
super(TestScriptTeardown, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(TestScriptTeardown, self).elementProperties()
js.extend([
("action", "action", TestScriptTeardownAction, True, None, True),
])
return js
class TestScriptTeardownAction(backboneelement.BackboneElement):
""" One or more teardown operations to perform.
The teardown action will only contain an operation.
"""
resource_type = "TestScriptTeardownAction"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.operation = None
""" The teardown operation to perform.
Type `TestScriptSetupActionOperation` (represented as `dict` in JSON). """
super(TestScriptTeardownAction, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(TestScriptTeardownAction, self).elementProperties()
js.extend([
("operation", "operation", TestScriptSetupActionOperation, False, None, True),
])
return js
class TestScriptTest(backboneelement.BackboneElement):
""" A test in this script.
"""
resource_type = "TestScriptTest"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.action = None
""" A test operation or assert to perform.
List of `TestScriptTestAction` items (represented as `dict` in JSON). """
self.description = None
""" Tracking/reporting short description of the test.
Type `str`. """
self.name = None
""" Tracking/logging name of this test.
Type `str`. """
super(TestScriptTest, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(TestScriptTest, self).elementProperties()
js.extend([
("action", "action", TestScriptTestAction, True, None, True),
("description", "description", str, False, None, False),
("name", "name", str, False, None, False),
])
return js
class TestScriptTestAction(backboneelement.BackboneElement):
""" A test operation or assert to perform.
Action would contain either an operation or an assertion.
"""
resource_type = "TestScriptTestAction"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.assert_fhir = None
""" The setup assertion to perform.
Type `TestScriptSetupActionAssert` (represented as `dict` in JSON). """
self.operation = None
""" The setup operation to perform.
Type `TestScriptSetupActionOperation` (represented as `dict` in JSON). """
super(TestScriptTestAction, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(TestScriptTestAction, self).elementProperties()
js.extend([
("assert_fhir", "assert", TestScriptSetupActionAssert, False, None, False),
("operation", "operation", TestScriptSetupActionOperation, False, None, False),
])
return js
class TestScriptVariable(backboneelement.BackboneElement):
""" Placeholder for evaluated elements.
Variable is set based either on element value in response body or on header
field value in the response headers.
"""
resource_type = "TestScriptVariable"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.defaultValue = None
""" Default, hard-coded, or user-defined value for this variable.
Type `str`. """
self.description = None
""" Natural language description of the variable.
Type `str`. """
self.expression = None
""" The fluentpath expression against the fixture body.
Type `str`. """
self.headerField = None
""" HTTP header field name for source.
Type `str`. """
self.hint = None
""" Hint help text for default value to enter.
Type `str`. """
self.name = None
""" Descriptive name for this variable.
Type `str`. """
self.path = None
""" XPath or JSONPath against the fixture body.
Type `str`. """
self.sourceId = None
""" Fixture Id of source expression or headerField within this variable.
Type `str`. """
super(TestScriptVariable, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(TestScriptVariable, self).elementProperties()
js.extend([
("defaultValue", "defaultValue", str, False, None, False),
("description", "description", str, False, None, False),
("expression", "expression", str, False, None, False),
("headerField", "headerField", str, False, None, False),
("hint", "hint", str, False, None, False),
("name", "name", str, False, None, True),
("path", "path", str, False, None, False),
("sourceId", "sourceId", str, False, None, False),
])
return js
import sys
try:
from . import codeableconcept
except ImportError:
codeableconcept = sys.modules[__package__ + '.codeableconcept']
try:
from . import coding
except ImportError:
coding = sys.modules[__package__ + '.coding']
try:
from . import contactdetail
except ImportError:
contactdetail = sys.modules[__package__ + '.contactdetail']
try:
from . import fhirdate
except ImportError:
fhirdate = sys.modules[__package__ + '.fhirdate']
try:
from . import fhirreference
except ImportError:
fhirreference = sys.modules[__package__ + '.fhirreference']
try:
from . import identifier
except ImportError:
identifier = sys.modules[__package__ + '.identifier']
try:
from . import usagecontext
except ImportError:
usagecontext = sys.modules[__package__ + '.usagecontext']<|fim▁end|> | resource_type = "TestScriptSetupActionAssertRuleParam"
def __init__(self, jsondict=None, strict=True): |
<|file_name|>errors.d.ts<|end_file_name|><|fim▁begin|>export declare const CLAMP_MIN_MAX: string;
export declare const ALERT_WARN_CANCEL_PROPS: string;<|fim▁hole|>export declare const CONTEXTMENU_WARN_DECORATOR_NO_METHOD: string;
export declare const HOTKEYS_HOTKEY_CHILDREN: string;
export declare const MENU_WARN_CHILDREN_SUBMENU_MUTEX: string;
export declare const NUMERIC_INPUT_MIN_MAX: string;
export declare const NUMERIC_INPUT_MINOR_STEP_SIZE_BOUND: string;
export declare const NUMERIC_INPUT_MAJOR_STEP_SIZE_BOUND: string;
export declare const NUMERIC_INPUT_MINOR_STEP_SIZE_NON_POSITIVE: string;
export declare const NUMERIC_INPUT_MAJOR_STEP_SIZE_NON_POSITIVE: string;
export declare const NUMERIC_INPUT_STEP_SIZE_NON_POSITIVE: string;
export declare const NUMERIC_INPUT_STEP_SIZE_NULL: string;
export declare const POPOVER_REQUIRES_TARGET: string;
export declare const POPOVER_MODAL_INTERACTION: string;
export declare const POPOVER_WARN_TOO_MANY_CHILDREN: string;
export declare const POPOVER_WARN_DOUBLE_CONTENT: string;
export declare const POPOVER_WARN_DOUBLE_TARGET: string;
export declare const POPOVER_WARN_EMPTY_CONTENT: string;
export declare const POPOVER_WARN_MODAL_INLINE: string;
export declare const POPOVER_WARN_DEPRECATED_CONSTRAINTS: string;
export declare const POPOVER_WARN_INLINE_NO_TETHER: string;
export declare const POPOVER_WARN_UNCONTROLLED_ONINTERACTION: string;
export declare const PORTAL_CONTEXT_CLASS_NAME_STRING: string;
export declare const RADIOGROUP_WARN_CHILDREN_OPTIONS_MUTEX: string;
export declare const SLIDER_ZERO_STEP: string;
export declare const SLIDER_ZERO_LABEL_STEP: string;
export declare const RANGESLIDER_NULL_VALUE: string;
export declare const TABS_FIRST_CHILD: string;
export declare const TABS_MISMATCH: string;
export declare const TABS_WARN_DEPRECATED: string;
export declare const TOASTER_WARN_INLINE: string;
export declare const TOASTER_WARN_LEFT_RIGHT: string;
export declare const DIALOG_WARN_NO_HEADER_ICON: string;
export declare const DIALOG_WARN_NO_HEADER_CLOSE_BUTTON: string;<|fim▁end|> | export declare const COLLAPSIBLE_LIST_INVALID_CHILD: string; |
<|file_name|>benchmark_bundle.js<|end_file_name|><|fim▁begin|>// modules are defined as an array
// [ module function, map of requireuires ]
//
// map of requireuires is short require name -> numeric require
//
// anything defined in a previous bundle is accessed via the
// orig method which is the requireuire for previous bundles
(function outer (modules, cache, entry) {
// Save the require from previous bundle to this closure if any
var previousRequire = typeof require == "function" && require;
function findProxyquireifyName() {
var deps = Object.keys(modules)
.map(function (k) { return modules[k][1]; });
for (var i = 0; i < deps.length; i++) {
var pq = deps[i]['proxyquireify'];
if (pq) return pq;
}
}
var proxyquireifyName = findProxyquireifyName();
function newRequire(name, jumped){
// Find the proxyquireify module, if present
var pqify = (proxyquireifyName != null) && cache[proxyquireifyName];
// Proxyquireify provides a separate cache that is used when inside
// a proxyquire call, and is set to null outside a proxyquire call.
// This allows the regular caching semantics to work correctly both
// inside and outside proxyquire calls while keeping the cached
// modules isolated.
// When switching from one proxyquire call to another, it clears
// the cache to prevent contamination between different sets
// of stubs.
var currentCache = (pqify && pqify.exports._cache) || cache;
if(!currentCache[name]) {
if(!modules[name]) {
// if we cannot find the the module within our internal map or
// cache jump to the current global require ie. the last bundle
// that was added to the page.
var currentRequire = typeof require == "function" && require;
if (!jumped && currentRequire) return currentRequire(name, true);
// If there are other bundles on this page the require from the
// previous one is saved to 'previousRequire'. Repeat this as
// many times as there are bundles until the module is found or
// we exhaust the require chain.
if (previousRequire) return previousRequire(name, true);
var err = new Error('Cannot find module \'' + name + '\'');
err.code = 'MODULE_NOT_FOUND';
throw err;
}
var m = currentCache[name] = {exports:{}};
// The normal browserify require function
var req = function(x){
var id = modules[name][1][x];
return newRequire(id ? id : x);
};
// The require function substituted for proxyquireify
var moduleRequire = function(x){
var pqify = (proxyquireifyName != null) && cache[proxyquireifyName];
// Only try to use the proxyquireify version if it has been `require`d
if (pqify && pqify.exports._proxy) {
return pqify.exports._proxy(req, x);
} else {
return req(x);
}
};
modules[name][0].call(m.exports,moduleRequire,m,m.exports,outer,modules,currentCache,entry);
}
return currentCache[name].exports;
}
for(var i=0;i<entry.length;i++) newRequire(entry[i]);
// Override the current require with this new one
return newRequire;
})
({1:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Float32Array === 'function' ) ? Float32Array : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],2:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of single-precision floating-point numbers in the platform byte order.
*
* @module @stdlib/array/float32
*
* @example
* var ctor = require( '@stdlib/array/float32' );
*
* var arr = new ctor( 10 );
* // returns <Float32Array>
*/
// MODULES //
var hasFloat32ArraySupport = require( '@stdlib/assert/has-float32array-support' );
var builtin = require( './float32array.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasFloat32ArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./float32array.js":1,"./polyfill.js":3,"@stdlib/assert/has-float32array-support":29}],3:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of single-precision floating-point numbers in the platform byte order.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],4:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Float64Array === 'function' ) ? Float64Array : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],5:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of double-precision floating-point numbers in the platform byte order.
*
* @module @stdlib/array/float64
*
* @example
* var ctor = require( '@stdlib/array/float64' );
*
* var arr = new ctor( 10 );
* // returns <Float64Array>
*/
// MODULES //
var hasFloat64ArraySupport = require( '@stdlib/assert/has-float64array-support' );
var builtin = require( './float64array.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasFloat64ArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./float64array.js":4,"./polyfill.js":6,"@stdlib/assert/has-float64array-support":32}],6:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of double-precision floating-point numbers in the platform byte order.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],7:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of twos-complement 16-bit signed integers in the platform byte order.
*
* @module @stdlib/array/int16
*
* @example
* var ctor = require( '@stdlib/array/int16' );
*
* var arr = new ctor( 10 );
* // returns <Int16Array>
*/
// MODULES //
var hasInt16ArraySupport = require( '@stdlib/assert/has-int16array-support' );
var builtin = require( './int16array.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasInt16ArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./int16array.js":8,"./polyfill.js":9,"@stdlib/assert/has-int16array-support":34}],8:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Int16Array === 'function' ) ? Int16Array : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],9:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of twos-complement 16-bit signed integers in the platform byte order.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],10:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of twos-complement 32-bit signed integers in the platform byte order.
*
* @module @stdlib/array/int32
*
* @example
* var ctor = require( '@stdlib/array/int32' );
*
* var arr = new ctor( 10 );
* // returns <Int32Array>
*/
// MODULES //
var hasInt32ArraySupport = require( '@stdlib/assert/has-int32array-support' );
var builtin = require( './int32array.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasInt32ArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./int32array.js":11,"./polyfill.js":12,"@stdlib/assert/has-int32array-support":37}],11:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Int32Array === 'function' ) ? Int32Array : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],12:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of twos-complement 32-bit signed integers in the platform byte order.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],13:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of twos-complement 8-bit signed integers in the platform byte order.
*
* @module @stdlib/array/int8
*
* @example
* var ctor = require( '@stdlib/array/int8' );
*
* var arr = new ctor( 10 );
* // returns <Int8Array>
*/
// MODULES //
var hasInt8ArraySupport = require( '@stdlib/assert/has-int8array-support' );
var builtin = require( './int8array.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasInt8ArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./int8array.js":14,"./polyfill.js":15,"@stdlib/assert/has-int8array-support":40}],14:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Int8Array === 'function' ) ? Int8Array : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],15:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of twos-complement 8-bit signed integers in the platform byte order.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],16:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of 16-bit unsigned integers in the platform byte order.
*
* @module @stdlib/array/uint16
*
* @example
* var ctor = require( '@stdlib/array/uint16' );
*
* var arr = new ctor( 10 );
* // returns <Uint16Array>
*/
// MODULES //
var hasUint16ArraySupport = require( '@stdlib/assert/has-uint16array-support' );
var builtin = require( './uint16array.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasUint16ArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./polyfill.js":17,"./uint16array.js":18,"@stdlib/assert/has-uint16array-support":52}],17:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of 16-bit unsigned integers in the platform byte order.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],18:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Uint16Array === 'function' ) ? Uint16Array : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],19:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of 32-bit unsigned integers in the platform byte order.
*
* @module @stdlib/array/uint32
*
* @example
* var ctor = require( '@stdlib/array/uint32' );
*
* var arr = new ctor( 10 );
* // returns <Uint32Array>
*/
// MODULES //
var hasUint32ArraySupport = require( '@stdlib/assert/has-uint32array-support' );
var builtin = require( './uint32array.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasUint32ArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./polyfill.js":20,"./uint32array.js":21,"@stdlib/assert/has-uint32array-support":55}],20:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of 32-bit unsigned integers in the platform byte order.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],21:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Uint32Array === 'function' ) ? Uint32Array : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],22:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of 8-bit unsigned integers in the platform byte order.
*
* @module @stdlib/array/uint8
*
* @example
* var ctor = require( '@stdlib/array/uint8' );
*
* var arr = new ctor( 10 );
* // returns <Uint8Array>
*/
// MODULES //
var hasUint8ArraySupport = require( '@stdlib/assert/has-uint8array-support' );
var builtin = require( './uint8array.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasUint8ArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./polyfill.js":23,"./uint8array.js":24,"@stdlib/assert/has-uint8array-support":58}],23:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of 8-bit unsigned integers in the platform byte order.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],24:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Uint8Array === 'function' ) ? Uint8Array : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],25:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of 8-bit unsigned integers in the platform byte order clamped to 0-255.
*
* @module @stdlib/array/uint8c
*
* @example
* var ctor = require( '@stdlib/array/uint8c' );
*
* var arr = new ctor( 10 );
* // returns <Uint8ClampedArray>
*/
// MODULES //
var hasUint8ClampedArraySupport = require( '@stdlib/assert/has-uint8clampedarray-support' ); // eslint-disable-line id-length
var builtin = require( './uint8clampedarray.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasUint8ClampedArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./polyfill.js":26,"./uint8clampedarray.js":27,"@stdlib/assert/has-uint8clampedarray-support":61}],26:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of 8-bit unsigned integers in the platform byte order clamped to 0-255.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],27:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Uint8ClampedArray === 'function' ) ? Uint8ClampedArray : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],28:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Float32Array === 'function' ) ? Float32Array : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],29:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test for native `Float32Array` support.
*
* @module @stdlib/assert/has-float32array-support
*
* @example
* var hasFloat32ArraySupport = require( '@stdlib/assert/has-float32array-support' );
*
* var bool = hasFloat32ArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasFloat32ArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasFloat32ArraySupport;
},{"./main.js":30}],30:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isFloat32Array = require( '@stdlib/assert/is-float32array' );
var PINF = require( '@stdlib/constants/float64/pinf' );
var GlobalFloat32Array = require( './float32array.js' );
// MAIN //
/**
* Tests for native `Float32Array` support.
*
* @returns {boolean} boolean indicating if an environment has `Float32Array` support
*
* @example
* var bool = hasFloat32ArraySupport();
* // returns <boolean>
*/
function hasFloat32ArraySupport() {
var bool;
var arr;
if ( typeof GlobalFloat32Array !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = new GlobalFloat32Array( [ 1.0, 3.14, -3.14, 5.0e40 ] );
bool = (
isFloat32Array( arr ) &&
arr[ 0 ] === 1.0 &&
arr[ 1 ] === 3.140000104904175 &&
arr[ 2 ] === -3.140000104904175 &&
arr[ 3 ] === PINF
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasFloat32ArraySupport;
},{"./float32array.js":28,"@stdlib/assert/is-float32array":89,"@stdlib/constants/float64/pinf":225}],31:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Float64Array === 'function' ) ? Float64Array : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],32:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test for native `Float64Array` support.
*
* @module @stdlib/assert/has-float64array-support
*
* @example
* var hasFloat64ArraySupport = require( '@stdlib/assert/has-float64array-support' );
*
* var bool = hasFloat64ArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasFloat64ArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasFloat64ArraySupport;
},{"./main.js":33}],33:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isFloat64Array = require( '@stdlib/assert/is-float64array' );
var GlobalFloat64Array = require( './float64array.js' );
// MAIN //
/**
* Tests for native `Float64Array` support.
*
* @returns {boolean} boolean indicating if an environment has `Float64Array` support
*
* @example
* var bool = hasFloat64ArraySupport();
* // returns <boolean>
*/
function hasFloat64ArraySupport() {
var bool;
var arr;
if ( typeof GlobalFloat64Array !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = new GlobalFloat64Array( [ 1.0, 3.14, -3.14, NaN ] );
bool = (
isFloat64Array( arr ) &&
arr[ 0 ] === 1.0 &&
arr[ 1 ] === 3.14 &&
arr[ 2 ] === -3.14 &&
arr[ 3 ] !== arr[ 3 ]
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasFloat64ArraySupport;
},{"./float64array.js":31,"@stdlib/assert/is-float64array":91}],34:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test for native `Int16Array` support.
*
* @module @stdlib/assert/has-int16array-support
*
* @example
* var hasInt16ArraySupport = require( '@stdlib/assert/has-int16array-support' );
*
* var bool = hasInt16ArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasInt16ArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasInt16ArraySupport;
},{"./main.js":36}],35:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Int16Array === 'function' ) ? Int16Array : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],36:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isInt16Array = require( '@stdlib/assert/is-int16array' );
var INT16_MAX = require( '@stdlib/constants/int16/max' );
var INT16_MIN = require( '@stdlib/constants/int16/min' );
var GlobalInt16Array = require( './int16array.js' );
// MAIN //
/**
* Tests for native `Int16Array` support.
*
* @returns {boolean} boolean indicating if an environment has `Int16Array` support
*
* @example
* var bool = hasInt16ArraySupport();
* // returns <boolean>
*/
function hasInt16ArraySupport() {
var bool;
var arr;
if ( typeof GlobalInt16Array !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = new GlobalInt16Array( [ 1, 3.14, -3.14, INT16_MAX+1 ] );
bool = (
isInt16Array( arr ) &&
arr[ 0 ] === 1 &&
arr[ 1 ] === 3 && // truncation
arr[ 2 ] === -3 && // truncation
arr[ 3 ] === INT16_MIN // wrap around
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasInt16ArraySupport;
},{"./int16array.js":35,"@stdlib/assert/is-int16array":95,"@stdlib/constants/int16/max":226,"@stdlib/constants/int16/min":227}],37:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test for native `Int32Array` support.
*
* @module @stdlib/assert/has-int32array-support
*
* @example
* var hasInt32ArraySupport = require( '@stdlib/assert/has-int32array-support' );
*
* var bool = hasInt32ArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasInt32ArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasInt32ArraySupport;
},{"./main.js":39}],38:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Int32Array === 'function' ) ? Int32Array : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],39:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isInt32Array = require( '@stdlib/assert/is-int32array' );
var INT32_MAX = require( '@stdlib/constants/int32/max' );
var INT32_MIN = require( '@stdlib/constants/int32/min' );
var GlobalInt32Array = require( './int32array.js' );
// MAIN //
/**
* Tests for native `Int32Array` support.
*
* @returns {boolean} boolean indicating if an environment has `Int32Array` support
*
* @example
* var bool = hasInt32ArraySupport();
* // returns <boolean>
*/
function hasInt32ArraySupport() {
var bool;
var arr;
if ( typeof GlobalInt32Array !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = new GlobalInt32Array( [ 1, 3.14, -3.14, INT32_MAX+1 ] );
bool = (
isInt32Array( arr ) &&
arr[ 0 ] === 1 &&
arr[ 1 ] === 3 && // truncation
arr[ 2 ] === -3 && // truncation
arr[ 3 ] === INT32_MIN // wrap around
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasInt32ArraySupport;
},{"./int32array.js":38,"@stdlib/assert/is-int32array":97,"@stdlib/constants/int32/max":228,"@stdlib/constants/int32/min":229}],40:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test for native `Int8Array` support.
*
* @module @stdlib/assert/has-int8array-support
*
* @example
* var hasInt8ArraySupport = require( '@stdlib/assert/has-int8array-support' );
*
* var bool = hasInt8ArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasInt8ArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasInt8ArraySupport;
},{"./main.js":42}],41:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Int8Array === 'function' ) ? Int8Array : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],42:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isInt8Array = require( '@stdlib/assert/is-int8array' );
var INT8_MAX = require( '@stdlib/constants/int8/max' );
var INT8_MIN = require( '@stdlib/constants/int8/min' );
var GlobalInt8Array = require( './int8array.js' );
// MAIN //
/**
* Tests for native `Int8Array` support.
*
* @returns {boolean} boolean indicating if an environment has `Int8Array` support
*
* @example
* var bool = hasInt8ArraySupport();
* // returns <boolean>
*/
function hasInt8ArraySupport() {
var bool;
var arr;
if ( typeof GlobalInt8Array !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = new GlobalInt8Array( [ 1, 3.14, -3.14, INT8_MAX+1 ] );
bool = (
isInt8Array( arr ) &&
arr[ 0 ] === 1 &&
arr[ 1 ] === 3 && // truncation
arr[ 2 ] === -3 && // truncation
arr[ 3 ] === INT8_MIN // wrap around
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasInt8ArraySupport;
},{"./int8array.js":41,"@stdlib/assert/is-int8array":99,"@stdlib/constants/int8/max":230,"@stdlib/constants/int8/min":231}],43:[function(require,module,exports){
(function (Buffer){(function (){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Buffer === 'function' ) ? Buffer : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
}).call(this)}).call(this,require("buffer").Buffer)
},{"buffer":379}],44:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test for native `Buffer` support.
*
* @module @stdlib/assert/has-node-buffer-support
*
* @example
* var hasNodeBufferSupport = require( '@stdlib/assert/has-node-buffer-support' );
*
* var bool = hasNodeBufferSupport();
* // returns <boolean>
*/
// MODULES //
var hasNodeBufferSupport = require( './main.js' );
// EXPORTS //
module.exports = hasNodeBufferSupport;
},{"./main.js":45}],45:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isBuffer = require( '@stdlib/assert/is-buffer' );
var GlobalBuffer = require( './buffer.js' );
// MAIN //
/**
* Tests for native `Buffer` support.
*
* @returns {boolean} boolean indicating if an environment has `Buffer` support
*
* @example
* var bool = hasNodeBufferSupport();
* // returns <boolean>
*/
function hasNodeBufferSupport() {
var bool;
var b;
if ( typeof GlobalBuffer !== 'function' ) {
return false;
}
// Test basic support...
try {
if ( typeof GlobalBuffer.from === 'function' ) {
b = GlobalBuffer.from( [ 1, 2, 3, 4 ] );
} else {
b = new GlobalBuffer( [ 1, 2, 3, 4 ] ); // Note: this is deprecated behavior starting in Node v6 (see https://nodejs.org/api/buffer.html#buffer_new_buffer_array)
}
bool = (
isBuffer( b ) &&
b[ 0 ] === 1 &&
b[ 1 ] === 2 &&
b[ 2 ] === 3 &&
b[ 3 ] === 4
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasNodeBufferSupport;
},{"./buffer.js":43,"@stdlib/assert/is-buffer":79}],46:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test whether an object has a specified property.
*
* @module @stdlib/assert/has-own-property
*
* @example
* var hasOwnProp = require( '@stdlib/assert/has-own-property' );
*
* var beep = {
* 'boop': true
* };
*
* var bool = hasOwnProp( beep, 'boop' );
* // returns true
*
* bool = hasOwnProp( beep, 'bop' );
* // returns false
*/
// MODULES //
var hasOwnProp = require( './main.js' );
// EXPORTS //
module.exports = hasOwnProp;
},{"./main.js":47}],47:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// FUNCTIONS //
var has = Object.prototype.hasOwnProperty;
// MAIN //
/**
* Tests if an object has a specified property.
*
* @param {*} value - value to test
* @param {*} property - property to test
* @returns {boolean} boolean indicating if an object has a specified property
*
* @example
* var beep = {
* 'boop': true
* };
*
* var bool = hasOwnProp( beep, 'boop' );
* // returns true
*
* @example
* var beep = {
* 'boop': true
* };
*
* var bool = hasOwnProp( beep, 'bap' );
* // returns false
*/
function hasOwnProp( value, property ) {
if (
value === void 0 ||
value === null
) {
return false;
}
return has.call( value, property );
}
// EXPORTS //
module.exports = hasOwnProp;
},{}],48:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test for native `Symbol` support.
*
* @module @stdlib/assert/has-symbol-support
*
* @example
* var hasSymbolSupport = require( '@stdlib/assert/has-symbol-support' );
*
* var bool = hasSymbolSupport();
* // returns <boolean>
*/
// MODULES //
var hasSymbolSupport = require( './main.js' );
// EXPORTS //
module.exports = hasSymbolSupport;
},{"./main.js":49}],49:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
/**
* Tests for native `Symbol` support.
*
* @returns {boolean} boolean indicating if an environment has `Symbol` support
*
* @example
* var bool = hasSymbolSupport();
* // returns <boolean>
*/
function hasSymbolSupport() {
return (
typeof Symbol === 'function' &&
typeof Symbol( 'foo' ) === 'symbol'
);
}
// EXPORTS //
module.exports = hasSymbolSupport;
},{}],50:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test for native `toStringTag` support.
*
* @module @stdlib/assert/has-tostringtag-support
*
* @example
* var hasToStringTagSupport = require( '@stdlib/assert/has-tostringtag-support' );
*
* var bool = hasToStringTagSupport();
* // returns <boolean>
*/
// MODULES //
var hasToStringTagSupport = require( './main.js' );
// EXPORTS //
module.exports = hasToStringTagSupport;
},{"./main.js":51}],51:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var hasSymbols = require( '@stdlib/assert/has-symbol-support' );
// VARIABLES //
var FLG = hasSymbols();
// MAIN //
/**
* Tests for native `toStringTag` support.
*
* @returns {boolean} boolean indicating if an environment has `toStringTag` support
*
* @example
* var bool = hasToStringTagSupport();
* // returns <boolean>
*/
function hasToStringTagSupport() {
return ( FLG && typeof Symbol.toStringTag === 'symbol' );
}
// EXPORTS //
module.exports = hasToStringTagSupport;
},{"@stdlib/assert/has-symbol-support":48}],52:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test for native `Uint16Array` support.
*
* @module @stdlib/assert/has-uint16array-support
*
* @example
* var hasUint16ArraySupport = require( '@stdlib/assert/has-uint16array-support' );
*
* var bool = hasUint16ArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasUint16ArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasUint16ArraySupport;
},{"./main.js":53}],53:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isUint16Array = require( '@stdlib/assert/is-uint16array' );
var UINT16_MAX = require( '@stdlib/constants/uint16/max' );
var GlobalUint16Array = require( './uint16array.js' );
// MAIN //
/**
* Tests for native `Uint16Array` support.
*
* @returns {boolean} boolean indicating if an environment has `Uint16Array` support
*
* @example
* var bool = hasUint16ArraySupport();
* // returns <boolean>
*/
function hasUint16ArraySupport() {
var bool;
var arr;
if ( typeof GlobalUint16Array !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = [ 1, 3.14, -3.14, UINT16_MAX+1, UINT16_MAX+2 ];
arr = new GlobalUint16Array( arr );
bool = (
isUint16Array( arr ) &&
arr[ 0 ] === 1 &&
arr[ 1 ] === 3 && // truncation
arr[ 2 ] === UINT16_MAX-2 && // truncation and wrap around
arr[ 3 ] === 0 && // wrap around
arr[ 4 ] === 1 // wrap around
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasUint16ArraySupport;
},{"./uint16array.js":54,"@stdlib/assert/is-uint16array":155,"@stdlib/constants/uint16/max":232}],54:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Uint16Array === 'function' ) ? Uint16Array : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],55:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test for native `Uint32Array` support.
*
* @module @stdlib/assert/has-uint32array-support
*
* @example
* var hasUint32ArraySupport = require( '@stdlib/assert/has-uint32array-support' );
*
* var bool = hasUint32ArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasUint32ArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasUint32ArraySupport;
},{"./main.js":56}],56:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isUint32Array = require( '@stdlib/assert/is-uint32array' );
var UINT32_MAX = require( '@stdlib/constants/uint32/max' );
var GlobalUint32Array = require( './uint32array.js' );
// MAIN //
/**
* Tests for native `Uint32Array` support.
*
* @returns {boolean} boolean indicating if an environment has `Uint32Array` support
*
* @example
* var bool = hasUint32ArraySupport();
* // returns <boolean>
*/
function hasUint32ArraySupport() {
var bool;
var arr;
if ( typeof GlobalUint32Array !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = [ 1, 3.14, -3.14, UINT32_MAX+1, UINT32_MAX+2 ];
arr = new GlobalUint32Array( arr );
bool = (
isUint32Array( arr ) &&
arr[ 0 ] === 1 &&
arr[ 1 ] === 3 && // truncation
arr[ 2 ] === UINT32_MAX-2 && // truncation and wrap around
arr[ 3 ] === 0 && // wrap around
arr[ 4 ] === 1 // wrap around
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasUint32ArraySupport;
},{"./uint32array.js":57,"@stdlib/assert/is-uint32array":157,"@stdlib/constants/uint32/max":233}],57:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Uint32Array === 'function' ) ? Uint32Array : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],58:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test for native `Uint8Array` support.
*
* @module @stdlib/assert/has-uint8array-support
*
* @example
* var hasUint8ArraySupport = require( '@stdlib/assert/has-uint8array-support' );
*
* var bool = hasUint8ArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasUint8ArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasUint8ArraySupport;
},{"./main.js":59}],59:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isUint8Array = require( '@stdlib/assert/is-uint8array' );
var UINT8_MAX = require( '@stdlib/constants/uint8/max' );
var GlobalUint8Array = require( './uint8array.js' );
// MAIN //
/**
* Tests for native `Uint8Array` support.
*
* @returns {boolean} boolean indicating if an environment has `Uint8Array` support
*
* @example
* var bool = hasUint8ArraySupport();
* // returns <boolean>
*/
function hasUint8ArraySupport() {
var bool;
var arr;
if ( typeof GlobalUint8Array !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = [ 1, 3.14, -3.14, UINT8_MAX+1, UINT8_MAX+2 ];
arr = new GlobalUint8Array( arr );
bool = (
isUint8Array( arr ) &&
arr[ 0 ] === 1 &&
arr[ 1 ] === 3 && // truncation
arr[ 2 ] === UINT8_MAX-2 && // truncation and wrap around
arr[ 3 ] === 0 && // wrap around
arr[ 4 ] === 1 // wrap around
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasUint8ArraySupport;
},{"./uint8array.js":60,"@stdlib/assert/is-uint8array":159,"@stdlib/constants/uint8/max":234}],60:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Uint8Array === 'function' ) ? Uint8Array : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],61:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test for native `Uint8ClampedArray` support.
*
* @module @stdlib/assert/has-uint8clampedarray-support
*
* @example
* var hasUint8ClampedArraySupport = require( '@stdlib/assert/has-uint8clampedarray-support' );
*
* var bool = hasUint8ClampedArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasUint8ClampedArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasUint8ClampedArraySupport;
},{"./main.js":62}],62:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isUint8ClampedArray = require( '@stdlib/assert/is-uint8clampedarray' );
var GlobalUint8ClampedArray = require( './uint8clampedarray.js' );
// MAIN //
/**
* Tests for native `Uint8ClampedArray` support.
*
* @returns {boolean} boolean indicating if an environment has `Uint8ClampedArray` support
*
* @example
* var bool = hasUint8ClampedArraySupport();
* // returns <boolean>
*/
function hasUint8ClampedArraySupport() { // eslint-disable-line id-length
var bool;
var arr;
if ( typeof GlobalUint8ClampedArray !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = new GlobalUint8ClampedArray( [ -1, 0, 1, 3.14, 4.99, 255, 256 ] );
bool = (
isUint8ClampedArray( arr ) &&
arr[ 0 ] === 0 && // clamped
arr[ 1 ] === 0 &&
arr[ 2 ] === 1 &&
arr[ 3 ] === 3 && // round to nearest
arr[ 4 ] === 5 && // round to nearest
arr[ 5 ] === 255 &&
arr[ 6 ] === 255 // clamped
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasUint8ClampedArraySupport;
},{"./uint8clampedarray.js":63,"@stdlib/assert/is-uint8clampedarray":161}],63:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Uint8ClampedArray === 'function' ) ? Uint8ClampedArray : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],64:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isArguments = require( './main.js' );
// VARIABLES //
var bool;
// FUNCTIONS //
/**
* Detects whether an environment returns the expected internal class of the `arguments` object.
*
* @private
* @returns {boolean} boolean indicating whether an environment behaves as expected
*
* @example
* var bool = detect();
* // returns <boolean>
*/
function detect() {
return isArguments( arguments );
}
// MAIN //
bool = detect();
// EXPORTS //
module.exports = bool;
},{"./main.js":66}],65:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test if a value is an `arguments` object.
*
* @module @stdlib/assert/is-arguments
*
* @example
* var isArguments = require( '@stdlib/assert/is-arguments' );
*
* function foo() {
* return arguments;
* }
*
* var bool = isArguments( foo() );
* // returns true
*
* bool = isArguments( [] );
* // returns false
*/
// MODULES //
var hasArgumentsClass = require( './detect.js' );
var main = require( './main.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var isArguments;
if ( hasArgumentsClass ) {
isArguments = main;
} else {
isArguments = polyfill;
}
// EXPORTS //
module.exports = isArguments;
},{"./detect.js":64,"./main.js":66,"./polyfill.js":67}],66:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// MAIN //
/**
* Tests whether a value is an `arguments` object.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value is an `arguments` object
*
* @example
* function foo() {
* return arguments;
* }
*
* var bool = isArguments( foo() );
* // returns true
*
* @example
* var bool = isArguments( [] );
* // returns false
*/
function isArguments( value ) {
return ( nativeClass( value ) === '[object Arguments]' );
}
// EXPORTS //
module.exports = isArguments;
},{"@stdlib/utils/native-class":346}],67:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isEnumerableProperty = require( '@stdlib/assert/is-enumerable-property' );
var isArray = require( '@stdlib/assert/is-array' );
var isInteger = require( '@stdlib/math/base/assert/is-integer' );
var MAX_LENGTH = require( '@stdlib/constants/uint32/max' );
// MAIN //
/**
* Tests whether a value is an `arguments` object.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value is an `arguments` object
*
* @example
* function foo() {
* return arguments;
* }
*
* var bool = isArguments( foo() );
* // returns true
*
* @example
* var bool = isArguments( [] );
* // returns false
*/
function isArguments( value ) {
return (
value !== null &&
typeof value === 'object' &&
!isArray( value ) &&
typeof value.length === 'number' &&
isInteger( value.length ) &&
value.length >= 0 &&
value.length <= MAX_LENGTH &&
hasOwnProp( value, 'callee' ) &&
!isEnumerableProperty( value, 'callee' )
);
}
// EXPORTS //
module.exports = isArguments;
},{"@stdlib/assert/has-own-property":46,"@stdlib/assert/is-array":70,"@stdlib/assert/is-enumerable-property":84,"@stdlib/constants/uint32/max":233,"@stdlib/math/base/assert/is-integer":237}],68:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test if a value is array-like.
*
* @module @stdlib/assert/is-array-like
*
* @example
* var isArrayLike = require( '@stdlib/assert/is-array-like' );
*
* var bool = isArrayLike( [] );
* // returns true
*
* bool = isArrayLike( { 'length': 10 } );
* // returns true
*
* bool = isArrayLike( 'beep' );
* // returns true
*/
// MODULES //
var isArrayLike = require( './main.js' );
// EXPORTS //
module.exports = isArrayLike;
},{"./main.js":69}],69:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isInteger = require( '@stdlib/math/base/assert/is-integer' );
var MAX_LENGTH = require( '@stdlib/constants/array/max-array-length' );
// MAIN //
/**
* Tests if a value is array-like.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is array-like
*
* @example
* var bool = isArrayLike( [] );
* // returns true
*
* @example
* var bool = isArrayLike( {'length':10} );
* // returns true
*/
function isArrayLike( value ) {
return (
value !== void 0 &&
value !== null &&
typeof value !== 'function' &&
typeof value.length === 'number' &&
isInteger( value.length ) &&
value.length >= 0 &&
value.length <= MAX_LENGTH
);
}
// EXPORTS //
module.exports = isArrayLike;
},{"@stdlib/constants/array/max-array-length":219,"@stdlib/math/base/assert/is-integer":237}],70:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test if a value is an array.
*
* @module @stdlib/assert/is-array
*
* @example
* var isArray = require( '@stdlib/assert/is-array' );
*
* var bool = isArray( [] );
* // returns true
*
* bool = isArray( {} );
* // returns false
*/
// MODULES //
var isArray = require( './main.js' );
// EXPORTS //
module.exports = isArray;
},{"./main.js":71}],71:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var f;
// FUNCTIONS //
/**
* Tests if a value is an array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is an array
*
* @example
* var bool = isArray( [] );
* // returns true
*
* @example
* var bool = isArray( {} );
* // returns false
*/
function isArray( value ) {
return ( nativeClass( value ) === '[object Array]' );
}
// MAIN //
if ( Array.isArray ) {
f = Array.isArray;
} else {
f = isArray;
}
// EXPORTS //
module.exports = f;
},{"@stdlib/utils/native-class":346}],72:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test if a value is a boolean.
*
* @module @stdlib/assert/is-boolean
*
* @example
* var isBoolean = require( '@stdlib/assert/is-boolean' );
*
* var bool = isBoolean( false );
* // returns true
*
* bool = isBoolean( new Boolean( false ) );
* // returns true
*
* @example
* // Use interface to check for boolean primitives...
* var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
*
* var bool = isBoolean( false );
* // returns true
*
* bool = isBoolean( new Boolean( true ) );
* // returns false
*
* @example
* // Use interface to check for boolean objects...
* var isBoolean = require( '@stdlib/assert/is-boolean' ).isObject;
*
* var bool = isBoolean( true );
* // returns false
*
* bool = isBoolean( new Boolean( false ) );
* // returns true
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isBoolean = require( './main.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
setReadOnly( isBoolean, 'isPrimitive', isPrimitive );
setReadOnly( isBoolean, 'isObject', isObject );
// EXPORTS //
module.exports = isBoolean;
},{"./main.js":73,"./object.js":74,"./primitive.js":75,"@stdlib/utils/define-nonenumerable-read-only-property":297}],73:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
/**
* Tests if a value is a boolean.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a boolean
*
* @example
* var bool = isBoolean( false );
* // returns true
*
* @example
* var bool = isBoolean( true );
* // returns true
*
* @example
* var bool = isBoolean( new Boolean( false ) );
* // returns true
*
* @example
* var bool = isBoolean( new Boolean( true ) );
* // returns true
*/
function isBoolean( value ) {
return ( isPrimitive( value ) || isObject( value ) );
}
// EXPORTS //
module.exports = isBoolean;
},{"./object.js":74,"./primitive.js":75}],74:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var hasToStringTag = require( '@stdlib/assert/has-tostringtag-support' );
var nativeClass = require( '@stdlib/utils/native-class' );
var test = require( './try2serialize.js' );
// VARIABLES //
var FLG = hasToStringTag();
// MAIN //
/**
* Tests if a value is a boolean object.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a boolean object
*
* @example
* var bool = isBoolean( true );
* // returns false
*
* @example
* var bool = isBoolean( new Boolean( false ) );
* // returns true
*/
function isBoolean( value ) {
if ( typeof value === 'object' ) {
if ( value instanceof Boolean ) {
return true;
}
if ( FLG ) {
return test( value );
}
return ( nativeClass( value ) === '[object Boolean]' );
}
return false;
}
// EXPORTS //
module.exports = isBoolean;
},{"./try2serialize.js":77,"@stdlib/assert/has-tostringtag-support":50,"@stdlib/utils/native-class":346}],75:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Tests if a value is a boolean primitive.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a boolean primitive
*
* @example
* var bool = isBoolean( true );
* // returns true
*
* @example
* var bool = isBoolean( false );
* // returns true
*
* @example
* var bool = isBoolean( new Boolean( true ) );
* // returns false
*/
function isBoolean( value ) {
return ( typeof value === 'boolean' );
}
// EXPORTS //
module.exports = isBoolean;
},{}],76:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// eslint-disable-next-line stdlib/no-redeclare
var toString = Boolean.prototype.toString; // non-generic
// EXPORTS //
module.exports = toString;
},{}],77:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var toString = require( './tostring.js' ); // eslint-disable-line stdlib/no-redeclare
// MAIN //
/**
* Attempts to serialize a value to a string.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value can be serialized
*/
function test( value ) {
try {
toString.call( value );
return true;
} catch ( err ) { // eslint-disable-line no-unused-vars
return false;
}
}
// EXPORTS //
module.exports = test;
},{"./tostring.js":76}],78:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// EXPORTS //
module.exports = true;
},{}],79:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test if a value is a Buffer instance.
*
* @module @stdlib/assert/is-buffer
*
* @example
* var isBuffer = require( '@stdlib/assert/is-buffer' );
*
* var v = isBuffer( new Buffer( 'beep' ) );
* // returns true
*
* v = isBuffer( {} );
* // returns false
*/
// MODULES //
var isBuffer = require( './main.js' );
// EXPORTS //
module.exports = isBuffer;
},{"./main.js":80}],80:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isObjectLike = require( '@stdlib/assert/is-object-like' );
// MAIN //
/**
* Tests if a value is a Buffer instance.
*
* @param {*} value - value to validate
* @returns {boolean} boolean indicating if a value is a Buffer instance
*
* @example
* var v = isBuffer( new Buffer( 'beep' ) );
* // returns true
*
* @example
* var v = isBuffer( new Buffer( [1,2,3,4] ) );
* // returns true
*
* @example
* var v = isBuffer( {} );
* // returns false
*
* @example
* var v = isBuffer( [] );
* // returns false
*/
function isBuffer( value ) {
return (
isObjectLike( value ) &&
(
// eslint-disable-next-line no-underscore-dangle
value._isBuffer || // for envs missing Object.prototype.constructor (e.g., Safari 5-7)
(
value.constructor &&
// WARNING: `typeof` is not a foolproof check, as certain envs consider RegExp and NodeList instances to be functions
typeof value.constructor.isBuffer === 'function' &&
value.constructor.isBuffer( value )
)
)
);
}
// EXPORTS //
module.exports = isBuffer;
},{"@stdlib/assert/is-object-like":134}],81:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test if a value is a collection.
*
* @module @stdlib/assert/is-collection
*
* @example
* var isCollection = require( '@stdlib/assert/is-collection' );
*
* var bool = isCollection( [] );
* // returns true
*
* bool = isCollection( {} );
* // returns false
*/
// MODULES //
var isCollection = require( './main.js' );
// EXPORTS //
module.exports = isCollection;
},{"./main.js":82}],82:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isInteger = require( '@stdlib/math/base/assert/is-integer' );
var MAX_LENGTH = require( '@stdlib/constants/array/max-typed-array-length' );
// MAIN //
/**
* Tests if a value is a collection.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value is a collection
*
* @example
* var bool = isCollection( [] );
* // returns true
*
* @example
* var bool = isCollection( {} );
* // returns false
*/
function isCollection( value ) {
return (
typeof value === 'object' &&
value !== null &&
typeof value.length === 'number' &&
isInteger( value.length ) &&
value.length >= 0 &&
value.length <= MAX_LENGTH
);
}
// EXPORTS //
module.exports = isCollection;
},{"@stdlib/constants/array/max-typed-array-length":220,"@stdlib/math/base/assert/is-integer":237}],83:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isEnum = require( './native.js' );
// VARIABLES //
var bool;
// FUNCTIONS //
/**
* Detects whether an environment has a bug where String indices are not detected as "enumerable" properties. Observed in Node v0.10.
*
* @private
* @returns {boolean} boolean indicating whether an environment has the bug
*/
function detect() {
return !isEnum.call( 'beep', '0' );
}
// MAIN //
bool = detect();
// EXPORTS //
module.exports = bool;
},{"./native.js":86}],84:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test whether an object's own property is enumerable.
*
* @module @stdlib/assert/is-enumerable-property
*
* @example
* var isEnumerableProperty = require( '@stdlib/assert/is-enumerable-property' );
*
* var beep = {
* 'boop': true
* };
*
* var bool = isEnumerableProperty( beep, 'boop' );
* // returns true
*
* bool = isEnumerableProperty( beep, 'hasOwnProperty' );
* // returns false
*/
// MODULES //
var isEnumerableProperty = require( './main.js' );
// EXPORTS //
module.exports = isEnumerableProperty;
},{"./main.js":85}],85:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' );
var isnan = require( '@stdlib/assert/is-nan' ).isPrimitive;
var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive;
var isEnum = require( './native.js' );
var hasStringEnumBug = require( './has_string_enumerability_bug.js' );
// MAIN //
/**
* Tests if an object's own property is enumerable.
*
* @param {*} value - value to test
* @param {*} property - property to test
* @returns {boolean} boolean indicating if an object property is enumerable
*
* @example
* var beep = {
* 'boop': true
* };
*
* var bool = isEnumerableProperty( beep, 'boop' );
* // returns true
*
* @example
* var beep = {
* 'boop': true
* };
*
* var bool = isEnumerableProperty( beep, 'hasOwnProperty' );
* // returns false
*/
function isEnumerableProperty( value, property ) {
var bool;
if (
value === void 0 ||
value === null
) {
return false;
}
bool = isEnum.call( value, property );
if ( !bool && hasStringEnumBug && isString( value ) ) {
// Note: we only check for indices, as properties attached to a `String` object are properly detected as enumerable above.
property = +property;
return (
!isnan( property ) &&
isInteger( property ) &&
property >= 0 &&
property < value.length
);
}
return bool;
}
// EXPORTS //
module.exports = isEnumerableProperty;
},{"./has_string_enumerability_bug.js":83,"./native.js":86,"@stdlib/assert/is-integer":101,"@stdlib/assert/is-nan":109,"@stdlib/assert/is-string":149}],86:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
/**
* Tests if an object's own property is enumerable.
*
* @private
* @name isEnumerableProperty
* @type {Function}
* @param {*} value - value to test
* @param {*} property - property to test
* @returns {boolean} boolean indicating if an object property is enumerable
*
* @example
* var beep = {
* 'boop': true
* };
*
* var bool = isEnumerableProperty( beep, 'boop' );
* // returns true
*
* @example
* var beep = {
* 'boop': true
* };
*
* var bool = isEnumerableProperty( beep, 'hasOwnProperty' );
* // returns false
*/
var isEnumerableProperty = Object.prototype.propertyIsEnumerable;
// EXPORTS //
module.exports = isEnumerableProperty;
},{}],87:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test if a value is an `Error` object.
*
* @module @stdlib/assert/is-error
*
* @example
* var isError = require( '@stdlib/assert/is-error' );
*
* var bool = isError( new Error( 'beep' ) );
* // returns true
*
* bool = isError( {} );
* // returns false
*/
// MODULES //
var isError = require( './main.js' );
// EXPORTS //
module.exports = isError;
},{"./main.js":88}],88:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var getPrototypeOf = require( '@stdlib/utils/get-prototype-of' );
var nativeClass = require( '@stdlib/utils/native-class' );
// MAIN //
/**
* Tests if a value is an `Error` object.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value is an `Error` object
*
* @example
* var bool = isError( new Error( 'beep' ) );
* // returns true
*
* @example
* var bool = isError( {} );
* // returns false
*/
function isError( value ) {
if ( typeof value !== 'object' || value === null ) {
return false;
}
// Check for `Error` objects from the same realm (same Node.js `vm` or same `Window` object)...
if ( value instanceof Error ) {
return true;
}
// Walk the prototype tree until we find an object having the desired native class...
while ( value ) {
if ( nativeClass( value ) === '[object Error]' ) {
return true;
}
value = getPrototypeOf( value );
}
return false;
}
// EXPORTS //
module.exports = isError;
},{"@stdlib/utils/get-prototype-of":312,"@stdlib/utils/native-class":346}],89:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test if a value is a Float32Array.
*
* @module @stdlib/assert/is-float32array
*
* @example
* var isFloat32Array = require( '@stdlib/assert/is-float32array' );
*
* var bool = isFloat32Array( new Float32Array( 10 ) );
* // returns true
*
* bool = isFloat32Array( [] );
* // returns false
*/
// MODULES //
var isFloat32Array = require( './main.js' );
// EXPORTS //
module.exports = isFloat32Array;
},{"./main.js":90}],90:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasFloat32Array = ( typeof Float32Array === 'function' );// eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is a Float32Array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a Float32Array
*
* @example
* var bool = isFloat32Array( new Float32Array( 10 ) );
* // returns true
*
* @example
* var bool = isFloat32Array( [] );
* // returns false
*/
function isFloat32Array( value ) {
return (
( hasFloat32Array && value instanceof Float32Array ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Float32Array]'
);
}
// EXPORTS //
module.exports = isFloat32Array;
},{"@stdlib/utils/native-class":346}],91:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test if a value is a Float64Array.
*
* @module @stdlib/assert/is-float64array
*
* @example
* var isFloat64Array = require( '@stdlib/assert/is-float64array' );
*
* var bool = isFloat64Array( new Float64Array( 10 ) );
* // returns true
*
* bool = isFloat64Array( [] );
* // returns false
*/
// MODULES //
var isFloat64Array = require( './main.js' );
// EXPORTS //
module.exports = isFloat64Array;
},{"./main.js":92}],92:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasFloat64Array = ( typeof Float64Array === 'function' ); // eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is a Float64Array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a Float64Array
*
* @example
* var bool = isFloat64Array( new Float64Array( 10 ) );
* // returns true
*
* @example
* var bool = isFloat64Array( [] );
* // returns false
*/
function isFloat64Array( value ) {
return (
( hasFloat64Array && value instanceof Float64Array ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Float64Array]'
);
}
// EXPORTS //
module.exports = isFloat64Array;
},{"@stdlib/utils/native-class":346}],93:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test if a value is a function.
*
* @module @stdlib/assert/is-function
*
* @example
* var isFunction = require( '@stdlib/assert/is-function' );
*
* function beep() {
* return 'beep';
* }
*
* var bool = isFunction( beep );
* // returns true
*/
// MODULES //
var isFunction = require( './main.js' );
// EXPORTS //
module.exports = isFunction;
},{"./main.js":94}],94:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var typeOf = require( '@stdlib/utils/type-of' );
// MAIN //
/**
* Tests if a value is a function.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a function
*
* @example
* function beep() {
* return 'beep';
* }
*
* var bool = isFunction( beep );
* // returns true
*/
function isFunction( value ) {
// Note: cannot use `typeof` directly, as various browser engines incorrectly return `'function'` when operating on non-function objects, such as regular expressions and NodeLists.
return ( typeOf( value ) === 'function' );
}
// EXPORTS //
module.exports = isFunction;
},{"@stdlib/utils/type-of":373}],95:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test if a value is an Int16Array.
*
* @module @stdlib/assert/is-int16array
*
* @example
* var isInt16Array = require( '@stdlib/assert/is-int16array' );
*
* var bool = isInt16Array( new Int16Array( 10 ) );
* // returns true
*
* bool = isInt16Array( [] );
* // returns false
*/
// MODULES //
var isInt16Array = require( './main.js' );
// EXPORTS //
module.exports = isInt16Array;
},{"./main.js":96}],96:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasInt16Array = ( typeof Int16Array === 'function' ); // eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is an Int16Array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is an Int16Array
*
* @example
* var bool = isInt16Array( new Int16Array( 10 ) );
* // returns true
*
* @example
* var bool = isInt16Array( [] );
* // returns false
*/
function isInt16Array( value ) {
return (
( hasInt16Array && value instanceof Int16Array ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Int16Array]'
);
}
// EXPORTS //
module.exports = isInt16Array;
},{"@stdlib/utils/native-class":346}],97:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test if a value is an Int32Array.
*
* @module @stdlib/assert/is-int32array
*
* @example
* var isInt32Array = require( '@stdlib/assert/is-int32array' );
*
* var bool = isInt32Array( new Int32Array( 10 ) );
* // returns true
*
* bool = isInt32Array( [] );
* // returns false
*/
// MODULES //
var isInt32Array = require( './main.js' );
// EXPORTS //
module.exports = isInt32Array;
},{"./main.js":98}],98:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasInt32Array = ( typeof Int32Array === 'function' ); // eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is an Int32Array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is an Int32Array
*
* @example
* var bool = isInt32Array( new Int32Array( 10 ) );
* // returns true
*
* @example
* var bool = isInt32Array( [] );
* // returns false
*/
function isInt32Array( value ) {
return (
( hasInt32Array && value instanceof Int32Array ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Int32Array]'
);
}
// EXPORTS //
module.exports = isInt32Array;
},{"@stdlib/utils/native-class":346}],99:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test if a value is an Int8Array.
*
* @module @stdlib/assert/is-int8array
*
* @example
* var isInt8Array = require( '@stdlib/assert/is-int8array' );
*
* var bool = isInt8Array( new Int8Array( 10 ) );
* // returns true
*
* bool = isInt8Array( [] );
* // returns false
*/
// MODULES //
var isInt8Array = require( './main.js' );
// EXPORTS //
module.exports = isInt8Array;
},{"./main.js":100}],100:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasInt8Array = ( typeof Int8Array === 'function' ); // eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is an Int8Array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is an Int8Array
*
* @example
* var bool = isInt8Array( new Int8Array( 10 ) );
* // returns true
*
* @example
* var bool = isInt8Array( [] );
* // returns false
*/
function isInt8Array( value ) {
return (
( hasInt8Array && value instanceof Int8Array ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Int8Array]'
);
}
// EXPORTS //
module.exports = isInt8Array;
},{"@stdlib/utils/native-class":346}],101:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test if a value is an integer.
*
* @module @stdlib/assert/is-integer
*
* @example
* var isInteger = require( '@stdlib/assert/is-integer' );
*
* var bool = isInteger( 5.0 );
* // returns true
*
* bool = isInteger( new Number( 5.0 ) );
* // returns true
*
* bool = isInteger( -3.14 );
* // returns false
*
* bool = isInteger( null );
* // returns false
*
* @example
* // Use interface to check for integer primitives...
* var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive;
*
* var bool = isInteger( -3.0 );
* // returns true
*
* bool = isInteger( new Number( -3.0 ) );
* // returns false
*
* @example
* // Use interface to check for integer objects...
* var isInteger = require( '@stdlib/assert/is-integer' ).isObject;
*
* var bool = isInteger( 3.0 );
* // returns false
*
* bool = isInteger( new Number( 3.0 ) );
* // returns true
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isInteger = require( './main.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
setReadOnly( isInteger, 'isPrimitive', isPrimitive );
setReadOnly( isInteger, 'isObject', isObject );
// EXPORTS //
module.exports = isInteger;
},{"./main.js":103,"./object.js":104,"./primitive.js":105,"@stdlib/utils/define-nonenumerable-read-only-property":297}],102:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var PINF = require( '@stdlib/constants/float64/pinf' );
var NINF = require( '@stdlib/constants/float64/ninf' );
var isInt = require( '@stdlib/math/base/assert/is-integer' );
// MAIN //
/**
* Tests if a number primitive is an integer value.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a number primitive is an integer value
*/
function isInteger( value ) {
return (
value < PINF &&
value > NINF &&
isInt( value )
);
}
// EXPORTS //
module.exports = isInteger;
},{"@stdlib/constants/float64/ninf":224,"@stdlib/constants/float64/pinf":225,"@stdlib/math/base/assert/is-integer":237}],103:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
/**
* Tests if a value is an integer.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is an integer
*
* @example
* var bool = isInteger( 5.0 );
* // returns true
*
* @example
* var bool = isInteger( new Number( 5.0 ) );
* // returns true
*
* @example
* var bool = isInteger( -3.14 );
* // returns false
*
* @example
* var bool = isInteger( null );
* // returns false
*/
function isInteger( value ) {
return ( isPrimitive( value ) || isObject( value ) );
}
// EXPORTS //
module.exports = isInteger;
},{"./object.js":104,"./primitive.js":105}],104:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isNumber = require( '@stdlib/assert/is-number' ).isObject;
var isInt = require( './integer.js' );
// MAIN //
/**
* Tests if a value is a number object having an integer value.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number object having an integer value
*
* @example
* var bool = isInteger( 3.0 );
* // returns false
*
* @example
* var bool = isInteger( new Number( 3.0 ) );
* // returns true
*/
function isInteger( value ) {
return (
isNumber( value ) &&
isInt( value.valueOf() )
);
}
// EXPORTS //
module.exports = isInteger;
},{"./integer.js":102,"@stdlib/assert/is-number":128}],105:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive;
var isInt = require( './integer.js' );
// MAIN //
/**
* Tests if a value is a number primitive having an integer value.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number primitive having an integer value
*
* @example
* var bool = isInteger( -3.0 );
* // returns true
*
* @example
* var bool = isInteger( new Number( -3.0 ) );
* // returns false
*/
function isInteger( value ) {
return (
isNumber( value ) &&
isInt( value )
);
}
// EXPORTS //
module.exports = isInteger;
},{"./integer.js":102,"@stdlib/assert/is-number":128}],106:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var Uint8Array = require( '@stdlib/array/uint8' );
var Uint16Array = require( '@stdlib/array/uint16' );
// MAIN //
var ctors = {
'uint16': Uint16Array,
'uint8': Uint8Array
};
// EXPORTS //
module.exports = ctors;
},{"@stdlib/array/uint16":16,"@stdlib/array/uint8":22}],107:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Return a boolean indicating if an environment is little endian.
*
* @module @stdlib/assert/is-little-endian
*
* @example
* var IS_LITTLE_ENDIAN = require( '@stdlib/assert/is-little-endian' );
*
* var bool = IS_LITTLE_ENDIAN;
* // returns <boolean>
*/
// MODULES //
var IS_LITTLE_ENDIAN = require( './main.js' );
// EXPORTS //
module.exports = IS_LITTLE_ENDIAN;
},{"./main.js":108}],108:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var ctors = require( './ctors.js' );
// VARIABLES //
var bool;
// FUNCTIONS //
/**
* Returns a boolean indicating if an environment is little endian.
*
* @private
* @returns {boolean} boolean indicating if an environment is little endian
*
* @example
* var bool = isLittleEndian();
* // returns <boolean>
*/
function isLittleEndian() {
var uint16view;
var uint8view;
uint16view = new ctors[ 'uint16' ]( 1 );
/*
* Set the uint16 view to a value having distinguishable lower and higher order words.
*
* 4660 => 0x1234 => 0x12 0x34 => '00010010 00110100' => (0x12,0x34) == (18,52)
*/
uint16view[ 0 ] = 0x1234;
// Create a uint8 view on top of the uint16 buffer:
uint8view = new ctors[ 'uint8' ]( uint16view.buffer );
// If little endian, the least significant byte will be first...
return ( uint8view[ 0 ] === 0x34 );
}
// MAIN //
bool = isLittleEndian();
// EXPORTS //
module.exports = bool;
},{"./ctors.js":106}],109:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test if a value is `NaN`.
*
* @module @stdlib/assert/is-nan
*
* @example
* var isnan = require( '@stdlib/assert/is-nan' );
*
* var bool = isnan( NaN );
* // returns true
*
* bool = isnan( new Number( NaN ) );
* // returns true
*
* bool = isnan( 3.14 );
* // returns false
*
* bool = isnan( null );
* // returns false
*
* @example
* var isnan = require( '@stdlib/assert/is-nan' ).isPrimitive;
*
* var bool = isnan( NaN );
* // returns true
*
* bool = isnan( 3.14 );
* // returns false
*
* bool = isnan( new Number( NaN ) );
* // returns false
*
* @example
* var isnan = require( '@stdlib/assert/is-nan' ).isObject;
*
* var bool = isnan( NaN );
* // returns false
*
* bool = isnan( new Number( NaN ) );
* // returns true
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isnan = require( './main.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
setReadOnly( isnan, 'isPrimitive', isPrimitive );
setReadOnly( isnan, 'isObject', isObject );
// EXPORTS //
module.exports = isnan;
},{"./main.js":110,"./object.js":111,"./primitive.js":112,"@stdlib/utils/define-nonenumerable-read-only-property":297}],110:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
/**
* Tests if a value is `NaN`.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is `NaN`
*
* @example
* var bool = isnan( NaN );
* // returns true
*
* @example
* var bool = isnan( new Number( NaN ) );
* // returns true
*
* @example
* var bool = isnan( 3.14 );
* // returns false
*
* @example
* var bool = isnan( null );
* // returns false
*/
function isnan( value ) {
return ( isPrimitive( value ) || isObject( value ) );
}
// EXPORTS //
module.exports = isnan;
},{"./object.js":111,"./primitive.js":112}],111:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isNumber = require( '@stdlib/assert/is-number' ).isObject;
var isNan = require( '@stdlib/math/base/assert/is-nan' );
// MAIN //
/**
* Tests if a value is a number object having a value of `NaN`.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number object having a value of `NaN`
*
* @example
* var bool = isnan( NaN );
* // returns false
*
* @example
* var bool = isnan( new Number( NaN ) );
* // returns true
*/
function isnan( value ) {
return (
isNumber( value ) &&
isNan( value.valueOf() )
);
}
// EXPORTS //
module.exports = isnan;
},{"@stdlib/assert/is-number":128,"@stdlib/math/base/assert/is-nan":239}],112:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive;
var isNan = require( '@stdlib/math/base/assert/is-nan' );
// MAIN //
/**
* Tests if a value is a `NaN` number primitive.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a `NaN` number primitive
*
* @example
* var bool = isnan( NaN );
* // returns true
*
* @example
* var bool = isnan( 3.14 );
* // returns false
*
* @example
* var bool = isnan( new Number( NaN ) );
* // returns false
*/
function isnan( value ) {
return (
isNumber( value ) &&
isNan( value )
);
}
// EXPORTS //
module.exports = isnan;
},{"@stdlib/assert/is-number":128,"@stdlib/math/base/assert/is-nan":239}],113:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test if a value is Node stream-like.
*
* @module @stdlib/assert/is-node-stream-like
*
* @example
* var transformStream = require( '@stdlib/streams/node/transform' );
* var isNodeStreamLike = require( '@stdlib/assert/is-node-stream-like' );
*
* var stream = transformStream();
*
* var bool = isNodeStreamLike( stream );
* // returns true
*
* bool = isNodeStreamLike( {} );
* // returns false
*/
// MODULES //
var isNodeStreamLike = require( './main.js' );
// EXPORTS //
module.exports = isNodeStreamLike;
},{"./main.js":114}],114:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
/**
* Tests if a value is Node stream-like.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is Node stream-like
*
* @example
* var transformStream = require( '@stdlib/streams/node/transform' );
*
* var stream = transformStream();
*
* var bool = isNodeStreamLike( stream );
* // returns true
*
* bool = isNodeStreamLike( {} );
* // returns false
*/
function isNodeStreamLike( value ) {
return (
// Must be an object:
value !== null &&
typeof value === 'object' &&
// Should be an event emitter:
typeof value.on === 'function' &&
typeof value.once === 'function' &&
typeof value.emit === 'function' &&
typeof value.addListener === 'function' &&
typeof value.removeListener === 'function' &&
typeof value.removeAllListeners === 'function' &&
// Should have a `pipe` method (Node streams inherit from `Stream`, including writable streams):
typeof value.pipe === 'function'
);
}
// EXPORTS //
module.exports = isNodeStreamLike;
},{}],115:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test if a value is Node writable stream-like.
*
* @module @stdlib/assert/is-node-writable-stream-like
*
* @example
* var transformStream = require( '@stdlib/streams/node/transform' );
* var isNodeWritableStreamLike = require( '@stdlib/assert/is-node-writable-stream-like' );
*
* var stream = transformStream();
*
* var bool = isNodeWritableStreamLike( stream );
* // returns true
*
* bool = isNodeWritableStreamLike( {} );
* // returns false
*/
// MODULES //
var isNodeWritableStreamLike = require( './main.js' );
// EXPORTS //
module.exports = isNodeWritableStreamLike;
},{"./main.js":116}],116:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
/* eslint-disable no-underscore-dangle */
'use strict';
// MODULES //
var isNodeStreamLike = require( '@stdlib/assert/is-node-stream-like' );
// MAIN //
/**
* Tests if a value is Node writable stream-like.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is Node writable stream-like
*
* @example
* var transformStream = require( '@stdlib/streams/node/transform' );
*
* var stream = transformStream();
*
* var bool = isNodeWritableStreamLike( stream );
* // returns true
*
* bool = isNodeWritableStreamLike( {} );
* // returns false
*/
function isNodeWritableStreamLike( value ) {
return (
// Must be stream-like:
isNodeStreamLike( value ) &&
// Should have writable stream methods:
typeof value._write === 'function' &&
// Should have writable stream state:
typeof value._writableState === 'object'
);
}
// EXPORTS //
module.exports = isNodeWritableStreamLike;
},{"@stdlib/assert/is-node-stream-like":113}],117:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test if a value is an array-like object containing only nonnegative integers.
*
* @module @stdlib/assert/is-nonnegative-integer-array
*
* @example
* var isNonNegativeIntegerArray = require( '@stdlib/assert/is-nonnegative-integer-array' );
*
* var bool = isNonNegativeIntegerArray( [ 3.0, new Number(3.0) ] );
* // returns true
*
* bool = isNonNegativeIntegerArray( [ 3.0, '3.0' ] );
* // returns false
*
* @example
* var isNonNegativeIntegerArray = require( '@stdlib/assert/is-nonnegative-integer-array' ).primitives;
*
* var bool = isNonNegativeIntegerArray( [ 1.0, 0.0, 10.0 ] );
* // returns true
*
* bool = isNonNegativeIntegerArray( [ 3.0, new Number(1.0) ] );
* // returns false
*
* @example
* var isNonNegativeIntegerArray = require( '@stdlib/assert/is-nonnegative-integer-array' ).objects;
*
* var bool = isNonNegativeIntegerArray( [ new Number(3.0), new Number(1.0) ] );
* // returns true
*
* bool = isNonNegativeIntegerArray( [ 1.0, 0.0, 10.0 ] );
* // returns false
*/
// MODULES //
var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' );
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var arrayfun = require( '@stdlib/assert/tools/array-like-function' );
// MAIN //
var isNonNegativeIntegerArray = arrayfun( isNonNegativeInteger );
setReadOnly( isNonNegativeIntegerArray, 'primitives', arrayfun( isNonNegativeInteger.isPrimitive ) );
setReadOnly( isNonNegativeIntegerArray, 'objects', arrayfun( isNonNegativeInteger.isObject ) );
// EXPORTS //
module.exports = isNonNegativeIntegerArray;
},{"@stdlib/assert/is-nonnegative-integer":118,"@stdlib/assert/tools/array-like-function":166,"@stdlib/utils/define-nonenumerable-read-only-property":297}],118:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test if a value is a nonnegative integer.
*
* @module @stdlib/assert/is-nonnegative-integer
*
* @example
* var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' );
*
* var bool = isNonNegativeInteger( 5.0 );
* // returns true
*
* bool = isNonNegativeInteger( new Number( 5.0 ) );
* // returns true
*
* bool = isNonNegativeInteger( -5.0 );
* // returns false
*
* bool = isNonNegativeInteger( 3.14 );
* // returns false
*
* bool = isNonNegativeInteger( null );
* // returns false
*
* @example
* var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive;
*
* var bool = isNonNegativeInteger( 3.0 );
* // returns true
*
* bool = isNonNegativeInteger( new Number( 3.0 ) );
* // returns false
*
* @example
* var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isObject;
*
* var bool = isNonNegativeInteger( 3.0 );
* // returns false
*
* bool = isNonNegativeInteger( new Number( 3.0 ) );
* // returns true
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isNonNegativeInteger = require( './main.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
setReadOnly( isNonNegativeInteger, 'isPrimitive', isPrimitive );
setReadOnly( isNonNegativeInteger, 'isObject', isObject );
// EXPORTS //
module.exports = isNonNegativeInteger;
},{"./main.js":119,"./object.js":120,"./primitive.js":121,"@stdlib/utils/define-nonenumerable-read-only-property":297}],119:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
/**
* Tests if a value is a nonnegative integer.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a nonnegative integer
*
* @example
* var bool = isNonNegativeInteger( 5.0 );
* // returns true
*
* @example
* var bool = isNonNegativeInteger( new Number( 5.0 ) );
* // returns true
*
* @example
* var bool = isNonNegativeInteger( -5.0 );
* // returns false
*
* @example
* var bool = isNonNegativeInteger( 3.14 );
* // returns false
*
* @example
* var bool = isNonNegativeInteger( null );
* // returns false
*/
function isNonNegativeInteger( value ) {
return ( isPrimitive( value ) || isObject( value ) );
}
// EXPORTS //
module.exports = isNonNegativeInteger;
},{"./object.js":120,"./primitive.js":121}],120:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isInteger = require( '@stdlib/assert/is-integer' ).isObject;
// MAIN //
/**
* Tests if a value is a number object having a nonnegative integer value.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number object having a nonnegative integer value
*
* @example
* var bool = isNonNegativeInteger( 3.0 );
* // returns false
*
* @example
* var bool = isNonNegativeInteger( new Number( 3.0 ) );
* // returns true
*/
function isNonNegativeInteger( value ) {
return (
isInteger( value ) &&
value.valueOf() >= 0
);
}
// EXPORTS //
module.exports = isNonNegativeInteger;
},{"@stdlib/assert/is-integer":101}],121:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive;
// MAIN //
/**
* Tests if a value is a number primitive having a nonnegative integer value.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number primitive having a nonnegative integer value
*
* @example
* var bool = isNonNegativeInteger( 3.0 );
* // returns true
*
* @example
* var bool = isNonNegativeInteger( new Number( 3.0 ) );
* // returns false
*/
function isNonNegativeInteger( value ) {
return (
isInteger( value ) &&
value >= 0
);
}
// EXPORTS //
module.exports = isNonNegativeInteger;
},{"@stdlib/assert/is-integer":101}],122:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test if a value is a nonnegative number.
*
* @module @stdlib/assert/is-nonnegative-number
*
* @example
* var isNonNegativeNumber = require( '@stdlib/assert/is-nonnegative-number' );
*
* var bool = isNonNegativeNumber( 5.0 );
* // returns true
*
* bool = isNonNegativeNumber( new Number( 5.0 ) );
* // returns true
*
* bool = isNonNegativeNumber( 3.14 );
* // returns true
*
* bool = isNonNegativeNumber( -5.0 );
* // returns false
*
* bool = isNonNegativeNumber( null );
* // returns false
*
* @example
* var isNonNegativeNumber = require( '@stdlib/assert/is-nonnegative-number' ).isPrimitive;
*
* var bool = isNonNegativeNumber( 3.0 );
* // returns true
*
* bool = isNonNegativeNumber( new Number( 3.0 ) );
* // returns false
*
* @example
* var isNonNegativeNumber = require( '@stdlib/assert/is-nonnegative-number' ).isObject;
*
* var bool = isNonNegativeNumber( 3.0 );
* // returns false
*
* bool = isNonNegativeNumber( new Number( 3.0 ) );
* // returns true
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isNonNegativeNumber = require( './main.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
setReadOnly( isNonNegativeNumber, 'isPrimitive', isPrimitive );
setReadOnly( isNonNegativeNumber, 'isObject', isObject );
// EXPORTS //
module.exports = isNonNegativeNumber;
},{"./main.js":123,"./object.js":124,"./primitive.js":125,"@stdlib/utils/define-nonenumerable-read-only-property":297}],123:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
/**
* Tests if a value is a nonnegative number.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a nonnegative number
*
* @example
* var bool = isNonNegativeNumber( 5.0 );
* // returns true
*
* @example
* var bool = isNonNegativeNumber( new Number( 5.0 ) );
* // returns true
*
* @example
* var bool = isNonNegativeNumber( 3.14 );
* // returns true
*
* @example
* var bool = isNonNegativeNumber( -5.0 );
* // returns false
*
* @example
* var bool = isNonNegativeNumber( null );
* // returns false
*/
function isNonNegativeNumber( value ) {
return ( isPrimitive( value ) || isObject( value ) );
}
// EXPORTS //
module.exports = isNonNegativeNumber;
},{"./object.js":124,"./primitive.js":125}],124:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isNumber = require( '@stdlib/assert/is-number' ).isObject;
// MAIN //
/**
* Tests if a value is a number object having a nonnegative value.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number object having a nonnegative number value
*
* @example
* var bool = isNonNegativeNumber( 3.0 );
* // returns false
*
* @example
* var bool = isNonNegativeNumber( new Number( 3.0 ) );
* // returns true
*/
function isNonNegativeNumber( value ) {
return (
isNumber( value ) &&
value.valueOf() >= 0.0
);
}
// EXPORTS //
module.exports = isNonNegativeNumber;
},{"@stdlib/assert/is-number":128}],125:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive;
// MAIN //
/**
* Tests if a value is a number primitive having a nonnegative value.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number primitive having a nonnegative number value
*
* @example
* var bool = isNonNegativeNumber( 3.0 );
* // returns true
*
* @example
* var bool = isNonNegativeNumber( new Number( 3.0 ) );
* // returns false
*/
function isNonNegativeNumber( value ) {
return (
isNumber( value ) &&
value >= 0.0
);
}
// EXPORTS //
module.exports = isNonNegativeNumber;
},{"@stdlib/assert/is-number":128}],126:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test if a value is `null`.
*
* @module @stdlib/assert/is-null
*
* @example
* var isNull = require( '@stdlib/assert/is-null' );
*
* var value = null;
*
* var bool = isNull( value );
* // returns true
*/
// MODULES //
var isNull = require( './main.js' );
// EXPORTS //
module.exports = isNull;
},{"./main.js":127}],127:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Tests if a value is `null`.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is null
*
* @example
* var bool = isNull( null );
* // returns true
*
* bool = isNull( true );
* // returns false
*/
function isNull( value ) {
return value === null;
}
// EXPORTS //
module.exports = isNull;
},{}],128:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test if a value is a number.
*
* @module @stdlib/assert/is-number
*
* @example
* var isNumber = require( '@stdlib/assert/is-number' );
*
* var bool = isNumber( 3.14 );
* // returns true
*
* bool = isNumber( new Number( 3.14 ) );
* // returns true
*
* bool = isNumber( NaN );
* // returns true
*
* bool = isNumber( null );
* // returns false
*
* @example
* var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive;
*
* var bool = isNumber( 3.14 );
* // returns true
*
* bool = isNumber( NaN );
* // returns true
*
* bool = isNumber( new Number( 3.14 ) );
* // returns false
*
* @example
* var isNumber = require( '@stdlib/assert/is-number' ).isObject;
*
* var bool = isNumber( 3.14 );
* // returns false
*
* bool = isNumber( new Number( 3.14 ) );
* // returns true
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isNumber = require( './main.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
setReadOnly( isNumber, 'isPrimitive', isPrimitive );
setReadOnly( isNumber, 'isObject', isObject );
// EXPORTS //
module.exports = isNumber;
},{"./main.js":129,"./object.js":130,"./primitive.js":131,"@stdlib/utils/define-nonenumerable-read-only-property":297}],129:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
/**
* Tests if a value is a number.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a number
*
* @example
* var bool = isNumber( 3.14 );
* // returns true
*
* @example
* var bool = isNumber( new Number( 3.14 ) );
* // returns true
*
* @example
* var bool = isNumber( NaN );
* // returns true
*
* @example
* var bool = isNumber( null );
* // returns false
*/
function isNumber( value ) {
return ( isPrimitive( value ) || isObject( value ) );
}
// EXPORTS //
module.exports = isNumber;
},{"./object.js":130,"./primitive.js":131}],130:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var hasToStringTag = require( '@stdlib/assert/has-tostringtag-support' );
var nativeClass = require( '@stdlib/utils/native-class' );
var Number = require( '@stdlib/number/ctor' );
var test = require( './try2serialize.js' );
// VARIABLES //
var FLG = hasToStringTag();
// MAIN //
/**
* Tests if a value is a number object.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number object
*
* @example
* var bool = isNumber( 3.14 );
* // returns false
*
* @example
* var bool = isNumber( new Number( 3.14 ) );
* // returns true
*/
function isNumber( value ) {
if ( typeof value === 'object' ) {
if ( value instanceof Number ) {
return true;
}
if ( FLG ) {
return test( value );
}
return ( nativeClass( value ) === '[object Number]' );
}
return false;
}
// EXPORTS //
module.exports = isNumber;
},{"./try2serialize.js":133,"@stdlib/assert/has-tostringtag-support":50,"@stdlib/number/ctor":248,"@stdlib/utils/native-class":346}],131:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Tests if a value is a number primitive.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number primitive
*
* @example
* var bool = isNumber( 3.14 );
* // returns true
*
* @example
* var bool = isNumber( NaN );
* // returns true
*
* @example
* var bool = isNumber( new Number( 3.14 ) );
* // returns false
*/
function isNumber( value ) {
return ( typeof value === 'number' );
}
// EXPORTS //
module.exports = isNumber;
},{}],132:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var Number = require( '@stdlib/number/ctor' );
// MAIN //
// eslint-disable-next-line stdlib/no-redeclare
var toString = Number.prototype.toString; // non-generic
// EXPORTS //
module.exports = toString;
},{"@stdlib/number/ctor":248}],133:[function(require,module,exports){
arguments[4][77][0].apply(exports,arguments)
},{"./tostring.js":132,"dup":77}],134:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test if a value is object-like.
*
* @module @stdlib/assert/is-object-like
*
* @example
* var isObjectLike = require( '@stdlib/assert/is-object-like' );
*
* var bool = isObjectLike( {} );
* // returns true
*
* bool = isObjectLike( [] );
* // returns true
*
* bool = isObjectLike( null );
* // returns false
*
* @example
* var isObjectLike = require( '@stdlib/assert/is-object-like' ).isObjectLikeArray;
*
* var bool = isObjectLike( [ {}, [] ] );
* // returns true
*
* bool = isObjectLike( [ {}, '3.0' ] );
* // returns false
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var arrayfun = require( '@stdlib/assert/tools/array-function' );
var isObjectLike = require( './main.js' );
// MAIN //
setReadOnly( isObjectLike, 'isObjectLikeArray', arrayfun( isObjectLike ) );
// EXPORTS //
module.exports = isObjectLike;
},{"./main.js":135,"@stdlib/assert/tools/array-function":164,"@stdlib/utils/define-nonenumerable-read-only-property":297}],135:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Tests if a value is object-like.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value is object-like
*
* @example
* var bool = isObjectLike( {} );
* // returns true
*
* @example
* var bool = isObjectLike( [] );
* // returns true
*
* @example
* var bool = isObjectLike( null );
* // returns false
*/
function isObjectLike( value ) {
return (
value !== null &&
typeof value === 'object'
);
}
// EXPORTS //
module.exports = isObjectLike;
},{}],136:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test if a value is an object.
*
* @module @stdlib/assert/is-object
*
* @example
* var isObject = require( '@stdlib/assert/is-object' );
*
* var bool = isObject( {} );
* // returns true
*
* bool = isObject( true );
* // returns false
*/
// MODULES //
var isObject = require( './main.js' );
// EXPORTS //
module.exports = isObject;
},{"./main.js":137}],137:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isArray = require( '@stdlib/assert/is-array' );
// MAIN //
/**
* Tests if a value is an object; e.g., `{}`.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is an object
*
* @example
* var bool = isObject( {} );
* // returns true
*
* @example
* var bool = isObject( null );
* // returns false
*/
function isObject( value ) {
return (
typeof value === 'object' &&
value !== null &&
!isArray( value )
);
}
// EXPORTS //
module.exports = isObject;
},{"@stdlib/assert/is-array":70}],138:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test if a value is a plain object.
*
* @module @stdlib/assert/is-plain-object
*
* @example
* var isPlainObject = require( '@stdlib/assert/is-plain-object' );
*
* var bool = isPlainObject( {} );
* // returns true
*
* bool = isPlainObject( null );
* // returns false
*/
// MODULES //
var isPlainObject = require( './main.js' );
// EXPORTS //
module.exports = isPlainObject;
},{"./main.js":139}],139:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isObject = require( '@stdlib/assert/is-object' );
var isFunction = require( '@stdlib/assert/is-function' );
var getPrototypeOf = require( '@stdlib/utils/get-prototype-of' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var objectPrototype = Object.prototype;
// FUNCTIONS //
/**
* Tests that an object only has own properties.
*
* @private
* @param {Object} obj - value to test
* @returns {boolean} boolean indicating if an object only has own properties
*/
function ownProps( obj ) {
var key;
// NOTE: possibility of perf boost if key enumeration order is known (see http://stackoverflow.com/questions/18531624/isplainobject-thing).
for ( key in obj ) {
if ( !hasOwnProp( obj, key ) ) {
return false;
}
}
return true;
}
// MAIN //
/**
* Tests if a value is a plain object.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a plain object
*
* @example
* var bool = isPlainObject( {} );
* // returns true
*
* @example
* var bool = isPlainObject( null );
* // returns false
*/
function isPlainObject( value ) {
var proto;
// Screen for obvious non-objects...
if ( !isObject( value ) ) {
return false;
}
// Objects with no prototype (e.g., `Object.create( null )`) are plain...
proto = getPrototypeOf( value );
if ( !proto ) {
return true;
}
// Objects having a prototype are plain if and only if they are constructed with a global `Object` function and the prototype points to the prototype of a plain object...
return (
// Cannot have own `constructor` property:
!hasOwnProp( value, 'constructor' ) &&
// Prototype `constructor` property must be a function (see also https://bugs.jquery.com/ticket/9897 and http://stackoverflow.com/questions/18531624/isplainobject-thing):
hasOwnProp( proto, 'constructor' ) &&
isFunction( proto.constructor ) &&
nativeClass( proto.constructor ) === '[object Function]' &&
// Test for object-specific method:
hasOwnProp( proto, 'isPrototypeOf' ) &&
isFunction( proto.isPrototypeOf ) &&
(
// Test if the prototype matches the global `Object` prototype (same realm):
proto === objectPrototype ||
// Test that all properties are own properties (cross-realm; *most* likely a plain object):
ownProps( value )
)
);
}
// EXPORTS //
module.exports = isPlainObject;
},{"@stdlib/assert/has-own-property":46,"@stdlib/assert/is-function":93,"@stdlib/assert/is-object":136,"@stdlib/utils/get-prototype-of":312,"@stdlib/utils/native-class":346}],140:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test if a value is a positive integer.
*
* @module @stdlib/assert/is-positive-integer
*
* @example
* var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' );
*
* var bool = isPositiveInteger( 5.0 );
* // returns true
*
* bool = isPositiveInteger( new Number( 5.0 ) );
* // returns true
*
* bool = isPositiveInteger( -5.0 );
* // returns false
*
* bool = isPositiveInteger( 3.14 );
* // returns false
*
* bool = isPositiveInteger( null );
* // returns false
*
* @example
* var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive;
*
* var bool = isPositiveInteger( 3.0 );
* // returns true
*
* bool = isPositiveInteger( new Number( 3.0 ) );
* // returns false
*
* @example
* var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isObject;
*
* var bool = isPositiveInteger( 3.0 );
* // returns false
*
* bool = isPositiveInteger( new Number( 3.0 ) );
* // returns true
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isPositiveInteger = require( './main.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
setReadOnly( isPositiveInteger, 'isPrimitive', isPrimitive );
setReadOnly( isPositiveInteger, 'isObject', isObject );
// EXPORTS //
module.exports = isPositiveInteger;
},{"./main.js":141,"./object.js":142,"./primitive.js":143,"@stdlib/utils/define-nonenumerable-read-only-property":297}],141:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
/**
* Tests if a value is a positive integer.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a positive integer
*
* @example
* var bool = isPositiveInteger( 5.0 );
* // returns true
*
* @example
* var bool = isPositiveInteger( new Number( 5.0 ) );
* // returns true
*
* @example
* var bool = isPositiveInteger( 0.0 );
* // returns false
*
* @example
* var bool = isPositiveInteger( -5.0 );
* // returns false
*
* @example
* var bool = isPositiveInteger( 3.14 );
* // returns false
*
* @example
* var bool = isPositiveInteger( null );
* // returns false
*/
function isPositiveInteger( value ) {
return ( isPrimitive( value ) || isObject( value ) );
}
// EXPORTS //
module.exports = isPositiveInteger;
},{"./object.js":142,"./primitive.js":143}],142:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isInteger = require( '@stdlib/assert/is-integer' ).isObject;
// MAIN //
/**
* Tests if a value is a number object having a positive integer value.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number object having a positive integer value
*
* @example
* var bool = isPositiveInteger( 3.0 );
* // returns false
*
* @example
* var bool = isPositiveInteger( new Number( 3.0 ) );
* // returns true
*/
function isPositiveInteger( value ) {
return (
isInteger( value ) &&
value.valueOf() > 0.0
);
}
// EXPORTS //
module.exports = isPositiveInteger;
},{"@stdlib/assert/is-integer":101}],143:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive;
// MAIN //
/**
* Tests if a value is a number primitive having a positive integer value.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number primitive having a positive integer value
*
* @example
* var bool = isPositiveInteger( 3.0 );
* // returns true
*
* @example
* var bool = isPositiveInteger( new Number( 3.0 ) );
* // returns false
*/
function isPositiveInteger( value ) {
return (
isInteger( value ) &&
value > 0.0
);
}
// EXPORTS //
module.exports = isPositiveInteger;
},{"@stdlib/assert/is-integer":101}],144:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
var exec = RegExp.prototype.exec; // non-generic
// EXPORTS //
module.exports = exec;
},{}],145:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test if a value is a regular expression.
*
* @module @stdlib/assert/is-regexp
*
* @example
* var isRegExp = require( '@stdlib/assert/is-regexp' );
*
* var bool = isRegExp( /\.+/ );
* // returns true
*
* bool = isRegExp( {} );
* // returns false
*/
// MODULES //
var isRegExp = require( './main.js' );
// EXPORTS //
module.exports = isRegExp;
},{"./main.js":146}],146:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var hasToStringTag = require( '@stdlib/assert/has-tostringtag-support' );
var nativeClass = require( '@stdlib/utils/native-class' );
var test = require( './try2exec.js' );
// VARIABLES //
var FLG = hasToStringTag();
// MAIN //
/**
* Tests if a value is a regular expression.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a regular expression
*
* @example
* var bool = isRegExp( /\.+/ );
* // returns true
*
* @example
* var bool = isRegExp( {} );
* // returns false
*/
function isRegExp( value ) {
if ( typeof value === 'object' ) {
if ( value instanceof RegExp ) {
return true;
}
if ( FLG ) {
return test( value );
}
return ( nativeClass( value ) === '[object RegExp]' );
}
return false;
}
// EXPORTS //
module.exports = isRegExp;
},{"./try2exec.js":147,"@stdlib/assert/has-tostringtag-support":50,"@stdlib/utils/native-class":346}],147:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var exec = require( './exec.js' );
// MAIN //
/**
* Attempts to call a `RegExp` method.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating if able to call a `RegExp` method
*/
function test( value ) {
try {
exec.call( value );
return true;
} catch ( err ) { // eslint-disable-line no-unused-vars
return false;
}
}
// EXPORTS //
module.exports = test;
},{"./exec.js":144}],148:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test if a value is an array of strings.
*
* @module @stdlib/assert/is-string-array
*
* @example
* var isStringArray = require( '@stdlib/assert/is-string-array' );
*
* var bool = isStringArray( [ 'abc', 'def' ] );
* // returns true
*
* bool = isStringArray( [ 'abc', 123 ] );
* // returns false
*
* @example
* var isStringArray = require( '@stdlib/assert/is-string-array' ).primitives;
*
* var bool = isStringArray( [ 'abc', 'def' ] );
* // returns true
*
* bool = isStringArray( [ 'abc', new String( 'def' ) ] );
* // returns false
*
* @example
* var isStringArray = require( '@stdlib/assert/is-string-array' ).objects;
*
* var bool = isStringArray( [ new String( 'abc' ), new String( 'def' ) ] );
* // returns true
*
* bool = isStringArray( [ new String( 'abc' ), 'def' ] );
* // returns false
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var arrayfun = require( '@stdlib/assert/tools/array-function' );
var isString = require( '@stdlib/assert/is-string' );
// MAIN //
var isStringArray = arrayfun( isString );
setReadOnly( isStringArray, 'primitives', arrayfun( isString.isPrimitive ) );
setReadOnly( isStringArray, 'objects', arrayfun( isString.isObject ) );
// EXPORTS //
module.exports = isStringArray;
},{"@stdlib/assert/is-string":149,"@stdlib/assert/tools/array-function":164,"@stdlib/utils/define-nonenumerable-read-only-property":297}],149:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test if a value is a string.
*
* @module @stdlib/assert/is-string
*
* @example
* var isString = require( '@stdlib/assert/is-string' );
*
* var bool = isString( 'beep' );
* // returns true
*
* bool = isString( new String( 'beep' ) );
* // returns true
*
* bool = isString( 5 );
* // returns false
*
* @example
* var isString = require( '@stdlib/assert/is-string' ).isObject;
*
* var bool = isString( new String( 'beep' ) );
* // returns true
*
* bool = isString( 'beep' );
* // returns false
*
* @example
* var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
*
* var bool = isString( 'beep' );
* // returns true
*
* bool = isString( new String( 'beep' ) );
* // returns false
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isString = require( './main.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
setReadOnly( isString, 'isPrimitive', isPrimitive );
setReadOnly( isString, 'isObject', isObject );
// EXPORTS //
module.exports = isString;
},{"./main.js":150,"./object.js":151,"./primitive.js":152,"@stdlib/utils/define-nonenumerable-read-only-property":297}],150:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
/**
* Tests if a value is a string.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a string
*
* @example
* var bool = isString( new String( 'beep' ) );
* // returns true
*
* @example
* var bool = isString( 'beep' );
* // returns true
*/
function isString( value ) {
return ( isPrimitive( value ) || isObject( value ) );
}
// EXPORTS //
module.exports = isString;
},{"./object.js":151,"./primitive.js":152}],151:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var hasToStringTag = require( '@stdlib/assert/has-tostringtag-support' );
var nativeClass = require( '@stdlib/utils/native-class' );
var test = require( './try2valueof.js' );
// VARIABLES //
var FLG = hasToStringTag();
// MAIN //
/**
* Tests if a value is a string object.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a string object
*
* @example
* var bool = isString( new String( 'beep' ) );
* // returns true
*
* @example
* var bool = isString( 'beep' );
* // returns false
*/
function isString( value ) {
if ( typeof value === 'object' ) {
if ( value instanceof String ) {
return true;
}
if ( FLG ) {
return test( value );
}
return ( nativeClass( value ) === '[object String]' );
}
return false;
}
// EXPORTS //
module.exports = isString;
},{"./try2valueof.js":153,"@stdlib/assert/has-tostringtag-support":50,"@stdlib/utils/native-class":346}],152:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Tests if a value is a string primitive.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a string primitive
*
* @example
* var bool = isString( 'beep' );
* // returns true
*
* @example
* var bool = isString( new String( 'beep' ) );
* // returns false
*/
function isString( value ) {
return ( typeof value === 'string' );
}
// EXPORTS //
module.exports = isString;
},{}],153:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var valueOf = require( './valueof.js' ); // eslint-disable-line stdlib/no-redeclare
// MAIN //
/**
* Attempts to extract a string value.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a string can be extracted
*/
function test( value ) {
try {
valueOf.call( value );
return true;
} catch ( err ) { // eslint-disable-line no-unused-vars
return false;
}
}
// EXPORTS //
module.exports = test;
},{"./valueof.js":154}],154:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// eslint-disable-next-line stdlib/no-redeclare
var valueOf = String.prototype.valueOf; // non-generic
// EXPORTS //
module.exports = valueOf;
},{}],155:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test if a value is a Uint16Array.
*
* @module @stdlib/assert/is-uint16array
*
* @example
* var isUint16Array = require( '@stdlib/assert/is-uint16array' );
*
* var bool = isUint16Array( new Uint16Array( 10 ) );
* // returns true
*
* bool = isUint16Array( [] );
* // returns false
*/
// MODULES //
var isUint16Array = require( './main.js' );
// EXPORTS //
module.exports = isUint16Array;
},{"./main.js":156}],156:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasUint16Array = ( typeof Uint16Array === 'function' ); // eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is a Uint16Array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a Uint16Array
*
* @example
* var bool = isUint16Array( new Uint16Array( 10 ) );
* // returns true
*
* @example
* var bool = isUint16Array( [] );
* // returns false
*/
function isUint16Array( value ) {
return (
( hasUint16Array && value instanceof Uint16Array ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Uint16Array]'
);
}
// EXPORTS //
module.exports = isUint16Array;
},{"@stdlib/utils/native-class":346}],157:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test if a value is a Uint32Array.
*
* @module @stdlib/assert/is-uint32array
*
* @example
* var isUint32Array = require( '@stdlib/assert/is-uint32array' );
*
* var bool = isUint32Array( new Uint32Array( 10 ) );
* // returns true
*
* bool = isUint32Array( [] );
* // returns false
*/
// MODULES //
var isUint32Array = require( './main.js' );
// EXPORTS //
module.exports = isUint32Array;
},{"./main.js":158}],158:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasUint32Array = ( typeof Uint32Array === 'function' ); // eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is a Uint32Array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a Uint32Array
*
* @example
* var bool = isUint32Array( new Uint32Array( 10 ) );
* // returns true
*
* @example
* var bool = isUint32Array( [] );
* // returns false
*/
function isUint32Array( value ) {
return (
( hasUint32Array && value instanceof Uint32Array ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Uint32Array]'
);
}
// EXPORTS //
module.exports = isUint32Array;
},{"@stdlib/utils/native-class":346}],159:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test if a value is a Uint8Array.
*
* @module @stdlib/assert/is-uint8array
*
* @example
* var isUint8Array = require( '@stdlib/assert/is-uint8array' );
*
* var bool = isUint8Array( new Uint8Array( 10 ) );
* // returns true
*
* bool = isUint8Array( [] );
* // returns false
*/
// MODULES //
var isUint8Array = require( './main.js' );
// EXPORTS //
module.exports = isUint8Array;
},{"./main.js":160}],160:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasUint8Array = ( typeof Uint8Array === 'function' ); // eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is a Uint8Array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a Uint8Array
*
* @example
* var bool = isUint8Array( new Uint8Array( 10 ) );
* // returns true
*
* @example
* var bool = isUint8Array( [] );
* // returns false
*/
function isUint8Array( value ) {
return (
( hasUint8Array && value instanceof Uint8Array ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Uint8Array]'
);
}
// EXPORTS //
module.exports = isUint8Array;
},{"@stdlib/utils/native-class":346}],161:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test if a value is a Uint8ClampedArray.
*
* @module @stdlib/assert/is-uint8clampedarray
*
* @example
* var isUint8ClampedArray = require( '@stdlib/assert/is-uint8clampedarray' );
*
* var bool = isUint8ClampedArray( new Uint8ClampedArray( 10 ) );
* // returns true
*
* bool = isUint8ClampedArray( [] );
* // returns false
*/
// MODULES //
var isUint8ClampedArray = require( './main.js' );
// EXPORTS //
module.exports = isUint8ClampedArray;
},{"./main.js":162}],162:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasUint8ClampedArray = ( typeof Uint8ClampedArray === 'function' ); // eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is a Uint8ClampedArray.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a Uint8ClampedArray
*
* @example
* var bool = isUint8ClampedArray( new Uint8ClampedArray( 10 ) );
* // returns true
*
* @example
* var bool = isUint8ClampedArray( [] );
* // returns false
*/
function isUint8ClampedArray( value ) {
return (
( hasUint8ClampedArray && value instanceof Uint8ClampedArray ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Uint8ClampedArray]'
);
}
// EXPORTS //
module.exports = isUint8ClampedArray;
},{"@stdlib/utils/native-class":346}],163:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isArray = require( '@stdlib/assert/is-array' );
// MAIN //
/**
* Returns a function which tests if every element in an array passes a test condition.
*
* @param {Function} predicate - function to apply
* @throws {TypeError} must provide a function
* @returns {Function} an array function
*
* @example
* var isOdd = require( '@stdlib/assert/is-odd' );
*
* var arr1 = [ 1, 3, 5, 7 ];
* var arr2 = [ 3, 5, 8 ];
*
* var validate = arrayfcn( isOdd );
*
* var bool = validate( arr1 );
* // returns true
*
* bool = validate( arr2 );
* // returns false
*/
function arrayfcn( predicate ) {
if ( typeof predicate !== 'function' ) {
throw new TypeError( 'invalid argument. Must provide a function. Value: `' + predicate + '`.' );
}
return every;
/**
* Tests if every element in an array passes a test condition.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value is an array for which all elements pass a test condition
*/
function every( value ) {
var len;
var i;
if ( !isArray( value ) ) {
return false;
}
len = value.length;
if ( len === 0 ) {
return false;
}
for ( i = 0; i < len; i++ ) {
if ( predicate( value[ i ] ) === false ) {
return false;
}
}
return true;
}
}
// EXPORTS //
module.exports = arrayfcn;
},{"@stdlib/assert/is-array":70}],164:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Return a function which tests if every element in an array passes a test condition.
*
* @module @stdlib/assert/tools/array-function
*
* @example
* var isOdd = require( '@stdlib/assert/is-odd' );
* var arrayfcn = require( '@stdlib/assert/tools/array-function' );
*
* var arr1 = [ 1, 3, 5, 7 ];
* var arr2 = [ 3, 5, 8 ];
*
* var validate = arrayfcn( isOdd );
*
* var bool = validate( arr1 );
* // returns true
*
* bool = validate( arr2 );
* // returns false
*/
// MODULES //
var arrayfcn = require( './arrayfcn.js' );
// EXPORTS //
module.exports = arrayfcn;
},{"./arrayfcn.js":163}],165:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isArrayLike = require( '@stdlib/assert/is-array-like' );
// MAIN //
/**
* Returns a function which tests if every element in an array-like object passes a test condition.
*
* @param {Function} predicate - function to apply
* @throws {TypeError} must provide a function
* @returns {Function} an array-like object function
*
* @example
* var isOdd = require( '@stdlib/assert/is-odd' );
*
* var arr1 = [ 1, 3, 5, 7 ];
* var arr2 = [ 3, 5, 8 ];
*
* var validate = arraylikefcn( isOdd );
*
* var bool = validate( arr1 );
* // returns true
*
* bool = validate( arr2 );
* // returns false
*/
function arraylikefcn( predicate ) {
if ( typeof predicate !== 'function' ) {
throw new TypeError( 'invalid argument. Must provide a function. Value: `' + predicate + '`.' );
}
return every;
/**
* Tests if every element in an array-like object passes a test condition.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value is an array-like object for which all elements pass a test condition
*/
function every( value ) {
var len;
var i;
if ( !isArrayLike( value ) ) {
return false;
}
len = value.length;
if ( len === 0 ) {
return false;
}
for ( i = 0; i < len; i++ ) {
if ( predicate( value[ i ] ) === false ) {
return false;
}
}
return true;
}
}
// EXPORTS //
module.exports = arraylikefcn;
},{"@stdlib/assert/is-array-like":68}],166:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Return a function which tests if every element in an array-like object passes a test condition.
*
* @module @stdlib/assert/tools/array-like-function
*
* @example
* var isOdd = require( '@stdlib/assert/is-odd' );
* var arraylikefcn = require( '@stdlib/assert/tools/array-like-function' );
*
* var arr1 = [ 1, 3, 5, 7 ];
* var arr2 = [ 3, 5, 8 ];
*
* var validate = arraylikefcn( isOdd );
*
* var bool = validate( arr1 );
* // returns true
*
* bool = validate( arr2 );
* // returns false
*/
// MODULES //
var arraylikefcn = require( './arraylikefcn.js' );
// EXPORTS //
module.exports = arraylikefcn;
},{"./arraylikefcn.js":165}],167:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var TransformStream = require( '@stdlib/streams/node/transform' );
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isFunction = require( '@stdlib/assert/is-function' );
var createHarness = require( './harness' );
var harness = require( './get_harness.js' );
// VARIABLES //
var listeners = [];
// FUNCTIONS //
/**
* Callback invoked when a harness finishes running all benchmarks.
*
* @private
*/
function done() {
var len;
var f;
var i;
len = listeners.length;
// Inform all the listeners that the harness has finished...
for ( i = 0; i < len; i++ ) {
f = listeners.shift();
f();
}
}
/**
* Creates a results stream.
*
* @private
* @param {Options} [options] - stream options
* @throws {Error} must provide valid stream options
* @returns {TransformStream} results stream
*/
function createStream( options ) {
var stream;
var bench;
var opts;
if ( arguments.length ) {
opts = options;
} else {
opts = {};
}
// If we have already created a harness, calling this function simply creates another results stream...
if ( harness.cached ) {
bench = harness();
return bench.createStream( opts );
}
stream = new TransformStream( opts );
opts.stream = stream;
// Create a harness which uses the created output stream:
harness( opts, done );
return stream;
}
/**
* Adds a listener for when a harness finishes running all benchmarks.
*
* @private
* @param {Callback} clbk - listener
* @throws {TypeError} must provide a function
* @throws {Error} must provide a listener only once
* @returns {void}
*/
function onFinish( clbk ) {
var i;
if ( !isFunction( clbk ) ) {
throw new TypeError( 'invalid argument. Must provide a function. Value: `'+clbk+'`.' );
}
// Allow adding a listener only once...
for ( i = 0; i < listeners.length; i++ ) {
if ( clbk === listeners[ i ] ) {
throw new Error( 'invalid argument. Attempted to add duplicate listener.' );
}
}
listeners.push( clbk );
}
// MAIN //
/**
* Runs a benchmark.
*
* @param {string} name - benchmark name
* @param {Options} [options] - benchmark options
* @param {boolean} [options.skip=false] - boolean indicating whether to skip a benchmark
* @param {(PositiveInteger|null)} [options.iterations=null] - number of iterations
* @param {PositiveInteger} [options.repeats=3] - number of repeats
* @param {PositiveInteger} [options.timeout=300000] - number of milliseconds before a benchmark automatically fails
* @param {Function} [benchmark] - function containing benchmark code
* @throws {TypeError} first argument must be a string
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {TypeError} benchmark argument must a function
* @returns {Benchmark} benchmark harness
*
* @example
* bench( 'beep', function benchmark( b ) {
* var x;
* var i;
* b.tic();
* for ( i = 0; i < b.iterations; i++ ) {
* x = Math.sin( Math.random() );
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* }
* b.toc();
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* b.end();
* });
*/
function bench( name, options, benchmark ) {
var h = harness( done );
if ( arguments.length < 2 ) {
h( name );
} else if ( arguments.length === 2 ) {
h( name, options );
} else {
h( name, options, benchmark );
}
return bench;
}
/**
* Creates a benchmark harness.
*
* @name createHarness
* @memberof bench
* @type {Function}
* @param {Options} [options] - harness options
* @param {Callback} [clbk] - callback to invoke when a harness finishes running all benchmarks
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {TypeError} callback argument must be a function
* @returns {Function} benchmark harness
*/
setReadOnly( bench, 'createHarness', createHarness );
/**
* Creates a results stream.
*
* @name createStream
* @memberof bench
* @type {Function}
* @param {Options} [options] - stream options
* @throws {Error} must provide valid stream options
* @returns {TransformStream} results stream
*/
setReadOnly( bench, 'createStream', createStream );
/**
* Adds a listener for when a harness finishes running all benchmarks.
*
* @name onFinish
* @memberof bench
* @type {Function}
* @param {Callback} clbk - listener
* @throws {TypeError} must provide a function
* @throws {Error} must provide a listener only once
* @returns {void}
*/
setReadOnly( bench, 'onFinish', onFinish );
// EXPORTS //
module.exports = bench;
},{"./get_harness.js":189,"./harness":190,"@stdlib/assert/is-function":93,"@stdlib/streams/node/transform":273,"@stdlib/utils/define-nonenumerable-read-only-property":297}],168:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
// MAIN //
/**
* Generates an assertion.
*
* @private
* @param {boolean} ok - assertion outcome
* @param {Options} opts - options
*/
function assert( ok, opts ) {
/* eslint-disable no-invalid-this, no-unused-vars */ // TODO: remove no-unused-vars once `err` is used
var result;
var err;
result = {
'id': this._count,
'ok': ok,
'skip': opts.skip,
'todo': opts.todo,
'name': opts.message || '(unnamed assert)',
'operator': opts.operator
};
if ( hasOwnProp( opts, 'actual' ) ) {
result.actual = opts.actual;
}
if ( hasOwnProp( opts, 'expected' ) ) {
result.expected = opts.expected;
}
if ( !ok ) {
result.error = opts.error || new Error( this.name );
err = new Error( 'exception' );
// TODO: generate an exception in order to locate the calling function (https://github.com/substack/tape/blob/master/lib/test.js#L215)
}
this._count += 1;
this.emit( 'result', result );
}
// EXPORTS //
module.exports = assert;
},{"@stdlib/assert/has-own-property":46}],169:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// EXPORTS //
module.exports = clearTimeout;
},{}],170:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var trim = require( '@stdlib/string/trim' );
var replace = require( '@stdlib/string/replace' );
var EOL = require( '@stdlib/regexp/eol' ).REGEXP;
// VARIABLES //
var RE_COMMENT = /^#\s*/;
// MAIN //
/**
* Writes a comment.
*
* @private
* @param {string} msg - comment message
*/
function comment( msg ) {
/* eslint-disable no-invalid-this */
var lines;
var i;
msg = trim( msg );
lines = msg.split( EOL );
for ( i = 0; i < lines.length; i++ ) {
msg = trim( lines[ i ] );
msg = replace( msg, RE_COMMENT, '' );
this.emit( 'result', msg );
}
}
// EXPORTS //
module.exports = comment;
},{"@stdlib/regexp/eol":257,"@stdlib/string/replace":279,"@stdlib/string/trim":281}],171:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
/**
* Asserts that `actual` is deeply equal to `expected`.
*
* @private
* @param {*} actual - actual value
* @param {*} expected - expected value
* @param {string} [msg] message
*/
function deepEqual( actual, expected, msg ) {
/* eslint-disable no-invalid-this */
this.comment( 'actual: '+actual+'. expected: '+expected+'. msg: '+msg+'.' );
// TODO: implement
}
// EXPORTS //
module.exports = deepEqual;
},{}],172:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var nextTick = require( './../utils/next_tick.js' );
// MAIN //
/**
* Ends a benchmark.
*
* @private
*/
function end() {
/* eslint-disable no-invalid-this */
var self = this;
if ( this._ended ) {
this.fail( '.end() called more than once' );
} else {
// Prevents releasing the zalgo when running synchronous benchmarks.
nextTick( onTick );
}
this._ended = true;
this._running = false;
/**
* Callback invoked upon a subsequent tick of the event loop.
*
* @private
*/
function onTick() {
self.emit( 'end' );
}
}
// EXPORTS //
module.exports = end;
},{"./../utils/next_tick.js":209}],173:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
/**
* Returns a `boolean` indicating if a benchmark has ended.
*
* @private
* @returns {boolean} boolean indicating if a benchmark has ended
*/
function ended() {
/* eslint-disable no-invalid-this */
return this._ended;
}
// EXPORTS //
module.exports = ended;
},{}],174:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
/**
* Asserts that `actual` is strictly equal to `expected`.
*
* @private
* @param {*} actual - actual value
* @param {*} expected - expected value
* @param {string} [msg] - message
*/
function equal( actual, expected, msg ) {
/* eslint-disable no-invalid-this */
this._assert( actual === expected, {
'message': msg || 'should be equal',
'operator': 'equal',
'expected': expected,
'actual': actual
});
}
// EXPORTS //
module.exports = equal;
},{}],175:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
/**
* Forcefully ends a benchmark.
*
* @private
* @returns {void}
*/
function exit() {
/* eslint-disable no-invalid-this */
if ( this._exited ) {
// If we have already "exited", do not create more failing assertions when one should suffice...
return;
}
// Only "exit" when a benchmark has either not yet been run or is currently running. If a benchmark has already ended, no need to generate a failing assertion.
if ( !this._ended ) {
this._exited = true;
this.fail( 'benchmark exited without ending' );
// Allow running benchmarks to call `end` on their own...
if ( !this._running ) {
this.end();
}
}
}
// EXPORTS //
module.exports = exit;
},{}],176:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
/**
* Generates a failing assertion.
*
* @private
* @param {string} msg - message
*/
function fail( msg ) {
/* eslint-disable no-invalid-this */
this._assert( false, {
'message': msg,
'operator': 'fail'
});
}
// EXPORTS //
module.exports = fail;
},{}],177:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var EventEmitter = require( 'events' ).EventEmitter;
var inherit = require( '@stdlib/utils/inherit' );
var defineProperty = require( '@stdlib/utils/define-property' );
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var tic = require( '@stdlib/time/tic' );
var toc = require( '@stdlib/time/toc' );
var run = require( './run.js' );
var exit = require( './exit.js' );
var ended = require( './ended.js' );
var assert = require( './assert.js' );
var comment = require( './comment.js' );
var skip = require( './skip.js' );
var todo = require( './todo.js' );
var fail = require( './fail.js' );
var pass = require( './pass.js' );
var ok = require( './ok.js' );
var notOk = require( './not_ok.js' );
var equal = require( './equal.js' );
var notEqual = require( './not_equal.js' );
var deepEqual = require( './deep_equal.js' );
var notDeepEqual = require( './not_deep_equal.js' );
var end = require( './end.js' );
// MAIN //
/**
* Benchmark constructor.
*
* @constructor
* @param {string} name - benchmark name
* @param {Options} opts - benchmark options
* @param {boolean} opts.skip - boolean indicating whether to skip a benchmark
* @param {PositiveInteger} opts.iterations - number of iterations
* @param {PositiveInteger} opts.timeout - number of milliseconds before a benchmark automatically fails
* @param {Function} [benchmark] - function containing benchmark code
* @returns {Benchmark} Benchmark instance
*
* @example
* var bench = new Benchmark( 'beep', function benchmark( b ) {
* var x;
* var i;
* b.comment( 'Running benchmarks...' );
* b.tic();
* for ( i = 0; i < b.iterations; i++ ) {
* x = Math.sin( Math.random() );
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* }
* b.toc();
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* b.comment( 'Finished running benchmarks.' );
* b.end();
* });
*/
function Benchmark( name, opts, benchmark ) {
var hasTicked;
var hasTocked;
var self;
var time;
if ( !( this instanceof Benchmark ) ) {
return new Benchmark( name, opts, benchmark );
}
self = this;
hasTicked = false;
hasTocked = false;
EventEmitter.call( this );
// Private properties:
setReadOnly( this, '_benchmark', benchmark );
setReadOnly( this, '_skip', opts.skip );
defineProperty( this, '_ended', {
'configurable': false,
'enumerable': false,
'writable': true,
'value': false
});
defineProperty( this, '_running', {
'configurable': false,
'enumerable': false,
'writable': true,
'value': false
});
defineProperty( this, '_exited', {
'configurable': false,
'enumerable': false,
'writable': true,
'value': false
});
defineProperty( this, '_count', {
'configurable': false,
'enumerable': false,
'writable': true,
'value': 0
});
// Read-only:
setReadOnly( this, 'name', name );
setReadOnly( this, 'tic', start );
setReadOnly( this, 'toc', stop );
setReadOnly( this, 'iterations', opts.iterations );
setReadOnly( this, 'timeout', opts.timeout );
return this;
/**
* Starts a benchmark timer.
*
* ## Notes
*
* - Using a scoped variable prevents nefarious mutation by bad actors hoping to manipulate benchmark results.
* - The one attack vector which remains is manipulation of the `require` cache for `tic` and `toc`.
* - One way to combat cache manipulation is by comparing the checksum of `Function#toString()` against known values.
*
* @private
*/
function start() {
if ( hasTicked ) {
self.fail( '.tic() called more than once' );
} else {
self.emit( 'tic' );
hasTicked = true;
time = tic();
}
}
/**
* Stops a benchmark timer.
*
* @private
* @returns {void}
*/
function stop() {
var elapsed;
var secs;
var rate;
var out;
if ( hasTicked === false ) {
return self.fail( '.toc() called before .tic()' );
}
elapsed = toc( time );
if ( hasTocked ) {
return self.fail( '.toc() called more than once' );
}
hasTocked = true;
self.emit( 'toc' );
secs = elapsed[ 0 ] + ( elapsed[ 1 ]/1e9 );
rate = self.iterations / secs;
out = {
'ok': true,
'operator': 'result',
'iterations': self.iterations,
'elapsed': secs,
'rate': rate
};
self.emit( 'result', out );
}
}
/*
* Inherit from the `EventEmitter` prototype.
*/
inherit( Benchmark, EventEmitter );
/**
* Runs a benchmark.
*
* @private
* @name run
* @memberof Benchmark.prototype
* @type {Function}
*/
setReadOnly( Benchmark.prototype, 'run', run );
/**
* Forcefully ends a benchmark.
*
* @private
* @name exit
* @memberof Benchmark.prototype
* @type {Function}
*/
setReadOnly( Benchmark.prototype, 'exit', exit );
/**
* Returns a `boolean` indicating if a benchmark has ended.
*
* @private
* @name ended
* @memberof Benchmark.prototype
* @type {Function}
* @returns {boolean} boolean indicating if a benchmark has ended
*/
setReadOnly( Benchmark.prototype, 'ended', ended );
/**
* Generates an assertion.
*
* @private
* @name _assert
* @memberof Benchmark.prototype
* @type {Function}
* @param {boolean} ok - assertion outcome
* @param {Options} opts - options
*/
setReadOnly( Benchmark.prototype, '_assert', assert );
/**
* Writes a comment.
*
* @name comment
* @memberof Benchmark.prototype
* @type {Function}
* @param {string} msg - comment message
*/
setReadOnly( Benchmark.prototype, 'comment', comment );
/**
* Generates an assertion which will be skipped.
*
* @name skip
* @memberof Benchmark.prototype
* @type {Function}
* @param {*} value - value
* @param {string} msg - message
*/
setReadOnly( Benchmark.prototype, 'skip', skip );
/**
* Generates an assertion which should be implemented.
*
* @name todo
* @memberof Benchmark.prototype
* @type {Function}
* @param {*} value - value
* @param {string} msg - message
*/
setReadOnly( Benchmark.prototype, 'todo', todo );
/**
* Generates a failing assertion.
*
* @name fail
* @memberof Benchmark.prototype
* @type {Function}
* @param {string} msg - message
*/
setReadOnly( Benchmark.prototype, 'fail', fail );
/**
* Generates a passing assertion.
*
* @name pass
* @memberof Benchmark.prototype
* @type {Function}
* @param {string} msg - message
*/
setReadOnly( Benchmark.prototype, 'pass', pass );
/**
* Asserts that a `value` is truthy.
*
* @name ok
* @memberof Benchmark.prototype
* @type {Function}
* @param {*} value - value
* @param {string} [msg] - message
*/
setReadOnly( Benchmark.prototype, 'ok', ok );
/**
* Asserts that a `value` is falsy.
*
* @name notOk
* @memberof Benchmark.prototype
* @type {Function}
* @param {*} value - value
* @param {string} [msg] - message
*/
setReadOnly( Benchmark.prototype, 'notOk', notOk );
/**
* Asserts that `actual` is strictly equal to `expected`.
*
* @name equal
* @memberof Benchmark.prototype
* @type {Function}
* @param {*} actual - actual value
* @param {*} expected - expected value
* @param {string} [msg] - message
*/
setReadOnly( Benchmark.prototype, 'equal', equal );
/**
* Asserts that `actual` is not strictly equal to `expected`.
*
* @name notEqual
* @memberof Benchmark.prototype
* @type {Function}
* @param {*} actual - actual value
* @param {*} expected - expected value
* @param {string} [msg] - message
*/
setReadOnly( Benchmark.prototype, 'notEqual', notEqual );
/**
* Asserts that `actual` is deeply equal to `expected`.
*
* @name deepEqual
* @memberof Benchmark.prototype
* @type {Function}
* @param {*} actual - actual value
* @param {*} expected - expected value
* @param {string} [msg] message
*/
setReadOnly( Benchmark.prototype, 'deepEqual', deepEqual );
/**
* Asserts that `actual` is not deeply equal to `expected`.
*
* @name notDeepEqual
* @memberof Benchmark.prototype
* @type {Function}
* @param {*} actual - actual value
* @param {*} expected - expected value
* @param {string} [msg] message
*/
setReadOnly( Benchmark.prototype, 'notDeepEqual', notDeepEqual );
/**
* Ends a benchmark.
*
* @name end
* @memberof Benchmark.prototype
* @type {Function}
*/
setReadOnly( Benchmark.prototype, 'end', end );
// EXPORTS //
module.exports = Benchmark;
},{"./assert.js":168,"./comment.js":170,"./deep_equal.js":171,"./end.js":172,"./ended.js":173,"./equal.js":174,"./exit.js":175,"./fail.js":176,"./not_deep_equal.js":178,"./not_equal.js":179,"./not_ok.js":180,"./ok.js":181,"./pass.js":182,"./run.js":183,"./skip.js":185,"./todo.js":186,"@stdlib/time/tic":283,"@stdlib/time/toc":287,"@stdlib/utils/define-nonenumerable-read-only-property":297,"@stdlib/utils/define-property":302,"@stdlib/utils/inherit":325,"events":378}],178:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
/**
* Asserts that `actual` is not deeply equal to `expected`.
*
* @private
* @param {*} actual - actual value
* @param {*} expected - expected value
* @param {string} [msg] message
*/
function notDeepEqual( actual, expected, msg ) {
/* eslint-disable no-invalid-this */
this.comment( 'actual: '+actual+'. expected: '+expected+'. msg: '+msg+'.' );
// TODO: implement
}
// EXPORTS //
module.exports = notDeepEqual;
},{}],179:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
/**
* Asserts that `actual` is not strictly equal to `expected`.
*
* @private
* @param {*} actual - actual value
* @param {*} expected - expected value
* @param {string} [msg] - message
*/
function notEqual( actual, expected, msg ) {
/* eslint-disable no-invalid-this */
this._assert( actual !== expected, {
'message': msg || 'should not be equal',
'operator': 'notEqual',
'expected': expected,
'actual': actual
});
}
// EXPORTS //
module.exports = notEqual;
},{}],180:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
/**
* Asserts that a `value` is falsy.
*
* @private
* @param {*} value - value
* @param {string} [msg] - message
*/
function notOk( value, msg ) {
/* eslint-disable no-invalid-this */
this._assert( !value, {
'message': msg || 'should be falsy',
'operator': 'notOk',
'expected': false,
'actual': value
});
}
// EXPORTS //
module.exports = notOk;
},{}],181:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
/**
* Asserts that a `value` is truthy.
*
* @private
* @param {*} value - value
* @param {string} [msg] - message
*/
function ok( value, msg ) {
/* eslint-disable no-invalid-this */
this._assert( !!value, {
'message': msg || 'should be truthy',
'operator': 'ok',
'expected': true,
'actual': value
});
}
// EXPORTS //
module.exports = ok;
},{}],182:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
/**
* Generates a passing assertion.
*
* @private
* @param {string} msg - message
*/
function pass( msg ) {
/* eslint-disable no-invalid-this */
this._assert( true, {
'message': msg,
'operator': 'pass'
});
}
// EXPORTS //
module.exports = pass;
},{}],183:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var timeout = require( './set_timeout.js' );
var clear = require( './clear_timeout.js' );
// MAIN //
/**
* Runs a benchmark.
*
* @private
* @returns {void}
*/
function run() {
/* eslint-disable no-invalid-this */
var self;
var id;
if ( this._skip ) {
this.comment( 'SKIP '+this.name );
return this.end();
}
if ( !this._benchmark ) {
this.comment( 'TODO '+this.name );
return this.end();
}
self = this;
this._running = true;
id = timeout( onTimeout, this.timeout );
this.once( 'end', endTimeout );
this.emit( 'prerun' );
this._benchmark( this );
this.emit( 'run' );
/**
* Callback invoked once a timeout ends.
*
* @private
*/
function onTimeout() {
self.fail( 'benchmark timed out after '+self.timeout+'ms' );
}
/**
* Clears a timeout.
*
* @private
*/
function endTimeout() {
clear( id );
}
}
// EXPORTS //
module.exports = run;
},{"./clear_timeout.js":169,"./set_timeout.js":184}],184:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// EXPORTS //
module.exports = setTimeout;
},{}],185:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
/**
* Generates an assertion which will be skipped.
*
* @private
* @param {*} value - value
* @param {string} msg - message
*/
function skip( value, msg ) {
/* eslint-disable no-invalid-this */
this._assert( true, {
'message': msg,
'operator': 'skip',
'skip': true
});
}
// EXPORTS //
module.exports = skip;
},{}],186:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
/**
* Generates an assertion which should be implemented.
*
* @private
* @param {*} value - value
* @param {string} msg - message
*/
function todo( value, msg ) {
/* eslint-disable no-invalid-this */
this._assert( !!value, {
'message': msg,
'operator': 'todo',
'todo': true
});
}
// EXPORTS //
module.exports = todo;
},{}],187:[function(require,module,exports){
module.exports={
"skip": false,
"iterations": null,
"repeats": 3,
"timeout": 300000
}
},{}],188:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isFunction = require( '@stdlib/assert/is-function' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isObject = require( '@stdlib/assert/is-plain-object' );
var isNodeWritableStreamLike = require( '@stdlib/assert/is-node-writable-stream-like' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var pick = require( '@stdlib/utils/pick' );
var omit = require( '@stdlib/utils/omit' );
var noop = require( '@stdlib/utils/noop' );
var createHarness = require( './harness' );
var logStream = require( './log' );
var canEmitExit = require( './utils/can_emit_exit.js' );
var proc = require( './utils/process.js' );
// MAIN //
/**
* Creates a benchmark harness which supports closing when a process exits.
*
* @private
* @param {Options} [options] - function options
* @param {boolean} [options.autoclose] - boolean indicating whether to automatically close a harness after a harness finishes running all benchmarks
* @param {Stream} [options.stream] - output writable stream
* @param {Callback} [clbk] - callback to invoke when a harness finishes running all benchmarks
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {TypeError} callback argument must be a function
* @returns {Function} benchmark harness
*
* @example
* var proc = require( 'process' );
* var bench = createExitHarness( onFinish );
*
* function onFinish() {
* bench.close();
* }
*
* bench( 'beep', function benchmark( b ) {
* var x;
* var i;
* b.tic();
* for ( i = 0; i < b.iterations; i++ ) {
* x = Math.sin( Math.random() );
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* }
* b.toc();
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* b.end();
* });
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
*
* var stream = createExitHarness().createStream();
* stream.pipe( stdout );
*/
function createExitHarness() {
var exitCode;
var pipeline;
var harness;
var options;
var stream;
var topts;
var opts;
var clbk;
if ( arguments.length === 0 ) {
options = {};
clbk = noop;
} else if ( arguments.length === 1 ) {
if ( isFunction( arguments[ 0 ] ) ) {
options = {};
clbk = arguments[ 0 ];
} else if ( isObject( arguments[ 0 ] ) ) {
options = arguments[ 0 ];
clbk = noop;
} else {
throw new TypeError( 'invalid argument. Must provide either an options object or a callback function. Value: `'+arguments[ 0 ]+'`.' );
}
} else {
options = arguments[ 0 ];
if ( !isObject( options ) ) {
throw new TypeError( 'invalid argument. First argument must be an object. Value: `'+options+'`.' );
}
clbk = arguments[ 1 ];
if ( !isFunction( clbk ) ) {
throw new TypeError( 'invalid argument. Second argument must be a function. Value: `'+clbk+'`.' );
}
}
opts = {};
if ( hasOwnProp( options, 'autoclose' ) ) {
opts.autoclose = options.autoclose;
if ( !isBoolean( opts.autoclose ) ) {
throw new TypeError( 'invalid option. `autoclose` option must be a boolean primitive. Option: `'+opts.autoclose+'`.' );
}
}
if ( hasOwnProp( options, 'stream' ) ) {
opts.stream = options.stream;
if ( !isNodeWritableStreamLike( opts.stream ) ) {
throw new TypeError( 'invalid option. `stream` option must be a writable stream. Option: `'+opts.stream+'`.' );
}
}
exitCode = 0;
// Create a new harness:
topts = pick( opts, [ 'autoclose' ] );
harness = createHarness( topts, done );
// Create a results stream:
topts = omit( options, [ 'autoclose', 'stream' ] );
stream = harness.createStream( topts );
// Pipe results to an output stream:
pipeline = stream.pipe( opts.stream || logStream() );
// If a process can emit an 'exit' event, capture errors in order to set the exit code...
if ( canEmitExit ) {
pipeline.on( 'error', onError );
proc.on( 'exit', onExit );
}
return harness;
/**
* Callback invoked when a harness finishes.
*
* @private
* @returns {void}
*/
function done() {
return clbk();
}
/**
* Callback invoked upon a stream `error` event.
*
* @private
* @param {Error} error - error object
*/
function onError() {
exitCode = 1;
}
/**
* Callback invoked upon an `exit` event.
*
* @private
* @param {integer} code - exit code
*/
function onExit( code ) {
if ( code !== 0 ) {
// Allow the process to exit...
return;
}
harness.close();
proc.exit( exitCode || harness.exitCode );
}
}
// EXPORTS //
module.exports = createExitHarness;
},{"./harness":190,"./log":196,"./utils/can_emit_exit.js":207,"./utils/process.js":210,"@stdlib/assert/has-own-property":46,"@stdlib/assert/is-boolean":72,"@stdlib/assert/is-function":93,"@stdlib/assert/is-node-writable-stream-like":115,"@stdlib/assert/is-plain-object":138,"@stdlib/utils/noop":353,"@stdlib/utils/omit":355,"@stdlib/utils/pick":357}],189:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var canEmitExit = require( './utils/can_emit_exit.js' );
var createExitHarness = require( './exit_harness.js' );
// VARIABLES //
var harness;
// MAIN //
/**
* Returns a benchmark harness. If a harness has already been created, returns the cached harness.
*
* @private
* @param {Options} [options] - harness options
* @param {Callback} [clbk] - callback to invoke when a harness finishes running all benchmarks
* @returns {Function} benchmark harness
*/
function getHarness( options, clbk ) {
var opts;
var cb;
if ( harness ) {
return harness;
}
if ( arguments.length > 1 ) {
opts = options;
cb = clbk;
} else {
opts = {};
cb = options;
}
opts.autoclose = !canEmitExit;
harness = createExitHarness( opts, cb );
// Update state:
getHarness.cached = true;
return harness;
}
// EXPORTS //
module.exports = getHarness;
},{"./exit_harness.js":188,"./utils/can_emit_exit.js":207}],190:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var setReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' );
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var isFunction = require( '@stdlib/assert/is-function' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isObject = require( '@stdlib/assert/is-plain-object' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var copy = require( '@stdlib/utils/copy' );
var Benchmark = require( './../benchmark-class' );
var Runner = require( './../runner' );
var nextTick = require( './../utils/next_tick.js' );
var DEFAULTS = require( './../defaults.json' );
var validate = require( './validate.js' );
var init = require( './init.js' );
// MAIN //
/**
* Creates a benchmark harness.
*
* @param {Options} [options] - function options
* @param {boolean} [options.autoclose] - boolean indicating whether to automatically close a harness after a harness finishes running all benchmarks
* @param {Callback} [clbk] - callback to invoke when a harness finishes running all benchmarks
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {TypeError} callback argument must be a function
* @returns {Function} benchmark harness
*
* @example
* var bench = createHarness( onFinish );
*
* function onFinish() {
* bench.close();
* console.log( 'Exit code: %d', bench.exitCode );
* }
*
* bench( 'beep', function benchmark( b ) {
* var x;
* var i;
* b.tic();
* for ( i = 0; i < b.iterations; i++ ) {
* x = Math.sin( Math.random() );
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* }
* b.toc();
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* b.end();
* });
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
*
* var stream = createHarness().createStream();
* stream.pipe( stdout );
*/
function createHarness( options, clbk ) {
var exitCode;
var runner;
var queue;
var opts;
var cb;
opts = {};
if ( arguments.length === 1 ) {
if ( isFunction( options ) ) {
cb = options;
} else if ( isObject( options ) ) {
opts = options;
} else {
throw new TypeError( 'invalid argument. Must provide either an options object or a callback function. Value: `'+options+'`.' );
}
} else if ( arguments.length > 1 ) {
if ( !isObject( options ) ) {
throw new TypeError( 'invalid argument. First argument must be an object. Value: `'+options+'`.' );
}
if ( hasOwnProp( options, 'autoclose' ) ) {
opts.autoclose = options.autoclose;
if ( !isBoolean( opts.autoclose ) ) {
throw new TypeError( 'invalid option. `autoclose` option must be a boolean primitive. Option: `'+opts.autoclose+'`.' );
}
}
cb = clbk;
if ( !isFunction( cb ) ) {
throw new TypeError( 'invalid argument. Second argument must be a function. Value: `'+cb+'`.' );
}
}
runner = new Runner();
if ( opts.autoclose ) {
runner.once( 'done', close );
}
if ( cb ) {
runner.once( 'done', cb );
}
exitCode = 0;
queue = [];
/**
* Benchmark harness.
*
* @private
* @param {string} name - benchmark name
* @param {Options} [options] - benchmark options
* @param {boolean} [options.skip=false] - boolean indicating whether to skip a benchmark
* @param {(PositiveInteger|null)} [options.iterations=null] - number of iterations
* @param {PositiveInteger} [options.repeats=3] - number of repeats
* @param {PositiveInteger} [options.timeout=300000] - number of milliseconds before a benchmark automatically fails
* @param {Function} [benchmark] - function containing benchmark code
* @throws {TypeError} first argument must be a string
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {TypeError} benchmark argument must a function
* @throws {Error} benchmark error
* @returns {Function} benchmark harness
*/
function harness( name, options, benchmark ) {
var opts;
var err;
var b;
if ( !isString( name ) ) {
throw new TypeError( 'invalid argument. First argument must be a string. Value: `'+name+'`.' );
}
opts = copy( DEFAULTS );
if ( arguments.length === 2 ) {
if ( isFunction( options ) ) {
b = options;
} else {
err = validate( opts, options );
if ( err ) {
throw err;
}
}
} else if ( arguments.length > 2 ) {
err = validate( opts, options );
if ( err ) {
throw err;
}
b = benchmark;
if ( !isFunction( b ) ) {
throw new TypeError( 'invalid argument. Third argument must be a function. Value: `'+b+'`.' );
}
}
// Add the benchmark to the initialization queue:
queue.push( [ name, opts, b ] );
// Perform initialization on the next turn of the event loop (note: this allows all benchmarks to be "registered" within the same turn of the loop; otherwise, we run the risk of registration-execution race conditions (i.e., a benchmark registers and executes before other benchmarks can register, depleting the benchmark queue and leading the harness to close)):
if ( queue.length === 1 ) {
nextTick( initialize );
}
return harness;
}
/**
* Initializes each benchmark.
*
* @private
* @returns {void}
*/
function initialize() {
var idx = -1;
return next();
/**
* Initialize the next benchmark.
*
* @private
* @returns {void}
*/
function next() {
var args;
idx += 1;
// If all benchmarks have been initialized, begin running the benchmarks:
if ( idx === queue.length ) {
queue.length = 0;
return runner.run();
}
// Initialize the next benchmark:
args = queue[ idx ];
init( args[ 0 ], args[ 1 ], args[ 2 ], onInit );
}
/**
* Callback invoked after performing initialization tasks.
*
* @private
* @param {string} name - benchmark name
* @param {Options} opts - benchmark options
* @param {(Function|undefined)} benchmark - function containing benchmark code
* @returns {void}
*/
function onInit( name, opts, benchmark ) {
var b;
var i;
// Create a `Benchmark` instance for each repeat to ensure each benchmark has its own state...
for ( i = 0; i < opts.repeats; i++ ) {
b = new Benchmark( name, opts, benchmark );
b.on( 'result', onResult );
runner.push( b );
}
return next();
}
}
/**
* Callback invoked upon a `result` event.
*
* @private
* @param {(string|Object)} result - result
*/
function onResult( result ) {
if (
!isString( result ) &&
!result.ok &&
!result.todo
) {
exitCode = 1;
}
}
/**
* Returns a results stream.
*
* @private
* @param {Object} [options] - options
* @returns {TransformStream} transform stream
*/
function createStream( options ) {
if ( arguments.length ) {
return runner.createStream( options );
}
return runner.createStream();
}
/**
* Closes a benchmark harness.
*
* @private
*/
function close() {
runner.close();
}
/**
* Forcefully exits a benchmark harness.
*
* @private
*/
function exit() {
runner.exit();
}
/**
* Returns the harness exit code.
*
* @private
* @returns {NonNegativeInteger} exit code
*/
function getExitCode() {
return exitCode;
}
setReadOnly( harness, 'createStream', createStream );
setReadOnly( harness, 'close', close );
setReadOnly( harness, 'exit', exit );
setReadOnlyAccessor( harness, 'exitCode', getExitCode );
return harness;
}
// EXPORTS //
module.exports = createHarness;
},{"./../benchmark-class":177,"./../defaults.json":187,"./../runner":204,"./../utils/next_tick.js":209,"./init.js":191,"./validate.js":194,"@stdlib/assert/has-own-property":46,"@stdlib/assert/is-boolean":72,"@stdlib/assert/is-function":93,"@stdlib/assert/is-plain-object":138,"@stdlib/assert/is-string":149,"@stdlib/utils/copy":293,"@stdlib/utils/define-nonenumerable-read-only-accessor":295,"@stdlib/utils/define-nonenumerable-read-only-property":297}],191:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var pretest = require( './pretest.js' );
var iterations = require( './iterations.js' );
// MAIN //
/**
* Performs benchmark initialization tasks.
*
* @private
* @param {string} name - benchmark name
* @param {Options} opts - benchmark options
* @param {(Function|undefined)} benchmark - function containing benchmark code
* @param {Callback} clbk - callback to invoke after completing initialization tasks
* @returns {void}
*/
function init( name, opts, benchmark, clbk ) {
// If no benchmark function, then the benchmark is considered a "todo", so no need to repeat multiple times...
if ( !benchmark ) {
opts.repeats = 1;
return clbk( name, opts, benchmark );
}
// If the `skip` option to `true`, no need to initialize or repeat multiple times as will not be running the benchmark:
if ( opts.skip ) {
opts.repeats = 1;
return clbk( name, opts, benchmark );
}
// Perform pretests:
pretest( name, opts, benchmark, onPreTest );
/**
* Callback invoked upon completing pretests.
*
* @private
* @param {Error} [error] - error object
* @returns {void}
*/
function onPreTest( error ) {
// If the pretests failed, don't run the benchmark multiple times...
if ( error ) {
opts.repeats = 1;
opts.iterations = 1;
return clbk( name, opts, benchmark );
}
// If a user specified an iteration number, we can begin running benchmarks...
if ( opts.iterations ) {
return clbk( name, opts, benchmark );
}
// Determine iteration number:
iterations( name, opts, benchmark, onIterations );
}
/**
* Callback invoked upon determining an iteration number.
*
* @private
* @param {(Error|null)} error - error object
* @param {PositiveInteger} iter - number of iterations
* @returns {void}
*/
function onIterations( error, iter ) {
// If provided an error, then a benchmark failed, and, similar to pretests, don't run the benchmark multiple times...
if ( error ) {
opts.repeats = 1;
opts.iterations = 1;
return clbk( name, opts, benchmark );
}
opts.iterations = iter;
return clbk( name, opts, benchmark );
}
}
// EXPORTS //
module.exports = init;
},{"./iterations.js":192,"./pretest.js":193}],192:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var copy = require( '@stdlib/utils/copy' );
var Benchmark = require( './../benchmark-class' );
// VARIABLES //
var MIN_TIME = 0.1; // seconds
var ITERATIONS = 10; // 10^1
var MAX_ITERATIONS = 10000000000; // 10^10
// MAIN //
/**
* Determines the number of iterations.
*
* @private
* @param {string} name - benchmark name
* @param {Options} options - benchmark options
* @param {(Function|undefined)} benchmark - function containing benchmark code
* @param {Callback} clbk - callback to invoke after determining number of iterations
* @returns {void}
*/
function iterations( name, options, benchmark, clbk ) {
var opts;
var time;
// Elapsed time (in seconds):
time = 0;
// Create a local copy:
opts = copy( options );
opts.iterations = ITERATIONS;
// Begin running benchmarks:
return next();
/**
* Run a new benchmark.
*
* @private
*/
function next() {
var b = new Benchmark( name, opts, benchmark );
b.on( 'result', onResult );
b.once( 'end', onEnd );
b.run();
}
/**
* Callback invoked upon a `result` event.
*
* @private
* @param {(string|Object)} result - result
*/
function onResult( result ) {
if ( !isString( result ) && result.operator === 'result' ) {
time = result.elapsed;
}
}
/**
* Callback invoked upon an `end` event.
*
* @private
* @returns {void}
*/
function onEnd() {
if (
time < MIN_TIME &&
opts.iterations < MAX_ITERATIONS
) {
opts.iterations *= 10;
return next();
}
clbk( null, opts.iterations );
}
}
// EXPORTS //
module.exports = iterations;
},{"./../benchmark-class":177,"@stdlib/assert/is-string":149,"@stdlib/utils/copy":293}],193:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var copy = require( '@stdlib/utils/copy' );
var Benchmark = require( './../benchmark-class' );
// MAIN //
/**
* Runs pretests to sanity check and/or catch failures.
*
* @private
* @param {string} name - benchmark name
* @param {Options} options - benchmark options
* @param {(Function|undefined)} benchmark - function containing benchmark code
* @param {Callback} clbk - callback to invoke after completing pretests
*/
function pretest( name, options, benchmark, clbk ) {
var fail;
var opts;
var tic;
var toc;
var b;
// Counters to determine the number of `tic` and `toc` events:
tic = 0;
toc = 0;
// Local copy:
opts = copy( options );
opts.iterations = 1;
// Pretest to check for minimum requirements and/or errors...
b = new Benchmark( name, opts, benchmark );
b.on( 'result', onResult );
b.on( 'tic', onTic );
b.on( 'toc', onToc );
b.once( 'end', onEnd );
b.run();
/**
* Callback invoked upon a `result` event.
*
* @private
* @param {(string|Object)} result - result
*/
function onResult( result ) {
if (
!isString( result ) &&
!result.ok &&
!result.todo
) {
fail = true;
}
}
/**
* Callback invoked upon a `tic` event.
*
* @private
*/
function onTic() {
tic += 1;
}
/**
* Callback invoked upon a `toc` event.
*
* @private
*/
function onToc() {
toc += 1;
}
/**
* Callback invoked upon an `end` event.
*
* @private
* @returns {void}
*/
function onEnd() {
var err;
if ( fail ) {
// Possibility that failure is intermittent, but we will assume that the usual case is that the failure would persist across all repeats and no sense failing multiple times when once suffices.
err = new Error( 'benchmark failed' );
} else if ( tic !== 1 || toc !== 1 ) {
// Unable to do anything definitive with timing information (e.g., a tic with no toc or vice versa, or benchmark function calls neither tic nor toc).
err = new Error( 'invalid benchmark' );
}
if ( err ) {
return clbk( err );
}
return clbk();
}
}
// EXPORTS //
module.exports = pretest;
},{"./../benchmark-class":177,"@stdlib/assert/is-string":149,"@stdlib/utils/copy":293}],194:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isObject = require( '@stdlib/assert/is-plain-object' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isNull = require( '@stdlib/assert/is-null' );
var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive;
// MAIN //
/**
* Validates function options.
*
* @private
* @param {Object} opts - destination object
* @param {Options} options - function options
* @param {boolean} [options.skip] - boolean indicating whether to skip a benchmark
* @param {(PositiveInteger|null)} [options.iterations] - number of iterations
* @param {PositiveInteger} [options.repeats] - number of repeats
* @param {PositiveInteger} [options.timeout] - number of milliseconds before a benchmark automatically fails
* @returns {(Error|null)} error object or null
*
* @example
* var opts = {};
* var options = {
* 'skip': false,
* 'iterations': 1e6,
* 'repeats': 3,
* 'timeout': 10000
* };
*
* var err = validate( opts, options );
* if ( err ) {
* throw err;
* }
*/
function validate( opts, options ) {
if ( !isObject( options ) ) {
return new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' );
}
if ( hasOwnProp( options, 'skip' ) ) {
opts.skip = options.skip;
if ( !isBoolean( opts.skip ) ) {
return new TypeError( 'invalid option. `skip` option must be a boolean primitive. Option: `' + opts.skip + '`.' );
}
}
if ( hasOwnProp( options, 'iterations' ) ) {
opts.iterations = options.iterations;
if (
!isPositiveInteger( opts.iterations ) &&
!isNull( opts.iterations )
) {
return new TypeError( 'invalid option. `iterations` option must be either a positive integer or `null`. Option: `' + opts.iterations + '`.' );
}
}
if ( hasOwnProp( options, 'repeats' ) ) {
opts.repeats = options.repeats;
if ( !isPositiveInteger( opts.repeats ) ) {
return new TypeError( 'invalid option. `repeats` option must be a positive integer. Option: `' + opts.repeats + '`.' );
}
}
if ( hasOwnProp( options, 'timeout' ) ) {
opts.timeout = options.timeout;
if ( !isPositiveInteger( opts.timeout ) ) {
return new TypeError( 'invalid option. `timeout` option must be a positive integer. Option: `' + opts.timeout + '`.' );
}
}
return null;
}
// EXPORTS //
module.exports = validate;
},{"@stdlib/assert/has-own-property":46,"@stdlib/assert/is-boolean":72,"@stdlib/assert/is-null":126,"@stdlib/assert/is-plain-object":138,"@stdlib/assert/is-positive-integer":140}],195:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Benchmark harness.
*
* @module @stdlib/bench/harness
*
* @example
* var bench = require( '@stdlib/bench/harness' );
*
* bench( 'beep', function benchmark( b ) {
* var x;
* var i;
* b.tic();
* for ( i = 0; i < b.iterations; i++ ) {
* x = Math.sin( Math.random() );
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* }
* b.toc();
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* b.end();
* });
*/
// MODULES //
var bench = require( './bench.js' );
// EXPORTS //
module.exports = bench;
},{"./bench.js":167}],196:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var TransformStream = require( '@stdlib/streams/node/transform' );
var fromCodePoint = require( '@stdlib/string/from-code-point' );
var log = require( './log.js' );
// MAIN //
/**
* Returns a Transform stream for logging to the console.
*
* @private
* @returns {TransformStream} transform stream
*/
function createStream() {
var stream;
var line;
stream = new TransformStream({
'transform': transform,
'flush': flush
});
line = '';
return stream;
/**
* Callback invoked upon receiving a new chunk.
*
* @private
* @param {(Buffer|string)} chunk - chunk
* @param {string} enc - Buffer encoding
* @param {Callback} clbk - callback to invoke after transforming the streamed chunk
*/
function transform( chunk, enc, clbk ) {
var c;
var i;
for ( i = 0; i < chunk.length; i++ ) {
c = fromCodePoint( chunk[ i ] );
if ( c === '\n' ) {
flush();
} else {
line += c;
}
}
clbk();
}
/**
* Callback to flush data to `stdout`.
*
* @private
* @param {Callback} [clbk] - callback to invoke after processing data
* @returns {void}
*/
function flush( clbk ) {
try {
log( line );
} catch ( err ) {
stream.emit( 'error', err );
}
line = '';
if ( clbk ) {
return clbk();
}
}
}
// EXPORTS //
module.exports = createStream;
},{"./log.js":197,"@stdlib/streams/node/transform":273,"@stdlib/string/from-code-point":277}],197:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
/**
* Writes a string to the console.
*
* @private
* @param {string} str - string to write
*/
function log( str ) {
console.log( str ); // eslint-disable-line no-console
}
// EXPORTS //
module.exports = log;
},{}],198:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
/**
* Removes any pending benchmarks.
*
* @private
*/
function clear() {
/* eslint-disable no-invalid-this */
this._benchmarks.length = 0;
}
// EXPORTS //
module.exports = clear;
},{}],199:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
/**
* Closes a benchmark runner.
*
* @private
* @returns {void}
*/
function closeRunner() {
/* eslint-disable no-invalid-this */
var self = this;
if ( this._closed ) {
return;
}
this._closed = true;
if ( this._benchmarks.length ) {
this.clear();
this._stream.write( '# WARNING: harness closed before completion.\n' );
} else {
this._stream.write( '#\n' );
this._stream.write( '1..'+this.total+'\n' );
this._stream.write( '# total '+this.total+'\n' );
this._stream.write( '# pass '+this.pass+'\n' );
if ( this.fail ) {
this._stream.write( '# fail '+this.fail+'\n' );
}
if ( this.skip ) {
this._stream.write( '# skip '+this.skip+'\n' );
}
if ( this.todo ) {
this._stream.write( '# todo '+this.todo+'\n' );
}
if ( !this.fail ) {
this._stream.write( '#\n# ok\n' );
}
}
this._stream.once( 'close', onClose );
this._stream.destroy();
/**
* Callback invoked upon a `close` event.
*
* @private
*/
function onClose() {
self.emit( 'close' );
}
}
// EXPORTS //
module.exports = closeRunner;
},{}],200:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
/* eslint-disable no-underscore-dangle */
'use strict';
// MODULES //
var TransformStream = require( '@stdlib/streams/node/transform' );
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var nextTick = require( './../utils/next_tick.js' );
// VARIABLES //
var TAP_HEADER = 'TAP version 13';
// MAIN //
/**
* Creates a results stream.
*
* @private
* @param {Options} [options] - stream options
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @returns {TransformStream} transform stream
*/
function createStream( options ) {
/* eslint-disable no-invalid-this */
var stream;
var opts;
var self;
var id;
self = this;
if ( arguments.length ) {
opts = options;
} else {
opts = {};
}
stream = new TransformStream( opts );
if ( opts.objectMode ) {
id = 0;
this.on( '_push', onPush );
this.on( 'done', onDone );
} else {
stream.write( TAP_HEADER+'\n' );
this._stream.pipe( stream );
}
this.on( '_run', onRun );
return stream;
/**
* Runs the next benchmark.
*
* @private
*/
function next() {
nextTick( onTick );
}
/**
* Callback invoked upon the next tick.
*
* @private
* @returns {void}
*/
function onTick() {
var b = self._benchmarks.shift();
if ( b ) {
b.run();
if ( !b.ended() ) {
return b.once( 'end', next );
}
return next();
}
self._running = false;
self.emit( 'done' );
}
/**
* Callback invoked upon a run event.
*
* @private
* @returns {void}
*/
function onRun() {
if ( !self._running ) {
self._running = true;
return next();
}
}
/**
* Callback invoked upon a push event.
*
* @private
* @param {Benchmark} b - benchmark
*/
function onPush( b ) {
var bid = id;
id += 1;
b.once( 'prerun', onPreRun );
b.on( 'result', onResult );
b.on( 'end', onEnd );
/**
* Callback invoked upon a `prerun` event.
*
* @private
*/
function onPreRun() {
var row = {
'type': 'benchmark',
'name': b.name,
'id': bid
};
stream.write( row );
}
/**
* Callback invoked upon a `result` event.
*
* @private
* @param {(Object|string)} res - result
*/
function onResult( res ) {
if ( isString( res ) ) {
res = {
'benchmark': bid,
'type': 'comment',
'name': res
};
} else if ( res.operator === 'result' ) {
res.benchmark = bid;
res.type = 'result';
} else {
res.benchmark = bid;
res.type = 'assert';
}
stream.write( res );
}
/**
* Callback invoked upon an `end` event.
*
* @private
*/
function onEnd() {
stream.write({
'benchmark': bid,
'type': 'end'
});
}
}
/**
* Callback invoked upon a `done` event.
*
* @private
*/
function onDone() {
stream.destroy();
}
}
// EXPORTS //
module.exports = createStream;
},{"./../utils/next_tick.js":209,"@stdlib/assert/is-string":149,"@stdlib/streams/node/transform":273}],201:[function(require,module,exports){
/* eslint-disable stdlib/jsdoc-require-throws-tags */
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var replace = require( '@stdlib/string/replace' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var reEOL = require( '@stdlib/regexp/eol' );
// VARIABLES //
var RE_WHITESPACE = /\s+/g;
// MAIN //
/**
* Encodes an assertion.
*
* @private
* @param {Object} result - result
* @param {PositiveInteger} count - result count
* @returns {string} encoded assertion
*/
function encodeAssertion( result, count ) {
var actualStack;
var errorStack;
var expected;
var actual;
var indent;
var stack;
var lines;
var out;
var i;
out = '';
if ( !result.ok ) {
out += 'not ';
}
// Add result count:
out += 'ok ' + count;
// Add description:
if ( result.name ) {
out += ' ' + replace( result.name.toString(), RE_WHITESPACE, ' ' );
}
// Append directives:
if ( result.skip ) {
out += ' # SKIP';
} else if ( result.todo ) {
out += ' # TODO';
}
out += '\n';
if ( result.ok ) {
return out;
}
// Format diagnostics as YAML...
indent = ' ';
out += indent + '---\n';
out += indent + 'operator: ' + result.operator + '\n';
if (
hasOwnProp( result, 'actual' ) ||
hasOwnProp( result, 'expected' )
) {
// TODO: inspect object logic (https://github.com/substack/tape/blob/master/lib/results.js#L145)
expected = result.expected;
actual = result.actual;
if ( actual !== actual && expected !== expected ) {
throw new Error( 'TODO: remove me' );
}
}
if ( result.at ) {
out += indent + 'at: ' + result.at + '\n';
}
if ( result.actual ) {
actualStack = result.actual.stack;
}
if ( result.error ) {
errorStack = result.error.stack;
}
if ( actualStack ) {
stack = actualStack;
} else {
stack = errorStack;
}
if ( stack ) {
lines = stack.toString().split( reEOL.REGEXP );
out += indent + 'stack: |-\n';
for ( i = 0; i < lines.length; i++ ) {
out += indent + ' ' + lines[ i ] + '\n';
}
}
out += indent + '...\n';
return out;
}
// EXPORTS //
module.exports = encodeAssertion;
},{"@stdlib/assert/has-own-property":46,"@stdlib/regexp/eol":257,"@stdlib/string/replace":279}],202:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// VARIABLES //
var YAML_INDENT = ' ';
var YAML_BEGIN = YAML_INDENT + '---\n';
var YAML_END = YAML_INDENT + '...\n';
// MAIN //
/**
* Encodes a result as a YAML block.
*
* @private
* @param {Object} result - result
* @returns {string} encoded result
*/
function encodeResult( result ) {
var out = YAML_BEGIN;
out += YAML_INDENT + 'iterations: '+result.iterations+'\n';
out += YAML_INDENT + 'elapsed: '+result.elapsed+'\n';
out += YAML_INDENT + 'rate: '+result.rate+'\n';
out += YAML_END;
return out;
}
// EXPORTS //
module.exports = encodeResult;
},{}],203:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
/**
* Forcefully exits a benchmark runner.
*
* @private
*/
function exit() {
/* eslint-disable no-invalid-this */
var self;
var i;
for ( i = 0; i < this._benchmarks.length; i++ ) {
this._benchmarks[ i ].exit();
}
self = this;
this.clear();
this._stream.once( 'close', onClose );
this._stream.destroy();
/**
* Callback invoked upon a `close` event.
*
* @private
*/
function onClose() {
self.emit( 'close' );
}
}
// EXPORTS //
module.exports = exit;
},{}],204:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var EventEmitter = require( 'events' ).EventEmitter;
var inherit = require( '@stdlib/utils/inherit' );
var defineProperty = require( '@stdlib/utils/define-property' );
var TransformStream = require( '@stdlib/streams/node/transform' );
var push = require( './push.js' );
var createStream = require( './create_stream.js' );
var run = require( './run.js' );
var clear = require( './clear.js' );
var close = require( './close.js' ); // eslint-disable-line stdlib/no-redeclare
var exit = require( './exit.js' );
// MAIN //
/**
* Benchmark runner.
*
* @private
* @constructor
* @returns {Runner} Runner instance
*
* @example
* var runner = new Runner();
*/
function Runner() {
if ( !( this instanceof Runner ) ) {
return new Runner();
}
EventEmitter.call( this );
// Private properties:
defineProperty( this, '_benchmarks', {
'value': [],
'configurable': false,
'writable': false,
'enumerable': false
});
defineProperty( this, '_stream', {
'value': new TransformStream(),
'configurable': false,
'writable': false,
'enumerable': false
});
defineProperty( this, '_closed', {
'value': false,
'configurable': false,
'writable': true,
'enumerable': false
});
defineProperty( this, '_running', {
'value': false,
'configurable': false,
'writable': true,
'enumerable': false
});
// Public properties:
defineProperty( this, 'total', {
'value': 0,
'configurable': false,
'writable': true,
'enumerable': true
});
defineProperty( this, 'fail', {
'value': 0,
'configurable': false,
'writable': true,
'enumerable': true
});
defineProperty( this, 'pass', {
'value': 0,
'configurable': false,
'writable': true,
'enumerable': true
});
defineProperty( this, 'skip', {
'value': 0,
'configurable': false,
'writable': true,
'enumerable': true
});
defineProperty( this, 'todo', {
'value': 0,
'configurable': false,
'writable': true,
'enumerable': true
});
return this;
}
/*
* Inherit from the `EventEmitter` prototype.
*/
inherit( Runner, EventEmitter );
/**
* Adds a new benchmark.
*
* @private
* @memberof Runner.prototype
* @function push
* @param {Benchmark} b - benchmark
*/
defineProperty( Runner.prototype, 'push', {
'value': push,
'configurable': false,
'writable': false,
'enumerable': false
});
/**
* Creates a results stream.
*
* @private
* @memberof Runner.prototype
* @function createStream
* @param {Options} [options] - stream options
* @returns {TransformStream} transform stream
*/
defineProperty( Runner.prototype, 'createStream', {
'value': createStream,
'configurable': false,
'writable': false,
'enumerable': false
});
/**
* Runs pending benchmarks.
*
* @private
* @memberof Runner.prototype
* @function run
*/
defineProperty( Runner.prototype, 'run', {
'value': run,
'configurable': false,
'writable': false,
'enumerable': false
});
/**
* Removes any pending benchmarks.
*
* @private
* @memberof Runner.prototype
* @function clear
*/
defineProperty( Runner.prototype, 'clear', {
'value': clear,
'configurable': false,
'writable': false,
'enumerable': false
});
/**
* Closes a benchmark runner.
*
* @private
* @memberof Runner.prototype
* @function close
*/
defineProperty( Runner.prototype, 'close', {
'value': close,
'configurable': false,
'writable': false,
'enumerable': false
});
/**
* Forcefully exits a benchmark runner.
*
* @private
* @memberof Runner.prototype
* @function exit
*/
defineProperty( Runner.prototype, 'exit', {
'value': exit,
'configurable': false,
'writable': false,
'enumerable': false
});
// EXPORTS //
module.exports = Runner;
},{"./clear.js":198,"./close.js":199,"./create_stream.js":200,"./exit.js":203,"./push.js":205,"./run.js":206,"@stdlib/streams/node/transform":273,"@stdlib/utils/define-property":302,"@stdlib/utils/inherit":325,"events":378}],205:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
/* eslint-disable no-underscore-dangle */
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var encodeAssertion = require( './encode_assertion.js' );
var encodeResult = require( './encode_result.js' );
// MAIN //
/**
* Adds a new benchmark.
*
* @private
* @param {Benchmark} b - benchmark
*/
function push( b ) {
/* eslint-disable no-invalid-this */
var self = this;
this._benchmarks.push( b );
b.once( 'prerun', onPreRun );
b.on( 'result', onResult );
this.emit( '_push', b );
/**
* Callback invoked upon a `prerun` event.
*
* @private
*/
function onPreRun() {
self._stream.write( '# '+b.name+'\n' );
}
/**
* Callback invoked upon a `result` event.
*
* @private
* @param {(Object|string)} res - result
* @returns {void}
*/
function onResult( res ) {
// Check for a comment...
if ( isString( res ) ) {
return self._stream.write( '# '+res+'\n' );
}
if ( res.operator === 'result' ) {
res = encodeResult( res );
return self._stream.write( res );
}
self.total += 1;
if ( res.ok ) {
if ( res.skip ) {
self.skip += 1;
} else if ( res.todo ) {
self.todo += 1;
}
self.pass += 1;
}
// According to the TAP spec, todos pass even if not "ok"...
else if ( res.todo ) {
self.pass += 1;
self.todo += 1;
}
// Everything else is a failure...
else {
self.fail += 1;
}
res = encodeAssertion( res, self.total );
self._stream.write( res );
}
}
// EXPORTS //
module.exports = push;
},{"./encode_assertion.js":201,"./encode_result.js":202,"@stdlib/assert/is-string":149}],206:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
/**
* Runs pending benchmarks.
*
* @private
*/
function run() {
/* eslint-disable no-invalid-this */
this.emit( '_run' );
}
// EXPORTS //
module.exports = run;
},{}],207:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var IS_BROWSER = require( '@stdlib/assert/is-browser' );
var canExit = require( './can_exit.js' );
// MAIN //
var bool = ( !IS_BROWSER && canExit );
// EXPORTS //
module.exports = bool;
},{"./can_exit.js":208,"@stdlib/assert/is-browser":78}],208:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var proc = require( './process.js' );
// MAIN //
var bool = ( proc && typeof proc.exit === 'function' );
// EXPORTS //
module.exports = bool;
},{"./process.js":210}],209:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
/**
* Runs a function on a subsequent turn of the event loop.
*
* ## Notes
*
* - `process.nextTick` is only Node.js.
* - `setImmediate` is non-standard.
* - Everything else is browser based (e.g., mutation observer, requestAnimationFrame, etc).
* - Only API which is universal is `setTimeout`.
* - Note that `0` is not actually `0ms`. Browser environments commonly have a minimum delay of `4ms`. This is acceptable. Here, the main intent of this function is to give the runtime a chance to run garbage collection, clear state, and tend to any other pending tasks before returning control to benchmark tasks. The larger aim (attainable or not) is to provide each benchmark run with as much of a fresh state as possible.
*
*
* @private
* @param {Function} fcn - function to run upon a subsequent turn of the event loop
*/
function nextTick( fcn ) {
setTimeout( fcn, 0 );
}
// EXPORTS //
module.exports = nextTick;
},{}],210:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var proc = require( 'process' );
// EXPORTS //
module.exports = proc;
},{"process":389}],211:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Benchmark harness.
*
* @module @stdlib/bench
*
* @example
* var bench = require( '@stdlib/bench' );
*
* bench( 'beep', function benchmark( b ) {
* var x;
* var i;
* b.tic();
* for ( i = 0; i < b.iterations; i++ ) {
* x = Math.sin( Math.random() );
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* }
* b.toc();
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* b.end();
* });
*/
// MODULES //
var bench = require( '@stdlib/bench/harness' );
// EXPORTS //
module.exports = bench;
},{"@stdlib/bench/harness":195}],212:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
var ctor = require( 'buffer' ).Buffer; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{"buffer":379}],213:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Buffer constructor.
*
* @module @stdlib/buffer/ctor
*
* @example
* var ctor = require( '@stdlib/buffer/ctor' );
*
* var b = new ctor( [ 1, 2, 3, 4 ] );
* // returns <Buffer>
*/
// MODULES //
var hasNodeBufferSupport = require( '@stdlib/assert/has-node-buffer-support' );
var main = require( './buffer.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasNodeBufferSupport() ) {
ctor = main;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./buffer.js":212,"./polyfill.js":214,"@stdlib/assert/has-node-buffer-support":44}],214:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// TODO: write (browser) polyfill
// MAIN //
/**
* Buffer constructor.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],215:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isFunction = require( '@stdlib/assert/is-function' );
var Buffer = require( '@stdlib/buffer/ctor' );
// MAIN //
var bool = isFunction( Buffer.from );
// EXPORTS //
module.exports = bool;
},{"@stdlib/assert/is-function":93,"@stdlib/buffer/ctor":213}],216:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Copy buffer data to a new `Buffer` instance.
*
* @module @stdlib/buffer/from-buffer
*
* @example
* var fromArray = require( '@stdlib/buffer/from-array' );
* var copyBuffer = require( '@stdlib/buffer/from-buffer' );
*
* var b1 = fromArray( [ 1, 2, 3, 4 ] );
* // returns <Buffer>
*
* var b2 = copyBuffer( b1 );
* // returns <Buffer>
*/
// MODULES //
var hasFrom = require( './has_from.js' );
var main = require( './main.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var copyBuffer;
if ( hasFrom ) {
copyBuffer = main;
} else {
copyBuffer = polyfill;
}
// EXPORTS //
module.exports = copyBuffer;
},{"./has_from.js":215,"./main.js":217,"./polyfill.js":218}],217:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isBuffer = require( '@stdlib/assert/is-buffer' );
var Buffer = require( '@stdlib/buffer/ctor' );
// MAIN //
/**
* Copies buffer data to a new `Buffer` instance.
*
* @param {Buffer} buffer - buffer from which to copy
* @throws {TypeError} must provide a `Buffer` instance
* @returns {Buffer} new `Buffer` instance
*
* @example
* var fromArray = require( '@stdlib/buffer/from-array' );
*
* var b1 = fromArray( [ 1, 2, 3, 4 ] );
* // returns <Buffer>
*
* var b2 = fromBuffer( b1 );
* // returns <Buffer>
*/
function fromBuffer( buffer ) {
if ( !isBuffer( buffer ) ) {
throw new TypeError( 'invalid argument. Must provide a Buffer. Value: `' + buffer + '`' );
}
return Buffer.from( buffer );
}
// EXPORTS //
module.exports = fromBuffer;
},{"@stdlib/assert/is-buffer":79,"@stdlib/buffer/ctor":213}],218:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isBuffer = require( '@stdlib/assert/is-buffer' );
var Buffer = require( '@stdlib/buffer/ctor' );
// MAIN //
/**
* Copies buffer data to a new `Buffer` instance.
*
* @param {Buffer} buffer - buffer from which to copy
* @throws {TypeError} must provide a `Buffer` instance
* @returns {Buffer} new `Buffer` instance
*
* @example
* var fromArray = require( '@stdlib/buffer/from-array' );
*
* var b1 = fromArray( [ 1, 2, 3, 4 ] );
* // returns <Buffer>
*
* var b2 = fromBuffer( b1 );
* // returns <Buffer>
*/
function fromBuffer( buffer ) {
if ( !isBuffer( buffer ) ) {
throw new TypeError( 'invalid argument. Must provide a Buffer. Value: `' + buffer + '`' );
}
return new Buffer( buffer ); // eslint-disable-line no-buffer-constructor
}
// EXPORTS //
module.exports = fromBuffer;
},{"@stdlib/assert/is-buffer":79,"@stdlib/buffer/ctor":213}],219:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Maximum length of a generic array.
*
* @module @stdlib/constants/array/max-array-length
*
* @example
* var MAX_ARRAY_LENGTH = require( '@stdlib/constants/array/max-array-length' );
* // returns 4294967295
*/
// MAIN //
/**
* Maximum length of a generic array.
*
* ```tex
* 2^{32} - 1
* ```
*
* @constant
* @type {uinteger32}
* @default 4294967295
*/
var MAX_ARRAY_LENGTH = 4294967295>>>0; // asm type annotation
// EXPORTS //
module.exports = MAX_ARRAY_LENGTH;
},{}],220:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Maximum length of a typed array.
*
* @module @stdlib/constants/array/max-typed-array-length
*
* @example
* var MAX_TYPED_ARRAY_LENGTH = require( '@stdlib/constants/array/max-typed-array-length' );
* // returns 9007199254740991
*/
// MAIN //
/**
* Maximum length of a typed array.
*
* ```tex
* 2^{53} - 1
* ```
*
* @constant
* @type {number}
* @default 9007199254740991
*/
var MAX_TYPED_ARRAY_LENGTH = 9007199254740991;
// EXPORTS //
module.exports = MAX_TYPED_ARRAY_LENGTH;
},{}],221:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* The bias of a double-precision floating-point number's exponent.
*
* @module @stdlib/constants/float64/exponent-bias
* @type {integer32}
*
* @example
* var FLOAT64_EXPONENT_BIAS = require( '@stdlib/constants/float64/exponent-bias' );
* // returns 1023
*/
// MAIN //
/**
* Bias of a double-precision floating-point number's exponent.
*
* ## Notes
*
* The bias can be computed via
*
* ```tex
* \mathrm{bias} = 2^{k-1} - 1
* ```
*
* where \\(k\\) is the number of bits in the exponent; here, \\(k = 11\\).
*
* @constant
* @type {integer32}
* @default 1023
* @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985}
*/
var FLOAT64_EXPONENT_BIAS = 1023|0; // asm type annotation
// EXPORTS //
module.exports = FLOAT64_EXPONENT_BIAS;
},{}],222:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* High word mask for the exponent of a double-precision floating-point number.
*
* @module @stdlib/constants/float64/high-word-exponent-mask
* @type {uinteger32}
*
* @example
* var FLOAT64_HIGH_WORD_EXPONENT_MASK = require( '@stdlib/constants/float64/high-word-exponent-mask' );
* // returns 2146435072
*/
// MAIN //
/**
* High word mask for the exponent of a double-precision floating-point number.
*
* ## Notes
*
* The high word mask for the exponent of a double-precision floating-point number is an unsigned 32-bit integer with the value \\( 2146435072 \\), which corresponds to the bit sequence
*
* ```binarystring
* 0 11111111111 00000000000000000000
* ```
*
* @constant
* @type {uinteger32}
* @default 0x7ff00000
* @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985}
*/
var FLOAT64_HIGH_WORD_EXPONENT_MASK = 0x7ff00000;
// EXPORTS //
module.exports = FLOAT64_HIGH_WORD_EXPONENT_MASK;
},{}],223:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* High word mask for the significand of a double-precision floating-point number.
*
* @module @stdlib/constants/float64/high-word-significand-mask
* @type {uinteger32}
*
* @example
* var FLOAT64_HIGH_WORD_SIGNIFICAND_MASK = require( '@stdlib/constants/float64/high-word-significand-mask' );
* // returns 1048575
*/
// MAIN //
/**
* High word mask for the significand of a double-precision floating-point number.
*
* ## Notes
*
* The high word mask for the significand of a double-precision floating-point number is an unsigned 32-bit integer with the value \\( 1048575 \\), which corresponds to the bit sequence
*
* ```binarystring
* 0 00000000000 11111111111111111111
* ```
*
* @constant
* @type {uinteger32}
* @default 0x000fffff
* @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985}
*/
var FLOAT64_HIGH_WORD_SIGNIFICAND_MASK = 0x000fffff;
// EXPORTS //
module.exports = FLOAT64_HIGH_WORD_SIGNIFICAND_MASK;
},{}],224:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Double-precision floating-point negative infinity.
*
* @module @stdlib/constants/float64/ninf
* @type {number}
*
* @example
* var FLOAT64_NINF = require( '@stdlib/constants/float64/ninf' );
* // returns -Infinity
*/
// MODULES //
var Number = require( '@stdlib/number/ctor' );
// MAIN //
/**
* Double-precision floating-point negative infinity.
*
* ## Notes
*
* Double-precision floating-point negative infinity has the bit sequence
*
* ```binarystring
* 1 11111111111 00000000000000000000 00000000000000000000000000000000
* ```
*
* @constant
* @type {number}
* @default Number.NEGATIVE_INFINITY
* @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985}
*/
var FLOAT64_NINF = Number.NEGATIVE_INFINITY;
// EXPORTS //
module.exports = FLOAT64_NINF;
},{"@stdlib/number/ctor":248}],225:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Double-precision floating-point positive infinity.
*
* @module @stdlib/constants/float64/pinf
* @type {number}
*
* @example
* var FLOAT64_PINF = require( '@stdlib/constants/float64/pinf' );
* // returns Infinity
*/
// MAIN //
/**
* Double-precision floating-point positive infinity.
*
* ## Notes
*
* Double-precision floating-point positive infinity has the bit sequence
*
* ```binarystring
* 0 11111111111 00000000000000000000 00000000000000000000000000000000
* ```
*
* @constant
* @type {number}
* @default Number.POSITIVE_INFINITY
* @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985}
*/
var FLOAT64_PINF = Number.POSITIVE_INFINITY; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = FLOAT64_PINF;
},{}],226:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Maximum signed 16-bit integer.
*
* @module @stdlib/constants/int16/max
* @type {integer32}
*
* @example
* var INT16_MAX = require( '@stdlib/constants/int16/max' );
* // returns 32767
*/
// MAIN //
/**
* Maximum signed 16-bit integer.
*
* ## Notes
*
* The number has the value
*
* ```tex
* 2^{15} - 1
* ```
*
* which corresponds to the bit sequence
*
* ```binarystring
* 0111111111111111
* ```
*
* @constant
* @type {integer32}
* @default 32767
*/
var INT16_MAX = 32767|0; // asm type annotation
// EXPORTS //
module.exports = INT16_MAX;
},{}],227:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Minimum signed 16-bit integer.
*
* @module @stdlib/constants/int16/min
* @type {integer32}
*
* @example
* var INT16_MIN = require( '@stdlib/constants/int16/min' );
* // returns -32768
*/
// MAIN //
/**
* Minimum signed 16-bit integer.
*
* ## Notes
*
* The number has the value
*
* ```tex
* -(2^{15})
* ```
*
* which corresponds to the two's complement bit sequence
*
* ```binarystring
* 1000000000000000
* ```
*
* @constant
* @type {integer32}
* @default -32768
*/
var INT16_MIN = -32768|0; // asm type annotation
// EXPORTS //
module.exports = INT16_MIN;
},{}],228:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Maximum signed 32-bit integer.
*
* @module @stdlib/constants/int32/max
* @type {integer32}
*
* @example
* var INT32_MAX = require( '@stdlib/constants/int32/max' );
* // returns 2147483647
*/
// MAIN //
/**
* Maximum signed 32-bit integer.
*
* ## Notes
*
* The number has the value
*
* ```tex
* 2^{31} - 1
* ```
*
* which corresponds to the bit sequence
*
* ```binarystring
* 01111111111111111111111111111111
* ```
*
* @constant
* @type {integer32}
* @default 2147483647
*/
var INT32_MAX = 2147483647|0; // asm type annotation
// EXPORTS //
module.exports = INT32_MAX;
},{}],229:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Minimum signed 32-bit integer.
*
* @module @stdlib/constants/int32/min
* @type {integer32}
*
* @example
* var INT32_MIN = require( '@stdlib/constants/int32/min' );
* // returns -2147483648
*/
// MAIN //
/**
* Minimum signed 32-bit integer.
*
* ## Notes
*
* The number has the value
*
* ```tex
* -(2^{31})
* ```
*
* which corresponds to the two's complement bit sequence
*
* ```binarystring
* 10000000000000000000000000000000
* ```
*
* @constant
* @type {integer32}
* @default -2147483648
*/
var INT32_MIN = -2147483648|0; // asm type annotation
// EXPORTS //
module.exports = INT32_MIN;
},{}],230:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Maximum signed 8-bit integer.
*
* @module @stdlib/constants/int8/max
* @type {integer32}
*
* @example
* var INT8_MAX = require( '@stdlib/constants/int8/max' );
* // returns 127
*/
// MAIN //
/**
* Maximum signed 8-bit integer.
*
* ## Notes
*
* The number is given by
*
* ```tex
* 2^{7} - 1
* ```
*
* which corresponds to the bit sequence
*
* ```binarystring
* 01111111
* ```
*
* @constant
* @type {integer32}
* @default 127
*/
var INT8_MAX = 127|0; // asm type annotation
// EXPORTS //
module.exports = INT8_MAX;
},{}],231:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Minimum signed 8-bit integer.
*
* @module @stdlib/constants/int8/min
* @type {integer32}
*
* @example
* var INT8_MIN = require( '@stdlib/constants/int8/min' );
* // returns -128
*/
// MAIN //
/**
* Minimum signed 8-bit integer.
*
* ## Notes
*
* The number is given by
*
* ```tex
* -(2^{7})
* ```
*
* which corresponds to the two's complement bit sequence
*
* ```binarystring
* 10000000
* ```
*
* @constant
* @type {integer32}
* @default -128
*/
var INT8_MIN = -128|0; // asm type annotation
// EXPORTS //
module.exports = INT8_MIN;
},{}],232:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Maximum unsigned 16-bit integer.
*
* @module @stdlib/constants/uint16/max
* @type {integer32}
*
* @example
* var UINT16_MAX = require( '@stdlib/constants/uint16/max' );
* // returns 65535
*/
// MAIN //
/**
* Maximum unsigned 16-bit integer.
*
* ## Notes
*
* The number has the value
*
* ```tex
* 2^{16} - 1
* ```
*
* which corresponds to the bit sequence
*
* ```binarystring
* 1111111111111111
* ```
*
* @constant
* @type {integer32}
* @default 65535
*/
var UINT16_MAX = 65535|0; // asm type annotation
// EXPORTS //
module.exports = UINT16_MAX;
},{}],233:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Maximum unsigned 32-bit integer.
*
* @module @stdlib/constants/uint32/max
* @type {uinteger32}
*
* @example
* var UINT32_MAX = require( '@stdlib/constants/uint32/max' );
* // returns 4294967295
*/
// MAIN //
/**
* Maximum unsigned 32-bit integer.
*
* ## Notes
*
* The number has the value
*
* ```tex
* 2^{32} - 1
* ```
*
* which corresponds to the bit sequence
*
* ```binarystring
* 11111111111111111111111111111111
* ```
*
* @constant
* @type {uinteger32}
* @default 4294967295
*/
var UINT32_MAX = 4294967295;
// EXPORTS //
module.exports = UINT32_MAX;
},{}],234:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Maximum unsigned 8-bit integer.
*
* @module @stdlib/constants/uint8/max
* @type {integer32}
*
* @example
* var UINT8_MAX = require( '@stdlib/constants/uint8/max' );
* // returns 255
*/
// MAIN //
/**
* Maximum unsigned 8-bit integer.
*
* ## Notes
*
* The number has the value
*
* ```tex
* 2^{8} - 1
* ```
*
* which corresponds to the bit sequence
*
* ```binarystring
* 11111111
* ```
*
* @constant
* @type {integer32}
* @default 255
*/
var UINT8_MAX = 255|0; // asm type annotation
// EXPORTS //
module.exports = UINT8_MAX;
},{}],235:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Maximum Unicode code point in the Basic Multilingual Plane (BMP).
*
* @module @stdlib/constants/unicode/max-bmp
* @type {integer32}
*
* @example
* var UNICODE_MAX_BMP = require( '@stdlib/constants/unicode/max-bmp' );
* // returns 65535
*/
// MAIN //
/**
* Maximum Unicode code point in the Basic Multilingual Plane (BMP).
*
* @constant
* @type {integer32}
* @default 65535
* @see [Unicode]{@link https://en.wikipedia.org/wiki/Unicode}
*/
var UNICODE_MAX_BMP = 0xFFFF|0; // asm type annotation
// EXPORTS //
module.exports = UNICODE_MAX_BMP;
},{}],236:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Maximum Unicode code point.
*
* @module @stdlib/constants/unicode/max
* @type {integer32}
*
* @example
* var UNICODE_MAX = require( '@stdlib/constants/unicode/max' );
* // returns 1114111
*/
// MAIN //
/**
* Maximum Unicode code point.
*
* @constant
* @type {integer32}
* @default 1114111
* @see [Unicode]{@link https://en.wikipedia.org/wiki/Unicode}
*/
var UNICODE_MAX = 0x10FFFF|0; // asm type annotation
// EXPORTS //
module.exports = UNICODE_MAX;
},{}],237:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test if a finite double-precision floating-point number is an integer.
*
* @module @stdlib/math/base/assert/is-integer
*
* @example
* var isInteger = require( '@stdlib/math/base/assert/is-integer' );
*
* var bool = isInteger( 1.0 );
* // returns true
*
* bool = isInteger( 3.14 );
* // returns false
*/
// MODULES //
var isInteger = require( './is_integer.js' );
// EXPORTS //
module.exports = isInteger;
},{"./is_integer.js":238}],238:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var floor = require( '@stdlib/math/base/special/floor' );
// MAIN //
/**
* Tests if a finite double-precision floating-point number is an integer.
*
* @param {number} x - value to test
* @returns {boolean} boolean indicating whether the value is an integer
*
* @example
* var bool = isInteger( 1.0 );
* // returns true
*
* @example
* var bool = isInteger( 3.14 );
* // returns false
*/
function isInteger( x ) {
return (floor(x) === x);
}
// EXPORTS //
module.exports = isInteger;
},{"@stdlib/math/base/special/floor":241}],239:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test if a double-precision floating-point numeric value is `NaN`.
*
* @module @stdlib/math/base/assert/is-nan
*
* @example
* var isnan = require( '@stdlib/math/base/assert/is-nan' );
*
* var bool = isnan( NaN );
* // returns true
*
* bool = isnan( 7.0 );
* // returns false
*/
// MODULES //
var isnan = require( './main.js' );
// EXPORTS //
module.exports = isnan;
},{"./main.js":240}],240:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
/**
* Tests if a double-precision floating-point numeric value is `NaN`.
*
* @param {number} x - value to test
* @returns {boolean} boolean indicating whether the value is `NaN`
*
* @example
* var bool = isnan( NaN );
* // returns true
*
* @example
* var bool = isnan( 7.0 );
* // returns false
*/
function isnan( x ) {
return ( x !== x );
}
// EXPORTS //
module.exports = isnan;
},{}],241:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Round a double-precision floating-point number toward negative infinity.
*
* @module @stdlib/math/base/special/floor
*
* @example
* var floor = require( '@stdlib/math/base/special/floor' );
*
* var v = floor( -4.2 );
* // returns -5.0
*
* v = floor( 9.99999 );
* // returns 9.0
*
* v = floor( 0.0 );
* // returns 0.0
*
* v = floor( NaN );
* // returns NaN
*/
// MODULES //
var floor = require( './main.js' );
// EXPORTS //
module.exports = floor;
},{"./main.js":242}],242:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// TODO: implementation (?)
/**
* Rounds a double-precision floating-point number toward negative infinity.
*
* @param {number} x - input value
* @returns {number} rounded value
*
* @example
* var v = floor( -4.2 );
* // returns -5.0
*
* @example
* var v = floor( 9.99999 );
* // returns 9.0
*
* @example
* var v = floor( 0.0 );
* // returns 0.0
*
* @example
* var v = floor( NaN );
* // returns NaN
*/
var floor = Math.floor; // eslint-disable-line stdlib/no-builtin-math
// EXPORTS //
module.exports = floor;
},{}],243:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Decompose a double-precision floating-point number into integral and fractional parts.
*
* @module @stdlib/math/base/special/modf
*
* @example
* var modf = require( '@stdlib/math/base/special/modf' );
*
* var parts = modf( 3.14 );
* // returns [ 3.0, 0.14000000000000012 ]
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
* var modf = require( '@stdlib/math/base/special/modf' );
*
* var out = new Float64Array( 2 );
*
* var parts = modf( out, 3.14 );
* // returns [ 3.0, 0.14000000000000012 ]
*
* var bool = ( parts === out );
* // returns true
*/
// MODULES //
var modf = require( './main.js' );
// EXPORTS //
module.exports = modf;
},{"./main.js":244}],244:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var fcn = require( './modf.js' );
// MAIN //
/**
* Decomposes a double-precision floating-point number into integral and fractional parts, each having the same type and sign as the input value.
*
* @param {(Array|TypedArray|Object)} [out] - output array
* @param {number} x - input value
* @returns {(Array|TypedArray|Object)} output array
*
* @example
* var parts = modf( 3.14 );
* // returns [ 3.0, 0.14000000000000012 ]
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
*
* var out = new Float64Array( 2 );
*
* var parts = modf( out, 3.14 );
* // returns <Float64Array>[ 3.0, 0.14000000000000012 ]
*
* var bool = ( parts === out );
* // returns true
*/
function modf( out, x ) {
if ( arguments.length === 1 ) {
return fcn( [ 0.0, 0.0 ], out );
}
return fcn( out, x );
}
// EXPORTS //
module.exports = modf;
},{"./modf.js":245}],245:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var toWords = require( '@stdlib/number/float64/base/to-words' );
var fromWords = require( '@stdlib/number/float64/base/from-words' );
var PINF = require( '@stdlib/constants/float64/pinf' );
var FLOAT64_EXPONENT_BIAS = require( '@stdlib/constants/float64/exponent-bias' );
var FLOAT64_HIGH_WORD_EXPONENT_MASK = require( '@stdlib/constants/float64/high-word-exponent-mask' ); // eslint-disable-line id-length
var FLOAT64_HIGH_WORD_SIGNIFICAND_MASK = require( '@stdlib/constants/float64/high-word-significand-mask' ); // eslint-disable-line id-length
// VARIABLES //
// 4294967295 => 0xffffffff => 11111111111111111111111111111111
var ALL_ONES = 4294967295>>>0; // asm type annotation
// High/low words workspace:
var WORDS = [ 0|0, 0|0 ]; // WARNING: not thread safe
// MAIN //
/**
* Decomposes a double-precision floating-point number into integral and fractional parts, each having the same type and sign as the input value.
*
* @private
* @param {(Array|TypedArray|Object)} out - output array
* @param {number} x - input value
* @returns {(Array|TypedArray|Object)} output array
*
* @example
* var parts = modf( [ 0.0, 0.0 ], 3.14 );
* // returns [ 3.0, 0.14000000000000012 ]
*/
function modf( out, x ) {
var high;
var low;
var exp;
var i;
// Special cases...
if ( x < 1.0 ) {
if ( x < 0.0 ) {
modf( out, -x );
out[ 0 ] *= -1.0;
out[ 1 ] *= -1.0;
return out;
}
if ( x === 0.0 ) { // [ +-0, +-0 ]
out[ 0 ] = x;
out[ 1 ] = x;
return out;
}
out[ 0 ] = 0.0;
out[ 1 ] = x;
return out;
}
if ( isnan( x ) ) {
out[ 0 ] = NaN;
out[ 1 ] = NaN;
return out;
}
if ( x === PINF ) {
out[ 0 ] = PINF;
out[ 1 ] = 0.0;
return out;
}
// Decompose |x|...
// Extract the high and low words:
toWords( WORDS, x );
high = WORDS[ 0 ];
low = WORDS[ 1 ];
// Extract the unbiased exponent from the high word:
exp = ((high & FLOAT64_HIGH_WORD_EXPONENT_MASK) >> 20)|0; // asm type annotation
exp -= FLOAT64_EXPONENT_BIAS|0; // asm type annotation
// Handle smaller values (x < 2**20 = 1048576)...
if ( exp < 20 ) {
i = (FLOAT64_HIGH_WORD_SIGNIFICAND_MASK >> exp)|0; // asm type annotation
// Determine if `x` is integral by checking for significand bits which cannot be exponentiated away...
if ( ((high&i)|low) === 0 ) {
out[ 0 ] = x;
out[ 1 ] = 0.0;
return out;
}
// Turn off all the bits which cannot be exponentiated away:
high &= (~i);
// Generate the integral part:
i = fromWords( high, 0 );
// The fractional part is whatever is leftover:
out[ 0 ] = i;
out[ 1 ] = x - i;
return out;
}
// Check if `x` can even have a fractional part...
if ( exp > 51 ) {
// `x` is integral:
out[ 0 ] = x;
out[ 1 ] = 0.0;
return out;
}
i = ALL_ONES >>> (exp-20);
// Determine if `x` is integral by checking for less significant significand bits which cannot be exponentiated away...
if ( (low&i) === 0 ) {
out[ 0 ] = x;
out[ 1 ] = 0.0;
return out;
}
// Turn off all the bits which cannot be exponentiated away:
low &= (~i);
// Generate the integral part:
i = fromWords( high, low );
// The fractional part is whatever is leftover:
out[ 0 ] = i;
out[ 1 ] = x - i;
return out;
}
// EXPORTS //
module.exports = modf;
},{"@stdlib/constants/float64/exponent-bias":221,"@stdlib/constants/float64/high-word-exponent-mask":222,"@stdlib/constants/float64/high-word-significand-mask":223,"@stdlib/constants/float64/pinf":225,"@stdlib/math/base/assert/is-nan":239,"@stdlib/number/float64/base/from-words":250,"@stdlib/number/float64/base/to-words":253}],246:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// TODO: implementation
/**
* Round a numeric value to the nearest integer.
*
* @module @stdlib/math/base/special/round
*
* @example
* var round = require( '@stdlib/math/base/special/round' );
*
* var v = round( -4.2 );
* // returns -4.0
*
* v = round( -4.5 );
* // returns -4.0
*
* v = round( -4.6 );
* // returns -5.0
*
* v = round( 9.99999 );
* // returns 10.0
*
* v = round( 9.5 );
* // returns 10.0
*
* v = round( 9.2 );
* // returns 9.0
*
* v = round( 0.0 );
* // returns 0.0
*
* v = round( -0.0 );
* // returns -0.0
*
* v = round( Infinity );
* // returns Infinity
*
* v = round( -Infinity );
* // returns -Infinity
*
* v = round( NaN );
* // returns NaN
*/
// MODULES //
var round = require( './round.js' );
// EXPORTS //
module.exports = round;
},{"./round.js":247}],247:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// TODO: implementation
/**
* Rounds a numeric value to the nearest integer.
*
* @param {number} x - input value
* @returns {number} function value
*
* @example
* var v = round( -4.2 );
* // returns -4.0
*
* @example
* var v = round( -4.5 );
* // returns -4.0
*
* @example
* var v = round( -4.6 );
* // returns -5.0
*
* @example
* var v = round( 9.99999 );
* // returns 10.0
*
* @example
* var v = round( 9.5 );
* // returns 10.0
*
* @example
* var v = round( 9.2 );
* // returns 9.0
*
* @example
* var v = round( 0.0 );
* // returns 0.0
*
* @example
* var v = round( -0.0 );
* // returns -0.0
*
* @example
* var v = round( Infinity );
* // returns Infinity
*
* @example
* var v = round( -Infinity );
* // returns -Infinity
*
* @example
* var v = round( NaN );
* // returns NaN
*/
var round = Math.round; // eslint-disable-line stdlib/no-builtin-math
// EXPORTS //
module.exports = round;
},{}],248:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Constructor which returns a `Number` object.
*
* @module @stdlib/number/ctor
*
* @example
* var Number = require( '@stdlib/number/ctor' );
*
* var v = new Number( 10.0 );
* // returns <Number>
*/
// MODULES //
var Number = require( './number.js' );
// EXPORTS //
module.exports = Number;
},{"./number.js":249}],249:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// EXPORTS //
module.exports = Number; // eslint-disable-line stdlib/require-globals
},{}],250:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Create a double-precision floating-point number from a higher order word (unsigned 32-bit integer) and a lower order word (unsigned 32-bit integer).
*
* @module @stdlib/number/float64/base/from-words
*
* @example
* var fromWords = require( '@stdlib/number/float64/base/from-words' );
*
* var v = fromWords( 1774486211, 2479577218 );
* // returns 3.14e201
*
* v = fromWords( 3221823995, 1413754136 );
* // returns -3.141592653589793
*
* v = fromWords( 0, 0 );
* // returns 0.0
*
* v = fromWords( 2147483648, 0 );
* // returns -0.0
*
* v = fromWords( 2146959360, 0 );
* // returns NaN
*
* v = fromWords( 2146435072, 0 );
* // returns Infinity
*
* v = fromWords( 4293918720, 0 );
* // returns -Infinity
*/
// MODULES //
var fromWords = require( './main.js' );
// EXPORTS //
module.exports = fromWords;
},{"./main.js":252}],251:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isLittleEndian = require( '@stdlib/assert/is-little-endian' );
// MAIN //
var indices;
var HIGH;
var LOW;
if ( isLittleEndian === true ) {
HIGH = 1; // second index
LOW = 0; // first index
} else {
HIGH = 0; // first index
LOW = 1; // second index
}
indices = {
'HIGH': HIGH,
'LOW': LOW
};
// EXPORTS //
module.exports = indices;
},{"@stdlib/assert/is-little-endian":107}],252:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var Uint32Array = require( '@stdlib/array/uint32' );
var Float64Array = require( '@stdlib/array/float64' );
var indices = require( './indices.js' );
// VARIABLES //
var FLOAT64_VIEW = new Float64Array( 1 );
var UINT32_VIEW = new Uint32Array( FLOAT64_VIEW.buffer );
var HIGH = indices.HIGH;
var LOW = indices.LOW;
// MAIN //
/**
* Creates a double-precision floating-point number from a higher order word (unsigned 32-bit integer) and a lower order word (unsigned 32-bit integer).
*
* ## Notes
*
* ```text
* float64 (64 bits)
* f := fraction (significand/mantissa) (52 bits)
* e := exponent (11 bits)
* s := sign bit (1 bit)
*
* |-------- -------- -------- -------- -------- -------- -------- --------|
* | Float64 |
* |-------- -------- -------- -------- -------- -------- -------- --------|
* | Uint32 | Uint32 |
* |-------- -------- -------- -------- -------- -------- -------- --------|
* ```
*
* If little endian (more significant bits last):
*
* ```text
* <-- lower higher -->
* | f7 f6 f5 f4 f3 f2 e2 | f1 |s| e1 |
* ```
*
* If big endian (more significant bits first):
*
* ```text
* <-- higher lower -->
* |s| e1 e2 | f1 f2 f3 f4 f5 f6 f7 |
* ```
*
*
* In which Uint32 should we place the higher order bits? If little endian, the second; if big endian, the first.
*
*
* ## References
*
* - [Open Group][1]
*
* [1]: http://pubs.opengroup.org/onlinepubs/9629399/chap14.htm
*
* @param {uinteger32} high - higher order word (unsigned 32-bit integer)
* @param {uinteger32} low - lower order word (unsigned 32-bit integer)
* @returns {number} floating-point number
*
* @example
* var v = fromWords( 1774486211, 2479577218 );
* // returns 3.14e201
*
* @example
* var v = fromWords( 3221823995, 1413754136 );
* // returns -3.141592653589793
*
* @example
* var v = fromWords( 0, 0 );
* // returns 0.0
*
* @example
* var v = fromWords( 2147483648, 0 );
* // returns -0.0
*
* @example
* var v = fromWords( 2146959360, 0 );
* // returns NaN
*
* @example
* var v = fromWords( 2146435072, 0 );
* // returns Infinity
*
* @example
* var v = fromWords( 4293918720, 0 );
* // returns -Infinity
*/
function fromWords( high, low ) {
UINT32_VIEW[ HIGH ] = high;
UINT32_VIEW[ LOW ] = low;
return FLOAT64_VIEW[ 0 ];
}
// EXPORTS //
module.exports = fromWords;
},{"./indices.js":251,"@stdlib/array/float64":5,"@stdlib/array/uint32":19}],253:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Split a double-precision floating-point number into a higher order word (unsigned 32-bit integer) and a lower order word (unsigned 32-bit integer).
*
* @module @stdlib/number/float64/base/to-words
*
* @example
* var toWords = require( '@stdlib/number/float64/base/to-words' );
*
* var w = toWords( 3.14e201 );
* // returns [ 1774486211, 2479577218 ]
*
* @example
* var Uint32Array = require( '@stdlib/array/uint32' );
* var toWords = require( '@stdlib/number/float64/base/to-words' );
*
* var out = new Uint32Array( 2 );
*
* var w = toWords( out, 3.14e201 );
* // returns <Uint32Array>[ 1774486211, 2479577218 ]
*
* var bool = ( w === out );
* // returns true
*/
// MODULES //
var toWords = require( './main.js' );
// EXPORTS //
module.exports = toWords;
},{"./main.js":255}],254:[function(require,module,exports){
arguments[4][251][0].apply(exports,arguments)
},{"@stdlib/assert/is-little-endian":107,"dup":251}],255:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var fcn = require( './to_words.js' );
// MAIN //
/**
* Splits a double-precision floating-point number into a higher order word (unsigned 32-bit integer) and a lower order word (unsigned 32-bit integer).
*
* @param {(Array|TypedArray|Object)} [out] - output array
* @param {number} x - input value
* @returns {(Array|TypedArray|Object)} output array
*
* @example
* var w = toWords( 3.14e201 );
* // returns [ 1774486211, 2479577218 ]
*
* @example
* var Uint32Array = require( '@stdlib/array/uint32' );
*
* var out = new Uint32Array( 2 );
*
* var w = toWords( out, 3.14e201 );
* // returns <Uint32Array>[ 1774486211, 2479577218 ]
*
* var bool = ( w === out );
* // returns true
*/
function toWords( out, x ) {
if ( arguments.length === 1 ) {
return fcn( [ 0, 0 ], out );
}
return fcn( out, x );
}
// EXPORTS //
module.exports = toWords;
},{"./to_words.js":256}],256:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var Uint32Array = require( '@stdlib/array/uint32' );
var Float64Array = require( '@stdlib/array/float64' );
var indices = require( './indices.js' );
// VARIABLES //
var FLOAT64_VIEW = new Float64Array( 1 );
var UINT32_VIEW = new Uint32Array( FLOAT64_VIEW.buffer );
var HIGH = indices.HIGH;
var LOW = indices.LOW;
// MAIN //
/**
* Splits a double-precision floating-point number into a higher order word (unsigned 32-bit integer) and a lower order word (unsigned 32-bit integer).
*
* ## Notes
*
* ```text
* float64 (64 bits)
* f := fraction (significand/mantissa) (52 bits)
* e := exponent (11 bits)
* s := sign bit (1 bit)
*
* |-------- -------- -------- -------- -------- -------- -------- --------|
* | Float64 |
* |-------- -------- -------- -------- -------- -------- -------- --------|
* | Uint32 | Uint32 |
* |-------- -------- -------- -------- -------- -------- -------- --------|
* ```
*
* If little endian (more significant bits last):
*
* ```text
* <-- lower higher -->
* | f7 f6 f5 f4 f3 f2 e2 | f1 |s| e1 |
* ```
*
* If big endian (more significant bits first):
*
* ```text
* <-- higher lower -->
* |s| e1 e2 | f1 f2 f3 f4 f5 f6 f7 |
* ```
*
* In which Uint32 can we find the higher order bits? If little endian, the second; if big endian, the first.
*
*
* ## References
*
* - [Open Group][1]
*
* [1]: http://pubs.opengroup.org/onlinepubs/9629399/chap14.htm
*
*
* @private
* @param {(Array|TypedArray|Object)} out - output array
* @param {number} x - input value
* @returns {(Array|TypedArray|Object)} output array
*
* @example
* var Uint32Array = require( '@stdlib/array/uint32' );
*
* var out = new Uint32Array( 2 );
*
* var w = toWords( out, 3.14e201 );
* // returns <Uint32Array>[ 1774486211, 2479577218 ]
*
* var bool = ( w === out );
* // returns true
*/
function toWords( out, x ) {
FLOAT64_VIEW[ 0 ] = x;
out[ 0 ] = UINT32_VIEW[ HIGH ];
out[ 1 ] = UINT32_VIEW[ LOW ];
return out;
}
// EXPORTS //
module.exports = toWords;
},{"./indices.js":254,"@stdlib/array/float64":5,"@stdlib/array/uint32":19}],257:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Regular expression to match a newline character sequence.
*
* @module @stdlib/regexp/eol
*
* @example
* var reEOL = require( '@stdlib/regexp/eol' );
* var RE_EOL = reEOL();
*
* var bool = RE_EOL.test( '\n' );
* // returns true
*
* bool = RE_EOL.test( '\\r\\n' );
* // returns false
*
* @example
* var reEOL = require( '@stdlib/regexp/eol' );
* var replace = require( '@stdlib/string/replace' );
*
* var RE_EOL = reEOL({
* 'flags': 'g'
* });
* var str = '1\n2\n3';
* var out = replace( str, RE_EOL, '' );
*
* @example
* var reEOL = require( '@stdlib/regexp/eol' );
* var bool = reEOL.REGEXP.test( '\r\n' );
* // returns true
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var reEOL = require( './main.js' );
var REGEXP_CAPTURE = require( './regexp_capture.js' );
var REGEXP = require( './regexp.js' );
// MAIN //
setReadOnly( reEOL, 'REGEXP', REGEXP );
setReadOnly( reEOL, 'REGEXP_CAPTURE', REGEXP_CAPTURE );
// EXPORTS //
module.exports = reEOL;
},{"./main.js":258,"./regexp.js":259,"./regexp_capture.js":260,"@stdlib/utils/define-nonenumerable-read-only-property":297}],258:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var validate = require( './validate.js' );
// VARIABLES //
var REGEXP_STRING = '\\r?\\n';
// MAIN //
/**
* Returns a regular expression to match a newline character sequence.
*
* @param {Options} [options] - function options
* @param {string} [options.flags=''] - regular expression flags
* @param {boolean} [options.capture=false] - boolean indicating whether to create a capture group for the match
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @returns {RegExp} regular expression
*
* @example
* var RE_EOL = reEOL();
* var bool = RE_EOL.test( '\r\n' );
* // returns true
*
* @example
* var replace = require( '@stdlib/string/replace' );
*
* var RE_EOL = reEOL({
* 'flags': 'g'
* });
* var str = '1\n2\n3';
* var out = replace( str, RE_EOL, '' );
*/
function reEOL( options ) {
var opts;
var err;
if ( arguments.length > 0 ) {
opts = {};
err = validate( opts, options );
if ( err ) {
throw err;
}
if ( opts.capture ) {
return new RegExp( '('+REGEXP_STRING+')', opts.flags );
}
return new RegExp( REGEXP_STRING, opts.flags );
}
return /\r?\n/;
}
// EXPORTS //
module.exports = reEOL;
},{"./validate.js":261}],259:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var reEOL = require( './main.js' );
// MAIN //
/**
* Matches a newline character sequence.
*
* Regular expression: `/\r?\n/`
*
* - `\r?`
* - match a carriage return character (optional)
*
* - `\n`
* - match a line feed character
*
* @constant
* @type {RegExp}
* @default /\r?\n/
*/
var REGEXP = reEOL();
// EXPORTS //
module.exports = REGEXP;
},{"./main.js":258}],260:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var reEOL = require( './main.js' );
// MAIN //
/**
* Captures a newline character sequence.
*
* Regular expression: `/\r?\n/`
*
* - `()`
* - capture
*
* - `\r?`
* - match a carriage return character (optional)
*
* - `\n`
* - match a line feed character
*
* @constant
* @type {RegExp}
* @default /(\r?\n)/
*/
var REGEXP_CAPTURE = reEOL({
'capture': true
});
// EXPORTS //
module.exports = REGEXP_CAPTURE;
},{"./main.js":258}],261:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isObject = require( '@stdlib/assert/is-plain-object' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
// MAIN //
/**
* Validates function options.
*
* @private
* @param {Object} opts - destination object
* @param {Options} options - function options
* @param {string} [options.flags] - regular expression flags
* @param {boolean} [options.capture] - boolean indicating whether to wrap a regular expression matching a decimal number with a capture group
* @returns {(Error|null)} null or an error object
*
* @example
* var opts = {};
* var options = {
* 'flags': 'gm'
* };
* var err = validate( opts, options );
* if ( err ) {
* throw err;
* }
*/
function validate( opts, options ) {
if ( !isObject( options ) ) {
return new TypeError( 'invalid argument. Options must be an object. Value: `' + options + '`.' );
}
if ( hasOwnProp( options, 'flags' ) ) {
opts.flags = options.flags;
if ( !isString( opts.flags ) ) {
return new TypeError( 'invalid option. `flags` option must be a string primitive. Option: `' + opts.flags + '`.' );
}
}
if ( hasOwnProp( options, 'capture' ) ) {
opts.capture = options.capture;
if ( !isBoolean( opts.capture ) ) {
return new TypeError( 'invalid option. `capture` option must be a boolean primitive. Option: `' + opts.capture + '`.' );
}
}
return null;
}
// EXPORTS //
module.exports = validate;
},{"@stdlib/assert/has-own-property":46,"@stdlib/assert/is-boolean":72,"@stdlib/assert/is-plain-object":138,"@stdlib/assert/is-string":149}],262:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Regular expression to capture everything that is not a space immediately after the `function` keyword and before the first left parenthesis.
*
* @module @stdlib/regexp/function-name
*
* @example
* var reFunctionName = require( '@stdlib/regexp/function-name' );
* var RE_FUNCTION_NAME = reFunctionName();
*
* function fname( fcn ) {
* return RE_FUNCTION_NAME.exec( fcn.toString() )[ 1 ];
* }
*
* var fn = fname( Math.sqrt );
* // returns 'sqrt'
*
* fn = fname( Int8Array );
* // returns 'Int8Array'
*
* fn = fname( Object.prototype.toString );
* // returns 'toString'
*
* fn = fname( function(){} );
* // returns ''
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var reFunctionName = require( './main.js' );
var REGEXP = require( './regexp.js' );
// MAIN //
setReadOnly( reFunctionName, 'REGEXP', REGEXP );
// EXPORTS //
module.exports = reFunctionName;
},{"./main.js":263,"./regexp.js":264,"@stdlib/utils/define-nonenumerable-read-only-property":297}],263:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
/**
* Returns a regular expression to capture everything that is not a space immediately after the `function` keyword and before the first left parenthesis.
*
* @returns {RegExp} regular expression
*
* @example
* var RE_FUNCTION_NAME = reFunctionName();
*
* function fname( fcn ) {
* return RE_FUNCTION_NAME.exec( fcn.toString() )[ 1 ];
* }
*
* var fn = fname( Math.sqrt );
* // returns 'sqrt'
*
* fn = fname( Int8Array );
* // returns 'Int8Array'
*
* fn = fname( Object.prototype.toString );
* // returns 'toString'
*
* fn = fname( function(){} );
* // returns ''
*/
function reFunctionName() {
return /^\s*function\s*([^(]*)/i;
}
// EXPORTS //
module.exports = reFunctionName;
},{}],264:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var reFunctionName = require( './main.js' );
// MAIN //
/**
* Captures everything that is not a space immediately after the `function` keyword and before the first left parenthesis.
*
* Regular expression: `/^\s*function\s*([^(]*)/i`
*
* - `/^\s*`
* - Match zero or more spaces at beginning
*
* - `function`
* - Match the word `function`
*
* - `\s*`
* - Match zero or more spaces after the word `function`
*
* - `()`
* - Capture
*
* - `[^(]*`
* - Match anything except a left parenthesis `(` zero or more times
*
* - `/i`
* - ignore case
*
* @constant
* @type {RegExp}
* @default /^\s*function\s*([^(]*)/i
*/
var RE_FUNCTION_NAME = reFunctionName();
// EXPORTS //
module.exports = RE_FUNCTION_NAME;
},{"./main.js":263}],265:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Return a regular expression to parse a regular expression string.
*
* @module @stdlib/regexp/regexp
*
* @example
* var reRegExp = require( '@stdlib/regexp/regexp' );
*
* var RE_REGEXP = reRegExp();
*
* var bool = RE_REGEXP.test( '/^beep$/' );
* // returns true
*
* bool = RE_REGEXP.test( '' );
* // returns false
*
* @example
* var reRegExp = require( '@stdlib/regexp/regexp' );
*
* var RE_REGEXP = reRegExp();
*
* var parts = RE_REGEXP.exec( '/^.*$/ig' );
* // returns [ '/^.*$/ig', '^.*$', 'ig', 'index': 0, 'input': '/^.*$/ig' ]
*/
// MAIN //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var reRegExp = require( './main.js' );
var REGEXP = require( './regexp.js' );
// MAIN //
setReadOnly( reRegExp, 'REGEXP', REGEXP );
// EXPORTS //
module.exports = reRegExp;
// EXPORTS //
module.exports = reRegExp;
},{"./main.js":266,"./regexp.js":267,"@stdlib/utils/define-nonenumerable-read-only-property":297}],266:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
/**
* Returns a regular expression to parse a regular expression string.
*
* @returns {RegExp} regular expression
*
* @example
* var RE_REGEXP = reRegExp();
*
* var bool = RE_REGEXP.test( '/^beep$/' );
* // returns true
*
* bool = RE_REGEXP.test( '' );
* // returns false
*/
function reRegExp() {
return /^\/((?:\\\/|[^\/])+)\/([imgy]*)$/; // eslint-disable-line no-useless-escape
}
// EXPORTS //
module.exports = reRegExp;
},{}],267:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var reRegExp = require( './main.js' );
// MAIN //
/**
* Matches parts of a regular expression string.
*
* Regular expression: `/^\/((?:\\\/|[^\/])+)\/([imgy]*)$/`
*
* - `/^\/`
* - match a string that begins with a `/`
*
* - `()`
* - capture
*
* - `(?:)+`
* - capture, but do not remember, a group of characters which occur one or more times
*
* - `\\\/`
* - match the literal `\/`
*
* - `|`
* - OR
*
* - `[^\/]`
* - anything which is not the literal `\/`
*
* - `\/`
* - match the literal `/`
*
* - `([imgy]*)`
* - capture any characters matching `imgy` occurring zero or more times
*
* - `$/`
* - string end
*
*
* @constant
* @type {RegExp}
* @default /^\/((?:\\\/|[^\/])+)\/([imgy]*)$/
*/
var RE_REGEXP = reRegExp();
// EXPORTS //
module.exports = RE_REGEXP;
},{"./main.js":266}],268:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var logger = require( 'debug' );
// VARIABLES //
var debug = logger( 'transform-stream:transform' );
// MAIN //
/**
* Implements the `_transform` method as a pass through.
*
* @private
* @param {(Uint8Array|Buffer|string)} chunk - streamed chunk
* @param {string} encoding - Buffer encoding
* @param {Callback} clbk - callback to invoke after transforming the streamed chunk
*/
function transform( chunk, encoding, clbk ) {
debug( 'Received a new chunk. Chunk: %s. Encoding: %s.', chunk.toString(), encoding );
clbk( null, chunk );
}
// EXPORTS //
module.exports = transform;
},{"debug":381}],269:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var logger = require( 'debug' );
var Transform = require( 'readable-stream' ).Transform;
var inherit = require( '@stdlib/utils/inherit' );
var copy = require( '@stdlib/utils/copy' );
var DEFAULTS = require( './defaults.json' );
var validate = require( './validate.js' );
var destroy = require( './destroy.js' );
var _transform = require( './_transform.js' ); // eslint-disable-line no-underscore-dangle
// VARIABLES //
var debug = logger( 'transform-stream:ctor' );
// MAIN //
/**
* Transform stream constructor factory.
*
* @param {Options} [options] - stream options
* @param {Function} [options.transform] - callback to invoke upon receiving a new chunk
* @param {Function} [options.flush] - callback to invoke after receiving all chunks and prior to the stream closing
* @param {boolean} [options.objectMode=false] - specifies whether a stream should operate in object mode
* @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings`
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false`
* @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends
* @param {boolean} [options.decodeStrings=true] - specifies whether to decode `strings` into `Buffer` objects when writing
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @returns {Function} Transform stream constructor
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
*
* function transform( chunk, enc, clbk ) {
* clbk( null, chunk.toString()+'\n' );
* }
*
* var opts = {
* 'transform': transform
* };
*
* var TransformStream = ctor( opts );
*
* var stream = new TransformStream();
*
* stream.pipe( stdout );
*
* stream.write( '1' );
* stream.write( '2' );
* stream.write( '3' );
*
* stream.end();
*
* // prints: '1\n2\n3\n'
*/
function ctor( options ) {
var transform;
var copts;
var err;
copts = copy( DEFAULTS );
if ( arguments.length ) {
err = validate( copts, options );
if ( err ) {
throw err;
}
}
if ( copts.transform ) {
transform = copts.transform;
} else {
transform = _transform;
}
/**
* Transform stream constructor.
*
* @private
* @constructor
* @param {Options} [options] - stream options
* @param {boolean} [options.objectMode=false] - specifies whether a stream should operate in object mode
* @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings`
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false`
* @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends
* @param {boolean} [options.decodeStrings=true] - specifies whether to decode `strings` into `Buffer` objects when writing
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @returns {TransformStream} transform stream
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
*
* var stream = new TransformStream();
*
* stream.pipe( stdout );
*
* stream.write( '1' );
* stream.write( '2' );
* stream.write( '3' );
*
* stream.end();
*
* // prints: '1\n2\n3\n'
*/
function TransformStream( options ) {
var opts;
var err;
if ( !( this instanceof TransformStream ) ) {
if ( arguments.length ) {
return new TransformStream( options );
}
return new TransformStream();
}
opts = copy( copts );
if ( arguments.length ) {
err = validate( opts, options );
if ( err ) {
throw err;
}
}
debug( 'Creating a transform stream configured with the following options: %s.', JSON.stringify( opts ) );
Transform.call( this, opts );
this._destroyed = false;
return this;
}
/**
* Inherit from the `Transform` prototype.
*/
inherit( TransformStream, Transform );
/**
* Implements the `_transform` method.
*
* @private
* @name _transform
* @memberof TransformStream.prototype
* @type {Function}
* @param {(Buffer|string)} chunk - streamed chunk
* @param {string} encoding - Buffer encoding
* @param {Callback} clbk - callback to invoke after transforming the streamed chunk
*/
TransformStream.prototype._transform = transform; // eslint-disable-line no-underscore-dangle
if ( copts.flush ) {
/**
* Implements the `_flush` method.
*
* @private
* @name _flush
* @memberof TransformStream.prototype
* @type {Function}
* @param {Callback} callback to invoke after performing flush tasks
*/
TransformStream.prototype._flush = copts.flush; // eslint-disable-line no-underscore-dangle
}
/**
* Gracefully destroys a stream, providing backward compatibility.
*
* @private
* @name destroy
* @memberof TransformStream.prototype
* @type {Function}
* @param {Object} [error] - optional error message
* @returns {TransformStream} stream instance
*/
TransformStream.prototype.destroy = destroy;
return TransformStream;
}
// EXPORTS //
module.exports = ctor;
},{"./_transform.js":268,"./defaults.json":270,"./destroy.js":271,"./validate.js":276,"@stdlib/utils/copy":293,"@stdlib/utils/inherit":325,"debug":381,"readable-stream":398}],270:[function(require,module,exports){
module.exports={
"objectMode": false,
"encoding": null,
"allowHalfOpen": false,
"decodeStrings": true
}
},{}],271:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var logger = require( 'debug' );
var nextTick = require( '@stdlib/utils/next-tick' );
// VARIABLES //
var debug = logger( 'transform-stream:destroy' );
// MAIN //
/**
* Gracefully destroys a stream, providing backward compatibility.
*
* @private
* @param {Object} [error] - optional error message
* @returns {Stream} stream instance
*/
function destroy( error ) {
/* eslint-disable no-invalid-this */
var self;
if ( this._destroyed ) {
debug( 'Attempted to destroy an already destroyed stream.' );
return this;
}
self = this;
this._destroyed = true;
nextTick( close );
return this;
/**
* Closes a stream.
*
* @private
*/
function close() {
if ( error ) {
debug( 'Stream was destroyed due to an error. Error: %s.', JSON.stringify( error ) );
self.emit( 'error', error );
}
debug( 'Closing the stream...' );
self.emit( 'close' );
}
}
// EXPORTS //
module.exports = destroy;
},{"@stdlib/utils/next-tick":351,"debug":381}],272:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isObject = require( '@stdlib/assert/is-plain-object' );
var copy = require( '@stdlib/utils/copy' );
var Stream = require( './main.js' );
// MAIN //
/**
* Creates a reusable transform stream factory.
*
* @param {Options} [options] - stream options
* @param {boolean} [options.objectMode=false] - specifies whether a stream should operate in object mode
* @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings`
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false`
* @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends
* @param {boolean} [options.decodeStrings=true] - specifies whether to decode `strings` into `Buffer` objects when writing
* @throws {TypeError} options argument must be an object
* @returns {Function} transform stream factory
*
* @example
* function transform( chunk, enc, clbk ) {
* clbk( null, chunk.toString()+'\n' );
* }
*
* var opts = {
* 'objectMode': true,
* 'encoding': 'utf8',
* 'highWaterMark': 64,
* 'decodeStrings': false
* };
*
* var factory = streamFactory( opts );
*
* // Create 10 identically configured streams...
* var streams = [];
* var i;
* for ( i = 0; i < 10; i++ ) {
* streams.push( factory( transform ) );
* }
*/
function streamFactory( options ) {
var opts;
if ( arguments.length ) {
if ( !isObject( options ) ) {
throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' );
}
opts = copy( options );
} else {
opts = {};
}
return createStream;
/**
* Creates a transform stream.
*
* @private
* @param {Function} transform - callback to invoke upon receiving a new chunk
* @param {Function} [flush] - callback to invoke after receiving all chunks and prior to the stream closing
* @throws {TypeError} must provide valid options
* @throws {TypeError} transform callback must be a function
* @throws {TypeError} flush callback must be a function
* @returns {TransformStream} transform stream
*/
function createStream( transform, flush ) {
opts.transform = transform;
if ( arguments.length > 1 ) {
opts.flush = flush;
} else {
delete opts.flush; // clear any previous `flush`
}
return new Stream( opts );
}
}
// EXPORTS //
module.exports = streamFactory;
},{"./main.js":274,"@stdlib/assert/is-plain-object":138,"@stdlib/utils/copy":293}],273:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Transform stream.
*
* @module @stdlib/streams/node/transform
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
* var transformStream = require( '@stdlib/streams/node/transform' );
*
* function transform( chunk, enc, clbk ) {
* clbk( null, chunk.toString()+'\n' );
* }
*
* var opts = {
* 'transform': transform
* };
* var stream = transformStream( opts );
*
* stream.pipe( stdout );
*
* stream.write( '1' );
* stream.write( '2' );
* stream.write( '3' );
*
* stream.end();
* // => '1\n2\n3\n'
*
*
* @example
* var transformStream = require( '@stdlib/streams/node/transform' );
*
* function transform( chunk, enc, clbk ) {
* clbk( null, chunk.toString()+'\n' );
* }
*
* var opts = {
* 'objectMode': true,
* 'encoding': 'utf8',
* 'highWaterMark': 64,
* 'decodeStrings': false
* };
*
* var factory = transformStream.factory( opts );
*
* // Create 10 identically configured streams...
* var streams = [];
* var i;
* for ( i = 0; i < 10; i++ ) {
* streams.push( factory( transform ) );
* }
*
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
* var transformStream = require( '@stdlib/streams/node/transform' );
*
* function stringify( chunk, enc, clbk ) {
* clbk( null, JSON.stringify( chunk ) );
* }
*
* function newline( chunk, enc, clbk ) {
* clbk( null, chunk+'\n' );
* }
*
* var s1 = transformStream.objectMode({
* 'transform': stringify
* });
*
* var s2 = transformStream.objectMode({
* 'transform': newline
* });
*
* s1.pipe( s2 ).pipe( stdout );
*
* s1.write( {'value': 'a'} );
* s1.write( {'value': 'b'} );
* s1.write( {'value': 'c'} );
*
* s1.end();
* // => '{"value":"a"}\n{"value":"b"}\n{"value":"c"}\n'
*
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
* var transformStream = require( '@stdlib/streams/node/transform' );
*
* function transform( chunk, enc, clbk ) {
* clbk( null, chunk.toString()+'\n' );
* }
*
* var opts = {
* 'transform': transform
* };
*
* var Stream = transformStream.ctor( opts );
*
* var stream = new Stream();
*
* stream.pipe( stdout );
*
* stream.write( '1' );
* stream.write( '2' );
* stream.write( '3' );
*
* stream.end();
* // => '1\n2\n3\n'
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var transform = require( './main.js' );
var objectMode = require( './object_mode.js' );
var factory = require( './factory.js' );
var ctor = require( './ctor.js' );
// MAIN //
setReadOnly( transform, 'objectMode', objectMode );
setReadOnly( transform, 'factory', factory );
setReadOnly( transform, 'ctor', ctor );
// EXPORTS //
module.exports = transform;
},{"./ctor.js":269,"./factory.js":272,"./main.js":274,"./object_mode.js":275,"@stdlib/utils/define-nonenumerable-read-only-property":297}],274:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var logger = require( 'debug' );
var Transform = require( 'readable-stream' ).Transform;
var inherit = require( '@stdlib/utils/inherit' );
var copy = require( '@stdlib/utils/copy' );
var DEFAULTS = require( './defaults.json' );
var validate = require( './validate.js' );
var destroy = require( './destroy.js' );
var _transform = require( './_transform.js' ); // eslint-disable-line no-underscore-dangle
// VARIABLES //
var debug = logger( 'transform-stream:main' );
// MAIN //
/**
* Transform stream constructor.
*
* @constructor
* @param {Options} [options] - stream options
* @param {Function} [options.transform] - callback to invoke upon receiving a new chunk
* @param {Function} [options.flush] - callback to invoke after receiving all chunks and prior to the stream closing
* @param {boolean} [options.objectMode=false] - specifies whether stream should operate in object mode
* @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings`
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false`
* @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends
* @param {boolean} [options.decodeStrings=true] - specifies whether to decode `strings` into `Buffer` objects when writing
* @throws {TypeError} must provide valid options
* @returns {TransformStream} transform stream
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
*
* function transform( chunk, enc, clbk ) {
* clbk( null, chunk.toString()+'\n' );
* }
*
* var opts = {
* 'transform': transform
* };
* var stream = new TransformStream( opts );
*
* stream.pipe( stdout );
*
* stream.write( '1' );
* stream.write( '2' );
* stream.write( '3' );
*
* stream.end();
*
* // prints: '1\n2\n3\n'
*/
function TransformStream( options ) {
var opts;
var err;
if ( !( this instanceof TransformStream ) ) {
if ( arguments.length ) {
return new TransformStream( options );
}
return new TransformStream();
}
opts = copy( DEFAULTS );
if ( arguments.length ) {
err = validate( opts, options );
if ( err ) {
throw err;
}
}
debug( 'Creating a transform stream configured with the following options: %s.', JSON.stringify( opts ) );
Transform.call( this, opts );
this._destroyed = false;
if ( opts.transform ) {
this._transform = opts.transform;
} else {
this._transform = _transform;
}
if ( opts.flush ) {
this._flush = opts.flush;
}
return this;
}
/*
* Inherit from the `Transform` prototype.
*/
inherit( TransformStream, Transform );
/**
* Gracefully destroys a stream, providing backward compatibility.
*
* @name destroy
* @memberof TransformStream.prototype
* @type {Function}
* @param {Object} [error] - optional error message
* @returns {TransformStream} stream instance
*/
TransformStream.prototype.destroy = destroy;
// EXPORTS //
module.exports = TransformStream;
},{"./_transform.js":268,"./defaults.json":270,"./destroy.js":271,"./validate.js":276,"@stdlib/utils/copy":293,"@stdlib/utils/inherit":325,"debug":381,"readable-stream":398}],275:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isObject = require( '@stdlib/assert/is-plain-object' );
var copy = require( '@stdlib/utils/copy' );
var Stream = require( './main.js' );
// MAIN //
/**
* Returns a transform stream with `objectMode` set to `true`.
*
* @param {Options} [options] - stream options
* @param {Function} [options.transform] - callback to invoke upon receiving a new chunk
* @param {Function} [options.flush] - callback to invoke after receiving all chunks and prior to the stream closing
* @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings`
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false`
* @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends
* @param {boolean} [options.decodeStrings=true] - specifies whether to decode `strings` into `Buffer` objects when writing
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @returns {TransformStream} transform stream
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
*
* function stringify( chunk, enc, clbk ) {
* clbk( null, JSON.stringify( chunk ) );
* }
*
* function newline( chunk, enc, clbk ) {
* clbk( null, chunk+'\n' );
* }
*
* var s1 = objectMode({
* 'transform': stringify
* });
*
* var s2 = objectMode({
* 'transform': newline
* });
*
* s1.pipe( s2 ).pipe( stdout );
*
* s1.write( {'value': 'a'} );
* s1.write( {'value': 'b'} );
* s1.write( {'value': 'c'} );
*
* s1.end();
*
* // prints: '{"value":"a"}\n{"value":"b"}\n{"value":"c"}\n'
*/
function objectMode( options ) {
var opts;
if ( arguments.length ) {
if ( !isObject( options ) ) {
throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' );
}
opts = copy( options );
} else {
opts = {};
}
opts.objectMode = true;
return new Stream( opts );
}
// EXPORTS //
module.exports = objectMode;
},{"./main.js":274,"@stdlib/assert/is-plain-object":138,"@stdlib/utils/copy":293}],276:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isObject = require( '@stdlib/assert/is-plain-object' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isFunction = require( '@stdlib/assert/is-function' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isNonNegative = require( '@stdlib/assert/is-nonnegative-number' ).isPrimitive;
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
// MAIN //
/**
* Validates function options.
*
* @private
* @param {Object} opts - destination object
* @param {Options} options - function options
* @param {Function} [options.transform] - callback to invoke upon receiving a new chunk
* @param {Function} [options.flush] - callback to invoke after receiving all chunks and prior to the stream closing
* @param {boolean} [options.objectMode] - specifies whether a stream should operate in object mode
* @param {(string|null)} [options.encoding] - specifies how `Buffer` objects should be decoded to `strings`
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false`
* @param {boolean} [options.allowHalfOpen] - specifies whether the stream should remain open even if one side ends
* @param {boolean} [options.decodeStrings] - specifies whether to decode `strings` into `Buffer` objects when writing
* @returns {(Error|null)} null or an error object
*/
function validate( opts, options ) {
if ( !isObject( options ) ) {
return new TypeError( 'invalid argument. Options must be an object. Value: `' + options + '`.' );
}
if ( hasOwnProp( options, 'transform' ) ) {
opts.transform = options.transform;
if ( !isFunction( opts.transform ) ) {
return new TypeError( 'invalid option. `transform` option must be a function. Option: `' + opts.transform + '`.' );
}
}
if ( hasOwnProp( options, 'flush' ) ) {
opts.flush = options.flush;
if ( !isFunction( opts.flush ) ) {
return new TypeError( 'invalid option. `flush` option must be a function. Option: `' + opts.flush + '`.' );
}
}
if ( hasOwnProp( options, 'objectMode' ) ) {
opts.objectMode = options.objectMode;
if ( !isBoolean( opts.objectMode ) ) {
return new TypeError( 'invalid option. `objectMode` option must be a primitive boolean. Option: `' + opts.objectMode + '`.' );
}
}
if ( hasOwnProp( options, 'encoding' ) ) {
opts.encoding = options.encoding;
if ( !isString( opts.encoding ) ) {
return new TypeError( 'invalid option. `encoding` option must be a primitive string. Option: `' + opts.encoding + '`.' );
}
}
if ( hasOwnProp( options, 'allowHalfOpen' ) ) {
opts.allowHalfOpen = options.allowHalfOpen;
if ( !isBoolean( opts.allowHalfOpen ) ) {
return new TypeError( 'invalid option. `allowHalfOpen` option must be a primitive boolean. Option: `' + opts.allowHalfOpen + '`.' );
}
}
if ( hasOwnProp( options, 'highWaterMark' ) ) {
opts.highWaterMark = options.highWaterMark;
if ( !isNonNegative( opts.highWaterMark ) ) {
return new TypeError( 'invalid option. `highWaterMark` option must be a nonnegative number. Option: `' + opts.highWaterMark + '`.' );
}
}
if ( hasOwnProp( options, 'decodeStrings' ) ) {
opts.decodeStrings = options.decodeStrings;
if ( !isBoolean( opts.decodeStrings ) ) {
return new TypeError( 'invalid option. `decodeStrings` option must be a primitive boolean. Option: `' + opts.decodeStrings + '`.' );
}
}
return null;
}
// EXPORTS //
module.exports = validate;
},{"@stdlib/assert/has-own-property":46,"@stdlib/assert/is-boolean":72,"@stdlib/assert/is-function":93,"@stdlib/assert/is-nonnegative-number":122,"@stdlib/assert/is-plain-object":138,"@stdlib/assert/is-string":149}],277:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Create a string from a sequence of Unicode code points.
*
* @module @stdlib/string/from-code-point
*
* @example
* var fromCodePoint = require( '@stdlib/string/from-code-point' );
*
* var str = fromCodePoint( 9731 );
* // returns '☃'
*/
// MODULES //
var fromCodePoint = require( './main.js' );
// EXPORTS //
module.exports = fromCodePoint;
},{"./main.js":278}],278:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive;
var isCollection = require( '@stdlib/assert/is-collection' );
var UNICODE_MAX = require( '@stdlib/constants/unicode/max' );
var UNICODE_MAX_BMP = require( '@stdlib/constants/unicode/max-bmp' );
// VARIABLES //
var fromCharCode = String.fromCharCode;
// Factor to rescale a code point from a supplementary plane:
var Ox10000 = 0x10000|0; // 65536
// Factor added to obtain a high surrogate:
var OxD800 = 0xD800|0; // 55296
// Factor added to obtain a low surrogate:
var OxDC00 = 0xDC00|0; // 56320
// 10-bit mask: 2^10-1 = 1023 => 0x3ff => 00000000 00000000 00000011 11111111
var Ox3FF = 1023|0;
// MAIN //
/**
* Creates a string from a sequence of Unicode code points.
*
* ## Notes
*
* - UTF-16 encoding uses one 16-bit unit for non-surrogates (U+0000 to U+D7FF and U+E000 to U+FFFF).
* - UTF-16 encoding uses two 16-bit units (surrogate pairs) for U+10000 to U+10FFFF and encodes U+10000-U+10FFFF by subtracting 0x10000 from the code point, expressing the result as a 20-bit binary, and splitting the 20 bits of 0x0-0xFFFFF as upper and lower 10-bits. The respective 10-bits are stored in two 16-bit words: a high and a low surrogate.
*
*
* @param {...NonNegativeInteger} args - sequence of code points
* @throws {Error} must provide either an array-like object of code points or one or more code points as separate arguments
* @throws {TypeError} a code point must be a nonnegative integer
* @throws {RangeError} must provide a valid Unicode code point
* @returns {string} created string
*
* @example
* var str = fromCodePoint( 9731 );
* // returns '☃'
*/
function fromCodePoint( args ) {
var len;
var str;
var arr;
var low;
var hi;
var pt;
var i;
len = arguments.length;
if ( len === 1 && isCollection( args ) ) {
arr = arguments[ 0 ];
len = arr.length;
} else {
arr = [];
for ( i = 0; i < len; i++ ) {
arr.push( arguments[ i ] );
}
}
if ( len === 0 ) {
throw new Error( 'insufficient input arguments. Must provide either an array of code points or one or more code points as separate arguments.' );
}
str = '';
for ( i = 0; i < len; i++ ) {
pt = arr[ i ];
if ( !isNonNegativeInteger( pt ) ) {
throw new TypeError( 'invalid argument. Must provide valid code points (nonnegative integers). Value: `'+pt+'`.' );
}
if ( pt > UNICODE_MAX ) {
throw new RangeError( 'invalid argument. Must provide a valid code point (cannot exceed max). Value: `'+pt+'`.' );
}
if ( pt <= UNICODE_MAX_BMP ) {
str += fromCharCode( pt );
} else {
// Code point from a supplementary plane. Split into two 16-bit code units (surrogate pair).
pt -= Ox10000;
hi = (pt >> 10) + OxD800;
low = (pt & Ox3FF) + OxDC00;
str += fromCharCode( hi, low );
}
}
return str;
}
// EXPORTS //
module.exports = fromCodePoint;
},{"@stdlib/assert/is-collection":81,"@stdlib/assert/is-nonnegative-integer":118,"@stdlib/constants/unicode/max":236,"@stdlib/constants/unicode/max-bmp":235}],279:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Replace search occurrences with a replacement string.
*
* @module @stdlib/string/replace
*
* @example
* var replace = require( '@stdlib/string/replace' );
*
* var str = 'beep';
* var out = replace( str, 'e', 'o' );
* // returns 'boop'
*
* str = 'Hello World';
* out = replace( str, /world/i, 'Mr. President' );
* // returns 'Hello Mr. President'
*/
// MODULES //
var replace = require( './replace.js' );
// EXPORTS //
module.exports = replace;
},{"./replace.js":280}],280:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var rescape = require( '@stdlib/utils/escape-regexp-string' );
var isFunction = require( '@stdlib/assert/is-function' );
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var isRegExp = require( '@stdlib/assert/is-regexp' );
// MAIN //
/**
* Replace search occurrences with a replacement string.
*
* @param {string} str - input string
* @param {(string|RegExp)} search - search expression
* @param {(string|Function)} newval - replacement value or function
* @throws {TypeError} first argument must be a string primitive
* @throws {TypeError} second argument argument must be a string primitive or regular expression
* @throws {TypeError} third argument must be a string primitive or function
* @returns {string} new string containing replacement(s)
*
* @example
* var str = 'beep';
* var out = replace( str, 'e', 'o' );
* // returns 'boop'
*
* @example
* var str = 'Hello World';
* var out = replace( str, /world/i, 'Mr. President' );
* // returns 'Hello Mr. President'
*
* @example
* var capitalize = require( '@stdlib/string/capitalize' );
*
* var str = 'Oranges and lemons say the bells of St. Clement\'s';
*
* function replacer( match, p1 ) {
* return capitalize( p1 );
* }
*
* var out = replace( str, /([^\s]*)/gi, replacer);
* // returns 'Oranges And Lemons Say The Bells Of St. Clement\'s'
*/
function replace( str, search, newval ) {
if ( !isString( str ) ) {
throw new TypeError( 'invalid argument. First argument must be a string primitive. Value: `' + str + '`.' );
}
if ( isString( search ) ) {
search = rescape( search );
search = new RegExp( search, 'g' );
}
else if ( !isRegExp( search ) ) {
throw new TypeError( 'invalid argument. Second argument must be a string primitive or regular expression. Value: `' + search + '`.' );
}
if ( !isString( newval ) && !isFunction( newval ) ) {
throw new TypeError( 'invalid argument. Third argument must be a string primitive or replacement function. Value: `' + newval + '`.' );
}
return str.replace( search, newval );
}
// EXPORTS //
module.exports = replace;
},{"@stdlib/assert/is-function":93,"@stdlib/assert/is-regexp":145,"@stdlib/assert/is-string":149,"@stdlib/utils/escape-regexp-string":304}],281:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Trim whitespace characters from the beginning and end of a string.
*
* @module @stdlib/string/trim
*
* @example
* var trim = require( '@stdlib/string/trim' );
*
* var out = trim( ' Whitespace ' );
* // returns 'Whitespace'
*
* out = trim( '\t\t\tTabs\t\t\t' );
* // returns 'Tabs'
*
* out = trim( '\n\n\nNew Lines\n\n\n' );
* // returns 'New Lines'
*/
// MODULES //
var trim = require( './trim.js' );
// EXPORTS //
module.exports = trim;
},{"./trim.js":282}],282:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
<|fim▁hole|>
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var replace = require( '@stdlib/string/replace' );
// VARIABLES //
// The following regular expression should suffice to polyfill (most?) all environments.
var RE = /^[\u0020\f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]*([\S\s]*?)[\u0020\f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]*$/;
// MAIN //
/**
* Trim whitespace characters from beginning and end of a string.
*
* @param {string} str - input string
* @throws {TypeError} must provide a string primitive
* @returns {string} trimmed string
*
* @example
* var out = trim( ' Whitespace ' );
* // returns 'Whitespace'
*
* @example
* var out = trim( '\t\t\tTabs\t\t\t' );
* // returns 'Tabs'
*
* @example
* var out = trim( '\n\n\nNew Lines\n\n\n' );
* // returns 'New Lines'
*/
function trim( str ) {
if ( !isString( str ) ) {
throw new TypeError( 'invalid argument. Must provide a string primitive. Value: `' + str + '`.' );
}
return replace( str, RE, '$1' );
}
// EXPORTS //
module.exports = trim;
},{"@stdlib/assert/is-string":149,"@stdlib/string/replace":279}],283:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var getGlobal = require( '@stdlib/utils/global' );
var isObject = require( '@stdlib/assert/is-object' );
var modf = require( '@stdlib/math/base/special/modf' );
var round = require( '@stdlib/math/base/special/round' );
var now = require( './now.js' );
// VARIABLES //
var Global = getGlobal();
var ts;
var ns;
if ( isObject( Global.performance ) ) {
ns = Global.performance;
} else {
ns = {};
}
if ( ns.now ) {
ts = ns.now.bind( ns );
} else if ( ns.mozNow ) {
ts = ns.mozNow.bind( ns );
} else if ( ns.msNow ) {
ts = ns.msNow.bind( ns );
} else if ( ns.oNow ) {
ts = ns.oNow.bind( ns );
} else if ( ns.webkitNow ) {
ts = ns.webkitNow.bind( ns );
} else {
ts = now;
}
// MAIN //
/**
* Returns a high-resolution time.
*
* ## Notes
*
* - Output format: `[seconds, nanoseconds]`.
*
*
* @private
* @returns {NumberArray} high-resolution time
*
* @example
* var t = tic();
* // returns [<number>,<number>]
*/
function tic() {
var parts;
var t;
// Get a millisecond timestamp and convert to seconds:
t = ts() / 1000;
// Decompose the timestamp into integer (seconds) and fractional parts:
parts = modf( t );
// Convert the fractional part to nanoseconds:
parts[ 1 ] = round( parts[1] * 1.0e9 );
// Return the high-resolution time:
return parts;
}
// EXPORTS //
module.exports = tic;
},{"./now.js":285,"@stdlib/assert/is-object":136,"@stdlib/math/base/special/modf":243,"@stdlib/math/base/special/round":246,"@stdlib/utils/global":318}],284:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isFunction = require( '@stdlib/assert/is-function' );
// MAIN //
var bool = isFunction( Date.now );
// EXPORTS //
module.exports = bool;
},{"@stdlib/assert/is-function":93}],285:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var bool = require( './detect.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var now;
if ( bool ) {
now = Date.now;
} else {
now = polyfill;
}
// EXPORTS //
module.exports = now;
},{"./detect.js":284,"./polyfill.js":286}],286:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
/**
* Returns the time in milliseconds since the epoch.
*
* @private
* @returns {number} time
*
* @example
* var ts = now();
* // returns <number>
*/
function now() {
var d = new Date();
return d.getTime();
}
// EXPORTS //
module.exports = now;
},{}],287:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Return a high-resolution time difference.
*
* @module @stdlib/time/toc
*
* @example
* var tic = require( '@stdlib/time/tic' );
* var toc = require( '@stdlib/time/toc' );
*
* var start = tic();
* var delta = toc( start );
* // returns [<number>,<number>]
*/
// MODULES //
var toc = require( './toc.js' );
// EXPORTS //
module.exports = toc;
},{"./toc.js":288}],288:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isNonNegativeIntegerArray = require( '@stdlib/assert/is-nonnegative-integer-array' ).primitives;
var tic = require( '@stdlib/time/tic' );
// MAIN //
/**
* Returns a high-resolution time difference.
*
* ## Notes
*
* - Output format: `[seconds, nanoseconds]`.
*
*
* @param {NonNegativeIntegerArray} time - high-resolution time
* @throws {TypeError} must provide a nonnegative integer array
* @throws {RangeError} input array must have length `2`
* @returns {NumberArray} high resolution time difference
*
* @example
* var tic = require( '@stdlib/time/tic' );
*
* var start = tic();
* var delta = toc( start );
* // returns [<number>,<number>]
*/
function toc( time ) {
var now = tic();
var sec;
var ns;
if ( !isNonNegativeIntegerArray( time ) ) {
throw new TypeError( 'invalid argument. Must provide an array of nonnegative integers. Value: `' + time + '`.' );
}
if ( time.length !== 2 ) {
throw new RangeError( 'invalid argument. Input array must have length `2`.' );
}
sec = now[ 0 ] - time[ 0 ];
ns = now[ 1 ] - time[ 1 ];
if ( sec > 0 && ns < 0 ) {
sec -= 1;
ns += 1e9;
}
else if ( sec < 0 && ns > 0 ) {
sec += 1;
ns -= 1e9;
}
return [ sec, ns ];
}
// EXPORTS //
module.exports = toc;
},{"@stdlib/assert/is-nonnegative-integer-array":117,"@stdlib/time/tic":283}],289:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Determine the name of a value's constructor.
*
* @module @stdlib/utils/constructor-name
*
* @example
* var constructorName = require( '@stdlib/utils/constructor-name' );
*
* var v = constructorName( 'a' );
* // returns 'String'
*
* v = constructorName( {} );
* // returns 'Object'
*
* v = constructorName( true );
* // returns 'Boolean'
*/
// MODULES //
var constructorName = require( './main.js' );
// EXPORTS //
module.exports = constructorName;
},{"./main.js":290}],290:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
var RE = require( '@stdlib/regexp/function-name' ).REGEXP;
var isBuffer = require( '@stdlib/assert/is-buffer' );
// MAIN //
/**
* Determines the name of a value's constructor.
*
* @param {*} v - input value
* @returns {string} name of a value's constructor
*
* @example
* var v = constructorName( 'a' );
* // returns 'String'
*
* @example
* var v = constructorName( 5 );
* // returns 'Number'
*
* @example
* var v = constructorName( null );
* // returns 'Null'
*
* @example
* var v = constructorName( undefined );
* // returns 'Undefined'
*
* @example
* var v = constructorName( function noop() {} );
* // returns 'Function'
*/
function constructorName( v ) {
var match;
var name;
var ctor;
name = nativeClass( v ).slice( 8, -1 );
if ( (name === 'Object' || name === 'Error') && v.constructor ) {
ctor = v.constructor;
if ( typeof ctor.name === 'string' ) {
return ctor.name;
}
match = RE.exec( ctor.toString() );
if ( match ) {
return match[ 1 ];
}
}
if ( isBuffer( v ) ) {
return 'Buffer';
}
return name;
}
// EXPORTS //
module.exports = constructorName;
},{"@stdlib/assert/is-buffer":79,"@stdlib/regexp/function-name":262,"@stdlib/utils/native-class":346}],291:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isArray = require( '@stdlib/assert/is-array' );
var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive;
var PINF = require( '@stdlib/constants/float64/pinf' );
var deepCopy = require( './deep_copy.js' );
// MAIN //
/**
* Copies or deep clones a value to an arbitrary depth.
*
* @param {*} value - value to copy
* @param {NonNegativeInteger} [level=+infinity] - copy depth
* @throws {TypeError} `level` must be a nonnegative integer
* @returns {*} value copy
*
* @example
* var out = copy( 'beep' );
* // returns 'beep'
*
* @example
* var value = [
* {
* 'a': 1,
* 'b': true,
* 'c': [ 1, 2, 3 ]
* }
* ];
* var out = copy( value );
* // returns [ { 'a': 1, 'b': true, 'c': [ 1, 2, 3 ] } ]
*
* var bool = ( value[0].c === out[0].c );
* // returns false
*/
function copy( value, level ) {
var out;
if ( arguments.length > 1 ) {
if ( !isNonNegativeInteger( level ) ) {
throw new TypeError( 'invalid argument. `level` must be a nonnegative integer. Value: `' + level + '`.' );
}
if ( level === 0 ) {
return value;
}
} else {
level = PINF;
}
out = ( isArray( value ) ) ? new Array( value.length ) : {};
return deepCopy( value, out, [value], [out], level );
}
// EXPORTS //
module.exports = copy;
},{"./deep_copy.js":292,"@stdlib/assert/is-array":70,"@stdlib/assert/is-nonnegative-integer":118,"@stdlib/constants/float64/pinf":225}],292:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isArray = require( '@stdlib/assert/is-array' );
var isBuffer = require( '@stdlib/assert/is-buffer' );
var isError = require( '@stdlib/assert/is-error' );
var typeOf = require( '@stdlib/utils/type-of' );
var regexp = require( '@stdlib/utils/regexp-from-string' );
var indexOf = require( '@stdlib/utils/index-of' );
var objectKeys = require( '@stdlib/utils/keys' );
var propertyNames = require( '@stdlib/utils/property-names' );
var propertyDescriptor = require( '@stdlib/utils/property-descriptor' );
var getPrototypeOf = require( '@stdlib/utils/get-prototype-of' );
var defineProperty = require( '@stdlib/utils/define-property' );
var copyBuffer = require( '@stdlib/buffer/from-buffer' );
var typedArrays = require( './typed_arrays.js' );
// FUNCTIONS //
/**
* Clones a class instance.
*
* ## Notes
*
* - This should **only** be used for simple cases. Any instances with privileged access to variables (e.g., within closures) cannot be cloned. This approach should be considered **fragile**.
* - The function is greedy, disregarding the notion of a `level`. Instead, the function deep copies all properties, as we assume the concept of `level` applies only to the class instance reference but not to its internal state. This prevents, in theory, two instances from sharing state.
*
*
* @private
* @param {Object} val - class instance
* @returns {Object} new instance
*/
function cloneInstance( val ) {
var cache;
var names;
var name;
var refs;
var desc;
var tmp;
var ref;
var i;
cache = [];
refs = [];
ref = Object.create( getPrototypeOf( val ) );
cache.push( val );
refs.push( ref );
names = propertyNames( val );
for ( i = 0; i < names.length; i++ ) {
name = names[ i ];
desc = propertyDescriptor( val, name );
if ( hasOwnProp( desc, 'value' ) ) {
tmp = ( isArray( val[name] ) ) ? [] : {};
desc.value = deepCopy( val[name], tmp, cache, refs, -1 );
}
defineProperty( ref, name, desc );
}
if ( !Object.isExtensible( val ) ) {
Object.preventExtensions( ref );
}
if ( Object.isSealed( val ) ) {
Object.seal( ref );
}
if ( Object.isFrozen( val ) ) {
Object.freeze( ref );
}
return ref;
}
/**
* Copies an error object.
*
* @private
* @param {(Error|TypeError|SyntaxError|URIError|ReferenceError|RangeError|EvalError)} error - error to copy
* @returns {(Error|TypeError|SyntaxError|URIError|ReferenceError|RangeError|EvalError)} error copy
*
* @example
* var err1 = new TypeError( 'beep' );
*
* var err2 = copyError( err1 );
* // returns <TypeError>
*/
function copyError( error ) {
var cache = [];
var refs = [];
var keys;
var desc;
var tmp;
var key;
var err;
var i;
// Create a new error...
err = new error.constructor( error.message );
cache.push( error );
refs.push( err );
// If a `stack` property is present, copy it over...
if ( error.stack ) {
err.stack = error.stack;
}
// Node.js specific (system errors)...
if ( error.code ) {
err.code = error.code;
}
if ( error.errno ) {
err.errno = error.errno;
}
if ( error.syscall ) {
err.syscall = error.syscall;
}
// Any enumerable properties...
keys = objectKeys( error );
for ( i = 0; i < keys.length; i++ ) {
key = keys[ i ];
desc = propertyDescriptor( error, key );
if ( hasOwnProp( desc, 'value' ) ) {
tmp = ( isArray( error[ key ] ) ) ? [] : {};
desc.value = deepCopy( error[ key ], tmp, cache, refs, -1 );
}
defineProperty( err, key, desc );
}
return err;
}
// MAIN //
/**
* Recursively performs a deep copy of an input object.
*
* @private
* @param {*} val - value to copy
* @param {(Array|Object)} copy - copy
* @param {Array} cache - an array of visited objects
* @param {Array} refs - an array of object references
* @param {NonNegativeInteger} level - copy depth
* @returns {*} deep copy
*/
function deepCopy( val, copy, cache, refs, level ) {
var parent;
var keys;
var name;
var desc;
var ctor;
var key;
var ref;
var x;
var i;
var j;
level -= 1;
// Primitives and functions...
if (
typeof val !== 'object' ||
val === null
) {
return val;
}
if ( isBuffer( val ) ) {
return copyBuffer( val );
}
if ( isError( val ) ) {
return copyError( val );
}
// Objects...
name = typeOf( val );
if ( name === 'date' ) {
return new Date( +val );
}
if ( name === 'regexp' ) {
return regexp( val.toString() );
}
if ( name === 'set' ) {
return new Set( val );
}
if ( name === 'map' ) {
return new Map( val );
}
if (
name === 'string' ||
name === 'boolean' ||
name === 'number'
) {
// If provided an `Object`, return an equivalent primitive!
return val.valueOf();
}
ctor = typedArrays[ name ];
if ( ctor ) {
return ctor( val );
}
// Class instances...
if (
name !== 'array' &&
name !== 'object'
) {
// Cloning requires ES5 or higher...
if ( typeof Object.freeze === 'function' ) {
return cloneInstance( val );
}
return {};
}
// Arrays and plain objects...
keys = objectKeys( val );
if ( level > 0 ) {
parent = name;
for ( j = 0; j < keys.length; j++ ) {
key = keys[ j ];
x = val[ key ];
// Primitive, Buffer, special class instance...
name = typeOf( x );
if (
typeof x !== 'object' ||
x === null ||
(
name !== 'array' &&
name !== 'object'
) ||
isBuffer( x )
) {
if ( parent === 'object' ) {
desc = propertyDescriptor( val, key );
if ( hasOwnProp( desc, 'value' ) ) {
desc.value = deepCopy( x );
}
defineProperty( copy, key, desc );
} else {
copy[ key ] = deepCopy( x );
}
continue;
}
// Circular reference...
i = indexOf( cache, x );
if ( i !== -1 ) {
copy[ key ] = refs[ i ];
continue;
}
// Plain array or object...
ref = ( isArray( x ) ) ? new Array( x.length ) : {};
cache.push( x );
refs.push( ref );
if ( parent === 'array' ) {
copy[ key ] = deepCopy( x, ref, cache, refs, level );
} else {
desc = propertyDescriptor( val, key );
if ( hasOwnProp( desc, 'value' ) ) {
desc.value = deepCopy( x, ref, cache, refs, level );
}
defineProperty( copy, key, desc );
}
}
} else if ( name === 'array' ) {
for ( j = 0; j < keys.length; j++ ) {
key = keys[ j ];
copy[ key ] = val[ key ];
}
} else {
for ( j = 0; j < keys.length; j++ ) {
key = keys[ j ];
desc = propertyDescriptor( val, key );
defineProperty( copy, key, desc );
}
}
if ( !Object.isExtensible( val ) ) {
Object.preventExtensions( copy );
}
if ( Object.isSealed( val ) ) {
Object.seal( copy );
}
if ( Object.isFrozen( val ) ) {
Object.freeze( copy );
}
return copy;
}
// EXPORTS //
module.exports = deepCopy;
},{"./typed_arrays.js":294,"@stdlib/assert/has-own-property":46,"@stdlib/assert/is-array":70,"@stdlib/assert/is-buffer":79,"@stdlib/assert/is-error":87,"@stdlib/buffer/from-buffer":216,"@stdlib/utils/define-property":302,"@stdlib/utils/get-prototype-of":312,"@stdlib/utils/index-of":322,"@stdlib/utils/keys":339,"@stdlib/utils/property-descriptor":361,"@stdlib/utils/property-names":365,"@stdlib/utils/regexp-from-string":368,"@stdlib/utils/type-of":373}],293:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Copy or deep clone a value to an arbitrary depth.
*
* @module @stdlib/utils/copy
*
* @example
* var copy = require( '@stdlib/utils/copy' );
*
* var out = copy( 'beep' );
* // returns 'beep'
*
* @example
* var copy = require( '@stdlib/utils/copy' );
*
* var value = [
* {
* 'a': 1,
* 'b': true,
* 'c': [ 1, 2, 3 ]
* }
* ];
* var out = copy( value );
* // returns [ {'a': 1, 'b': true, 'c': [ 1, 2, 3 ] } ]
*
* var bool = ( value[0].c === out[0].c );
* // returns false
*/
// MODULES //
var copy = require( './copy.js' );
// EXPORTS //
module.exports = copy;
},{"./copy.js":291}],294:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var Int8Array = require( '@stdlib/array/int8' );
var Uint8Array = require( '@stdlib/array/uint8' );
var Uint8ClampedArray = require( '@stdlib/array/uint8c' );
var Int16Array = require( '@stdlib/array/int16' );
var Uint16Array = require( '@stdlib/array/uint16' );
var Int32Array = require( '@stdlib/array/int32' );
var Uint32Array = require( '@stdlib/array/uint32' );
var Float32Array = require( '@stdlib/array/float32' );
var Float64Array = require( '@stdlib/array/float64' );
// VARIABLES //
var hash;
// FUNCTIONS //
/**
* Copies an `Int8Array`.
*
* @private
* @param {Int8Array} arr - array to copy
* @returns {Int8Array} new array
*/
function int8array( arr ) {
return new Int8Array( arr );
}
/**
* Copies a `Uint8Array`.
*
* @private
* @param {Uint8Array} arr - array to copy
* @returns {Uint8Array} new array
*/
function uint8array( arr ) {
return new Uint8Array( arr );
}
/**
* Copies a `Uint8ClampedArray`.
*
* @private
* @param {Uint8ClampedArray} arr - array to copy
* @returns {Uint8ClampedArray} new array
*/
function uint8clampedarray( arr ) {
return new Uint8ClampedArray( arr );
}
/**
* Copies an `Int16Array`.
*
* @private
* @param {Int16Array} arr - array to copy
* @returns {Int16Array} new array
*/
function int16array( arr ) {
return new Int16Array( arr );
}
/**
* Copies a `Uint16Array`.
*
* @private
* @param {Uint16Array} arr - array to copy
* @returns {Uint16Array} new array
*/
function uint16array( arr ) {
return new Uint16Array( arr );
}
/**
* Copies an `Int32Array`.
*
* @private
* @param {Int32Array} arr - array to copy
* @returns {Int32Array} new array
*/
function int32array( arr ) {
return new Int32Array( arr );
}
/**
* Copies a `Uint32Array`.
*
* @private
* @param {Uint32Array} arr - array to copy
* @returns {Uint32Array} new array
*/
function uint32array( arr ) {
return new Uint32Array( arr );
}
/**
* Copies a `Float32Array`.
*
* @private
* @param {Float32Array} arr - array to copy
* @returns {Float32Array} new array
*/
function float32array( arr ) {
return new Float32Array( arr );
}
/**
* Copies a `Float64Array`.
*
* @private
* @param {Float64Array} arr - array to copy
* @returns {Float64Array} new array
*/
function float64array( arr ) {
return new Float64Array( arr );
}
/**
* Returns a hash of functions for copying typed arrays.
*
* @private
* @returns {Object} function hash
*/
function typedarrays() {
var out = {
'int8array': int8array,
'uint8array': uint8array,
'uint8clampedarray': uint8clampedarray,
'int16array': int16array,
'uint16array': uint16array,
'int32array': int32array,
'uint32array': uint32array,
'float32array': float32array,
'float64array': float64array
};
return out;
}
// MAIN //
hash = typedarrays();
// EXPORTS //
module.exports = hash;
},{"@stdlib/array/float32":2,"@stdlib/array/float64":5,"@stdlib/array/int16":7,"@stdlib/array/int32":10,"@stdlib/array/int8":13,"@stdlib/array/uint16":16,"@stdlib/array/uint32":19,"@stdlib/array/uint8":22,"@stdlib/array/uint8c":25}],295:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Define a non-enumerable read-only accessor.
*
* @module @stdlib/utils/define-nonenumerable-read-only-accessor
*
* @example
* var setNonEnumerableReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' );
*
* function getter() {
* return 'bar';
* }
*
* var obj = {};
*
* setNonEnumerableReadOnlyAccessor( obj, 'foo', getter );
*
* try {
* obj.foo = 'boop';
* } catch ( err ) {
* console.error( err.message );
* }
*/
// MODULES //
var setNonEnumerableReadOnlyAccessor = require( './main.js' ); // eslint-disable-line id-length
// EXPORTS //
module.exports = setNonEnumerableReadOnlyAccessor;
},{"./main.js":296}],296:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var defineProperty = require( '@stdlib/utils/define-property' );
// MAIN //
/**
* Defines a non-enumerable read-only accessor.
*
* @param {Object} obj - object on which to define the property
* @param {(string|symbol)} prop - property name
* @param {Function} getter - accessor
*
* @example
* function getter() {
* return 'bar';
* }
*
* var obj = {};
*
* setNonEnumerableReadOnlyAccessor( obj, 'foo', getter );
*
* try {
* obj.foo = 'boop';
* } catch ( err ) {
* console.error( err.message );
* }
*/
function setNonEnumerableReadOnlyAccessor( obj, prop, getter ) { // eslint-disable-line id-length
defineProperty( obj, prop, {
'configurable': false,
'enumerable': false,
'get': getter
});
}
// EXPORTS //
module.exports = setNonEnumerableReadOnlyAccessor;
},{"@stdlib/utils/define-property":302}],297:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Define a non-enumerable read-only property.
*
* @module @stdlib/utils/define-nonenumerable-read-only-property
*
* @example
* var setNonEnumerableReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
*
* var obj = {};
*
* setNonEnumerableReadOnly( obj, 'foo', 'bar' );
*
* try {
* obj.foo = 'boop';
* } catch ( err ) {
* console.error( err.message );
* }
*/
// MODULES //
var setNonEnumerableReadOnly = require( './main.js' );
// EXPORTS //
module.exports = setNonEnumerableReadOnly;
},{"./main.js":298}],298:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var defineProperty = require( '@stdlib/utils/define-property' );
// MAIN //
/**
* Defines a non-enumerable read-only property.
*
* @param {Object} obj - object on which to define the property
* @param {(string|symbol)} prop - property name
* @param {*} value - value to set
*
* @example
* var obj = {};
*
* setNonEnumerableReadOnly( obj, 'foo', 'bar' );
*
* try {
* obj.foo = 'boop';
* } catch ( err ) {
* console.error( err.message );
* }
*/
function setNonEnumerableReadOnly( obj, prop, value ) {
defineProperty( obj, prop, {
'configurable': false,
'enumerable': false,
'writable': false,
'value': value
});
}
// EXPORTS //
module.exports = setNonEnumerableReadOnly;
},{"@stdlib/utils/define-property":302}],299:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
/**
* Defines (or modifies) an object property.
*
* ## Notes
*
* - Property descriptors come in two flavors: **data descriptors** and **accessor descriptors**. A data descriptor is a property that has a value, which may or may not be writable. An accessor descriptor is a property described by a getter-setter function pair. A descriptor must be one of these two flavors and cannot be both.
*
* @name defineProperty
* @type {Function}
* @param {Object} obj - object on which to define the property
* @param {(string|symbol)} prop - property name
* @param {Object} descriptor - property descriptor
* @param {boolean} [descriptor.configurable=false] - boolean indicating if property descriptor can be changed and if the property can be deleted from the provided object
* @param {boolean} [descriptor.enumerable=false] - boolean indicating if the property shows up when enumerating object properties
* @param {boolean} [descriptor.writable=false] - boolean indicating if the value associated with the property can be changed with an assignment operator
* @param {*} [descriptor.value] - property value
* @param {(Function|void)} [descriptor.get=undefined] - function which serves as a getter for the property, or, if no getter, undefined. When the property is accessed, a getter function is called without arguments and with the `this` context set to the object through which the property is accessed (which may not be the object on which the property is defined due to inheritance). The return value will be used as the property value.
* @param {(Function|void)} [descriptor.set=undefined] - function which serves as a setter for the property, or, if no setter, undefined. When assigning a property value, a setter function is called with one argument (the value being assigned to the property) and with the `this` context set to the object through which the property is assigned.
* @throws {TypeError} first argument must be an object
* @throws {TypeError} third argument must be an object
* @throws {Error} property descriptor cannot have both a value and a setter and/or getter
* @returns {Object} object with added property
*
* @example
* var obj = {};
*
* defineProperty( obj, 'foo', {
* 'value': 'bar'
* });
*
* var str = obj.foo;
* // returns 'bar'
*/
var defineProperty = Object.defineProperty;
// EXPORTS //
module.exports = defineProperty;
},{}],300:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Object.defineProperty === 'function' ) ? Object.defineProperty : null;
// EXPORTS //
module.exports = main;
},{}],301:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var defineProperty = require( './define_property.js' );
// MAIN //
/**
* Tests for `Object.defineProperty` support.
*
* @private
* @returns {boolean} boolean indicating if an environment has `Object.defineProperty` support
*
* @example
* var bool = hasDefinePropertySupport();
* // returns <boolean>
*/
function hasDefinePropertySupport() {
// Test basic support...
try {
defineProperty( {}, 'x', {} );
return true;
} catch ( err ) { // eslint-disable-line no-unused-vars
return false;
}
}
// EXPORTS //
module.exports = hasDefinePropertySupport;
},{"./define_property.js":300}],302:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Define (or modify) an object property.
*
* @module @stdlib/utils/define-property
*
* @example
* var defineProperty = require( '@stdlib/utils/define-property' );
*
* var obj = {};
* defineProperty( obj, 'foo', {
* 'value': 'bar',
* 'writable': false,
* 'configurable': false,
* 'enumerable': false
* });
* obj.foo = 'boop'; // => throws
*/
// MODULES //
var hasDefinePropertySupport = require( './has_define_property_support.js' );
var builtin = require( './builtin.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var defineProperty;
if ( hasDefinePropertySupport() ) {
defineProperty = builtin;
} else {
defineProperty = polyfill;
}
// EXPORTS //
module.exports = defineProperty;
},{"./builtin.js":299,"./has_define_property_support.js":301,"./polyfill.js":303}],303:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
/* eslint-disable no-underscore-dangle, no-proto */
'use strict';
// VARIABLES //
var objectProtoype = Object.prototype;
var toStr = objectProtoype.toString;
var defineGetter = objectProtoype.__defineGetter__;
var defineSetter = objectProtoype.__defineSetter__;
var lookupGetter = objectProtoype.__lookupGetter__;
var lookupSetter = objectProtoype.__lookupSetter__;
// MAIN //
/**
* Defines (or modifies) an object property.
*
* ## Notes
*
* - Property descriptors come in two flavors: **data descriptors** and **accessor descriptors**. A data descriptor is a property that has a value, which may or may not be writable. An accessor descriptor is a property described by a getter-setter function pair. A descriptor must be one of these two flavors and cannot be both.
*
* @param {Object} obj - object on which to define the property
* @param {string} prop - property name
* @param {Object} descriptor - property descriptor
* @param {boolean} [descriptor.configurable=false] - boolean indicating if property descriptor can be changed and if the property can be deleted from the provided object
* @param {boolean} [descriptor.enumerable=false] - boolean indicating if the property shows up when enumerating object properties
* @param {boolean} [descriptor.writable=false] - boolean indicating if the value associated with the property can be changed with an assignment operator
* @param {*} [descriptor.value] - property value
* @param {(Function|void)} [descriptor.get=undefined] - function which serves as a getter for the property, or, if no getter, undefined. When the property is accessed, a getter function is called without arguments and with the `this` context set to the object through which the property is accessed (which may not be the object on which the property is defined due to inheritance). The return value will be used as the property value.
* @param {(Function|void)} [descriptor.set=undefined] - function which serves as a setter for the property, or, if no setter, undefined. When assigning a property value, a setter function is called with one argument (the value being assigned to the property) and with the `this` context set to the object through which the property is assigned.
* @throws {TypeError} first argument must be an object
* @throws {TypeError} third argument must be an object
* @throws {Error} property descriptor cannot have both a value and a setter and/or getter
* @returns {Object} object with added property
*
* @example
* var obj = {};
*
* defineProperty( obj, 'foo', {
* 'value': 'bar'
* });
*
* var str = obj.foo;
* // returns 'bar'
*/
function defineProperty( obj, prop, descriptor ) {
var prototype;
var hasValue;
var hasGet;
var hasSet;
if ( typeof obj !== 'object' || obj === null || toStr.call( obj ) === '[object Array]' ) {
throw new TypeError( 'invalid argument. First argument must be an object. Value: `' + obj + '`.' );
}
if ( typeof descriptor !== 'object' || descriptor === null || toStr.call( descriptor ) === '[object Array]' ) {
throw new TypeError( 'invalid argument. Property descriptor must be an object. Value: `' + descriptor + '`.' );
}
hasValue = ( 'value' in descriptor );
if ( hasValue ) {
if (
lookupGetter.call( obj, prop ) ||
lookupSetter.call( obj, prop )
) {
// Override `__proto__` to avoid touching inherited accessors:
prototype = obj.__proto__;
obj.__proto__ = objectProtoype;
// Delete property as existing getters/setters prevent assigning value to specified property:
delete obj[ prop ];
obj[ prop ] = descriptor.value;
// Restore original prototype:
obj.__proto__ = prototype;
} else {
obj[ prop ] = descriptor.value;
}
}
hasGet = ( 'get' in descriptor );
hasSet = ( 'set' in descriptor );
if ( hasValue && ( hasGet || hasSet ) ) {
throw new Error( 'invalid argument. Cannot specify one or more accessors and a value or writable attribute in the property descriptor.' );
}
if ( hasGet && defineGetter ) {
defineGetter.call( obj, prop, descriptor.get );
}
if ( hasSet && defineSetter ) {
defineSetter.call( obj, prop, descriptor.set );
}
return obj;
}
// EXPORTS //
module.exports = defineProperty;
},{}],304:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Escape a regular expression string or pattern.
*
* @module @stdlib/utils/escape-regexp-string
*
* @example
* var rescape = require( '@stdlib/utils/escape-regexp-string' );
*
* var str = rescape( '[A-Z]*' );
* // returns '\\[A\\-Z\\]\\*'
*/
// MODULES //
var rescape = require( './main.js' );
// EXPORTS //
module.exports = rescape;
},{"./main.js":305}],305:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
// VARIABLES //
var RE_CHARS = /[-\/\\^$*+?.()|[\]{}]/g; // eslint-disable-line no-useless-escape
// MAIN //
/**
* Escapes a regular expression string.
*
* @param {string} str - regular expression string
* @throws {TypeError} first argument must be a string primitive
* @returns {string} escaped string
*
* @example
* var str = rescape( '[A-Z]*' );
* // returns '\\[A\\-Z\\]\\*'
*/
function rescape( str ) {
var len;
var s;
var i;
if ( !isString( str ) ) {
throw new TypeError( 'invalid argument. Must provide a regular expression string. Value: `' + str + '`.' );
}
// Check if the string starts with a forward slash...
if ( str[ 0 ] === '/' ) {
// Find the last forward slash...
len = str.length;
for ( i = len-1; i >= 0; i-- ) {
if ( str[ i ] === '/' ) {
break;
}
}
}
// If we searched the string to no avail or if the first letter is not `/`, assume that the string is not of the form `/[...]/[guimy]`:
if ( i === void 0 || i <= 0 ) {
return str.replace( RE_CHARS, '\\$&' );
}
// We need to de-construct the string...
s = str.substring( 1, i );
// Only escape the characters between the `/`:
s = s.replace( RE_CHARS, '\\$&' );
// Reassemble:
str = str[ 0 ] + s + str.substring( i );
return str;
}
// EXPORTS //
module.exports = rescape;
},{"@stdlib/assert/is-string":149}],306:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var bench = require( '@stdlib/bench' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var pkg = require( './../package.json' ).name;
var everyBy = require( './../lib' );
// MAIN //
bench( pkg, function benchmark( b ) {
var bool;
var arr;
var i;
function predicate( v ) {
return !isnan( v );
}
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
arr = [ i, i+1, i+2, i+3, i+4 ];
bool = everyBy( arr, predicate );
if ( !isBoolean( bool ) ) {
b.fail( 'should return a boolean' );
}
}
b.toc();
if ( !isBoolean( bool ) ) {
b.fail( 'should return a boolean' );
}
b.pass( 'benchmark finished' );
b.end();
});
bench( pkg+'::built-in', function benchmark( b ) {
var bool;
var arr;
var i;
function predicate( v ) {
return !isnan( v );
}
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
arr = [ i, i+1, i+2, i+3, i+4 ];
bool = arr.every( predicate );
if ( !isBoolean( bool ) ) {
b.fail( 'should return a boolean' );
}
}
b.toc();
if ( !isBoolean( bool ) ) {
b.fail( 'should return a boolean' );
}
b.pass( 'benchmark finished' );
b.end();
});
bench( pkg+'::loop', function benchmark( b ) {
var bool;
var arr;
var i;
var j;
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
arr = [ i, i+1, i+2, i+3, i+4 ];
bool = true;
for ( j = 0; j < arr.length; j++ ) {
if ( isnan( arr[ j ] ) ) {
bool = false;
break;
}
}
if ( !isBoolean( bool ) ) {
b.fail( 'should be a boolean' );
}
}
b.toc();
if ( !isBoolean( bool ) ) {
b.fail( 'should be a boolean' );
}
b.pass( 'benchmark finished' );
b.end();
});
},{"./../lib":308,"./../package.json":309,"@stdlib/assert/is-boolean":72,"@stdlib/bench":211,"@stdlib/math/base/assert/is-nan":239}],307:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isCollection = require( '@stdlib/assert/is-collection' );
var isFunction = require( '@stdlib/assert/is-function' );
// MAIN //
/**
* Tests whether all elements in a collection pass a test implemented by a predicate function.
*
* @param {Collection} collection - input collection
* @param {Function} predicate - test function
* @param {*} [thisArg] - execution context
* @throws {TypeError} first argument must be a collection
* @throws {TypeError} second argument must be a function
* @returns {boolean} boolean indicating whether all elements pass a test
*
* @example
* function isPositive( v ) {
* return ( v > 0 );
* }
*
* var arr = [ 1, 2, 3, 4 ];
*
* var bool = everyBy( arr, isPositive );
* // returns true
*/
function everyBy( collection, predicate, thisArg ) {
var out;
var len;
var i;
if ( !isCollection( collection ) ) {
throw new TypeError( 'invalid argument. First argument must be a collection. Value: `'+collection+'`.' );
}
if ( !isFunction( predicate ) ) {
throw new TypeError( 'invalid argument. Second argument must be a function. Value: `'+predicate+'`.' );
}
len = collection.length;
for ( i = 0; i < len; i++ ) {
out = predicate.call( thisArg, collection[ i ], i, collection );
if ( !out ) {
return false;
}
// Account for dynamically resizing a collection:
len = collection.length;
}
return true;
}
// EXPORTS //
module.exports = everyBy;
},{"@stdlib/assert/is-collection":81,"@stdlib/assert/is-function":93}],308:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Test whether all elements in a collection pass a test implemented by a predicate function.
*
* @module @stdlib/utils/every-by
*
* @example
* var every = require( '@stdlib/utils/every-by' );
*
* function isPositive( v ) {
* return ( v > 0 );
* }
*
* var arr = [ 1, 2, 3, 4 ];
*
* var bool = everyBy( arr, isPositive );
* // returns true
*/
// MODULES //
var everyBy = require( './every_by.js' );
// EXPORTS //
module.exports = everyBy;
},{"./every_by.js":307}],309:[function(require,module,exports){
module.exports={
"name": "@stdlib/utils/every-by",
"version": "0.0.0",
"description": "Test whether all elements in a collection pass a test implemented by a predicate function.",
"license": "Apache-2.0",
"author": {
"name": "The Stdlib Authors",
"url": "https://github.com/stdlib-js/stdlib/graphs/contributors"
},
"contributors": [
{
"name": "The Stdlib Authors",
"url": "https://github.com/stdlib-js/stdlib/graphs/contributors"
}
],
"main": "./lib",
"directories": {
"benchmark": "./benchmark",
"doc": "./docs",
"example": "./examples",
"lib": "./lib",
"test": "./test"
},
"types": "./docs/types",
"scripts": {},
"homepage": "https://github.com/stdlib-js/stdlib",
"repository": {
"type": "git",
"url": "git://github.com/stdlib-js/stdlib.git"
},
"bugs": {
"url": "https://github.com/stdlib-js/stdlib/issues"
},
"dependencies": {},
"devDependencies": {},
"engines": {
"node": ">=0.10.0",
"npm": ">2.7.0"
},
"os": [
"aix",
"darwin",
"freebsd",
"linux",
"macos",
"openbsd",
"sunos",
"win32",
"windows"
],
"keywords": [
"stdlib",
"stdutils",
"stdutil",
"utilities",
"utility",
"utils",
"util",
"test",
"predicate",
"every",
"all",
"array.every",
"iterate",
"collection",
"array-like",
"validate"
]
}
},{}],310:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isFunction = require( '@stdlib/assert/is-function' );
var builtin = require( './native.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var getProto;
if ( isFunction( Object.getPrototypeOf ) ) {
getProto = builtin;
} else {
getProto = polyfill;
}
// EXPORTS //
module.exports = getProto;
},{"./native.js":313,"./polyfill.js":314,"@stdlib/assert/is-function":93}],311:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var getProto = require( './detect.js' );
// MAIN //
/**
* Returns the prototype of a provided object.
*
* @param {*} value - input value
* @returns {(Object|null)} prototype
*
* @example
* var proto = getPrototypeOf( {} );
* // returns {}
*/
function getPrototypeOf( value ) {
if (
value === null ||
value === void 0
) {
return null;
}
// In order to ensure consistent ES5/ES6 behavior, cast input value to an object (strings, numbers, booleans); ES5 `Object.getPrototypeOf` throws when provided primitives and ES6 `Object.getPrototypeOf` casts:
value = Object( value );
return getProto( value );
}
// EXPORTS //
module.exports = getPrototypeOf;
},{"./detect.js":310}],312:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Return the prototype of a provided object.
*
* @module @stdlib/utils/get-prototype-of
*
* @example
* var getPrototype = require( '@stdlib/utils/get-prototype-of' );
*
* var proto = getPrototype( {} );
* // returns {}
*/
// MODULES //
var getPrototype = require( './get_prototype_of.js' );
// EXPORTS //
module.exports = getPrototype;
},{"./get_prototype_of.js":311}],313:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
var getProto = Object.getPrototypeOf;
// EXPORTS //
module.exports = getProto;
},{}],314:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
var getProto = require( './proto.js' );
// MAIN //
/**
* Returns the prototype of a provided object.
*
* @private
* @param {Object} obj - input object
* @returns {(Object|null)} prototype
*/
function getPrototypeOf( obj ) {
var proto = getProto( obj );
if ( proto || proto === null ) {
return proto;
}
if ( nativeClass( obj.constructor ) === '[object Function]' ) {
// May break if the constructor has been tampered with...
return obj.constructor.prototype;
}
if ( obj instanceof Object ) {
return Object.prototype;
}
// Return `null` for objects created via `Object.create( null )`. Also return `null` for cross-realm objects on browsers that lack `__proto__` support, such as IE < 11.
return null;
}
// EXPORTS //
module.exports = getPrototypeOf;
},{"./proto.js":315,"@stdlib/utils/native-class":346}],315:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Returns the value of the `__proto__` property.
*
* @private
* @param {Object} obj - input object
* @returns {*} value of `__proto__` property
*/
function getProto( obj ) {
// eslint-disable-next-line no-proto
return obj.__proto__;
}
// EXPORTS //
module.exports = getProto;
},{}],316:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
/**
* Returns the global object using code generation.
*
* @private
* @returns {Object} global object
*/
function getGlobal() {
return new Function( 'return this;' )(); // eslint-disable-line no-new-func
}
// EXPORTS //
module.exports = getGlobal;
},{}],317:[function(require,module,exports){
(function (global){(function (){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
var obj = ( typeof global === 'object' ) ? global : null;
// EXPORTS //
module.exports = obj;
}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],318:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Return the global object.
*
* @module @stdlib/utils/global
*
* @example
* var getGlobal = require( '@stdlib/utils/global' );
*
* var g = getGlobal();
* // returns {...}
*/
// MODULES //
var getGlobal = require( './main.js' );
// EXPORTS //
module.exports = getGlobal;
},{"./main.js":319}],319:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var getThis = require( './codegen.js' );
var Self = require( './self.js' );
var Win = require( './window.js' );
var Global = require( './global.js' );
// MAIN //
/**
* Returns the global object.
*
* ## Notes
*
* - Using code generation is the **most** reliable way to resolve the global object; however, doing so is likely to violate content security policies (CSPs) in, e.g., Chrome Apps and elsewhere.
*
* @param {boolean} [codegen=false] - boolean indicating whether to use code generation to resolve the global object
* @throws {TypeError} must provide a boolean
* @throws {Error} unable to resolve global object
* @returns {Object} global object
*
* @example
* var g = getGlobal();
* // returns {...}
*/
function getGlobal( codegen ) {
if ( arguments.length ) {
if ( !isBoolean( codegen ) ) {
throw new TypeError( 'invalid argument. Must provide a boolean primitive. Value: `'+codegen+'`.' );
}
if ( codegen ) {
return getThis();
}
// Fall through...
}
// Case: browsers and web workers
if ( Self ) {
return Self;
}
// Case: browsers
if ( Win ) {
return Win;
}
// Case: Node.js
if ( Global ) {
return Global;
}
// Case: unknown
throw new Error( 'unexpected error. Unable to resolve global object.' );
}
// EXPORTS //
module.exports = getGlobal;
},{"./codegen.js":316,"./global.js":317,"./self.js":320,"./window.js":321,"@stdlib/assert/is-boolean":72}],320:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
var obj = ( typeof self === 'object' ) ? self : null;
// EXPORTS //
module.exports = obj;
},{}],321:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
var obj = ( typeof window === 'object' ) ? window : null;
// EXPORTS //
module.exports = obj;
},{}],322:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Return the first index at which a given element can be found.
*
* @module @stdlib/utils/index-of
*
* @example
* var indexOf = require( '@stdlib/utils/index-of' );
*
* var arr = [ 4, 3, 2, 1 ];
* var idx = indexOf( arr, 3 );
* // returns 1
*
* arr = [ 4, 3, 2, 1 ];
* idx = indexOf( arr, 5 );
* // returns -1
*
* // Using a `fromIndex`:
* arr = [ 1, 2, 3, 4, 5, 2, 6 ];
* idx = indexOf( arr, 2, 3 );
* // returns 5
*
* // `fromIndex` which exceeds `array` length:
* arr = [ 1, 2, 3, 4, 2, 5 ];
* idx = indexOf( arr, 2, 10 );
* // returns -1
*
* // Negative `fromIndex`:
* arr = [ 1, 2, 3, 4, 5, 2, 6, 2 ];
* idx = indexOf( arr, 2, -4 );
* // returns 5
*
* idx = indexOf( arr, 2, -1 );
* // returns 7
*
* // Negative `fromIndex` exceeding input `array` length:
* arr = [ 1, 2, 3, 4, 5, 2, 6 ];
* idx = indexOf( arr, 2, -10 );
* // returns 1
*
* // Array-like objects:
* var str = 'bebop';
* idx = indexOf( str, 'o' );
* // returns 3
*/
// MODULES //
var indexOf = require( './index_of.js' );
// EXPORTS //
module.exports = indexOf;
},{"./index_of.js":323}],323:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isnan = require( '@stdlib/assert/is-nan' );
var isCollection = require( '@stdlib/assert/is-collection' );
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive;
// MAIN //
/**
* Returns the first index at which a given element can be found.
*
* @param {ArrayLike} arr - array-like object
* @param {*} searchElement - element to find
* @param {integer} [fromIndex] - starting index (if negative, the start index is determined relative to last element)
* @throws {TypeError} must provide an array-like object
* @throws {TypeError} `fromIndex` must be an integer
* @returns {integer} index or -1
*
* @example
* var arr = [ 4, 3, 2, 1 ];
* var idx = indexOf( arr, 3 );
* // returns 1
*
* @example
* var arr = [ 4, 3, 2, 1 ];
* var idx = indexOf( arr, 5 );
* // returns -1
*
* @example
* // Using a `fromIndex`:
* var arr = [ 1, 2, 3, 4, 5, 2, 6 ];
* var idx = indexOf( arr, 2, 3 );
* // returns 5
*
* @example
* // `fromIndex` which exceeds `array` length:
* var arr = [ 1, 2, 3, 4, 2, 5 ];
* var idx = indexOf( arr, 2, 10 );
* // returns -1
*
* @example
* // Negative `fromIndex`:
* var arr = [ 1, 2, 3, 4, 5, 2, 6, 2 ];
* var idx = indexOf( arr, 2, -4 );
* // returns 5
*
* idx = indexOf( arr, 2, -1 );
* // returns 7
*
* @example
* // Negative `fromIndex` exceeding input `array` length:
* var arr = [ 1, 2, 3, 4, 5, 2, 6 ];
* var idx = indexOf( arr, 2, -10 );
* // returns 1
*
* @example
* // Array-like objects:
* var str = 'bebop';
* var idx = indexOf( str, 'o' );
* // returns 3
*/
function indexOf( arr, searchElement, fromIndex ) {
var len;
var i;
if ( !isCollection( arr ) && !isString( arr ) ) {
throw new TypeError( 'invalid argument. First argument must be an array-like object. Value: `' + arr + '`.' );
}
len = arr.length;
if ( len === 0 ) {
return -1;
}
if ( arguments.length === 3 ) {
if ( !isInteger( fromIndex ) ) {
throw new TypeError( 'invalid argument. `fromIndex` must be an integer. Value: `' + fromIndex + '`.' );
}
if ( fromIndex >= 0 ) {
if ( fromIndex >= len ) {
return -1;
}
i = fromIndex;
} else {
i = len + fromIndex;
if ( i < 0 ) {
i = 0;
}
}
} else {
i = 0;
}
// Check for `NaN`...
if ( isnan( searchElement ) ) {
for ( ; i < len; i++ ) {
if ( isnan( arr[i] ) ) {
return i;
}
}
} else {
for ( ; i < len; i++ ) {
if ( arr[ i ] === searchElement ) {
return i;
}
}
}
return -1;
}
// EXPORTS //
module.exports = indexOf;
},{"@stdlib/assert/is-collection":81,"@stdlib/assert/is-integer":101,"@stdlib/assert/is-nan":109,"@stdlib/assert/is-string":149}],324:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var builtin = require( './native.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var createObject;
if ( typeof builtin === 'function' ) {
createObject = builtin;
} else {
createObject = polyfill;
}
// EXPORTS //
module.exports = createObject;
},{"./native.js":327,"./polyfill.js":328}],325:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Implement prototypical inheritance by replacing the prototype of one constructor with the prototype of another constructor.
*
* @module @stdlib/utils/inherit
*
* @example
* var inherit = require( '@stdlib/utils/inherit' );
*
* function Foo() {
* return this;
* }
* Foo.prototype.beep = function beep() {
* return 'boop';
* };
*
* function Bar() {
* Foo.call( this );
* return this;
* }
* inherit( Bar, Foo );
*
* var bar = new Bar();
* var v = bar.beep();
* // returns 'boop'
*/
// MODULES //
var inherit = require( './inherit.js' );
// EXPORTS //
module.exports = inherit;
},{"./inherit.js":326}],326:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var defineProperty = require( '@stdlib/utils/define-property' );
var validate = require( './validate.js' );
var createObject = require( './detect.js' );
// MAIN //
/**
* Implements prototypical inheritance by replacing the prototype of one constructor with the prototype of another constructor.
*
* ## Notes
*
* - This implementation is not designed to work with ES2015/ES6 classes. For ES2015/ES6 classes, use `class` with `extends`.
* - For reference, see [node#3455](https://github.com/nodejs/node/pull/3455), [node#4179](https://github.com/nodejs/node/issues/4179), [node#3452](https://github.com/nodejs/node/issues/3452), and [node commit](https://github.com/nodejs/node/commit/29da8cf8d7ab8f66b9091ab22664067d4468461e#diff-3deb3f32958bb937ae05c6f3e4abbdf5).
*
*
* @param {(Object|Function)} ctor - constructor which will inherit
* @param {(Object|Function)} superCtor - super (parent) constructor
* @throws {TypeError} first argument must be either an object or a function which can inherit
* @throws {TypeError} second argument must be either an object or a function from which a constructor can inherit
* @throws {TypeError} second argument must have an inheritable prototype
* @returns {(Object|Function)} child constructor
*
* @example
* function Foo() {
* return this;
* }
* Foo.prototype.beep = function beep() {
* return 'boop';
* };
*
* function Bar() {
* Foo.call( this );
* return this;
* }
* inherit( Bar, Foo );
*
* var bar = new Bar();
* var v = bar.beep();
* // returns 'boop'
*/
function inherit( ctor, superCtor ) {
var err = validate( ctor );
if ( err ) {
throw err;
}
err = validate( superCtor );
if ( err ) {
throw err;
}
if ( typeof superCtor.prototype === 'undefined' ) {
throw new TypeError( 'invalid argument. Second argument must have a prototype from which another object can inherit. Value: `'+superCtor.prototype+'`.' );
}
// Create a prototype which inherits from the parent prototype:
ctor.prototype = createObject( superCtor.prototype );
// Set the constructor to refer to the child constructor:
defineProperty( ctor.prototype, 'constructor', {
'configurable': true,
'enumerable': false,
'writable': true,
'value': ctor
});
return ctor;
}
// EXPORTS //
module.exports = inherit;
},{"./detect.js":324,"./validate.js":329,"@stdlib/utils/define-property":302}],327:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// EXPORTS //
module.exports = Object.create;
},{}],328:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// FUNCTIONS //
/**
* Dummy constructor.
*
* @private
*/
function Ctor() {
// Empty...
}
// MAIN //
/**
* An `Object.create` shim for older JavaScript engines.
*
* @private
* @param {Object} proto - prototype
* @returns {Object} created object
*
* @example
* var obj = createObject( Object.prototype );
* // returns {}
*/
function createObject( proto ) {
Ctor.prototype = proto;
return new Ctor();
}
// EXPORTS //
module.exports = createObject;
},{}],329:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Tests that a value is a valid constructor.
*
* @private
* @param {*} value - value to test
* @returns {(Error|null)} error object or null
*
* @example
* var ctor = function ctor() {};
*
* var err = validate( ctor );
* // returns null
*
* err = validate( null );
* // returns <TypeError>
*/
function validate( value ) {
var type = typeof value;
if (
value === null ||
(type !== 'object' && type !== 'function')
) {
return new TypeError( 'invalid argument. A provided constructor must be either an object (except null) or a function. Value: `'+value+'`.' );
}
return null;
}
// EXPORTS //
module.exports = validate;
},{}],330:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
/**
* Returns an array of an object's own enumerable property names.
*
* ## Notes
*
* - In contrast to the built-in `Object.keys()`, this function returns an empty array if provided `undefined` or `null`, rather than throwing an error.
*
* @private
* @param {*} value - input object
* @returns {Array} a list of own enumerable property names
*
* @example
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var k = keys( obj );
* // e.g., returns [ 'beep', 'foo' ]
*/
function keys( value ) {
return Object.keys( Object( value ) );
}
// EXPORTS //
module.exports = keys;
},{}],331:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isArguments = require( '@stdlib/assert/is-arguments' );
var builtin = require( './builtin.js' );
// VARIABLES //
var slice = Array.prototype.slice;
// MAIN //
/**
* Returns an array of an object's own enumerable property names.
*
* @private
* @param {*} value - input object
* @returns {Array} a list of own enumerable property names
*
* @example
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var k = keys( obj );
* // e.g., returns [ 'beep', 'foo' ]
*/
function keys( value ) {
if ( isArguments( value ) ) {
return builtin( slice.call( value ) );
}
return builtin( value );
}
// EXPORTS //
module.exports = keys;
},{"./builtin.js":330,"@stdlib/assert/is-arguments":65}],332:[function(require,module,exports){
module.exports=[
"console",
"external",
"frame",
"frameElement",
"frames",
"innerHeight",
"innerWidth",
"outerHeight",
"outerWidth",
"pageXOffset",
"pageYOffset",
"parent",
"scrollLeft",
"scrollTop",
"scrollX",
"scrollY",
"self",
"webkitIndexedDB",
"webkitStorageInfo",
"window"
]
},{}],333:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var keys = require( './builtin.js' );
// FUNCTIONS //
/**
* Tests the built-in `Object.keys()` implementation when provided `arguments`.
*
* @private
* @returns {boolean} boolean indicating whether the built-in implementation returns the expected number of keys
*/
function test() {
return ( keys( arguments ) || '' ).length !== 2;
}
// MAIN //
/**
* Tests whether the built-in `Object.keys()` implementation supports providing `arguments` as an input value.
*
* ## Notes
*
* - Safari 5.0 does **not** support `arguments` as an input value.
*
* @private
* @returns {boolean} boolean indicating whether a built-in implementation supports `arguments`
*/
function check() {
return test( 1, 2 );
}
// EXPORTS //
module.exports = check;
},{"./builtin.js":330}],334:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var indexOf = require( '@stdlib/utils/index-of' );
var typeOf = require( '@stdlib/utils/type-of' );
var isConstructorPrototype = require( './is_constructor_prototype.js' );
var EXCLUDED_KEYS = require( './excluded_keys.json' );
var win = require( './window.js' );
// VARIABLES //
var bool;
// FUNCTIONS //
/**
* Determines whether an environment throws when comparing to the prototype of a value's constructor (e.g., [IE9][1]).
*
* [1]: https://stackoverflow.com/questions/7688070/why-is-comparing-the-constructor-property-of-two-windows-unreliable
*
* @private
* @returns {boolean} boolean indicating whether an environment is buggy
*/
function check() {
var k;
if ( typeOf( win ) === 'undefined' ) {
return false;
}
for ( k in win ) { // eslint-disable-line guard-for-in
try {
if (
indexOf( EXCLUDED_KEYS, k ) === -1 &&
hasOwnProp( win, k ) &&
win[ k ] !== null &&
typeOf( win[ k ] ) === 'object'
) {
isConstructorPrototype( win[ k ] );
}
} catch ( err ) { // eslint-disable-line no-unused-vars
return true;
}
}
return false;
}
// MAIN //
bool = check();
// EXPORTS //
module.exports = bool;
},{"./excluded_keys.json":332,"./is_constructor_prototype.js":340,"./window.js":345,"@stdlib/assert/has-own-property":46,"@stdlib/utils/index-of":322,"@stdlib/utils/type-of":373}],335:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
var bool = ( typeof Object.keys !== 'undefined' );
// EXPORTS //
module.exports = bool;
},{}],336:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isEnumerableProperty = require( '@stdlib/assert/is-enumerable-property' );
var noop = require( '@stdlib/utils/noop' );
// MAIN //
// Note: certain environments treat an object's prototype as enumerable, which, as a matter of convention, it shouldn't be...
var bool = isEnumerableProperty( noop, 'prototype' );
// EXPORTS //
module.exports = bool;
},{"@stdlib/assert/is-enumerable-property":84,"@stdlib/utils/noop":353}],337:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isEnumerableProperty = require( '@stdlib/assert/is-enumerable-property' );
// VARIABLES //
var obj = {
'toString': null
};
// MAIN //
// Note: certain environments don't allow enumeration of overwritten properties which are considered non-enumerable...
var bool = !isEnumerableProperty( obj, 'toString' );
// EXPORTS //
module.exports = bool;
},{"@stdlib/assert/is-enumerable-property":84}],338:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
var bool = ( typeof window !== 'undefined' );
// EXPORTS //
module.exports = bool;
},{}],339:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Return an array of an object's own enumerable property names.
*
* @module @stdlib/utils/keys
*
* @example
* var keys = require( '@stdlib/utils/keys' );
*
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var k = keys( obj );
* // e.g., returns [ 'beep', 'foo' ]
*/
// MODULES //
var keys = require( './main.js' );
// EXPORTS //
module.exports = keys;
},{"./main.js":342}],340:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
/**
* Tests whether a value equals the prototype of its constructor.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value equals the prototype of its constructor
*/
function isConstructorPrototype( value ) {
return ( value.constructor && value.constructor.prototype === value );
}
// EXPORTS //
module.exports = isConstructorPrototype;
},{}],341:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var hasAutomationEqualityBug = require( './has_automation_equality_bug.js' );
var isConstructorPrototype = require( './is_constructor_prototype.js' );
var HAS_WINDOW = require( './has_window.js' );
// MAIN //
/**
* Wraps the test for constructor prototype equality to accommodate buggy environments (e.g., environments which throw when testing equality).
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value equals the prototype of its constructor
*/
function wrapper( value ) {
if ( HAS_WINDOW === false && !hasAutomationEqualityBug ) {
return isConstructorPrototype( value );
}
try {
return isConstructorPrototype( value );
} catch ( error ) { // eslint-disable-line no-unused-vars
return false;
}
}
// EXPORTS //
module.exports = wrapper;
},{"./has_automation_equality_bug.js":334,"./has_window.js":338,"./is_constructor_prototype.js":340}],342:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var hasArgumentsBug = require( './has_arguments_bug.js' );
var HAS_BUILTIN = require( './has_builtin.js' );
var builtin = require( './builtin.js' );
var wrapper = require( './builtin_wrapper.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
/**
* Returns an array of an object's own enumerable property names.
*
* @name keys
* @type {Function}
* @param {*} value - input object
* @returns {Array} a list of own enumerable property names
*
* @example
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var k = keys( obj );
* // e.g., returns [ 'beep', 'foo' ]
*/
var keys;
if ( HAS_BUILTIN ) {
if ( hasArgumentsBug() ) {
keys = wrapper;
} else {
keys = builtin;
}
} else {
keys = polyfill;
}
// EXPORTS //
module.exports = keys;
},{"./builtin.js":330,"./builtin_wrapper.js":331,"./has_arguments_bug.js":333,"./has_builtin.js":335,"./polyfill.js":344}],343:[function(require,module,exports){
module.exports=[
"toString",
"toLocaleString",
"valueOf",
"hasOwnProperty",
"isPrototypeOf",
"propertyIsEnumerable",
"constructor"
]
},{}],344:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isObjectLike = require( '@stdlib/assert/is-object-like' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isArguments = require( '@stdlib/assert/is-arguments' );
var HAS_ENUM_PROTO_BUG = require( './has_enumerable_prototype_bug.js' );
var HAS_NON_ENUM_PROPS_BUG = require( './has_non_enumerable_properties_bug.js' );
var isConstructorPrototype = require( './is_constructor_prototype_wrapper.js' );
var NON_ENUMERABLE = require( './non_enumerable.json' );
// MAIN //
/**
* Returns an array of an object's own enumerable property names.
*
* @private
* @param {*} value - input object
* @returns {Array} a list of own enumerable property names
*
* @example
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var k = keys( obj );
* // e.g., returns [ 'beep', 'foo' ]
*/
function keys( value ) {
var skipConstructor;
var skipPrototype;
var isFcn;
var out;
var k;
var p;
var i;
out = [];
if ( isArguments( value ) ) {
// Account for environments which treat `arguments` differently...
for ( i = 0; i < value.length; i++ ) {
out.push( i.toString() );
}
// Note: yes, we are precluding the `arguments` array-like object from having other enumerable properties; however, this should (1) be very rare and (2) not be encouraged (e.g., doing something like `arguments.a = 'b'`; in certain engines directly manipulating the `arguments` value results in automatic de-optimization).
return out;
}
if ( typeof value === 'string' ) {
// Account for environments which do not treat string character indices as "own" properties...
if ( value.length > 0 && !hasOwnProp( value, '0' ) ) {
for ( i = 0; i < value.length; i++ ) {
out.push( i.toString() );
}
}
} else {
isFcn = ( typeof value === 'function' );
if ( isFcn === false && !isObjectLike( value ) ) {
return out;
}
skipPrototype = ( HAS_ENUM_PROTO_BUG && isFcn );
}
for ( k in value ) {
if ( !( skipPrototype && k === 'prototype' ) && hasOwnProp( value, k ) ) {
out.push( String( k ) );
}
}
if ( HAS_NON_ENUM_PROPS_BUG ) {
skipConstructor = isConstructorPrototype( value );
for ( i = 0; i < NON_ENUMERABLE.length; i++ ) {
p = NON_ENUMERABLE[ i ];
if ( !( skipConstructor && p === 'constructor' ) && hasOwnProp( value, p ) ) {
out.push( String( p ) );
}
}
}
return out;
}
// EXPORTS //
module.exports = keys;
},{"./has_enumerable_prototype_bug.js":336,"./has_non_enumerable_properties_bug.js":337,"./is_constructor_prototype_wrapper.js":341,"./non_enumerable.json":343,"@stdlib/assert/has-own-property":46,"@stdlib/assert/is-arguments":65,"@stdlib/assert/is-object-like":134}],345:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
var w = ( typeof window === 'undefined' ) ? void 0 : window;
// EXPORTS //
module.exports = w;
},{}],346:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Return a string value indicating a specification defined classification of an object.
*
* @module @stdlib/utils/native-class
*
* @example
* var nativeClass = require( '@stdlib/utils/native-class' );
*
* var str = nativeClass( 'a' );
* // returns '[object String]'
*
* str = nativeClass( 5 );
* // returns '[object Number]'
*
* function Beep() {
* return this;
* }
* str = nativeClass( new Beep() );
* // returns '[object Object]'
*/
// MODULES //
var hasToStringTag = require( '@stdlib/assert/has-tostringtag-support' );
var builtin = require( './native_class.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var nativeClass;
if ( hasToStringTag() ) {
nativeClass = polyfill;
} else {
nativeClass = builtin;
}
// EXPORTS //
module.exports = nativeClass;
},{"./native_class.js":347,"./polyfill.js":348,"@stdlib/assert/has-tostringtag-support":50}],347:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var toStr = require( './tostring.js' );
// MAIN //
/**
* Returns a string value indicating a specification defined classification (via the internal property `[[Class]]`) of an object.
*
* @param {*} v - input value
* @returns {string} string value indicating a specification defined classification of the input value
*
* @example
* var str = nativeClass( 'a' );
* // returns '[object String]'
*
* @example
* var str = nativeClass( 5 );
* // returns '[object Number]'
*
* @example
* function Beep() {
* return this;
* }
* var str = nativeClass( new Beep() );
* // returns '[object Object]'
*/
function nativeClass( v ) {
return toStr.call( v );
}
// EXPORTS //
module.exports = nativeClass;
},{"./tostring.js":349}],348:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var toStringTag = require( './tostringtag.js' );
var toStr = require( './tostring.js' );
// MAIN //
/**
* Returns a string value indicating a specification defined classification of an object in environments supporting `Symbol.toStringTag`.
*
* @param {*} v - input value
* @returns {string} string value indicating a specification defined classification of the input value
*
* @example
* var str = nativeClass( 'a' );
* // returns '[object String]'
*
* @example
* var str = nativeClass( 5 );
* // returns '[object Number]'
*
* @example
* function Beep() {
* return this;
* }
* var str = nativeClass( new Beep() );
* // returns '[object Object]'
*/
function nativeClass( v ) {
var isOwn;
var tag;
var out;
if ( v === null || v === void 0 ) {
return toStr.call( v );
}
tag = v[ toStringTag ];
isOwn = hasOwnProp( v, toStringTag );
// Attempt to override the `toStringTag` property. For built-ins having a `Symbol.toStringTag` property (e.g., `JSON`, `Math`, etc), the `Symbol.toStringTag` property is read-only (e.g., , so we need to wrap in a `try/catch`.
try {
v[ toStringTag ] = void 0;
} catch ( err ) { // eslint-disable-line no-unused-vars
return toStr.call( v );
}
out = toStr.call( v );
if ( isOwn ) {
v[ toStringTag ] = tag;
} else {
delete v[ toStringTag ];
}
return out;
}
// EXPORTS //
module.exports = nativeClass;
},{"./tostring.js":349,"./tostringtag.js":350,"@stdlib/assert/has-own-property":46}],349:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
var toStr = Object.prototype.toString;
// EXPORTS //
module.exports = toStr;
},{}],350:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
var toStrTag = ( typeof Symbol === 'function' ) ? Symbol.toStringTag : '';
// EXPORTS //
module.exports = toStrTag;
},{}],351:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Add a callback to the "next tick queue".
*
* @module @stdlib/utils/next-tick
*
* @example
* var nextTick = require( '@stdlib/utils/next-tick' );
*
* function beep() {
* console.log( 'boop' );
* }
*
* nextTick( beep );
*/
// MODULES //
var nextTick = require( './main.js' );
// EXPORTS //
module.exports = nextTick;
},{"./main.js":352}],352:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var proc = require( 'process' );
// MAIN //
/**
* Adds a callback to the "next tick queue".
*
* ## Notes
*
* - The queue is fully drained after the current operation on the JavaScript stack runs to completion and before the event loop is allowed to continue.
*
* @param {Callback} clbk - callback
* @param {...*} [args] - arguments to provide to the callback upon invocation
*
* @example
* function beep() {
* console.log( 'boop' );
* }
*
* nextTick( beep );
*/
function nextTick( clbk ) {
var args;
var i;
args = [];
for ( i = 1; i < arguments.length; i++ ) {
args.push( arguments[ i ] );
}
proc.nextTick( wrapper );
/**
* Callback wrapper.
*
* ## Notes
*
* - The ability to provide additional arguments was added in Node.js v1.8.1. The wrapper provides support for earlier Node.js versions.
*
* @private
*/
function wrapper() {
clbk.apply( null, args );
}
}
// EXPORTS //
module.exports = nextTick;
},{"process":389}],353:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* No operation.
*
* @module @stdlib/utils/noop
*
* @example
* var noop = require( '@stdlib/utils/noop' );
*
* noop();
* // ...does nothing.
*/
// MODULES //
var noop = require( './noop.js' );
// EXPORTS //
module.exports = noop;
},{"./noop.js":354}],354:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* No operation.
*
* @example
* noop();
* // ...does nothing.
*/
function noop() {
// Empty function...
}
// EXPORTS //
module.exports = noop;
},{}],355:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Return a partial object copy excluding specified keys.
*
* @module @stdlib/utils/omit
*
* @example
* var omit = require( '@stdlib/utils/omit' );
*
* var obj1 = {
* 'a': 1,
* 'b': 2
* };
*
* var obj2 = omit( obj1, 'b' );
* // returns { 'a': 1 }
*/
// MODULES //
var omit = require( './omit.js' );
// EXPORTS //
module.exports = omit;
},{"./omit.js":356}],356:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var objectKeys = require( '@stdlib/utils/keys' );
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var isStringArray = require( '@stdlib/assert/is-string-array' ).primitives;
var indexOf = require( '@stdlib/utils/index-of' );
// MAIN //
/**
* Returns a partial object copy excluding specified keys.
*
* @param {Object} obj - source object
* @param {(string|StringArray)} keys - keys to exclude
* @throws {TypeError} first argument must be an object
* @throws {TypeError} second argument must be either a string or an array of strings
* @returns {Object} new object
*
* @example
* var obj1 = {
* 'a': 1,
* 'b': 2
* };
*
* var obj2 = omit( obj1, 'b' );
* // returns { 'a': 1 }
*/
function omit( obj, keys ) {
var ownKeys;
var out;
var key;
var i;
if ( typeof obj !== 'object' || obj === null ) {
throw new TypeError( 'invalid argument. First argument must be an object. Value: `'+obj+'`.' );
}
ownKeys = objectKeys( obj );
out = {};
if ( isString( keys ) ) {
for ( i = 0; i < ownKeys.length; i++ ) {
key = ownKeys[ i ];
if ( key !== keys ) {
out[ key ] = obj[ key ];
}
}
return out;
}
if ( isStringArray( keys ) ) {
for ( i = 0; i < ownKeys.length; i++ ) {
key = ownKeys[ i ];
if ( indexOf( keys, key ) === -1 ) {
out[ key ] = obj[ key ];
}
}
return out;
}
throw new TypeError( 'invalid argument. Second argument must be either a string primitive or an array of string primitives. Value: `'+keys+'`.' );
}
// EXPORTS //
module.exports = omit;
},{"@stdlib/assert/is-string":149,"@stdlib/assert/is-string-array":148,"@stdlib/utils/index-of":322,"@stdlib/utils/keys":339}],357:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Return a partial object copy containing only specified keys.
*
* @module @stdlib/utils/pick
*
* @example
* var pick = require( '@stdlib/utils/pick' );
*
* var obj1 = {
* 'a': 1,
* 'b': 2
* };
*
* var obj2 = pick( obj1, 'b' );
* // returns { 'b': 2 }
*/
// MODULES //
var pick = require( './pick.js' );
// EXPORTS //
module.exports = pick;
},{"./pick.js":358}],358:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var isStringArray = require( '@stdlib/assert/is-string-array' ).primitives;
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
// MAIN //
/**
* Returns a partial object copy containing only specified keys. If a key does not exist as an own property in a source object, the key is ignored.
*
* @param {Object} obj - source object
* @param {(string|StringArray)} keys - keys to copy
* @throws {TypeError} first argument must be an object
* @throws {TypeError} second argument must be either a string or an array of strings
* @returns {Object} new object
*
* @example
* var obj1 = {
* 'a': 1,
* 'b': 2
* };
*
* var obj2 = pick( obj1, 'b' );
* // returns { 'b': 2 }
*/
function pick( obj, keys ) {
var out;
var key;
var i;
if ( typeof obj !== 'object' || obj === null ) {
throw new TypeError( 'invalid argument. First argument must be an object. Value: `'+obj+'`.' );
}
out = {};
if ( isString( keys ) ) {
if ( hasOwnProp( obj, keys ) ) {
out[ keys ] = obj[ keys ];
}
return out;
}
if ( isStringArray( keys ) ) {
for ( i = 0; i < keys.length; i++ ) {
key = keys[ i ];
if ( hasOwnProp( obj, key ) ) {
out[ key ] = obj[ key ];
}
}
return out;
}
throw new TypeError( 'invalid argument. Second argument must be either a string primitive or an array of string primitives. Value: `'+keys+'`.' );
}
// EXPORTS //
module.exports = pick;
},{"@stdlib/assert/has-own-property":46,"@stdlib/assert/is-string":149,"@stdlib/assert/is-string-array":148}],359:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// VARIABLES //
var propertyDescriptor = Object.getOwnPropertyDescriptor;
// MAIN //
/**
* Returns a property descriptor for an object's own property.
*
* ## Notes
*
* - In contrast to the built-in `Object.getOwnPropertyDescriptor()`, this function returns `null` if provided `undefined` or `null`, rather than throwing an error.
* - In contrast to the built-in `Object.getOwnPropertyDescriptor()`, this function returns `null` if an object does not have a provided property, rather than `undefined`.
*
* @private
* @param {*} value - input object
* @param {(string|symbol)} property - property
* @returns {(Object|null)} property descriptor or null
*
* @example
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var desc = getOwnPropertyDescriptor( obj, 'foo' );
* // returns {'configurable':true,'enumerable':true,'writable':true,'value':3.14}
*/
function getOwnPropertyDescriptor( value, property ) {
var desc;
if ( value === null || value === void 0 ) {
return null;
}
desc = propertyDescriptor( value, property );
return ( desc === void 0 ) ? null : desc;
}
// EXPORTS //
module.exports = getOwnPropertyDescriptor;
},{}],360:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
var bool = ( typeof Object.getOwnPropertyDescriptor !== 'undefined' );
// EXPORTS //
module.exports = bool;
},{}],361:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Return a property descriptor for an object's own property.
*
* @module @stdlib/utils/property-descriptor
*
* @example
* var getOwnPropertyDescriptor = require( '@stdlib/utils/property-descriptor' );
*
* var obj = {
* 'foo': 'bar',
* 'beep': 'boop'
* };
*
* var keys = getOwnPropertyDescriptor( obj, 'foo' );
* // returns {'configurable':true,'enumerable':true,'writable':true,'value':'bar'}
*/
// MODULES //
var HAS_BUILTIN = require( './has_builtin.js' );
var builtin = require( './builtin.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var main;
if ( HAS_BUILTIN ) {
main = builtin;
} else {
main = polyfill;
}
// EXPORTS //
module.exports = main;
},{"./builtin.js":359,"./has_builtin.js":360,"./polyfill.js":362}],362:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
// MAIN //
/**
* Returns a property descriptor for an object's own property.
*
* ## Notes
*
* - In contrast to the built-in `Object.getOwnPropertyDescriptor()`, this function returns `null` if provided `undefined` or `null`, rather than throwing an error.
* - In contrast to the built-in `Object.getOwnPropertyDescriptor()`, this function returns `null` if an object does not have a provided property, rather than `undefined`.
* - In environments lacking `Object.getOwnPropertyDescriptor()` support, property descriptors do not exist. In non-supporting environment, if an object has a provided property, this function returns a descriptor object equivalent to that returned in a supporting environment; otherwise, the function returns `null`.
*
* @private
* @param {*} value - input object
* @param {(string|symbol)} property - property
* @returns {(Object|null)} property descriptor or null
*
* @example
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var desc = getOwnPropertyDescriptor( obj, 'foo' );
* // returns {'configurable':true,'enumerable':true,'writable':true,'value':3.14}
*/
function getOwnPropertyDescriptor( value, property ) {
if ( hasOwnProp( value, property ) ) {
return {
'configurable': true,
'enumerable': true,
'writable': true,
'value': value[ property ]
};
}
return null;
}
// EXPORTS //
module.exports = getOwnPropertyDescriptor;
},{"@stdlib/assert/has-own-property":46}],363:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// VARIABLES //
var propertyNames = Object.getOwnPropertyNames;
// MAIN //
/**
* Returns an array of an object's own enumerable and non-enumerable property names.
*
* ## Notes
*
* - In contrast to the built-in `Object.getOwnPropertyNames()`, this function returns an empty array if provided `undefined` or `null`, rather than throwing an error.
*
* @private
* @param {*} value - input object
* @returns {Array} a list of own property names
*
* @example
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var keys = getOwnPropertyNames( obj );
* // e.g., returns [ 'beep', 'foo' ]
*/
function getOwnPropertyNames( value ) {
return propertyNames( Object( value ) );
}
// EXPORTS //
module.exports = getOwnPropertyNames;
},{}],364:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MAIN //
var bool = ( typeof Object.getOwnPropertyNames !== 'undefined' );
// EXPORTS //
module.exports = bool;
},{}],365:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Return an array of an object's own enumerable and non-enumerable property names.
*
* @module @stdlib/utils/property-names
*
* @example
* var getOwnPropertyNames = require( '@stdlib/utils/property-names' );
*
* var keys = getOwnPropertyNames({
* 'foo': 'bar',
* 'beep': 'boop'
* });
* // e.g., returns [ 'foo', 'beep' ]
*/
// MODULES //
var HAS_BUILTIN = require( './has_builtin.js' );
var builtin = require( './builtin.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var main;
if ( HAS_BUILTIN ) {
main = builtin;
} else {
main = polyfill;
}
// EXPORTS //
module.exports = main;
},{"./builtin.js":363,"./has_builtin.js":364,"./polyfill.js":366}],366:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var keys = require( '@stdlib/utils/keys' );
// MAIN //
/**
* Returns an array of an object's own enumerable and non-enumerable property names.
*
* ## Notes
*
* - In contrast to the built-in `Object.getOwnPropertyNames()`, this function returns an empty array if provided `undefined` or `null`, rather than throwing an error.
* - In environments lacking support for `Object.getOwnPropertyNames()`, property descriptors are unavailable, and thus all properties can be safely assumed to be enumerable. Hence, we can defer to calling `Object.keys`, which retrieves all own enumerable property names.
*
* @private
* @param {*} value - input object
* @returns {Array} a list of own property names
*
* @example
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var keys = getOwnPropertyNames( obj );
* // e.g., returns [ 'beep', 'foo' ]
*/
function getOwnPropertyNames( value ) {
return keys( Object( value ) );
}
// EXPORTS //
module.exports = getOwnPropertyNames;
},{"@stdlib/utils/keys":339}],367:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var reRegExp = require( '@stdlib/regexp/regexp' );
// MAIN //
/**
* Parses a regular expression string and returns a new regular expression.
*
* @param {string} str - regular expression string
* @throws {TypeError} must provide a regular expression string
* @returns {(RegExp|null)} regular expression or null
*
* @example
* var re = reFromString( '/beep/' );
* // returns /beep/
*/
function reFromString( str ) {
if ( !isString( str ) ) {
throw new TypeError( 'invalid argument. Must provide a regular expression string. Value: `' + str + '`.' );
}
// Capture the regular expression pattern and any flags:
str = reRegExp().exec( str );
// Create a new regular expression:
return ( str ) ? new RegExp( str[1], str[2] ) : null;
}
// EXPORTS //
module.exports = reFromString;
},{"@stdlib/assert/is-string":149,"@stdlib/regexp/regexp":265}],368:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Create a regular expression from a regular expression string.
*
* @module @stdlib/utils/regexp-from-string
*
* @example
* var reFromString = require( '@stdlib/utils/regexp-from-string' );
*
* var re = reFromString( '/beep/' );
* // returns /beep/
*/
// MODULES //
var reFromString = require( './from_string.js' );
// EXPORTS //
module.exports = reFromString;
},{"./from_string.js":367}],369:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var RE = require( './fixtures/re.js' );
var nodeList = require( './fixtures/nodelist.js' );
var typedarray = require( './fixtures/typedarray.js' );
// MAIN //
/**
* Checks whether a polyfill is needed when using the `typeof` operator.
*
* @private
* @returns {boolean} boolean indicating whether a polyfill is needed
*/
function check() {
if (
// Chrome 1-12 returns 'function' for regular expression instances (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof):
typeof RE === 'function' ||
// Safari 8 returns 'object' for typed array and weak map constructors (underscore #1929):
typeof typedarray === 'object' ||
// PhantomJS 1.9 returns 'function' for `NodeList` instances (underscore #2236):
typeof nodeList === 'function'
) {
return true;
}
return false;
}
// EXPORTS //
module.exports = check;
},{"./fixtures/nodelist.js":370,"./fixtures/re.js":371,"./fixtures/typedarray.js":372}],370:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var getGlobal = require( '@stdlib/utils/global' );
// MAIN //
var root = getGlobal();
var nodeList = root.document && root.document.childNodes;
// EXPORTS //
module.exports = nodeList;
},{"@stdlib/utils/global":318}],371:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
var RE = /./;
// EXPORTS //
module.exports = RE;
},{}],372:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
var typedarray = Int8Array; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = typedarray;
},{}],373:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
/**
* Determine a value's type.
*
* @module @stdlib/utils/type-of
*
* @example
* var typeOf = require( '@stdlib/utils/type-of' );
*
* var str = typeOf( 'a' );
* // returns 'string'
*
* str = typeOf( 5 );
* // returns 'number'
*/
// MODULES //
var usePolyfill = require( './check.js' );
var typeOf = require( './typeof.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var main = ( usePolyfill() ) ? polyfill : typeOf;
// EXPORTS //
module.exports = main;
},{"./check.js":369,"./polyfill.js":374,"./typeof.js":375}],374:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var ctorName = require( '@stdlib/utils/constructor-name' );
// MAIN //
/**
* Determines a value's type.
*
* @param {*} v - input value
* @returns {string} string indicating the value's type
*/
function typeOf( v ) {
return ctorName( v ).toLowerCase();
}
// EXPORTS //
module.exports = typeOf;
},{"@stdlib/utils/constructor-name":289}],375:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var ctorName = require( '@stdlib/utils/constructor-name' );
// NOTES //
/*
* Built-in `typeof` operator behavior:
*
* ```text
* typeof null => 'object'
* typeof undefined => 'undefined'
* typeof 'a' => 'string'
* typeof 5 => 'number'
* typeof NaN => 'number'
* typeof true => 'boolean'
* typeof false => 'boolean'
* typeof {} => 'object'
* typeof [] => 'object'
* typeof function foo(){} => 'function'
* typeof function* foo(){} => 'object'
* typeof Symbol() => 'symbol'
* ```
*
*/
// MAIN //
/**
* Determines a value's type.
*
* @param {*} v - input value
* @returns {string} string indicating the value's type
*/
function typeOf( v ) {
var type;
// Address `typeof null` => `object` (see http://wiki.ecmascript.org/doku.php?id=harmony:typeof_null):
if ( v === null ) {
return 'null';
}
type = typeof v;
// If the `typeof` operator returned something other than `object`, we are done. Otherwise, we need to check for an internal class name or search for a constructor.
if ( type === 'object' ) {
return ctorName( v ).toLowerCase();
}
return type;
}
// EXPORTS //
module.exports = typeOf;
},{"@stdlib/utils/constructor-name":289}],376:[function(require,module,exports){
'use strict'
exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray
var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i]
revLookup[code.charCodeAt(i)] = i
}
// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63
function getLens (b64) {
var len = b64.length
if (len % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// Trim off extra bytes after placeholder bytes are found
// See: https://github.com/beatgammit/base64-js/issues/42
var validLen = b64.indexOf('=')
if (validLen === -1) validLen = len
var placeHoldersLen = validLen === len
? 0
: 4 - (validLen % 4)
return [validLen, placeHoldersLen]
}
// base64 is 4/3 + up to two characters of the original data
function byteLength (b64) {
var lens = getLens(b64)
var validLen = lens[0]
var placeHoldersLen = lens[1]
return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}
function _byteLength (b64, validLen, placeHoldersLen) {
return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}
function toByteArray (b64) {
var tmp
var lens = getLens(b64)
var validLen = lens[0]
var placeHoldersLen = lens[1]
var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
var curByte = 0
// if there are placeholders, only get up to the last complete 4 chars
var len = placeHoldersLen > 0
? validLen - 4
: validLen
var i
for (i = 0; i < len; i += 4) {
tmp =
(revLookup[b64.charCodeAt(i)] << 18) |
(revLookup[b64.charCodeAt(i + 1)] << 12) |
(revLookup[b64.charCodeAt(i + 2)] << 6) |
revLookup[b64.charCodeAt(i + 3)]
arr[curByte++] = (tmp >> 16) & 0xFF
arr[curByte++] = (tmp >> 8) & 0xFF
arr[curByte++] = tmp & 0xFF
}
if (placeHoldersLen === 2) {
tmp =
(revLookup[b64.charCodeAt(i)] << 2) |
(revLookup[b64.charCodeAt(i + 1)] >> 4)
arr[curByte++] = tmp & 0xFF
}
if (placeHoldersLen === 1) {
tmp =
(revLookup[b64.charCodeAt(i)] << 10) |
(revLookup[b64.charCodeAt(i + 1)] << 4) |
(revLookup[b64.charCodeAt(i + 2)] >> 2)
arr[curByte++] = (tmp >> 8) & 0xFF
arr[curByte++] = tmp & 0xFF
}
return arr
}
function tripletToBase64 (num) {
return lookup[num >> 18 & 0x3F] +
lookup[num >> 12 & 0x3F] +
lookup[num >> 6 & 0x3F] +
lookup[num & 0x3F]
}
function encodeChunk (uint8, start, end) {
var tmp
var output = []
for (var i = start; i < end; i += 3) {
tmp =
((uint8[i] << 16) & 0xFF0000) +
((uint8[i + 1] << 8) & 0xFF00) +
(uint8[i + 2] & 0xFF)
output.push(tripletToBase64(tmp))
}
return output.join('')
}
function fromByteArray (uint8) {
var tmp
var len = uint8.length
var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
var parts = []
var maxChunkLength = 16383 // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1]
parts.push(
lookup[tmp >> 2] +
lookup[(tmp << 4) & 0x3F] +
'=='
)
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + uint8[len - 1]
parts.push(
lookup[tmp >> 10] +
lookup[(tmp >> 4) & 0x3F] +
lookup[(tmp << 2) & 0x3F] +
'='
)
}
return parts.join('')
}
},{}],377:[function(require,module,exports){
},{}],378:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
'use strict';
var R = typeof Reflect === 'object' ? Reflect : null
var ReflectApply = R && typeof R.apply === 'function'
? R.apply
: function ReflectApply(target, receiver, args) {
return Function.prototype.apply.call(target, receiver, args);
}
var ReflectOwnKeys
if (R && typeof R.ownKeys === 'function') {
ReflectOwnKeys = R.ownKeys
} else if (Object.getOwnPropertySymbols) {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target)
.concat(Object.getOwnPropertySymbols(target));
};
} else {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target);
};
}
function ProcessEmitWarning(warning) {
if (console && console.warn) console.warn(warning);
}
var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
return value !== value;
}
function EventEmitter() {
EventEmitter.init.call(this);
}
module.exports = EventEmitter;
module.exports.once = once;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._eventsCount = 0;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
var defaultMaxListeners = 10;
function checkListener(listener) {
if (typeof listener !== 'function') {
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
}
}
Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
enumerable: true,
get: function() {
return defaultMaxListeners;
},
set: function(arg) {
if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
}
defaultMaxListeners = arg;
}
});
EventEmitter.init = function() {
if (this._events === undefined ||
this._events === Object.getPrototypeOf(this)._events) {
this._events = Object.create(null);
this._eventsCount = 0;
}
this._maxListeners = this._maxListeners || undefined;
};
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
}
this._maxListeners = n;
return this;
};
function _getMaxListeners(that) {
if (that._maxListeners === undefined)
return EventEmitter.defaultMaxListeners;
return that._maxListeners;
}
EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
return _getMaxListeners(this);
};
EventEmitter.prototype.emit = function emit(type) {
var args = [];
for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
var doError = (type === 'error');
var events = this._events;
if (events !== undefined)
doError = (doError && events.error === undefined);
else if (!doError)
return false;
// If there is no 'error' event listener then throw.
if (doError) {
var er;
if (args.length > 0)
er = args[0];
if (er instanceof Error) {
// Note: The comments on the `throw` lines are intentional, they show
// up in Node's output if this results in an unhandled exception.
throw er; // Unhandled 'error' event
}
// At least give some kind of context to the user
var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
err.context = er;
throw err; // Unhandled 'error' event
}
var handler = events[type];
if (handler === undefined)
return false;
if (typeof handler === 'function') {
ReflectApply(handler, this, args);
} else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i)
ReflectApply(listeners[i], this, args);
}
return true;
};
function _addListener(target, type, listener, prepend) {
var m;
var events;
var existing;
checkListener(listener);
events = target._events;
if (events === undefined) {
events = target._events = Object.create(null);
target._eventsCount = 0;
} else {
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (events.newListener !== undefined) {
target.emit('newListener', type,
listener.listener ? listener.listener : listener);
// Re-assign `events` because a newListener handler could have caused the
// this._events to be assigned to a new object
events = target._events;
}
existing = events[type];
}
if (existing === undefined) {
// Optimize the case of one listener. Don't need the extra array object.
existing = events[type] = listener;
++target._eventsCount;
} else {
if (typeof existing === 'function') {
// Adding the second element, need to change to array.
existing = events[type] =
prepend ? [listener, existing] : [existing, listener];
// If we've already got an array, just append.
} else if (prepend) {
existing.unshift(listener);
} else {
existing.push(listener);
}
// Check for listener leak
m = _getMaxListeners(target);
if (m > 0 && existing.length > m && !existing.warned) {
existing.warned = true;
// No error code for this since it is a Warning
// eslint-disable-next-line no-restricted-syntax
var w = new Error('Possible EventEmitter memory leak detected. ' +
existing.length + ' ' + String(type) + ' listeners ' +
'added. Use emitter.setMaxListeners() to ' +
'increase limit');
w.name = 'MaxListenersExceededWarning';
w.emitter = target;
w.type = type;
w.count = existing.length;
ProcessEmitWarning(w);
}
}
return target;
}
EventEmitter.prototype.addListener = function addListener(type, listener) {
return _addListener(this, type, listener, false);
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.prependListener =
function prependListener(type, listener) {
return _addListener(this, type, listener, true);
};
function onceWrapper() {
if (!this.fired) {
this.target.removeListener(this.type, this.wrapFn);
this.fired = true;
if (arguments.length === 0)
return this.listener.call(this.target);
return this.listener.apply(this.target, arguments);
}
}
function _onceWrap(target, type, listener) {
var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
var wrapped = onceWrapper.bind(state);
wrapped.listener = listener;
state.wrapFn = wrapped;
return wrapped;
}
EventEmitter.prototype.once = function once(type, listener) {
checkListener(listener);
this.on(type, _onceWrap(this, type, listener));
return this;
};
EventEmitter.prototype.prependOnceListener =
function prependOnceListener(type, listener) {
checkListener(listener);
this.prependListener(type, _onceWrap(this, type, listener));
return this;
};
// Emits a 'removeListener' event if and only if the listener was removed.
EventEmitter.prototype.removeListener =
function removeListener(type, listener) {
var list, events, position, i, originalListener;
checkListener(listener);
events = this._events;
if (events === undefined)
return this;
list = events[type];
if (list === undefined)
return this;
if (list === listener || list.listener === listener) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else {
delete events[type];
if (events.removeListener)
this.emit('removeListener', type, list.listener || listener);
}
} else if (typeof list !== 'function') {
position = -1;
for (i = list.length - 1; i >= 0; i--) {
if (list[i] === listener || list[i].listener === listener) {
originalListener = list[i].listener;
position = i;
break;
}
}
if (position < 0)
return this;
if (position === 0)
list.shift();
else {
spliceOne(list, position);
}
if (list.length === 1)
events[type] = list[0];
if (events.removeListener !== undefined)
this.emit('removeListener', type, originalListener || listener);
}
return this;
};
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.removeAllListeners =
function removeAllListeners(type) {
var listeners, events, i;
events = this._events;
if (events === undefined)
return this;
// not listening for removeListener, no need to emit
if (events.removeListener === undefined) {
if (arguments.length === 0) {
this._events = Object.create(null);
this._eventsCount = 0;
} else if (events[type] !== undefined) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else
delete events[type];
}
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
var keys = Object.keys(events);
var key;
for (i = 0; i < keys.length; ++i) {
key = keys[i];
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = Object.create(null);
this._eventsCount = 0;
return this;
}
listeners = events[type];
if (typeof listeners === 'function') {
this.removeListener(type, listeners);
} else if (listeners !== undefined) {
// LIFO order
for (i = listeners.length - 1; i >= 0; i--) {
this.removeListener(type, listeners[i]);
}
}
return this;
};
function _listeners(target, type, unwrap) {
var events = target._events;
if (events === undefined)
return [];
var evlistener = events[type];
if (evlistener === undefined)
return [];
if (typeof evlistener === 'function')
return unwrap ? [evlistener.listener || evlistener] : [evlistener];
return unwrap ?
unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
}
EventEmitter.prototype.listeners = function listeners(type) {
return _listeners(this, type, true);
};
EventEmitter.prototype.rawListeners = function rawListeners(type) {
return _listeners(this, type, false);
};
EventEmitter.listenerCount = function(emitter, type) {
if (typeof emitter.listenerCount === 'function') {
return emitter.listenerCount(type);
} else {
return listenerCount.call(emitter, type);
}
};
EventEmitter.prototype.listenerCount = listenerCount;
function listenerCount(type) {
var events = this._events;
if (events !== undefined) {
var evlistener = events[type];
if (typeof evlistener === 'function') {
return 1;
} else if (evlistener !== undefined) {
return evlistener.length;
}
}
return 0;
}
EventEmitter.prototype.eventNames = function eventNames() {
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
};
function arrayClone(arr, n) {
var copy = new Array(n);
for (var i = 0; i < n; ++i)
copy[i] = arr[i];
return copy;
}
function spliceOne(list, index) {
for (; index + 1 < list.length; index++)
list[index] = list[index + 1];
list.pop();
}
function unwrapListeners(arr) {
var ret = new Array(arr.length);
for (var i = 0; i < ret.length; ++i) {
ret[i] = arr[i].listener || arr[i];
}
return ret;
}
function once(emitter, name) {
return new Promise(function (resolve, reject) {
function errorListener(err) {
emitter.removeListener(name, resolver);
reject(err);
}
function resolver() {
if (typeof emitter.removeListener === 'function') {
emitter.removeListener('error', errorListener);
}
resolve([].slice.call(arguments));
};
eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
if (name !== 'error') {
addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
}
});
}
function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
if (typeof emitter.on === 'function') {
eventTargetAgnosticAddListener(emitter, 'error', handler, flags);
}
}
function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
if (typeof emitter.on === 'function') {
if (flags.once) {
emitter.once(name, listener);
} else {
emitter.on(name, listener);
}
} else if (typeof emitter.addEventListener === 'function') {
// EventTarget does not have `error` event semantics like Node
// EventEmitters, we do not listen for `error` events here.
emitter.addEventListener(name, function wrapListener(arg) {
// IE does not have builtin `{ once: true }` support so we
// have to do it manually.
if (flags.once) {
emitter.removeEventListener(name, wrapListener);
}
listener(arg);
});
} else {
throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
}
}
},{}],379:[function(require,module,exports){
(function (Buffer){(function (){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*/
/* eslint-disable no-proto */
'use strict'
var base64 = require('base64-js')
var ieee754 = require('ieee754')
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
var K_MAX_LENGTH = 0x7fffffff
exports.kMaxLength = K_MAX_LENGTH
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Print warning and recommend using `buffer` v4.x which has an Object
* implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* We report that the browser does not support typed arrays if the are not subclassable
* using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
* (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
* for __proto__ and has a buggy typed array implementation.
*/
Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
typeof console.error === 'function') {
console.error(
'This browser lacks typed array (Uint8Array) support which is required by ' +
'`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
)
}
function typedArraySupport () {
// Can typed array instances can be augmented?
try {
var arr = new Uint8Array(1)
arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
return arr.foo() === 42
} catch (e) {
return false
}
}
Object.defineProperty(Buffer.prototype, 'parent', {
enumerable: true,
get: function () {
if (!Buffer.isBuffer(this)) return undefined
return this.buffer
}
})
Object.defineProperty(Buffer.prototype, 'offset', {
enumerable: true,
get: function () {
if (!Buffer.isBuffer(this)) return undefined
return this.byteOffset
}
})
function createBuffer (length) {
if (length > K_MAX_LENGTH) {
throw new RangeError('The value "' + length + '" is invalid for option "size"')
}
// Return an augmented `Uint8Array` instance
var buf = new Uint8Array(length)
buf.__proto__ = Buffer.prototype
return buf
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer (arg, encodingOrOffset, length) {
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new TypeError(
'The "string" argument must be of type string. Received type number'
)
}
return allocUnsafe(arg)
}
return from(arg, encodingOrOffset, length)
}
// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
if (typeof Symbol !== 'undefined' && Symbol.species != null &&
Buffer[Symbol.species] === Buffer) {
Object.defineProperty(Buffer, Symbol.species, {
value: null,
configurable: true,
enumerable: false,
writable: false
})
}
Buffer.poolSize = 8192 // not used by this implementation
function from (value, encodingOrOffset, length) {
if (typeof value === 'string') {
return fromString(value, encodingOrOffset)
}
if (ArrayBuffer.isView(value)) {
return fromArrayLike(value)
}
if (value == null) {
throw TypeError(
'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
'or Array-like Object. Received type ' + (typeof value)
)
}
if (isInstance(value, ArrayBuffer) ||
(value && isInstance(value.buffer, ArrayBuffer))) {
return fromArrayBuffer(value, encodingOrOffset, length)
}
if (typeof value === 'number') {
throw new TypeError(
'The "value" argument must not be of type number. Received type number'
)
}
var valueOf = value.valueOf && value.valueOf()
if (valueOf != null && valueOf !== value) {
return Buffer.from(valueOf, encodingOrOffset, length)
}
var b = fromObject(value)
if (b) return b
if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
typeof value[Symbol.toPrimitive] === 'function') {
return Buffer.from(
value[Symbol.toPrimitive]('string'), encodingOrOffset, length
)
}
throw new TypeError(
'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
'or Array-like Object. Received type ' + (typeof value)
)
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function (value, encodingOrOffset, length) {
return from(value, encodingOrOffset, length)
}
// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
// https://github.com/feross/buffer/pull/148
Buffer.prototype.__proto__ = Uint8Array.prototype
Buffer.__proto__ = Uint8Array
function assertSize (size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be of type number')
} else if (size < 0) {
throw new RangeError('The value "' + size + '" is invalid for option "size"')
}
}
function alloc (size, fill, encoding) {
assertSize(size)
if (size <= 0) {
return createBuffer(size)
}
if (fill !== undefined) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpretted as a start offset.
return typeof encoding === 'string'
? createBuffer(size).fill(fill, encoding)
: createBuffer(size).fill(fill)
}
return createBuffer(size)
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(size, fill, encoding)
}
function allocUnsafe (size) {
assertSize(size)
return createBuffer(size < 0 ? 0 : checked(size) | 0)
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(size)
}
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(size)
}
function fromString (string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8'
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
var length = byteLength(string, encoding) | 0
var buf = createBuffer(length)
var actual = buf.write(string, encoding)
if (actual !== length) {
// Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
buf = buf.slice(0, actual)
}
return buf
}
function fromArrayLike (array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0
var buf = createBuffer(length)
for (var i = 0; i < length; i += 1) {
buf[i] = array[i] & 255
}
return buf
}
function fromArrayBuffer (array, byteOffset, length) {
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('"offset" is outside of buffer bounds')
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('"length" is outside of buffer bounds')
}
var buf
if (byteOffset === undefined && length === undefined) {
buf = new Uint8Array(array)
} else if (length === undefined) {
buf = new Uint8Array(array, byteOffset)
} else {
buf = new Uint8Array(array, byteOffset, length)
}
// Return an augmented `Uint8Array` instance
buf.__proto__ = Buffer.prototype
return buf
}
function fromObject (obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0
var buf = createBuffer(len)
if (buf.length === 0) {
return buf
}
obj.copy(buf, 0, 0, len)
return buf
}
if (obj.length !== undefined) {
if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
return createBuffer(0)
}
return fromArrayLike(obj)
}
if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
return fromArrayLike(obj.data)
}
}
function checked (length) {
// Note: cannot use `length < K_MAX_LENGTH` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= K_MAX_LENGTH) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
}
return length | 0
}
function SlowBuffer (length) {
if (+length != length) { // eslint-disable-line eqeqeq
length = 0
}
return Buffer.alloc(+length)
}
Buffer.isBuffer = function isBuffer (b) {
return b != null && b._isBuffer === true &&
b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
}
Buffer.compare = function compare (a, b) {
if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError(
'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
)
}
if (a === b) return 0
var x = a.length
var y = b.length
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i]
y = b[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'latin1':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function concat (list, length) {
if (!Array.isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
if (list.length === 0) {
return Buffer.alloc(0)
}
var i
if (length === undefined) {
length = 0
for (i = 0; i < list.length; ++i) {
length += list[i].length
}
}
var buffer = Buffer.allocUnsafe(length)
var pos = 0
for (i = 0; i < list.length; ++i) {
var buf = list[i]
if (isInstance(buf, Uint8Array)) {
buf = Buffer.from(buf)
}
if (!Buffer.isBuffer(buf)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
buf.copy(buffer, pos)
pos += buf.length
}
return buffer
}
function byteLength (string, encoding) {
if (Buffer.isBuffer(string)) {
return string.length
}
if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
return string.byteLength
}
if (typeof string !== 'string') {
throw new TypeError(
'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
'Received type ' + typeof string
)
}
var len = string.length
var mustMatch = (arguments.length > 2 && arguments[2] === true)
if (!mustMatch && len === 0) return 0
// Use a for loop to avoid recursion
var loweredCase = false
for (;;) {
switch (encoding) {
case 'ascii':
case 'latin1':
case 'binary':
return len
case 'utf8':
case 'utf-8':
return utf8ToBytes(string).length
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2
case 'hex':
return len >>> 1
case 'base64':
return base64ToBytes(string).length
default:
if (loweredCase) {
return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
}
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.byteLength = byteLength
function slowToString (encoding, start, end) {
var loweredCase = false
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if (start === undefined || start < 0) {
start = 0
}
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if (start > this.length) {
return ''
}
if (end === undefined || end > this.length) {
end = this.length
}
if (end <= 0) {
return ''
}
// Force coersion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0
start >>>= 0
if (end <= start) {
return ''
}
if (!encoding) encoding = 'utf8'
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'latin1':
case 'binary':
return latin1Slice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
// reliably in a browserify context because there could be multiple different
// copies of the 'buffer' package in use. This method works even for Buffer
// instances that were created from another copy of the `buffer` package.
// See: https://github.com/feross/buffer/issues/154
Buffer.prototype._isBuffer = true
function swap (b, n, m) {
var i = b[n]
b[n] = b[m]
b[m] = i
}
Buffer.prototype.swap16 = function swap16 () {
var len = this.length
if (len % 2 !== 0) {
throw new RangeError('Buffer size must be a multiple of 16-bits')
}
for (var i = 0; i < len; i += 2) {
swap(this, i, i + 1)
}
return this
}
Buffer.prototype.swap32 = function swap32 () {
var len = this.length
if (len % 4 !== 0) {
throw new RangeError('Buffer size must be a multiple of 32-bits')
}
for (var i = 0; i < len; i += 4) {
swap(this, i, i + 3)
swap(this, i + 1, i + 2)
}
return this
}
Buffer.prototype.swap64 = function swap64 () {
var len = this.length
if (len % 8 !== 0) {
throw new RangeError('Buffer size must be a multiple of 64-bits')
}
for (var i = 0; i < len; i += 8) {
swap(this, i, i + 7)
swap(this, i + 1, i + 6)
swap(this, i + 2, i + 5)
swap(this, i + 3, i + 4)
}
return this
}
Buffer.prototype.toString = function toString () {
var length = this.length
if (length === 0) return ''
if (arguments.length === 0) return utf8Slice(this, 0, length)
return slowToString.apply(this, arguments)
}
Buffer.prototype.toLocaleString = Buffer.prototype.toString
Buffer.prototype.equals = function equals (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function inspect () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
if (this.length > max) str += ' ... '
return '<Buffer ' + str + '>'
}
Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
if (isInstance(target, Uint8Array)) {
target = Buffer.from(target, target.offset, target.byteLength)
}
if (!Buffer.isBuffer(target)) {
throw new TypeError(
'The "target" argument must be one of type Buffer or Uint8Array. ' +
'Received type ' + (typeof target)
)
}
if (start === undefined) {
start = 0
}
if (end === undefined) {
end = target ? target.length : 0
}
if (thisStart === undefined) {
thisStart = 0
}
if (thisEnd === undefined) {
thisEnd = this.length
}
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
throw new RangeError('out of range index')
}
if (thisStart >= thisEnd && start >= end) {
return 0
}
if (thisStart >= thisEnd) {
return -1
}
if (start >= end) {
return 1
}
start >>>= 0
end >>>= 0
thisStart >>>= 0
thisEnd >>>= 0
if (this === target) return 0
var x = thisEnd - thisStart
var y = end - start
var len = Math.min(x, y)
var thisCopy = this.slice(thisStart, thisEnd)
var targetCopy = target.slice(start, end)
for (var i = 0; i < len; ++i) {
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i]
y = targetCopy[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
// Empty buffer means no match
if (buffer.length === 0) return -1
// Normalize byteOffset
if (typeof byteOffset === 'string') {
encoding = byteOffset
byteOffset = 0
} else if (byteOffset > 0x7fffffff) {
byteOffset = 0x7fffffff
} else if (byteOffset < -0x80000000) {
byteOffset = -0x80000000
}
byteOffset = +byteOffset // Coerce to Number.
if (numberIsNaN(byteOffset)) {
// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
byteOffset = dir ? 0 : (buffer.length - 1)
}
// Normalize byteOffset: negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = buffer.length + byteOffset
if (byteOffset >= buffer.length) {
if (dir) return -1
else byteOffset = buffer.length - 1
} else if (byteOffset < 0) {
if (dir) byteOffset = 0
else return -1
}
// Normalize val
if (typeof val === 'string') {
val = Buffer.from(val, encoding)
}
// Finally, search either indexOf (if dir is true) or lastIndexOf
if (Buffer.isBuffer(val)) {
// Special case: looking for empty string/buffer always fails
if (val.length === 0) {
return -1
}
return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
} else if (typeof val === 'number') {
val = val & 0xFF // Search for a byte value [0-255]
if (typeof Uint8Array.prototype.indexOf === 'function') {
if (dir) {
return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
} else {
return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
}
}
return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
}
throw new TypeError('val must be string, number or Buffer')
}
function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
var indexSize = 1
var arrLength = arr.length
var valLength = val.length
if (encoding !== undefined) {
encoding = String(encoding).toLowerCase()
if (encoding === 'ucs2' || encoding === 'ucs-2' ||
encoding === 'utf16le' || encoding === 'utf-16le') {
if (arr.length < 2 || val.length < 2) {
return -1
}
indexSize = 2
arrLength /= 2
valLength /= 2
byteOffset /= 2
}
}
function read (buf, i) {
if (indexSize === 1) {
return buf[i]
} else {
return buf.readUInt16BE(i * indexSize)
}
}
var i
if (dir) {
var foundIndex = -1
for (i = byteOffset; i < arrLength; i++) {
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
} else {
if (foundIndex !== -1) i -= i - foundIndex
foundIndex = -1
}
}
} else {
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
for (i = byteOffset; i >= 0; i--) {
var found = true
for (var j = 0; j < valLength; j++) {
if (read(arr, i + j) !== read(val, j)) {
found = false
break
}
}
if (found) return i
}
}
return -1
}
Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1
}
Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}
Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
var strLen = string.length
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; ++i) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
if (numberIsNaN(parsed)) return i
buf[offset + i] = parsed
}
return i
}
function utf8Write (buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}
function asciiWrite (buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length)
}
function latin1Write (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length)
}
function ucs2Write (buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8'
length = this.length
offset = 0
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset
length = this.length
offset = 0
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset >>> 0
if (isFinite(length)) {
length = length >>> 0
if (encoding === undefined) encoding = 'utf8'
} else {
encoding = length
length = undefined
}
} else {
throw new Error(
'Buffer.write(string, encoding, offset[, length]) is no longer supported'
)
}
var remaining = this.length - offset
if (length === undefined || length > remaining) length = remaining
if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
throw new RangeError('Attempt to write outside buffer bounds')
}
if (!encoding) encoding = 'utf8'
var loweredCase = false
for (;;) {
switch (encoding) {
case 'hex':
return hexWrite(this, string, offset, length)
case 'utf8':
case 'utf-8':
return utf8Write(this, string, offset, length)
case 'ascii':
return asciiWrite(this, string, offset, length)
case 'latin1':
case 'binary':
return latin1Write(this, string, offset, length)
case 'base64':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return ucs2Write(this, string, offset, length)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
end = Math.min(buf.length, end)
var res = []
var i = start
while (i < end) {
var firstByte = buf[i]
var codePoint = null
var bytesPerSequence = (firstByte > 0xEF) ? 4
: (firstByte > 0xDF) ? 3
: (firstByte > 0xBF) ? 2
: 1
if (i + bytesPerSequence <= end) {
var secondByte, thirdByte, fourthByte, tempCodePoint
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte
}
break
case 2:
secondByte = buf[i + 1]
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint
}
}
break
case 3:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint
}
}
break
case 4:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
fourthByte = buf[i + 3]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD
bytesPerSequence = 1
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000
res.push(codePoint >>> 10 & 0x3FF | 0xD800)
codePoint = 0xDC00 | codePoint & 0x3FF
}
res.push(codePoint)
i += bytesPerSequence
}
return decodeCodePointsArray(res)
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000
function decodeCodePointsArray (codePoints) {
var len = codePoints.length
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
var res = ''
var i = 0
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
)
}
return res
}
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
function latin1Slice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; ++i) {
out += toHex(buf[i])
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
}
return res
}
Buffer.prototype.slice = function slice (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len
if (start < 0) start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0) end = 0
} else if (end > len) {
end = len
}
if (end < start) end = start
var newBuf = this.subarray(start, end)
// Return an augmented `Uint8Array` instance
newBuf.__proto__ = Buffer.prototype
return newBuf
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
return val
}
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
checkOffset(offset, byteLength, this.length)
}
var val = this[offset + --byteLength]
var mul = 1
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul
}
return val
}
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var i = byteLength
var mul = 1
var val = this[offset + --i]
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
}
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
}
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
if (offset + ext > buf.length) throw new RangeError('Index out of range')
}
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var mul = 1
var i = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var i = byteLength - 1
var mul = 1
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
return offset + 2
}
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
return offset + 2
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = (value & 0xff)
return offset + 4
}
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
return offset + 4
}
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
var limit = Math.pow(2, (8 * byteLength) - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = 0
var mul = 1
var sub = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
var limit = Math.pow(2, (8 * byteLength) - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = byteLength - 1
var mul = 1
var sub = 0
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
if (value < 0) value = 0xff + value + 1
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
return offset + 2
}
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
return offset + 2
}
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
return offset + 4
}
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (offset + ext > buf.length) throw new RangeError('Index out of range')
if (offset < 0) throw new RangeError('Index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (targetStart >= target.length) targetStart = target.length
if (!targetStart) targetStart = 0
if (end > 0 && end < start) end = start
// Copy 0 bytes; we're done
if (end === start) return 0
if (target.length === 0 || this.length === 0) return 0
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds')
}
if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length) end = this.length
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start
}
var len = end - start
if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
// Use built-in when available, missing from IE11
this.copyWithin(targetStart, start, end)
} else if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
for (var i = len - 1; i >= 0; --i) {
target[i + targetStart] = this[i + start]
}
} else {
Uint8Array.prototype.set.call(
target,
this.subarray(start, end),
targetStart
)
}
return len
}
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
// Handle string cases:
if (typeof val === 'string') {
if (typeof start === 'string') {
encoding = start
start = 0
end = this.length
} else if (typeof end === 'string') {
encoding = end
end = this.length
}
if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string')
}
if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
if (val.length === 1) {
var code = val.charCodeAt(0)
if ((encoding === 'utf8' && code < 128) ||
encoding === 'latin1') {
// Fast path: If `val` fits into a single byte, use that numeric value.
val = code
}
}
} else if (typeof val === 'number') {
val = val & 255
}
// Invalid ranges are not set to a default, so can range check early.
if (start < 0 || this.length < start || this.length < end) {
throw new RangeError('Out of range index')
}
if (end <= start) {
return this
}
start = start >>> 0
end = end === undefined ? this.length : end >>> 0
if (!val) val = 0
var i
if (typeof val === 'number') {
for (i = start; i < end; ++i) {
this[i] = val
}
} else {
var bytes = Buffer.isBuffer(val)
? val
: Buffer.from(val, encoding)
var len = bytes.length
if (len === 0) {
throw new TypeError('The value "' + val +
'" is invalid for argument "value"')
}
for (i = 0; i < end - start; ++i) {
this[i + start] = bytes[i % len]
}
}
return this
}
// HELPER FUNCTIONS
// ================
var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
function base64clean (str) {
// Node takes equal signs as end of the Base64 encoding
str = str.split('=')[0]
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = str.trim().replace(INVALID_BASE64_RE, '')
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (string, units) {
units = units || Infinity
var codePoint
var length = string.length
var leadSurrogate = null
var bytes = []
for (var i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
}
// valid lead
leadSurrogate = codePoint
continue
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
}
// valid surrogate pair
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
}
leadSurrogate = null
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint)
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else {
throw new Error('Invalid code point')
}
}
return bytes
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; ++i) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str, units) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; ++i) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; ++i) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
// the `instanceof` check but they should be treated as of that type.
// See: https://github.com/feross/buffer/issues/166
function isInstance (obj, type) {
return obj instanceof type ||
(obj != null && obj.constructor != null && obj.constructor.name != null &&
obj.constructor.name === type.name)
}
function numberIsNaN (obj) {
// For IE11 support
return obj !== obj // eslint-disable-line no-self-compare
}
}).call(this)}).call(this,require("buffer").Buffer)
},{"base64-js":376,"buffer":379,"ieee754":383}],380:[function(require,module,exports){
(function (Buffer){(function (){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(arg) {
if (Array.isArray) {
return Array.isArray(arg);
}
return objectToString(arg) === '[object Array]';
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return (objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = Buffer.isBuffer;
function objectToString(o) {
return Object.prototype.toString.call(o);
}
}).call(this)}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
},{"../../is-buffer/index.js":385}],381:[function(require,module,exports){
(function (process){(function (){
/**
* This is the web browser implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = require('./debug');
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = 'undefined' != typeof chrome
&& 'undefined' != typeof chrome.storage
? chrome.storage.local
: localstorage();
/**
* Colors.
*/
exports.colors = [
'lightseagreen',
'forestgreen',
'goldenrod',
'dodgerblue',
'darkorchid',
'crimson'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
function useColors() {
// NB: In an Electron preload script, document will be defined but not fully
// initialized. Since we know we're in Chrome, we'll just detect this case
// explicitly
if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
return true;
}
// is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
// is firebug? http://stackoverflow.com/a/398120/376773
(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
// is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
// double check webkit in userAgent just in case we are in a worker
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
}
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
exports.formatters.j = function(v) {
try {
return JSON.stringify(v);
} catch (err) {
return '[UnexpectedJSONParseError]: ' + err.message;
}
};
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs(args) {
var useColors = this.useColors;
args[0] = (useColors ? '%c' : '')
+ this.namespace
+ (useColors ? ' %c' : ' ')
+ args[0]
+ (useColors ? '%c ' : ' ')
+ '+' + exports.humanize(this.diff);
if (!useColors) return;
var c = 'color: ' + this.color;
args.splice(1, 0, c, 'color: inherit')
// the final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
var index = 0;
var lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, function(match) {
if ('%%' === match) return;
index++;
if ('%c' === match) {
// we only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
*
* @api public
*/
function log() {
// this hackery is required for IE8/9, where
// the `console.log` function doesn't have 'apply'
return 'object' === typeof console
&& console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (null == namespaces) {
exports.storage.removeItem('debug');
} else {
exports.storage.debug = namespaces;
}
} catch(e) {}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
var r;
try {
r = exports.storage.debug;
} catch(e) {}
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (!r && typeof process !== 'undefined' && 'env' in process) {
r = process.env.DEBUG;
}
return r;
}
/**
* Enable namespaces listed in `localStorage.debug` initially.
*/
exports.enable(load());
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage() {
try {
return window.localStorage;
} catch (e) {}
}
}).call(this)}).call(this,require('_process'))
},{"./debug":382,"_process":389}],382:[function(require,module,exports){
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
exports.enabled = enabled;
exports.humanize = require('ms');
/**
* The currently active debug mode names, and names to skip.
*/
exports.names = [];
exports.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
exports.formatters = {};
/**
* Previous log timestamp.
*/
var prevTime;
/**
* Select a color.
* @param {String} namespace
* @return {Number}
* @api private
*/
function selectColor(namespace) {
var hash = 0, i;
for (i in namespace) {
hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return exports.colors[Math.abs(hash) % exports.colors.length];
}
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function createDebug(namespace) {
function debug() {
// disabled?
if (!debug.enabled) return;
var self = debug;
// set `diff` timestamp
var curr = +new Date();
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
// turn the `arguments` into a proper Array
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
args[0] = exports.coerce(args[0]);
if ('string' !== typeof args[0]) {
// anything else let's inspect with %O
args.unshift('%O');
}
// apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
// if we encounter an escaped % then don't increase the array index
if (match === '%%') return match;
index++;
var formatter = exports.formatters[format];
if ('function' === typeof formatter) {
var val = args[index];
match = formatter.call(self, val);
// now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
// apply env-specific formatting (colors, etc.)
exports.formatArgs.call(self, args);
var logFn = debug.log || exports.log || console.log.bind(console);
logFn.apply(self, args);
}
debug.namespace = namespace;
debug.enabled = exports.enabled(namespace);
debug.useColors = exports.useColors();
debug.color = selectColor(namespace);
// env-specific initialization logic for debug instances
if ('function' === typeof exports.init) {
exports.init(debug);
}
return debug;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
exports.save(namespaces);
exports.names = [];
exports.skips = [];
var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
var len = split.length;
for (var i = 0; i < len; i++) {
if (!split[i]) continue; // ignore empty strings
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
exports.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @api public
*/
function disable() {
exports.enable('');
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
var i, len;
for (i = 0, len = exports.skips.length; i < len; i++) {
if (exports.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = exports.names.length; i < len; i++) {
if (exports.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
},{"ms":387}],383:[function(require,module,exports){
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
var e, m
var eLen = (nBytes * 8) - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var nBits = -7
var i = isLE ? (nBytes - 1) : 0
var d = isLE ? -1 : 1
var s = buffer[offset + i]
i += d
e = s & ((1 << (-nBits)) - 1)
s >>= (-nBits)
nBits += eLen
for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
m = e & ((1 << (-nBits)) - 1)
e >>= (-nBits)
nBits += mLen
for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity)
} else {
m = m + Math.pow(2, mLen)
e = e - eBias
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}
exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c
var eLen = (nBytes * 8) - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
var i = isLE ? 0 : (nBytes - 1)
var d = isLE ? 1 : -1
var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
value = Math.abs(value)
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0
e = eMax
} else {
e = Math.floor(Math.log(value) / Math.LN2)
if (value * (c = Math.pow(2, -e)) < 1) {
e--
c *= 2
}
if (e + eBias >= 1) {
value += rt / c
} else {
value += rt * Math.pow(2, 1 - eBias)
}
if (value * c >= 2) {
e++
c /= 2
}
if (e + eBias >= eMax) {
m = 0
e = eMax
} else if (e + eBias >= 1) {
m = ((value * c) - 1) * Math.pow(2, mLen)
e = e + eBias
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
e = 0
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
e = (e << mLen) | m
eLen += mLen
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128
}
},{}],384:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
})
}
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
}
},{}],385:[function(require,module,exports){
/*!
* Determine if an object is a Buffer
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*/
// The _isBuffer check is for Safari 5-7 support, because it's missing
// Object.prototype.constructor. Remove this eventually
module.exports = function (obj) {
return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
}
function isBuffer (obj) {
return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
}
// For Node v0.10 support. Remove this eventually.
function isSlowBuffer (obj) {
return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
}
},{}],386:[function(require,module,exports){
var toString = {}.toString;
module.exports = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';
};
},{}],387:[function(require,module,exports){
/**
* Helpers.
*/
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} [options]
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
module.exports = function(val, options) {
options = options || {};
var type = typeof val;
if (type === 'string' && val.length > 0) {
return parse(val);
} else if (type === 'number' && isNaN(val) === false) {
return options.long ? fmtLong(val) : fmtShort(val);
}
throw new Error(
'val is not a non-empty string or a valid number. val=' +
JSON.stringify(val)
);
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(
str
);
if (!match) {
return;
}
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s;
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n;
default:
return undefined;
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
if (ms >= d) {
return Math.round(ms / d) + 'd';
}
if (ms >= h) {
return Math.round(ms / h) + 'h';
}
if (ms >= m) {
return Math.round(ms / m) + 'm';
}
if (ms >= s) {
return Math.round(ms / s) + 's';
}
return ms + 'ms';
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
return plural(ms, d, 'day') ||
plural(ms, h, 'hour') ||
plural(ms, m, 'minute') ||
plural(ms, s, 'second') ||
ms + ' ms';
}
/**
* Pluralization helper.
*/
function plural(ms, n, name) {
if (ms < n) {
return;
}
if (ms < n * 1.5) {
return Math.floor(ms / n) + ' ' + name;
}
return Math.ceil(ms / n) + ' ' + name + 's';
}
},{}],388:[function(require,module,exports){
(function (process){(function (){
'use strict';
if (typeof process === 'undefined' ||
!process.version ||
process.version.indexOf('v0.') === 0 ||
process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
module.exports = { nextTick: nextTick };
} else {
module.exports = process
}
function nextTick(fn, arg1, arg2, arg3) {
if (typeof fn !== 'function') {
throw new TypeError('"callback" argument must be a function');
}
var len = arguments.length;
var args, i;
switch (len) {
case 0:
case 1:
return process.nextTick(fn);
case 2:
return process.nextTick(function afterTickOne() {
fn.call(null, arg1);
});
case 3:
return process.nextTick(function afterTickTwo() {
fn.call(null, arg1, arg2);
});
case 4:
return process.nextTick(function afterTickThree() {
fn.call(null, arg1, arg2, arg3);
});
default:
args = new Array(len - 1);
i = 0;
while (i < args.length) {
args[i++] = arguments[i];
}
return process.nextTick(function afterTick() {
fn.apply(null, args);
});
}
}
}).call(this)}).call(this,require('_process'))
},{"_process":389}],389:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],390:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.
'use strict';
/*<replacement>*/
var pna = require('process-nextick-args');
/*</replacement>*/
/*<replacement>*/
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) {
keys.push(key);
}return keys;
};
/*</replacement>*/
module.exports = Duplex;
/*<replacement>*/
var util = Object.create(require('core-util-is'));
util.inherits = require('inherits');
/*</replacement>*/
var Readable = require('./_stream_readable');
var Writable = require('./_stream_writable');
util.inherits(Duplex, Readable);
{
// avoid scope creep, the keys array can then be collected
var keys = objectKeys(Writable.prototype);
for (var v = 0; v < keys.length; v++) {
var method = keys[v];
if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
}
}
function Duplex(options) {
if (!(this instanceof Duplex)) return new Duplex(options);
Readable.call(this, options);
Writable.call(this, options);
if (options && options.readable === false) this.readable = false;
if (options && options.writable === false) this.writable = false;
this.allowHalfOpen = true;
if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
this.once('end', onend);
}
Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function () {
return this._writableState.highWaterMark;
}
});
// the no-half-open enforcer
function onend() {
// if we allow half-open state, or if the writable side ended,
// then we're ok.
if (this.allowHalfOpen || this._writableState.ended) return;
// no more data can be written.
// But allow more writes to happen in this tick.
pna.nextTick(onEndNT, this);
}
function onEndNT(self) {
self.end();
}
Object.defineProperty(Duplex.prototype, 'destroyed', {
get: function () {
if (this._readableState === undefined || this._writableState === undefined) {
return false;
}
return this._readableState.destroyed && this._writableState.destroyed;
},
set: function (value) {
// we ignore the value if the stream
// has not been initialized yet
if (this._readableState === undefined || this._writableState === undefined) {
return;
}
// backward compatibility, the user is explicitly
// managing destroyed
this._readableState.destroyed = value;
this._writableState.destroyed = value;
}
});
Duplex.prototype._destroy = function (err, cb) {
this.push(null);
this.end();
pna.nextTick(cb, err);
};
},{"./_stream_readable":392,"./_stream_writable":394,"core-util-is":380,"inherits":384,"process-nextick-args":388}],391:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
// a passthrough stream.
// basically just the most minimal sort of Transform stream.
// Every written chunk gets output as-is.
'use strict';
module.exports = PassThrough;
var Transform = require('./_stream_transform');
/*<replacement>*/
var util = Object.create(require('core-util-is'));
util.inherits = require('inherits');
/*</replacement>*/
util.inherits(PassThrough, Transform);
function PassThrough(options) {
if (!(this instanceof PassThrough)) return new PassThrough(options);
Transform.call(this, options);
}
PassThrough.prototype._transform = function (chunk, encoding, cb) {
cb(null, chunk);
};
},{"./_stream_transform":393,"core-util-is":380,"inherits":384}],392:[function(require,module,exports){
(function (process,global){(function (){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
'use strict';
/*<replacement>*/
var pna = require('process-nextick-args');
/*</replacement>*/
module.exports = Readable;
/*<replacement>*/
var isArray = require('isarray');
/*</replacement>*/
/*<replacement>*/
var Duplex;
/*</replacement>*/
Readable.ReadableState = ReadableState;
/*<replacement>*/
var EE = require('events').EventEmitter;
var EElistenerCount = function (emitter, type) {
return emitter.listeners(type).length;
};
/*</replacement>*/
/*<replacement>*/
var Stream = require('./internal/streams/stream');
/*</replacement>*/
/*<replacement>*/
var Buffer = require('safe-buffer').Buffer;
var OurUint8Array = global.Uint8Array || function () {};
function _uint8ArrayToBuffer(chunk) {
return Buffer.from(chunk);
}
function _isUint8Array(obj) {
return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
}
/*</replacement>*/
/*<replacement>*/
var util = Object.create(require('core-util-is'));
util.inherits = require('inherits');
/*</replacement>*/
/*<replacement>*/
var debugUtil = require('util');
var debug = void 0;
if (debugUtil && debugUtil.debuglog) {
debug = debugUtil.debuglog('stream');
} else {
debug = function () {};
}
/*</replacement>*/
var BufferList = require('./internal/streams/BufferList');
var destroyImpl = require('./internal/streams/destroy');
var StringDecoder;
util.inherits(Readable, Stream);
var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
function prependListener(emitter, event, fn) {
// Sadly this is not cacheable as some libraries bundle their own
// event emitter implementation with them.
if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
// This is a hack to make sure that our error handler is attached before any
// userland ones. NEVER DO THIS. This is here only because this code needs
// to continue to work with older versions of Node.js that do not include
// the prependListener() method. The goal is to eventually remove this hack.
if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
}
function ReadableState(options, stream) {
Duplex = Duplex || require('./_stream_duplex');
options = options || {};
// Duplex streams are both readable and writable, but share
// the same options object.
// However, some cases require setting options to different
// values for the readable and the writable sides of the duplex stream.
// These options can be provided separately as readableXXX and writableXXX.
var isDuplex = stream instanceof Duplex;
// object stream flag. Used to make read(n) ignore n and to
// make all the buffer merging and length checks go away
this.objectMode = !!options.objectMode;
if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
// the point at which it stops calling _read() to fill the buffer
// Note: 0 is a valid value, means "don't call _read preemptively ever"
var hwm = options.highWaterMark;
var readableHwm = options.readableHighWaterMark;
var defaultHwm = this.objectMode ? 16 : 16 * 1024;
if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
// cast to ints.
this.highWaterMark = Math.floor(this.highWaterMark);
// A linked list is used to store data chunks instead of an array because the
// linked list can remove elements from the beginning faster than
// array.shift()
this.buffer = new BufferList();
this.length = 0;
this.pipes = null;
this.pipesCount = 0;
this.flowing = null;
this.ended = false;
this.endEmitted = false;
this.reading = false;
// a flag to be able to tell if the event 'readable'/'data' is emitted
// immediately, or on a later tick. We set this to true at first, because
// any actions that shouldn't happen until "later" should generally also
// not happen before the first read call.
this.sync = true;
// whenever we return null, then we set a flag to say
// that we're awaiting a 'readable' event emission.
this.needReadable = false;
this.emittedReadable = false;
this.readableListening = false;
this.resumeScheduled = false;
// has it been destroyed
this.destroyed = false;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// the number of writers that are awaiting a drain event in .pipe()s
this.awaitDrain = 0;
// if true, a maybeReadMore has been scheduled
this.readingMore = false;
this.decoder = null;
this.encoding = null;
if (options.encoding) {
if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
this.decoder = new StringDecoder(options.encoding);
this.encoding = options.encoding;
}
}
function Readable(options) {
Duplex = Duplex || require('./_stream_duplex');
if (!(this instanceof Readable)) return new Readable(options);
this._readableState = new ReadableState(options, this);
// legacy
this.readable = true;
if (options) {
if (typeof options.read === 'function') this._read = options.read;
if (typeof options.destroy === 'function') this._destroy = options.destroy;
}
Stream.call(this);
}
Object.defineProperty(Readable.prototype, 'destroyed', {
get: function () {
if (this._readableState === undefined) {
return false;
}
return this._readableState.destroyed;
},
set: function (value) {
// we ignore the value if the stream
// has not been initialized yet
if (!this._readableState) {
return;
}
// backward compatibility, the user is explicitly
// managing destroyed
this._readableState.destroyed = value;
}
});
Readable.prototype.destroy = destroyImpl.destroy;
Readable.prototype._undestroy = destroyImpl.undestroy;
Readable.prototype._destroy = function (err, cb) {
this.push(null);
cb(err);
};
// Manually shove something into the read() buffer.
// This returns true if the highWaterMark has not been hit yet,
// similar to how Writable.write() returns true if you should
// write() some more.
Readable.prototype.push = function (chunk, encoding) {
var state = this._readableState;
var skipChunkCheck;
if (!state.objectMode) {
if (typeof chunk === 'string') {
encoding = encoding || state.defaultEncoding;
if (encoding !== state.encoding) {
chunk = Buffer.from(chunk, encoding);
encoding = '';
}
skipChunkCheck = true;
}
} else {
skipChunkCheck = true;
}
return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
};
// Unshift should *always* be something directly out of read()
Readable.prototype.unshift = function (chunk) {
return readableAddChunk(this, chunk, null, true, false);
};
function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
var state = stream._readableState;
if (chunk === null) {
state.reading = false;
onEofChunk(stream, state);
} else {
var er;
if (!skipChunkCheck) er = chunkInvalid(state, chunk);
if (er) {
stream.emit('error', er);
} else if (state.objectMode || chunk && chunk.length > 0) {
if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
chunk = _uint8ArrayToBuffer(chunk);
}
if (addToFront) {
if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
} else if (state.ended) {
stream.emit('error', new Error('stream.push() after EOF'));
} else {
state.reading = false;
if (state.decoder && !encoding) {
chunk = state.decoder.write(chunk);
if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
} else {
addChunk(stream, state, chunk, false);
}
}
} else if (!addToFront) {
state.reading = false;
}
}
return needMoreData(state);
}
function addChunk(stream, state, chunk, addToFront) {
if (state.flowing && state.length === 0 && !state.sync) {
stream.emit('data', chunk);
stream.read(0);
} else {
// update the buffer info.
state.length += state.objectMode ? 1 : chunk.length;
if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
if (state.needReadable) emitReadable(stream);
}
maybeReadMore(stream, state);
}
function chunkInvalid(state, chunk) {
var er;
if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');
}
return er;
}
// if it's past the high water mark, we can push in some more.
// Also, if we have no data yet, we can stand some
// more bytes. This is to work around cases where hwm=0,
// such as the repl. Also, if the push() triggered a
// readable event, and the user called read(largeNumber) such that
// needReadable was set, then we ought to push more, so that another
// 'readable' event will be triggered.
function needMoreData(state) {
return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
}
Readable.prototype.isPaused = function () {
return this._readableState.flowing === false;
};
// backwards compatibility.
Readable.prototype.setEncoding = function (enc) {
if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
this._readableState.decoder = new StringDecoder(enc);
this._readableState.encoding = enc;
return this;
};
// Don't raise the hwm > 8MB
var MAX_HWM = 0x800000;
function computeNewHighWaterMark(n) {
if (n >= MAX_HWM) {
n = MAX_HWM;
} else {
// Get the next highest power of 2 to prevent increasing hwm excessively in
// tiny amounts
n--;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
n++;
}
return n;
}
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function howMuchToRead(n, state) {
if (n <= 0 || state.length === 0 && state.ended) return 0;
if (state.objectMode) return 1;
if (n !== n) {
// Only flow one buffer at a time
if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
}
// If we're asking for more than the current hwm, then raise the hwm.
if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
if (n <= state.length) return n;
// Don't have enough
if (!state.ended) {
state.needReadable = true;
return 0;
}
return state.length;
}
// you can override either this method, or the async _read(n) below.
Readable.prototype.read = function (n) {
debug('read', n);
n = parseInt(n, 10);
var state = this._readableState;
var nOrig = n;
if (n !== 0) state.emittedReadable = false;
// if we're doing read(0) to trigger a readable event, but we
// already have a bunch of data in the buffer, then just trigger
// the 'readable' event and move on.
if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
debug('read: emitReadable', state.length, state.ended);
if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
return null;
}
n = howMuchToRead(n, state);
// if we've ended, and we're now clear, then finish it up.
if (n === 0 && state.ended) {
if (state.length === 0) endReadable(this);
return null;
}
// All the actual chunk generation logic needs to be
// *below* the call to _read. The reason is that in certain
// synthetic stream cases, such as passthrough streams, _read
// may be a completely synchronous operation which may change
// the state of the read buffer, providing enough data when
// before there was *not* enough.
//
// So, the steps are:
// 1. Figure out what the state of things will be after we do
// a read from the buffer.
//
// 2. If that resulting state will trigger a _read, then call _read.
// Note that this may be asynchronous, or synchronous. Yes, it is
// deeply ugly to write APIs this way, but that still doesn't mean
// that the Readable class should behave improperly, as streams are
// designed to be sync/async agnostic.
// Take note if the _read call is sync or async (ie, if the read call
// has returned yet), so that we know whether or not it's safe to emit
// 'readable' etc.
//
// 3. Actually pull the requested chunks out of the buffer and return.
// if we need a readable event, then we need to do some reading.
var doRead = state.needReadable;
debug('need readable', doRead);
// if we currently have less than the highWaterMark, then also read some
if (state.length === 0 || state.length - n < state.highWaterMark) {
doRead = true;
debug('length less than watermark', doRead);
}
// however, if we've ended, then there's no point, and if we're already
// reading, then it's unnecessary.
if (state.ended || state.reading) {
doRead = false;
debug('reading or ended', doRead);
} else if (doRead) {
debug('do read');
state.reading = true;
state.sync = true;
// if the length is currently zero, then we *need* a readable event.
if (state.length === 0) state.needReadable = true;
// call internal read method
this._read(state.highWaterMark);
state.sync = false;
// If _read pushed data synchronously, then `reading` will be false,
// and we need to re-evaluate how much data we can return to the user.
if (!state.reading) n = howMuchToRead(nOrig, state);
}
var ret;
if (n > 0) ret = fromList(n, state);else ret = null;
if (ret === null) {
state.needReadable = true;
n = 0;
} else {
state.length -= n;
}
if (state.length === 0) {
// If we have nothing in the buffer, then we want to know
// as soon as we *do* get something into the buffer.
if (!state.ended) state.needReadable = true;
// If we tried to read() past the EOF, then emit end on the next tick.
if (nOrig !== n && state.ended) endReadable(this);
}
if (ret !== null) this.emit('data', ret);
return ret;
};
function onEofChunk(stream, state) {
if (state.ended) return;
if (state.decoder) {
var chunk = state.decoder.end();
if (chunk && chunk.length) {
state.buffer.push(chunk);
state.length += state.objectMode ? 1 : chunk.length;
}
}
state.ended = true;
// emit 'readable' now to make sure it gets picked up.
emitReadable(stream);
}
// Don't emit readable right away in sync mode, because this can trigger
// another read() call => stack overflow. This way, it might trigger
// a nextTick recursion warning, but that's not so bad.
function emitReadable(stream) {
var state = stream._readableState;
state.needReadable = false;
if (!state.emittedReadable) {
debug('emitReadable', state.flowing);
state.emittedReadable = true;
if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
}
}
function emitReadable_(stream) {
debug('emit readable');
stream.emit('readable');
flow(stream);
}
// at this point, the user has presumably seen the 'readable' event,
// and called read() to consume some data. that may have triggered
// in turn another _read(n) call, in which case reading = true if
// it's in progress.
// However, if we're not ended, or reading, and the length < hwm,
// then go ahead and try to read some more preemptively.
function maybeReadMore(stream, state) {
if (!state.readingMore) {
state.readingMore = true;
pna.nextTick(maybeReadMore_, stream, state);
}
}
function maybeReadMore_(stream, state) {
var len = state.length;
while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
debug('maybeReadMore read 0');
stream.read(0);
if (len === state.length)
// didn't get any data, stop spinning.
break;else len = state.length;
}
state.readingMore = false;
}
// abstract method. to be overridden in specific implementation classes.
// call cb(er, data) where data is <= n in length.
// for virtual (non-string, non-buffer) streams, "length" is somewhat
// arbitrary, and perhaps not very meaningful.
Readable.prototype._read = function (n) {
this.emit('error', new Error('_read() is not implemented'));
};
Readable.prototype.pipe = function (dest, pipeOpts) {
var src = this;
var state = this._readableState;
switch (state.pipesCount) {
case 0:
state.pipes = dest;
break;
case 1:
state.pipes = [state.pipes, dest];
break;
default:
state.pipes.push(dest);
break;
}
state.pipesCount += 1;
debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
var endFn = doEnd ? onend : unpipe;
if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
dest.on('unpipe', onunpipe);
function onunpipe(readable, unpipeInfo) {
debug('onunpipe');
if (readable === src) {
if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
unpipeInfo.hasUnpiped = true;
cleanup();
}
}
}
function onend() {
debug('onend');
dest.end();
}
// when the dest drains, it reduces the awaitDrain counter
// on the source. This would be more elegant with a .once()
// handler in flow(), but adding and removing repeatedly is
// too slow.
var ondrain = pipeOnDrain(src);
dest.on('drain', ondrain);
var cleanedUp = false;
function cleanup() {
debug('cleanup');
// cleanup event handlers once the pipe is broken
dest.removeListener('close', onclose);
dest.removeListener('finish', onfinish);
dest.removeListener('drain', ondrain);
dest.removeListener('error', onerror);
dest.removeListener('unpipe', onunpipe);
src.removeListener('end', onend);
src.removeListener('end', unpipe);
src.removeListener('data', ondata);
cleanedUp = true;
// if the reader is waiting for a drain event from this
// specific writer, then it would cause it to never start
// flowing again.
// So, if this is awaiting a drain, then we just call it now.
// If we don't know, then assume that we are waiting for one.
if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
}
// If the user pushes more data while we're writing to dest then we'll end up
// in ondata again. However, we only want to increase awaitDrain once because
// dest will only emit one 'drain' event for the multiple writes.
// => Introduce a guard on increasing awaitDrain.
var increasedAwaitDrain = false;
src.on('data', ondata);
function ondata(chunk) {
debug('ondata');
increasedAwaitDrain = false;
var ret = dest.write(chunk);
if (false === ret && !increasedAwaitDrain) {
// If the user unpiped during `dest.write()`, it is possible
// to get stuck in a permanently paused state if that write
// also returned false.
// => Check whether `dest` is still a piping destination.
if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
debug('false write response, pause', src._readableState.awaitDrain);
src._readableState.awaitDrain++;
increasedAwaitDrain = true;
}
src.pause();
}
}
// if the dest has an error, then stop piping into it.
// however, don't suppress the throwing behavior for this.
function onerror(er) {
debug('onerror', er);
unpipe();
dest.removeListener('error', onerror);
if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
}
// Make sure our error handler is attached before userland ones.
prependListener(dest, 'error', onerror);
// Both close and finish should trigger unpipe, but only once.
function onclose() {
dest.removeListener('finish', onfinish);
unpipe();
}
dest.once('close', onclose);
function onfinish() {
debug('onfinish');
dest.removeListener('close', onclose);
unpipe();
}
dest.once('finish', onfinish);
function unpipe() {
debug('unpipe');
src.unpipe(dest);
}
// tell the dest that it's being piped to
dest.emit('pipe', src);
// start the flow if it hasn't been started already.
if (!state.flowing) {
debug('pipe resume');
src.resume();
}
return dest;
};
function pipeOnDrain(src) {
return function () {
var state = src._readableState;
debug('pipeOnDrain', state.awaitDrain);
if (state.awaitDrain) state.awaitDrain--;
if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
state.flowing = true;
flow(src);
}
};
}
Readable.prototype.unpipe = function (dest) {
var state = this._readableState;
var unpipeInfo = { hasUnpiped: false };
// if we're not piping anywhere, then do nothing.
if (state.pipesCount === 0) return this;
// just one destination. most common case.
if (state.pipesCount === 1) {
// passed in one, but it's not the right one.
if (dest && dest !== state.pipes) return this;
if (!dest) dest = state.pipes;
// got a match.
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
if (dest) dest.emit('unpipe', this, unpipeInfo);
return this;
}
// slow case. multiple pipe destinations.
if (!dest) {
// remove all.
var dests = state.pipes;
var len = state.pipesCount;
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
for (var i = 0; i < len; i++) {
dests[i].emit('unpipe', this, unpipeInfo);
}return this;
}
// try to find the right one.
var index = indexOf(state.pipes, dest);
if (index === -1) return this;
state.pipes.splice(index, 1);
state.pipesCount -= 1;
if (state.pipesCount === 1) state.pipes = state.pipes[0];
dest.emit('unpipe', this, unpipeInfo);
return this;
};
// set up data events if they are asked for
// Ensure readable listeners eventually get something
Readable.prototype.on = function (ev, fn) {
var res = Stream.prototype.on.call(this, ev, fn);
if (ev === 'data') {
// Start flowing on next tick if stream isn't explicitly paused
if (this._readableState.flowing !== false) this.resume();
} else if (ev === 'readable') {
var state = this._readableState;
if (!state.endEmitted && !state.readableListening) {
state.readableListening = state.needReadable = true;
state.emittedReadable = false;
if (!state.reading) {
pna.nextTick(nReadingNextTick, this);
} else if (state.length) {
emitReadable(this);
}
}
}
return res;
};
Readable.prototype.addListener = Readable.prototype.on;
function nReadingNextTick(self) {
debug('readable nexttick read 0');
self.read(0);
}
// pause() and resume() are remnants of the legacy readable stream API
// If the user uses them, then switch into old mode.
Readable.prototype.resume = function () {
var state = this._readableState;
if (!state.flowing) {
debug('resume');
state.flowing = true;
resume(this, state);
}
return this;
};
function resume(stream, state) {
if (!state.resumeScheduled) {
state.resumeScheduled = true;
pna.nextTick(resume_, stream, state);
}
}
function resume_(stream, state) {
if (!state.reading) {
debug('resume read 0');
stream.read(0);
}
state.resumeScheduled = false;
state.awaitDrain = 0;
stream.emit('resume');
flow(stream);
if (state.flowing && !state.reading) stream.read(0);
}
Readable.prototype.pause = function () {
debug('call pause flowing=%j', this._readableState.flowing);
if (false !== this._readableState.flowing) {
debug('pause');
this._readableState.flowing = false;
this.emit('pause');
}
return this;
};
function flow(stream) {
var state = stream._readableState;
debug('flow', state.flowing);
while (state.flowing && stream.read() !== null) {}
}
// wrap an old-style stream as the async data source.
// This is *not* part of the readable stream interface.
// It is an ugly unfortunate mess of history.
Readable.prototype.wrap = function (stream) {
var _this = this;
var state = this._readableState;
var paused = false;
stream.on('end', function () {
debug('wrapped end');
if (state.decoder && !state.ended) {
var chunk = state.decoder.end();
if (chunk && chunk.length) _this.push(chunk);
}
_this.push(null);
});
stream.on('data', function (chunk) {
debug('wrapped data');
if (state.decoder) chunk = state.decoder.write(chunk);
// don't skip over falsy values in objectMode
if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
var ret = _this.push(chunk);
if (!ret) {
paused = true;
stream.pause();
}
});
// proxy all the other methods.
// important when wrapping filters and duplexes.
for (var i in stream) {
if (this[i] === undefined && typeof stream[i] === 'function') {
this[i] = function (method) {
return function () {
return stream[method].apply(stream, arguments);
};
}(i);
}
}
// proxy certain important events.
for (var n = 0; n < kProxyEvents.length; n++) {
stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
}
// when we try to consume some more bytes, simply unpause the
// underlying stream.
this._read = function (n) {
debug('wrapped _read', n);
if (paused) {
paused = false;
stream.resume();
}
};
return this;
};
Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function () {
return this._readableState.highWaterMark;
}
});
// exposed for testing purposes only.
Readable._fromList = fromList;
// Pluck off n bytes from an array of buffers.
// Length is the combined lengths of all the buffers in the list.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromList(n, state) {
// nothing buffered
if (state.length === 0) return null;
var ret;
if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
// read it all, truncate the list
if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
state.buffer.clear();
} else {
// read part of list
ret = fromListPartial(n, state.buffer, state.decoder);
}
return ret;
}
// Extracts only enough buffered data to satisfy the amount requested.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromListPartial(n, list, hasStrings) {
var ret;
if (n < list.head.data.length) {
// slice is the same for buffers and strings
ret = list.head.data.slice(0, n);
list.head.data = list.head.data.slice(n);
} else if (n === list.head.data.length) {
// first chunk is a perfect match
ret = list.shift();
} else {
// result spans more than one buffer
ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
}
return ret;
}
// Copies a specified amount of characters from the list of buffered data
// chunks.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function copyFromBufferString(n, list) {
var p = list.head;
var c = 1;
var ret = p.data;
n -= ret.length;
while (p = p.next) {
var str = p.data;
var nb = n > str.length ? str.length : n;
if (nb === str.length) ret += str;else ret += str.slice(0, n);
n -= nb;
if (n === 0) {
if (nb === str.length) {
++c;
if (p.next) list.head = p.next;else list.head = list.tail = null;
} else {
list.head = p;
p.data = str.slice(nb);
}
break;
}
++c;
}
list.length -= c;
return ret;
}
// Copies a specified amount of bytes from the list of buffered data chunks.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function copyFromBuffer(n, list) {
var ret = Buffer.allocUnsafe(n);
var p = list.head;
var c = 1;
p.data.copy(ret);
n -= p.data.length;
while (p = p.next) {
var buf = p.data;
var nb = n > buf.length ? buf.length : n;
buf.copy(ret, ret.length - n, 0, nb);
n -= nb;
if (n === 0) {
if (nb === buf.length) {
++c;
if (p.next) list.head = p.next;else list.head = list.tail = null;
} else {
list.head = p;
p.data = buf.slice(nb);
}
break;
}
++c;
}
list.length -= c;
return ret;
}
function endReadable(stream) {
var state = stream._readableState;
// If we get here before consuming all the bytes, then that is a
// bug in node. Should never happen.
if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
if (!state.endEmitted) {
state.ended = true;
pna.nextTick(endReadableNT, state, stream);
}
}
function endReadableNT(state, stream) {
// Check that we didn't get one last unshift.
if (!state.endEmitted && state.length === 0) {
state.endEmitted = true;
stream.readable = false;
stream.emit('end');
}
}
function indexOf(xs, x) {
for (var i = 0, l = xs.length; i < l; i++) {
if (xs[i] === x) return i;
}
return -1;
}
}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./_stream_duplex":390,"./internal/streams/BufferList":395,"./internal/streams/destroy":396,"./internal/streams/stream":397,"_process":389,"core-util-is":380,"events":378,"inherits":384,"isarray":386,"process-nextick-args":388,"safe-buffer":399,"string_decoder/":400,"util":377}],393:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
// a transform stream is a readable/writable stream where you do
// something with the data. Sometimes it's called a "filter",
// but that's not a great name for it, since that implies a thing where
// some bits pass through, and others are simply ignored. (That would
// be a valid example of a transform, of course.)
//
// While the output is causally related to the input, it's not a
// necessarily symmetric or synchronous transformation. For example,
// a zlib stream might take multiple plain-text writes(), and then
// emit a single compressed chunk some time in the future.
//
// Here's how this works:
//
// The Transform stream has all the aspects of the readable and writable
// stream classes. When you write(chunk), that calls _write(chunk,cb)
// internally, and returns false if there's a lot of pending writes
// buffered up. When you call read(), that calls _read(n) until
// there's enough pending readable data buffered up.
//
// In a transform stream, the written data is placed in a buffer. When
// _read(n) is called, it transforms the queued up data, calling the
// buffered _write cb's as it consumes chunks. If consuming a single
// written chunk would result in multiple output chunks, then the first
// outputted bit calls the readcb, and subsequent chunks just go into
// the read buffer, and will cause it to emit 'readable' if necessary.
//
// This way, back-pressure is actually determined by the reading side,
// since _read has to be called to start processing a new chunk. However,
// a pathological inflate type of transform can cause excessive buffering
// here. For example, imagine a stream where every byte of input is
// interpreted as an integer from 0-255, and then results in that many
// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
// 1kb of data being output. In this case, you could write a very small
// amount of input, and end up with a very large amount of output. In
// such a pathological inflating mechanism, there'd be no way to tell
// the system to stop doing the transform. A single 4MB write could
// cause the system to run out of memory.
//
// However, even in such a pathological case, only a single written chunk
// would be consumed, and then the rest would wait (un-transformed) until
// the results of the previous transformed chunk were consumed.
'use strict';
module.exports = Transform;
var Duplex = require('./_stream_duplex');
/*<replacement>*/
var util = Object.create(require('core-util-is'));
util.inherits = require('inherits');
/*</replacement>*/
util.inherits(Transform, Duplex);
function afterTransform(er, data) {
var ts = this._transformState;
ts.transforming = false;
var cb = ts.writecb;
if (!cb) {
return this.emit('error', new Error('write callback called multiple times'));
}
ts.writechunk = null;
ts.writecb = null;
if (data != null) // single equals check for both `null` and `undefined`
this.push(data);
cb(er);
var rs = this._readableState;
rs.reading = false;
if (rs.needReadable || rs.length < rs.highWaterMark) {
this._read(rs.highWaterMark);
}
}
function Transform(options) {
if (!(this instanceof Transform)) return new Transform(options);
Duplex.call(this, options);
this._transformState = {
afterTransform: afterTransform.bind(this),
needTransform: false,
transforming: false,
writecb: null,
writechunk: null,
writeencoding: null
};
// start out asking for a readable event once data is transformed.
this._readableState.needReadable = true;
// we have implemented the _read method, and done the other things
// that Readable wants before the first _read call, so unset the
// sync guard flag.
this._readableState.sync = false;
if (options) {
if (typeof options.transform === 'function') this._transform = options.transform;
if (typeof options.flush === 'function') this._flush = options.flush;
}
// When the writable side finishes, then flush out anything remaining.
this.on('prefinish', prefinish);
}
function prefinish() {
var _this = this;
if (typeof this._flush === 'function') {
this._flush(function (er, data) {
done(_this, er, data);
});
} else {
done(this, null, null);
}
}
Transform.prototype.push = function (chunk, encoding) {
this._transformState.needTransform = false;
return Duplex.prototype.push.call(this, chunk, encoding);
};
// This is the part where you do stuff!
// override this function in implementation classes.
// 'chunk' is an input chunk.
//
// Call `push(newChunk)` to pass along transformed output
// to the readable side. You may call 'push' zero or more times.
//
// Call `cb(err)` when you are done with this chunk. If you pass
// an error, then that'll put the hurt on the whole operation. If you
// never call cb(), then you'll never get another chunk.
Transform.prototype._transform = function (chunk, encoding, cb) {
throw new Error('_transform() is not implemented');
};
Transform.prototype._write = function (chunk, encoding, cb) {
var ts = this._transformState;
ts.writecb = cb;
ts.writechunk = chunk;
ts.writeencoding = encoding;
if (!ts.transforming) {
var rs = this._readableState;
if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
}
};
// Doesn't matter what the args are here.
// _transform does all the work.
// That we got here means that the readable side wants more data.
Transform.prototype._read = function (n) {
var ts = this._transformState;
if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
ts.transforming = true;
this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
} else {
// mark that we need a transform, so that any data that comes in
// will get processed, now that we've asked for it.
ts.needTransform = true;
}
};
Transform.prototype._destroy = function (err, cb) {
var _this2 = this;
Duplex.prototype._destroy.call(this, err, function (err2) {
cb(err2);
_this2.emit('close');
});
};
function done(stream, er, data) {
if (er) return stream.emit('error', er);
if (data != null) // single equals check for both `null` and `undefined`
stream.push(data);
// if there's nothing in the write buffer, then that means
// that nothing more will ever be provided
if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
return stream.push(null);
}
},{"./_stream_duplex":390,"core-util-is":380,"inherits":384}],394:[function(require,module,exports){
(function (process,global,setImmediate){(function (){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
// A bit simpler than readable streams.
// Implement an async ._write(chunk, encoding, cb), and it'll handle all
// the drain event emission and buffering.
'use strict';
/*<replacement>*/
var pna = require('process-nextick-args');
/*</replacement>*/
module.exports = Writable;
/* <replacement> */
function WriteReq(chunk, encoding, cb) {
this.chunk = chunk;
this.encoding = encoding;
this.callback = cb;
this.next = null;
}
// It seems a linked list but it is not
// there will be only 2 of these for each stream
function CorkedRequest(state) {
var _this = this;
this.next = null;
this.entry = null;
this.finish = function () {
onCorkedFinish(_this, state);
};
}
/* </replacement> */
/*<replacement>*/
var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
/*</replacement>*/
/*<replacement>*/
var Duplex;
/*</replacement>*/
Writable.WritableState = WritableState;
/*<replacement>*/
var util = Object.create(require('core-util-is'));
util.inherits = require('inherits');
/*</replacement>*/
/*<replacement>*/
var internalUtil = {
deprecate: require('util-deprecate')
};
/*</replacement>*/
/*<replacement>*/
var Stream = require('./internal/streams/stream');
/*</replacement>*/
/*<replacement>*/
var Buffer = require('safe-buffer').Buffer;
var OurUint8Array = global.Uint8Array || function () {};
function _uint8ArrayToBuffer(chunk) {
return Buffer.from(chunk);
}
function _isUint8Array(obj) {
return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
}
/*</replacement>*/
var destroyImpl = require('./internal/streams/destroy');
util.inherits(Writable, Stream);
function nop() {}
function WritableState(options, stream) {
Duplex = Duplex || require('./_stream_duplex');
options = options || {};
// Duplex streams are both readable and writable, but share
// the same options object.
// However, some cases require setting options to different
// values for the readable and the writable sides of the duplex stream.
// These options can be provided separately as readableXXX and writableXXX.
var isDuplex = stream instanceof Duplex;
// object stream flag to indicate whether or not this stream
// contains buffers or objects.
this.objectMode = !!options.objectMode;
if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
// the point at which write() starts returning false
// Note: 0 is a valid value, means that we always return false if
// the entire buffer is not flushed immediately on write()
var hwm = options.highWaterMark;
var writableHwm = options.writableHighWaterMark;
var defaultHwm = this.objectMode ? 16 : 16 * 1024;
if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
// cast to ints.
this.highWaterMark = Math.floor(this.highWaterMark);
// if _final has been called
this.finalCalled = false;
// drain event flag.
this.needDrain = false;
// at the start of calling end()
this.ending = false;
// when end() has been called, and returned
this.ended = false;
// when 'finish' is emitted
this.finished = false;
// has it been destroyed
this.destroyed = false;
// should we decode strings into buffers before passing to _write?
// this is here so that some node-core streams can optimize string
// handling at a lower level.
var noDecode = options.decodeStrings === false;
this.decodeStrings = !noDecode;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// not an actual buffer we keep track of, but a measurement
// of how much we're waiting to get pushed to some underlying
// socket or file.
this.length = 0;
// a flag to see when we're in the middle of a write.
this.writing = false;
// when true all writes will be buffered until .uncork() call
this.corked = 0;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, because any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// a flag to know if we're processing previously buffered items, which
// may call the _write() callback in the same tick, so that we don't
// end up in an overlapped onwrite situation.
this.bufferProcessing = false;
// the callback that's passed to _write(chunk,cb)
this.onwrite = function (er) {
onwrite(stream, er);
};
// the callback that the user supplies to write(chunk,encoding,cb)
this.writecb = null;
// the amount that is being written when _write is called.
this.writelen = 0;
this.bufferedRequest = null;
this.lastBufferedRequest = null;
// number of pending user-supplied write callbacks
// this must be 0 before 'finish' can be emitted
this.pendingcb = 0;
// emit prefinish if the only thing we're waiting for is _write cbs
// This is relevant for synchronous Transform streams
this.prefinished = false;
// True if the error was already emitted and should not be thrown again
this.errorEmitted = false;
// count buffered requests
this.bufferedRequestCount = 0;
// allocate the first CorkedRequest, there is always
// one allocated and free to use, and we maintain at most two
this.corkedRequestsFree = new CorkedRequest(this);
}
WritableState.prototype.getBuffer = function getBuffer() {
var current = this.bufferedRequest;
var out = [];
while (current) {
out.push(current);
current = current.next;
}
return out;
};
(function () {
try {
Object.defineProperty(WritableState.prototype, 'buffer', {
get: internalUtil.deprecate(function () {
return this.getBuffer();
}, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
});
} catch (_) {}
})();
// Test _writableState for inheritance to account for Duplex streams,
// whose prototype chain only points to Readable.
var realHasInstance;
if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
realHasInstance = Function.prototype[Symbol.hasInstance];
Object.defineProperty(Writable, Symbol.hasInstance, {
value: function (object) {
if (realHasInstance.call(this, object)) return true;
if (this !== Writable) return false;
return object && object._writableState instanceof WritableState;
}
});
} else {
realHasInstance = function (object) {
return object instanceof this;
};
}
function Writable(options) {
Duplex = Duplex || require('./_stream_duplex');
// Writable ctor is applied to Duplexes, too.
// `realHasInstance` is necessary because using plain `instanceof`
// would return false, as no `_writableState` property is attached.
// Trying to use the custom `instanceof` for Writable here will also break the
// Node.js LazyTransform implementation, which has a non-trivial getter for
// `_writableState` that would lead to infinite recursion.
if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
return new Writable(options);
}
this._writableState = new WritableState(options, this);
// legacy.
this.writable = true;
if (options) {
if (typeof options.write === 'function') this._write = options.write;
if (typeof options.writev === 'function') this._writev = options.writev;
if (typeof options.destroy === 'function') this._destroy = options.destroy;
if (typeof options.final === 'function') this._final = options.final;
}
Stream.call(this);
}
// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function () {
this.emit('error', new Error('Cannot pipe, not readable'));
};
function writeAfterEnd(stream, cb) {
var er = new Error('write after end');
// TODO: defer error events consistently everywhere, not just the cb
stream.emit('error', er);
pna.nextTick(cb, er);
}
// Checks that a user-supplied chunk is valid, especially for the particular
// mode the stream is in. Currently this means that `null` is never accepted
// and undefined/non-string values are only allowed in object mode.
function validChunk(stream, state, chunk, cb) {
var valid = true;
var er = false;
if (chunk === null) {
er = new TypeError('May not write null values to stream');
} else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');
}
if (er) {
stream.emit('error', er);
pna.nextTick(cb, er);
valid = false;
}
return valid;
}
Writable.prototype.write = function (chunk, encoding, cb) {
var state = this._writableState;
var ret = false;
var isBuf = !state.objectMode && _isUint8Array(chunk);
if (isBuf && !Buffer.isBuffer(chunk)) {
chunk = _uint8ArrayToBuffer(chunk);
}
if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
if (typeof cb !== 'function') cb = nop;
if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
state.pendingcb++;
ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
}
return ret;
};
Writable.prototype.cork = function () {
var state = this._writableState;
state.corked++;
};
Writable.prototype.uncork = function () {
var state = this._writableState;
if (state.corked) {
state.corked--;
if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
}
};
Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
// node::ParseEncoding() requires lower case.
if (typeof encoding === 'string') encoding = encoding.toLowerCase();
if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
this._writableState.defaultEncoding = encoding;
return this;
};
function decodeChunk(state, chunk, encoding) {
if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
chunk = Buffer.from(chunk, encoding);
}
return chunk;
}
Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function () {
return this._writableState.highWaterMark;
}
});
// if we're already writing something, then just put this
// in the queue, and wait our turn. Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
if (!isBuf) {
var newChunk = decodeChunk(state, chunk, encoding);
if (chunk !== newChunk) {
isBuf = true;
encoding = 'buffer';
chunk = newChunk;
}
}
var len = state.objectMode ? 1 : chunk.length;
state.length += len;
var ret = state.length < state.highWaterMark;
// we must ensure that previous needDrain will not be reset to false.
if (!ret) state.needDrain = true;
if (state.writing || state.corked) {
var last = state.lastBufferedRequest;
state.lastBufferedRequest = {
chunk: chunk,
encoding: encoding,
isBuf: isBuf,
callback: cb,
next: null
};
if (last) {
last.next = state.lastBufferedRequest;
} else {
state.bufferedRequest = state.lastBufferedRequest;
}
state.bufferedRequestCount += 1;
} else {
doWrite(stream, state, false, len, chunk, encoding, cb);
}
return ret;
}
function doWrite(stream, state, writev, len, chunk, encoding, cb) {
state.writelen = len;
state.writecb = cb;
state.writing = true;
state.sync = true;
if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
state.sync = false;
}
function onwriteError(stream, state, sync, er, cb) {
--state.pendingcb;
if (sync) {
// defer the callback if we are being called synchronously
// to avoid piling up things on the stack
pna.nextTick(cb, er);
// this can emit finish, and it will always happen
// after error
pna.nextTick(finishMaybe, stream, state);
stream._writableState.errorEmitted = true;
stream.emit('error', er);
} else {
// the caller expect this to happen before if
// it is async
cb(er);
stream._writableState.errorEmitted = true;
stream.emit('error', er);
// this can emit finish, but finish must
// always follow error
finishMaybe(stream, state);
}
}
function onwriteStateUpdate(state) {
state.writing = false;
state.writecb = null;
state.length -= state.writelen;
state.writelen = 0;
}
function onwrite(stream, er) {
var state = stream._writableState;
var sync = state.sync;
var cb = state.writecb;
onwriteStateUpdate(state);
if (er) onwriteError(stream, state, sync, er, cb);else {
// Check if we're actually ready to finish, but don't emit yet
var finished = needFinish(state);
if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
clearBuffer(stream, state);
}
if (sync) {
/*<replacement>*/
asyncWrite(afterWrite, stream, state, finished, cb);
/*</replacement>*/
} else {
afterWrite(stream, state, finished, cb);
}
}
}
function afterWrite(stream, state, finished, cb) {
if (!finished) onwriteDrain(stream, state);
state.pendingcb--;
cb();
finishMaybe(stream, state);
}
// Must force callback to be called on nextTick, so that we don't
// emit 'drain' before the write() consumer gets the 'false' return
// value, and has a chance to attach a 'drain' listener.
function onwriteDrain(stream, state) {
if (state.length === 0 && state.needDrain) {
state.needDrain = false;
stream.emit('drain');
}
}
// if there's something in the buffer waiting, then process it
function clearBuffer(stream, state) {
state.bufferProcessing = true;
var entry = state.bufferedRequest;
if (stream._writev && entry && entry.next) {
// Fast case, write everything using _writev()
var l = state.bufferedRequestCount;
var buffer = new Array(l);
var holder = state.corkedRequestsFree;
holder.entry = entry;
var count = 0;
var allBuffers = true;
while (entry) {
buffer[count] = entry;
if (!entry.isBuf) allBuffers = false;
entry = entry.next;
count += 1;
}
buffer.allBuffers = allBuffers;
doWrite(stream, state, true, state.length, buffer, '', holder.finish);
// doWrite is almost always async, defer these to save a bit of time
// as the hot path ends with doWrite
state.pendingcb++;
state.lastBufferedRequest = null;
if (holder.next) {
state.corkedRequestsFree = holder.next;
holder.next = null;
} else {
state.corkedRequestsFree = new CorkedRequest(state);
}
state.bufferedRequestCount = 0;
} else {
// Slow case, write chunks one-by-one
while (entry) {
var chunk = entry.chunk;
var encoding = entry.encoding;
var cb = entry.callback;
var len = state.objectMode ? 1 : chunk.length;
doWrite(stream, state, false, len, chunk, encoding, cb);
entry = entry.next;
state.bufferedRequestCount--;
// if we didn't call the onwrite immediately, then
// it means that we need to wait until it does.
// also, that means that the chunk and cb are currently
// being processed, so move the buffer counter past them.
if (state.writing) {
break;
}
}
if (entry === null) state.lastBufferedRequest = null;
}
state.bufferedRequest = entry;
state.bufferProcessing = false;
}
Writable.prototype._write = function (chunk, encoding, cb) {
cb(new Error('_write() is not implemented'));
};
Writable.prototype._writev = null;
Writable.prototype.end = function (chunk, encoding, cb) {
var state = this._writableState;
if (typeof chunk === 'function') {
cb = chunk;
chunk = null;
encoding = null;
} else if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
// .end() fully uncorks
if (state.corked) {
state.corked = 1;
this.uncork();
}
// ignore unnecessary end() calls.
if (!state.ending && !state.finished) endWritable(this, state, cb);
};
function needFinish(state) {
return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
}
function callFinal(stream, state) {
stream._final(function (err) {
state.pendingcb--;
if (err) {
stream.emit('error', err);
}
state.prefinished = true;
stream.emit('prefinish');
finishMaybe(stream, state);
});
}
function prefinish(stream, state) {
if (!state.prefinished && !state.finalCalled) {
if (typeof stream._final === 'function') {
state.pendingcb++;
state.finalCalled = true;
pna.nextTick(callFinal, stream, state);
} else {
state.prefinished = true;
stream.emit('prefinish');
}
}
}
function finishMaybe(stream, state) {
var need = needFinish(state);
if (need) {
prefinish(stream, state);
if (state.pendingcb === 0) {
state.finished = true;
stream.emit('finish');
}
}
return need;
}
function endWritable(stream, state, cb) {
state.ending = true;
finishMaybe(stream, state);
if (cb) {
if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
}
state.ended = true;
stream.writable = false;
}
function onCorkedFinish(corkReq, state, err) {
var entry = corkReq.entry;
corkReq.entry = null;
while (entry) {
var cb = entry.callback;
state.pendingcb--;
cb(err);
entry = entry.next;
}
if (state.corkedRequestsFree) {
state.corkedRequestsFree.next = corkReq;
} else {
state.corkedRequestsFree = corkReq;
}
}
Object.defineProperty(Writable.prototype, 'destroyed', {
get: function () {
if (this._writableState === undefined) {
return false;
}
return this._writableState.destroyed;
},
set: function (value) {
// we ignore the value if the stream
// has not been initialized yet
if (!this._writableState) {
return;
}
// backward compatibility, the user is explicitly
// managing destroyed
this._writableState.destroyed = value;
}
});
Writable.prototype.destroy = destroyImpl.destroy;
Writable.prototype._undestroy = destroyImpl.undestroy;
Writable.prototype._destroy = function (err, cb) {
this.end();
cb(err);
};
}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate)
},{"./_stream_duplex":390,"./internal/streams/destroy":396,"./internal/streams/stream":397,"_process":389,"core-util-is":380,"inherits":384,"process-nextick-args":388,"safe-buffer":399,"timers":401,"util-deprecate":402}],395:[function(require,module,exports){
'use strict';
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Buffer = require('safe-buffer').Buffer;
var util = require('util');
function copyBuffer(src, target, offset) {
src.copy(target, offset);
}
module.exports = function () {
function BufferList() {
_classCallCheck(this, BufferList);
this.head = null;
this.tail = null;
this.length = 0;
}
BufferList.prototype.push = function push(v) {
var entry = { data: v, next: null };
if (this.length > 0) this.tail.next = entry;else this.head = entry;
this.tail = entry;
++this.length;
};
BufferList.prototype.unshift = function unshift(v) {
var entry = { data: v, next: this.head };
if (this.length === 0) this.tail = entry;
this.head = entry;
++this.length;
};
BufferList.prototype.shift = function shift() {
if (this.length === 0) return;
var ret = this.head.data;
if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
--this.length;
return ret;
};
BufferList.prototype.clear = function clear() {
this.head = this.tail = null;
this.length = 0;
};
BufferList.prototype.join = function join(s) {
if (this.length === 0) return '';
var p = this.head;
var ret = '' + p.data;
while (p = p.next) {
ret += s + p.data;
}return ret;
};
BufferList.prototype.concat = function concat(n) {
if (this.length === 0) return Buffer.alloc(0);
if (this.length === 1) return this.head.data;
var ret = Buffer.allocUnsafe(n >>> 0);
var p = this.head;
var i = 0;
while (p) {
copyBuffer(p.data, ret, i);
i += p.data.length;
p = p.next;
}
return ret;
};
return BufferList;
}();
if (util && util.inspect && util.inspect.custom) {
module.exports.prototype[util.inspect.custom] = function () {
var obj = util.inspect({ length: this.length });
return this.constructor.name + ' ' + obj;
};
}
},{"safe-buffer":399,"util":377}],396:[function(require,module,exports){
'use strict';
/*<replacement>*/
var pna = require('process-nextick-args');
/*</replacement>*/
// undocumented cb() API, needed for core, not for public API
function destroy(err, cb) {
var _this = this;
var readableDestroyed = this._readableState && this._readableState.destroyed;
var writableDestroyed = this._writableState && this._writableState.destroyed;
if (readableDestroyed || writableDestroyed) {
if (cb) {
cb(err);
} else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
pna.nextTick(emitErrorNT, this, err);
}
return this;
}
// we set destroyed to true before firing error callbacks in order
// to make it re-entrance safe in case destroy() is called within callbacks
if (this._readableState) {
this._readableState.destroyed = true;
}
// if this is a duplex stream mark the writable part as destroyed as well
if (this._writableState) {
this._writableState.destroyed = true;
}
this._destroy(err || null, function (err) {
if (!cb && err) {
pna.nextTick(emitErrorNT, _this, err);
if (_this._writableState) {
_this._writableState.errorEmitted = true;
}
} else if (cb) {
cb(err);
}
});
return this;
}
function undestroy() {
if (this._readableState) {
this._readableState.destroyed = false;
this._readableState.reading = false;
this._readableState.ended = false;
this._readableState.endEmitted = false;
}
if (this._writableState) {
this._writableState.destroyed = false;
this._writableState.ended = false;
this._writableState.ending = false;
this._writableState.finished = false;
this._writableState.errorEmitted = false;
}
}
function emitErrorNT(self, err) {
self.emit('error', err);
}
module.exports = {
destroy: destroy,
undestroy: undestroy
};
},{"process-nextick-args":388}],397:[function(require,module,exports){
module.exports = require('events').EventEmitter;
},{"events":378}],398:[function(require,module,exports){
exports = module.exports = require('./lib/_stream_readable.js');
exports.Stream = exports;
exports.Readable = exports;
exports.Writable = require('./lib/_stream_writable.js');
exports.Duplex = require('./lib/_stream_duplex.js');
exports.Transform = require('./lib/_stream_transform.js');
exports.PassThrough = require('./lib/_stream_passthrough.js');
},{"./lib/_stream_duplex.js":390,"./lib/_stream_passthrough.js":391,"./lib/_stream_readable.js":392,"./lib/_stream_transform.js":393,"./lib/_stream_writable.js":394}],399:[function(require,module,exports){
/* eslint-disable node/no-deprecated-api */
var buffer = require('buffer')
var Buffer = buffer.Buffer
// alternative to using Object.keys for old browsers
function copyProps (src, dst) {
for (var key in src) {
dst[key] = src[key]
}
}
if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
module.exports = buffer
} else {
// Copy properties from require('buffer')
copyProps(buffer, exports)
exports.Buffer = SafeBuffer
}
function SafeBuffer (arg, encodingOrOffset, length) {
return Buffer(arg, encodingOrOffset, length)
}
// Copy static methods from Buffer
copyProps(Buffer, SafeBuffer)
SafeBuffer.from = function (arg, encodingOrOffset, length) {
if (typeof arg === 'number') {
throw new TypeError('Argument must not be a number')
}
return Buffer(arg, encodingOrOffset, length)
}
SafeBuffer.alloc = function (size, fill, encoding) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
var buf = Buffer(size)
if (fill !== undefined) {
if (typeof encoding === 'string') {
buf.fill(fill, encoding)
} else {
buf.fill(fill)
}
} else {
buf.fill(0)
}
return buf
}
SafeBuffer.allocUnsafe = function (size) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
return Buffer(size)
}
SafeBuffer.allocUnsafeSlow = function (size) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
return buffer.SlowBuffer(size)
}
},{"buffer":379}],400:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
'use strict';
/*<replacement>*/
var Buffer = require('safe-buffer').Buffer;
/*</replacement>*/
var isEncoding = Buffer.isEncoding || function (encoding) {
encoding = '' + encoding;
switch (encoding && encoding.toLowerCase()) {
case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
return true;
default:
return false;
}
};
function _normalizeEncoding(enc) {
if (!enc) return 'utf8';
var retried;
while (true) {
switch (enc) {
case 'utf8':
case 'utf-8':
return 'utf8';
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return 'utf16le';
case 'latin1':
case 'binary':
return 'latin1';
case 'base64':
case 'ascii':
case 'hex':
return enc;
default:
if (retried) return; // undefined
enc = ('' + enc).toLowerCase();
retried = true;
}
}
};
// Do not cache `Buffer.isEncoding` when checking encoding names as some
// modules monkey-patch it to support additional encodings
function normalizeEncoding(enc) {
var nenc = _normalizeEncoding(enc);
if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
return nenc || enc;
}
// StringDecoder provides an interface for efficiently splitting a series of
// buffers into a series of JS strings without breaking apart multi-byte
// characters.
exports.StringDecoder = StringDecoder;
function StringDecoder(encoding) {
this.encoding = normalizeEncoding(encoding);
var nb;
switch (this.encoding) {
case 'utf16le':
this.text = utf16Text;
this.end = utf16End;
nb = 4;
break;
case 'utf8':
this.fillLast = utf8FillLast;
nb = 4;
break;
case 'base64':
this.text = base64Text;
this.end = base64End;
nb = 3;
break;
default:
this.write = simpleWrite;
this.end = simpleEnd;
return;
}
this.lastNeed = 0;
this.lastTotal = 0;
this.lastChar = Buffer.allocUnsafe(nb);
}
StringDecoder.prototype.write = function (buf) {
if (buf.length === 0) return '';
var r;
var i;
if (this.lastNeed) {
r = this.fillLast(buf);
if (r === undefined) return '';
i = this.lastNeed;
this.lastNeed = 0;
} else {
i = 0;
}
if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
return r || '';
};
StringDecoder.prototype.end = utf8End;
// Returns only complete characters in a Buffer
StringDecoder.prototype.text = utf8Text;
// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
StringDecoder.prototype.fillLast = function (buf) {
if (this.lastNeed <= buf.length) {
buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
return this.lastChar.toString(this.encoding, 0, this.lastTotal);
}
buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
this.lastNeed -= buf.length;
};
// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
// continuation byte. If an invalid byte is detected, -2 is returned.
function utf8CheckByte(byte) {
if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
return byte >> 6 === 0x02 ? -1 : -2;
}
// Checks at most 3 bytes at the end of a Buffer in order to detect an
// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
// needed to complete the UTF-8 character (if applicable) are returned.
function utf8CheckIncomplete(self, buf, i) {
var j = buf.length - 1;
if (j < i) return 0;
var nb = utf8CheckByte(buf[j]);
if (nb >= 0) {
if (nb > 0) self.lastNeed = nb - 1;
return nb;
}
if (--j < i || nb === -2) return 0;
nb = utf8CheckByte(buf[j]);
if (nb >= 0) {
if (nb > 0) self.lastNeed = nb - 2;
return nb;
}
if (--j < i || nb === -2) return 0;
nb = utf8CheckByte(buf[j]);
if (nb >= 0) {
if (nb > 0) {
if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
}
return nb;
}
return 0;
}
// Validates as many continuation bytes for a multi-byte UTF-8 character as
// needed or are available. If we see a non-continuation byte where we expect
// one, we "replace" the validated continuation bytes we've seen so far with
// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
// behavior. The continuation byte check is included three times in the case
// where all of the continuation bytes for a character exist in the same buffer.
// It is also done this way as a slight performance increase instead of using a
// loop.
function utf8CheckExtraBytes(self, buf, p) {
if ((buf[0] & 0xC0) !== 0x80) {
self.lastNeed = 0;
return '\ufffd';
}
if (self.lastNeed > 1 && buf.length > 1) {
if ((buf[1] & 0xC0) !== 0x80) {
self.lastNeed = 1;
return '\ufffd';
}
if (self.lastNeed > 2 && buf.length > 2) {
if ((buf[2] & 0xC0) !== 0x80) {
self.lastNeed = 2;
return '\ufffd';
}
}
}
}
// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
function utf8FillLast(buf) {
var p = this.lastTotal - this.lastNeed;
var r = utf8CheckExtraBytes(this, buf, p);
if (r !== undefined) return r;
if (this.lastNeed <= buf.length) {
buf.copy(this.lastChar, p, 0, this.lastNeed);
return this.lastChar.toString(this.encoding, 0, this.lastTotal);
}
buf.copy(this.lastChar, p, 0, buf.length);
this.lastNeed -= buf.length;
}
// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
// partial character, the character's bytes are buffered until the required
// number of bytes are available.
function utf8Text(buf, i) {
var total = utf8CheckIncomplete(this, buf, i);
if (!this.lastNeed) return buf.toString('utf8', i);
this.lastTotal = total;
var end = buf.length - (total - this.lastNeed);
buf.copy(this.lastChar, 0, end);
return buf.toString('utf8', i, end);
}
// For UTF-8, a replacement character is added when ending on a partial
// character.
function utf8End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) return r + '\ufffd';
return r;
}
// UTF-16LE typically needs two bytes per character, but even if we have an even
// number of bytes available, we need to check if we end on a leading/high
// surrogate. In that case, we need to wait for the next two bytes in order to
// decode the last character properly.
function utf16Text(buf, i) {
if ((buf.length - i) % 2 === 0) {
var r = buf.toString('utf16le', i);
if (r) {
var c = r.charCodeAt(r.length - 1);
if (c >= 0xD800 && c <= 0xDBFF) {
this.lastNeed = 2;
this.lastTotal = 4;
this.lastChar[0] = buf[buf.length - 2];
this.lastChar[1] = buf[buf.length - 1];
return r.slice(0, -1);
}
}
return r;
}
this.lastNeed = 1;
this.lastTotal = 2;
this.lastChar[0] = buf[buf.length - 1];
return buf.toString('utf16le', i, buf.length - 1);
}
// For UTF-16LE we do not explicitly append special replacement characters if we
// end on a partial character, we simply let v8 handle that.
function utf16End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) {
var end = this.lastTotal - this.lastNeed;
return r + this.lastChar.toString('utf16le', 0, end);
}
return r;
}
function base64Text(buf, i) {
var n = (buf.length - i) % 3;
if (n === 0) return buf.toString('base64', i);
this.lastNeed = 3 - n;
this.lastTotal = 3;
if (n === 1) {
this.lastChar[0] = buf[buf.length - 1];
} else {
this.lastChar[0] = buf[buf.length - 2];
this.lastChar[1] = buf[buf.length - 1];
}
return buf.toString('base64', i, buf.length - n);
}
function base64End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
return r;
}
// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
function simpleWrite(buf) {
return buf.toString(this.encoding);
}
function simpleEnd(buf) {
return buf && buf.length ? this.write(buf) : '';
}
},{"safe-buffer":399}],401:[function(require,module,exports){
(function (setImmediate,clearImmediate){(function (){
var nextTick = require('process/browser.js').nextTick;
var apply = Function.prototype.apply;
var slice = Array.prototype.slice;
var immediateIds = {};
var nextImmediateId = 0;
// DOM APIs, for completeness
exports.setTimeout = function() {
return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
};
exports.setInterval = function() {
return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
};
exports.clearTimeout =
exports.clearInterval = function(timeout) { timeout.close(); };
function Timeout(id, clearFn) {
this._id = id;
this._clearFn = clearFn;
}
Timeout.prototype.unref = Timeout.prototype.ref = function() {};
Timeout.prototype.close = function() {
this._clearFn.call(window, this._id);
};
// Does not start the time, just sets up the members needed.
exports.enroll = function(item, msecs) {
clearTimeout(item._idleTimeoutId);
item._idleTimeout = msecs;
};
exports.unenroll = function(item) {
clearTimeout(item._idleTimeoutId);
item._idleTimeout = -1;
};
exports._unrefActive = exports.active = function(item) {
clearTimeout(item._idleTimeoutId);
var msecs = item._idleTimeout;
if (msecs >= 0) {
item._idleTimeoutId = setTimeout(function onTimeout() {
if (item._onTimeout)
item._onTimeout();
}, msecs);
}
};
// That's not how node.js implements it but the exposed api is the same.
exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
var id = nextImmediateId++;
var args = arguments.length < 2 ? false : slice.call(arguments, 1);
immediateIds[id] = true;
nextTick(function onNextTick() {
if (immediateIds[id]) {
// fn.call() is faster so we optimize for the common use-case
// @see http://jsperf.com/call-apply-segu
if (args) {
fn.apply(null, args);
} else {
fn.call(null);
}
// Prevent ids from leaking
exports.clearImmediate(id);
}
});
return id;
};
exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
delete immediateIds[id];
};
}).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate)
},{"process/browser.js":389,"timers":401}],402:[function(require,module,exports){
(function (global){(function (){
/**
* Module exports.
*/
module.exports = deprecate;
/**
* Mark that a method should not be used.
* Returns a modified function which warns once by default.
*
* If `localStorage.noDeprecation = true` is set, then it is a no-op.
*
* If `localStorage.throwDeprecation = true` is set, then deprecated functions
* will throw an Error when invoked.
*
* If `localStorage.traceDeprecation = true` is set, then deprecated functions
* will invoke `console.trace()` instead of `console.error()`.
*
* @param {Function} fn - the function to deprecate
* @param {String} msg - the string to print to the console when `fn` is invoked
* @returns {Function} a new "deprecated" version of `fn`
* @api public
*/
function deprecate (fn, msg) {
if (config('noDeprecation')) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (config('throwDeprecation')) {
throw new Error(msg);
} else if (config('traceDeprecation')) {
console.trace(msg);
} else {
console.warn(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
}
/**
* Checks `localStorage` for boolean values for the given `name`.
*
* @param {String} name
* @returns {Boolean}
* @api private
*/
function config (name) {
// accessing global.localStorage can trigger a DOMException in sandboxed iframes
try {
if (!global.localStorage) return false;
} catch (_) {
return false;
}
var val = global.localStorage[name];
if (null == val) return false;
return String(val).toLowerCase() === 'true';
}
}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}]},{},[306]);<|fim▁end|> | // MODULES // |
<|file_name|>StringUtils.java<|end_file_name|><|fim▁begin|>package ch.hgdev.toposuite.utils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Useful static method for manipulating String.
*
* @author HGdev
*/
public class StringUtils {
public static final String UTF8_BOM = "\uFEFF";
/**
* This method assumes that the String contains a number.
*
* @param str A String.
* @return The String incremented by 1.
* @throws IllegalArgumentException Thrown if the input String does not end with a suitable
* number.
*/
public static String incrementAsNumber(String str) throws IllegalArgumentException {
if (str == null) {
throw new IllegalArgumentException("The input String must not be null!");
}
Pattern p = Pattern.compile("([0-9]+)$");
Matcher m = p.matcher(str);
if (!m.find()) {<|fim▁hole|> throw new IllegalArgumentException(
"Invalid input argument! The input String must end with a valid number");
}
String number = m.group(1);
String prefix = str.substring(0, str.length() - number.length());
return prefix + String.valueOf(Integer.valueOf(number) + 1);
}
}<|fim▁end|> | |
<|file_name|>java_agent.java<|end_file_name|><|fim▁begin|>import ch.usi.overseer.OverAgent;
import ch.usi.overseer.OverHpc;
/**
* Overseer.OverAgent sample application.
* This example shows a basic usage of the OverAgent java agent to keep track of all the threads created
* by the JVM. Threads include garbage collectors, finalizers, etc. In order to use OverAgent, make sure to <|fim▁hole|> *
* -agentpath:/usr/local/lib/liboverAgent.so
*
* @author Achille Peternier (C) 2011 USI
*/
public class java_agent
{
static public void main(String argv[])
{
// Credits:
System.out.println("Overseer Java Agent test, A. Peternier (C) USI 2011\n");
// Check that -agentpath is working:
if (OverAgent.isRunning())
System.out.println(" OverAgent is running");
else
{
System.out.println(" OverAgent is not running (check your JVM settings)");
return;
}
// Get some info:
System.out.println(" Threads running: " + OverAgent.getNumberOfThreads());
System.out.println();
OverAgent.initEventCallback(new OverAgent.Callback()
{
// Callback invoked at thread creation:
public int onThreadCreation(int pid, String name)
{
System.out.println("[new] " + name + " (" + pid + ")");
return 0;
}
// Callback invoked at thread termination:
public int onThreadTermination(int pid, String name)
{
System.out.println("[delete] " + name + " (" + pid + ")");
return 0;
}});
OverHpc oHpc = OverHpc.getInstance();
int pid = oHpc.getThreadId();
OverAgent.updateStats();
// Waste some time:
double r = 0.0;
for (int d=0; d<10; d++)
{
if (true)
{
for (long c=0; c<100000000; c++)
{
r += r * Math.sqrt(r) * Math.pow(r, 40.0);
}
}
else
{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
OverAgent.updateStats();
System.out.println(" Thread " + pid + " abs: " + OverAgent.getThreadCpuUsage(pid) + "%, rel: " + OverAgent.getThreadCpuUsageRelative(pid) + "%");
}
// Done:
System.out.println("Application terminated");
}
}<|fim▁end|> | * append this option to your command-line: |
<|file_name|>refextract_cli.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""This is file handles the command line interface
* We parse the options for both daemon and standalone usage
* When using using the standalone mode, we use the function "main"
defined here to begin the extraction of references
"""
__revision__ = "$Id$"
import traceback
import optparse
import sys
from invenio.docextract_record import print_records
from invenio.docextract_utils import write_message, setup_loggers
from invenio.bibtask import task_update_progress
from invenio.refextract_api import extract_references_from_file, \
extract_references_from_string
# Is refextract running standalone? (Default = yes)
RUNNING_INDEPENDENTLY = False
DESCRIPTION = ""
# Help message, used by bibtask's 'task_init()' and 'usage()'
HELP_MESSAGE = """
--kb-journals Manually specify the location of a journal title
knowledge-base file.
--kb-journals-re Manually specify the location of a journal title regexps
knowledge-base file.
--kb-report-numbers Manually specify the location of a report number
knowledge-base file.
--kb-authors Manually specify the location of an author
knowledge-base file.
--kb-books Manually specify the location of a book
knowledge-base file.
--no-overwrite Do not touch record if it already has references
"""
HELP_STANDALONE_MESSAGE = """
Standalone Refextract options:
-o, --out Write the extracted references, in xml form, to a file
rather than standard output.
--dictfile Write statistics about all matched title abbreviations
(i.e. LHS terms in the titles knowledge base) to a file.
--output-raw-refs Output raw references, as extracted from the document.
No MARC XML mark-up - just each extracted line, prefixed
by the recid of the document that it came from.
--raw-references Treat the input file as pure references. i.e. skip the
stage of trying to locate the reference section within a
document and instead move to the stage of recognition
and standardisation of citations within lines.
"""
USAGE_MESSAGE = """Usage: docextract [options] file1 [file2 ...]
Command options: %s%s
Examples:
docextract -o /home/chayward/refs.xml /home/chayward/thesis.pdf
""" % (HELP_MESSAGE, HELP_STANDALONE_MESSAGE)
def get_cli_options():
"""Get the various arguments and options from the command line and populate
a dictionary of cli_options.
@return: (tuple) of 2 elements. First element is a dictionary of cli
options and flags, set as appropriate; Second element is a list of cli
arguments.
"""
parser = optparse.OptionParser(description=DESCRIPTION,
usage=USAGE_MESSAGE,
add_help_option=False)
# Display help and exit
parser.add_option('-h', '--help', action='store_true')
# Display version and exit
parser.add_option('-V', '--version', action='store_true')
# Output recognised journal titles in the Inspire compatible format
parser.add_option('-i', '--inspire', action='store_true')
# The location of the report number kb requested to override
# a 'configuration file'-specified kb
parser.add_option('--kb-report-numbers', dest='kb_report_numbers')
# The location of the journal title kb requested to override
# a 'configuration file'-specified kb, holding
# 'seek---replace' terms, used when matching titles in references
parser.add_option('--kb-journals', dest='kb_journals')
parser.add_option('--kb-journals-re', dest='kb_journals_re')
# The location of the author kb requested to override
parser.add_option('--kb-authors', dest='kb_authors')
# The location of the author kb requested to override
parser.add_option('--kb-books', dest='kb_books')
# The location of the author kb requested to override
parser.add_option('--kb-conferences', dest='kb_conferences')
# Write out the statistics of all titles matched during the
# extraction job to the specified file
parser.add_option('--dictfile')
# Write out MARC XML references to the specified file
parser.add_option('-o', '--out', dest='xmlfile')
# Handle verbosity
parser.add_option('-v', '--verbose', type=int, dest='verbosity', default=0)
# Output a raw list of refs
parser.add_option('--output-raw-refs', action='store_true',
dest='output_raw')
# Treat input as pure reference lines:
# (bypass the reference section lookup)
parser.add_option('--raw-references', action='store_true',
dest='treat_as_reference_section')
return parser.parse_args()
def halt(err=StandardError, msg=None, exit_code=1):
""" Stop extraction, and deal with the error in the appropriate
manner, based on whether Refextract is running in standalone or
bibsched mode.
@param err: (exception) The exception raised from an error, if any
@param msg: (string) The brief error message, either displayed
on the bibsched interface, or written to stderr.
@param exit_code: (integer) Either 0 or 1, depending on the cause
of the halting. This is only used when running standalone."""
# If refextract is running independently, exit.
# 'RUNNING_INDEPENDENTLY' is a global variable
if RUNNING_INDEPENDENTLY:
if msg:
write_message(msg, stream=sys.stderr, verbose=0)
sys.exit(exit_code)
# Else, raise an exception so Bibsched will flag this task.
else:
if msg:
# Update the status of refextract inside the Bibsched UI
task_update_progress(msg.strip())
raise err(msg)
def usage(wmsg=None, err_code=0):
"""Display a usage message for refextract on the standard error stream and
then exit.
@param wmsg: (string) some kind of brief warning message for the user.
@param err_code: (integer) an error code to be passed to halt,
which is called after the usage message has been printed.
@return: None.
"""
if wmsg:
wmsg = wmsg.strip()
# Display the help information and the warning in the stderr stream
# 'help_message' is global
print >> sys.stderr, USAGE_MESSAGE
# Output error message, either to the stderr stream also or
# on the interface. Stop the extraction procedure
halt(msg=wmsg, exit_code=err_code)
def main(config, args, run):
"""Main wrapper function for begin_extraction, and is
always accessed in a standalone/independent way. (i.e. calling main
will cause refextract to run in an independent mode)"""
# Flag as running out of bibtask
global RUNNING_INDEPENDENTLY
RUNNING_INDEPENDENTLY = True
if config.verbosity not in range(0, 10):
usage("Error: Verbosity must be an integer between 0 and 10")
setup_loggers(config.verbosity)
if config.version:
# version message and exit
write_message(__revision__, verbose=0)
halt(exit_code=0)
if config.help:
usage()
if not args:
# no files provided for reference extraction - error message
usage("Error: No valid input file specified (file1 [file2 ...])")
try:
run(config, args)
write_message("Extraction complete", verbose=2)
except StandardError, e:
# Remove extra '\n'
write_message(traceback.format_exc()[:-1], verbose=9)
write_message("Error: %s" % e, verbose=0)
halt(exit_code=1)
def extract_one(config, pdf_path):
"""Extract references from one file"""<|fim▁hole|> if config.treat_as_reference_section:
docbody = open(pdf_path).read().decode('utf-8')
record = extract_references_from_string(docbody)
else:
write_message("* processing pdffile: %s" % pdf_path, verbose=2)
record = extract_references_from_file(pdf_path)
return record
def begin_extraction(config, files):
"""Starts the core extraction procedure. [Entry point from main]
Only refextract_daemon calls this directly, from _task_run_core()
@param daemon_cli_options: contains the pre-assembled list of cli flags
and values processed by the Refextract Daemon. This is full only when
called as a scheduled bibtask inside bibsched.
"""
# Store records here
records = []
for num, path in enumerate(files):
# Announce the document extraction number
write_message("Extracting %d of %d" % (num + 1, len(files)),
verbose=1)
# Parse references
rec = extract_one(config, path)
records.append(rec)
# Write our references
write_references(config, records)
def write_references(config, records):
"""Write in marcxml"""
if config.xmlfile:
ofilehdl = open(config.xmlfile, 'w')
else:
ofilehdl = sys.stdout
if config.xmlfile:
for rec in records:
for subfield in rec.find_subfields('999C5m'):
if len(subfield.value) > 2048:
subfield.value = subfield.value[:2048]
try:
xml = print_records(records)
print >>ofilehdl, xml
ofilehdl.flush()
except IOError, err:
write_message("%s\n%s\n" % (config.xmlfile, err),
sys.stderr, verbose=0)
halt(err=IOError, msg="Error: Unable to write to '%s'"
% config.xmlfile, exit_code=1)<|fim▁end|> | # If necessary, locate the reference section: |
<|file_name|>ExecuteAsynchronousScript.spec.ts<|end_file_name|><|fim▁begin|>import 'mocha';
import { EventRecorder, expect } from '@integration/testing-tools';
import { Ensure, equals } from '@serenity-js/assertions';
import { actorCalled, Question, Serenity } from '@serenity-js/core';
import { ActivityFinished, ActivityRelatedArtifactGenerated, ActivityStarts, ArtifactGenerated } from '@serenity-js/core/lib/events';
import { TextData } from '@serenity-js/core/lib/model';
import { Clock } from '@serenity-js/core/lib/stage';
import { by, ExecuteScript, Navigate, Target, Value } from '../../../../src';
import { Actors } from '../../Actors';
/** @test {ExecuteScript} */
describe('ExecuteAsynchronousScript', function () {
class Sandbox {
static Input = Target.the('input field').located(by.id('name'));
}
/** @test {ExecuteScript.async} */
/** @test {ExecuteAsynchronousScript} */
it('allows the actor to execute an asynchronous script', () =>
actorCalled('Joe').attemptsTo(
Navigate.to('/screenplay/interactions/execute-script/input_field.html'),
ExecuteScript.async(`
var callback = arguments[arguments.length - 1];
setTimeout(function () {
document.getElementById('name').value = 'Joe';
callback();
}, 100);
`),
Ensure.that(Value.of(Sandbox.Input), equals(actorCalled('Joe').name)),
));
/** @test {ExecuteScript.async} */
/** @test {ExecuteAsynchronousScript} */
it('allows the actor to execute an asynchronous script with a static argument', () =>
actorCalled('Joe').attemptsTo(
Navigate.to('/screenplay/interactions/execute-script/input_field.html'),
ExecuteScript.async(`
var name = arguments[0];
var callback = arguments[arguments.length - 1];
setTimeout(function () {
document.getElementById('name').value = name;
callback();
}, 100);
`).withArguments(actorCalled('Joe').name),
Ensure.that(Value.of(Sandbox.Input), equals(actorCalled('Joe').name)),
));
/** @test {ExecuteScript.async} */
/** @test {ExecuteAsynchronousScript} */
it('allows the actor to execute an asynchronous script with a promised argument', () =>
actorCalled('Joe').attemptsTo(
Navigate.to('/screenplay/interactions/execute-script/input_field.html'),
ExecuteScript.async(`
var name = arguments[0];
var callback = arguments[arguments.length - 1];
setTimeout(function () {
document.getElementById('name').value = name;
callback();
}, 100);
`).withArguments(Promise.resolve(actorCalled('Joe').name)),
Ensure.that(Value.of(Sandbox.Input), equals(actorCalled('Joe').name)),
));
/** @test {ExecuteScript.async} */
/** @test {ExecuteAsynchronousScript} */
it('allows the actor to execute an asynchronous script with a Target argument', () =>
actorCalled('Joe').attemptsTo(
Navigate.to('/screenplay/interactions/execute-script/input_field.html'),
ExecuteScript.async(`
var name = arguments[0];
var field = arguments[1];
var callback = arguments[arguments.length - 1];
setTimeout(function () {
field.value = name;
callback();
}, 100);
`).withArguments(actorCalled('Joe').name, Sandbox.Input),
Ensure.that(Value.of(Sandbox.Input), equals(actorCalled('Joe').name)),
));
/** @test {ExecuteScript.async} */
/** @test {ExecuteAsynchronousScript} */
/** @test {ExecuteAsynchronousScript#toString} */
it('provides a sensible description of the interaction being performed when invoked without arguments', () => {
expect(ExecuteScript.async(`
arguments[arguments.length - 1]();
`).toString()).to.equal(`#actor executes an asynchronous script`);
});
/** @test {ExecuteScript.async} */
/** @test {ExecuteAsynchronousScript#toString} */
it('provides a sensible description of the interaction being performed when invoked with arguments', () => {
const arg3 = Question.about('arg number 3', actor => void 0);
expect(ExecuteScript.async(`arguments[arguments.length - 1]();`)
.withArguments(Promise.resolve('arg1'), 'arg2', arg3).toString(),
).to.equal(`#actor executes an asynchronous script with arguments: [ a Promise, 'arg2', arg number 3 ]`);
});
<|fim▁hole|> expect(actorCalled('Joe').attemptsTo(
Navigate.to('/screenplay/interactions/execute-script/input_field.html'),
ExecuteScript.async(`
var callback = arguments[arguments.length - 1];
throw new Error("something's not quite right here");
`),
)).to.be.rejectedWith(Error, `something's not quite right here`));
/** @test {ExecuteScript.async} */
/** @test {ExecuteAsynchronousScript} */
it('emits the events so that the details of the script being executed can be reported', () => {
const frozenClock = new Clock(() => new Date('1970-01-01'));
const serenity = new Serenity(frozenClock);
const recorder = new EventRecorder();
serenity.configure({
actors: new Actors(),
crew: [ recorder ],
});
return serenity.theActorCalled('Ashwin').attemptsTo(
ExecuteScript.async(`arguments[arguments.length - 1]();`),
).then(() => {
const events = recorder.events;
expect(events).to.have.lengthOf(3);
expect(events[ 0 ]).to.be.instanceOf(ActivityStarts);
expect(events[ 1 ]).to.be.instanceOf(ArtifactGenerated);
expect(events[ 2 ]).to.be.instanceOf(ActivityFinished);
const artifactGenerated = events[ 1 ] as ActivityRelatedArtifactGenerated;
expect(artifactGenerated.name.value).to.equal(`Script source`);
expect(artifactGenerated.artifact.equals(TextData.fromJSON({
contentType: 'text/javascript;charset=UTF-8',
data: 'arguments[arguments.length - 1]();',
}))).to.equal(true, JSON.stringify(artifactGenerated.artifact.toJSON()));
expect(artifactGenerated.timestamp.equals(frozenClock.now())).to.equal(true, artifactGenerated.timestamp.toString());
});
});
});<|fim▁end|> | /** @test {ExecuteScript.async} */
/** @test {ExecuteAsynchronousScript} */
it('complains if the script has failed', () => |
<|file_name|>element.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Element nodes.
use devtools_traits::AttrInfo;
use dom::activation::Activatable;
use dom::attr::{Attr, AttrHelpersForLayout};
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods;
use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
use dom::bindings::codegen::Bindings::ElementBinding;
use dom::bindings::codegen::Bindings::ElementBinding::ElementMethods;
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::FunctionBinding::Function;
use dom::bindings::codegen::Bindings::HTMLTemplateElementBinding::HTMLTemplateElementMethods;
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::codegen::Bindings::WindowBinding::{ScrollBehavior, ScrollToOptions};
use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use dom::bindings::codegen::UnionTypes::NodeOrString;
use dom::bindings::conversions::DerivedFrom;
use dom::bindings::error::{Error, ErrorResult, Fallible};
use dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId};
use dom::bindings::refcounted::{Trusted, TrustedPromise};
use dom::bindings::reflector::DomObject;
use dom::bindings::root::{Dom, DomRoot, LayoutDom, MutNullableDom, RootedReference};
use dom::bindings::str::DOMString;
use dom::bindings::xmlname::{namespace_from_domstring, validate_and_extract, xml_name_type};
use dom::bindings::xmlname::XMLName::InvalidXMLName;
use dom::characterdata::CharacterData;
use dom::create::create_element;
use dom::customelementregistry::{CallbackReaction, CustomElementDefinition, CustomElementReaction};
use dom::document::{Document, LayoutDocumentHelpers};
use dom::documentfragment::DocumentFragment;
use dom::domrect::DOMRect;
use dom::domtokenlist::DOMTokenList;
use dom::event::Event;
use dom::eventtarget::EventTarget;
use dom::htmlanchorelement::HTMLAnchorElement;
use dom::htmlbodyelement::{HTMLBodyElement, HTMLBodyElementLayoutHelpers};
use dom::htmlbuttonelement::HTMLButtonElement;
use dom::htmlcanvaselement::{HTMLCanvasElement, LayoutHTMLCanvasElementHelpers};
use dom::htmlcollection::HTMLCollection;
use dom::htmlelement::HTMLElement;
use dom::htmlfieldsetelement::HTMLFieldSetElement;
use dom::htmlfontelement::{HTMLFontElement, HTMLFontElementLayoutHelpers};
use dom::htmlformelement::FormControlElementHelpers;
use dom::htmlhrelement::{HTMLHRElement, HTMLHRLayoutHelpers};
use dom::htmliframeelement::{HTMLIFrameElement, HTMLIFrameElementLayoutMethods};
use dom::htmlimageelement::{HTMLImageElement, LayoutHTMLImageElementHelpers};
use dom::htmlinputelement::{HTMLInputElement, LayoutHTMLInputElementHelpers};
use dom::htmllabelelement::HTMLLabelElement;
use dom::htmllegendelement::HTMLLegendElement;
use dom::htmllinkelement::HTMLLinkElement;
use dom::htmlobjectelement::HTMLObjectElement;
use dom::htmloptgroupelement::HTMLOptGroupElement;
use dom::htmlselectelement::HTMLSelectElement;
use dom::htmlstyleelement::HTMLStyleElement;
use dom::htmltablecellelement::{HTMLTableCellElement, HTMLTableCellElementLayoutHelpers};
use dom::htmltableelement::{HTMLTableElement, HTMLTableElementLayoutHelpers};
use dom::htmltablerowelement::{HTMLTableRowElement, HTMLTableRowElementLayoutHelpers};
use dom::htmltablesectionelement::{HTMLTableSectionElement, HTMLTableSectionElementLayoutHelpers};
use dom::htmltemplateelement::HTMLTemplateElement;
use dom::htmltextareaelement::{HTMLTextAreaElement, LayoutHTMLTextAreaElementHelpers};
use dom::mutationobserver::{Mutation, MutationObserver};
use dom::namednodemap::NamedNodeMap;
use dom::node::{ChildrenMutation, LayoutNodeHelpers, Node};
use dom::node::{NodeDamage, NodeFlags, UnbindContext};
use dom::node::{document_from_node, window_from_node};
use dom::nodelist::NodeList;
use dom::promise::Promise;
use dom::servoparser::ServoParser;
use dom::text::Text;
use dom::validation::Validatable;
use dom::virtualmethods::{VirtualMethods, vtable_for};
use dom::window::ReflowReason;
use dom_struct::dom_struct;
use html5ever::{Prefix, LocalName, Namespace, QualName};
use html5ever::serialize;
use html5ever::serialize::SerializeOpts;
use html5ever::serialize::TraversalScope;
use html5ever::serialize::TraversalScope::{ChildrenOnly, IncludeNode};
use js::jsapi::Heap;
use js::jsval::JSVal;
use msg::constellation_msg::InputMethodType;
use net_traits::request::CorsSettings;
use ref_filter_map::ref_filter_map;
use script_layout_interface::message::ReflowGoal;
use script_thread::ScriptThread;
use selectors::Element as SelectorsElement;
use selectors::attr::{AttrSelectorOperation, NamespaceConstraint, CaseSensitivity};
use selectors::matching::{ElementSelectorFlags, MatchingContext};
use selectors::sink::Push;
use servo_arc::Arc;
use servo_atoms::Atom;
use std::borrow::Cow;
use std::cell::{Cell, Ref};
use std::default::Default;
use std::fmt;
use std::mem;
use std::rc::Rc;
use std::str::FromStr;
use style::CaseSensitivityExt;
use style::applicable_declarations::ApplicableDeclarationBlock;
use style::attr::{AttrValue, LengthOrPercentageOrAuto};
use style::context::QuirksMode;
use style::dom_apis;
use style::element_state::ElementState;
use style::invalidation::element::restyle_hints::RestyleHint;
use style::properties::{ComputedValues, Importance, PropertyDeclaration};
use style::properties::{PropertyDeclarationBlock, parse_style_attribute};
use style::properties::longhands::{self, background_image, border_spacing, font_family, font_size};
use style::properties::longhands::{overflow_x, overflow_y};
use style::rule_tree::CascadeLevel;
use style::selector_parser::{NonTSPseudoClass, PseudoElement, RestyleDamage, SelectorImpl, SelectorParser};
use style::selector_parser::extended_filtering;
use style::shared_lock::{SharedRwLock, Locked};
use style::thread_state;
use style::values::{CSSFloat, Either};
use style::values::{specified, computed};
use stylesheet_loader::StylesheetOwner;
use task::TaskOnce;
use xml5ever::serialize as xmlSerialize;
use xml5ever::serialize::SerializeOpts as XmlSerializeOpts;
use xml5ever::serialize::TraversalScope as XmlTraversalScope;
use xml5ever::serialize::TraversalScope::ChildrenOnly as XmlChildrenOnly;
use xml5ever::serialize::TraversalScope::IncludeNode as XmlIncludeNode;
// TODO: Update focus state when the top-level browsing context gains or loses system focus,
// and when the element enters or leaves a browsing context container.
// https://html.spec.whatwg.org/multipage/#selector-focus
#[dom_struct]
pub struct Element {
node: Node,
local_name: LocalName,
tag_name: TagName,
namespace: Namespace,
prefix: DomRefCell<Option<Prefix>>,
attrs: DomRefCell<Vec<Dom<Attr>>>,
id_attribute: DomRefCell<Option<Atom>>,
is: DomRefCell<Option<LocalName>>,
#[ignore_malloc_size_of = "Arc"]
style_attribute: DomRefCell<Option<Arc<Locked<PropertyDeclarationBlock>>>>,
attr_list: MutNullableDom<NamedNodeMap>,
class_list: MutNullableDom<DOMTokenList>,
state: Cell<ElementState>,
/// These flags are set by the style system to indicate the that certain
/// operations may require restyling this element or its descendants. The
/// flags are not atomic, so the style system takes care of only set them
/// when it has exclusive access to the element.
#[ignore_malloc_size_of = "bitflags defined in rust-selectors"]
selector_flags: Cell<ElementSelectorFlags>,
/// <https://html.spec.whatwg.org/multipage/#custom-element-reaction-queue>
custom_element_reaction_queue: DomRefCell<Vec<CustomElementReaction>>,
/// <https://dom.spec.whatwg.org/#concept-element-custom-element-definition>
#[ignore_malloc_size_of = "Rc"]
custom_element_definition: DomRefCell<Option<Rc<CustomElementDefinition>>>,
/// <https://dom.spec.whatwg.org/#concept-element-custom-element-state>
custom_element_state: Cell<CustomElementState>,
}
impl fmt::Debug for Element {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "<{}", self.local_name)?;
if let Some(ref id) = *self.id_attribute.borrow() {
write!(f, " id={}", id)?;
}
write!(f, ">")
}
}
impl fmt::Debug for DomRoot<Element> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
(**self).fmt(f)
}
}
#[derive(MallocSizeOf, PartialEq)]
pub enum ElementCreator {
ParserCreated(u64),
ScriptCreated,
}
pub enum CustomElementCreationMode {
Synchronous,
Asynchronous,
}
/// <https://dom.spec.whatwg.org/#concept-element-custom-element-state>
#[derive(Clone, Copy, Eq, JSTraceable, MallocSizeOf, PartialEq)]
pub enum CustomElementState {
Undefined,
Failed,
Uncustomized,
Custom,
}
impl ElementCreator {
pub fn is_parser_created(&self) -> bool {
match *self {
ElementCreator::ParserCreated(_) => true,
ElementCreator::ScriptCreated => false,
}
}
pub fn return_line_number(&self) -> u64 {
match *self {
ElementCreator::ParserCreated(l) => l,
ElementCreator::ScriptCreated => 1,
}
}
}
pub enum AdjacentPosition {
BeforeBegin,
AfterEnd,
AfterBegin,
BeforeEnd,
}
impl FromStr for AdjacentPosition {
type Err = Error;
fn from_str(position: &str) -> Result<Self, Self::Err> {
match_ignore_ascii_case! { &*position,
"beforebegin" => Ok(AdjacentPosition::BeforeBegin),
"afterbegin" => Ok(AdjacentPosition::AfterBegin),
"beforeend" => Ok(AdjacentPosition::BeforeEnd),
"afterend" => Ok(AdjacentPosition::AfterEnd),
_ => Err(Error::Syntax)
}
}
}
//
// Element methods
//
impl Element {
pub fn create(name: QualName,
is: Option<LocalName>,
document: &Document,
creator: ElementCreator,
mode: CustomElementCreationMode)
-> DomRoot<Element> {
create_element(name, is, document, creator, mode)
}
pub fn new_inherited(local_name: LocalName,
namespace: Namespace, prefix: Option<Prefix>,
document: &Document) -> Element {
Element::new_inherited_with_state(ElementState::empty(), local_name,
namespace, prefix, document)
}
pub fn new_inherited_with_state(state: ElementState, local_name: LocalName,
namespace: Namespace, prefix: Option<Prefix>,
document: &Document)
-> Element {
Element {
node: Node::new_inherited(document),
local_name: local_name,
tag_name: TagName::new(),
namespace: namespace,
prefix: DomRefCell::new(prefix),
attrs: DomRefCell::new(vec![]),
id_attribute: DomRefCell::new(None),
is: DomRefCell::new(None),
style_attribute: DomRefCell::new(None),
attr_list: Default::default(),
class_list: Default::default(),
state: Cell::new(state),
selector_flags: Cell::new(ElementSelectorFlags::empty()),
custom_element_reaction_queue: Default::default(),
custom_element_definition: Default::default(),
custom_element_state: Cell::new(CustomElementState::Uncustomized),
}
}
pub fn new(local_name: LocalName,
namespace: Namespace,
prefix: Option<Prefix>,
document: &Document) -> DomRoot<Element> {
Node::reflect_node(
Box::new(Element::new_inherited(local_name, namespace, prefix, document)),
document,
ElementBinding::Wrap)
}
pub fn restyle(&self, damage: NodeDamage) {
let doc = self.node.owner_doc();
let mut restyle = doc.ensure_pending_restyle(self);
// FIXME(bholley): I think we should probably only do this for
// NodeStyleDamaged, but I'm preserving existing behavior.
restyle.hint.insert(RestyleHint::RESTYLE_SELF);
if damage == NodeDamage::OtherNodeDamage {
restyle.damage = RestyleDamage::rebuild_and_reflow();
}
}
pub fn set_is(&self, is: LocalName) {
*self.is.borrow_mut() = Some(is);
}
pub fn get_is(&self) -> Option<LocalName> {
self.is.borrow().clone()
}
pub fn set_custom_element_state(&self, state: CustomElementState) {
self.custom_element_state.set(state);
}
pub fn get_custom_element_state(&self) -> CustomElementState {
self.custom_element_state.get()
}
pub fn set_custom_element_definition(&self, definition: Rc<CustomElementDefinition>) {
*self.custom_element_definition.borrow_mut() = Some(definition);
}
pub fn get_custom_element_definition(&self) -> Option<Rc<CustomElementDefinition>> {
(*self.custom_element_definition.borrow()).clone()
}
pub fn push_callback_reaction(&self, function: Rc<Function>, args: Box<[Heap<JSVal>]>) {
self.custom_element_reaction_queue.borrow_mut().push(CustomElementReaction::Callback(function, args));
}
pub fn push_upgrade_reaction(&self, definition: Rc<CustomElementDefinition>) {
self.custom_element_reaction_queue.borrow_mut().push(CustomElementReaction::Upgrade(definition));
}
pub fn clear_reaction_queue(&self) {
self.custom_element_reaction_queue.borrow_mut().clear();
}
pub fn invoke_reactions(&self) {
// TODO: This is not spec compliant, as this will allow some reactions to be processed
// after clear_reaction_queue has been called.
rooted_vec!(let mut reactions);
while !self.custom_element_reaction_queue.borrow().is_empty() {
mem::swap(&mut *reactions, &mut *self.custom_element_reaction_queue.borrow_mut());
for reaction in reactions.iter() {
reaction.invoke(self);
}
reactions.clear();
}
}
/// style will be `None` for elements in a `display: none` subtree. otherwise, the element has a
/// layout box iff it doesn't have `display: none`.
pub fn style(&self) -> Option<Arc<ComputedValues>> {
window_from_node(self).style_query(
self.upcast::<Node>().to_trusted_node_address()
)
}
// https://drafts.csswg.org/cssom-view/#css-layout-box
pub fn has_css_layout_box(&self) -> bool {
self.style()
.map_or(false, |s| !s.get_box().clone_display().is_none())
}
// https://drafts.csswg.org/cssom-view/#potentially-scrollable
fn potentially_scrollable(&self) -> bool {
self.has_css_layout_box() && !self.has_any_visible_overflow()
}
// https://drafts.csswg.org/cssom-view/#scrolling-box
fn has_scrolling_box(&self) -> bool {
// TODO: scrolling mechanism, such as scrollbar (We don't have scrollbar yet)
// self.has_scrolling_mechanism()
self.has_any_hidden_overflow()
}
fn has_overflow(&self) -> bool {
self.ScrollHeight() > self.ClientHeight() ||
self.ScrollWidth() > self.ClientWidth()
}
// TODO: Once #19183 is closed (overflow-x/y types moved out of mako), then we could implement
// a more generic `fn has_some_overflow(&self, overflow: Overflow)` rather than have
// these two `has_any_{visible,hidden}_overflow` methods which are very structurally
// similar.
/// Computed value of overflow-x or overflow-y is "visible"
fn has_any_visible_overflow(&self) -> bool {
self.style().map_or(false, |s| {
let box_ = s.get_box();
box_.clone_overflow_x() == overflow_x::computed_value::T::Visible ||
box_.clone_overflow_y() == overflow_y::computed_value::T::Visible
})
}
/// Computed value of overflow-x or overflow-y is "hidden"
fn has_any_hidden_overflow(&self) -> bool {
self.style().map_or(false, |s| {
let box_ = s.get_box();
box_.clone_overflow_x() == overflow_x::computed_value::T::Hidden ||
box_.clone_overflow_y() == overflow_y::computed_value::T::Hidden
})
}
}
#[allow(unsafe_code)]
pub trait RawLayoutElementHelpers {
unsafe fn get_attr_for_layout<'a>(&'a self, namespace: &Namespace, name: &LocalName)
-> Option<&'a AttrValue>;
unsafe fn get_attr_val_for_layout<'a>(&'a self, namespace: &Namespace, name: &LocalName)
-> Option<&'a str>;
unsafe fn get_attr_vals_for_layout<'a>(&'a self, name: &LocalName) -> Vec<&'a AttrValue>;
}
#[inline]
#[allow(unsafe_code)]
pub unsafe fn get_attr_for_layout<'a>(elem: &'a Element, namespace: &Namespace, name: &LocalName)
-> Option<LayoutDom<Attr>> {
// cast to point to T in RefCell<T> directly
let attrs = elem.attrs.borrow_for_layout();
attrs.iter().find(|attr| {
let attr = attr.to_layout();
*name == attr.local_name_atom_forever() &&
(*attr.unsafe_get()).namespace() == namespace
}).map(|attr| attr.to_layout())
}
#[allow(unsafe_code)]
impl RawLayoutElementHelpers for Element {
#[inline]
unsafe fn get_attr_for_layout<'a>(&'a self, namespace: &Namespace, name: &LocalName)
-> Option<&'a AttrValue> {
get_attr_for_layout(self, namespace, name).map(|attr| {
attr.value_forever()
})
}
#[inline]
unsafe fn get_attr_val_for_layout<'a>(&'a self, namespace: &Namespace, name: &LocalName)
-> Option<&'a str> {
get_attr_for_layout(self, namespace, name).map(|attr| {
attr.value_ref_forever()
})
}
#[inline]
unsafe fn get_attr_vals_for_layout<'a>(&'a self, name: &LocalName) -> Vec<&'a AttrValue> {
let attrs = self.attrs.borrow_for_layout();
attrs.iter().filter_map(|attr| {
let attr = attr.to_layout();
if *name == attr.local_name_atom_forever() {
Some(attr.value_forever())
} else {
None
}
}).collect()
}
}
pub trait LayoutElementHelpers {
#[allow(unsafe_code)]
unsafe fn has_class_for_layout(&self, name: &Atom, case_sensitivity: CaseSensitivity) -> bool;
#[allow(unsafe_code)]
unsafe fn get_classes_for_layout(&self) -> Option<&'static [Atom]>;
#[allow(unsafe_code)]
unsafe fn synthesize_presentational_hints_for_legacy_attributes<V>(&self, &mut V)
where V: Push<ApplicableDeclarationBlock>;
#[allow(unsafe_code)]
unsafe fn get_colspan(self) -> u32;
#[allow(unsafe_code)]
unsafe fn get_rowspan(self) -> u32;
#[allow(unsafe_code)]
unsafe fn is_html_element(&self) -> bool;
fn id_attribute(&self) -> *const Option<Atom>;
fn style_attribute(&self) -> *const Option<Arc<Locked<PropertyDeclarationBlock>>>;
fn local_name(&self) -> &LocalName;
fn namespace(&self) -> &Namespace;
fn get_lang_for_layout(&self) -> String;
fn get_checked_state_for_layout(&self) -> bool;
fn get_indeterminate_state_for_layout(&self) -> bool;
fn get_state_for_layout(&self) -> ElementState;
fn insert_selector_flags(&self, flags: ElementSelectorFlags);
fn has_selector_flags(&self, flags: ElementSelectorFlags) -> bool;
}
impl LayoutElementHelpers for LayoutDom<Element> {
#[allow(unsafe_code)]
#[inline]
unsafe fn has_class_for_layout(&self, name: &Atom, case_sensitivity: CaseSensitivity) -> bool {
get_attr_for_layout(&*self.unsafe_get(), &ns!(), &local_name!("class")).map_or(false, |attr| {
attr.value_tokens_forever().unwrap().iter().any(|atom| case_sensitivity.eq_atom(atom, name))
})
}
#[allow(unsafe_code)]
#[inline]
unsafe fn get_classes_for_layout(&self) -> Option<&'static [Atom]> {
get_attr_for_layout(&*self.unsafe_get(), &ns!(), &local_name!("class"))
.map(|attr| attr.value_tokens_forever().unwrap())
}
#[allow(unsafe_code)]
unsafe fn synthesize_presentational_hints_for_legacy_attributes<V>(&self, hints: &mut V)
where V: Push<ApplicableDeclarationBlock>
{
// FIXME(emilio): Just a single PDB should be enough.
#[inline]
fn from_declaration(shared_lock: &SharedRwLock, declaration: PropertyDeclaration)
-> ApplicableDeclarationBlock {
ApplicableDeclarationBlock::from_declarations(
Arc::new(shared_lock.wrap(PropertyDeclarationBlock::with_one(
declaration, Importance::Normal
))),
CascadeLevel::PresHints)
}
let document = self.upcast::<Node>().owner_doc_for_layout();
let shared_lock = document.style_shared_lock();
let bgcolor = if let Some(this) = self.downcast::<HTMLBodyElement>() {
this.get_background_color()
} else if let Some(this) = self.downcast::<HTMLTableElement>() {
this.get_background_color()
} else if let Some(this) = self.downcast::<HTMLTableCellElement>() {
this.get_background_color()
} else if let Some(this) = self.downcast::<HTMLTableRowElement>() {
this.get_background_color()
} else if let Some(this) = self.downcast::<HTMLTableSectionElement>() {
this.get_background_color()
} else {
None
};
if let Some(color) = bgcolor {
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::BackgroundColor(color.into())
));
}
let background = if let Some(this) = self.downcast::<HTMLBodyElement>() {
this.get_background()
} else {
None
};
if let Some(url) = background {
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::BackgroundImage(
background_image::SpecifiedValue(vec![
Either::Second(specified::Image::for_cascade(url.into()))
]))));
}
let color = if let Some(this) = self.downcast::<HTMLFontElement>() {
this.get_color()
} else if let Some(this) = self.downcast::<HTMLBodyElement>() {
// https://html.spec.whatwg.org/multipage/#the-page:the-body-element-20
this.get_color()
} else if let Some(this) = self.downcast::<HTMLHRElement>() {
// https://html.spec.whatwg.org/multipage/#the-hr-element-2:presentational-hints-5
this.get_color()
} else {
None
};
if let Some(color) = color {
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::Color(
longhands::color::SpecifiedValue(color.into())
)
));
}
let font_family = if let Some(this) = self.downcast::<HTMLFontElement>() {
this.get_face()
} else {
None
};
if let Some(font_family) = font_family {
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::FontFamily(
font_family::SpecifiedValue::Values(
computed::font::FontFamilyList::new(Box::new([
computed::font::SingleFontFamily::from_atom(
font_family)]))))));
}
let font_size = self.downcast::<HTMLFontElement>().and_then(|this| this.get_size());
if let Some(font_size) = font_size {
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::FontSize(
font_size::SpecifiedValue::from_html_size(font_size as u8)
)
))
}
let cellspacing = if let Some(this) = self.downcast::<HTMLTableElement>() {
this.get_cellspacing()
} else {
None
};
if let Some(cellspacing) = cellspacing {
let width_value = specified::Length::from_px(cellspacing as f32);
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::BorderSpacing(
Box::new(border_spacing::SpecifiedValue::new(
width_value.clone().into(),
width_value.into()
))
)
));
}
let size = if let Some(this) = self.downcast::<HTMLInputElement>() {
// FIXME(pcwalton): More use of atoms, please!
match (*self.unsafe_get()).get_attr_val_for_layout(&ns!(), &local_name!("type")) {
// Not text entry widget
Some("hidden") | Some("date") | Some("month") | Some("week") |
Some("time") | Some("datetime-local") | Some("number") | Some("range") |
Some("color") | Some("checkbox") | Some("radio") | Some("file") |
Some("submit") | Some("image") | Some("reset") | Some("button") => {
None
},
// Others
_ => {
match this.size_for_layout() {
0 => None,
s => Some(s as i32),
}
},
}
} else {
None
};
if let Some(size) = size {
let value = specified::NoCalcLength::ServoCharacterWidth(specified::CharacterWidth(size));
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::Width(
specified::LengthOrPercentageOrAuto::Length(value))));
}
let width = if let Some(this) = self.downcast::<HTMLIFrameElement>() {
this.get_width()
} else if let Some(this) = self.downcast::<HTMLImageElement>() {
this.get_width()
} else if let Some(this) = self.downcast::<HTMLTableElement>() {
this.get_width()
} else if let Some(this) = self.downcast::<HTMLTableCellElement>() {
this.get_width()
} else if let Some(this) = self.downcast::<HTMLHRElement>() {
// https://html.spec.whatwg.org/multipage/#the-hr-element-2:attr-hr-width
this.get_width()
} else if let Some(this) = self.downcast::<HTMLCanvasElement>() {
this.get_width()
} else {
LengthOrPercentageOrAuto::Auto
};
// FIXME(emilio): Use from_computed value here and below.
match width {
LengthOrPercentageOrAuto::Auto => {}
LengthOrPercentageOrAuto::Percentage(percentage) => {
let width_value =
specified::LengthOrPercentageOrAuto::Percentage(computed::Percentage(percentage));
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::Width(width_value)));
}
LengthOrPercentageOrAuto::Length(length) => {
let width_value = specified::LengthOrPercentageOrAuto::Length(
specified::NoCalcLength::Absolute(specified::AbsoluteLength::Px(length.to_f32_px())));
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::Width(width_value)));
}
}
let height = if let Some(this) = self.downcast::<HTMLIFrameElement>() {
this.get_height()
} else if let Some(this) = self.downcast::<HTMLImageElement>() {
this.get_height()
} else if let Some(this) = self.downcast::<HTMLCanvasElement>() {
this.get_height()
} else {
LengthOrPercentageOrAuto::Auto
};
match height {
LengthOrPercentageOrAuto::Auto => {}
LengthOrPercentageOrAuto::Percentage(percentage) => {
let height_value =
specified::LengthOrPercentageOrAuto::Percentage(computed::Percentage(percentage));
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::Height(height_value)));
}
LengthOrPercentageOrAuto::Length(length) => {
let height_value = specified::LengthOrPercentageOrAuto::Length(
specified::NoCalcLength::Absolute(specified::AbsoluteLength::Px(length.to_f32_px())));
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::Height(height_value)));
}
}
let cols = if let Some(this) = self.downcast::<HTMLTextAreaElement>() {
match this.get_cols() {
0 => None,
c => Some(c as i32),
}
} else {
None
};
if let Some(cols) = cols {
// TODO(mttr) ServoCharacterWidth uses the size math for <input type="text">, but
// the math for <textarea> is a little different since we need to take
// scrollbar size into consideration (but we don't have a scrollbar yet!)
//
// https://html.spec.whatwg.org/multipage/#textarea-effective-width
let value = specified::NoCalcLength::ServoCharacterWidth(specified::CharacterWidth(cols));
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::Width(specified::LengthOrPercentageOrAuto::Length(value))));
}
let rows = if let Some(this) = self.downcast::<HTMLTextAreaElement>() {
match this.get_rows() {
0 => None,
r => Some(r as i32),
}
} else {
None
};
if let Some(rows) = rows {
// TODO(mttr) This should take scrollbar size into consideration.
//
// https://html.spec.whatwg.org/multipage/#textarea-effective-height
let value = specified::NoCalcLength::FontRelative(specified::FontRelativeLength::Em(rows as CSSFloat));
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::Height(specified::LengthOrPercentageOrAuto::Length(value))));
}
let border = if let Some(this) = self.downcast::<HTMLTableElement>() {
this.get_border()
} else {
None
};
if let Some(border) = border {
let width_value = specified::BorderSideWidth::Length(specified::Length::from_px(border as f32));
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::BorderTopWidth(width_value.clone())));
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::BorderLeftWidth(width_value.clone())));
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::BorderBottomWidth(width_value.clone())));
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::BorderRightWidth(width_value)));
}
}
#[allow(unsafe_code)]
unsafe fn get_colspan(self) -> u32 {
if let Some(this) = self.downcast::<HTMLTableCellElement>() {
this.get_colspan().unwrap_or(1)
} else {
// Don't panic since `display` can cause this to be called on arbitrary
// elements.
1
}
}
#[allow(unsafe_code)]
unsafe fn get_rowspan(self) -> u32 {
if let Some(this) = self.downcast::<HTMLTableCellElement>() {
this.get_rowspan().unwrap_or(1)
} else {
// Don't panic since `display` can cause this to be called on arbitrary
// elements.
1
}
}
#[inline]
#[allow(unsafe_code)]
unsafe fn is_html_element(&self) -> bool {
(*self.unsafe_get()).namespace == ns!(html)
}
#[allow(unsafe_code)]
fn id_attribute(&self) -> *const Option<Atom> {
unsafe {
(*self.unsafe_get()).id_attribute.borrow_for_layout()
}
}
#[allow(unsafe_code)]
fn style_attribute(&self) -> *const Option<Arc<Locked<PropertyDeclarationBlock>>> {
unsafe {
(*self.unsafe_get()).style_attribute.borrow_for_layout()
}
}
#[allow(unsafe_code)]
fn local_name(&self) -> &LocalName {
unsafe {
&(*self.unsafe_get()).local_name
}
}
#[allow(unsafe_code)]
fn namespace(&self) -> &Namespace {
unsafe {
&(*self.unsafe_get()).namespace
}
}
#[allow(unsafe_code)]
fn get_lang_for_layout(&self) -> String {
unsafe {
let mut current_node = Some(self.upcast::<Node>());
while let Some(node) = current_node {
current_node = node.parent_node_ref();
match node.downcast::<Element>().map(|el| el.unsafe_get()) {
Some(elem) => {
if let Some(attr) = (*elem).get_attr_val_for_layout(&ns!(xml), &local_name!("lang")) {
return attr.to_owned();
}
if let Some(attr) = (*elem).get_attr_val_for_layout(&ns!(), &local_name!("lang")) {
return attr.to_owned();
}
}
None => continue
}
}
// TODO: Check meta tags for a pragma-set default language
// TODO: Check HTTP Content-Language header
String::new()
}
}
#[inline]
#[allow(unsafe_code)]
fn get_checked_state_for_layout(&self) -> bool {
// TODO option and menuitem can also have a checked state.
match self.downcast::<HTMLInputElement>() {
Some(input) => unsafe {
input.checked_state_for_layout()
},
None => false,
}
}
#[inline]
#[allow(unsafe_code)]
fn get_indeterminate_state_for_layout(&self) -> bool {
// TODO progress elements can also be matched with :indeterminate
match self.downcast::<HTMLInputElement>() {
Some(input) => unsafe {
input.indeterminate_state_for_layout()
},
None => false,
}
}
#[inline]
#[allow(unsafe_code)]
fn get_state_for_layout(&self) -> ElementState {
unsafe {
(*self.unsafe_get()).state.get()
}
}
#[inline]
#[allow(unsafe_code)]
fn insert_selector_flags(&self, flags: ElementSelectorFlags) {
debug_assert!(thread_state::get().is_layout());
unsafe {
let f = &(*self.unsafe_get()).selector_flags;
f.set(f.get() | flags);
}
}
#[inline]
#[allow(unsafe_code)]
fn has_selector_flags(&self, flags: ElementSelectorFlags) -> bool {
unsafe {
(*self.unsafe_get()).selector_flags.get().contains(flags)
}
}
}
impl Element {
pub fn is_html_element(&self) -> bool {
self.namespace == ns!(html)
}
pub fn html_element_in_html_document(&self) -> bool {
self.is_html_element() && self.upcast::<Node>().is_in_html_doc()
}
pub fn local_name(&self) -> &LocalName {
&self.local_name
}
pub fn parsed_name(&self, mut name: DOMString) -> LocalName {
if self.html_element_in_html_document() {
name.make_ascii_lowercase();
}
LocalName::from(name)
}
pub fn namespace(&self) -> &Namespace {
&self.namespace
}
pub fn prefix(&self) -> Ref<Option<Prefix>> {
self.prefix.borrow()
}
pub fn set_prefix(&self, prefix: Option<Prefix>) {
*self.prefix.borrow_mut() = prefix;
}
pub fn attrs(&self) -> Ref<[Dom<Attr>]> {
Ref::map(self.attrs.borrow(), |attrs| &**attrs)
}
// Element branch of https://dom.spec.whatwg.org/#locate-a-namespace
pub fn locate_namespace(&self, prefix: Option<DOMString>) -> Namespace {
let prefix = prefix.map(String::from).map(LocalName::from);
let inclusive_ancestor_elements =
self.upcast::<Node>()
.inclusive_ancestors()
.filter_map(DomRoot::downcast::<Self>);
// Steps 3-4.
for element in inclusive_ancestor_elements {
// Step 1.
if element.namespace() != &ns!() &&
element.prefix().as_ref().map(|p| &**p) == prefix.as_ref().map(|p| &**p)
{
return element.namespace().clone();
}
// Step 2.
let attr = ref_filter_map(self.attrs(), |attrs| {
attrs.iter().find(|attr| {
if attr.namespace() != &ns!(xmlns) {
return false;
}
match (attr.prefix(), prefix.as_ref()) {
(Some(&namespace_prefix!("xmlns")), Some(prefix)) => {
attr.local_name() == prefix
},
(None, None) => attr.local_name() == &local_name!("xmlns"),
_ => false,
}
})
});
if let Some(attr) = attr {
return (**attr.value()).into();
}
}
ns!()
}
pub fn style_attribute(&self) -> &DomRefCell<Option<Arc<Locked<PropertyDeclarationBlock>>>> {
&self.style_attribute
}
pub fn summarize(&self) -> Vec<AttrInfo> {
self.attrs.borrow().iter()
.map(|attr| attr.summarize())
.collect()
}
pub fn is_void(&self) -> bool {
if self.namespace != ns!(html) {
return false
}
match self.local_name {
/* List of void elements from
https://html.spec.whatwg.org/multipage/#html-fragment-serialisation-algorithm */
local_name!("area") | local_name!("base") | local_name!("basefont") |
local_name!("bgsound") | local_name!("br") |
local_name!("col") | local_name!("embed") | local_name!("frame") |
local_name!("hr") | local_name!("img") |
local_name!("input") | local_name!("keygen") | local_name!("link") |
local_name!("menuitem") | local_name!("meta") |
local_name!("param") | local_name!("source") | local_name!("track") |
local_name!("wbr") => true,
_ => false
}
}
pub fn serialize(&self, traversal_scope: TraversalScope) -> Fallible<DOMString> {
let mut writer = vec![];
match serialize(&mut writer,
&self.upcast::<Node>(),
SerializeOpts {
traversal_scope: traversal_scope,
..Default::default()
}) {
// FIXME(ajeffrey): Directly convert UTF8 to DOMString
Ok(()) => Ok(DOMString::from(String::from_utf8(writer).unwrap())),
Err(_) => panic!("Cannot serialize element"),
}
}
pub fn xmlSerialize(&self, traversal_scope: XmlTraversalScope) -> Fallible<DOMString> {
let mut writer = vec![];
match xmlSerialize::serialize(&mut writer,
&self.upcast::<Node>(),
XmlSerializeOpts {
traversal_scope: traversal_scope,
..Default::default()
}) {
Ok(()) => Ok(DOMString::from(String::from_utf8(writer).unwrap())),
Err(_) => panic!("Cannot serialize element"),
}
}
pub fn root_element(&self) -> DomRoot<Element> {
if self.node.is_in_doc() {
self.upcast::<Node>()
.owner_doc()
.GetDocumentElement()
.unwrap()
} else {
self.upcast::<Node>()
.inclusive_ancestors()
.filter_map(DomRoot::downcast)
.last()
.expect("We know inclusive_ancestors will return `self` which is an element")
}
}
// https://dom.spec.whatwg.org/#locate-a-namespace-prefix
pub fn lookup_prefix(&self, namespace: Namespace) -> Option<DOMString> {
for node in self.upcast::<Node>().inclusive_ancestors() {
let element = node.downcast::<Element>()?;
// Step 1.
if *element.namespace() == namespace {
if let Some(prefix) = element.GetPrefix() {
return Some(prefix);
}
}
// Step 2.
for attr in element.attrs.borrow().iter() {
if attr.prefix() == Some(&namespace_prefix!("xmlns")) &&
**attr.value() == *namespace {
return Some(attr.LocalName());
}
}
}
None
}
// Returns the kind of IME control needed for a focusable element, if any.
pub fn input_method_type(&self) -> Option<InputMethodType> {
if !self.is_focusable_area() {
return None;
}
if let Some(input) = self.downcast::<HTMLInputElement>() {
input.input_type().as_ime_type()
} else if self.is::<HTMLTextAreaElement>() {
Some(InputMethodType::Text)
} else {
// Other focusable elements that are not input fields.
None
}
}
pub fn is_focusable_area(&self) -> bool {
if self.is_actually_disabled() {
return false;
}
// TODO: Check whether the element is being rendered (i.e. not hidden).
let node = self.upcast::<Node>();
if node.get_flag(NodeFlags::SEQUENTIALLY_FOCUSABLE) {
return true;
}
// https://html.spec.whatwg.org/multipage/#specially-focusable
match node.type_id() {
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAnchorElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSelectElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTextAreaElement)) => {
true
}
_ => false,
}
}
pub fn is_actually_disabled(&self) -> bool {
let node = self.upcast::<Node>();
match node.type_id() {
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLButtonElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSelectElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTextAreaElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLOptionElement)) => {
self.disabled_state()
}
// TODO:
// an optgroup element that has a disabled attribute
// a menuitem element that has a disabled attribute
// a fieldset element that is a disabled fieldset
_ => false,
}
}
pub fn push_new_attribute(&self,
local_name: LocalName,
value: AttrValue,
name: LocalName,
namespace: Namespace,
prefix: Option<Prefix>) {
let window = window_from_node(self);
let attr = Attr::new(&window,
local_name,
value,
name,
namespace,
prefix,
Some(self));
self.push_attribute(&attr);
}
pub fn push_attribute(&self, attr: &Attr) {
let name = attr.local_name().clone();
let namespace = attr.namespace().clone();
let mutation = Mutation::Attribute {
name: name.clone(),
namespace: namespace.clone(),
old_value: None,
};
MutationObserver::queue_a_mutation_record(&self.node, mutation);
if self.get_custom_element_definition().is_some() {
let value = DOMString::from(&**attr.value());
let reaction = CallbackReaction::AttributeChanged(name, None, Some(value), namespace);
ScriptThread::enqueue_callback_reaction(self, reaction, None);
}
assert!(attr.GetOwnerElement().r() == Some(self));
self.will_mutate_attr(attr);
self.attrs.borrow_mut().push(Dom::from_ref(attr));
if attr.namespace() == &ns!() {
vtable_for(self.upcast()).attribute_mutated(attr, AttributeMutation::Set(None));
}
}
pub fn get_attribute(&self, namespace: &Namespace, local_name: &LocalName) -> Option<DomRoot<Attr>> {
self.attrs
.borrow()
.iter()
.find(|attr| attr.local_name() == local_name && attr.namespace() == namespace)
.map(|js| DomRoot::from_ref(&**js))
}
// https://dom.spec.whatwg.org/#concept-element-attributes-get-by-name
pub fn get_attribute_by_name(&self, name: DOMString) -> Option<DomRoot<Attr>> {
let name = &self.parsed_name(name);
self.attrs.borrow().iter().find(|a| a.name() == name).map(|js| DomRoot::from_ref(&**js))
}
pub fn set_attribute_from_parser(&self,
qname: QualName,
value: DOMString,
prefix: Option<Prefix>) {
// Don't set if the attribute already exists, so we can handle add_attrs_if_missing
if self.attrs
.borrow()
.iter()
.any(|a| *a.local_name() == qname.local && *a.namespace() == qname.ns) {
return;
}
let name = match prefix {
None => qname.local.clone(),
Some(ref prefix) => {
let name = format!("{}:{}", &**prefix, &*qname.local);
LocalName::from(name)
},
};
let value = self.parse_attribute(&qname.ns, &qname.local, value);
self.push_new_attribute(qname.local, value, name, qname.ns, prefix);
}
pub fn set_attribute(&self, name: &LocalName, value: AttrValue) {
assert!(name == &name.to_ascii_lowercase());
assert!(!name.contains(":"));
self.set_first_matching_attribute(name.clone(),
value,
name.clone(),
ns!(),
None,
|attr| attr.local_name() == name);
}
// https://html.spec.whatwg.org/multipage/#attr-data-*
pub fn set_custom_attribute(&self, name: DOMString, value: DOMString) -> ErrorResult {
// Step 1.
if let InvalidXMLName = xml_name_type(&name) {
return Err(Error::InvalidCharacter);
}
// Steps 2-5.
let name = LocalName::from(name);
let value = self.parse_attribute(&ns!(), &name, value);
self.set_first_matching_attribute(name.clone(),
value,
name.clone(),
ns!(),
None,
|attr| {
*attr.name() == name && *attr.namespace() == ns!()
});
Ok(())
}
fn set_first_matching_attribute<F>(&self,
local_name: LocalName,
value: AttrValue,
name: LocalName,
namespace: Namespace,
prefix: Option<Prefix>,
find: F)
where F: Fn(&Attr) -> bool
{
let attr = self.attrs
.borrow()
.iter()
.find(|attr| find(&attr))
.map(|js| DomRoot::from_ref(&**js));
if let Some(attr) = attr {
attr.set_value(value, self);
} else {
self.push_new_attribute(local_name, value, name, namespace, prefix);
};
}
pub fn parse_attribute(&self,
namespace: &Namespace,
local_name: &LocalName,
value: DOMString)
-> AttrValue {
if *namespace == ns!() {
vtable_for(self.upcast()).parse_plain_attribute(local_name, value)
} else {
AttrValue::String(value.into())
}
}
pub fn remove_attribute(&self, namespace: &Namespace, local_name: &LocalName) -> Option<DomRoot<Attr>> {
self.remove_first_matching_attribute(|attr| {
attr.namespace() == namespace && attr.local_name() == local_name
})
}
pub fn remove_attribute_by_name(&self, name: &LocalName) -> Option<DomRoot<Attr>> {
self.remove_first_matching_attribute(|attr| attr.name() == name)
}
fn remove_first_matching_attribute<F>(&self, find: F) -> Option<DomRoot<Attr>>
where F: Fn(&Attr) -> bool {
let idx = self.attrs.borrow().iter().position(|attr| find(&attr));
idx.map(|idx| {
let attr = DomRoot::from_ref(&*(*self.attrs.borrow())[idx]);
self.will_mutate_attr(&attr);
let name = attr.local_name().clone();
let namespace = attr.namespace().clone();
let old_value = DOMString::from(&**attr.value());
let mutation = Mutation::Attribute {
name: name.clone(),
namespace: namespace.clone(),
old_value: Some(old_value.clone()),
};
MutationObserver::queue_a_mutation_record(&self.node, mutation);
let reaction = CallbackReaction::AttributeChanged(name, Some(old_value), None, namespace);
ScriptThread::enqueue_callback_reaction(self, reaction, None);
self.attrs.borrow_mut().remove(idx);
attr.set_owner(None);
if attr.namespace() == &ns!() {
vtable_for(self.upcast()).attribute_mutated(&attr, AttributeMutation::Removed);
}
attr
})
}
pub fn has_class(&self, name: &Atom, case_sensitivity: CaseSensitivity) -> bool {
self.get_attribute(&ns!(), &local_name!("class")).map_or(false, |attr| {
attr.value().as_tokens().iter().any(|atom| case_sensitivity.eq_atom(name, atom))
})
}
pub fn set_atomic_attribute(&self, local_name: &LocalName, value: DOMString) {
assert!(*local_name == local_name.to_ascii_lowercase());
let value = AttrValue::from_atomic(value.into());
self.set_attribute(local_name, value);
}
pub fn has_attribute(&self, local_name: &LocalName) -> bool {
assert!(local_name.bytes().all(|b| b.to_ascii_lowercase() == b));
self.attrs
.borrow()
.iter()
.any(|attr| attr.local_name() == local_name && attr.namespace() == &ns!())
}
pub fn set_bool_attribute(&self, local_name: &LocalName, value: bool) {
if self.has_attribute(local_name) == value {
return;
}
if value {
self.set_string_attribute(local_name, DOMString::new());
} else {
self.remove_attribute(&ns!(), local_name);
}
}
pub fn get_url_attribute(&self, local_name: &LocalName) -> DOMString {
assert!(*local_name == local_name.to_ascii_lowercase());
let attr = match self.get_attribute(&ns!(), local_name) {
Some(attr) => attr,
None => return DOMString::new(),
};
let value = &**attr.value();
// XXXManishearth this doesn't handle `javascript:` urls properly
let base = document_from_node(self).base_url();
let value = base.join(value)
.map(|parsed| parsed.into_string())
.unwrap_or_else(|_| value.to_owned());
DOMString::from(value)
}
pub fn get_string_attribute(&self, local_name: &LocalName) -> DOMString {
match self.get_attribute(&ns!(), local_name) {
Some(x) => x.Value(),
None => DOMString::new(),
}
}
pub fn set_string_attribute(&self, local_name: &LocalName, value: DOMString) {
assert!(*local_name == local_name.to_ascii_lowercase());
self.set_attribute(local_name, AttrValue::String(value.into()));
}
pub fn get_tokenlist_attribute(&self, local_name: &LocalName) -> Vec<Atom> {
self.get_attribute(&ns!(), local_name).map(|attr| {
attr.value()
.as_tokens()
.to_vec()
}).unwrap_or(vec!())
}
pub fn set_tokenlist_attribute(&self, local_name: &LocalName, value: DOMString) {
assert!(*local_name == local_name.to_ascii_lowercase());
self.set_attribute(local_name,
AttrValue::from_serialized_tokenlist(value.into()));
}
pub fn set_atomic_tokenlist_attribute(&self, local_name: &LocalName, tokens: Vec<Atom>) {
assert!(*local_name == local_name.to_ascii_lowercase());
self.set_attribute(local_name, AttrValue::from_atomic_tokens(tokens));
}
pub fn get_int_attribute(&self, local_name: &LocalName, default: i32) -> i32 {
// TODO: Is this assert necessary?
assert!(local_name.chars().all(|ch| {
!ch.is_ascii() || ch.to_ascii_lowercase() == ch
}));
let attribute = self.get_attribute(&ns!(), local_name);
match attribute {
Some(ref attribute) => {
match *attribute.value() {
AttrValue::Int(_, value) => value,
_ => panic!("Expected an AttrValue::Int: \
implement parse_plain_attribute"),
}
}
None => default,
}
}
pub fn set_int_attribute(&self, local_name: &LocalName, value: i32) {
assert!(*local_name == local_name.to_ascii_lowercase());
self.set_attribute(local_name, AttrValue::Int(value.to_string(), value));
}
pub fn get_uint_attribute(&self, local_name: &LocalName, default: u32) -> u32 {
assert!(local_name.chars().all(|ch| !ch.is_ascii() || ch.to_ascii_lowercase() == ch));
let attribute = self.get_attribute(&ns!(), local_name);
match attribute {
Some(ref attribute) => {
match *attribute.value() {
AttrValue::UInt(_, value) => value,
_ => panic!("Expected an AttrValue::UInt: implement parse_plain_attribute"),
}
}
None => default,
}
}
pub fn set_uint_attribute(&self, local_name: &LocalName, value: u32) {
assert!(*local_name == local_name.to_ascii_lowercase());
self.set_attribute(local_name, AttrValue::UInt(value.to_string(), value));
}
pub fn will_mutate_attr(&self, attr: &Attr) {
let node = self.upcast::<Node>();
node.owner_doc().element_attr_will_change(self, attr);
}
// https://dom.spec.whatwg.org/#insert-adjacent
pub fn insert_adjacent(&self, where_: AdjacentPosition, node: &Node)
-> Fallible<Option<DomRoot<Node>>> {
let self_node = self.upcast::<Node>();
match where_ {
AdjacentPosition::BeforeBegin => {
if let Some(parent) = self_node.GetParentNode() {
Node::pre_insert(node, &parent, Some(self_node)).map(Some)
} else {
Ok(None)
}
}
AdjacentPosition::AfterBegin => {
Node::pre_insert(node, &self_node, self_node.GetFirstChild().r()).map(Some)
}
AdjacentPosition::BeforeEnd => {
Node::pre_insert(node, &self_node, None).map(Some)
}
AdjacentPosition::AfterEnd => {
if let Some(parent) = self_node.GetParentNode() {
Node::pre_insert(node, &parent, self_node.GetNextSibling().r()).map(Some)
} else {
Ok(None)
}
}
}
}
// https://drafts.csswg.org/cssom-view/#dom-element-scroll
pub fn scroll(&self, x_: f64, y_: f64, behavior: ScrollBehavior) {
// Step 1.2 or 2.3
let x = if x_.is_finite() { x_ } else { 0.0f64 };
let y = if y_.is_finite() { y_ } else { 0.0f64 };
let node = self.upcast::<Node>();
// Step 3
let doc = node.owner_doc();
// Step 4
if !doc.is_fully_active() {
return;
}
// Step 5
let win = match doc.GetDefaultView() {
None => return,
Some(win) => win,
};
// Step 7
if *self.root_element() == *self {
if doc.quirks_mode() != QuirksMode::Quirks {
win.scroll(x, y, behavior);
}
return;
}
// Step 9
if doc.GetBody().r() == self.downcast::<HTMLElement>() &&
doc.quirks_mode() == QuirksMode::Quirks &&
!self.potentially_scrollable() {
win.scroll(x, y, behavior);
return;
}
// Step 10
if !self.has_css_layout_box() ||
!self.has_scrolling_box() ||
!self.has_overflow()
{
return;
}
// Step 11
win.scroll_node(node, x, y, behavior);
}
// https://w3c.github.io/DOM-Parsing/#parsing
pub fn parse_fragment(&self, markup: DOMString) -> Fallible<DomRoot<DocumentFragment>> {
// Steps 1-2.
let context_document = document_from_node(self);
// TODO(#11995): XML case.
let new_children = ServoParser::parse_html_fragment(self, markup);
// Step 3.
let fragment = DocumentFragment::new(&context_document);
// Step 4.
for child in new_children {
fragment.upcast::<Node>().AppendChild(&child).unwrap();
}
// Step 5.
Ok(fragment)
}
pub fn fragment_parsing_context(owner_doc: &Document, element: Option<&Self>) -> DomRoot<Self> {
match element {
Some(elem) if elem.local_name() != &local_name!("html") || !elem.html_element_in_html_document() => {
DomRoot::from_ref(elem)
},
_ => {
DomRoot::upcast(HTMLBodyElement::new(local_name!("body"), None, owner_doc))
}
}
}
// https://fullscreen.spec.whatwg.org/#fullscreen-element-ready-check
pub fn fullscreen_element_ready_check(&self) -> bool {
if !self.is_connected() {
return false
}
let document = document_from_node(self);
document.get_allow_fullscreen()
}
// https://html.spec.whatwg.org/multipage/#home-subtree
pub fn is_in_same_home_subtree<T>(&self, other: &T) -> bool
where T: DerivedFrom<Element> + DomObject
{
let other = other.upcast::<Element>();
self.root_element() == other.root_element()
}
}
impl ElementMethods for Element {
// https://dom.spec.whatwg.org/#dom-element-namespaceuri
fn GetNamespaceURI(&self) -> Option<DOMString> {
Node::namespace_to_string(self.namespace.clone())
}
// https://dom.spec.whatwg.org/#dom-element-localname
fn LocalName(&self) -> DOMString {
// FIXME(ajeffrey): Convert directly from LocalName to DOMString
DOMString::from(&*self.local_name)
}
// https://dom.spec.whatwg.org/#dom-element-prefix
fn GetPrefix(&self) -> Option<DOMString> {
self.prefix.borrow().as_ref().map(|p| DOMString::from(&**p))
}
// https://dom.spec.whatwg.org/#dom-element-tagname
fn TagName(&self) -> DOMString {
let name = self.tag_name.or_init(|| {
let qualified_name = match *self.prefix.borrow() {
Some(ref prefix) => {
Cow::Owned(format!("{}:{}", &**prefix, &*self.local_name))
},
None => Cow::Borrowed(&*self.local_name)
};
if self.html_element_in_html_document() {
LocalName::from(qualified_name.to_ascii_uppercase())
} else {
LocalName::from(qualified_name)
}
});
DOMString::from(&*name)
}
// https://dom.spec.whatwg.org/#dom-element-id
fn Id(&self) -> DOMString {
self.get_string_attribute(&local_name!("id"))
}
// https://dom.spec.whatwg.org/#dom-element-id
fn SetId(&self, id: DOMString) {
self.set_atomic_attribute(&local_name!("id"), id);
}
// https://dom.spec.whatwg.org/#dom-element-classname
fn ClassName(&self) -> DOMString {
self.get_string_attribute(&local_name!("class"))
}
// https://dom.spec.whatwg.org/#dom-element-classname
fn SetClassName(&self, class: DOMString) {
self.set_tokenlist_attribute(&local_name!("class"), class);
}
// https://dom.spec.whatwg.org/#dom-element-classlist
fn ClassList(&self) -> DomRoot<DOMTokenList> {
self.class_list.or_init(|| DOMTokenList::new(self, &local_name!("class")))
}
// https://dom.spec.whatwg.org/#dom-element-attributes
fn Attributes(&self) -> DomRoot<NamedNodeMap> {
self.attr_list.or_init(|| NamedNodeMap::new(&window_from_node(self), self))
}
// https://dom.spec.whatwg.org/#dom-element-hasattributes
fn HasAttributes(&self) -> bool {
!self.attrs.borrow().is_empty()
}
// https://dom.spec.whatwg.org/#dom-element-getattributenames
fn GetAttributeNames(&self) -> Vec<DOMString> {
self.attrs.borrow().iter().map(|attr| attr.Name()).collect()
}
// https://dom.spec.whatwg.org/#dom-element-getattribute
fn GetAttribute(&self, name: DOMString) -> Option<DOMString> {
self.GetAttributeNode(name)
.map(|s| s.Value())
}
// https://dom.spec.whatwg.org/#dom-element-getattributens
fn GetAttributeNS(&self,
namespace: Option<DOMString>,
local_name: DOMString)
-> Option<DOMString> {
self.GetAttributeNodeNS(namespace, local_name)
.map(|attr| attr.Value())
}
// https://dom.spec.whatwg.org/#dom-element-getattributenode
fn GetAttributeNode(&self, name: DOMString) -> Option<DomRoot<Attr>> {
self.get_attribute_by_name(name)
}
// https://dom.spec.whatwg.org/#dom-element-getattributenodens
fn GetAttributeNodeNS(&self,
namespace: Option<DOMString>,
local_name: DOMString)
-> Option<DomRoot<Attr>> {
let namespace = &namespace_from_domstring(namespace);
self.get_attribute(namespace, &LocalName::from(local_name))
}
// https://dom.spec.whatwg.org/#dom-element-toggleattribute
fn ToggleAttribute(&self, name: DOMString, force: Option<bool>) -> Fallible<bool> {
// Step 1.
if xml_name_type(&name) == InvalidXMLName {
return Err(Error::InvalidCharacter);
}
// Step 3.
let attribute = self.GetAttribute(name.clone());
// Step 2.
let name = self.parsed_name(name);
match attribute {
// Step 4
None => match force {
// Step 4.1.
None | Some(true) => {
self.set_first_matching_attribute(
name.clone(), AttrValue::String(String::new()), name.clone(), ns!(), None,
|attr| *attr.name() == name);
Ok(true)
},
// Step 4.2.
Some(false) => Ok(false),
},
Some(_index) => match force {
// Step 5.
None | Some(false) => {
self.remove_attribute_by_name(&name);
Ok(false)
},
// Step 6.
Some(true) => Ok(true),
},
}
}
// https://dom.spec.whatwg.org/#dom-element-setattribute
fn SetAttribute(&self, name: DOMString, value: DOMString) -> ErrorResult {
// Step 1.
if xml_name_type(&name) == InvalidXMLName {
return Err(Error::InvalidCharacter);
}
// Step 2.
let name = self.parsed_name(name);
// Step 3-5.
let value = self.parse_attribute(&ns!(), &name, value);
self.set_first_matching_attribute(
name.clone(), value, name.clone(), ns!(), None,
|attr| *attr.name() == name);
Ok(())
}
// https://dom.spec.whatwg.org/#dom-element-setattributens
fn SetAttributeNS(&self,
namespace: Option<DOMString>,
qualified_name: DOMString,
value: DOMString) -> ErrorResult {
let (namespace, prefix, local_name) =
validate_and_extract(namespace, &qualified_name)?;
let qualified_name = LocalName::from(qualified_name);
let value = self.parse_attribute(&namespace, &local_name, value);
self.set_first_matching_attribute(
local_name.clone(), value, qualified_name, namespace.clone(), prefix,
|attr| *attr.local_name() == local_name && *attr.namespace() == namespace);
Ok(())
}
// https://dom.spec.whatwg.org/#dom-element-setattributenode
fn SetAttributeNode(&self, attr: &Attr) -> Fallible<Option<DomRoot<Attr>>> {
// Step 1.
if let Some(owner) = attr.GetOwnerElement() {
if &*owner != self {
return Err(Error::InUseAttribute);
}
}
let vtable = vtable_for(self.upcast());
// This ensures that the attribute is of the expected kind for this
// specific element. This is inefficient and should probably be done
// differently.
attr.swap_value(
&mut vtable.parse_plain_attribute(attr.local_name(), attr.Value()),
);
// Step 2.
let position = self.attrs.borrow().iter().position(|old_attr| {
attr.namespace() == old_attr.namespace() && attr.local_name() == old_attr.local_name()
});
if let Some(position) = position {
let old_attr = DomRoot::from_ref(&*self.attrs.borrow()[position]);
// Step 3.
if &*old_attr == attr {
return Ok(Some(DomRoot::from_ref(attr)));
}
// Step 4.
if self.get_custom_element_definition().is_some() {
let old_name = old_attr.local_name().clone();
let old_value = DOMString::from(&**old_attr.value());
let new_value = DOMString::from(&**attr.value());
let namespace = old_attr.namespace().clone();
let reaction = CallbackReaction::AttributeChanged(old_name, Some(old_value),
Some(new_value), namespace);
ScriptThread::enqueue_callback_reaction(self, reaction, None);
}
self.will_mutate_attr(attr);
attr.set_owner(Some(self));
self.attrs.borrow_mut()[position] = Dom::from_ref(attr);
old_attr.set_owner(None);
if attr.namespace() == &ns!() {
vtable.attribute_mutated(
&attr, AttributeMutation::Set(Some(&old_attr.value())));
}
// Step 6.
Ok(Some(old_attr))
} else {
// Step 5.
attr.set_owner(Some(self));
self.push_attribute(attr);
// Step 6.
Ok(None)
}
}
// https://dom.spec.whatwg.org/#dom-element-setattributenodens
fn SetAttributeNodeNS(&self, attr: &Attr) -> Fallible<Option<DomRoot<Attr>>> {
self.SetAttributeNode(attr)
}
// https://dom.spec.whatwg.org/#dom-element-removeattribute
fn RemoveAttribute(&self, name: DOMString) {
let name = self.parsed_name(name);
self.remove_attribute_by_name(&name);
}
// https://dom.spec.whatwg.org/#dom-element-removeattributens
fn RemoveAttributeNS(&self, namespace: Option<DOMString>, local_name: DOMString) {
let namespace = namespace_from_domstring(namespace);
let local_name = LocalName::from(local_name);
self.remove_attribute(&namespace, &local_name);
}
// https://dom.spec.whatwg.org/#dom-element-removeattributenode
fn RemoveAttributeNode(&self, attr: &Attr) -> Fallible<DomRoot<Attr>> {
self.remove_first_matching_attribute(|a| a == attr)
.ok_or(Error::NotFound)
}
// https://dom.spec.whatwg.org/#dom-element-hasattribute
fn HasAttribute(&self, name: DOMString) -> bool {
self.GetAttribute(name).is_some()
}
// https://dom.spec.whatwg.org/#dom-element-hasattributens
fn HasAttributeNS(&self, namespace: Option<DOMString>, local_name: DOMString) -> bool {
self.GetAttributeNS(namespace, local_name).is_some()
}
// https://dom.spec.whatwg.org/#dom-element-getelementsbytagname
fn GetElementsByTagName(&self, localname: DOMString) -> DomRoot<HTMLCollection> {
let window = window_from_node(self);
HTMLCollection::by_qualified_name(&window, self.upcast(), LocalName::from(&*localname))
}
// https://dom.spec.whatwg.org/#dom-element-getelementsbytagnamens
fn GetElementsByTagNameNS(&self,
maybe_ns: Option<DOMString>,
localname: DOMString)
-> DomRoot<HTMLCollection> {
let window = window_from_node(self);
HTMLCollection::by_tag_name_ns(&window, self.upcast(), localname, maybe_ns)
}
// https://dom.spec.whatwg.org/#dom-element-getelementsbyclassname
fn GetElementsByClassName(&self, classes: DOMString) -> DomRoot<HTMLCollection> {
let window = window_from_node(self);
HTMLCollection::by_class_name(&window, self.upcast(), classes)
}
// https://drafts.csswg.org/cssom-view/#dom-element-getclientrects
fn GetClientRects(&self) -> Vec<DomRoot<DOMRect>> {
let win = window_from_node(self);
let raw_rects = self.upcast::<Node>().content_boxes();
raw_rects.iter().map(|rect| {
DOMRect::new(win.upcast(),
rect.origin.x.to_f64_px(),
rect.origin.y.to_f64_px(),
rect.size.width.to_f64_px(),
rect.size.height.to_f64_px())
}).collect()
}
// https://drafts.csswg.org/cssom-view/#dom-element-getboundingclientrect
fn GetBoundingClientRect(&self) -> DomRoot<DOMRect> {
let win = window_from_node(self);
let rect = self.upcast::<Node>().bounding_content_box_or_zero();
DOMRect::new(win.upcast(),
rect.origin.x.to_f64_px(),
rect.origin.y.to_f64_px(),
rect.size.width.to_f64_px(),
rect.size.height.to_f64_px())
}
// https://drafts.csswg.org/cssom-view/#dom-element-scroll
fn Scroll(&self, options: &ScrollToOptions) {
// Step 1
let left = options.left.unwrap_or(self.ScrollLeft());
let top = options.top.unwrap_or(self.ScrollTop());
self.scroll(left, top, options.parent.behavior);
}
// https://drafts.csswg.org/cssom-view/#dom-element-scroll
fn Scroll_(&self, x: f64, y: f64) {
self.scroll(x, y, ScrollBehavior::Auto);
}
// https://drafts.csswg.org/cssom-view/#dom-element-scrollto
fn ScrollTo(&self, options: &ScrollToOptions) {
self.Scroll(options);
}
// https://drafts.csswg.org/cssom-view/#dom-element-scrollto
fn ScrollTo_(&self, x: f64, y: f64) {
self.Scroll_(x, y);
}
// https://drafts.csswg.org/cssom-view/#dom-element-scrollby
fn ScrollBy(&self, options: &ScrollToOptions) {
// Step 2
let delta_left = options.left.unwrap_or(0.0f64);
let delta_top = options.top.unwrap_or(0.0f64);
let left = self.ScrollLeft();
let top = self.ScrollTop();
self.scroll(left + delta_left, top + delta_top,
options.parent.behavior);
}
// https://drafts.csswg.org/cssom-view/#dom-element-scrollby
fn ScrollBy_(&self, x: f64, y: f64) {
let left = self.ScrollLeft();
let top = self.ScrollTop();
self.scroll(left + x, top + y, ScrollBehavior::Auto);
}
// https://drafts.csswg.org/cssom-view/#dom-element-scrolltop
fn ScrollTop(&self) -> f64 {
let node = self.upcast::<Node>();
// Step 1
let doc = node.owner_doc();
// Step 2
if !doc.is_fully_active() {
return 0.0;
}
// Step 3
let win = match doc.GetDefaultView() {
None => return 0.0,
Some(win) => win,
};
// Step 5
if *self.root_element() == *self {
if doc.quirks_mode() == QuirksMode::Quirks {
return 0.0;
}
// Step 6
return win.ScrollY() as f64;
}
// Step 7
if doc.GetBody().r() == self.downcast::<HTMLElement>() &&
doc.quirks_mode() == QuirksMode::Quirks &&
!self.potentially_scrollable() {
return win.ScrollY() as f64;
}
// Step 8
if !self.has_css_layout_box() {
return 0.0;
}
// Step 9
let point = node.scroll_offset();
return point.y.abs() as f64;
}
// https://drafts.csswg.org/cssom-view/#dom-element-scrolltop
fn SetScrollTop(&self, y_: f64) {
let behavior = ScrollBehavior::Auto;
// Step 1, 2
let y = if y_.is_finite() { y_ } else { 0.0f64 };
let node = self.upcast::<Node>();
// Step 3
let doc = node.owner_doc();
// Step 4
if !doc.is_fully_active() {
return;
}
// Step 5
let win = match doc.GetDefaultView() {
None => return,
Some(win) => win,
};
// Step 7
if *self.root_element() == *self {
if doc.quirks_mode() != QuirksMode::Quirks {
win.scroll(win.ScrollX() as f64, y, behavior);
}
return;
}
// Step 9
if doc.GetBody().r() == self.downcast::<HTMLElement>() &&
doc.quirks_mode() == QuirksMode::Quirks &&
!self.potentially_scrollable() {
win.scroll(win.ScrollX() as f64, y, behavior);
return;
}
// Step 10
if !self.has_css_layout_box() ||
!self.has_scrolling_box() ||
!self.has_overflow()
{
return;
}
// Step 11
win.scroll_node(node, self.ScrollLeft(), y, behavior);
}
// https://drafts.csswg.org/cssom-view/#dom-element-scrolltop
fn ScrollLeft(&self) -> f64 {
let node = self.upcast::<Node>();
// Step 1
let doc = node.owner_doc();
// Step 2
if !doc.is_fully_active() {
return 0.0;
}
// Step 3
let win = match doc.GetDefaultView() {
None => return 0.0,
Some(win) => win,
};
// Step 5
if *self.root_element() == *self {
if doc.quirks_mode() != QuirksMode::Quirks {
// Step 6
return win.ScrollX() as f64;
}
return 0.0;
}
// Step 7
if doc.GetBody().r() == self.downcast::<HTMLElement>() &&
doc.quirks_mode() == QuirksMode::Quirks &&
!self.potentially_scrollable() {
return win.ScrollX() as f64;
}
// Step 8
if !self.has_css_layout_box() {
return 0.0;
}
// Step 9
let point = node.scroll_offset();
return point.x.abs() as f64;
}
// https://drafts.csswg.org/cssom-view/#dom-element-scrollleft
fn SetScrollLeft(&self, x_: f64) {
let behavior = ScrollBehavior::Auto;
// Step 1, 2
let x = if x_.is_finite() { x_ } else { 0.0f64 };
let node = self.upcast::<Node>();
// Step 3
let doc = node.owner_doc();
// Step 4
if !doc.is_fully_active() {
return;
}
// Step 5
let win = match doc.GetDefaultView() {
None => return,
Some(win) => win,
};
// Step 7
if *self.root_element() == *self {
if doc.quirks_mode() == QuirksMode::Quirks {
return;
}
win.scroll(x, win.ScrollY() as f64, behavior);
return;
}
// Step 9
if doc.GetBody().r() == self.downcast::<HTMLElement>() &&
doc.quirks_mode() == QuirksMode::Quirks &&
!self.potentially_scrollable() {
win.scroll(x, win.ScrollY() as f64, behavior);
return;
}
// Step 10
if !self.has_css_layout_box() ||
!self.has_scrolling_box() ||
!self.has_overflow()
{
return;
}
// Step 11
win.scroll_node(node, x, self.ScrollTop(), behavior);
}
// https://drafts.csswg.org/cssom-view/#dom-element-scrollwidth
fn ScrollWidth(&self) -> i32 {
self.upcast::<Node>().scroll_area().size.width
}
// https://drafts.csswg.org/cssom-view/#dom-element-scrollheight
fn ScrollHeight(&self) -> i32 {
self.upcast::<Node>().scroll_area().size.height
}
// https://drafts.csswg.org/cssom-view/#dom-element-clienttop
fn ClientTop(&self) -> i32 {
self.upcast::<Node>().client_rect().origin.y
}
// https://drafts.csswg.org/cssom-view/#dom-element-clientleft
fn ClientLeft(&self) -> i32 {
self.upcast::<Node>().client_rect().origin.x
}
// https://drafts.csswg.org/cssom-view/#dom-element-clientwidth
fn ClientWidth(&self) -> i32 {
self.upcast::<Node>().client_rect().size.width
}
// https://drafts.csswg.org/cssom-view/#dom-element-clientheight
fn ClientHeight(&self) -> i32 {
self.upcast::<Node>().client_rect().size.height
}
/// <https://w3c.github.io/DOM-Parsing/#widl-Element-innerHTML>
fn GetInnerHTML(&self) -> Fallible<DOMString> {
let qname = QualName::new(self.prefix().clone(),
self.namespace().clone(),
self.local_name().clone());
if document_from_node(self).is_html_document() {
return self.serialize(ChildrenOnly(Some(qname)));
} else {
return self.xmlSerialize(XmlChildrenOnly(Some(qname)));
}
}
/// <https://w3c.github.io/DOM-Parsing/#widl-Element-innerHTML>
fn SetInnerHTML(&self, value: DOMString) -> ErrorResult {
// Step 1.
let frag = self.parse_fragment(value)?;
// Step 2.
// https://github.com/w3c/DOM-Parsing/issues/1
let target = if let Some(template) = self.downcast::<HTMLTemplateElement>() {
DomRoot::upcast(template.Content())
} else {
DomRoot::from_ref(self.upcast())
};
Node::replace_all(Some(frag.upcast()), &target);
Ok(())
}
// https://dvcs.w3.org/hg/innerhtml/raw-file/tip/index.html#widl-Element-outerHTML
fn GetOuterHTML(&self) -> Fallible<DOMString> {
if document_from_node(self).is_html_document() {
return self.serialize(IncludeNode);
} else {
return self.xmlSerialize(XmlIncludeNode);
}
}
// https://w3c.github.io/DOM-Parsing/#dom-element-outerhtml
fn SetOuterHTML(&self, value: DOMString) -> ErrorResult {
let context_document = document_from_node(self);
let context_node = self.upcast::<Node>();
// Step 1.
let context_parent = match context_node.GetParentNode() {
None => {
// Step 2.
return Ok(());
},
Some(parent) => parent,
};
let parent = match context_parent.type_id() {
// Step 3.
NodeTypeId::Document(_) => return Err(Error::NoModificationAllowed),
// Step 4.
NodeTypeId::DocumentFragment => {
let body_elem = Element::create(QualName::new(None, ns!(html), local_name!("body")),
None,
&context_document,
ElementCreator::ScriptCreated,
CustomElementCreationMode::Synchronous);
DomRoot::upcast(body_elem)
},
_ => context_node.GetParentElement().unwrap()
};
// Step 5.
let frag = parent.parse_fragment(value)?;
// Step 6.
context_parent.ReplaceChild(frag.upcast(), context_node)?;
Ok(())
}
// https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-previouselementsibling
fn GetPreviousElementSibling(&self) -> Option<DomRoot<Element>> {
self.upcast::<Node>().preceding_siblings().filter_map(DomRoot::downcast).next()
}
// https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-nextelementsibling
fn GetNextElementSibling(&self) -> Option<DomRoot<Element>> {
self.upcast::<Node>().following_siblings().filter_map(DomRoot::downcast).next()
}
// https://dom.spec.whatwg.org/#dom-parentnode-children
fn Children(&self) -> DomRoot<HTMLCollection> {
let window = window_from_node(self);
HTMLCollection::children(&window, self.upcast())
}
// https://dom.spec.whatwg.org/#dom-parentnode-firstelementchild
fn GetFirstElementChild(&self) -> Option<DomRoot<Element>> {
self.upcast::<Node>().child_elements().next()
}
// https://dom.spec.whatwg.org/#dom-parentnode-lastelementchild
fn GetLastElementChild(&self) -> Option<DomRoot<Element>> {
self.upcast::<Node>().rev_children().filter_map(DomRoot::downcast::<Element>).next()
}
// https://dom.spec.whatwg.org/#dom-parentnode-childelementcount
fn ChildElementCount(&self) -> u32 {
self.upcast::<Node>().child_elements().count() as u32
}
// https://dom.spec.whatwg.org/#dom-parentnode-prepend
fn Prepend(&self, nodes: Vec<NodeOrString>) -> ErrorResult {
self.upcast::<Node>().prepend(nodes)
}
// https://dom.spec.whatwg.org/#dom-parentnode-append
fn Append(&self, nodes: Vec<NodeOrString>) -> ErrorResult {
self.upcast::<Node>().append(nodes)
}
// https://dom.spec.whatwg.org/#dom-parentnode-queryselector
fn QuerySelector(&self, selectors: DOMString) -> Fallible<Option<DomRoot<Element>>> {
let root = self.upcast::<Node>();
root.query_selector(selectors)
}
// https://dom.spec.whatwg.org/#dom-parentnode-queryselectorall
fn QuerySelectorAll(&self, selectors: DOMString) -> Fallible<DomRoot<NodeList>> {
let root = self.upcast::<Node>();
root.query_selector_all(selectors)
}
// https://dom.spec.whatwg.org/#dom-childnode-before
fn Before(&self, nodes: Vec<NodeOrString>) -> ErrorResult {
self.upcast::<Node>().before(nodes)
}
// https://dom.spec.whatwg.org/#dom-childnode-after
fn After(&self, nodes: Vec<NodeOrString>) -> ErrorResult {
self.upcast::<Node>().after(nodes)
}
// https://dom.spec.whatwg.org/#dom-childnode-replacewith
fn ReplaceWith(&self, nodes: Vec<NodeOrString>) -> ErrorResult {
self.upcast::<Node>().replace_with(nodes)
}
// https://dom.spec.whatwg.org/#dom-childnode-remove
fn Remove(&self) {
self.upcast::<Node>().remove_self();
}
// https://dom.spec.whatwg.org/#dom-element-matches
fn Matches(&self, selectors: DOMString) -> Fallible<bool> {
let selectors =
match SelectorParser::parse_author_origin_no_namespace(&selectors) {
Err(_) => return Err(Error::Syntax),
Ok(selectors) => selectors,
};
let quirks_mode = document_from_node(self).quirks_mode();
let element = DomRoot::from_ref(self);
Ok(dom_apis::element_matches(&element, &selectors, quirks_mode))
}
// https://dom.spec.whatwg.org/#dom-element-webkitmatchesselector
fn WebkitMatchesSelector(&self, selectors: DOMString) -> Fallible<bool> {
self.Matches(selectors)
}
// https://dom.spec.whatwg.org/#dom-element-closest
fn Closest(&self, selectors: DOMString) -> Fallible<Option<DomRoot<Element>>> {
let selectors =
match SelectorParser::parse_author_origin_no_namespace(&selectors) {
Err(_) => return Err(Error::Syntax),
Ok(selectors) => selectors,
};
let quirks_mode = document_from_node(self).quirks_mode();
Ok(dom_apis::element_closest(
DomRoot::from_ref(self),
&selectors,
quirks_mode,
))
}
// https://dom.spec.whatwg.org/#dom-element-insertadjacentelement
fn InsertAdjacentElement(&self, where_: DOMString, element: &Element)
-> Fallible<Option<DomRoot<Element>>> {
let where_ = where_.parse::<AdjacentPosition>()?;
let inserted_node = self.insert_adjacent(where_, element.upcast())?;
Ok(inserted_node.map(|node| DomRoot::downcast(node).unwrap()))
}
// https://dom.spec.whatwg.org/#dom-element-insertadjacenttext
fn InsertAdjacentText(&self, where_: DOMString, data: DOMString)
-> ErrorResult {
// Step 1.
let text = Text::new(data, &document_from_node(self));
// Step 2.
let where_ = where_.parse::<AdjacentPosition>()?;
self.insert_adjacent(where_, text.upcast()).map(|_| ())
}
// https://w3c.github.io/DOM-Parsing/#dom-element-insertadjacenthtml
fn InsertAdjacentHTML(&self, position: DOMString, text: DOMString)
-> ErrorResult {
// Step 1.
let position = position.parse::<AdjacentPosition>()?;
let context = match position {
AdjacentPosition::BeforeBegin | AdjacentPosition::AfterEnd => {
match self.upcast::<Node>().GetParentNode() {
Some(ref node) if node.is::<Document>() => {
return Err(Error::NoModificationAllowed)
}
None => return Err(Error::NoModificationAllowed),
Some(node) => node,
}
}
AdjacentPosition::AfterBegin | AdjacentPosition::BeforeEnd => {
DomRoot::from_ref(self.upcast::<Node>())
}
};
// Step 2.
let context = Element::fragment_parsing_context(
&context.owner_doc(), context.downcast::<Element>());
// Step 3.
let fragment = context.parse_fragment(text)?;
// Step 4.
self.insert_adjacent(position, fragment.upcast()).map(|_| ())
}
// check-tidy: no specs after this line
fn EnterFormalActivationState(&self) -> ErrorResult {
match self.as_maybe_activatable() {
Some(a) => {
a.enter_formal_activation_state();
return Ok(());
},
None => return Err(Error::NotSupported)
}
}
fn ExitFormalActivationState(&self) -> ErrorResult {
match self.as_maybe_activatable() {
Some(a) => {
a.exit_formal_activation_state();
return Ok(());
},
None => return Err(Error::NotSupported)
}
}
// https://fullscreen.spec.whatwg.org/#dom-element-requestfullscreen
#[allow(unrooted_must_root)]
fn RequestFullscreen(&self) -> Rc<Promise> {
let doc = document_from_node(self);
doc.enter_fullscreen(self)
}
}
impl VirtualMethods for Element {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<Node>() as &VirtualMethods)
}
fn attribute_affects_presentational_hints(&self, attr: &Attr) -> bool {
// FIXME: This should be more fine-grained, not all elements care about these.
if attr.local_name() == &local_name!("width") ||
attr.local_name() == &local_name!("height") {
return true;
}
self.super_type().unwrap().attribute_affects_presentational_hints(attr)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
let node = self.upcast::<Node>();
let doc = node.owner_doc();
match attr.local_name() {
&local_name!("style") => {
// Modifying the `style` attribute might change style.
*self.style_attribute.borrow_mut() = match mutation {
AttributeMutation::Set(..) => {
// This is the fast path we use from
// CSSStyleDeclaration.
//
// Juggle a bit to keep the borrow checker happy
// while avoiding the extra clone.
let is_declaration = match *attr.value() {
AttrValue::Declaration(..) => true,
_ => false,
};
let block = if is_declaration {
let mut value = AttrValue::String(String::new());
attr.swap_value(&mut value);
let (serialization, block) = match value {
AttrValue::Declaration(s, b) => (s, b),
_ => unreachable!(),
};
let mut value = AttrValue::String(serialization);
attr.swap_value(&mut value);
block
} else {
let win = window_from_node(self);
Arc::new(doc.style_shared_lock().wrap(parse_style_attribute(
&attr.value(),
&doc.base_url(),
win.css_error_reporter(),
doc.quirks_mode())))
};
Some(block)
}
AttributeMutation::Removed => {
None
}
};
},
&local_name!("id") => {
*self.id_attribute.borrow_mut() =
mutation.new_value(attr).and_then(|value| {
let value = value.as_atom();
if value != &atom!("") {
Some(value.clone())
} else {
None
}
});
if node.is_in_doc() {
let value = attr.value().as_atom().clone();
match mutation {
AttributeMutation::Set(old_value) => {
if let Some(old_value) = old_value {
let old_value = old_value.as_atom().clone();
doc.unregister_named_element(self, old_value);
}
if value != atom!("") {
doc.register_named_element(self, value);
}
},
AttributeMutation::Removed => {
if value != atom!("") {
doc.unregister_named_element(self, value);
}
}
}
}
},
_ => {
// FIXME(emilio): This is pretty dubious, and should be done in
// the relevant super-classes.
if attr.namespace() == &ns!() &&
attr.local_name() == &local_name!("src") {
node.dirty(NodeDamage::OtherNodeDamage);
}
},
};
// Make sure we rev the version even if we didn't dirty the node. If we
// don't do this, various attribute-dependent htmlcollections (like those
// generated by getElementsByClassName) might become stale.
node.rev_version();
}
fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
match name {
&local_name!("id") => AttrValue::from_atomic(value.into()),
&local_name!("class") => AttrValue::from_serialized_tokenlist(value.into()),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.bind_to_tree(tree_in_doc);
}
if let Some(f) = self.as_maybe_form_control() {
f.bind_form_control_to_tree();
}
if !tree_in_doc {
return;
}
let doc = document_from_node(self);
if let Some(ref value) = *self.id_attribute.borrow() {
doc.register_named_element(self, value.clone());
}
// This is used for layout optimization.
doc.increment_dom_count();
}
fn unbind_from_tree(&self, context: &UnbindContext) {
self.super_type().unwrap().unbind_from_tree(context);
if let Some(f) = self.as_maybe_form_control() {
f.unbind_form_control_from_tree();
}
if !context.tree_in_doc {
return;
}
let doc = document_from_node(self);
let fullscreen = doc.GetFullscreenElement();
if fullscreen.r() == Some(self) {
doc.exit_fullscreen();
}
if let Some(ref value) = *self.id_attribute.borrow() {
doc.unregister_named_element(self, value.clone());
}
// This is used for layout optimization.
doc.decrement_dom_count();
}
fn children_changed(&self, mutation: &ChildrenMutation) {
if let Some(ref s) = self.super_type() {
s.children_changed(mutation);
}
let flags = self.selector_flags.get();
if flags.intersects(ElementSelectorFlags::HAS_SLOW_SELECTOR) {
// All children of this node need to be restyled when any child changes.
self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage);
} else {
if flags.intersects(ElementSelectorFlags::HAS_SLOW_SELECTOR_LATER_SIBLINGS) {
if let Some(next_child) = mutation.next_child() {
for child in next_child.inclusively_following_siblings() {
if child.is::<Element>() {
child.dirty(NodeDamage::OtherNodeDamage);
}
}
}
}
if flags.intersects(ElementSelectorFlags::HAS_EDGE_CHILD_SELECTOR) {
if let Some(child) = mutation.modified_edge_element() {
child.dirty(NodeDamage::OtherNodeDamage);
}
}
}
}
fn adopting_steps(&self, old_doc: &Document) {
self.super_type().unwrap().adopting_steps(old_doc);
if document_from_node(self).is_html_document() != old_doc.is_html_document() {
self.tag_name.clear();
}
}
}
impl<'a> SelectorsElement for DomRoot<Element> {
type Impl = SelectorImpl;
fn opaque(&self) -> ::selectors::OpaqueElement {
::selectors::OpaqueElement::new(self.reflector().get_jsobject().get())
}
fn parent_element(&self) -> Option<DomRoot<Element>> {
self.upcast::<Node>().GetParentElement()
}
fn parent_node_is_shadow_root(&self) -> bool {
false
}
fn containing_shadow_host(&self) -> Option<Self> {
None
}
fn match_pseudo_element(
&self,
_pseudo: &PseudoElement,
_context: &mut MatchingContext<Self::Impl>,
) -> bool {
false
}
fn prev_sibling_element(&self) -> Option<DomRoot<Element>> {
self.node.preceding_siblings().filter_map(DomRoot::downcast).next()
}
fn next_sibling_element(&self) -> Option<DomRoot<Element>> {
self.node.following_siblings().filter_map(DomRoot::downcast).next()
}
fn attr_matches(&self,
ns: &NamespaceConstraint<&Namespace>,
local_name: &LocalName,
operation: &AttrSelectorOperation<&String>)
-> bool {
match *ns {
NamespaceConstraint::Specific(ref ns) => {
self.get_attribute(ns, local_name)
.map_or(false, |attr| attr.value().eval_selector(operation))
}
NamespaceConstraint::Any => {
self.attrs.borrow().iter().any(|attr| {
attr.local_name() == local_name &&
attr.value().eval_selector(operation)
})
}
}
}
fn is_root(&self) -> bool {
match self.node.GetParentNode() {
None => false,
Some(node) => node.is::<Document>(),
}
}
fn is_empty(&self) -> bool {
self.node.children().all(|node| !node.is::<Element>() && match node.downcast::<Text>() {
None => true,
Some(text) => text.upcast::<CharacterData>().data().is_empty()
})
}
fn local_name(&self) -> &LocalName {
Element::local_name(self)
}
fn namespace(&self) -> &Namespace {
Element::namespace(self)
}
fn match_non_ts_pseudo_class<F>(
&self,
pseudo_class: &NonTSPseudoClass,
_: &mut MatchingContext<Self::Impl>,
_: &mut F,
) -> bool
where
F: FnMut(&Self, ElementSelectorFlags),
{
match *pseudo_class {
// https://github.com/servo/servo/issues/8718
NonTSPseudoClass::Link |
NonTSPseudoClass::AnyLink => self.is_link(),
NonTSPseudoClass::Visited => false,
NonTSPseudoClass::ServoNonZeroBorder => {
match self.downcast::<HTMLTableElement>() {
None => false,
Some(this) => {
match this.get_border() {
None | Some(0) => false,
Some(_) => true,
}
}
}
},
NonTSPseudoClass::ServoCaseSensitiveTypeAttr(ref expected_value) => {
self.get_attribute(&ns!(), &local_name!("type"))
.map_or(false, |attr| attr.value().eq(expected_value))
}
// FIXME(heycam): This is wrong, since extended_filtering accepts
// a string containing commas (separating each language tag in
// a list) but the pseudo-class instead should be parsing and
// storing separate <ident> or <string>s for each language tag.
NonTSPseudoClass::Lang(ref lang) => extended_filtering(&*self.get_lang(), &*lang),
NonTSPseudoClass::ReadOnly =>
!Element::state(self).contains(pseudo_class.state_flag()),
NonTSPseudoClass::Active |
NonTSPseudoClass::Focus |
NonTSPseudoClass::Fullscreen |
NonTSPseudoClass::Hover |
NonTSPseudoClass::Enabled |
NonTSPseudoClass::Disabled |
NonTSPseudoClass::Checked |
NonTSPseudoClass::Indeterminate |
NonTSPseudoClass::ReadWrite |
NonTSPseudoClass::PlaceholderShown |
NonTSPseudoClass::Target =>
Element::state(self).contains(pseudo_class.state_flag()),
}
}
fn is_link(&self) -> bool {
// FIXME: This is HTML only.
let node = self.upcast::<Node>();
match node.type_id() {
// https://html.spec.whatwg.org/multipage/#selector-link
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAnchorElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAreaElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLLinkElement)) => {
self.has_attribute(&local_name!("href"))
},
_ => false,
}
}
fn has_id(&self, id: &Atom, case_sensitivity: CaseSensitivity) -> bool {
self.id_attribute.borrow().as_ref().map_or(false, |atom| case_sensitivity.eq_atom(id, atom))
}
fn has_class(&self, name: &Atom, case_sensitivity: CaseSensitivity) -> bool {
Element::has_class(&**self, name, case_sensitivity)
}
fn is_html_element_in_html_document(&self) -> bool {
self.html_element_in_html_document()
}
fn is_html_slot_element(&self) -> bool {
self.is_html_element() && self.local_name() == &local_name!("slot")
}
}
impl Element {
pub fn as_maybe_activatable(&self) -> Option<&Activatable> {
let element = match self.upcast::<Node>().type_id() {
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement)) => {
let element = self.downcast::<HTMLInputElement>().unwrap();
Some(element as &Activatable)
},
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLButtonElement)) => {
let element = self.downcast::<HTMLButtonElement>().unwrap();
Some(element as &Activatable)
},
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAnchorElement)) => {
let element = self.downcast::<HTMLAnchorElement>().unwrap();
Some(element as &Activatable)
},
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLLabelElement)) => {
let element = self.downcast::<HTMLLabelElement>().unwrap();
Some(element as &Activatable)
},
_ => {
None
}
};
element.and_then(|elem| {
if elem.is_instance_activatable() {
Some(elem)
} else {
None
}
})
}
pub fn as_stylesheet_owner(&self) -> Option<&StylesheetOwner> {
if let Some(s) = self.downcast::<HTMLStyleElement>() {
return Some(s as &StylesheetOwner)
}
if let Some(l) = self.downcast::<HTMLLinkElement>() {
return Some(l as &StylesheetOwner)
}
None
}
// https://html.spec.whatwg.org/multipage/#category-submit
pub fn as_maybe_validatable(&self) -> Option<&Validatable> {
let element = match self.upcast::<Node>().type_id() {
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement)) => {
let element = self.downcast::<HTMLInputElement>().unwrap();
Some(element as &Validatable)
},
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLButtonElement)) => {
let element = self.downcast::<HTMLButtonElement>().unwrap();
Some(element as &Validatable)
},
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLObjectElement)) => {
let element = self.downcast::<HTMLObjectElement>().unwrap();
Some(element as &Validatable)
},
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSelectElement)) => {
let element = self.downcast::<HTMLSelectElement>().unwrap();
Some(element as &Validatable)
},
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTextAreaElement)) => {
let element = self.downcast::<HTMLTextAreaElement>().unwrap();
Some(element as &Validatable)
},
_ => {
None
}
};
element
}
pub fn click_in_progress(&self) -> bool {
self.upcast::<Node>().get_flag(NodeFlags::CLICK_IN_PROGRESS)
}
pub fn set_click_in_progress(&self, click: bool) {
self.upcast::<Node>().set_flag(NodeFlags::CLICK_IN_PROGRESS, click)
}
// https://html.spec.whatwg.org/multipage/#nearest-activatable-element
pub fn nearest_activable_element(&self) -> Option<DomRoot<Element>> {
match self.as_maybe_activatable() {
Some(el) => Some(DomRoot::from_ref(el.as_element())),
None => {
let node = self.upcast::<Node>();
for node in node.ancestors() {
if let Some(node) = node.downcast::<Element>() {
if node.as_maybe_activatable().is_some() {
return Some(DomRoot::from_ref(node));
}
}
}
None
}
}
}
/// Please call this method *only* for real click events
///
/// <https://html.spec.whatwg.org/multipage/#run-authentic-click-activation-steps>
///
/// Use an element's synthetic click activation (or handle_event) for any script-triggered clicks.
/// If the spec says otherwise, check with Manishearth first
pub fn authentic_click_activation(&self, event: &Event) {
// Not explicitly part of the spec, however this helps enforce the invariants
// required to save state between pre-activation and post-activation
// since we cannot nest authentic clicks (unlike synthetic click activation, where
// the script can generate more click events from the handler)
assert!(!self.click_in_progress());
let target = self.upcast();
// Step 2 (requires canvas support)
// Step 3
self.set_click_in_progress(true);
// Step 4
let e = self.nearest_activable_element();
match e {
Some(ref el) => match el.as_maybe_activatable() {
Some(elem) => {
// Step 5-6
elem.pre_click_activation();
event.fire(target);
if !event.DefaultPrevented() {
// post click activation
elem.activation_behavior(event, target);
} else {
elem.canceled_activation();
}
}
// Step 6
None => {
event.fire(target);
}
},
// Step 6
None => {
event.fire(target);
}
}
// Step 7
self.set_click_in_progress(false);
}
// https://html.spec.whatwg.org/multipage/#language
pub fn get_lang(&self) -> String {
self.upcast::<Node>().inclusive_ancestors().filter_map(|node| {
node.downcast::<Element>().and_then(|el| {
el.get_attribute(&ns!(xml), &local_name!("lang")).or_else(|| {
el.get_attribute(&ns!(), &local_name!("lang"))
}).map(|attr| String::from(attr.Value()))
})
// TODO: Check meta tags for a pragma-set default language
// TODO: Check HTTP Content-Language header
}).next().unwrap_or(String::new())
}
pub fn state(&self) -> ElementState {
self.state.get()
}
pub fn set_state(&self, which: ElementState, value: bool) {
let mut state = self.state.get();
if state.contains(which) == value {
return;
}
let node = self.upcast::<Node>();
node.owner_doc().element_state_will_change(self);
if value {
state.insert(which);
} else {
state.remove(which);
}
self.state.set(state);
}
pub fn active_state(&self) -> bool {
self.state.get().contains(ElementState::IN_ACTIVE_STATE)
}
/// <https://html.spec.whatwg.org/multipage/#concept-selector-active>
pub fn set_active_state(&self, value: bool) {
self.set_state(ElementState::IN_ACTIVE_STATE, value);
if let Some(parent) = self.upcast::<Node>().GetParentElement() {
parent.set_active_state(value);
}
}
pub fn focus_state(&self) -> bool {
self.state.get().contains(ElementState::IN_FOCUS_STATE)
}
pub fn set_focus_state(&self, value: bool) {
self.set_state(ElementState::IN_FOCUS_STATE, value);
self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage);
}
pub fn hover_state(&self) -> bool {
self.state.get().contains(ElementState::IN_HOVER_STATE)
}
pub fn set_hover_state(&self, value: bool) {
self.set_state(ElementState::IN_HOVER_STATE, value)
}
pub fn enabled_state(&self) -> bool {
self.state.get().contains(ElementState::IN_ENABLED_STATE)
}
pub fn set_enabled_state(&self, value: bool) {
self.set_state(ElementState::IN_ENABLED_STATE, value)
}
pub fn disabled_state(&self) -> bool {
self.state.get().contains(ElementState::IN_DISABLED_STATE)
}
pub fn set_disabled_state(&self, value: bool) {
self.set_state(ElementState::IN_DISABLED_STATE, value)
}
pub fn read_write_state(&self) -> bool {
self.state.get().contains(ElementState::IN_READ_WRITE_STATE)
}
pub fn set_read_write_state(&self, value: bool) {
self.set_state(ElementState::IN_READ_WRITE_STATE, value)
}
pub fn placeholder_shown_state(&self) -> bool {
self.state.get().contains(ElementState::IN_PLACEHOLDER_SHOWN_STATE)
}
pub fn set_placeholder_shown_state(&self, value: bool) {
if self.placeholder_shown_state() != value {
self.set_state(ElementState::IN_PLACEHOLDER_SHOWN_STATE, value);
self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage);
}
}
pub fn target_state(&self) -> bool {
self.state.get().contains(ElementState::IN_TARGET_STATE)
}
pub fn set_target_state(&self, value: bool) {
self.set_state(ElementState::IN_TARGET_STATE, value)
}
pub fn fullscreen_state(&self) -> bool {
self.state.get().contains(ElementState::IN_FULLSCREEN_STATE)
}
pub fn set_fullscreen_state(&self, value: bool) {
self.set_state(ElementState::IN_FULLSCREEN_STATE, value)
}
/// <https://dom.spec.whatwg.org/#connected>
pub fn is_connected(&self) -> bool {
let node = self.upcast::<Node>();
let root = node.GetRootNode();
root.is::<Document>()
}
}
impl Element {
pub fn check_ancestors_disabled_state_for_form_control(&self) {
let node = self.upcast::<Node>();
if self.disabled_state() {
return;
}
for ancestor in node.ancestors() {
if !ancestor.is::<HTMLFieldSetElement>() {
continue;
}
if !ancestor.downcast::<Element>().unwrap().disabled_state() {
continue;<|fim▁hole|> self.set_disabled_state(true);
self.set_enabled_state(false);
return;
}
if let Some(ref legend) = ancestor.children().find(|n| n.is::<HTMLLegendElement>()) {
// XXXabinader: should we save previous ancestor to avoid this iteration?
if node.ancestors().any(|ancestor| ancestor == *legend) {
continue;
}
}
self.set_disabled_state(true);
self.set_enabled_state(false);
return;
}
}
pub fn check_parent_disabled_state_for_option(&self) {
if self.disabled_state() {
return;
}
let node = self.upcast::<Node>();
if let Some(ref parent) = node.GetParentNode() {
if parent.is::<HTMLOptGroupElement>() &&
parent.downcast::<Element>().unwrap().disabled_state() {
self.set_disabled_state(true);
self.set_enabled_state(false);
}
}
}
pub fn check_disabled_attribute(&self) {
let has_disabled_attrib = self.has_attribute(&local_name!("disabled"));
self.set_disabled_state(has_disabled_attrib);
self.set_enabled_state(!has_disabled_attrib);
}
}
#[derive(Clone, Copy)]
pub enum AttributeMutation<'a> {
/// The attribute is set, keep track of old value.
/// <https://dom.spec.whatwg.org/#attribute-is-set>
Set(Option<&'a AttrValue>),
/// The attribute is removed.
/// <https://dom.spec.whatwg.org/#attribute-is-removed>
Removed,
}
impl<'a> AttributeMutation<'a> {
pub fn is_removal(&self) -> bool {
match *self {
AttributeMutation::Removed => true,
AttributeMutation::Set(..) => false,
}
}
pub fn new_value<'b>(&self, attr: &'b Attr) -> Option<Ref<'b, AttrValue>> {
match *self {
AttributeMutation::Set(_) => Some(attr.value()),
AttributeMutation::Removed => None,
}
}
}
/// A holder for an element's "tag name", which will be lazily
/// resolved and cached. Should be reset when the document
/// owner changes.
#[derive(JSTraceable, MallocSizeOf)]
struct TagName {
ptr: DomRefCell<Option<LocalName>>,
}
impl TagName {
fn new() -> TagName {
TagName { ptr: DomRefCell::new(None) }
}
/// Retrieve a copy of the current inner value. If it is `None`, it is
/// initialized with the result of `cb` first.
fn or_init<F>(&self, cb: F) -> LocalName
where F: FnOnce() -> LocalName
{
match &mut *self.ptr.borrow_mut() {
&mut Some(ref name) => name.clone(),
ptr => {
let name = cb();
*ptr = Some(name.clone());
name
}
}
}
/// Clear the cached tag name, so that it will be re-calculated the
/// next time that `or_init()` is called.
fn clear(&self) {
*self.ptr.borrow_mut() = None;
}
}
pub struct ElementPerformFullscreenEnter {
element: Trusted<Element>,
promise: TrustedPromise,
error: bool,
}
impl ElementPerformFullscreenEnter {
pub fn new(element: Trusted<Element>, promise: TrustedPromise, error: bool) -> Box<ElementPerformFullscreenEnter> {
Box::new(ElementPerformFullscreenEnter {
element: element,
promise: promise,
error: error,
})
}
}
impl TaskOnce for ElementPerformFullscreenEnter {
#[allow(unrooted_must_root)]
fn run_once(self) {
let element = self.element.root();
let promise = self.promise.root();
let document = document_from_node(element.r());
// Step 7.1
if self.error || !element.fullscreen_element_ready_check() {
document.upcast::<EventTarget>().fire_event(atom!("fullscreenerror"));
promise.reject_error(Error::Type(String::from("fullscreen is not connected")));
return
}
// TODO Step 7.2-4
// Step 7.5
element.set_fullscreen_state(true);
document.set_fullscreen_element(Some(&element));
document.window().reflow(ReflowGoal::Full, ReflowReason::ElementStateChanged);
// Step 7.6
document.upcast::<EventTarget>().fire_event(atom!("fullscreenchange"));
// Step 7.7
promise.resolve_native(&());
}
}
pub struct ElementPerformFullscreenExit {
element: Trusted<Element>,
promise: TrustedPromise,
}
impl ElementPerformFullscreenExit {
pub fn new(element: Trusted<Element>, promise: TrustedPromise) -> Box<ElementPerformFullscreenExit> {
Box::new(ElementPerformFullscreenExit {
element: element,
promise: promise,
})
}
}
impl TaskOnce for ElementPerformFullscreenExit {
#[allow(unrooted_must_root)]
fn run_once(self) {
let element = self.element.root();
let document = document_from_node(element.r());
// TODO Step 9.1-5
// Step 9.6
element.set_fullscreen_state(false);
document.window().reflow(ReflowGoal::Full, ReflowReason::ElementStateChanged);
document.set_fullscreen_element(None);
// Step 9.8
document.upcast::<EventTarget>().fire_event(atom!("fullscreenchange"));
// Step 9.10
self.promise.root().resolve_native(&());
}
}
pub fn reflect_cross_origin_attribute(element: &Element) -> Option<DOMString> {
let attr = element.get_attribute(&ns!(), &local_name!("crossorigin"));
if let Some(mut val) = attr.map(|v| v.Value()) {
val.make_ascii_lowercase();
if val == "anonymous" || val == "use-credentials" {
return Some(val);
}
return Some(DOMString::from("anonymous"));
}
None
}
pub fn set_cross_origin_attribute(element: &Element, value: Option<DOMString>) {
match value {
Some(val) => element.set_string_attribute(&local_name!("crossorigin"), val),
None => {
element.remove_attribute(&ns!(), &local_name!("crossorigin"));
}
}
}
pub fn cors_setting_for_element(element: &Element) -> Option<CorsSettings> {
reflect_cross_origin_attribute(element).map_or(None, |attr| {
match &*attr {
"anonymous" => Some(CorsSettings::Anonymous),
"use-credentials" => Some(CorsSettings::UseCredentials),
_ => unreachable!()
}
})
}<|fim▁end|> | }
if ancestor.is_parent_of(node) { |
<|file_name|>ANTES01.java<|end_file_name|><|fim▁begin|>import processing.core.*;
import processing.data.*;
import processing.event.*;
import processing.opengl.*;
import ddf.minim.spi.*;
import ddf.minim.signals.*;
import ddf.minim.*;
import ddf.minim.analysis.*;
import ddf.minim.ugens.*;
import ddf.minim.effects.*;
import codeanticode.syphon.*;
import java.util.HashMap;
import java.util.ArrayList;
import java.io.File;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
public class ANTES01 extends PApplet {
//
//////////
// <|fim▁hole|>//
// V.00 paraelfestival"ANTES"
// feelGoodSoftwareporGuillermoGonz\u00e1lezIrigoyen
//
//////////
//
//VARIABLES DE CONFIGURACI\u00d3N
//Tama\u00f1o de la pantalla , proporciones y tweak
boolean pCompleta = false; //salidas a proyector 1024X768
boolean pCambiable= true;
int pPantalla = 4;
int pP,pW,pH;
//Syphon
SyphonServer server;
String nombreServer = "ANTES01";
//Audio
Minim minim;
AudioInput in0;
//
// ...
//LINEA
Linea lin,lin1;
int[] coloresAntes = { 0xff2693FF, 0xffEF3B63 , 0xffFFFFFB, 0xff000000};
int numColor = 1;
boolean hay;
int alfa = 255;
boolean moverL = false;
boolean moverH = false;
int xIL = 0;
int yIL = 10;
int intA = 50;
int sepLR = 5;
int anchoL = 0;
int anchoR = 0;
int anchoS = 1;
int distMov = 1;
//FONDO
boolean fondo = true;
boolean textura = true;
boolean sinCuadricula = true;
int R = 85;
int G = 85;
int B = 85;
int A = 10;
//CONTROLES
boolean sumar = true;
int paso = 2;
//##SETUP##
//
public void setup()
{
//CANVAS
pP = (pCompleta == true)? 1 : pPantalla;
size(displayWidth/pP, displayHeight/pP, P3D);
pW=width;pH=height;
frame.setResizable(pCambiable);
//SYPHON SERVER
server = new SyphonServer(this, nombreServer);
//AUDIO
minim = new Minim(this);
in0 = minim.getLineIn();
//
// ...
yIL = height/2;
lin = new Linea(xIL, yIL, coloresAntes[numColor], alfa);
lin1 = new Linea(xIL, yIL-50, coloresAntes[numColor+1], alfa);
}
//##DRAW##
//
public void draw()
{
pW=width;
pH=height;
if(fondo){ background(coloresAntes[2]); }
int normi;
pushMatrix();
for(int i = 0; i < pW; i++)
{
normi=i;
if(i>1024||i==1024){ normi = PApplet.parseInt(norm(i,0,1024)); }
lin.conectarHorizontal(i, normi, intA, sepLR, anchoL, anchoR, anchoS, coloresAntes[numColor], alfa);
}
if(moverL==true){ lin.moverVertical(moverL, distMov, moverH);
lin1.moverVertical(moverL, distMov, moverH); }
popMatrix();
//fondo
if(textura){ pushMatrix(); fondodePapel(R,G,B,A,sinCuadricula); popMatrix(); }
//SYPHON SERVER
server.sendScreen();
}
//
//##CONTROLES##
//
public void keyPressed()
{
char k = key;
switch(k)
{
////////////////////////////////////////////
////////////////////////////////////////////
//controles//
case '<':
sumar = !sumar;
print("sumar :",sumar,"\n");
print("paso :",paso,"\n");
print("___________________\n");
break;
case '0':
break;
case '1':
fondo=!fondo;
print("fondo :",fondo,"\n");
print("___________________\n");
break;
case '2':
sinCuadricula=!sinCuadricula;
print("sinCuadricula :",sinCuadricula,"\n");
print("___________________\n");
break;
case '3':
textura=!textura;
print("textura :",textura,"\n");
print("___________________\n");
break;
case 'z':
paso--;
paso = (paso>255)?255:paso;
paso = (paso<0)?0:paso;
print("paso :",paso,"\n");
print("___________________\n");
break;
case 'x':
paso++;
paso = (paso>255)?255:paso;
paso = (paso<0)?0:paso;
print("paso :",paso,"\n");
print("___________________\n");
break;
////////////////////////////////////////////
////////////////////////////////////////////
//fondo//
case 'q':
if(sumar==true)
{
R+=paso;
R = (R>255)?255:R;
R = (R<0)?0:R;
} else {
R-=paso;
R = (R>255)?255:R;
R = (R<0)?0:R;
}
print("Rojo :",R,"\n");
print("___________________\n");
break;
case 'w':
if(sumar==true)
{
G+=paso;
G = (G>255)?255:G;
G = (G<0)?0:G;
} else {
G-=paso;
G = (G>255)?255:G;
G = (G<0)?0:G;
}
print("Verde :",G,"\n");
print("___________________\n");
break;
case 'e':
if(sumar==true)
{
B+=paso;
B = (B>255)?255:B;
B = (B<0)?0:B;
} else {
B-=paso;
B = (B>255)?255:B;
B = (B<0)?0:B;
}
print("Azul :",B,"\n");
print("___________________\n");
break;
case 'a':
if(sumar==true)
{
A+=paso;
A = (A>255)?255:A;
A = (A<0)?0:A;
} else {
A-=paso;
A = (A>255)?255:A;
A = (A<0)?0:A;
}
print("Grano Papel :",A,"\n");
print("___________________\n");
break;
case 's':
break;
////////////////////////////////////////////
////////////////////////////////////////////
//Linea//
case 'r':
numColor+=1;
hay = (numColor > coloresAntes.length || numColor == coloresAntes.length)? false : true;
numColor = (hay)? numColor : 0;
print("numColor :",numColor,"\n");
print("___________________\n");
break;
case 't':
if(sumar==true)
{
anchoL+=paso;
anchoL = (anchoL>1000)?1000:anchoL;
anchoL = (anchoL<0)?0:anchoL;
} else {
anchoL-=paso;
anchoL = (anchoL>1000)?1000:anchoL;
anchoL = (anchoL<0)?0:anchoL;
}
print("Ancho canal izquierdo :",anchoL,"\n");
print("___________________\n");
break;
case 'y':
if(sumar==true)
{
anchoR+=paso;
anchoR = (anchoR>1000)?1000:anchoR;
anchoR = (anchoR<0)?0:anchoR;
} else {
anchoR-=paso;
anchoR = (anchoR>1000)?1000:anchoR;
anchoR = (anchoR<0)?0:anchoR;
}
print("Ancho canal derecho :",anchoR,"\n");
print("___________________\n");
break;
case 'f':
moverL = !moverL;
print("Mover Linea :",moverL,"\n");
print("___________________\n");
break;
case 'g':
moverH = !moverH;
print("Mover distancia horizontal :",moverH,"\n");
print("___________________\n");
break;
case 'h':
if(sumar==true)
{
sepLR+=paso;
sepLR = (anchoR>1000)?1000:sepLR;
sepLR = (anchoR<0)?0:sepLR;
} else {
sepLR-=paso;
sepLR = (anchoR>1000)?1000:sepLR;
sepLR = (anchoR<0)?10:anchoR;
}
print("Separaci\u00f3n canales :",sepLR,"\n");
print("___________________\n");
break;
case 'v':
if(sumar==true)
{
intA+=paso;
intA = (intA>1000)?1000:intA;
intA = (intA<0)?0:intA;
} else {
intA-=paso;
intA = (intA>1000)?1000:intA;
intA = (intA<0)?0:intA;
}
print("intencidad respuesta input :",intA,"\n");
print("___________________\n");
break;
case 'b':
if(sumar==true)
{
distMov+=paso;
distMov = (distMov>1000)?1000:distMov;
distMov = (distMov<0)?0:distMov;
} else {
distMov-=paso;
distMov = (distMov>1000)?1000:distMov;
distMov = (distMov<0)?0:distMov;
}
print("distMov :",distMov,"\n");
print("___________________\n");
break;
case 'n':
if(sumar==true)
{
anchoS+=paso;
anchoS = (anchoS>1000)?1000:anchoS;
anchoS = (anchoS<0)?0:anchoS;
} else {
anchoS-=paso;
anchoS = (anchoS>1000)?1000:anchoS;
anchoS = (anchoS<0)?0:anchoS;
}
print("distMov :",anchoS,"\n");
print("___________________\n");
break;
////////////////////////////////////////////
////////////////////////////////////////////
//RESETS 7 8 9//
case '9':
numColor = 1;
alfa = 255;
moverL = false;
moverH = false;
xIL = 0;
yIL = 10;
intA = 50;
sepLR = 5;
anchoL = 0;
anchoR = 0;
anchoS = 1;
distMov = 1;
fondo = true;
textura = true;
sinCuadricula = true;
R = 85;
G = 85;
B = 85;
A = 10;
break;
case '8':
numColor = 1;
alfa = 255;
moverL = false;
moverH = false;
xIL = 0;
yIL = 10;
intA = 50;
sepLR = 5;
anchoL = 0;
anchoR = 0;
anchoS = 1;
distMov = 1;
break;
case '7':
fondo = false;
textura = true;
sinCuadricula = true;
R = 85;
G = 85;
B = 85;
A = 10;
break;
//
//DEFAULT
default:
break;
}
}
//
//##FONDO
//
public void fondodePapel(int R, int G, int B, int A, boolean sinCuadricula)
{
if(sinCuadricula){ noStroke(); }
for (int i = 0; i<width; i+=2)
{
for (int j = 0; j<height; j+=2)
{
fill(random(R-10, R+10),random(G-10, G+10),random(B-10, B+10), random(A*2.5f,A*3));
rect(i, j, 2, 2);
}
}
for (int i = 0; i<30; i++)
{
fill(random(R/2, R+R/2), random(A*2.5f, A*3));
rect(random(0, width-2), random(0, height-2), random(1, 3), random(1, 3));
}
}
//
//##OVER##
//
public boolean sketchFullScreen() { return pCompleta; }
class Linea
{
int x, y, largo, colorLinea, a;
Linea(int X, int Y, int COLORLINEA, int A)
{
x=X;
y=Y;
colorLinea=COLORLINEA;
a=A;
}
public void conectarHorizontal(int I, int NORMI, int INTEN, int DISTI, int A1, int A2 , float GROSLIN, int COLORLINEA, int A)
{
stroke(COLORLINEA, A);
strokeWeight(GROSLIN);
line( y+in0.left.get(NORMI)*INTEN, x+I, y+A1+in0.left.get(NORMI)*INTEN, x+I+1);
line( y+DISTI+in0.right.get(NORMI)*INTEN, x+I, y+A2+DISTI+in0.right.get(NORMI)*INTEN, x+I+1);
}
public void conectarVertical(int I, int NORMI, int INTEN, int DISTI, int A1, int A2 , float GROSLIN, int COLORLINEA, int A)
{
stroke(COLORLINEA, A);
strokeWeight(GROSLIN);
line( y+in0.left.get(NORMI)*INTEN, x+I, y+A1+in0.left.get(NORMI)*INTEN, x+I+1);
line( y+DISTI+in0.right.get(NORMI)*INTEN, x+I+1, y+A2+DISTI+in0.right.get(NORMI)*INTEN, x+I);
}
public void moverVertical(boolean MOVER, int CUANTO, boolean WIDTH)
{
if(MOVER == true)
{
y+=CUANTO;
int distancia = (WIDTH == true) ? width : height;
if(y>distancia)
{
y=0;
}
}
}
}
static public void main(String[] passedArgs) {
String[] appletArgs = new String[] { "ANTES01" };
if (passedArgs != null) {
PApplet.main(concat(appletArgs, passedArgs));
} else {
PApplet.main(appletArgs);
}
}
}<|fim▁end|> | // WRAP
// Syphon/minim/fun000 |
<|file_name|>setup.py<|end_file_name|><|fim▁begin|># Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# =============================================================================
"""Cloud TPU profiler package."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from setuptools import setup
_VERSION = '1.7.0'
CONSOLE_SCRIPTS = [
'capture_tpu_profile=cloud_tpu_profiler.main:run_main',
]
setup(
name='cloud_tpu_profiler',
version=_VERSION.replace('-', ''),
description='Trace and profile Cloud TPU performance',
long_description='Tools for capture TPU profile',
url='https://www.tensorflow.org/tfrc/',
author='Google Inc.',
author_email='[email protected]',
packages=['cloud_tpu_profiler'],
package_data={
'cloud_tpu_profiler': ['data/*'],
},
entry_points={
'console_scripts': CONSOLE_SCRIPTS,
},
classifiers=[<|fim▁hole|> # 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: Education',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Scientific/Engineering',
'Topic :: Scientific/Engineering :: Mathematics',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules',
],
license='Apache 2.0',
keywords='tensorflow performance tpu',
)<|fim▁end|> | # How mature is this project? Common values are |
<|file_name|>syst_rvr.rs<|end_file_name|><|fim▁begin|>#[doc = "Register `SYST_RVR` reader"]
pub struct R(crate::R<SYST_RVR_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<SYST_RVR_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<SYST_RVR_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<SYST_RVR_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `SYST_RVR` writer"]
pub struct W(crate::W<SYST_RVR_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<SYST_RVR_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<SYST_RVR_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<SYST_RVR_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `RELOAD` reader - Reload Value"]
pub struct RELOAD_R(crate::FieldReader<u32, u32>);
impl RELOAD_R {
pub(crate) fn new(bits: u32) -> Self {
RELOAD_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for RELOAD_R {
type Target = crate::FieldReader<u32, u32>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `RELOAD` writer - Reload Value"]
pub struct RELOAD_W<'a> {
w: &'a mut W,
}
impl<'a> RELOAD_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u32) -> &'a mut W {
self.w.bits = (self.w.bits & !0x00ff_ffff) | (value as u32 & 0x00ff_ffff);
self.w
}
}
impl R {
#[doc = "Bits 0:23 - Reload Value"]
#[inline(always)]
pub fn reload(&self) -> RELOAD_R {
RELOAD_R::new((self.bits & 0x00ff_ffff) as u32)
}
}
impl W {<|fim▁hole|> #[doc = "Bits 0:23 - Reload Value"]
#[inline(always)]
pub fn reload(&mut self) -> RELOAD_W {
RELOAD_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "SysTick Reload Value Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [syst_rvr](index.html) module"]
pub struct SYST_RVR_SPEC;
impl crate::RegisterSpec for SYST_RVR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [syst_rvr::R](R) reader structure"]
impl crate::Readable for SYST_RVR_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [syst_rvr::W](W) writer structure"]
impl crate::Writable for SYST_RVR_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets SYST_RVR to value 0"]
impl crate::Resettable for SYST_RVR_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}<|fim▁end|> | |
<|file_name|>sequences.py<|end_file_name|><|fim▁begin|># encoding: utf-8
" This sub-module provides 'sequence awareness' for blessed."
__author__ = 'Jeff Quast <[email protected]>'
__license__ = 'MIT'
__all__ = ('init_sequence_patterns', 'Sequence', 'SequenceTextWrapper',)
# built-ins
import functools
import textwrap
import warnings
import math
import sys
import re
# local
from ._binterms import binary_terminals as _BINTERM_UNSUPPORTED
# 3rd-party
import wcwidth # https://github.com/jquast/wcwidth
_BINTERM_UNSUPPORTED_MSG = (
u"Terminal kind {0!r} contains binary-packed capabilities, blessed "
u"is likely to fail to measure the length of its sequences.")
if sys.version_info[0] == 3:
text_type = str
else:
text_type = unicode # noqa
def _merge_sequences(inp):
"""Merge a list of input sequence patterns for use in a regular expression.
Order by lengthyness (full sequence set precedent over subset),
and exclude any empty (u'') sequences.
"""
return sorted(list(filter(None, inp)), key=len, reverse=True)
def _build_numeric_capability(term, cap, optional=False,
base_num=99, nparams=1):
""" Build regexp from capabilities having matching numeric
parameter contained within termcap value: n->(\d+).
"""
_cap = getattr(term, cap)
opt = '?' if optional else ''
if _cap:
args = (base_num,) * nparams
cap_re = re.escape(_cap(*args))
for num in range(base_num - 1, base_num + 2):
# search for matching ascii, n-1 through n+1
if str(num) in cap_re:
# modify & return n to matching digit expression
cap_re = cap_re.replace(str(num), r'(\d+)%s' % (opt,))
return cap_re
warnings.warn('Unknown parameter in %r (%r, %r)' % (cap, _cap, cap_re))
return None # no such capability
def _build_any_numeric_capability(term, cap, num=99, nparams=1):
""" Build regexp from capabilities having *any* digit parameters
(substitute matching \d with pattern \d and return).
"""
_cap = getattr(term, cap)
if _cap:
cap_re = re.escape(_cap(*((num,) * nparams)))
cap_re = re.sub('(\d+)', r'(\d+)', cap_re)
if r'(\d+)' in cap_re:
return cap_re
warnings.warn('Missing numerics in %r, %r' % (cap, cap_re))
return None # no such capability
def get_movement_sequence_patterns(term):
""" Build and return set of regexp for capabilities of ``term`` known
to cause movement.
"""
bnc = functools.partial(_build_numeric_capability, term)
return set([
# carriage_return
re.escape(term.cr),
# column_address: Horizontal position, absolute
bnc(cap='hpa'),
# row_address: Vertical position #1 absolute
bnc(cap='vpa'),
# cursor_address: Move to row #1 columns #2
bnc(cap='cup', nparams=2),
# cursor_down: Down one line
re.escape(term.cud1),
# cursor_home: Home cursor (if no cup)
re.escape(term.home),
# cursor_left: Move left one space
re.escape(term.cub1),
# cursor_right: Non-destructive space (move right one space)
re.escape(term.cuf1),
# cursor_up: Up one line
re.escape(term.cuu1),
# param_down_cursor: Down #1 lines
bnc(cap='cud', optional=True),
# restore_cursor: Restore cursor to position of last save_cursor
re.escape(term.rc),
# clear_screen: clear screen and home cursor
re.escape(term.clear),
# enter/exit_fullscreen: switch to alternate screen buffer
re.escape(term.enter_fullscreen),
re.escape(term.exit_fullscreen),
# forward cursor
term._cuf,
# backward cursor
term._cub,
])
def get_wontmove_sequence_patterns(term):
""" Build and return set of regexp for capabilities of ``term`` known
not to cause any movement.
"""
bnc = functools.partial(_build_numeric_capability, term)
bna = functools.partial(_build_any_numeric_capability, term)
return list([
# print_screen: Print contents of screen
re.escape(term.mc0),
# prtr_off: Turn off printer
re.escape(term.mc4),
# prtr_on: Turn on printer
re.escape(term.mc5),
# save_cursor: Save current cursor position (P)
re.escape(term.sc),
# set_tab: Set a tab in every row, current columns
re.escape(term.hts),
# enter_bold_mode: Turn on bold (extra bright) mode
re.escape(term.bold),
# enter_standout_mode
re.escape(term.standout),
# enter_subscript_mode
re.escape(term.subscript),
# enter_superscript_mode
re.escape(term.superscript),
# enter_underline_mode: Begin underline mode
re.escape(term.underline),
# enter_blink_mode: Turn on blinking
re.escape(term.blink),
# enter_dim_mode: Turn on half-bright mode
re.escape(term.dim),
# cursor_invisible: Make cursor invisible
re.escape(term.civis),
# cursor_visible: Make cursor very visible
re.escape(term.cvvis),
# cursor_normal: Make cursor appear normal (undo civis/cvvis)
re.escape(term.cnorm),
# clear_all_tabs: Clear all tab stops
re.escape(term.tbc),
# change_scroll_region: Change region to line #1 to line #2
bnc(cap='csr', nparams=2),
# clr_bol: Clear to beginning of line
re.escape(term.el1),
# clr_eol: Clear to end of line
re.escape(term.el),
# clr_eos: Clear to end of screen
re.escape(term.clear_eos),
# delete_character: Delete character
re.escape(term.dch1),
# delete_line: Delete line (P*)
re.escape(term.dl1),
# erase_chars: Erase #1 characters
bnc(cap='ech'),
# insert_line: Insert line (P*)
re.escape(term.il1),
# parm_dch: Delete #1 characters
bnc(cap='dch'),
# parm_delete_line: Delete #1 lines
bnc(cap='dl'),
# exit_alt_charset_mode: End alternate character set (P)
re.escape(term.rmacs),
# exit_am_mode: Turn off automatic margins
re.escape(term.rmam),
# exit_attribute_mode: Turn off all attributes
re.escape(term.sgr0),
# exit_ca_mode: Strings to end programs using cup
re.escape(term.rmcup),
# exit_insert_mode: Exit insert mode
re.escape(term.rmir),
# exit_standout_mode: Exit standout mode
re.escape(term.rmso),
# exit_underline_mode: Exit underline mode
re.escape(term.rmul),
# flash_hook: Flash switch hook
re.escape(term.hook),
# flash_screen: Visible bell (may not move cursor)
re.escape(term.flash),
# keypad_local: Leave 'keyboard_transmit' mode
re.escape(term.rmkx),
# keypad_xmit: Enter 'keyboard_transmit' mode
re.escape(term.smkx),
# meta_off: Turn off meta mode
re.escape(term.rmm),
# meta_on: Turn on meta mode (8th-bit on)
re.escape(term.smm),
# orig_pair: Set default pair to its original value
re.escape(term.op),
# parm_ich: Insert #1 characters
bnc(cap='ich'),
# parm_index: Scroll forward #1
bnc(cap='indn'),
# parm_insert_line: Insert #1 lines
bnc(cap='il'),
# erase_chars: Erase #1 characters
bnc(cap='ech'),
# parm_rindex: Scroll back #1 lines
bnc(cap='rin'),
# parm_up_cursor: Up #1 lines
bnc(cap='cuu'),
# scroll_forward: Scroll text up (P)
re.escape(term.ind),
# scroll_reverse: Scroll text down (P)
re.escape(term.rev),
# tab: Tab to next 8-space hardware tab stop
re.escape(term.ht),
# set_a_background: Set background color to #1, using ANSI escape
bna(cap='setab', num=1),
bna(cap='setab', num=(term.number_of_colors - 1)),
# set_a_foreground: Set foreground color to #1, using ANSI escape
bna(cap='setaf', num=1),
bna(cap='setaf', num=(term.number_of_colors - 1)),
] + [
# set_attributes: Define video attributes #1-#9 (PG9)
# ( not *exactly* legal, being extra forgiving. )
bna(cap='sgr', nparams=_num) for _num in range(1, 10)
# reset_{1,2,3}string: Reset string
] + list(map(re.escape, (term.r1, term.r2, term.r3,))))
def init_sequence_patterns(term):
"""Given a Terminal instance, ``term``, this function processes
and parses several known terminal capabilities, and builds and
returns a dictionary database of regular expressions, which may
be re-attached to the terminal by attributes of the same key-name:
``_re_will_move``
any sequence matching this pattern will cause the terminal
cursor to move (such as *term.home*).
``_re_wont_move``
any sequence matching this pattern will not cause the cursor
to move (such as *term.bold*).
``_re_cuf``
regular expression that matches term.cuf(N) (move N characters forward),
or None if temrinal is without cuf sequence.
``_cuf1``
*term.cuf1* sequence (cursor forward 1 character) as a static value.
``_re_cub``
regular expression that matches term.cub(N) (move N characters backward),
or None if terminal is without cub sequence.
``_cub1``
*term.cuf1* sequence (cursor backward 1 character) as a static value.
These attributes make it possible to perform introspection on strings
containing sequences generated by this terminal, to determine the
printable length of a string.
"""
if term.kind in _BINTERM_UNSUPPORTED:
warnings.warn(_BINTERM_UNSUPPORTED_MSG.format(term.kind))
# Build will_move, a list of terminal capabilities that have
# indeterminate effects on the terminal cursor position.
_will_move = set()
if term.does_styling:
_will_move = _merge_sequences(get_movement_sequence_patterns(term))
# Build wont_move, a list of terminal capabilities that mainly affect
# video attributes, for use with measure_length().
_wont_move = set()
if term.does_styling:
_wont_move = _merge_sequences(get_wontmove_sequence_patterns(term))
_wont_move += [
# some last-ditch match efforts; well, xterm and aixterm is going
# to throw \x1b(B and other oddities all around, so, when given
# input such as ansi art (see test using wall.ans), and well,
# theres no reason a vt220 terminal shouldn't be able to recognize
# blue_on_red, even if it didn't cause it to be generated. these
# are final "ok, i will match this, anyway"
re.escape(u'\x1b') + r'\[(\d+)m',
re.escape(u'\x1b') + r'\[(\d+)\;(\d+)m',
re.escape(u'\x1b') + r'\[(\d+)\;(\d+)\;(\d+)m',
re.escape(u'\x1b') + r'\[(\d+)\;(\d+)\;(\d+)\;(\d+)m',
re.escape(u'\x1b(B'),
]
# compile as regular expressions, OR'd.
_re_will_move = re.compile('(%s)' % ('|'.join(_will_move)))
_re_wont_move = re.compile('(%s)' % ('|'.join(_wont_move)))
# static pattern matching for horizontal_distance(ucs, term)
bnc = functools.partial(_build_numeric_capability, term)
# parm_right_cursor: Move #1 characters to the right
_cuf = bnc(cap='cuf', optional=True)
_re_cuf = re.compile(_cuf) if _cuf else None
# cursor_right: Non-destructive space (move right one space)
_cuf1 = term.cuf1
# parm_left_cursor: Move #1 characters to the left
_cub = bnc(cap='cub', optional=True)
_re_cub = re.compile(_cub) if _cub else None
# cursor_left: Move left one space
_cub1 = term.cub1
return {'_re_will_move': _re_will_move,<|fim▁hole|> '_cub1': _cub1, }
class SequenceTextWrapper(textwrap.TextWrapper):
def __init__(self, width, term, **kwargs):
self.term = term
textwrap.TextWrapper.__init__(self, width, **kwargs)
def _wrap_chunks(self, chunks):
"""
escape-sequence aware variant of _wrap_chunks. Though
movement sequences, such as term.left() are certainly not
honored, sequences such as term.bold() are, and are not
broken mid-sequence.
"""
lines = []
if self.width <= 0 or not isinstance(self.width, int):
raise ValueError("invalid width %r(%s) (must be integer > 0)" % (
self.width, type(self.width)))
term = self.term
drop_whitespace = not hasattr(self, 'drop_whitespace'
) or self.drop_whitespace
chunks.reverse()
while chunks:
cur_line = []
cur_len = 0
if lines:
indent = self.subsequent_indent
else:
indent = self.initial_indent
width = self.width - len(indent)
if drop_whitespace and (
Sequence(chunks[-1], term).strip() == '' and lines):
del chunks[-1]
while chunks:
chunk_len = Sequence(chunks[-1], term).length()
if cur_len + chunk_len <= width:
cur_line.append(chunks.pop())
cur_len += chunk_len
else:
break
if chunks and Sequence(chunks[-1], term).length() > width:
self._handle_long_word(chunks, cur_line, cur_len, width)
if drop_whitespace and (
cur_line and Sequence(cur_line[-1], term).strip() == ''):
del cur_line[-1]
if cur_line:
lines.append(indent + u''.join(cur_line))
return lines
def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):
"""_handle_long_word(chunks : [string],
cur_line : [string],
cur_len : int, width : int)
Handle a chunk of text (most likely a word, not whitespace) that
is too long to fit in any line.
"""
# Figure out when indent is larger than the specified width, and make
# sure at least one character is stripped off on every pass
if width < 1:
space_left = 1
else:
space_left = width - cur_len
# If we're allowed to break long words, then do so: put as much
# of the next chunk onto the current line as will fit.
if self.break_long_words:
term = self.term
chunk = reversed_chunks[-1]
nxt = 0
for idx in range(0, len(chunk)):
if idx == nxt:
# at sequence, point beyond it,
nxt = idx + measure_length(chunk[idx:], term)
if nxt <= idx:
# point beyond next sequence, if any,
# otherwise point to next character
nxt = idx + measure_length(chunk[idx:], term) + 1
if Sequence(chunk[:nxt], term).length() > space_left:
break
else:
# our text ends with a sequence, such as in text
# u'!\x1b(B\x1b[m', set index at at end (nxt)
idx = nxt
cur_line.append(chunk[:idx])
reversed_chunks[-1] = chunk[idx:]
# Otherwise, we have to preserve the long word intact. Only add
# it to the current line if there's nothing already there --
# that minimizes how much we violate the width constraint.
elif not cur_line:
cur_line.append(reversed_chunks.pop())
# If we're not allowed to break long words, and there's already
# text on the current line, do nothing. Next time through the
# main loop of _wrap_chunks(), we'll wind up here again, but
# cur_len will be zero, so the next line will be entirely
# devoted to the long word that we can't handle right now.
SequenceTextWrapper.__doc__ = textwrap.TextWrapper.__doc__
class Sequence(text_type):
"""
This unicode-derived class understands the effect of escape sequences
of printable length, allowing a properly implemented .rjust(), .ljust(),
.center(), and .len()
"""
def __new__(cls, sequence_text, term):
"""Sequence(sequence_text, term) -> unicode object
:arg sequence_text: A string containing sequences.
:arg term: Terminal instance this string was created with.
"""
new = text_type.__new__(cls, sequence_text)
new._term = term
return new
def ljust(self, width, fillchar=u' '):
"""S.ljust(width, fillchar) -> unicode
Returns string derived from unicode string ``S``, left-adjusted
by trailing whitespace padding ``fillchar``."""
rightside = fillchar * int((max(0.0, float(width - self.length())))
/ float(len(fillchar)))
return u''.join((self, rightside))
def rjust(self, width, fillchar=u' '):
"""S.rjust(width, fillchar=u'') -> unicode
Returns string derived from unicode string ``S``, right-adjusted
by leading whitespace padding ``fillchar``."""
leftside = fillchar * int((max(0.0, float(width - self.length())))
/ float(len(fillchar)))
return u''.join((leftside, self))
def center(self, width, fillchar=u' '):
"""S.center(width, fillchar=u'') -> unicode
Returns string derived from unicode string ``S``, centered
and surrounded with whitespace padding ``fillchar``."""
split = max(0.0, float(width) - self.length()) / 2
leftside = fillchar * int((max(0.0, math.floor(split)))
/ float(len(fillchar)))
rightside = fillchar * int((max(0.0, math.ceil(split)))
/ float(len(fillchar)))
return u''.join((leftside, self, rightside))
def length(self):
"""S.length() -> int
Returns printable length of unicode string ``S`` that may contain
terminal sequences.
Although accounted for, strings containing sequences such as
``term.clear`` will not give accurate returns, it is not
considered lengthy (a length of 0). Combining characters,
are also not considered lengthy.
Strings containing ``term.left`` or ``\b`` will cause "overstrike",
but a length less than 0 is not ever returned. So ``_\b+`` is a
length of 1 (``+``), but ``\b`` is simply a length of 0.
Some characters may consume more than one cell, mainly those CJK
Unified Ideographs (Chinese, Japanese, Korean) defined by Unicode
as half or full-width characters.
For example:
>>> from blessed import Terminal
>>> from blessed.sequences import Sequence
>>> term = Terminal()
>>> Sequence(term.clear + term.red(u'コンニチハ')).length()
5
"""
# because combining characters may return -1, "clip" their length to 0.
clip = functools.partial(max, 0)
return sum(clip(wcwidth.wcwidth(w_char))
for w_char in self.strip_seqs())
def strip(self, chars=None):
"""S.strip([chars]) -> unicode
Return a copy of the string S with terminal sequences removed, and
leading and trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
"""
return self.strip_seqs().strip(chars)
def lstrip(self, chars=None):
"""S.lstrip([chars]) -> unicode
Return a copy of the string S with terminal sequences and leading
whitespace removed.
If chars is given and not None, remove characters in chars instead.
"""
return self.strip_seqs().lstrip(chars)
def rstrip(self, chars=None):
"""S.rstrip([chars]) -> unicode
Return a copy of the string S with terminal sequences and trailing
whitespace removed.
If chars is given and not None, remove characters in chars instead.
"""
return self.strip_seqs().rstrip(chars)
def strip_seqs(self):
"""S.strip_seqs() -> unicode
Return a string without sequences for a string that contains
sequences for the Terminal with which they were created.
Where sequence ``move_right(n)`` is detected, it is replaced with
``n * u' '``, and where ``move_left()`` or ``\\b`` is detected,
those last-most characters are destroyed.
All other sequences are simply removed. An example,
>>> from blessed import Terminal
>>> from blessed.sequences import Sequence
>>> term = Terminal()
>>> Sequence(term.clear + term.red(u'test')).strip_seqs()
u'test'
"""
# nxt: points to first character beyond current escape sequence.
# width: currently estimated display length.
input = self.padd()
outp = u''
nxt = 0
for idx in range(0, len(input)):
if idx == nxt:
# at sequence, point beyond it,
nxt = idx + measure_length(input[idx:], self._term)
if nxt <= idx:
# append non-sequence to outp,
outp += input[idx]
# point beyond next sequence, if any,
# otherwise point to next character
nxt = idx + measure_length(input[idx:], self._term) + 1
return outp
def padd(self):
"""S.padd() -> unicode
Make non-destructive space or backspace into destructive ones.
Where sequence ``move_right(n)`` is detected, it is replaced with
``n * u' '``. Where sequence ``move_left(n)`` or ``\\b`` is
detected, those last-most characters are destroyed.
"""
outp = u''
nxt = 0
for idx in range(0, text_type.__len__(self)):
width = horizontal_distance(self[idx:], self._term)
if width != 0:
nxt = idx + measure_length(self[idx:], self._term)
if width > 0:
outp += u' ' * width
elif width < 0:
outp = outp[:width]
if nxt <= idx:
outp += self[idx]
nxt = idx + 1
return outp
def measure_length(ucs, term):
"""measure_length(S, term) -> int
Returns non-zero for string ``S`` that begins with a terminal sequence,
that is: the width of the first unprintable sequence found in S. For use
as a *next* pointer to skip past sequences. If string ``S`` is not a
sequence, 0 is returned.
A sequence may be a typical terminal sequence beginning with Escape
(``\x1b``), especially a Control Sequence Initiator (``CSI``, ``\x1b[``,
...), or those of ``\a``, ``\b``, ``\r``, ``\n``, ``\xe0`` (shift in),
``\x0f`` (shift out). They do not necessarily have to begin with CSI, they
need only match the capabilities of attributes ``_re_will_move`` and
``_re_wont_move`` of terminal ``term``.
"""
# simple terminal control characters,
ctrl_seqs = u'\a\b\r\n\x0e\x0f'
if any([ucs.startswith(_ch) for _ch in ctrl_seqs]):
return 1
# known multibyte sequences,
matching_seq = term and (
term._re_will_move.match(ucs) or
term._re_wont_move.match(ucs) or
term._re_cub and term._re_cub.match(ucs) or
term._re_cuf and term._re_cuf.match(ucs)
)
if matching_seq:
start, end = matching_seq.span()
return end
# none found, must be printable!
return 0
def termcap_distance(ucs, cap, unit, term):
"""termcap_distance(S, cap, unit, term) -> int
Match horizontal distance by simple ``cap`` capability name, ``cub1`` or
``cuf1``, with string matching the sequences identified by Terminal
instance ``term`` and a distance of ``unit`` *1* or *-1*, for right and
left, respectively.
Otherwise, by regular expression (using dynamic regular expressions built
using ``cub(n)`` and ``cuf(n)``. Failing that, any of the standard SGR
sequences (``\033[C``, ``\033[D``, ``\033[nC``, ``\033[nD``).
Returns 0 if unmatched.
"""
assert cap in ('cuf', 'cub')
# match cub1(left), cuf1(right)
one = getattr(term, '_%s1' % (cap,))
if one and ucs.startswith(one):
return unit
# match cub(n), cuf(n) using regular expressions
re_pattern = getattr(term, '_re_%s' % (cap,))
_dist = re_pattern and re_pattern.match(ucs)
if _dist:
return unit * int(_dist.group(1))
return 0
def horizontal_distance(ucs, term):
"""horizontal_distance(S, term) -> int
Returns Integer ``<n>`` in SGR sequence of form ``<ESC>[<n>C``
(T.move_right(n)), or ``-(n)`` in sequence of form ``<ESC>[<n>D``
(T.move_left(n)). Returns -1 for backspace (0x08), Otherwise 0.
Tabstop (``\t``) cannot be correctly calculated, as the relative column
position cannot be determined: 8 is always (and, incorrectly) returned.
"""
if ucs.startswith('\b'):
return -1
elif ucs.startswith('\t'):
# As best as I can prove it, a tabstop is always 8 by default.
# Though, given that blessings is:
#
# 1. unaware of the output device's current cursor position, and
# 2. unaware of the location the callee may chose to output any
# given string,
#
# It is not possible to determine how many cells any particular
# \t would consume on the output device!
return 8
return (termcap_distance(ucs, 'cub', -1, term) or
termcap_distance(ucs, 'cuf', 1, term) or
0)<|fim▁end|> | '_re_wont_move': _re_wont_move,
'_re_cuf': _re_cuf,
'_re_cub': _re_cub,
'_cuf1': _cuf1, |
<|file_name|>view3_test.js<|end_file_name|><|fim▁begin|>'use strict';
describe('myApp.view3 module', function() {
var scope, view3Ctrl;
beforeEach(module('myApp.view3'));
beforeEach(module('matchingServices'));
beforeEach(inject(function ($controller, $rootScope) { // inject $rootScope
scope = $rootScope.$new();
view3Ctrl = $controller('View3Ctrl',{$scope : scope});
}));
describe('view3 controller', function(){
it('should ....', function() {
//spec body<|fim▁hole|> });
});<|fim▁end|> | expect(view3Ctrl).toBeDefined();
});
|
<|file_name|>app.py<|end_file_name|><|fim▁begin|>import os
from flask import Flask, request, render_template
from flask.ext.sqlalchemy import SQLAlchemy
<|fim▁hole|>
app = Flask(__name__)
app.debug = True
app.threaded = True
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL', 'sqlite:////tmp/test.db')
db = SQLAlchemy(app)
class Email(db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(255))
@app.route('/', methods=['GET', 'POST'])
def main():
if request.method == 'POST':
email = Email(email=request.post('email'))
db.session.add(email)
db.session.commit()
return 'ok'
return render_template('index.html')
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)<|fim▁end|> | |
<|file_name|>principe_de_superposition_lineaire.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import os
"""
Illustration d'un exercice de TD visant à montrer l'évolution temporelle de la
densité de probabilité pour la superposition équiprobable d'un état n=1 et
d'un état n quelconque (à fixer) pour le puits quantique infini.
Par souci de simplicité, on se débrouille pour que E_1/hbar = 1
"""
import numpy as np # Boîte à outils numériques
import matplotlib.pyplot as plt # Boîte à outils graphiques
from matplotlib import animation # Pour l'animation progressive
# Second état n observer (à fixer)
n = 2
# On met tous les paramètres à 1 (ou presque)
t0 = 0<|fim▁hole|>dt = 0.1
L = 1
hbar = 1
h = hbar * 2 * np.pi
m = (2 * np.pi)**2
E1 = h**2 / (8 * m * L**2)
En = n * E1
x = np.linspace(0, L, 1000)
def psi1(x, t):
return np.sin(np.pi * x / L) * np.exp(1j * E1 * t / hbar)
def psin(x, t):
return np.sin(n * np.pi * x / L) * np.exp(1j * En * t / hbar)
def psi(x, t):
return 1 / L**0.5 * (psi1(x, t) + psin(x, t))
fig = plt.figure()
line, = plt.plot(x, abs(psi(x, t0))**2)
plt.title('$t={}$'.format(t0))
plt.ylabel('$|\psi(x,t)|^2$')
plt.xlabel('$x$')
plt.plot(x, abs(psi1(x, t0))**2, '--', label='$|\psi_1|^2$')
plt.plot(x, abs(psin(x, t0))**2, '--', label='$|\psi_{}|^2$'.format(n))
plt.legend()
def init():
pass
def animate(i):
t = i * dt + t0
line.set_ydata(abs(psi(x, t))**2)
plt.title('$t={}$'.format(t))
anim = animation.FuncAnimation(fig, animate, frames=1000, interval=20)
plt.show()
os.system("pause")<|fim▁end|> | |
<|file_name|>RedisFxApp.java<|end_file_name|><|fim▁begin|>package com.hyd.redisfx;
import com.hyd.fx.Fxml;
import com.hyd.fx.app.AppLogo;
import com.hyd.fx.app.AppPrimaryStage;
import com.hyd.redisfx.fx.BackgroundExecutor;
import com.hyd.redisfx.i18n.I18n;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class RedisFxApp extends Application {<|fim▁hole|> public static void main(String[] args) {
launch(RedisFxApp.class);
}
@Override
public void start(Stage primaryStage) throws Exception {
AppPrimaryStage.setPrimaryStage(primaryStage);
AppLogo.setStageLogo(primaryStage);
primaryStage.setTitle("RedisFX");
primaryStage.setScene(new Scene(getRoot()));
primaryStage.setOnCloseRequest(event -> BackgroundExecutor.shutdown());
primaryStage.show();
}
public Parent getRoot() throws Exception {
FXMLLoader fxmlLoader = Fxml.load("/fxml/Main.fxml", I18n.UI_MAIN_BUNDLE);
return fxmlLoader.<BorderPane>getRoot();
}
}<|fim▁end|> | |
<|file_name|>stitching.js<|end_file_name|><|fim▁begin|>var taxi = require('..');
var chromedriver = require('chromedriver');
var fs = require('fs');
var user = process.env.SAUCE_USERNAME;
var accessKey = process.env.SAUCE_ACCESS_KEY;
var sauceLabsUrl = "http://" + user + ":" + accessKey + "@ondemand.saucelabs.com/wd/hub";
var tests = [
{ url:'http://localhost:9515/', capabilities: { browserName:'chrome' }, beforeFn: function () { chromedriver.start(); }, afterFn: function () { chromedriver.stop() } },
{ url:'http://localhost:9517/', capabilities: { browserName:'phantomjs', browserVersion:'1.9.8' } },
{ url:'http://localhost:4444/wd/hub', capabilities: { browserName:'firefox' } },
{ url:'http://makingshaking.corp.ne1.yahoo.com:4444', capabilities: { browserName:'phantomjs', browserVersion: '2.0.0 dev' } },
{ url:sauceLabsUrl, capabilities: { browserName:'chrome', version:'41.0', platform:'Windows 8.1' } },
{ url:sauceLabsUrl, capabilities: { browserName:'firefox', version:'37.0', platform:'Windows 8.1' } },
{ url:sauceLabsUrl, capabilities: { browserName:'internet explorer', version:'11.0', platform:'Windows 8.1' } },
{ url:sauceLabsUrl, capabilities: { browserName:'internet explorer', version:'10.0', platform:'Windows 8' } },
{ url:sauceLabsUrl, capabilities: { browserName:'internet explorer', version:'9.0', platform:'Windows 7' } },
{ url:sauceLabsUrl, capabilities: { browserName:'safari', version:'5.1', platform:'Windows 7' } },
{ url:sauceLabsUrl, capabilities: { browserName:'safari', version:'8.0', platform:'OS X 10.10' } },
{ url:sauceLabsUrl, capabilities: { browserName:'iphone', version:'8.2', platform: 'OS X 10.10', deviceName:'iPad Simulator', "device-orientation":'portrait' } },
{ url:sauceLabsUrl, capabilities: { browserName:'iphone', version:'8.2', platform: 'OS X 10.10', deviceName:'iPad Simulator', "device-orientation":'landscape' } },
{ url:sauceLabsUrl, capabilities: { browserName:'iphone', version:'8.2', platform: 'OS X 10.10', deviceName:'iPhone Simulator', "device-orientation":'portrait' } },
{ url:sauceLabsUrl, capabilities: { browserName:'iphone', version:'8.2', platform: 'OS X 10.10', deviceName:'iPhone Simulator', "device-orientation":'landscape' } }
];
tests.forEach(function (test) {
// Do we need to run something before the test-run?
if (test.beforeFn) {
test.beforeFn();
}
try {
var driver = taxi(test.url, test.capabilities, {mode: taxi.Driver.MODE_SYNC, debug: true, httpDebug: true});
var browser = driver.browser();
var activeWindow = browser.activeWindow();
// Navigate to Yahoo
activeWindow.navigator().setUrl('http://www.yahoo.com');
<|fim▁hole|> var browserId = (driver.deviceName() != '' ? driver.deviceName() : driver.browserName()) + " " + driver.deviceOrientation() + " " + driver.browserVersion() + " " + driver.platform();
// Write screenshot to a file
fs.writeFileSync(__dirname + '/' + browserId.trim() + '.png', activeWindow.documentScreenshot({
eachFn: function (index) {
// Remove the header when the second screenshot is reached.
// The header keeps following the scrolling position.
// So, we want to turn it off here.
if (index >= 1 && document.getElementById('masthead')) {
document.getElementById('masthead').style.display = 'none';
}
},
completeFn: function () {
// When it has a "masthead", then display it again
if (document.getElementById('masthead')) {
document.getElementById('masthead').style.display = '';
}
},
// Here is a list of areas that should be blocked-out
blockOuts: [
// Block-out all text-boxes
'input',
// Custom block-out at static location with custom color
{x:60, y: 50, width: 200, height: 200, color:{red:255,green:0,blue:128}}
]
// The element cannot be found in mobile browsers since they have a different layout
//, activeWindow.getElement('.footer-section')]
}));
} catch (err) {
console.error(err.stack);
} finally {
driver.dispose();
// Do we need to run something after the test-run?
if (test.afterFn) {
test.afterFn();
}
}
});<|fim▁end|> | |
<|file_name|>helpers.rs<|end_file_name|><|fim▁begin|>#[derive(Debug)]
pub enum Entry {
// either a unique page and its link data
Page {
title: String,
children: Vec<u32>,
parents: Vec<u32>,
},
// or the redirect page and its address
// these will eventually be taken out of db::entries
Redirect {
title: String,
target: Option<u32>,
}
}
//what phase the database is in
//TODO should I get rid of the numbers? They don't matter except that without
// them it might not be clear that the order of the values is what determines
// their inequality; here concrete values make it clearer
#[derive(PartialEq, PartialOrd, Debug)]
pub enum State {
Begin = 0,
AddPages = 1,
AddRedirects = 2,
TidyEntries = 3,
AddLinks = 4,<|fim▁hole|><|fim▁end|> | Done = 5,
} |
<|file_name|>ajax.py<|end_file_name|><|fim▁begin|>from django.utils import simplejson
from dajaxice.decorators import dajaxice_register
from django.utils.translation import ugettext as _
from django.template.loader import render_to_string
from dajax.core import Dajax
from django.db import transaction
from darkoob.book.models import Book, Review
@dajaxice_register(method='POST')
@transaction.commit_manually
def rate(request, rate, book_id):
done = False
book = ''
try:
book = Book.objects.get(id = book_id)
book.rating.add(score=rate, user=request.user, ip_address=request.META['REMOTE_ADDR'])
except:
errors.append('An error occoured in record in database')
transaction.rollback()
else:
done = True
transaction.commit()
return simplejson.dumps({'done':done})
@dajaxice_register(method='POST')
@transaction.commit_manually
def review_rate(request, rate, review_id):
print "review id",review_id
done = False
try:
review = Review.objects.get(id=review_id)
review.rating.add(score=rate, user=request.user, ip_address=request.META['REMOTE_ADDR'])
except:
errors.append('An error occoured in record in database')
transaction.rollback()
else:
done = True<|fim▁hole|>
return simplejson.dumps({'done': done})
@dajaxice_register(method='POST')
def submit_review(request, book_id, title, text):
dajax = Dajax()
#TODO: checks if you have permission for posting review
try:
book = Book.objects.get(id=book_id)
except Book.DoesNotExist:
dajax.script('''
$.pnotify({
title: 'Review',
type:'error',
text: 'This Book doesn\'t exsist.',
opacity: .8
});
$('#id_text').val('');
$('#id_title').val('');
''')
else:
if len(text) < 200:
transaction.rollback()
dajax.script('''
$.pnotify({
title: 'Review',
type:'error',
text: 'Complete your review. We need some checks',
opacity: .8
});
$('#id_text').val('');
$('#id_title').val('');
''')
else:
review = Review.objects.create(book=book, user=request.user, title=title, text=text)
t_rendered = render_to_string('book/review.html', {'review': review})
dajax.prepend('#id_new_post_position', 'innerHTML', t_rendered)
dajax.script('''
$.pnotify({
title: 'Review',
type:'success',
text: 'Your review record',
opacity: .8
});
$('#id_text').val('');
$('#id_title').val('');
''')
return dajax.json()
@dajaxice_register(method='POST')
def ha(request, book_name):
print "book_name", book_name
return simplejson.dumps({'done': True})<|fim▁end|> | transaction.commit() |
<|file_name|>mesonlib.py<|end_file_name|><|fim▁begin|># Copyright 2012-2015 The Meson development team
# 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.
"""A library of random helper functionality."""
import platform, subprocess, operator, os, shutil, re, sys
from glob import glob
class MesonException(Exception):
def __init__(self, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
class File:
def __init__(self, is_built, subdir, fname):
self.is_built = is_built
self.subdir = subdir
self.fname = fname
def __str__(self):
return os.path.join(self.subdir, self.fname)
def __repr__(self):
ret = '<File: {0}'
if not self.is_built:
ret += ' (not built)'
ret += '>'
return ret.format(os.path.join(self.subdir, self.fname))
@staticmethod
def from_source_file(source_root, subdir, fname):
if not os.path.isfile(os.path.join(source_root, subdir, fname)):
raise MesonException('File %s does not exist.' % fname)
return File(False, subdir, fname)
@staticmethod
def from_built_file(subdir, fname):
return File(True, subdir, fname)
@staticmethod
def from_absolute_file(fname):
return File(False, '', fname)
def rel_to_builddir(self, build_to_src):
if self.is_built:
return os.path.join(self.subdir, self.fname)
else:
return os.path.join(build_to_src, self.subdir, self.fname)
def endswith(self, ending):
return self.fname.endswith(ending)
def split(self, s):
return self.fname.split(s)
def __eq__(self, other):
return (self.fname, self.subdir, self.is_built) == (other.fname, other.subdir, other.is_built)
def __hash__(self):
return hash((self.fname, self.subdir, self.is_built))
def get_compiler_for_source(compilers, src):
for comp in compilers:
if comp.can_compile(src):
return comp
raise RuntimeError('No specified compiler can handle file {!s}'.format(src))
def classify_unity_sources(compilers, sources):
compsrclist = {}
for src in sources:
comp = get_compiler_for_source(compilers, src)
if comp not in compsrclist:
compsrclist[comp] = [src]
else:
compsrclist[comp].append(src)
return compsrclist
def flatten(item):
if not isinstance(item, list):
return item
result = []
for i in item:
if isinstance(i, list):
result += flatten(i)
else:
result.append(i)
return result
def is_osx():
return platform.system().lower() == 'darwin'<|fim▁hole|>def is_windows():
platname = platform.system().lower()
return platname == 'windows' or 'mingw' in platname
def is_debianlike():
return os.path.isfile('/etc/debian_version')
def exe_exists(arglist):
try:
p = subprocess.Popen(arglist, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.communicate()
if p.returncode == 0:
return True
except FileNotFoundError:
pass
return False
def detect_vcs(source_dir):
vcs_systems = [
dict(name = 'git', cmd = 'git', repo_dir = '.git', get_rev = 'git describe --dirty=+', rev_regex = '(.*)', dep = '.git/logs/HEAD'),
dict(name = 'mercurial', cmd = 'hg', repo_dir = '.hg', get_rev = 'hg id -i', rev_regex = '(.*)', dep = '.hg/dirstate'),
dict(name = 'subversion', cmd = 'svn', repo_dir = '.svn', get_rev = 'svn info', rev_regex = 'Revision: (.*)', dep = '.svn/wc.db'),
dict(name = 'bazaar', cmd = 'bzr', repo_dir = '.bzr', get_rev = 'bzr revno', rev_regex = '(.*)', dep = '.bzr'),
]
segs = source_dir.replace('\\', '/').split('/')
for i in range(len(segs), -1, -1):
curdir = '/'.join(segs[:i])
for vcs in vcs_systems:
if os.path.isdir(os.path.join(curdir, vcs['repo_dir'])) and shutil.which(vcs['cmd']):
vcs['wc_dir'] = curdir
return vcs
return None
def grab_leading_numbers(vstr):
result = []
for x in vstr.split('.'):
try:
result.append(int(x))
except ValueError:
break
return result
numpart = re.compile('[0-9.]+')
def version_compare(vstr1, vstr2):
match = numpart.match(vstr1.strip())
if match is None:
raise MesonException('Uncomparable version string %s.' % vstr1)
vstr1 = match.group(0)
if vstr2.startswith('>='):
cmpop = operator.ge
vstr2 = vstr2[2:]
elif vstr2.startswith('<='):
cmpop = operator.le
vstr2 = vstr2[2:]
elif vstr2.startswith('!='):
cmpop = operator.ne
vstr2 = vstr2[2:]
elif vstr2.startswith('=='):
cmpop = operator.eq
vstr2 = vstr2[2:]
elif vstr2.startswith('='):
cmpop = operator.eq
vstr2 = vstr2[1:]
elif vstr2.startswith('>'):
cmpop = operator.gt
vstr2 = vstr2[1:]
elif vstr2.startswith('<'):
cmpop = operator.lt
vstr2 = vstr2[1:]
else:
cmpop = operator.eq
varr1 = grab_leading_numbers(vstr1)
varr2 = grab_leading_numbers(vstr2)
return cmpop(varr1, varr2)
def default_libdir():
if is_debianlike():
try:
pc = subprocess.Popen(['dpkg-architecture', '-qDEB_HOST_MULTIARCH'],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL)
(stdo, _) = pc.communicate()
if pc.returncode == 0:
archpath = stdo.decode().strip()
return 'lib/' + archpath
except Exception:
pass
if os.path.isdir('/usr/lib64') and not os.path.islink('/usr/lib64'):
return 'lib64'
return 'lib'
def default_libexecdir():
# There is no way to auto-detect this, so it must be set at build time
return 'libexec'
def default_prefix():
return 'c:/' if is_windows() else '/usr/local'
def get_library_dirs():
if is_windows():
return ['C:/mingw/lib'] # Fixme
if is_osx():
return ['/usr/lib'] # Fix me as well.
# The following is probably Debian/Ubuntu specific.
# /usr/local/lib is first because it contains stuff
# installed by the sysadmin and is probably more up-to-date
# than /usr/lib. If you feel that this search order is
# problematic, please raise the issue on the mailing list.
unixdirs = ['/usr/local/lib', '/usr/lib', '/lib']
plat = subprocess.check_output(['uname', '-m']).decode().strip()
# This is a terrible hack. I admit it and I'm really sorry.
# I just don't know what the correct solution is.
if plat == 'i686':
plat = 'i386'
if plat.startswith('arm'):
plat = 'arm'
unixdirs += glob('/usr/lib/' + plat + '*')
if os.path.exists('/usr/lib64'):
unixdirs.append('/usr/lib64')
unixdirs += glob('/lib/' + plat + '*')
if os.path.exists('/lib64'):
unixdirs.append('/lib64')
unixdirs += glob('/lib/' + plat + '*')
return unixdirs
def do_replacement(regex, line, confdata):
match = re.search(regex, line)
while match:
varname = match.group(1)
if varname in confdata.keys():
(var, desc) = confdata.get(varname)
if isinstance(var, str):
pass
elif isinstance(var, int):
var = str(var)
else:
raise RuntimeError('Tried to replace a variable with something other than a string or int.')
else:
var = ''
line = line.replace('@' + varname + '@', var)
match = re.search(regex, line)
return line
def do_mesondefine(line, confdata):
arr = line.split()
if len(arr) != 2:
raise MesonException('#mesondefine does not contain exactly two tokens: %s', line.strip())
varname = arr[1]
try:
(v, desc) = confdata.get(varname)
except KeyError:
return '/* #undef %s */\n' % varname
if isinstance(v, bool):
if v:
return '#define %s\n' % varname
else:
return '#undef %s\n' % varname
elif isinstance(v, int):
return '#define %s %d\n' % (varname, v)
elif isinstance(v, str):
return '#define %s %s\n' % (varname, v)
else:
raise MesonException('#mesondefine argument "%s" is of unknown type.' % varname)
def do_conf_file(src, dst, confdata):
try:
with open(src, encoding='utf-8') as f:
data = f.readlines()
except Exception as e:
raise MesonException('Could not read input file %s: %s' % (src, str(e)))
# Only allow (a-z, A-Z, 0-9, _, -) as valid characters for a define
# Also allow escaping '@' with '\@'
regex = re.compile(r'[^\\]?@([-a-zA-Z0-9_]+)@')
result = []
for line in data:
if line.startswith('#mesondefine'):
line = do_mesondefine(line, confdata)
else:
line = do_replacement(regex, line, confdata)
result.append(line)
dst_tmp = dst + '~'
with open(dst_tmp, 'w') as f:
f.writelines(result)
shutil.copymode(src, dst_tmp)
replace_if_different(dst, dst_tmp)
def dump_conf_header(ofilename, cdata):
with open(ofilename, 'w') as ofile:
ofile.write('''/*
* Autogenerated by the Meson build system.
* Do not edit, your changes will be lost.
*/
#pragma once
''')
for k in sorted(cdata.keys()):
(v, desc) = cdata.get(k)
if desc:
ofile.write('/* %s */\n' % desc)
if isinstance(v, bool):
if v:
ofile.write('#define %s\n\n' % k)
else:
ofile.write('#undef %s\n\n' % k)
elif isinstance(v, (int, str)):
ofile.write('#define %s %s\n\n' % (k, v))
else:
raise MesonException('Unknown data type in configuration file entry: ' + k)
def replace_if_different(dst, dst_tmp):
# If contents are identical, don't touch the file to prevent
# unnecessary rebuilds.
different = True
try:
with open(dst, 'r') as f1, open(dst_tmp, 'r') as f2:
if f1.read() == f2.read():
different = False
except FileNotFoundError:
pass
if different:
os.replace(dst_tmp, dst)
else:
os.unlink(dst_tmp)
def stringlistify(item):
if isinstance(item, str):
item = [item]
if not isinstance(item, list):
raise MesonException('Item is not an array')
for i in item:
if not isinstance(i, str):
raise MesonException('List item not a string.')
return item
def expand_arguments(args):
expended_args = []
for arg in args:
if not arg.startswith('@'):
expended_args.append(arg)
continue
args_file = arg[1:]
try:
with open(args_file) as f:
extended_args = f.read().split()
expended_args += extended_args
except Exception as e:
print('Error expanding command line arguments, %s not found' % args_file)
print(e)
return None
return expended_args<|fim▁end|> |
def is_linux():
return platform.system().lower() == 'linux'
|
<|file_name|>callback.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
__author__ = 'Alex Starov'
try:
from django.utils.simplejson import dumps
# import simplejson as json
except ImportError:
from json import dumps
# import json
from django.http import HttpResponse
def callback_data_send(request, ):
if request.is_ajax():
if request.method == 'POST':
# request_cookie = request.session.get(u'cookie', None, )
# if request_cookie:
sessionid = request.POST.get(u'sessionid', None, )
print('CallBack:', )
print('sessionid: ', sessionid, )
userid = request.POST.get(u'userid', False, )
print('userid: ', userid, )
print('userid type: ', type(userid, ), )
if userid == 'None':
userid = False
name = request.POST.get(u'name', None, )
print('name: ', name.encode('utf8', ), )
email = request.POST.get(u'email', None, )
print('email: ', email, )
phone = request.POST.get(u'phone', None, )
print('phone: ', phone, )
from applications.callback.models import CallBack
try:
if userid:
""" Error: invalid literal for int() with base 10: 'None' """
""" Ошибка вылазила из за того, что я пытался подсунуть вместо int() в user_id - None """
print(userid, )
callback = CallBack.objects.create(sessionid=sessionid,
user_id=userid,
name=name,
email=email,<|fim▁hole|> email=email,
phone=phone, )
except Exception as e:
print('Exception: ', e, )
print('Exception message: ', e.message, )
response = {'result': 'Bad',
'error': e.message, }
data = dumps(response, )
mimetype = 'application/javascript'
return HttpResponse(data, mimetype, )
else:
print(callback, )
""" Отправка заказа обратного звонка """
subject = u'Заказ обратного звонка от пользователя: %s на номер: %s. Интернет магазин Кексик.' % (name, phone, )
from django.template.loader import render_to_string
html_content = render_to_string('email_request_callback_content.html',
{'name': name,
'email': email,
'phone': phone, }, )
from django.utils.html import strip_tags
text_content = strip_tags(html_content, )
from_email = u'Интерент магазин Кексик <[email protected]>'
from django.core.mail import get_connection
backend = get_connection(backend='django.core.mail.backends.smtp.EmailBackend',
fail_silently=False, )
from django.core.mail import EmailMultiAlternatives
from proj.settings import Email_MANAGER
msg = EmailMultiAlternatives(subject=subject,
body=text_content,
from_email=from_email,
to=[Email_MANAGER, ],
connection=backend, )
msg.attach_alternative(content=html_content,
mimetype="text/html", )
msg.content_subtype = "html"
msg.send(fail_silently=False, )
""" Отправка благодарности клиенту. """
subject = u'Ваш заказ обратного звонка с сайта принят. Интернет магазин Кексик.'
html_content = render_to_string('email_successful_request_callback_content.html', )
text_content = strip_tags(html_content, )
# from_email = u'[email protected]'
to_email = email
msg = EmailMultiAlternatives(subject=subject,
body=text_content,
from_email=from_email,
to=[to_email, ],
connection=backend, )
msg.attach_alternative(content=html_content,
mimetype="text/html", )
from smtplib import SMTPSenderRefused, SMTPDataError
try:
msg.send(fail_silently=False, )
except SMTPSenderRefused as e:
response = {'result': 'Bad',
'error': e, }
else:
response = {'result': 'Ok', }
data = dumps(response, )
mimetype = 'application/javascript'
return HttpResponse(data, mimetype, )
# else:
# response = {'result': 'Bad',
# 'error': u'Вы только-что зашли на сайт!!!', }
# data = dumps(response, )
# mimetype = 'application/javascript'
# return HttpResponse(data, mimetype, )
elif request.method == 'GET':
return HttpResponse(status=400, )
else:
return HttpResponse(status=400, )
else:
return HttpResponse(status=400, )<|fim▁end|> | phone=phone, )
else:
callback = CallBack.objects.create(sessionid=sessionid,
name=name, |
<|file_name|>client.py<|end_file_name|><|fim▁begin|># Copyright 2016 Google Inc. All rights reserved.
#
# 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.
"""Client for interacting with the `Google Monitoring API (V3)`_.
Example::
>>> from gcloud import monitoring
>>> client = monitoring.Client()
>>> query = client.query(minutes=5)
>>> print(query.as_dataframe()) # Requires pandas.
At present, the client supports querying of time series, metric descriptors,
and monitored resource descriptors.
.. _Google Monitoring API (V3): https://cloud.google.com/monitoring/api/
"""
from gcloud.client import JSONClient
from gcloud.monitoring.connection import Connection
from gcloud.monitoring.metric import MetricDescriptor
from gcloud.monitoring.query import Query
from gcloud.monitoring.resource import ResourceDescriptor
class Client(JSONClient):
"""Client to bundle configuration needed for API requests.
:type project: string
:param project: The target project. If not passed, falls back to the
default inferred from the environment.
:type credentials: :class:`oauth2client.client.OAuth2Credentials` or
:class:`NoneType`
:param credentials: The OAuth2 Credentials to use for the connection
owned by this client. If not passed (and if no ``http``<|fim▁hole|> from the environment.
:type http: :class:`httplib2.Http` or class that defines ``request()``
:param http: An optional HTTP object to make requests. If not passed, an
``http`` object is created that is bound to the
``credentials`` for the current object.
"""
_connection_class = Connection
def query(self,
metric_type=Query.DEFAULT_METRIC_TYPE,
end_time=None,
days=0, hours=0, minutes=0):
"""Construct a query object for listing time series.
Example::
>>> query = client.query(minutes=5)
>>> print(query.as_dataframe()) # Requires pandas.
:type metric_type: string
:param metric_type: The metric type name. The default value is
:data:`Query.DEFAULT_METRIC_TYPE
<gcloud.monitoring.query.Query.DEFAULT_METRIC_TYPE>`,
but please note that this default value is provided only for
demonstration purposes and is subject to change. See the
`supported metrics`_.
:type end_time: :class:`datetime.datetime` or None
:param end_time: The end time (inclusive) of the time interval
for which results should be returned, as a datetime object.
The default is the start of the current minute.
The start time (exclusive) is determined by combining the
values of ``days``, ``hours``, and ``minutes``, and
subtracting the resulting duration from the end time.
It is also allowed to omit the end time and duration here,
in which case
:meth:`~gcloud.monitoring.query.Query.select_interval`
must be called before the query is executed.
:type days: integer
:param days: The number of days in the time interval.
:type hours: integer
:param hours: The number of hours in the time interval.
:type minutes: integer
:param minutes: The number of minutes in the time interval.
:rtype: :class:`~gcloud.monitoring.query.Query`
:returns: The query object.
:raises: :exc:`ValueError` if ``end_time`` is specified but
``days``, ``hours``, and ``minutes`` are all zero.
If you really want to specify a point in time, use
:meth:`~gcloud.monitoring.query.Query.select_interval`.
.. _supported metrics: https://cloud.google.com/monitoring/api/metrics
"""
return Query(self, metric_type,
end_time=end_time,
days=days, hours=hours, minutes=minutes)
def fetch_metric_descriptor(self, metric_type):
"""Look up a metric descriptor by type.
Example::
>>> METRIC = 'compute.googleapis.com/instance/cpu/utilization'
>>> print(client.fetch_metric_descriptor(METRIC))
:type metric_type: string
:param metric_type: The metric type name.
:rtype: :class:`~gcloud.monitoring.metric.MetricDescriptor`
:returns: The metric descriptor instance.
:raises: :class:`gcloud.exceptions.NotFound` if the metric descriptor
is not found.
"""
return MetricDescriptor._fetch(self, metric_type)
def list_metric_descriptors(self, filter_string=None):
"""List all metric descriptors for the project.
Example::
>>> for descriptor in client.list_metric_descriptors():
... print(descriptor.type)
:type filter_string: string or None
:param filter_string:
An optional filter expression describing the metric descriptors
to be returned. See the `filter documentation`_.
:rtype: list of :class:`~gcloud.monitoring.metric.MetricDescriptor`
:returns: A list of metric descriptor instances.
.. _filter documentation:
https://cloud.google.com/monitoring/api/v3/filters
"""
return MetricDescriptor._list(self, filter_string)
def fetch_resource_descriptor(self, resource_type):
"""Look up a resource descriptor by type.
Example::
>>> print(client.fetch_resource_descriptor('gce_instance'))
:type resource_type: string
:param resource_type: The resource type name.
:rtype: :class:`~gcloud.monitoring.resource.ResourceDescriptor`
:returns: The resource descriptor instance.
:raises: :class:`gcloud.exceptions.NotFound` if the resource descriptor
is not found.
"""
return ResourceDescriptor._fetch(self, resource_type)
def list_resource_descriptors(self, filter_string=None):
"""List all resource descriptors for the project.
Example::
>>> for descriptor in client.list_resource_descriptors():
... print(descriptor.type)
:type filter_string: string or None
:param filter_string:
An optional filter expression describing the resource descriptors
to be returned. See the `filter documentation`_.
:rtype: list of :class:`~gcloud.monitoring.resource.ResourceDescriptor`
:returns: A list of resource descriptor instances.
.. _filter documentation:
https://cloud.google.com/monitoring/api/v3/filters
"""
return ResourceDescriptor._list(self, filter_string)<|fim▁end|> | object is passed), falls back to the default inferred |
<|file_name|>base.py<|end_file_name|><|fim▁begin|>import numpy as np
#numpy is used for later classifiers
#Note: this is just a template with all required methods
#text is the text represented as a string
#textName is optional, indicate sthe name of the text, used for debug
#args are aditional arguments for the feature calculator
#debug indicates wheter to display debug info
#f is features
class BaseFeature():
def __init__(self, text, textName="", args=[], debug=True):
self.text = text.lower()
self.args = args
self.debug = debug
self.textName = textName
#Features, not yet calculated
self.f = np.array([])
def debugStart(self):
if self.debug:
print "--BaseFeatures--"
def beginCalc(self):
if self.debug:
print "Feature calculation begining on " + self.textName
print "------"
def endCalc(self):
if self.debug:
print "Feature calculation finished on " + self.textName
print "Features Calculated:"
print self.f
print<|fim▁hole|> #Calculations go here
self.endCalc()
return self.f
def getFeatures(self):
return self.f
def setText(self, text):
if self.debug:
print self.textName + "'s text set."
self.text = text.lower()
def setName(self, name):
if self.debug:
print "Name set to: " + self.textName<|fim▁end|> |
def calc(self):
self.debugStart()
self.beginCalc() |
<|file_name|>timer.rs<|end_file_name|><|fim▁begin|>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::mem;
use std::rt::rtio::RtioTimer;
use std::rt::task::BlockedTask;
use homing::{HomeHandle, HomingIO};
use super::{UvHandle, ForbidUnwind, ForbidSwitch, wait_until_woken_after, Loop};
use uvio::UvIoFactory;
use uvll;
pub struct TimerWatcher {
pub handle: *uvll::uv_timer_t,
home: HomeHandle,
action: Option<NextAction>,
blocker: Option<BlockedTask>,
id: uint, // see comments in timer_cb
}
pub enum NextAction {
WakeTask,
SendOnce(Sender<()>),
SendMany(Sender<()>, uint),
}
impl TimerWatcher {
pub fn new(io: &mut UvIoFactory) -> Box<TimerWatcher> {
let handle = io.make_handle();
let me = box TimerWatcher::new_home(&io.loop_, handle);
me.install()
}
pub fn new_home(loop_: &Loop, home: HomeHandle) -> TimerWatcher {
let handle = UvHandle::alloc(None::<TimerWatcher>, uvll::UV_TIMER);
assert_eq!(unsafe { uvll::uv_timer_init(loop_.handle, handle) }, 0);
TimerWatcher {
handle: handle,
action: None,
blocker: None,
home: home,
id: 0,
}
}
pub fn start(&mut self, f: uvll::uv_timer_cb, msecs: u64, period: u64) {
assert_eq!(unsafe {
uvll::uv_timer_start(self.handle, f, msecs, period)
}, 0)
}
pub fn stop(&mut self) {
assert_eq!(unsafe { uvll::uv_timer_stop(self.handle) }, 0)
}
pub unsafe fn set_data<T>(&mut self, data: *T) {
uvll::set_data_for_uv_handle(self.handle, data);
}
}
impl HomingIO for TimerWatcher {
fn home<'r>(&'r mut self) -> &'r mut HomeHandle { &mut self.home }
}
impl UvHandle<uvll::uv_timer_t> for TimerWatcher {
fn uv_handle(&self) -> *uvll::uv_timer_t { self.handle }
}
impl RtioTimer for TimerWatcher {
fn sleep(&mut self, msecs: u64) {
// As with all of the below functions, we must be extra careful when
// destroying the previous action. If the previous action was a channel,
// destroying it could invoke a context switch. For these situtations,
// we must temporarily un-home ourselves, then destroy the action, and
// then re-home again.
let missile = self.fire_homing_missile();
self.id += 1;
self.stop();
let _missile = match mem::replace(&mut self.action, None) {
None => missile, // no need to do a homing dance
Some(action) => {
drop(missile); // un-home ourself
drop(action); // destroy the previous action
self.fire_homing_missile() // re-home ourself
}
};
// If the descheduling operation unwinds after the timer has been
// started, then we need to call stop on the timer.
let _f = ForbidUnwind::new("timer");
self.action = Some(WakeTask);
wait_until_woken_after(&mut self.blocker, &self.uv_loop(), || {
self.start(timer_cb, msecs, 0);
});
self.stop();
}
fn oneshot(&mut self, msecs: u64) -> Receiver<()> {
let (tx, rx) = channel();
// similarly to the destructor, we must drop the previous action outside
// of the homing missile
let _prev_action = {
let _m = self.fire_homing_missile();
self.id += 1;
self.stop();
self.start(timer_cb, msecs, 0);
mem::replace(&mut self.action, Some(SendOnce(tx)))
};
return rx;
}
fn period(&mut self, msecs: u64) -> Receiver<()> {
let (tx, rx) = channel();
// similarly to the destructor, we must drop the previous action outside
// of the homing missile
let _prev_action = {
let _m = self.fire_homing_missile();
self.id += 1;
self.stop();
self.start(timer_cb, msecs, msecs);
mem::replace(&mut self.action, Some(SendMany(tx, self.id)))
};
return rx;
}
}
extern fn timer_cb(handle: *uvll::uv_timer_t) {
let _f = ForbidSwitch::new("timer callback can't switch");
let timer: &mut TimerWatcher = unsafe { UvHandle::from_uv_handle(&handle) };
match timer.action.take_unwrap() {
WakeTask => {
let task = timer.blocker.take_unwrap();
let _ = task.wake().map(|t| t.reawaken());
}
SendOnce(chan) => { let _ = chan.send_opt(()); }
SendMany(chan, id) => {
let _ = chan.send_opt(());
// Note that the above operation could have performed some form of
// scheduling. This means that the timer may have decided to insert
// some other action to happen. This 'id' keeps track of the updates
// to the timer, so we only reset the action back to sending on this
// channel if the id has remained the same. This is essentially a
// bug in that we have mutably aliasable memory, but that's libuv
// for you. We're guaranteed to all be running on the same thread,
// so there's no need for any synchronization here.
if timer.id == id {
timer.action = Some(SendMany(chan, id));
}
}
}
}
impl Drop for TimerWatcher {
fn drop(&mut self) {
// note that this drop is a little subtle. Dropping a channel which is<|fim▁hole|> // the channel unless we're on the home scheduler, but once we're on the
// home scheduler we should never move. Hence, we take the timer's
// action item and then move it outside of the homing block.
let _action = {
let _m = self.fire_homing_missile();
self.stop();
self.close();
self.action.take()
};
}
}
#[cfg(test)]
mod test {
use std::rt::rtio::RtioTimer;
use super::super::local_loop;
use super::TimerWatcher;
#[test]
fn oneshot() {
let mut timer = TimerWatcher::new(local_loop());
let port = timer.oneshot(1);
port.recv();
let port = timer.oneshot(1);
port.recv();
}
#[test]
fn override() {
let mut timer = TimerWatcher::new(local_loop());
let oport = timer.oneshot(1);
let pport = timer.period(1);
timer.sleep(1);
assert_eq!(oport.recv_opt(), Err(()));
assert_eq!(pport.recv_opt(), Err(()));
timer.oneshot(1).recv();
}
#[test]
fn period() {
let mut timer = TimerWatcher::new(local_loop());
let port = timer.period(1);
port.recv();
port.recv();
let port2 = timer.period(1);
port2.recv();
port2.recv();
}
#[test]
fn sleep() {
let mut timer = TimerWatcher::new(local_loop());
timer.sleep(1);
timer.sleep(1);
}
#[test] #[should_fail]
fn oneshot_fail() {
let mut timer = TimerWatcher::new(local_loop());
let _port = timer.oneshot(1);
fail!();
}
#[test] #[should_fail]
fn period_fail() {
let mut timer = TimerWatcher::new(local_loop());
let _port = timer.period(1);
fail!();
}
#[test] #[should_fail]
fn normal_fail() {
let _timer = TimerWatcher::new(local_loop());
fail!();
}
#[test]
fn closing_channel_during_drop_doesnt_kill_everything() {
// see issue #10375
let mut timer = TimerWatcher::new(local_loop());
let timer_port = timer.period(1000);
spawn(proc() {
let _ = timer_port.recv_opt();
});
// when we drop the TimerWatcher we're going to destroy the channel,
// which must wake up the task on the other end
}
#[test]
fn reset_doesnt_switch_tasks() {
// similar test to the one above.
let mut timer = TimerWatcher::new(local_loop());
let timer_port = timer.period(1000);
spawn(proc() {
let _ = timer_port.recv_opt();
});
drop(timer.oneshot(1));
}
#[test]
fn reset_doesnt_switch_tasks2() {
// similar test to the one above.
let mut timer = TimerWatcher::new(local_loop());
let timer_port = timer.period(1000);
spawn(proc() {
let _ = timer_port.recv_opt();
});
timer.sleep(1);
}
#[test]
fn sender_goes_away_oneshot() {
let port = {
let mut timer = TimerWatcher::new(local_loop());
timer.oneshot(1000)
};
assert_eq!(port.recv_opt(), Err(()));
}
#[test]
fn sender_goes_away_period() {
let port = {
let mut timer = TimerWatcher::new(local_loop());
timer.period(1000)
};
assert_eq!(port.recv_opt(), Err(()));
}
#[test]
fn receiver_goes_away_oneshot() {
let mut timer1 = TimerWatcher::new(local_loop());
drop(timer1.oneshot(1));
let mut timer2 = TimerWatcher::new(local_loop());
// while sleeping, the prevous timer should fire and not have its
// callback do something terrible.
timer2.sleep(2);
}
#[test]
fn receiver_goes_away_period() {
let mut timer1 = TimerWatcher::new(local_loop());
drop(timer1.period(1));
let mut timer2 = TimerWatcher::new(local_loop());
// while sleeping, the prevous timer should fire and not have its
// callback do something terrible.
timer2.sleep(2);
}
}<|fim▁end|> | // held internally may invoke some scheduling operations. We can't take |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|>from ga_starters import *<|fim▁end|> | |
<|file_name|>unit-like-struct-drop-run.rs<|end_file_name|><|fim▁begin|>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
<|fim▁hole|>
use std::any::AnyOwnExt;
use std::task;
struct Foo;
impl Drop for Foo {
fn drop(&mut self) {
fail!("This failure should happen.");
}
}
pub fn main() {
let x = task::try(proc() {
let _b = Foo;
});
let s = x.unwrap_err().move::<&'static str>().unwrap();
assert_eq!(s.as_slice(), "This failure should happen.");
}<|fim▁end|> | // Make sure the destructor is run for unit-like structs. |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|> | __all__ = ('db', 'format', 'query', 'sync') |
<|file_name|>non-exhaustive-match-nested.rs<|end_file_name|><|fim▁begin|>// -*- rust -*-
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// error-pattern: non-exhaustive patterns
enum t { a(u), b }<|fim▁hole|>
fn main() {
let x = a(c);
match x {
a(d) => { fail!("hello"); }
b => { fail!("goodbye"); }
}
}<|fim▁end|> | enum u { c, d } |
<|file_name|>RunnableWithResult.java<|end_file_name|><|fim▁begin|>package monitor;
public interface RunnableWithResult<T> {
<|fim▁hole|><|fim▁end|> | public T run() ;
} |
<|file_name|>neutron_clean_secgroups.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
import sys # reads command-line args
import ConfigParser
import os
config = ConfigParser.ConfigParser()
config.read(['os.cfg',
os.path.expanduser('~/.os.cfg'),
'/etc/os-maint/os.cfg'])
os_user_name = config.get('OPENSTACK', 'os_user_name')
os_password = config.get('OPENSTACK', 'os_password')
os_tenant_name = config.get('OPENSTACK', 'os_tenant_name')
os_auth_url = config.get('OPENSTACK', 'os_auth_url')
os_region_name = config.get('OPENSTACK', 'os_region_name')
broken_n_sgroups = []
known_tids = []
from neutronclient.v2_0 import client as neutronclient
nc = neutronclient.Client(username=os_user_name,
password=os_password,
tenant_name=os_tenant_name,
auth_url=os_auth_url)
<|fim▁hole|> tenant_name=os_tenant_name,
auth_url=os_auth_url
)
for tenant in keystone.tenants.list():
known_tids.append(tenant.id)
security_groups = nc.list_security_groups()
for n_sgroup in security_groups.get('security_groups'):
tid = n_sgroup.get('tenant_id')
if tid not in known_tids:
print "stray sgroup %s (tenant %s DNE)" % (n_sgroup.get('id'), tid)<|fim▁end|> |
from keystoneclient.v2_0 import client as kclient
keystone = kclient.Client(username=os_user_name,
password=os_password, |
<|file_name|>ReactionsRemoveResponse.ts<|end_file_name|><|fim▁begin|>/* tslint:disable */
import { WebAPICallResult } from '../WebClient';
export type ReactionsRemoveResponse = WebAPICallResult & {<|fim▁hole|> needed?: string;
provided?: string;
};<|fim▁end|> | ok?: boolean;
error?: string; |
<|file_name|>manage.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
import os
import sys<|fim▁hole|>if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "aalto_fitness.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)<|fim▁end|> | |
<|file_name|>loader.e6.js<|end_file_name|><|fim▁begin|>import AMD from '../../amd/src/amd.e6';<|fim▁hole|>import Module from '../../modules/src/base.es6';
import ModulesApi from '../../modules/src/api.e6';
window.Moff = new Core();
window.Moff.amd = new AMD();
window.Moff.event = new Event();
window.Moff.Module = new Module();
window.Moff.detect = new Detect();
window.Moff.modules = new ModulesApi();<|fim▁end|> | import Core from '../../core/src/core.e6';
import Event from '../../event/src/event.e6';
import Detect from '../../detect/src/detect.e6'; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.