file_name
stringlengths 3
137
| prefix
stringlengths 0
918k
| suffix
stringlengths 0
962k
| middle
stringlengths 0
812k
|
---|---|---|---|
exc_01_11.py | import spacy
| from spacy.____ import ____
nlp = spacy.load("fr_core_news_sm")
doc = nlp("Le constructeur Citröen présente la e-Méhari Courrèges au public.")
# Initialise le matcher avec le vocabulaire partagé
matcher = ____(____.____)
# Crée un motif qui recherche les deux tokens : "e-Méhari" et "Courrèges"
pattern = [____]
# Ajoute le motif au matcher
____.____("MEHARI_PATTERN", None, ____)
# Utilise le matcher sur le doc
matches = ____
print("Résultats :", [doc[start:end].text for match_id, start, end in matches]) | # Importe le Matcher |
test_stream_generator.py | # ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
from azure.core.pipeline.transport import (
HttpRequest,
AsyncHttpResponse,
AsyncHttpTransport,
)
from azure.core.pipeline import AsyncPipeline
from azure.core.pipeline.transport._aiohttp import AioHttpStreamDownloadGenerator
from unittest import mock
import pytest
@pytest.mark.asyncio
async def test_connection_error_response():
class MockTransport(AsyncHttpTransport):
def __init__(self):
self._count = 0
async def __aexit__(self, exc_type, exc_val, exc_tb):
pass
async def close(self):
pass
async def open(self):
pass
async def send(self, request, **kwargs):
request = HttpRequest('GET', 'http://127.0.0.1/')
response = AsyncHttpResponse(request, None)
response.status_code = 200
return response
class MockContent():
def __init__(self):
self._first = True
async def read(self, block_size):
if self._first:
self._first = False
raise ConnectionError
return None
class MockInternalResponse():
def __init__(self):
self.headers = {}
self.content = MockContent()
async def close(self):
pass
class AsyncMock(mock.MagicMock): | async def __call__(self, *args, **kwargs):
return super(AsyncMock, self).__call__(*args, **kwargs)
http_request = HttpRequest('GET', 'http://127.0.0.1/')
pipeline = AsyncPipeline(MockTransport())
http_response = AsyncHttpResponse(http_request, None)
http_response.internal_response = MockInternalResponse()
stream = AioHttpStreamDownloadGenerator(pipeline, http_response)
with mock.patch('asyncio.sleep', new_callable=AsyncMock):
with pytest.raises(StopAsyncIteration):
await stream.__anext__()
@pytest.mark.asyncio
async def test_connection_error_416():
class MockTransport(AsyncHttpTransport):
def __init__(self):
self._count = 0
async def __aexit__(self, exc_type, exc_val, exc_tb):
pass
async def close(self):
pass
async def open(self):
pass
async def send(self, request, **kwargs):
request = HttpRequest('GET', 'http://127.0.0.1/')
response = AsyncHttpResponse(request, None)
response.status_code = 416
return response
class MockContent():
async def read(self, block_size):
raise ConnectionError
class MockInternalResponse():
def __init__(self):
self.headers = {}
self.content = MockContent()
async def close(self):
pass
class AsyncMock(mock.MagicMock):
async def __call__(self, *args, **kwargs):
return super(AsyncMock, self).__call__(*args, **kwargs)
http_request = HttpRequest('GET', 'http://127.0.0.1/')
pipeline = AsyncPipeline(MockTransport())
http_response = AsyncHttpResponse(http_request, None)
http_response.internal_response = MockInternalResponse()
stream = AioHttpStreamDownloadGenerator(pipeline, http_response)
with mock.patch('asyncio.sleep', new_callable=AsyncMock):
with pytest.raises(ConnectionError):
await stream.__anext__() | |
build.rs | extern crate gcc; | use std::env;
fn main() {
if env::var("TARGET").unwrap().contains("linux") {
gcc::compile_library("libgetauxval-wrapper.a", &["c/getauxval-wrapper.c"]);
}
} | |
server.js | const express = require('express');
const path = require('path');
const { ApolloServer } = require('apollo-server-express');
const { authMiddleware } = require('./utils/auth');
const db = require('./config/connection');
const { typeDefs, resolvers } = require('./schemas');
const app = express();
const PORT = process.env.PORT || 3001;
const server = new ApolloServer({
typeDefs,
resolvers,
context: authMiddleware
});
server.applyMiddleware({ app });
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
// if we're in production, serve client/build as static assets
if (process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, '../client/build')));
}
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../client/build/index.html'));
});
db.once('open', () => {
app.listen(PORT, () => { | }); | console.log(`API server running on port ${PORT}!`);
// log where we can go to test our GQL API
console.log(`Use GraphQL at http://localhost:${PORT}${server.graphqlPath}`);
}); |
columns.d.ts | import * as React from 'react';
import { IconBaseProps } from 'react-icon-base';
export default class | extends React.Component<IconBaseProps, any> { }
| FaColumns |
main.go | package main
import (
"github.com/squiddy/gitlab-cli/cmd"
)
func main() | {
cmd.Execute()
} |
|
anx_test.go | package anx
import (
"testing"
"github.com/extrame/gocryptotrader/config"
)
var anx ANX
func TestSetDefaults(t *testing.T) {
anx.SetDefaults()
if anx.Name != "ANX" {
t.Error("Test Failed - ANX SetDefaults() incorrect values set")
}
if anx.Enabled != false {
t.Error("Test Failed - ANX SetDefaults() incorrect values set")
}
if anx.TakerFee != 0.6 {
t.Error("Test Failed - ANX SetDefaults() incorrect values set")
}
if anx.MakerFee != 0.3 {
t.Error("Test Failed - ANX SetDefaults() incorrect values set")
}
if anx.Verbose != false {
t.Error("Test Failed - ANX SetDefaults() incorrect values set")
}
if anx.Websocket != false {
t.Error("Test Failed - ANX SetDefaults() incorrect values set")
}
if anx.RESTPollingDelay != 10 {
t.Error("Test Failed - ANX SetDefaults() incorrect values set")
}
}
func TestSetup(t *testing.T) {
anxSetupConfig := config.GetConfig()
anxSetupConfig.LoadConfig("../../testdata/configtest.json")
anxConfig, err := anxSetupConfig.GetExchangeConfig("ANX")
if err != nil {
t.Error("Test Failed - ANX Setup() init error")
}
anx.Setup(anxConfig)
if anx.Enabled != true {
t.Error("Test Failed - ANX Setup() incorrect values set")
}
if anx.AuthenticatedAPISupport != false {
t.Error("Test Failed - ANX Setup() incorrect values set")
}
if len(anx.APIKey) != 0 {
t.Error("Test Failed - ANX Setup() incorrect values set")
}
if len(anx.APISecret) != 0 {
t.Error("Test Failed - ANX Setup() incorrect values set")
}
if anx.RESTPollingDelay != 10 {
t.Error("Test Failed - ANX Setup() incorrect values set")
}
if anx.Verbose != false {
t.Error("Test Failed - ANX Setup() incorrect values set")
}
if anx.Websocket != false {
t.Error("Test Failed - ANX Setup() incorrect values set")
}
if len(anx.BaseCurrencies) <= 0 {
t.Error("Test Failed - ANX Setup() incorrect values set")
}
if len(anx.AvailablePairs) <= 0 {
t.Error("Test Failed - ANX Setup() incorrect values set")
}
if len(anx.EnabledPairs) <= 0 {
t.Error("Test Failed - ANX Setup() incorrect values set")
}
}
func TestGetCurrencies(t *testing.T) {
_, err := anx.GetCurrencies()
if err != nil {
t.Fatalf("Test failed. TestGetCurrencies failed. Err: %s", err)
}
}
func TestGetTradablePairs(t *testing.T) {
_, err := anx.GetTradablePairs()
if err != nil {
t.Fatalf("Test failed. TestGetTradablePairs failed. Err: %s", err)
}
}
func TestGetFee(t *testing.T) {
makerFeeExpected, takerFeeExpected := 0.3, 0.6
if anx.GetFee(true) != makerFeeExpected {
t.Error("Test Failed - ANX GetFee() incorrect return value")
}
if anx.GetFee(false) != takerFeeExpected {
t.Error("Test Failed - ANX GetFee() incorrect return value")
}
}
func TestGetTicker(t *testing.T) |
func TestGetDepth(t *testing.T) {
ticker, err := anx.GetDepth("BTCUSD")
if err != nil {
t.Errorf("Test Failed - ANX GetDepth() error: %s", err)
}
if ticker.Result != "success" {
t.Error("Test Failed - ANX GetDepth() unsuccessful")
}
}
func TestGetAPIKey(t *testing.T) {
apiKey, apiSecret, err := anx.GetAPIKey("userName", "passWord", "", "1337")
if err == nil {
t.Error("Test Failed - ANX GetAPIKey() Incorrect")
}
if apiKey != "" {
t.Error("Test Failed - ANX GetAPIKey() Incorrect")
}
if apiSecret != "" {
t.Error("Test Failed - ANX GetAPIKey() Incorrect")
}
}
| {
ticker, err := anx.GetTicker("BTCUSD")
if err != nil {
t.Errorf("Test Failed - ANX GetTicker() error: %s", err)
}
if ticker.Result != "success" {
t.Error("Test Failed - ANX GetTicker() unsuccessful")
}
} |
sign.go | package sign
import (
"app/applib/guestbook"
"net/http"
"time"
"github.com/pborman/uuid"
"appengine"
"appengine/datastore"
"appengine/user"
)
type Greeting struct {
Author string
Content string
Date time.Time
}
func NewGreeting(content string) Greeting |
func Sign(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
g := Greeting{
Content: r.FormValue("content"),
Date: time.Now(),
}
if u := user.Current(c); u != nil {
g.Author = u.String()
} else {
g.Author = uuid.New()
}
// We set the same parent key on every Greeting entity to ensure each Greeting
// is in the same entity group. Queries across the single entity group
// will be consistent. However, the write rate to a single entity group
// should be limited to ~1/second.
key := datastore.NewIncompleteKey(c, "Greeting", guestbook.Key(c))
_, err := datastore.Put(c, key, &g)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/", http.StatusFound)
}
| {
return Greeting{
Content: content,
Date: time.Now(),
}
} |
runner.py | #!/usr/bin/env python
"""Handles run."""
__author__ = '[email protected] (Pramod Gupta)'
__copyright__ = 'Copyright 2012 Room77, Inc.'
import itertools
import json
import os
import re
import sys
import time
from pylib.base.flags import Flags
from pylib.base.exec_utils import ExecUtils
from pylib.base.term_color import TermColor
from pylib.file.file_utils import FileUtils
from pylib.util.mail.mailer import Mailer
from pylib.zeus.pipeline_cmd_base import PipelineCmdBase
from pylib.zeus.pipeline_config import PipelineConfig
from pylib.zeus.pipeline_utils import PipelineUtils
class Runner(PipelineCmdBase):
"""Class to handle run."""
# The different exit codes that can be returned after running a task.
EXITCODE = {
'_LOWEST':-1, # Internal use.
'SUCCESS': 0,
'ALLOW_FAIL': 1,
'FAILURE': 2,
'ABORT_FAIL': 3,
}
EXITCODE_DESCRIPTION = {
0: 'SUCCESS',
1: 'ALLOW_FAIL',
2: 'FAILURE',
3: 'ABORT_FAIL',
}
EXITCODE_FILE = {
0: 'SUCCESS',
1: 'SUCCESS',
2: 'FAILURE',
3: 'ABORT',
}
TASK_OPTIONS = {
# Default option. Task will run regardless of if earlier tasks in the directory
# were successful or not. Task will not run if any task across the pipeline was
# marked as `abort_fail`.
'NORMAL': 0,
# If this step fails, prevent any subsequent steps across the entire pipeline from
# running. The pipeline will be aborted. All currently running tasks will finish,
# but no further tasks will be run. To enable this option, add `.abort_fail` to the
# task name.
'ABORT_FAIL': 1,
# If this step fails, do not mark the out directory as failed. Mark it as successful
# if all other tasks at this level have succeeded. This will allow publishing of a
# task directory even if the only steps that failed were marked as `allow_fail`. To
# enable this option, add `.allow_fail` to the task name.
'ALLOW_FAIL': 2,
# If any earlier tasks located in the same directory as this task failed, prevent
# this task from running. This task will also be marked as failed. To enable this
# option, add `.require_dir_success` to the task name.
'REQUIRE_DIR_SUCCESS': 3,
}
@classmethod
def Init(cls, parser):
super(Runner, cls).Init(parser)
parser.add_argument('-t', '--timeout', type=float, default=86400,
help='Timeout for each task in seconds.')
parser.add_argument('--pool_size', type=int, default=0,
help='The pool size for parallelization.')
parser.add_argument('--detailed_success_mail', action='store_true', default=False,
help='Sends a detailed mail even on success. Useful for debugging.')
parser.add_argument('--success_mail', type=str, default='',
help='The mail to use to send info in case of success.')
parser.add_argument('--failure_mail', type=str, default='',
help='The mail to use to send info in case of success.')
parser.add_argument('--mail_domain', type=str, default='corp.room77.com',
help='The domain to use when sending automated '
'pipeline mail.')
@classmethod
def WorkHorse(cls, tasks):
|
@classmethod
def _CreateDirsForTasks(cls, tasks):
"""Creates the relevant dirs for tasks.
Args:
tasks: OrderedDict {int, set(string)}: Dict from priority to set of tasks to execute at the
priority. Note: the dict is ordered by priority.
"""
for set_tasks in tasks.values():
for task in set_tasks:
rel_path = PipelineUtils.GetTaskOutputRelativeDir(task)
PipelineConfig.Instance().CreateAllSubDirsForPath(rel_path)
@classmethod
def _RunSingeTask(cls, task):
"""Runs a Single Task.
Args:
task: string: The task to run.
Return:
(EXITCODE, string): Returns a tuple of the result status and the task.
"""
TermColor.Info('Executing %s' % PipelineUtils.TaskDisplayName(task))
task_vars = cls.__GetEnvVarsForTask(task)
TermColor.VInfo(4, 'VARS: \n%s' % task_vars)
task_cmd = task
pipe_output = True
log_file = PipelineUtils.GetLogFileForTask(task)
if log_file:
task_cmd += ' > ' + PipelineUtils.GetLogFileForTask(task) + ' 2>&1'
pipe_output = False
timeout = cls.__GetTimeOutForTask(task)
start = time.time()
(status, out) = ExecUtils.RunCmd(task_cmd, timeout, pipe_output, task_vars)
time_taken = time.time() - start
TermColor.Info('Executed %s. Took %.2fs' % (PipelineUtils.TaskDisplayName(task), time_taken))
if status:
TermColor.Failure('Failed Task: %s' % PipelineUtils.TaskDisplayName(task))
if task_vars.get('PIPELINE_TASK_ABORT_FAIL', None):
status_code = Runner.EXITCODE['ABORT_FAIL']
elif task_vars.get('PIPELINE_TASK_ALLOW_FAIL', None):
status_code = Runner.EXITCODE['ALLOW_FAIL']
else:
status_code = Runner.EXITCODE['FAILURE']
else:
status_code = Runner.EXITCODE['SUCCESS']
cls._SendMailForTask(task, status_code, time_taken, log_file, out)
# Everything done. Mark the task as successful.
return (status_code, task)
@classmethod
def __GetEnvVarsForTask(cls, task):
"""Returns the env vars for the task.
Args:
task: string: The task for which the envvar should be prepared.
Returns:
dict {string, string}: The dictionary of IDS to values.
"""
rel_path = PipelineUtils.GetTaskOutputRelativeDir(task)
vars = {}
for k, v in PipelineConfig.Instance().GetAllSubDirsForPath(rel_path).items():
vars[k] = v
prev_dir = FileUtils.GetPreviousDatedDir(v)
if not prev_dir: prev_dir = v
vars[k + '_PREV'] = prev_dir
vars.update(PipelineConfig.Instance().GetAllENVVars())
# Check if the task is critical or not.
task_options = cls.__GetTaskOptions(task)
if task_options[Runner.TASK_OPTIONS['ABORT_FAIL']]:
vars['PIPELINE_TASK_ABORT_FAIL'] = '1'
if task_options[Runner.TASK_OPTIONS['ALLOW_FAIL']]:
vars['PIPELINE_TASK_ALLOW_FAIL'] = '1'
return vars
@classmethod
def __GetTimeOutForTask(cls, task):
"""Returns the timeout for the task.
Args:
task: string: The task for which the timeout should be prepared.
Returns:
int: The timeout in seconds.
"""
timeout = FileUtils.FileContents(task + '.timeout')
if not timeout:
timeout = FileUtils.FileContents(os.path.join(PipelineUtils.TaskDirName(task), 'timeout'))
if not timeout: return Flags.ARGS.timeout
timeout = re.sub('\s*', '', timeout)
timeout_parts = re.split('(\d+)', timeout)
if len(timeout_parts) < 3:
TermColor.Warning('Ignoring invalid timeout [%s] for task: %s' % (timeout, task))
return Flags.ARGS.timeout
timeout = float(timeout_parts[1])
annotation = timeout_parts[2]
if not annotation: return timeout
elif annotation == 'd': timeout *= 86400
elif annotation == 'h': timeout *= 3600
elif annotation == 'm': timeout *= 60
elif annotation == 'ms': timeout *= 0.001
elif annotation == 'us': timeout *= 0.000001
return timeout
@classmethod
def __GetTaskOptions(cls, task):
rel_task = PipelineUtils.TaskRelativeName(task)
options = {
v: False
for v in Runner.TASK_OPTIONS.values()
}
if '.abort_fail' in rel_task:
options[Runner.TASK_OPTIONS['ABORT_FAIL']] = True
if '.allow_fail' in rel_task:
options[Runner.TASK_OPTIONS['ALLOW_FAIL']] = True
if '.require_dir_success' in rel_task:
options[Runner.TASK_OPTIONS['REQUIRE_DIR_SUCCESS']] = True
if not options:
options[Runner.TASK_OPTIONS['NORMAL']] = True
return options
@classmethod
def _SendMailForTask(cls, task, status_code, time_taken, log_file, msg):
"""Sends the mail if required for the task.
Args:
task: string: The task for which the envvar should be prepared.
status_code: EXITCODE: The exit code for the task.
time_taken: float: Time taken in seconds.
log_file: string: The log file containing the output of the task.
msg: string: The output message piped directly. Note only one of msg or log_file will be
present at any time.
Returns:
dict {string, string}: The dictionary of IDS to values.
"""
if status_code == Runner.EXITCODE['SUCCESS']:
if not Flags.ARGS.detailed_success_mail: return
receiver = Flags.ARGS.success_mail
else: receiver = Flags.ARGS.failure_mail
# Check if there is no receiver for the mail.
if not receiver: return
mail_domain = Flags.ARGS.mail_domain
status_description = Runner.EXITCODE_DESCRIPTION[status_code]
subject = "[%s:%s] %s : %s" % (PipelineConfig.Instance().pipeline_id(),
PipelineConfig.Instance().pipeline_date(),
status_description, PipelineUtils.TaskDisplayName(task))
body = 'Executed task: %s. \nStatus:%s \nTime: %.2fs.' % (task, status_description, time_taken)
if msg:
body += '\n%s' % msg
Mailer().send_simple_message(
PipelineUtils.ZeusEmailId(mail_domain), [receiver], subject, body)
else:
Mailer().send_message_from_files(
PipelineUtils.ZeusEmailId(mail_domain), [receiver], subject, [log_file],
body)
@classmethod
def _WriteOutDirsStatus(cls, out_dirs_status):
"""Writes the status for each of the dirs in the dict.
Args:
out_dirs_status: dict {string, EXITCODE}: Dict of dir -> exit status.
"""
for k, v in out_dirs_status.items():
FileUtils.RemoveFiles([os.path.join(k, x) for x in Runner.EXITCODE_FILE.values()])
status_file = Runner.EXITCODE_FILE.get(v, '')
if not status_file: continue
FileUtils.CreateFileWithData(os.path.join(k, status_file))
@classmethod
def _SendFinalStatusMail(cls, successful_run, failed_run, aborted_task, time_taken):
"""Sends the final status mail if required.
Args:
(list, list): Returns a tuple of list in the form
(successful_tasks, failed_tasks) specifying tasks that succeeded and
ones that failed.
aborted_task: string: True if the pipeline was aborted.
time_taken: float: Time taken in seconds.
"""
if not successful_run and not failed_run: return
if not failed_run:
receiver = Flags.ARGS.success_mail
status_description = 'SUCCESS'
else:
receiver = Flags.ARGS.failure_mail
status_description = 'ABORT FAIL' if aborted_task else 'FAIL'
# Check if there is no receiver for the mail.
if not receiver: return
mail_domain = Flags.ARGS.mail_domain
subject = "[%s:%s] Final Status: %s" % (PipelineConfig.Instance().pipeline_id(),
PipelineConfig.Instance().pipeline_date(),
status_description)
body = 'Aborted by: %s\n\n' % aborted_task if aborted_task else ''
body += ('Successful tasks: %d\n%s\n\n'
'Failed tasks: %d\n%s\n\n'
'Total Time: %.2fs.\n'
'\n%s\n\n' %
(len(successful_run), json.dumps(successful_run, indent=2),
len(failed_run), json.dumps(failed_run, indent=2),
time_taken,
PipelineConfig.Instance().GetConfigString()))
Mailer().send_simple_message(
PipelineUtils.ZeusEmailId(mail_domain), [receiver], subject, body)
def main():
try:
Runner.Init(Flags.PARSER)
Flags.InitArgs()
return Runner.Run()
except KeyboardInterrupt as e:
TermColor.Warning('KeyboardInterrupt')
return 1
if __name__ == '__main__':
sys.exit(main())
| """Runs the workhorse for the command.
Args:
tasks: OrderedDict {int, set(string)}: Dict from priority to set of tasks to execute at the
priority. Note: the dict is ordered by priority.
Return:
(list, list): Returns a tuple of list in the form
(successful_tasks, failed_tasks) specifying tasks that succeeded and
ones that failed.
"""
# All our binaries assume they will be run from the source root.
start = time.time()
os.chdir(FileUtils.GetSrcRoot())
cls._CreateDirsForTasks(tasks)
successful_run = []; failed_run = []
aborted_task = None
# NOTE(stephen): Storing task dir status and task out dir status separately since
# pipelines do not always have an out dir defined.
dirs_status = {}
out_dirs_status = {}
for set_tasks in tasks.values():
if aborted_task:
failed_run += set_tasks
continue
tasks_to_run = []
for task in set_tasks:
task_options = cls.__GetTaskOptions(task)
# Check if this task requires all previous tasks in the same directory to be
# successful.
if task_options[Runner.TASK_OPTIONS['REQUIRE_DIR_SUCCESS']]:
task_dir = PipelineUtils.TaskDirName(task)
cur_dir_status = dirs_status.get(task_dir)
# If any previous tasks have been run in this directory, check to ensure all
# of them were successful.
if cur_dir_status and cur_dir_status != Runner.EXITCODE['SUCCESS']:
failed_run += [task]
task_display_name = PipelineUtils.TaskDisplayName(task)
TermColor.Info('Skipped %s' % task_display_name)
TermColor.Failure(
'Skipped Task: %s due to earlier failures in task dir' % task_display_name
)
continue
tasks_to_run.append(task)
# It is possible for all steps at this priority level to be skipped due to the
# task options selected.
if set_tasks and not tasks_to_run:
continue
# Run all the tasks at the same priority in parallel.
args = zip(itertools.repeat(cls), itertools.repeat('_RunSingeTask'),
tasks_to_run)
task_res = ExecUtils.ExecuteParallel(args, Flags.ARGS.pool_size)
# task_res = []
# for task in tasks_to_run: task_res += [cls._RunSingeTask(task)]
if not task_res:
TermColor.Error('Could not process: %s' % tasks_to_run)
failed_run += tasks_to_run
continue
for (res, task) in task_res:
if res == Runner.EXITCODE['SUCCESS']:
successful_run += [task]
elif res == Runner.EXITCODE['FAILURE']:
failed_run += [task]
elif res == Runner.EXITCODE['ALLOW_FAIL']:
failed_run += [task]
elif res == Runner.EXITCODE['ABORT_FAIL']:
failed_run += [task]
aborted_task = task
else:
TermColor.Fatal('Invalid return %d code for %s' % (res, task))
# Update the current status of all tasks in the same directory.
task_dir = PipelineUtils.TaskDirName(task)
dirs_status[task_dir] = max(
dirs_status.get(task_dir, Runner.EXITCODE['_LOWEST']), res,
)
# Update the out dir status.
out_dir = PipelineUtils.GetOutDirForTask(task)
if out_dir:
out_dirs_status[out_dir] = max(
out_dirs_status.get(out_dir, Runner.EXITCODE['_LOWEST']), res,
)
# Write the status files to the dirs.
cls._WriteOutDirsStatus(out_dirs_status)
# Send the final status mail.
time_taken = time.time() - start
cls._SendFinalStatusMail(successful_run, failed_run, aborted_task, time_taken)
if aborted_task:
TermColor.Failure('Aborted by task: %s' % aborted_task)
return (successful_run, failed_run) |
ends_with.rs | use nu_engine::CallExt;
use nu_protocol::ast::Call;
use nu_protocol::ast::CellPath;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::Category;
use nu_protocol::Spanned;
use nu_protocol::{Example, PipelineData, ShellError, Signature, Span, SyntaxShape, Value};
#[derive(Clone)]
pub struct SubCommand;
impl Command for SubCommand {
fn name(&self) -> &str {
"str ends-with"
}
fn signature(&self) -> Signature {
Signature::build("str ends-with")
.required("pattern", SyntaxShape::String, "the pattern to match")
.rest(
"rest",
SyntaxShape::CellPath,
"optionally matches suffix of text by column paths",
)
.category(Category::Strings)
}
fn usage(&self) -> &str {
"Check if a string ends with a pattern"
}
fn search_terms(&self) -> Vec<&str> {
vec!["pattern", "match", "find", "search"]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
operate(engine_state, stack, call, input)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Checks if string ends with '.rb' pattern",
example: "'my_library.rb' | str ends-with '.rb'",
result: Some(Value::Bool {
val: true,
span: Span::test_data(),
}),
},
Example {
description: "Checks if string ends with '.txt' pattern",
example: "'my_library.rb' | str ends-with '.txt'",
result: Some(Value::Bool {
val: false,
span: Span::test_data(), | }
}
fn operate(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let pattern: Spanned<String> = call.req(engine_state, stack, 0)?;
let column_paths: Vec<CellPath> = call.rest(engine_state, stack, 1)?;
input.map(
move |v| {
if column_paths.is_empty() {
action(&v, &pattern.item, head)
} else {
let mut ret = v;
for path in &column_paths {
let p = pattern.item.clone();
let r = ret.update_cell_path(
&path.members,
Box::new(move |old| action(old, &p, head)),
);
if let Err(error) = r {
return Value::Error { error };
}
}
ret
}
},
engine_state.ctrlc.clone(),
)
}
fn action(input: &Value, pattern: &str, head: Span) -> Value {
match input {
Value::String { val, .. } => Value::Bool {
val: val.ends_with(pattern),
span: head,
},
other => Value::Error {
error: ShellError::UnsupportedInput(
format!(
"Input's type is {}. This command only works with strings.",
other.get_type()
),
head,
),
},
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(SubCommand {})
}
} | }),
},
] |
api_op_TagRole.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package iam
import (
"context"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
"github.com/aws/aws-sdk-go-v2/service/iam/types"
"github.com/aws/smithy-go/middleware"
smithyhttp "github.com/aws/smithy-go/transport/http"
)
// Adds one or more tags to an IAM role. The role can be a regular role or a
// service-linked role. If a tag with the same key name already exists, then that
// tag is overwritten with the new value. A tag consists of a key name and an
// associated value. By assigning tags to your resources, you can do the
// following:
//
// * Administrative grouping and discovery - Attach tags to resources
// to aid in organization and search. For example, you could search for all
// resources with the key name Project and the value MyImportantProject. Or search
// for all resources with the key name Cost Center and the value 41200.
//
// * Access
// control - Reference tags in IAM user-based and resource-based policies. You can
// use tags to restrict access to only an IAM user or role that has a specified tag
// attached. You can also restrict access to only those resources that have a
// certain tag attached. For examples of policies that show how to use tags to
// control access, see Control Access Using IAM Tags
// (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_tags.html) in the IAM
// User Guide.
//
// * Cost allocation - Use tags to help track which individuals and
// teams are using which AWS resources.
//
// * Make sure that you have no invalid tags
// and that you do not exceed the allowed number of tags per role. In either case,
// the entire request fails and no tags are added to the role.
//
// * AWS always
// interprets the tag Value as a single string. If you need to store an array, you
// can store comma-separated values in the string. However, you must interpret the
// value in your code.
//
// For more information about tagging, see Tagging IAM
// Identities (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html) in
// the IAM User Guide.
func (c *Client) TagRole(ctx context.Context, params *TagRoleInput, optFns ...func(*Options)) (*TagRoleOutput, error) {
if params == nil {
params = &TagRoleInput{}
}
result, metadata, err := c.invokeOperation(ctx, "TagRole", params, optFns, addOperationTagRoleMiddlewares)
if err != nil {
return nil, err
}
out := result.(*TagRoleOutput)
out.ResultMetadata = metadata
return out, nil
}
type TagRoleInput struct {
// The name of the role that you want to add tags to. This parameter accepts
// (through its regex pattern (http://wikipedia.org/wiki/regex)) a string of
// characters that consist of upper and lowercase alphanumeric characters with no
// spaces. You can also include any of the following characters: _+=,.@-
//
// This member is required.
RoleName *string
// The list of tags that you want to attach to the role. Each tag consists of a key
// name and an associated value. You can specify this with a JSON string.
//
// This member is required.
Tags []types.Tag
}
type TagRoleOutput struct {
// Metadata pertaining to the operation's result.
ResultMetadata middleware.Metadata
}
func | (stack *middleware.Stack, options Options) (err error) {
err = stack.Serialize.Add(&awsAwsquery_serializeOpTagRole{}, middleware.After)
if err != nil {
return err
}
err = stack.Deserialize.Add(&awsAwsquery_deserializeOpTagRole{}, middleware.After)
if err != nil {
return err
}
if err = addSetLoggerMiddleware(stack, options); err != nil {
return err
}
if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil {
return err
}
if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil {
return err
}
if err = addResolveEndpointMiddleware(stack, options); err != nil {
return err
}
if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil {
return err
}
if err = addRetryMiddlewares(stack, options); err != nil {
return err
}
if err = addHTTPSignerV4Middleware(stack, options); err != nil {
return err
}
if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil {
return err
}
if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil {
return err
}
if err = addClientUserAgent(stack); err != nil {
return err
}
if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil {
return err
}
if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil {
return err
}
if err = addOpTagRoleValidationMiddleware(stack); err != nil {
return err
}
if err = stack.Initialize.Add(newServiceMetadataMiddleware_opTagRole(options.Region), middleware.Before); err != nil {
return err
}
if err = addRequestIDRetrieverMiddleware(stack); err != nil {
return err
}
if err = addResponseErrorMiddleware(stack); err != nil {
return err
}
if err = addRequestResponseLogging(stack, options); err != nil {
return err
}
return nil
}
func newServiceMetadataMiddleware_opTagRole(region string) *awsmiddleware.RegisterServiceMetadata {
return &awsmiddleware.RegisterServiceMetadata{
Region: region,
ServiceID: ServiceID,
SigningName: "iam",
OperationName: "TagRole",
}
}
| addOperationTagRoleMiddlewares |
ze_generated_example_runtimeversions_client_test.go | //go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armappplatform_test |
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/appplatform/armappplatform"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/appplatform/resource-manager/Microsoft.AppPlatform/preview/2022-05-01-preview/examples/RuntimeVersions_ListRuntimeVersions.json
func ExampleRuntimeVersionsClient_ListRuntimeVersions() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
client, err := armappplatform.NewRuntimeVersionsClient(cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
res, err := client.ListRuntimeVersions(ctx,
nil)
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
// TODO: use response item
_ = res
} |
import (
"context"
"log" |
_base.py | """
Generalized Linear Models.
"""
# Author: Alexandre Gramfort <[email protected]>
# Fabian Pedregosa <[email protected]>
# Olivier Grisel <[email protected]>
# Vincent Michel <[email protected]>
# Peter Prettenhofer <[email protected]>
# Mathieu Blondel <[email protected]>
# Lars Buitinck
# Maryan Morel <[email protected]>
# Giorgio Patrini <[email protected]>
# License: BSD 3 clause
from abc import ABCMeta, abstractmethod
import numbers
import warnings
import numpy as np
import scipy.sparse as sp
from scipy import linalg
from scipy import optimize
from scipy import sparse
from scipy.special import expit
from joblib import Parallel
from ..base import (BaseEstimator, ClassifierMixin, RegressorMixin,
MultiOutputMixin)
from ..utils import check_array
from ..utils.validation import FLOAT_DTYPES
from ..utils.validation import _deprecate_positional_args
from ..utils import check_random_state
from ..utils.extmath import safe_sparse_dot
from ..utils.sparsefuncs import mean_variance_axis, inplace_column_scale
from ..utils.fixes import sparse_lsqr
from ..utils._seq_dataset import ArrayDataset32, CSRDataset32
from ..utils._seq_dataset import ArrayDataset64, CSRDataset64
from ..utils.validation import check_is_fitted, _check_sample_weight
from ..utils.fixes import delayed
from ..preprocessing import normalize as f_normalize
# TODO: bayesian_ridge_regression and bayesian_regression_ard
# should be squashed into its respective objects.
SPARSE_INTERCEPT_DECAY = 0.01
# For sparse data intercept updates are scaled by this decay factor to avoid
# intercept oscillation.
def make_dataset(X, y, sample_weight, random_state=None):
"""Create ``Dataset`` abstraction for sparse and dense inputs.
This also returns the ``intercept_decay`` which is different
for sparse datasets.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training data
y : array-like, shape (n_samples, )
Target values.
|
random_state : int, RandomState instance or None (default)
Determines random number generation for dataset shuffling and noise.
Pass an int for reproducible output across multiple function calls.
See :term:`Glossary <random_state>`.
Returns
-------
dataset
The ``Dataset`` abstraction
intercept_decay
The intercept decay
"""
rng = check_random_state(random_state)
# seed should never be 0 in SequentialDataset64
seed = rng.randint(1, np.iinfo(np.int32).max)
if X.dtype == np.float32:
CSRData = CSRDataset32
ArrayData = ArrayDataset32
else:
CSRData = CSRDataset64
ArrayData = ArrayDataset64
if sp.issparse(X):
dataset = CSRData(X.data, X.indptr, X.indices, y, sample_weight,
seed=seed)
intercept_decay = SPARSE_INTERCEPT_DECAY
else:
X = np.ascontiguousarray(X)
dataset = ArrayData(X, y, sample_weight, seed=seed)
intercept_decay = 1.0
return dataset, intercept_decay
def _preprocess_data(X, y, fit_intercept, normalize=False, copy=True,
sample_weight=None, return_mean=False, check_input=True):
"""Center and scale data.
Centers data to have mean zero along axis 0. If fit_intercept=False or if
the X is a sparse matrix, no centering is done, but normalization can still
be applied. The function returns the statistics necessary to reconstruct
the input data, which are X_offset, y_offset, X_scale, such that the output
X = (X - X_offset) / X_scale
X_scale is the L2 norm of X - X_offset. If sample_weight is not None,
then the weighted mean of X and y is zero, and not the mean itself. If
return_mean=True, the mean, eventually weighted, is returned, independently
of whether X was centered (option used for optimization with sparse data in
coordinate_descend).
This is here because nearly all linear models will want their data to be
centered. This function also systematically makes y consistent with X.dtype
"""
if isinstance(sample_weight, numbers.Number):
sample_weight = None
if sample_weight is not None:
sample_weight = np.asarray(sample_weight)
if check_input:
X = check_array(X, copy=copy, accept_sparse=['csr', 'csc'],
dtype=FLOAT_DTYPES)
elif copy:
if sp.issparse(X):
X = X.copy()
else:
X = X.copy(order='K')
y = np.asarray(y, dtype=X.dtype)
if fit_intercept:
if sp.issparse(X):
X_offset, X_var = mean_variance_axis(X, axis=0)
if not return_mean:
X_offset[:] = X.dtype.type(0)
if normalize:
# TODO: f_normalize could be used here as well but the function
# inplace_csr_row_normalize_l2 must be changed such that it
# can return also the norms computed internally
# transform variance to norm in-place
X_var *= X.shape[0]
X_scale = np.sqrt(X_var, X_var)
del X_var
X_scale[X_scale == 0] = 1
inplace_column_scale(X, 1. / X_scale)
else:
X_scale = np.ones(X.shape[1], dtype=X.dtype)
else:
X_offset = np.average(X, axis=0, weights=sample_weight)
X -= X_offset
if normalize:
X, X_scale = f_normalize(X, axis=0, copy=False,
return_norm=True)
else:
X_scale = np.ones(X.shape[1], dtype=X.dtype)
y_offset = np.average(y, axis=0, weights=sample_weight)
y = y - y_offset
else:
X_offset = np.zeros(X.shape[1], dtype=X.dtype)
X_scale = np.ones(X.shape[1], dtype=X.dtype)
if y.ndim == 1:
y_offset = X.dtype.type(0)
else:
y_offset = np.zeros(y.shape[1], dtype=X.dtype)
return X, y, X_offset, y_offset, X_scale
# TODO: _rescale_data should be factored into _preprocess_data.
# Currently, the fact that sag implements its own way to deal with
# sample_weight makes the refactoring tricky.
def _rescale_data(X, y, sample_weight):
"""Rescale data sample-wise by square root of sample_weight.
For many linear models, this enables easy support for sample_weight.
Returns
-------
X_rescaled : {array-like, sparse matrix}
y_rescaled : {array-like, sparse matrix}
"""
n_samples = X.shape[0]
sample_weight = np.asarray(sample_weight)
if sample_weight.ndim == 0:
sample_weight = np.full(n_samples, sample_weight,
dtype=sample_weight.dtype)
sample_weight = np.sqrt(sample_weight)
sw_matrix = sparse.dia_matrix((sample_weight, 0),
shape=(n_samples, n_samples))
X = safe_sparse_dot(sw_matrix, X)
y = safe_sparse_dot(sw_matrix, y)
return X, y
class LinearModel(BaseEstimator, metaclass=ABCMeta):
"""Base class for Linear Models"""
@abstractmethod
def fit(self, X, y):
"""Fit model."""
def _decision_function(self, X):
check_is_fitted(self)
X = check_array(X, accept_sparse=['csr', 'csc', 'coo'])
return safe_sparse_dot(X, self.coef_.T,
dense_output=True) + self.intercept_
def predict(self, X):
"""
Predict using the linear model.
Parameters
----------
X : array-like or sparse matrix, shape (n_samples, n_features)
Samples.
Returns
-------
C : array, shape (n_samples,)
Returns predicted values.
"""
return self._decision_function(X)
_preprocess_data = staticmethod(_preprocess_data)
def _set_intercept(self, X_offset, y_offset, X_scale):
"""Set the intercept_
"""
if self.fit_intercept:
self.coef_ = self.coef_ / X_scale
self.intercept_ = y_offset - np.dot(X_offset, self.coef_.T)
else:
self.intercept_ = 0.
def _more_tags(self):
return {'requires_y': True}
# XXX Should this derive from LinearModel? It should be a mixin, not an ABC.
# Maybe the n_features checking can be moved to LinearModel.
class LinearClassifierMixin(ClassifierMixin):
"""Mixin for linear classifiers.
Handles prediction for sparse and dense X.
"""
def decision_function(self, X):
"""
Predict confidence scores for samples.
The confidence score for a sample is proportional to the signed
distance of that sample to the hyperplane.
Parameters
----------
X : array-like or sparse matrix, shape (n_samples, n_features)
Samples.
Returns
-------
array, shape=(n_samples,) if n_classes == 2 else (n_samples, n_classes)
Confidence scores per (sample, class) combination. In the binary
case, confidence score for self.classes_[1] where >0 means this
class would be predicted.
"""
check_is_fitted(self)
X = check_array(X, accept_sparse='csr')
n_features = self.coef_.shape[1]
if X.shape[1] != n_features:
raise ValueError("X has %d features per sample; expecting %d"
% (X.shape[1], n_features))
scores = safe_sparse_dot(X, self.coef_.T,
dense_output=True) + self.intercept_
return scores.ravel() if scores.shape[1] == 1 else scores
def predict(self, X):
"""
Predict class labels for samples in X.
Parameters
----------
X : array-like or sparse matrix, shape (n_samples, n_features)
Samples.
Returns
-------
C : array, shape [n_samples]
Predicted class label per sample.
"""
scores = self.decision_function(X)
if len(scores.shape) == 1:
indices = (scores > 0).astype(int)
else:
indices = scores.argmax(axis=1)
return self.classes_[indices]
def _predict_proba_lr(self, X):
"""Probability estimation for OvR logistic regression.
Positive class probabilities are computed as
1. / (1. + np.exp(-self.decision_function(X)));
multiclass is handled by normalizing that over all classes.
"""
prob = self.decision_function(X)
expit(prob, out=prob)
if prob.ndim == 1:
return np.vstack([1 - prob, prob]).T
else:
# OvR normalization, like LibLinear's predict_probability
prob /= prob.sum(axis=1).reshape((prob.shape[0], -1))
return prob
class SparseCoefMixin:
"""Mixin for converting coef_ to and from CSR format.
L1-regularizing estimators should inherit this.
"""
def densify(self):
"""
Convert coefficient matrix to dense array format.
Converts the ``coef_`` member (back) to a numpy.ndarray. This is the
default format of ``coef_`` and is required for fitting, so calling
this method is only required on models that have previously been
sparsified; otherwise, it is a no-op.
Returns
-------
self
Fitted estimator.
"""
msg = "Estimator, %(name)s, must be fitted before densifying."
check_is_fitted(self, msg=msg)
if sp.issparse(self.coef_):
self.coef_ = self.coef_.toarray()
return self
def sparsify(self):
"""
Convert coefficient matrix to sparse format.
Converts the ``coef_`` member to a scipy.sparse matrix, which for
L1-regularized models can be much more memory- and storage-efficient
than the usual numpy.ndarray representation.
The ``intercept_`` member is not converted.
Returns
-------
self
Fitted estimator.
Notes
-----
For non-sparse models, i.e. when there are not many zeros in ``coef_``,
this may actually *increase* memory usage, so use this method with
care. A rule of thumb is that the number of zero elements, which can
be computed with ``(coef_ == 0).sum()``, must be more than 50% for this
to provide significant benefits.
After calling this method, further fitting with the partial_fit
method (if any) will not work until you call densify.
"""
msg = "Estimator, %(name)s, must be fitted before sparsifying."
check_is_fitted(self, msg=msg)
self.coef_ = sp.csr_matrix(self.coef_)
return self
class LinearRegression(MultiOutputMixin, RegressorMixin, LinearModel):
"""
Ordinary least squares Linear Regression.
LinearRegression fits a linear model with coefficients w = (w1, ..., wp)
to minimize the residual sum of squares between the observed targets in
the dataset, and the targets predicted by the linear approximation.
Parameters
----------
fit_intercept : bool, default=True
Whether to calculate the intercept for this model. If set
to False, no intercept will be used in calculations
(i.e. data is expected to be centered).
normalize : bool, default=False
This parameter is ignored when ``fit_intercept`` is set to False.
If True, the regressors X will be normalized before regression by
subtracting the mean and dividing by the l2-norm.
If you wish to standardize, please use
:class:`~sklearn.preprocessing.StandardScaler` before calling ``fit``
on an estimator with ``normalize=False``.
copy_X : bool, default=True
If True, X will be copied; else, it may be overwritten.
n_jobs : int, default=None
The number of jobs to use for the computation. This will only provide
speedup for n_targets > 1 and sufficient large problems.
``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
``-1`` means using all processors. See :term:`Glossary <n_jobs>`
for more details.
positive : bool, default=False
When set to ``True``, forces the coefficients to be positive. This
option is only supported for dense arrays.
.. versionadded:: 0.24
Attributes
----------
coef_ : array of shape (n_features, ) or (n_targets, n_features)
Estimated coefficients for the linear regression problem.
If multiple targets are passed during the fit (y 2D), this
is a 2D array of shape (n_targets, n_features), while if only
one target is passed, this is a 1D array of length n_features.
rank_ : int
Rank of matrix `X`. Only available when `X` is dense.
singular_ : array of shape (min(X, y),)
Singular values of `X`. Only available when `X` is dense.
intercept_ : float or array of shape (n_targets,)
Independent term in the linear model. Set to 0.0 if
`fit_intercept = False`.
See Also
--------
Ridge : Ridge regression addresses some of the
problems of Ordinary Least Squares by imposing a penalty on the
size of the coefficients with l2 regularization.
Lasso : The Lasso is a linear model that estimates
sparse coefficients with l1 regularization.
ElasticNet : Elastic-Net is a linear regression
model trained with both l1 and l2 -norm regularization of the
coefficients.
Notes
-----
From the implementation point of view, this is just plain Ordinary
Least Squares (scipy.linalg.lstsq) or Non Negative Least Squares
(scipy.optimize.nnls) wrapped as a predictor object.
Examples
--------
>>> import numpy as np
>>> from sklearn.linear_model import LinearRegression
>>> X = np.array([[1, 1], [1, 2], [2, 2], [2, 3]])
>>> # y = 1 * x_0 + 2 * x_1 + 3
>>> y = np.dot(X, np.array([1, 2])) + 3
>>> reg = LinearRegression().fit(X, y)
>>> reg.score(X, y)
1.0
>>> reg.coef_
array([1., 2.])
>>> reg.intercept_
3.0...
>>> reg.predict(np.array([[3, 5]]))
array([16.])
"""
@_deprecate_positional_args
def __init__(self, *, fit_intercept=True, normalize=False, copy_X=True,
n_jobs=None, positive=False):
self.fit_intercept = fit_intercept
self.normalize = normalize
self.copy_X = copy_X
self.n_jobs = n_jobs
self.positive = positive
def fit(self, X, y, sample_weight=None):
"""
Fit linear model.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training data
y : array-like of shape (n_samples,) or (n_samples, n_targets)
Target values. Will be cast to X's dtype if necessary
sample_weight : array-like of shape (n_samples,), default=None
Individual weights for each sample
.. versionadded:: 0.17
parameter *sample_weight* support to LinearRegression.
Returns
-------
self : returns an instance of self.
"""
n_jobs_ = self.n_jobs
accept_sparse = False if self.positive else ['csr', 'csc', 'coo']
X, y = self._validate_data(X, y, accept_sparse=accept_sparse,
y_numeric=True, multi_output=True)
if sample_weight is not None:
sample_weight = _check_sample_weight(sample_weight, X,
dtype=X.dtype)
X, y, X_offset, y_offset, X_scale = self._preprocess_data(
X, y, fit_intercept=self.fit_intercept, normalize=self.normalize,
copy=self.copy_X, sample_weight=sample_weight,
return_mean=True)
if sample_weight is not None:
# Sample weight can be implemented via a simple rescaling.
X, y = _rescale_data(X, y, sample_weight)
if self.positive:
if y.ndim < 2:
self.coef_, self._residues = optimize.nnls(X, y)
else:
# scipy.optimize.nnls cannot handle y with shape (M, K)
outs = Parallel(n_jobs=n_jobs_)(
delayed(optimize.nnls)(X, y[:, j])
for j in range(y.shape[1]))
self.coef_, self._residues = map(np.vstack, zip(*outs))
elif sp.issparse(X):
X_offset_scale = X_offset / X_scale
def matvec(b):
return X.dot(b) - b.dot(X_offset_scale)
def rmatvec(b):
return X.T.dot(b) - X_offset_scale * np.sum(b)
X_centered = sparse.linalg.LinearOperator(shape=X.shape,
matvec=matvec,
rmatvec=rmatvec)
if y.ndim < 2:
out = sparse_lsqr(X_centered, y)
self.coef_ = out[0]
self._residues = out[3]
else:
# sparse_lstsq cannot handle y with shape (M, K)
outs = Parallel(n_jobs=n_jobs_)(
delayed(sparse_lsqr)(X_centered, y[:, j].ravel())
for j in range(y.shape[1]))
self.coef_ = np.vstack([out[0] for out in outs])
self._residues = np.vstack([out[3] for out in outs])
else:
self.coef_, self._residues, self.rank_, self.singular_ = \
linalg.lstsq(X, y)
self.coef_ = self.coef_.T
if y.ndim == 1:
self.coef_ = np.ravel(self.coef_)
self._set_intercept(X_offset, y_offset, X_scale)
return self
def _pre_fit(X, y, Xy, precompute, normalize, fit_intercept, copy,
check_input=True, sample_weight=None):
"""Aux function used at beginning of fit in linear models
Parameters
----------
order : 'F', 'C' or None, default=None
Whether X and y will be forced to be fortran or c-style. Only relevant
if sample_weight is not None.
"""
n_samples, n_features = X.shape
if sparse.isspmatrix(X):
# copy is not needed here as X is not modified inplace when X is sparse
precompute = False
X, y, X_offset, y_offset, X_scale = _preprocess_data(
X, y, fit_intercept=fit_intercept, normalize=normalize,
copy=False, return_mean=True, check_input=check_input)
else:
# copy was done in fit if necessary
X, y, X_offset, y_offset, X_scale = _preprocess_data(
X, y, fit_intercept=fit_intercept, normalize=normalize, copy=copy,
check_input=check_input, sample_weight=sample_weight)
if sample_weight is not None:
X, y = _rescale_data(X, y, sample_weight=sample_weight)
if hasattr(precompute, '__array__') and (
fit_intercept and not np.allclose(X_offset, np.zeros(n_features)) or
normalize and not np.allclose(X_scale, np.ones(n_features))):
warnings.warn("Gram matrix was provided but X was centered"
" to fit intercept, "
"or X was normalized : recomputing Gram matrix.",
UserWarning)
# recompute Gram
precompute = 'auto'
Xy = None
# precompute if n_samples > n_features
if isinstance(precompute, str) and precompute == 'auto':
precompute = (n_samples > n_features)
if precompute is True:
# make sure that the 'precompute' array is contiguous.
precompute = np.empty(shape=(n_features, n_features), dtype=X.dtype,
order='C')
np.dot(X.T, X, out=precompute)
if not hasattr(precompute, '__array__'):
Xy = None # cannot use Xy if precompute is not Gram
if hasattr(precompute, '__array__') and Xy is None:
common_dtype = np.find_common_type([X.dtype, y.dtype], [])
if y.ndim == 1:
# Xy is 1d, make sure it is contiguous.
Xy = np.empty(shape=n_features, dtype=common_dtype, order='C')
np.dot(X.T, y, out=Xy)
else:
# Make sure that Xy is always F contiguous even if X or y are not
# contiguous: the goal is to make it fast to extract the data for a
# specific target.
n_targets = y.shape[1]
Xy = np.empty(shape=(n_features, n_targets), dtype=common_dtype,
order='F')
np.dot(y.T, X, out=Xy.T)
return X, y, X_offset, y_offset, X_scale, precompute, Xy | sample_weight : numpy array of shape (n_samples,)
The weight of each sample |
177.3241-find-files-with-a-given-list-of-filename-extensions.py | """Find files with a given list of filename extensions.
Construct a list _L that contains all filenames that have the extension ".jpg" , ".jpeg" or ".png" in directory _D and all it's subdirectories.
Source: Bart
"""
# Implementation author: charlax | # Created on 2019-09-27T11:33:27.420533Z
# Last modified on 2019-09-27T11:33:27.420533Z
# Version 1
import glob
import itertools
list(itertools.chain(*(glob.glob("*/**.%s" % ext) for ext in ["jpg", "jpeg", "png"]))) | |
WalletController.js | import ObservableStore from 'obs-store';
import { seedUtils } from '@decentralchain/waves-transactions';
import { decrypt, encrypt } from '../lib/encryprtor';
import { Wallet } from '../lib/wallet';
const { Seed } = seedUtils;
export class | {
constructor(options = {}) {
const defaults = {
initialized: false,
};
const initState = Object.assign({}, defaults, options.initState);
this.store = new ObservableStore(initState);
this.store.updateState({ locked: true });
this.password = null;
this.wallets = [];
this.getNetwork = options.getNetwork;
this.getNetworks = options.getNetworks;
this.getNetworkCode = options.getNetworkCode;
this.trashControl = options.trash;
}
// Public
addWallet(options) {
if (this.store.getState().locked) throw new Error('App is locked');
let user;
switch (options.type) {
case 'seed':
const networkCode = this.getNetworkCode(options.network);
const seed = new Seed(options.seed, networkCode);
user = {
seed: seed.phrase,
publicKey: seed.keyPair.publicKey,
address: seed.address,
networkCode: options.networkCode || networkCode,
network: options.network,
type: options.type,
name: options.name,
};
break;
default:
throw new Error(`Unsupported type: ${options.type}`);
}
const wallet = new Wallet(user);
this._checkForDuplicate(wallet.getAccount().address, user.network);
this.wallets.push(wallet);
this._saveWallets();
}
removeWallet(address, network) {
if (this.store.getState().locked) throw new Error('App is locked');
const wallet = this.getWalletsByNetwork(network).find(
wallet => wallet.getAccount().address === address
);
this._walletToTrash(wallet);
this.wallets = this.wallets.filter(w => {
return w !== wallet;
});
this._saveWallets();
}
getAccounts() {
return this.wallets.map(wallet => wallet.getAccount());
}
lock() {
this.password = null;
this.wallets = [];
if (!this.store.getState().locked) {
this.store.updateState({ locked: true });
}
}
unlock(password) {
this._restoreWallets(password);
this.password = password;
this._migrateWalletsNetwork();
this.store.updateState({ locked: false });
}
isLocked() {
return this.store.getState().locked;
}
initVault(password) {
if (!password || typeof password !== 'string') {
throw new Error('Password is needed to init vault');
}
(this.wallets || []).forEach(wallet => this._walletToTrash(wallet));
this.password = password;
this.wallets = [];
this._saveWallets();
this.store.updateState({ locked: false, initialized: true });
}
deleteVault() {
(this.wallets || []).forEach(wallet => this._walletToTrash(wallet));
this.password = null;
this.wallets = [];
this.store.updateState({
locked: true,
initialized: false,
vault: undefined,
});
}
newPassword(oldPassword, newPassword) {
if (
!oldPassword ||
!newPassword ||
typeof oldPassword !== 'string' ||
typeof newPassword !== 'string'
) {
throw new Error('Password is required');
}
this._restoreWallets(oldPassword);
this.password = newPassword;
this._saveWallets();
}
/**
* Returns account seed
* @param {string} address - wallet address
* @param {string} password - application password
* @returns {string} encrypted seed
*/
exportAccount(address, password, network) {
if (!password) throw new Error('Password is required');
this._restoreWallets(password);
const wallet = this.getWalletsByNetwork(network).find(
wallet => wallet.getAccount().address === address
);
if (!wallet)
throw new Error(`Wallet not found for address: ${address} in ${network}`);
return wallet.getSecret();
}
exportSeed(address, network) {
const wallet = this._findWallet(address, network);
if (!wallet)
throw new Error(`Wallet not found for address: ${address} in ${network}`);
const seed = new Seed(wallet.user.seed);
return seed.encrypt(this.password, 5000);
}
/**
* Returns encrypted with current password account seed
* @param {string} address - wallet address
* @returns {string} encrypted seed
*/
encryptedSeed(address, network) {
const wallet = this._findWallet(address, network);
const seed = wallet.getSecret();
return Seed.encryptSeedPhrase(seed, this.password);
}
updateNetworkCode(network, code) {
code = code || this.getNetworkCode(network);
const wallets = this.getWalletsByNetwork(network);
wallets.forEach(wallet => {
if (wallet.user.networkCode !== code) {
const seed = new Seed(wallet.user.seed, code);
wallet.user.network = network;
wallet.user.networkCode = code;
wallet.user.address = seed.address;
}
});
if (wallets.length) {
this._saveWallets();
}
}
getWalletsByNetwork(network) {
return this.wallets.filter(wallet => wallet.isMyNetwork(network));
}
_walletToTrash(wallet) {
const walletsData = wallet && wallet.serialize && wallet.serialize();
if (walletsData) {
const saveData = {
walletsData: this.password
? encrypt(walletsData, this.password)
: walletsData,
address: wallet.address,
};
this.trashControl.addData(saveData);
}
}
_migrateWalletsNetwork() {
const networks = this.getNetworks().reduce((acc, net) => {
acc[net.code] = net.name;
return acc;
}, Object.create(null));
const wallets = this.wallets.map(wallet => wallet.serialize());
if (!wallets.find(item => !item.network)) {
return null;
}
const walletsData = this.wallets.map(wallet => {
const data = wallet.serialize();
if (!data.network) {
data.network = networks[data.networkCode];
}
return data;
});
this.wallets = walletsData.map(user => new Wallet(user));
this._saveWallets();
}
/**
* Signs transaction
* @param {string} address - wallet address
* @param {object} tx - transaction to sign
* @param {object} network
* @returns {Promise<string>} signed transaction as json string
*/
async signTx(address, tx, network) {
const wallet = this._findWallet(address, network);
return await wallet.signTx(tx);
}
async signWaves(type, data, address, network) {
const wallet = this._findWallet(address, network);
return await wallet.signWaves(type, data);
}
/**
* Signs transaction
* @param {string} address - wallet address
* @param {array} bytes - array of bytes
* @returns {Promise<string>} signed transaction as json string
*/
async signBytes(address, bytes, network) {
const wallet = this._findWallet(address, network);
return await wallet.signBytes(bytes);
}
/**
* Signs request
* @param {string} address - wallet address
* @param {object} request - transaction to sign
* @returns {Promise<string>} signature
*/
async signRequest(address, request, network) {
const wallet = this._findWallet(address, network);
return wallet.signRequest(request);
}
/**
* Signs request
* @param {string} address - wallet address
* @param {object} authData - object, representing auth request
* @returns {Promise<object>} object, representing auth response
*/
async auth(address, authData, network) {
const wallet = this._findWallet(address, network);
const signature = await wallet.signRequest(authData);
const { publicKey } = wallet.getAccount();
const { host, name, prefix, version } = authData.data;
return {
host,
name,
prefix,
address,
publicKey,
signature,
version,
};
}
async getKEK(address, network, publicKey, prefix) {
const wallet = this._findWallet(address, network);
return await wallet.getKEK(publicKey, prefix);
}
async encryptMessage(address, network, message, publicKey, prefix) {
const wallet = this._findWallet(address, network);
return await wallet.encryptMessage(message, publicKey, prefix);
}
async decryptMessage(address, network, message, publicKey, prefix) {
const wallet = this._findWallet(address, network);
return await wallet.decryptMessage(message, publicKey, prefix);
}
// Private
_checkForDuplicate(address, network) {
if (
this.getWalletsByNetwork(network).find(
account => account.address === address
)
) {
throw new Error(`Account with address ${address} already exists`);
}
}
_saveWallets() {
const walletsData = this.wallets.map(wallet => wallet.serialize());
this.store.updateState({ vault: encrypt(walletsData, this.password) });
}
_restoreWallets(password) {
const decryptedData = decrypt(this.store.getState().vault, password);
this.wallets = decryptedData.map(user => new Wallet(user));
}
_findWallet(address, network) {
if (this.store.getState().locked) throw new Error('App is locked');
const wallet = this.getWalletsByNetwork(network).find(
wallet => wallet.getAccount().address === address
);
if (!wallet) throw new Error(`Wallet not found for address ${address}`);
return wallet;
}
}
| WalletController |
service.py | import json
import pathlib
import sys
import time
from typing import Sequence
import bentoml
from bentoml.adapters import (
DataframeInput,
FileInput,
ImageInput,
JsonInput,
MultiImageInput,
)
from bentoml.frameworks.sklearn import SklearnModelArtifact
from bentoml.handlers import DataframeHandler # deprecated
from bentoml.service.artifacts.pickle import PickleArtifact
from bentoml.types import InferenceResult, InferenceTask
@bentoml.env(infer_pip_packages=True)
@bentoml.artifacts([PickleArtifact("model"), SklearnModelArtifact('sk_model')])
class ExampleService(bentoml.BentoService):
"""
Example BentoService class made for testing purpose
"""
@bentoml.api(
input=DataframeInput(dtype={"col1": "int"}),
mb_max_latency=1000,
mb_max_batch_size=2000,
batch=True,
)
def predict_dataframe(self, df):
return self.artifacts.model.predict_dataframe(df)
@bentoml.api(DataframeHandler, dtype={"col1": "int"}, batch=True) # deprecated
def | (self, df):
return self.artifacts.model.predict_dataframe(df)
@bentoml.api(
input=MultiImageInput(input_names=('original', 'compared')), batch=True
)
def predict_multi_images(self, originals, compareds):
return self.artifacts.model.predict_multi_images(originals, compareds)
@bentoml.api(input=ImageInput(), batch=True)
def predict_image(self, images):
return self.artifacts.model.predict_image(images)
@bentoml.api(
input=JsonInput(), mb_max_latency=1000, mb_max_batch_size=2000, batch=True,
)
def predict_with_sklearn(self, jsons):
return self.artifacts.sk_model.predict(jsons)
@bentoml.api(input=FileInput(), batch=True)
def predict_file(self, files):
return self.artifacts.model.predict_file(files)
@bentoml.api(input=JsonInput(), batch=True)
def predict_json(self, input_datas):
return self.artifacts.model.predict_json(input_datas)
@bentoml.api(input=JsonInput(), batch=True)
def predict_strict_json(self, input_datas, tasks: Sequence[InferenceTask] = None):
filtered_jsons = []
for j, t in zip(input_datas, tasks):
if t.http_headers.content_type != "application/json":
t.discard(http_status=400, err_msg="application/json only")
else:
filtered_jsons.append(j)
return self.artifacts.model.predict_json(filtered_jsons)
@bentoml.api(input=JsonInput(), batch=True)
def predict_direct_json(self, input_datas, tasks: Sequence[InferenceTask] = None):
filtered_jsons = []
for j, t in zip(input_datas, tasks):
if t.http_headers.content_type != "application/json":
t.discard(http_status=400, err_msg="application/json only")
else:
filtered_jsons.append(j)
rets = self.artifacts.model.predict_json(filtered_jsons)
return [
InferenceResult(http_status=200, data=json.dumps(result)) for result in rets
]
@bentoml.api(input=JsonInput(), mb_max_latency=10000 * 1000, batch=True)
def echo_with_delay(self, input_datas):
data = input_datas[0]
time.sleep(data['b'] + data['a'] * len(input_datas))
return input_datas
if __name__ == "__main__":
artifacts_path = sys.argv[1]
bento_dist_path = sys.argv[2]
service = ExampleService()
service.artifacts.load_all(artifacts_path)
pathlib.Path(bento_dist_path).mkdir(parents=True, exist_ok=True)
service.save_to_dir(bento_dist_path)
| predict_dataframe_v1 |
sdk_fetch_coverage_tools.py | #!/usr/bin/python
import os
import sdk_common
# Block in charge of fetching code coverage tools
class SDKCoverageToolsFetcher(sdk_common.BuildStepUsingGradle):
def __init__(self, logger=None):
super(SDKCoverageToolsFetcher, self).__init__('SDK Coverage tools fetch', logger)
self.is_code_coverage = self.common_config.get_config().should_perform_code_coverage()
self.artifacts_parser = self.common_config.get_config().get_new_artifact_log_parser(self)
self.jacoco_cli_name = 'jacococli.jar'
def retrieve_folder_location(self, key):
if not key:
return None
self.artifacts_parser.load()
return self.clean_path(
self.artifacts_parser.get_property(key),
False)
def check_whether_coverage_result_folder_has_been_created(self):
code_coverage_result_dir = self.retrieve_folder_location('SDK_COVERAGE_RESULTS_DIR')
return False if not code_coverage_result_dir else os.path.exists(code_coverage_result_dir)
def check_whether_tools_have_been_copied(self):
code_coverage_tools_dir = self.retrieve_folder_location('SDK_COVERAGE_TOOLS_DIR')
return False if not code_coverage_tools_dir else (
os.path.exists(code_coverage_tools_dir) and len(
os.listdir(code_coverage_tools_dir)) >= 2) # TODO change if fewer tools are used
def has_already_been_run(self):
return self.check_whether_coverage_result_folder_has_been_created() and self.check_whether_tools_have_been_copied()
def execute(self):
self.print_title()
try: | else:
self.log_info("Tools are already present.")
except:
self.log_error('Failed to retrieving code coverage tools')
return False
self.log_info("Done.")
return True | if self.is_code_coverage:
self.log_info("Retrieving code coverage tools")
if not self.has_already_been_run():
self.execute_gradle_task("copyCoverageAgent") |
transformer_units.py | # Copyright 2017 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.
# ==============================================================================
"""Network units implementing the Transformer network (Vaswani et al. 2017).
Heavily adapted from the tensor2tensor implementation of the Transformer,
described in detail here: https://arxiv.org/abs/1706.03762.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
from dragnn.python import network_units
def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4):
"""Adds a bunch of sinusoids of different frequencies to a Tensor.
Each channel of the input Tensor is incremented by a sinusoid of a different
frequency and phase.
This allows attention to learn to use absolute and relative positions.
Timing signals should be added to some precursors of both the query and the
memory inputs to attention.
The use of relative position is possible because sin(x+y) and cos(x+y) can be
expressed in terms of y, sin(x) and cos(x).
In particular, we use a geometric sequence of timescales starting with
min_timescale and ending with max_timescale. The number of different
timescales is equal to channels / 2. For each timescale, we
generate the two sinusoidal signals sin(timestep/timescale) and
cos(timestep/timescale). All of these sinusoids are concatenated in
the channels dimension.
Args:
x: a Tensor with shape [batch, length, channels]
min_timescale: a float
max_timescale: a float
Returns:
a Tensor the same shape as x.
"""
length = tf.shape(x)[1]
channels = tf.shape(x)[2]
pos = tf.to_float(tf.range(length))
num_timescales = channels // 2
log_timescale_increment = (
np.log(float(max_timescale) / float(min_timescale)) /
(tf.to_float(num_timescales) - 1))
inv_timescales = min_timescale * tf.exp(
tf.to_float(tf.range(num_timescales)) * -log_timescale_increment)
scaled_time = tf.expand_dims(pos, 1) * tf.expand_dims(inv_timescales, 0)
signal = tf.concat([tf.sin(scaled_time), tf.cos(scaled_time)], axis=1)
signal = tf.pad(signal, [[0, 0], [0, tf.mod(channels, 2)]])
signal = tf.reshape(signal, [1, length, channels])
return x + signal
def split_last_dimension(x, n):
"""Partitions x so that the last dimension becomes two dimensions.
The first of these two dimensions is n.
Args:
x: a Tensor with shape [..., m]
n: an integer.
Returns:
a Tensor with shape [..., n, m/n]
"""
old_shape = x.get_shape().dims
last = old_shape[-1]
new_shape = old_shape[:-1] + [n] + [last // n if last else None]
ret = tf.reshape(x, tf.concat([tf.shape(x)[:-1], [n, -1]], 0))
ret.set_shape(new_shape)
return ret
def combine_last_two_dimensions(x):
"""Reshape x so that the last two dimensions become one.
Args:
x: a Tensor with shape [..., a, b]
Returns:
a Tensor with shape [..., ab]
"""
old_shape = x.get_shape().dims
a, b = old_shape[-2:]
new_shape = old_shape[:-2] + [a * b if a and b else None]
ret = tf.reshape(x, tf.concat([tf.shape(x)[:-2], [-1]], 0))
ret.set_shape(new_shape)
return ret
def split_heads(x, num_heads):
"""Splits channels (dimension 3) into multiple heads (becomes dimension 1).
Args:
x: a Tensor with shape [batch, length, channels]
num_heads: an integer
Returns:
a Tensor with shape [batch, num_heads, length, channels / num_heads]
"""
return tf.transpose(split_last_dimension(x, num_heads), [0, 2, 1, 3])
def combine_heads(x):
"""Performs the inverse of split_heads.
Args:
x: a Tensor with shape [batch, num_heads, length, channels / num_heads]
Returns:
a Tensor with shape [batch, length, channels]
"""
return combine_last_two_dimensions(tf.transpose(x, [0, 2, 1, 3]))
def compute_padding_mask(lengths):
"""Computes an additive mask for padding.
Given the non-padded sequence lengths for the batch, computes a mask that will
send padding attention to 0 when added to logits before applying a softmax.
Args:
lengths: a Tensor containing the sequence length of each batch element
Returns:
A Tensor of shape [batch_size, 1, 1, max_len] with zeros in non-padding
entries and -1e9 in padding entries.
"""
lengths = tf.reshape(lengths, [-1])
mask = tf.sequence_mask(lengths)
# This will be used as an additive mask, so we want the inverse of the mask
# produced by tf.sequence_mask.
inv_mask = tf.to_float(tf.logical_not(mask))
mem_padding = inv_mask * -1e9
return tf.expand_dims(tf.expand_dims(mem_padding, 1), 1)
def | (queries, keys, values, dropout_keep_rate, bias=None):
"""Computes dot-product attention.
Args:
queries: a Tensor with shape [batch, heads, seq_len, depth_keys]
keys: a Tensor with shape [batch, heads, seq_len, depth_keys]
values: a Tensor with shape [batch, heads, seq_len, depth_values]
dropout_keep_rate: dropout proportion of units to keep
bias: A bias to add before applying the softmax, or None. This can be used
for masking padding in the batch.
Returns:
A Tensor with shape [batch, heads, seq_len, depth_values].
"""
# [batch, num_heads, seq_len, seq_len]
logits = tf.matmul(queries, keys, transpose_b=True)
if bias is not None:
logits += bias
attn_weights = tf.nn.softmax(logits)
# Dropping out the attention links for each of the heads
attn_weights = network_units.maybe_apply_dropout(attn_weights,
dropout_keep_rate,
False)
return tf.matmul(attn_weights, values)
def residual(old_input, new_input, dropout_keep_rate, layer_norm):
"""Residual layer combining old_input and new_input.
Computes old_input + dropout(new_input) if layer_norm is None; otherwise:
layer_norm(old_input + dropout(new_input)).
Args:
old_input: old float32 Tensor input to residual layer
new_input: new float32 Tensor input to residual layer
dropout_keep_rate: dropout proportion of units to keep
layer_norm: network_units.LayerNorm to apply to residual output, or None
Returns:
float32 Tensor output of residual layer.
"""
res_sum = old_input + network_units.maybe_apply_dropout(new_input,
dropout_keep_rate,
False)
return layer_norm.normalize(res_sum) if layer_norm else res_sum
def mlp(component, input_tensor, dropout_keep_rate, depth):
"""Feed the input through an MLP.
Each layer except the last is followed by a ReLU activation and dropout.
Args:
component: the DRAGNN Component containing parameters for the MLP
input_tensor: the float32 Tensor input to the MLP.
dropout_keep_rate: dropout proportion of units to keep
depth: depth of the MLP.
Returns:
the float32 output Tensor
"""
for i in range(depth):
ff_weights = component.get_variable('ff_weights_%d' % i)
input_tensor = tf.nn.conv2d(input_tensor,
ff_weights,
[1, 1, 1, 1],
padding='SAME')
# Apply ReLU and dropout to all but the last layer
if i < depth - 1:
input_tensor = tf.nn.relu(input_tensor)
input_tensor = network_units.maybe_apply_dropout(input_tensor,
dropout_keep_rate,
False)
return input_tensor
class TransformerEncoderNetwork(network_units.NetworkUnitInterface):
"""Implementation of the Transformer network encoder."""
def __init__(self, component):
"""Initializes parameters for this Transformer unit.
Args:
component: parent ComponentBuilderBase object.
Parameters used to construct the network:
num_layers: number of transformer layers (attention + MLP)
hidden_size: size of hidden layers in MLPs
filter_size: filter width for each attention head
num_heads: number of attention heads
residual_dropout: dropout keep rate for residual layers
attention_dropout: dropout keep rate for attention weights
mlp_dropout: dropout keep rate for mlp layers
initialization: initialization scheme to use for model parameters
bias_init: initial value for bias parameters
scale_attention: whether to scale attention parameters by filter_size^-0.5
layer_norm_residuals: whether to perform layer normalization on residual
layers
timing_signal: whether to add a position-wise timing signal to the input
kernel: kernel width in middle MLP layers
mlp_layers: number of MLP layers. Must be >= 2.
Raises:
ValueError: if mlp_layers < 2.
The input depth of the first layer is inferred from the total concatenated
size of the input features, minus 1 to account for the sequence lengths.
Hyperparameters used:
dropout_rate: The probability that an input is not dropped. This is the
default when the |dropout_keep_prob| parameter is unset.
"""
super(TransformerEncoderNetwork, self).__init__(component)
default_dropout_rate = component.master.hyperparams.dropout_rate
self._attrs = network_units.get_attrs_with_defaults(
component.spec.network_unit.parameters, defaults={
'num_layers': 4,
'hidden_size': 256,
'filter_size': 64,
'num_heads': 8,
'residual_drop': default_dropout_rate,
'attention_drop': default_dropout_rate,
'mlp_drop': default_dropout_rate,
'initialization': 'xavier',
'bias_init': 0.001,
'scale_attention': True,
'layer_norm_residuals': True,
'timing_signal': True,
'kernel': 1,
'mlp_layers': 2})
self._num_layers = self._attrs['num_layers']
self._hidden_size = self._attrs['hidden_size']
self._filter_size = self._attrs['filter_size']
self._num_heads = self._attrs['num_heads']
self._residual_dropout = self._attrs['residual_drop']
self._attention_dropout = self._attrs['attention_drop']
self._mlp_dropout = self._attrs['mlp_drop']
self._initialization = self._attrs['initialization']
self._bias_init = self._attrs['bias_init']
self._scale_attn = self._attrs['scale_attention']
self._layer_norm_res = self._attrs['layer_norm_residuals']
self._timing_signal = self._attrs['timing_signal']
self._kernel = self._attrs['kernel']
self._mlp_depth = self._attrs['mlp_layers']
if self._mlp_depth < 2:
raise ValueError('TransformerEncoderNetwork needs mlp_layers >= 2')
self._combined_filters = self._num_heads * self._filter_size
self._weights = []
self._biases = []
self._layer_norms = {}
# Hacky: one dimension comes from the lengths input; subtract it.
self._concatenated_input_dim -= 1
# Initial projection of inputs, this is mainly to project input down to the
# right size for residual layers
proj_shape = [1, 1, self._concatenated_input_dim, self._combined_filters]
self._weights.append(
network_units.add_var_initialized('init_proj', proj_shape,
self._initialization))
self._biases.append(tf.get_variable('init_bias',
self._combined_filters,
initializer=tf.constant_initializer(
self._bias_init),
dtype=tf.float32))
for i in range(self._num_layers):
with tf.variable_scope('transform_%d' % i):
# Attention weights: 3 * self.combined_filters = (q, k, v)
# We assume that q, k and v all have the same dimension
attn_shape = [1, 1, self._combined_filters, 3 * self._combined_filters]
self._weights.append(
network_units.add_var_initialized('attn_weights',
attn_shape,
self._initialization))
# Attention final projection weights
proj_shape = [1, 1, self._combined_filters, self._combined_filters]
self._weights.append(
network_units.add_var_initialized('proj_weights',
proj_shape,
self._initialization))
# MLP weights
with tf.variable_scope('mlp'):
ff_shape = [1, 1, self._combined_filters, self._hidden_size]
self._weights.append(
network_units.add_var_initialized('ff_weights_0',
ff_shape,
self._initialization))
ff_shape = [1, self._kernel, self._hidden_size, self._hidden_size]
for j in range(1, self._mlp_depth - 1):
self._weights.append(
network_units.add_var_initialized('ff_weights_%d' % j,
ff_shape,
self._initialization))
ff_shape = [1, 1, self._hidden_size, self._combined_filters]
self._weights.append(
network_units.add_var_initialized('ff_weights_%d' %
(self._mlp_depth - 1),
ff_shape,
self._initialization))
# Layer normalization for residual layers
if self._layer_norm_res:
attn_layer_norm = network_units.LayerNorm(component,
'attn_layer_norm_%d' % i,
self._combined_filters,
tf.float32)
self._layer_norms['attn_layer_norm_%d' % i] = attn_layer_norm
ff_layer_norm = network_units.LayerNorm(component,
'ff_layer_norm_%d' % i,
self._combined_filters,
tf.float32)
self._layer_norms['ff_layer_norm_%d' % i] = ff_layer_norm
# Layer norm parameters are not added to self._weights,
# which means that they are not l2 regularized
self._params.extend(attn_layer_norm.params + ff_layer_norm.params)
self._params.extend(self._weights)
self._params.extend(self._biases)
self._regularized_weights.extend(self._weights)
self._layers.append(
network_units.Layer(component, name='transformer_output',
dim=self._combined_filters))
def create(self,
fixed_embeddings,
linked_embeddings,
context_tensor_arrays,
attention_tensor,
during_training,
stride=None):
"""Requires |stride|; otherwise see base class."""
del context_tensor_arrays, attention_tensor
if stride is None:
raise RuntimeError("TransformerEncoderNetwork needs 'stride' and must be "
"called in the bulk feature extractor component.")
lengths = network_units.lookup_named_tensor('lengths', linked_embeddings)
lengths_s = tf.to_int32(tf.squeeze(lengths.tensor, [1]))
num_steps = tf.reduce_max(lengths_s)
in_tensor = network_units.lookup_named_tensor('features', linked_embeddings)
input_tensor = tf.reshape(in_tensor.tensor, [stride, num_steps, -1])
if self._timing_signal:
input_tensor = add_timing_signal_1d(input_tensor)
# Adds a dimension for conv2d
input_tensor = tf.expand_dims(input_tensor, 1)
# For masking padding in attention
mask = compute_padding_mask(lengths_s)
conv = tf.nn.conv2d(input_tensor,
self._component.get_variable('init_proj'),
[1, 1, 1, 1], padding='SAME')
conv = tf.nn.bias_add(conv, self._component.get_variable('init_bias'))
for i in range(self._num_layers):
with tf.variable_scope('transform_%d' % i, reuse=True):
attn_weights = self._component.get_variable('attn_weights')
attn_combined = tf.nn.conv2d(conv,
attn_weights,
[1, 1, 1, 1],
padding='SAME')
attn_combined = tf.squeeze(attn_combined, 1)
# Splits combined projection into queries, keys, and values
queries, keys, values = tf.split(attn_combined,
[self._combined_filters]*3,
axis=2)
# Splits each of queries, keys, values into attention heads
queries = split_heads(queries, self._num_heads)
keys = split_heads(keys, self._num_heads)
values = split_heads(values, self._num_heads)
if self._scale_attn:
queries *= self._filter_size**-0.5
# Performs dot product attention and concatenates the resulting heads
attended = dot_product_attention(queries, keys, values,
self._attention_dropout, mask)
attended = combine_heads(attended)
# Projects combined heads
attended = tf.expand_dims(attended, 1)
proj = tf.nn.conv2d(attended,
self._component.get_variable('proj_weights'),
[1, 1, 1, 1],
padding='SAME')
# Residual connection between input and attended input
attn_layer_norm_params = None
if self._layer_norm_res:
attn_layer_norm_params = self._layer_norms['attn_layer_norm_%d' % i]
proj_res = residual(conv, proj, self._residual_dropout,
attn_layer_norm_params)
# Feed forward
with tf.variable_scope('mlp'):
ff = mlp(self._component, proj_res, self._mlp_dropout,
self._mlp_depth)
# Residual connection between attended input and feed forward layers
ff_layer_norm_params = None
if self._layer_norm_res:
ff_layer_norm_params = self._layer_norms['ff_layer_norm_%d' % i]
conv = residual(proj_res, ff, self._residual_dropout,
ff_layer_norm_params)
return [tf.reshape(conv, [-1, self._combined_filters],
name='reshape_activations')]
class PairwiseBilinearLabelNetwork(network_units.NetworkUnitInterface):
r"""Network unit that computes pairwise bilinear label scores.
Given source and target representations for each token, this network unit
computes bilinear scores for each label for each of the N^2 combinations of
source and target tokens, rather than for only N already-computed
source/target pairs (as is performed by the biaffine_units). The output is
suitable as input to e.g. the heads_labels transition system.
Specifically, a weights tensor W called `bilinear' is used to compute bilinear
scores B for input tensors S and T:
B_{bnml} = \sum_{i,j} S_{bni} W_{ilj} T{bmj}
for batches b, steps n and m and labels l.
Parameters:
num_labels: The number of dependency labels, L.
Features:
sources: [B * N, S] matrix of batched activations for source tokens.
targets: [B * N, T] matrix of batched activations for target tokens.
Layers:
bilinear_scores: [B * N, N * L] matrix where vector b*N*N*L+t contains
per-label scores for all N possible arcs from token t in
batch b.
"""
def __init__(self, component):
super(PairwiseBilinearLabelNetwork, self).__init__(component)
parameters = component.spec.network_unit.parameters
self._num_labels = int(parameters['num_labels'])
self._source_dim = self._linked_feature_dims['sources']
self._target_dim = self._linked_feature_dims['targets']
self._weights = []
self._weights.append(
network_units.add_var_initialized('bilinear',
[self._source_dim,
self._num_labels,
self._target_dim],
'xavier'))
self._params.extend(self._weights)
self._regularized_weights.extend(self._weights)
self._layers.append(network_units.Layer(component,
name='bilinear_scores',
dim=self._num_labels))
def create(self,
fixed_embeddings,
linked_embeddings,
context_tensor_arrays,
attention_tensor,
during_training,
stride=None):
"""Requires |stride|; otherwise see base class."""
del context_tensor_arrays, attention_tensor
if stride is None:
raise RuntimeError("PairwiseBilinearLabelNetwork needs 'stride' and must "
"be called in a bulk component.")
sources = network_units.lookup_named_tensor('sources', linked_embeddings)
sources_tensor = tf.reshape(sources.tensor, [stride, -1, self._source_dim])
targets = network_units.lookup_named_tensor('targets', linked_embeddings)
targets_tensor = tf.reshape(targets.tensor, [stride, -1, self._target_dim])
# Dimensions: source_dim x num_labels x target_dim
bilinear_params = self._component.get_variable('bilinear')
# Ensures that num_steps is the same for both inputs
num_steps = tf.shape(sources_tensor)[1]
with tf.control_dependencies([tf.assert_equal(num_steps,
tf.shape(targets_tensor)[1],
name='num_steps_mismatch')]):
# Dimensions:
# (batch_size*num_steps x source_dim) *
# (source_dim x num_labels*target_dim)
# = (batch_size*num_steps x num_labels*target_dim)
lin = tf.matmul(tf.reshape(sources_tensor, [-1, self._source_dim]),
tf.reshape(bilinear_params, [self._source_dim, -1]))
# (batch_size x num_steps*num_labels x target_dim) *
# (batch_size x num_steps x target_dim)^T
# = (batch_size x num_steps*num_labels x num_steps)
bilin = tf.matmul(
tf.reshape(lin, [-1, num_steps*self._num_labels, self._target_dim]),
targets_tensor, transpose_b=True)
# (batch_size x num_steps*num_labels x num_steps) ->
# (batch_size x num_steps x num_steps*num_labels)
scores = tf.transpose(bilin, [0, 2, 1])
return [tf.reshape(scores, [-1, num_steps*self._num_labels],
name='reshape_activations')]
| dot_product_attention |
account_analytic_line.py | # Copyright 2016 Tecnativa - Antonio Espinosa
# Copyright 2016 Tecnativa - Sergio Teruel | from odoo import api, models
class AccountAnalyticLine(models.Model):
_inherit = "account.analytic.line"
@api.onchange("project_id")
def _onchange_project_id(self):
task = self.task_id
res = super()._onchange_project_id()
if res is None:
res = {}
if self.project_id: # Show only opened tasks
task_domain = [
("project_id", "=", self.project_id.id),
("stage_id.is_closed", "=", False),
]
res_domain = res.setdefault("domain", {})
res_domain.update({"task_id": task_domain})
else: # Reset domain for allowing selection of any task
res["domain"] = {"task_id": []}
if task.project_id == self.project_id:
# Restore previous task if belongs to the same project
self.task_id = task
return res | # Copyright 2016-2018 Tecnativa - Pedro M. Baeza
# Copyright 2019 Brainbean Apps (https://brainbeanapps.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
|
iris.rs | extern crate examples_common;
extern crate forester;
extern crate num_traits;
extern crate openml;
extern crate rand;
#[macro_use]
extern crate serde_derive;
use std::fmt;
use num_traits::ToPrimitive;
use rand::{thread_rng, Rng};
use openml::MeasureAccumulator;
use forester::categorical::{Categorical, CatCount};
use forester::criterion::GiniCriterion;
use forester::data::{SampleDescription, TrainingData};
use forester::dforest::DeterministicForestBuilder;
use forester::dtree::DeterministicTreeBuilder;
use forester::split::BestRandomSplit;
use examples_common::rgb_classes::ClassCounts;
#[derive(Debug, Copy, Clone, Deserialize, Eq, PartialEq)]
enum Iris {
None,
#[serde(rename = "Iris-setosa")]
Setosa,
#[serde(rename = "Iris-versicolor")]
Versicolor,
#[serde(rename = "Iris-virginica")]
Virginica,
}
impl<'a> From<&'a f64> for Iris {
fn from(f: &'a f64) -> Iris {
Iris::from_usize(*f as usize)
}
}
impl Categorical for Iris {
fn as_usize(&self) -> usize {
match *self {
Iris::Setosa => 0,
Iris::Versicolor => 1,
Iris::Virginica => 2,
Iris::None => panic!("invalid Iris")
}
}
fn from_usize(id: usize) -> Self {
match id as u8 {
0 => Iris::Setosa,
1 => Iris::Versicolor,
2 => Iris::Virginica,
_ => Iris::None
}
}
fn n_categories(&self) -> Option<usize> {
Some(3)
}
}
impl ToPrimitive for Iris {
fn to_i64(&self) -> Option<i64> {
Some(self.as_usize() as i64)
}
fn to_u64(&self) -> Option<u64> {
Some(self.as_usize() as u64)
}
}
#[derive(Debug, Clone, Deserialize)]
struct IrisData {
sepallength: f32,
sepalwidth: f32,
petallength: f32,
petalwidth: f32,
}
#[derive(Clone)]
struct Sample<'a> {
x: &'a IrisData,
y: Iris,
}
impl<'a> fmt::Debug for Sample<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result |
}
impl<'a> SampleDescription for Sample<'a> {
type ThetaSplit = usize;
type ThetaLeaf = ClassCounts;
type Feature = f32;
type Target = Iris;
type Prediction = ClassCounts;
fn target(&self) -> Self::Target {
self.y
}
fn sample_as_split_feature(&self, theta: &Self::ThetaSplit) -> Self::Feature {
// We use the data columns directly as features
match *theta {
0 => self.x.sepallength,
1 => self.x.sepalwidth,
2 => self.x.petallength,
3 => self.x.petalwidth,
_ => panic!("Invalid feature")
}
}
fn sample_predict(&self, c: &Self::ThetaLeaf) -> Self::Prediction {
c.clone()
}
}
impl<'a> TrainingData<Sample<'a>> for [Sample<'a>] {
type Criterion = GiniCriterion; // TODO: specialized Gini implementation for three classes
fn n_samples(&self) -> usize {
self.len()
}
fn gen_split_feature(&self) -> usize {
// The data set has four feature columns
thread_rng().gen_range(0, 4)
}
fn all_split_features(&self) -> Option<Box<Iterator<Item=usize>>> {
Some(Box::new(0..4))
}
fn train_leaf_predictor(&self) -> ClassCounts {
// count the number of samples in each class. This is possible
// because there exists an `impl iter::Sum for ClassCounts`.
self.iter().map(|sample| sample.y).sum()
}
fn feature_bounds(&self, theta: &usize) -> (f32, f32) {
// find minimum and maximum of a feature
self.iter()
.map(|sample| sample.sample_as_split_feature(theta))
.fold((std::f32::INFINITY, std::f32::NEG_INFINITY),
|(min, max), x| {
(if x < min {x} else {min},
if x > max {x} else {max})
})
}
}
fn main() {
let task = openml::SupervisedClassification::from_openml(59).unwrap();
println!("Task: {}", task.name());
let acc: openml::PredictiveAccuracy<_> = task.run_static(|train, test| {
let mut train: Vec<_> = train.map(|(x, &y)| Sample {x, y}).collect();
println!("Fitting...");
let forest = DeterministicForestBuilder::new(
100,
DeterministicTreeBuilder::new(
15,
BestRandomSplit::new(4)
)
).fit(&mut train as &mut [_]);
println!("Predicting...");
let result: Vec<_> = test.map(|x| {
let sample = Sample {
x,
y: Iris::None
};
let prediction: Iris = forest.predict(&sample).most_frequent();
prediction
}).collect();
Box::new(result.into_iter())
});
println!("{:#?}", acc);
println!("{:#?}", acc.result());
}
| {
write!(f, "{:?} : {:?}", self.x, self.y)
} |
as_place.rs | //! See docs in build/expr/mod.rs
use crate::build::expr::category::Category;
use crate::build::ForGuard::{OutsideGuard, RefWithinGuard};
use crate::build::{BlockAnd, BlockAndExtension, Builder};
use crate::hair::*;
use rustc::mir::interpret::InterpError::BoundsCheck;
use rustc::mir::*;
use rustc::ty::{CanonicalUserTypeAnnotation, Variance};
use rustc_data_structures::indexed_vec::Idx;
impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
/// Compile `expr`, yielding a place that we can move from etc.
pub fn as_place<M>(&mut self, block: BasicBlock, expr: M) -> BlockAnd<Place<'tcx>>
where
M: Mirror<'tcx, Output = Expr<'tcx>>,
|
/// Compile `expr`, yielding a place that we can move from etc.
/// Mutability note: The caller of this method promises only to read from the resulting
/// place. The place itself may or may not be mutable:
/// * If this expr is a place expr like a.b, then we will return that place.
/// * Otherwise, a temporary is created: in that event, it will be an immutable temporary.
pub fn as_read_only_place<M>(&mut self, block: BasicBlock, expr: M) -> BlockAnd<Place<'tcx>>
where
M: Mirror<'tcx, Output = Expr<'tcx>>,
{
let expr = self.hir.mirror(expr);
self.expr_as_place(block, expr, Mutability::Not)
}
fn expr_as_place(
&mut self,
mut block: BasicBlock,
expr: Expr<'tcx>,
mutability: Mutability,
) -> BlockAnd<Place<'tcx>> {
debug!(
"expr_as_place(block={:?}, expr={:?}, mutability={:?})",
block, expr, mutability
);
let this = self;
let expr_span = expr.span;
let source_info = this.source_info(expr_span);
match expr.kind {
ExprKind::Scope {
region_scope,
lint_level,
value,
} => this.in_scope((region_scope, source_info), lint_level, block, |this| {
if mutability == Mutability::Not {
this.as_read_only_place(block, value)
} else {
this.as_place(block, value)
}
}),
ExprKind::Field { lhs, name } => {
let place = unpack!(block = this.as_place(block, lhs));
let place = place.field(name, expr.ty);
block.and(place)
}
ExprKind::Deref { arg } => {
let place = unpack!(block = this.as_place(block, arg));
let place = place.deref();
block.and(place)
}
ExprKind::Index { lhs, index } => {
let (usize_ty, bool_ty) = (this.hir.usize_ty(), this.hir.bool_ty());
let slice = unpack!(block = this.as_place(block, lhs));
// region_scope=None so place indexes live forever. They are scalars so they
// do not need storage annotations, and they are often copied between
// places.
// Making this a *fresh* temporary also means we do not have to worry about
// the index changing later: Nothing will ever change this temporary.
// The "retagging" transformation (for Stacked Borrows) relies on this.
let idx = unpack!(block = this.as_temp(block, None, index, Mutability::Mut));
// bounds check:
let (len, lt) = (
this.temp(usize_ty.clone(), expr_span),
this.temp(bool_ty, expr_span),
);
this.cfg.push_assign(
block,
source_info, // len = len(slice)
&len,
Rvalue::Len(slice.clone()),
);
this.cfg.push_assign(
block,
source_info, // lt = idx < len
<,
Rvalue::BinaryOp(
BinOp::Lt,
Operand::Copy(Place::Base(PlaceBase::Local(idx))),
Operand::Copy(len.clone()),
),
);
let msg = BoundsCheck {
len: Operand::Move(len),
index: Operand::Copy(Place::Base(PlaceBase::Local(idx))),
};
let success = this.assert(block, Operand::Move(lt), true, msg, expr_span);
success.and(slice.index(idx))
}
ExprKind::SelfRef => block.and(Place::Base(PlaceBase::Local(Local::new(1)))),
ExprKind::VarRef { id } => {
let place = if this.is_bound_var_in_guard(id) && this
.hir
.tcx()
.all_pat_vars_are_implicit_refs_within_guards()
{
let index = this.var_local_id(id, RefWithinGuard);
Place::Base(PlaceBase::Local(index)).deref()
} else {
let index = this.var_local_id(id, OutsideGuard);
Place::Base(PlaceBase::Local(index))
};
block.and(place)
}
ExprKind::StaticRef { id } => block.and(Place::Base(PlaceBase::Static(Box::new(Static {
ty: expr.ty,
kind: StaticKind::Static(id),
})))),
ExprKind::PlaceTypeAscription { source, user_ty } => {
let place = unpack!(block = this.as_place(block, source));
if let Some(user_ty) = user_ty {
let annotation_index = this.canonical_user_type_annotations.push(
CanonicalUserTypeAnnotation {
span: source_info.span,
user_ty,
inferred_ty: expr.ty,
}
);
this.cfg.push(
block,
Statement {
source_info,
kind: StatementKind::AscribeUserType(
place.clone(),
Variance::Invariant,
box UserTypeProjection { base: annotation_index, projs: vec![], },
),
},
);
}
block.and(place)
}
ExprKind::ValueTypeAscription { source, user_ty } => {
let source = this.hir.mirror(source);
let temp = unpack!(
block = this.as_temp(block, source.temp_lifetime, source, mutability)
);
if let Some(user_ty) = user_ty {
let annotation_index = this.canonical_user_type_annotations.push(
CanonicalUserTypeAnnotation {
span: source_info.span,
user_ty,
inferred_ty: expr.ty,
}
);
this.cfg.push(
block,
Statement {
source_info,
kind: StatementKind::AscribeUserType(
Place::Base(PlaceBase::Local(temp.clone())),
Variance::Invariant,
box UserTypeProjection { base: annotation_index, projs: vec![], },
),
},
);
}
block.and(Place::Base(PlaceBase::Local(temp)))
}
ExprKind::Array { .. }
| ExprKind::Tuple { .. }
| ExprKind::Adt { .. }
| ExprKind::Closure { .. }
| ExprKind::Unary { .. }
| ExprKind::Binary { .. }
| ExprKind::LogicalOp { .. }
| ExprKind::Box { .. }
| ExprKind::Cast { .. }
| ExprKind::Use { .. }
| ExprKind::NeverToAny { .. }
| ExprKind::ReifyFnPointer { .. }
| ExprKind::ClosureFnPointer { .. }
| ExprKind::UnsafeFnPointer { .. }
| ExprKind::MutToConstPointer { .. }
| ExprKind::Unsize { .. }
| ExprKind::Repeat { .. }
| ExprKind::Borrow { .. }
| ExprKind::If { .. }
| ExprKind::Match { .. }
| ExprKind::Loop { .. }
| ExprKind::Block { .. }
| ExprKind::Assign { .. }
| ExprKind::AssignOp { .. }
| ExprKind::Break { .. }
| ExprKind::Continue { .. }
| ExprKind::Return { .. }
| ExprKind::Literal { .. }
| ExprKind::InlineAsm { .. }
| ExprKind::Yield { .. }
| ExprKind::Call { .. } => {
// these are not places, so we need to make a temporary.
debug_assert!(match Category::of(&expr.kind) {
Some(Category::Place) => false,
_ => true,
});
let temp =
unpack!(block = this.as_temp(block, expr.temp_lifetime, expr, mutability));
block.and(Place::Base(PlaceBase::Local(temp)))
}
}
}
}
| {
let expr = self.hir.mirror(expr);
self.expr_as_place(block, expr, Mutability::Mut)
} |
router-method-factory.d.ts | import { HttpServer } from '@nestjs/common';
import { RequestMethod } from '@nestjs/common/enums/request-method.enum'; | export declare class RouterMethodFactory {
get(target: HttpServer, requestMethod: RequestMethod): Function;
} |
|
pyscf_utils.py | #coverage:ignore
""" Drivers for various PySCF electronic structure routines """
from typing import Tuple, Optional
import sys
import h5py
import numpy as np
from pyscf import gto, scf, ao2mo, mcscf, lo, tools, cc
from pyscf.mcscf import avas
def stability(pyscf_mf):
"""
Test wave function stability and re-optimize SCF.
Args:
pyscf_mf: PySCF mean field object (e.g. `scf.RHF()`)
Returns:
pyscf_mf: Updated PySCF mean field object
"""
new_orbitals = pyscf_mf.stability()[0]
new_1rdm = pyscf_mf.make_rdm1(new_orbitals, pyscf_mf.mo_occ)
pyscf_mf = pyscf_mf.run(new_1rdm)
return pyscf_mf
def localize(pyscf_mf, loc_type='pm', verbose=0):
""" Localize orbitals given a PySCF mean-field object
Args:
pyscf_mf: PySCF mean field object
loc_type (str): localization type;
Pipek-Mezey ('pm') or Edmiston-Rudenberg ('er')
verbose (int): print level during localization
Returns:
pyscf_mf: Updated PySCF mean field object with localized orbitals
"""
# Note: After loading with `load_casfile_to_pyscf()` you can quiet message
# by resetting mf.mol, i.e., mf.mol = gto.M(...)
# but this assumes you have the *exact* molecular specification on hand.
# I've gotten acceptable results by restoring mf.mol this way (usually
# followed by calling mf.kernel()). But consistent localization is not a
# given (not unique) despite restoring data this way, hence the message.
if len(pyscf_mf.mol.atom) == 0:
sys.exit("`localize()` requires atom loc. and atomic basis to be" + \
" defined.\n " + \
"It also can be sensitive to the initial guess and MO" + \
" coefficients.\n " + \
"Best to try re-creating the PySCF molecule and doing the" + \
" SCF, rather than\n " + \
"try to load the mean-field object with" + \
" `load_casfile_to_pyscf()`. You can \n " + \
"try to provide the missing information, but consistency" + \
" cannot be guaranteed!")
# Split-localize (localize DOCC, SOCC, and virtual separately)
docc_idx = np.where(np.isclose(pyscf_mf.mo_occ, 2.))[0]
socc_idx = np.where(np.isclose(pyscf_mf.mo_occ, 1.))[0]
virt_idx = np.where(np.isclose(pyscf_mf.mo_occ, 0.))[0]
# Pipek-Mezey
if loc_type.lower() == 'pm':
print("Localizing doubly occupied ... ", end="")
loc_docc_mo = lo.PM(
pyscf_mf.mol,
pyscf_mf.mo_coeff[:, docc_idx]).kernel(verbose=verbose)
print("singly occupied ... ", end="")
loc_socc_mo = lo.PM(
pyscf_mf.mol,
pyscf_mf.mo_coeff[:, socc_idx]).kernel(verbose=verbose)
print("virtual ... ", end="")
loc_virt_mo = lo.PM(
pyscf_mf.mol,
pyscf_mf.mo_coeff[:, virt_idx]).kernel(verbose=verbose)
print("DONE")
# Edmiston-Rudenberg
elif loc_type.lower() == 'er':
print("Localizing doubly occupied ... ", end="")
loc_docc_mo = lo.ER(
pyscf_mf.mol,
pyscf_mf.mo_coeff[:, docc_idx]).kernel(verbose=verbose)
print("singly occupied ... ", end="")
loc_socc_mo = lo.ER(
pyscf_mf.mol,
pyscf_mf.mo_coeff[:, socc_idx]).kernel(verbose=verbose)
print("virtual ... ", end="")
loc_virt_mo = lo.ER(
pyscf_mf.mol,
pyscf_mf.mo_coeff[:, virt_idx]).kernel(verbose=verbose)
print("DONE")
# overwrite orbitals with localized orbitals
pyscf_mf.mo_coeff[:, docc_idx] = loc_docc_mo.copy()
pyscf_mf.mo_coeff[:, socc_idx] = loc_socc_mo.copy()
pyscf_mf.mo_coeff[:, virt_idx] = loc_virt_mo.copy()
return pyscf_mf
def avas_active_space(pyscf_mf,
ao_list=None,
molden_fname='avas_localized_orbitals',
**kwargs):
""" Return AVAS active space as PySCF molecule and mean-field object
Args:
pyscf_mf: PySCF mean field object
Kwargs:
ao_list: list of strings of AOs (print mol.ao_labels() to see options)
Example: ao_list = ['H 1s', 'O 2p', 'O 2s'] for water
verbose (bool): do additional print
molden_fname (str): MOLDEN filename to save AVAS active space orbitals.
Default is to save
to 'avas_localized_orbitals.molden'
**kwargs: other keyworded arguments to pass into avas.avas()
Returns:
pyscf_active_space_mol: Updated PySCF molecule object from
AVAS-selected active space
pyscf_active_space_mf: Updated PySCF mean field object from
AVAS-selected active space
"""
# Note: requires openshell_option = 3 for this to work, which keeps all
# singly occupied in CAS
# we also require canonicalize = False so that we don't destroy local orbs
avas_output = avas.avas(pyscf_mf,
ao_list,
canonicalize=False,
openshell_option=3,
**kwargs)
active_norb, active_ne, reordered_orbitals = avas_output
active_alpha, _ = get_num_active_alpha_beta(pyscf_mf, active_ne)
if molden_fname is not None:
# save set of localized orbitals for active space
if isinstance(pyscf_mf, scf.rohf.ROHF):
frozen_alpha = pyscf_mf.nelec[0] - active_alpha
assert frozen_alpha >= 0
else:
frozen_alpha = pyscf_mf.mol.nelectron // 2 - active_alpha
assert frozen_alpha >= 0
active_space_idx = slice(frozen_alpha, frozen_alpha + active_norb)
active_mos = reordered_orbitals[:, active_space_idx]
tools.molden.from_mo(pyscf_mf.mol,
molden_fname + '.molden',
mo_coeff=active_mos)
# Choosing an active space changes the molecule ("freezing" electrons,
# for example), so we
# form the active space tensors first, then re-form the PySCF objects to
# ensure consistency
pyscf_active_space_mol, pyscf_active_space_mf = cas_to_pyscf(
*pyscf_to_cas(pyscf_mf,
cas_orbitals=active_norb,
cas_electrons=active_ne,
avas_orbs=reordered_orbitals))
return pyscf_active_space_mol, pyscf_active_space_mf
def cas_to_pyscf(h1, eri, ecore, num_alpha, num_beta):
""" Return a PySCF molecule and mean-field object from pre-computed CAS Ham
Args:
h1 (ndarray) - 2D matrix containing one-body terms (MO basis)
eri (ndarray) - 4D tensor containing two-body terms (MO basis)
ecore (float) - frozen core electronic energy + nuclear repulsion energy
num_alpha (int) - number of spin up electrons in CAS space
num_beta (int) - number of spin down electrons in CAS space
Returns:
pyscf_mol: PySCF molecule object
pyscf_mf: PySCF mean field object
"""
n_orb = len(h1) # number orbitals
assert [n_orb] * 4 == [*eri.shape] # check dims are consistent
pyscf_mol = gto.M()
pyscf_mol.nelectron = num_alpha + num_beta
n_orb = h1.shape[0]
alpha_diag = [1] * num_alpha + [0] * (n_orb - num_alpha)
beta_diag = [1] * num_beta + [0] * (n_orb - num_beta)
# Assumes Hamiltonian is either RHF or ROHF ... should be OK since UHF will
# have two h1s, etc.
if num_alpha == num_beta:
pyscf_mf = scf.RHF(pyscf_mol)
scf_energy = ecore + \
2*np.einsum('ii', h1[:num_alpha,:num_alpha]) + \
2*np.einsum('iijj',
eri[:num_alpha,:num_alpha,:num_alpha,:num_alpha]) - \
np.einsum('ijji',
eri[:num_alpha,:num_alpha,:num_alpha,:num_alpha])
else:
pyscf_mf = scf.ROHF(pyscf_mol)
pyscf_mf.nelec = (num_alpha, num_beta)
# grab singly and doubly occupied orbitals (assume high-spin open shell)
docc = slice(None, min(num_alpha, num_beta))
socc = slice(min(num_alpha, num_beta), max(num_alpha, num_beta))
scf_energy = ecore + \
2.0*np.einsum('ii',h1[docc, docc]) + \
np.einsum('ii',h1[socc, socc]) + \
2.0*np.einsum('iijj',eri[docc, docc, docc, docc]) - \
np.einsum('ijji',eri[docc, docc, docc, docc]) + \
np.einsum('iijj',eri[socc, socc, docc, docc]) - \
0.5*np.einsum('ijji',eri[socc, docc, docc, socc]) + \
np.einsum('iijj',eri[docc, docc, socc, socc]) - \
0.5*np.einsum('ijji',eri[docc, socc, socc, docc]) + \
0.5*np.einsum('iijj',eri[socc, socc, socc, socc]) - \
0.5*np.einsum('ijji',eri[socc, socc, socc, socc])
pyscf_mf.get_hcore = lambda *args: np.asarray(h1)
pyscf_mf.get_ovlp = lambda *args: np.eye(h1.shape[0])
pyscf_mf.energy_nuc = lambda *args: ecore
pyscf_mf._eri = eri # ao2mo.restore('8', np.zeros((8, 8, 8, 8)), 8)
pyscf_mf.e_tot = scf_energy
pyscf_mf.init_guess = '1e'
pyscf_mf.mo_coeff = np.eye(n_orb)
pyscf_mf.mo_occ = np.array(alpha_diag) + np.array(beta_diag)
pyscf_mf.mo_energy, _ = np.linalg.eigh(pyscf_mf.get_fock())
return pyscf_mol, pyscf_mf
def pyscf_to_cas(pyscf_mf,
cas_orbitals: Optional[int] = None,
cas_electrons: Optional[int] = None,
avas_orbs=None):
|
def get_num_active_alpha_beta(pyscf_mf, cas_electrons):
""" Return number of alpha and beta electrons in the active space given
number of CAS electrons
This assumes that all the unpaired electrons are in the active space
Args:
pyscf_mf: PySCF mean field object
cas_orbitals (int): number of electrons in CAS space,
Returns:
num_alpha (int): number of alpha (spin-up) electrons in active space
num_beta (int): number of beta (spin-down) electrons in active space
"""
# Sanity checks and active space info
total_electrons = pyscf_mf.mol.nelectron
frozen_electrons = total_electrons - cas_electrons
assert frozen_electrons % 2 == 0
# ROHF == RHF but RHF != ROHF, and we only do either RHF or ROHF
if isinstance(pyscf_mf, scf.rohf.ROHF):
frozen_alpha = frozen_electrons // 2
frozen_beta = frozen_electrons // 2
num_alpha = pyscf_mf.nelec[0] - frozen_alpha
num_beta = pyscf_mf.nelec[1] - frozen_beta
assert np.isclose(num_beta + num_alpha, cas_electrons)
else:
assert cas_electrons % 2 == 0
num_alpha = cas_electrons // 2
num_beta = cas_electrons // 2
return num_alpha, num_beta
def load_casfile_to_pyscf(fname,
num_alpha: Optional[int] = None,
num_beta: Optional[int] = None):
""" Load CAS Hamiltonian from pre-computed HD5 file into a PySCF molecule
and mean-field object
Args:
fname (str): path to hd5 file to be created containing CAS one and two
body terms
num_alpha (int, optional): number of spin up electrons in CAS space
num_beta (int, optional): number of spin down electrons in CAS space
Returns:
pyscf_mol: PySCF molecule object
pyscf_mf: PySCF mean field object
"""
with h5py.File(fname, "r") as f:
eri = np.asarray(f['eri'][()])
# h1 one body elements are sometimes called different things. Try a few.
try:
h1 = np.asarray(f['h0'][()])
except KeyError:
try:
h1 = np.asarray(f['hcore'][()])
except KeyError:
try:
h1 = np.asarray(f['h1'][()])
except KeyError:
raise KeyError("Could not find 1-electron Hamiltonian")
# ecore sometimes exists, and sometimes as enuc (no frozen electrons)
try:
ecore = float(f['ecore'][()])
except KeyError:
try:
ecore = float(f['enuc'][()])
except KeyError:
ecore = 0.0
# read the number of spin up and spin down electrons if not input
if (num_alpha is None) or (num_beta is None):
try:
num_alpha = int(f['active_nalpha'][()])
except KeyError:
sys.exit("In `load_casfile_to_pyscf()`: \n" + \
" No values found on file for num_alpha " + \
"(key: 'active_nalpha' in h5). " + \
" Try passing in a value for num_alpha, or" + \
" re-check integral file.")
try:
num_beta = int(f['active_nbeta'][()])
except KeyError:
sys.exit("In `load_casfile_to_pyscf()`: \n" + \
" No values found on file for num_beta " + \
"(key: 'active_nbeta' in h5). " + \
" Try passing in a value for num_beta, or" + \
" re-check integral file.")
pyscf_mol, pyscf_mf = cas_to_pyscf(h1, eri, ecore, num_alpha, num_beta)
return pyscf_mol, pyscf_mf
def save_pyscf_to_casfile(fname,
pyscf_mf,
cas_orbitals: Optional[int] = None,
cas_electrons: Optional[int] = None,
avas_orbs=None):
""" Save CAS Hamiltonian from a PySCF mean-field object to an HD5 file
Args:
fname (str): path to hd5 file to be created containing CAS terms
pyscf_mf: PySCF mean field object
cas_orbitals (int, optional): number of orb in CAS space, default all
cas_electrons (int, optional): number of elec in CAS, default all elec
avas_orbs (ndarray, optional): orbitals selected by AVAS in PySCF
"""
h1, eri, ecore, num_alpha, num_beta = \
pyscf_to_cas(pyscf_mf, cas_orbitals, cas_electrons, avas_orbs)
with h5py.File(fname, 'w') as fid:
fid.create_dataset('ecore', data=float(ecore), dtype=float)
fid.create_dataset(
'h0',
data=h1) # note the name change to be consistent with THC paper
fid.create_dataset('eri', data=eri)
fid.create_dataset('active_nalpha', data=int(num_alpha), dtype=int)
fid.create_dataset('active_nbeta', data=int(num_beta), dtype=int)
def factorized_ccsd_t(pyscf_mf, eri_rr = None, use_kernel = True,\
no_triples=False) -> Tuple[float, float, float]:
""" Compute CCSD(T) energy using rank-reduced ERIs
Args:
pyscf_mf - PySCF mean field object
eri_rr (ndarray) - rank-reduced ERIs, or use full ERIs from pyscf_mf
use_kernel (bool) - re-do SCF, using canonical orbitals for one-body?
no_triples (bool) - skip the perturbative triples correction? (CCSD)
Returns:
e_scf (float) - SCF energy
e_cor (float) - Correlation energy from CCSD(T)
e_tot (float) - Total energy; i.e. SCF + Corr energy from CCSD(T)
"""
h1, eri_full, ecore, num_alpha, num_beta = pyscf_to_cas(pyscf_mf)
# If no rank-reduced ERIs, use the full (possibly local) ERIs from pyscf_mf
if eri_rr is None:
eri_rr = eri_full
e_scf, e_cor, e_tot = ccsd_t(h1, eri_rr, ecore, num_alpha, num_beta,\
eri_full, use_kernel, no_triples)
return e_scf, e_cor, e_tot
def ccsd_t(h1, eri, ecore, num_alpha: int, num_beta: int, eri_full = None,\
use_kernel=True, no_triples=False) -> Tuple[float, float, float]:
""" Helper function to do CCSD(T) on set of one- and two-body Hamil elems
Args:
h1 (ndarray) - 2D matrix containing one-body terms (MO basis)
eri (ndarray) - 4D tensor containing two-body terms (MO basis)
may be from integral factorization (e.g. SF/DF/THC)
ecore (float) - frozen core electronic energy + nuclear repulsion energy
num_alpha (int) - number of spin alpha electrons in Hamiltonian
num_beta (int) - number of spin beta electrons in Hamiltonian
eri_full (ndarray) - optional 4D tensor containing full two-body
terms (MO basis) for the SCF procedure only
use_kernel (bool) - re-run SCF prior to doing CCSD(T)?
no_triples (bool) - skip the perturbative triples correction? (CCSD)
Returns:
e_scf (float) - SCF energy
e_cor (float) - Correlation energy from CCSD(T)
e_tot (float) - Total energy; i.e. SCF + Corr energy from CCSD(T)
"""
mol = gto.M()
mol.nelectron = num_alpha + num_beta
n_orb = h1.shape[0]
alpha_diag = [1] * num_alpha + [0] * (n_orb - num_alpha)
beta_diag = [1] * num_beta + [0] * (n_orb - num_beta)
# If eri_full not provided, use (possibly rank-reduced) ERIs for check
if eri_full is None:
eri_full = eri
# either RHF or ROHF ... should be OK since UHF will have two h1s, etc.
if num_alpha == num_beta:
mf = scf.RHF(mol)
scf_energy = ecore + \
2*np.einsum('ii',h1[:num_alpha,:num_alpha]) + \
2*np.einsum('iijj',eri_full[:num_alpha,\
:num_alpha,\
:num_alpha,\
:num_alpha]) - \
np.einsum('ijji',eri_full[:num_alpha,\
:num_alpha,\
:num_alpha,\
:num_alpha])
else:
mf = scf.ROHF(mol)
mf.nelec = (num_alpha, num_beta)
# grab singly and doubly occupied orbitals (assume high-spin open shell)
docc = slice(None, min(num_alpha, num_beta))
socc = slice(min(num_alpha, num_beta), max(num_alpha, num_beta))
scf_energy = ecore + \
2.0*np.einsum('ii',h1[docc, docc]) + \
np.einsum('ii',h1[socc, socc]) + \
2.0*np.einsum('iijj',eri_full[docc, docc, docc, docc]) - \
np.einsum('ijji',eri_full[docc, docc, docc, docc]) + \
np.einsum('iijj',eri_full[socc, socc, docc, docc]) - \
0.5*np.einsum('ijji',eri_full[socc, docc, docc, socc]) + \
np.einsum('iijj',eri_full[docc, docc, socc, socc]) - \
0.5*np.einsum('ijji',eri_full[docc, socc, socc, docc]) + \
0.5*np.einsum('iijj',eri_full[socc, socc, socc, socc]) - \
0.5*np.einsum('ijji',eri_full[socc, socc, socc, socc])
mf.get_hcore = lambda *args: np.asarray(h1)
mf.get_ovlp = lambda *args: np.eye(h1.shape[0])
mf.energy_nuc = lambda *args: ecore
mf._eri = eri_full # ao2mo.restore('8', np.zeros((8, 8, 8, 8)), 8)
mf.init_guess = '1e'
mf.mo_coeff = np.eye(n_orb)
mf.mo_occ = np.array(alpha_diag) + np.array(beta_diag)
w, _ = np.linalg.eigh(mf.get_fock())
mf.mo_energy = w
# Rotate the interaction tensors into the canonical basis.
# Reiher and Li tensors, for example, are read-in in the local MO basis,
# which is not optimal for the CCSD(T) calculation (canonical gives better
# energy estimate whereas QPE is invariant to choice of basis)
if use_kernel:
mf.conv_tol = 1e-7
mf.init_guess = '1e'
mf.verbose = 4
mf.diis_space = 24
mf.level_shift = 0.5
mf.conv_check = False
mf.max_cycle = 800
mf.kernel(mf.make_rdm1(mf.mo_coeff,
mf.mo_occ)) # use MO info to generate guess
mf = stability(mf)
mf = stability(mf)
mf = stability(mf)
# Check if SCF has changed by doing restart, and print warning if so
try:
assert np.isclose(scf_energy, mf.e_tot, rtol=1e-14)
except AssertionError:
print(
"WARNING: E(SCF) from input integrals does not match E(SCF)" + \
" from mf.kernel()")
print(" Will use E(SCF) = {:12.6f} from mf.kernel going forward.".
format(mf.e_tot))
print("E(SCF, ints) = {:12.6f} whereas E(SCF) = {:12.6f}".format(
scf_energy, mf.e_tot))
# New SCF energy and orbitals for CCSD(T)
scf_energy = mf.e_tot
# Now re-set the eri's to the (possibly rank-reduced) ERIs
mf._eri = eri
mf.mol.incore_anyway = True
mycc = cc.CCSD(mf)
mycc.max_cycle = 800
mycc.conv_tol = 1E-8
mycc.conv_tol_normt = 1E-4
mycc.diis_space = 24
mycc.verbose = 4
mycc.kernel()
if no_triples:
et = 0.0
else:
et = mycc.ccsd_t()
e_scf = scf_energy # may be read-in value or 'fresh' SCF value
e_cor = mycc.e_corr + et
e_tot = e_scf + e_cor
print("E(SCF): ", e_scf)
print("E(cor): ", e_cor)
print("Total energy: ", e_tot)
return e_scf, e_cor, e_tot
def open_shell_t1_d1(t1a, t1b, mo_occ, nalpha, nbeta):
"""
T1-diagnostic for open-shell is defined w.r.t Sx eigenfunction of T1
where reference is ROHF.
given i double occ, c unoccupied, x is single occuplied The T1 amps
(high spin) in Sz basis are:
T1 = t_{ia}^{ca}(ca^ ia) + t_{ib}^{cb}(cb^ ib)
+ t_{xa}^{ca}(ca^ xa) + t_{ib}^{xb}(xb^ ib)
T1 in the Sx basis are
T1 = f_{i}^{c}E_{ci} + v_{i}^{c}A_{ci}
+ sqrt(2)f_{x}^{c}(ca^ xa) + sqrt(2)f_{i}^{x}(xb^ ib)
where E_{ci} = ca^ ia + cb^ ib and A_{ci} = ca^ ia - cb^ ib.
See: The Journal of Chemical Physics 98, 9734 (1993);
doi: 10.1063/1.464352
Chemical Physics Letters 372 (2003) 362–367;
doi:10.1016/S0009-2614(03)00435-4
based on these and two papers from Lee the T1-openshell diagnostic is
sqrt(sum_{ia}(f_{ia})^2 + 2sum_{xa}(t_{xa}^{ca})^2
+ 2 sum_{ix}(t_{ib}^{xb})^2) / 2 sqrt{N}
To get this relate eqs 3-7 from Chemical Physics Letters 372 (2003) 362–367
to Eqs. 45, 46, and 51 from Journal of Chemical Physics 98, 9734 (1993);
doi: 10.1063/1.464352.
"""
# compute t1-diagnostic
docc_idx = np.where(np.isclose(mo_occ, 2.))[0]
socc_idx = np.where(np.isclose(mo_occ, 1.))[0]
virt_idx = np.where(np.isclose(mo_occ, 0.))[0]
t1a_docc = t1a[docc_idx, :] # double occ-> virtual
t1b_docc = t1b[docc_idx, :][:, -len(virt_idx):] # double occ-> virtual
if len(socc_idx) > 0:
t1_xa = t1a[socc_idx, :] # single occ -> virtual
t1_ix = t1b[docc_idx, :][:, :len(socc_idx)] # double occ -> single occ
else:
t1_xa = np.array(())
t1_ix = np.array(())
if nalpha - nbeta + len(virt_idx) != t1b.shape[1]:
raise ValueError(
"Inconsistent shapes na {}, nb {}, t1b.shape {},{}".format(
nalpha, nbeta, t1b.shape[0], t1b.shape[1]))
if t1a_docc.shape != (len(docc_idx), len(virt_idx)):
raise ValueError("T1a_ia does not have the right shape")
if t1b_docc.shape != (len(docc_idx), len(virt_idx)):
raise ValueError("T1b_ia does not have the right shape")
if len(socc_idx) > 0:
if t1_ix.shape != (len(docc_idx), len(socc_idx)):
raise ValueError("T1_ix does not have the right shape")
if t1_xa.shape != (len(socc_idx), len(virt_idx)):
raise ValueError("T1_xa does not have the right shape")
t1_diagnostic = np.sqrt(
np.sum((t1a_docc + t1b_docc)**2) + 2 * np.sum(t1_xa**2) +
2 * np.sum(t1_ix**2)) / (2 * np.sqrt(nalpha + nbeta))
# compute D1-diagnostic
f_ia = 0.5 * (t1a_docc + t1b_docc)
s_f_ia_2, _ = np.linalg.eigh(f_ia @ f_ia.T)
s_f_ia_2_norm = np.sqrt(np.max(s_f_ia_2, initial=0))
if len(socc_idx) > 0:
f_xa = np.sqrt(1 / 2) * t1_xa
f_ix = np.sqrt(1 / 2) * t1_ix
s_f_xa_2, _ = np.linalg.eigh(f_xa @ f_xa.T)
s_f_ix_2, _ = np.linalg.eigh(f_ix @ f_ix.T)
else:
s_f_xa_2 = np.array(())
s_f_ix_2 = np.array(())
s_f_xa_2_norm = np.sqrt(np.max(s_f_xa_2, initial=0))
s_f_ix_2_norm = np.sqrt(np.max(s_f_ix_2, initial=0))
d1_diagnostic = np.max(
np.array([s_f_ia_2_norm, s_f_xa_2_norm, s_f_ix_2_norm]))
return t1_diagnostic, d1_diagnostic
| """ Return CAS Hamiltonian tensors from a PySCF mean-field object
Args:
pyscf_mf: PySCF mean field object
cas_orbitals (int, optional): number of orbitals in CAS space,
default all orbitals
cas_electrons (int, optional): number of electrons in CAS space,
default all electrons
avas_orbs (ndarray, optional): orbitals selected by AVAS in PySCF
Returns:
h1 (ndarray) - 2D matrix containing one-body terms (MO basis)
eri (ndarray) - 4D tensor containing two-body terms (MO basis)
ecore (float) - frozen core electronic energy + nuclear repulsion energy
num_alpha (int) - number of spin up electrons in CAS space
num_beta (int) - number of spin down electrons in CAS space
"""
# Only RHF or ROHF possible with mcscf.CASCI
assert isinstance(pyscf_mf, scf.rhf.RHF) # ROHF is child of RHF class
if cas_orbitals is None:
cas_orbitals = len(pyscf_mf.mo_coeff)
if cas_electrons is None:
cas_electrons = pyscf_mf.mol.nelectron
cas = mcscf.CASCI(pyscf_mf, ncas=cas_orbitals, nelecas=cas_electrons)
h1, ecore = cas.get_h1eff(mo_coeff=avas_orbs)
eri = cas.get_h2cas(mo_coeff=avas_orbs)
eri = ao2mo.restore('s1', eri, h1.shape[0]) # chemist convention (11|22)
ecore = float(ecore)
num_alpha, num_beta = get_num_active_alpha_beta(pyscf_mf, cas_electrons)
return h1, eri, ecore, num_alpha, num_beta |
mod.rs | use bitcoin::Txid;
use bitcoin_hashes::{sha256d, Hash, HashEngine};
use crate::error::{OptionExt, Result};
use crate::query::Query;
use crate::types::{MempoolEntry, ScriptHash, StatusHash, TxStatus};
use crate::util::BoolThen;
mod server;
pub use server::ElectrumServer;
pub fn electrum_height(status: TxStatus, has_unconfirmed_parents: Option<bool>) -> i32 {
match status {
TxStatus::Confirmed(height) => height as i32,
TxStatus::Unconfirmed => match has_unconfirmed_parents {
Some(false) => 0, // a height of 0 indicates an unconfirmed tx where all the parents are confirmed
Some(true) => -1, // a height of -1 indicates an unconfirmed tx with unconfirmed parents used as its inputs
None => -1, // if has_unconfirmed_parents is unknown, error on the side of caution
},
TxStatus::Conflicted => {
unreachable!("electrum_height() should not be called on conflicted txs")
}
}
}
trait QueryExt {
fn get_status_hash(&self, scripthash: &ScriptHash) -> Option<StatusHash>;
fn electrum_merkle_proof(
&self,
txid: &Txid,
height: u32,
) -> Result<(Vec<sha256d::Hash>, usize)>;
fn electrum_header_merkle_proof(
&self,
height: u32,
cp_height: u32,
) -> Result<(Vec<sha256d::Hash>, sha256d::Hash)>;
fn electrum_id_from_pos(
&self,
height: u32,
tx_pos: usize,
want_merkle: bool,
) -> Result<(Txid, Vec<sha256d::Hash>)>;
}
impl QueryExt for Query {
fn get_status_hash(&self, scripthash: &ScriptHash) -> Option<StatusHash> {
let mut engine = StatusHash::engine();
let has_history = self.for_each_history(scripthash, |hist| {
let has_unconfirmed_parents = hist.status.is_unconfirmed().and_then(|| {
self.with_mempool_entry(&hist.txid, MempoolEntry::has_unconfirmed_parents)
});
let p = format!(
"{}:{}:",
hist.txid,
electrum_height(hist.status, has_unconfirmed_parents)
);
engine.input(&p.into_bytes());
});
if has_history {
Some(StatusHash::from_engine(engine))
} else {
// empty history needs to be represented as a `null` in json
None
}
}
fn electrum_merkle_proof(
&self,
txid: &Txid,
height: u32,
) -> Result<(Vec<sha256d::Hash>, usize)> {
let block_hash = self.get_block_hash(height)?;
let txids = self.get_block_txids(&block_hash)?;
let pos = txids
.iter()
.position(|c_txid| c_txid == txid)
.or_err("missing tx")?;
let hashes = txids.into_iter().map(sha256d::Hash::from).collect();
let (branch, _root) = create_merkle_branch_and_root(hashes, pos);
Ok((branch, pos))
}
fn | (
&self,
height: u32,
cp_height: u32,
) -> Result<(Vec<sha256d::Hash>, sha256d::Hash)> {
if cp_height < height {
bail!("cp_height #{} < height #{}", cp_height, height);
}
let best_height = self.get_tip_height()?;
if best_height < cp_height {
bail!(
"cp_height #{} above best block height #{}",
cp_height,
best_height
);
}
let heights: Vec<u32> = (0..=cp_height).collect();
let header_hashes = heights
.into_iter()
.map(|height| self.get_block_hash(height).map(sha256d::Hash::from))
.collect::<Result<Vec<sha256d::Hash>>>()?;
Ok(create_merkle_branch_and_root(
header_hashes,
height as usize,
))
}
fn electrum_id_from_pos(
&self,
height: u32,
tx_pos: usize,
want_merkle: bool,
) -> Result<(Txid, Vec<sha256d::Hash>)> {
let block_hash = self.get_block_hash(height)?;
let txids = self.get_block_txids(&block_hash)?;
let txid = *txids.get(tx_pos).or_err(format!(
"No tx in position #{} in block #{}",
tx_pos, height
))?;
let branch = if want_merkle {
let hashes = txids.into_iter().map(sha256d::Hash::from).collect();
create_merkle_branch_and_root(hashes, tx_pos).0
} else {
vec![]
};
Ok((txid, branch))
}
}
fn merklize(left: sha256d::Hash, right: sha256d::Hash) -> sha256d::Hash {
let data = [&left[..], &right[..]].concat();
sha256d::Hash::hash(&data)
}
fn create_merkle_branch_and_root(
mut hashes: Vec<sha256d::Hash>,
mut index: usize,
) -> (Vec<sha256d::Hash>, sha256d::Hash) {
let mut merkle = vec![];
while hashes.len() > 1 {
if hashes.len() % 2 != 0 {
let last = *hashes.last().unwrap();
hashes.push(last);
}
index = if index % 2 == 0 { index + 1 } else { index - 1 };
merkle.push(hashes[index]);
index /= 2;
hashes = hashes
.chunks(2)
.map(|pair| merklize(pair[0], pair[1]))
.collect()
}
(merkle, hashes[0])
}
| electrum_header_merkle_proof |
lookup_tables.py | from typing import List, Callable, Dict, Tuple, Union
import math
import matplotlib.pyplot as plt
class ApproxMultiplicationTable:
"""
Multiplication done using a lookup table instead of a math unit
"""
table_entries: Dict[Tuple[int, int], int]
num_significant_bits: int
def __init__(self, num_significant_bits: int, unbiasing: float = 0.5):
"""
Create a lookup table that approximately multiplies pairs of positive integers
:param num_significant_bits: number of bits to preserve when approximating operands.
Lookup table size will be 2 ** (2 * num_significant bits), so recommended values are <=8
:param unbiasing: a value in the range [0,1) that is used to unbias lookup table error
"""
self.num_significant_bits = num_significant_bits
self.table_entries = {}
# Populate the lookup table
for i in range(1 << num_significant_bits):
for j in range(1 << num_significant_bits):
# i and j will be rounded versions of more precise numbers.
# To unbias the rounding error, we offset i and j slightly before dividing them
value: int = round((i + unbiasing) * (j + unbiasing))
self.table_entries[(i, j)] = value
def compute(self, a: int, b: int) -> int:
assert a > 0 and b > 0
# the exponent can be computed in tofino using TCAM lookup tables. If the operands are 32 bits,
# the lookup tables will have 32 entries
exponent: int = max(a.bit_length(), b.bit_length())
rshift: int = max(exponent - self.num_significant_bits, 0)
i = a >> rshift
j = b >> rshift
value = self.table_entries[(i, j)]
return value << (2 * rshift)
def table_size(self) -> int:
|
class ApproxDivisionTable:
"""
Division done using a lookup table instead of a math unit
"""
table_entries: Dict[Tuple[int, int], Tuple[int, int]]
num_significant_bits: int
MIN_LOOKUP_ENTRY = 2 ** -16 # lookup entries smaller than this will be rounded down to 0
def __init__(self, num_significant_bits: int, unbiasing: float = 0.5, lookup_value_mantissa_bits: int = 8):
"""
Create a lookup table that approximately divides pairs of positive integers
:param num_significant_bits: number of bits to preserve when approximating operands.
Lookup table size will be 2 ** (2 * num_significant bits), so recommended values are <=8
:param unbiasing: a value in the range [0,1) that is used to unbias lookup table error
:param lookup_value_mantissa_bits: significant bits of division results stored in the lookup table
"""
self.num_significant_bits = num_significant_bits
self.table_entries = {}
# populate the lookup table
for i in range(1 << num_significant_bits):
for j in range(1 << num_significant_bits):
# i and j will be rounded versions of more precise numbers.
# To unbias the rounding error, we offset i and j slightly before dividing them
value = (i + unbiasing) / (j + unbiasing)
exp: int
mantissa: int
if value < self.MIN_LOOKUP_ENTRY:
exp = 0
mantissa = 0
else:
exp = math.floor(math.log(value, 2)) - lookup_value_mantissa_bits + 1
mantissa = round(value * 2 ** (-exp))
self.table_entries[(i, j)] = (mantissa, exp)
def compute(self, a: int, b: int) -> float:
assert a > 0 and b > 0
exponent: int = max(a.bit_length(), b.bit_length())
rshift: int = exponent - self.num_significant_bits
i = a >> rshift
j = b >> rshift
mantissa, exponent = self.table_entries[(i, j)]
return mantissa * (2 ** exponent)
def table_size(self) -> int:
return len(self.table_entries)
def plot_relative_error(a_vals: List[int], b_vals: List[int],
true_func: Callable[[int, int], float],
lookup: Union[ApproxMultiplicationTable, ApproxDivisionTable]):
fig, ax = plt.subplots()
ax.set_title("Relative error for %s with %d entries" % (type(lookup).__name__, lookup.table_size()))
ax.set_ylabel("Relative error (0.1 = 10%)")
ax.set_xlabel("Input a to f(a,b)")
for b in b_vals:
errors = []
for a in a_vals:
approx_result = lookup.compute(a, b)
true_result = true_func(a, b)
error = (approx_result - true_result) / true_result
errors.append(error)
line, = ax.plot(a_vals, errors, label="%d" % b, linewidth=1.0)
ax.legend(title="Input b to f(a,b)")
plt.show()
def main():
a_vals = [i for i in range(100000, 500000)]
b_vals = [j for j in range(100000, 500000, 100000)]
mult_lookup = ApproxMultiplicationTable(num_significant_bits=7)
div_loookup = ApproxDivisionTable(num_significant_bits=7)
plot_relative_error(a_vals, b_vals, lambda a, b: a * b, mult_lookup)
plot_relative_error(a_vals, b_vals, lambda a, b: a / b, div_loookup)
if __name__ == "__main__":
main()
| return len(self.table_entries) |
settings.actions.ts | import { Action } from '@ngrx/store';
import { Language } from './settings.model';
export enum SettingsActionTypes {
CHANGE_LANGUAGE = '[Settings] Change Language',
CHANGE_THEME = '[Settings] Change Theme',
CHANGE_ANIMATIONS_PAGE = '[Settings] Change Animations Page',
CHANGE_ANIMATIONS_PAGE_DISABLED = '[Settings] Change Animations Page Disabled',
CHANGE_ANIMATIONS_ELEMENTS = '[Settings] Change Animations Elements',
CHANGE_HOUR = '[Settings] Change Hours'
}
export class ActionSettingsChangeLanguage implements Action {
readonly type = SettingsActionTypes.CHANGE_LANGUAGE;
constructor(readonly payload: { language: Language }) {}
}
export class ActionSettingsChangeTheme implements Action {
readonly type = SettingsActionTypes.CHANGE_THEME;
constructor(readonly payload: { theme: string }) {}
}
export class ActionSettingsChangeAnimationsPage implements Action {
readonly type = SettingsActionTypes.CHANGE_ANIMATIONS_PAGE;
constructor(readonly payload: { pageAnimations: boolean }) {}
}
export class ActionSettingsChangeAnimationsElements implements Action {
readonly type = SettingsActionTypes.CHANGE_ANIMATIONS_ELEMENTS;
constructor(readonly payload: { elementsAnimations: boolean }) {}
}
export class | implements Action {
readonly type = SettingsActionTypes.CHANGE_HOUR;
constructor(readonly payload: { hour: number }) {}
}
export type SettingsActions =
| ActionSettingsChangeLanguage
| ActionSettingsChangeTheme
| ActionSettingsChangeAnimationsPage
| ActionSettingsChangeAnimationsElements
| ActionSettingsChangeHour;
| ActionSettingsChangeHour |
string.js | /* eslint-env mocha */
/* eslint no-new-wrappers: 0 */
import expect from 'expect';
import fString from '../../src/types/string.js';
describe('string', () => {
context('.name', () => {
it('is "string"', () => {
expect(fString.name).toEqual('string');
});
});
context('.checker', () => {
it('accepts `new String()`', () => {
expect(fString.checker(new String())).toBe(true);
});
it('accepts empty string', () => {
expect(fString.checker('')).toBe(true);
});
it('accepts a filled string', () => {
expect(fString.checker('abc')).toBe(true);
});
it('refuses null', () => { | });
});
context('.printer', () => {
it('prints correctly an empty string', () => {
expect(fString.printer('')).toBe('""');
});
it('prints correctly a filled string', () => {
expect(fString.printer('abc')).toBe('"abc"');
});
});
}); | expect(fString.checker(null)).toBe(false); |
forms.py | from os.path import join
from email.mime.image import MIMEImage
from django.conf import settings
from django.forms import ModelForm, ValidationError, ChoiceField
from django.forms.models import BaseInlineFormSet
from django.forms.models import inlineformset_factory
from django.contrib.auth.forms import ReadOnlyPasswordHashWidget, ReadOnlyPasswordHashField, PasswordResetForm
from django.contrib.auth.tokens import default_token_generator
from django.core.mail import EmailMultiAlternatives
from django.template import loader
from crm.models import Person
from crm.forms import PersonSettingsForm
from django.contrib.auth.models import User
from security.forms import SecurityLevelModelFormMixin
from security.models import SecurityLevel
class UserAdminForm(SecurityLevelModelFormMixin, ModelForm):
"""
Override the user admin form so that we can force firstname, lastname
to be required --- needed for pushing changes over to crm.Person.
"""
password = ReadOnlyPasswordHashField(label=("Password"),
help_text=("Raw passwords are not stored, so there is no way to see "
"this user's password, but you can change the password "
"using <a href=\"password/\">this form</a>."))
# Need to minimally declare security_level here so that the user admin can see it.
# The mixin will take care of details.
security_level = ChoiceField()
def __init__(self, *args, **kwargs):
super(UserAdminForm, self).__init__(*args, **kwargs)
self.fields['first_name'].required = True
self.fields['last_name'].required = True
self.fields['email'].required = True
# self.fields['password'].widget = ReadOnlyPasswordHashWidget()
def get_security_level_default(self):
level_range = [x[0] for x in SecurityLevel.level_choices]
return max(level_range) # Default users to the lowest security level.
class Meta:
model = User
fields = '__all__'
class UserSettingsForm(ModelForm):
"""
This is the form used by the user menu to update user
profile settings. hides user password (for now).
"""
def __init__(self, *args, **kwargs):
super(UserSettingsForm, self).__init__(*args, **kwargs)
self.fields['first_name'].required = True
self.fields['last_name'].required = True
self.fields['email'].required = True
class Meta:
model = User
fields = ('first_name',
'last_name',
'email',)
class CedarPasswordResetForm(PasswordResetForm):
def | (self, subject_template_name, email_template_name,
context, from_email, to_email, html_email_template_name=None):
"""
Sends a django.core.mail.EmailMultiAlternatives to `to_email`.
"""
subject = loader.render_to_string(subject_template_name, context)
# Email subject *must not* contain newlines
subject = ''.join(subject.splitlines())
body = loader.render_to_string(email_template_name, context)
email_message = EmailMultiAlternatives(subject, body, from_email, [to_email])
if html_email_template_name is not None:
html_email = loader.render_to_string(html_email_template_name, context)
email_message.attach_alternative(html_email, 'text/html')
email_message.mixed_subtype = 'related'
with open(join(settings.STATIC_ROOT, 'css/cedarbox_icon_gry.png'), 'rb') as fp:
logo_img = MIMEImage(fp.read())
logo_img.add_header('Content-ID', '<{}>'.format('cedarbox_icon_gry.png'))
email_message.attach(logo_img)
email_message.send()
def save(self, domain_override=None,
subject_template_name='registration/password_reset_subject.txt',
email_template_name='registration/password_reset_email.html',
use_https=False, token_generator=default_token_generator,
from_email=None, request=None, html_email_template_name=None):
# If domain_override hasn't been provided. Let's override it ourself using the request.
if domain_override is None and request is not None:
domain_override = request.META['HTTP_HOST']
return super(CedarPasswordResetForm, self).save(
domain_override=domain_override,
subject_template_name=subject_template_name,
email_template_name=email_template_name,
use_https=use_https, token_generator=token_generator,
from_email=from_email, request=request, html_email_template_name=html_email_template_name
)
UserSettingsFormset = inlineformset_factory(User,
Person,
form=PersonSettingsForm,
extra=1
)
| send_mail |
update.spec.ts | import {SchematicTestRunner} from '@angular-devkit/schematics/testing';
import {migrationCollection} from '../utils/testing';
describe('material-nav-schematic', () => {
let runner: SchematicTestRunner;
beforeEach(() => {
runner = new SchematicTestRunner('schematics', migrationCollection); | });
}); |
|
mod.rs | use anyhow::anyhow;
use config::{Config, SortBy, SortOrder};
use std::fs::File;
use std::io;
use transaction::{Transaction, TransactionStatus};
mod formats;
pub struct | {}
impl TransactionIO {
pub fn import(config: &Config) -> anyhow::Result<Vec<Transaction>> {
let r: Box<dyn io::Read> = match config.src_file() {
Option::Some(f) => {
let f = File::open(f).map_err(|e| {
anyhow!(
"An error occurred while trying to open file [{}]: {}",
f.to_str().unwrap_or("Invalid file name"),
e
)
})?;
Box::new(io::BufReader::new(f))
}
Option::None => Box::new(io::stdin()),
};
let transactions = formats::import_from_configurable_format(r, config.src_format())?;
let transactions = filter(config, transactions);
let transactions = normalize_and_categorize(config, transactions);
Ok(transactions)
}
pub fn export(config: &Config, transactions: Vec<Transaction>) -> anyhow::Result<()> {
// Sort transactions just before exporting
let transactions = sort(config, transactions);
let w: Box<dyn io::Write> = match config.dst_file() {
Option::Some(f) => {
let f = File::create(f).map_err(|e| {
anyhow!(
"An error occurred while trying to open file [{}]: {}",
f.to_str().unwrap_or("Invalid file name"),
e
)
})?;
Box::new(io::BufWriter::new(f))
}
Option::None => Box::new(io::stdout()),
};
formats::export_to_configurable_format(w, config, config.dst_format(), transactions)?;
Ok(())
}
}
fn filter(config: &Config, mut transactions: Vec<Transaction>) -> Vec<Transaction> {
// We only support filtering pending transactions now, so just bail if we don't want to
// ignore pending.
if !config.ignore_pending() {
return transactions;
}
transactions.retain(|e| e.status == TransactionStatus::Cleared);
transactions
}
fn normalize_and_categorize(
config: &Config,
mut transactions: Vec<Transaction>,
) -> Vec<Transaction> {
transactions.iter_mut().for_each(|t| {
t.normalize_payee(config);
t.categorize(config);
});
transactions
}
fn sort(config: &Config, mut transactions: Vec<Transaction>) -> Vec<Transaction> {
if config.sort_by().is_none() || config.sort_order().is_none() {
return transactions;
}
let get_data_fn = match config.sort_by().unwrap() {
// todo: don't create an owned copy
SortBy::Date => |t: &Transaction| t.date().to_owned(),
};
if let Option::Some(ref sort_order) = config.sort_order() {
transactions.sort_by(|a, b| {
if SortOrder::Ascending == *sort_order {
get_data_fn(a).cmp(&get_data_fn(b))
} else {
get_data_fn(a).cmp(&get_data_fn(b)).reverse()
}
});
}
transactions
}
| TransactionIO |
login.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { HoodService } from '../hood.service'
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
input;
constructor(private hoodService: HoodService, private rouuter: Router) { }
ngOnInit(): void {
this.input = {
username: '',
password: '',
}
}
// onRegister() {
// this.hoodService.registerUser(this.input).subscribe(res:Response => {
// alert('user' + this.input.username + 'created')
// }, error => {
// console.log('error')
// });
// }
// onRegister() {
// this.hoodService.registerUser(this.input).subscribe((res: Response) => {
// alert('user' + this.input.username + 'created')
// console.log(res)
// }, error => {
// console.log('error')
// })
// }
onLogin() {
this.hoodService.loginUser(this.input).subscribe((res: Response) => {
// let token = res.json() && res.json().token;
console.log(res)
localStorage.setItem('accessToken', res['access'])
this.rouuter.navigate(['/allposts'])
// console.log(res['access'])
}, error => { | console.log('error')
})
}
} | |
Core.js | 'use strict';
/**
* Engagement Lab
* - Learning Games Core Functionality
* Developed by Engagement Lab, 2016-2017
* ==============
* Common functionality game controller for the Lab's socket-based learning games
*
* @author Johnny Richardson, Erica Salling
*
* ==========
*/
class Core {
constructor() {
// Duration to wait for player to refresh client before timing her out (TODO: config value)
this._player_timeout_duration = 10000,
this.Templates,
this.Session = require('./SessionManager'),
this.events = require('events'),
this.eventEmitter = new this.events.EventEmitter(),
this._current_players = {},
this._current_player_index = 0,
this._game_session,
this._game_timeout,
this._game_in_session,
this._config,
this._current_submissions = {},
this._players_submitted = [],
this._countdown,
this._countdown_duration,
this._countdown_paused,
this._event_countdown_done,
this._current_round,
this._showing_results = false,
this._votes = 0,
// Stores last event sent and its data
this._objLastTemplate,
this._strLastEventId,
this._current_player_cap,
// Identifies targets for socket events
this.players_id,
this.group_id,
this._group_socket,
// Flag for if session is being restarted
this._session_restarting;
}
/**
* Initialize this game's session.
*
* @param {Object} gameSession Player socket ID
* @param {Function} callback Function to fire after session initialized
* @class Core
* @name Initialize
*/
Initialize(gameSession, keystone, appRoot, callback) {
this.keystone = keystone;
this.appRoot = appRoot;
this._game_in_session = false;
var GameConfig = this.keystone.list('GameConfig').model;
this._countdown_paused = false;
this._session_restarting = false;
// Init session
this._game_session = gameSession;
// Init template loader with current game type
var TemplateLoader = require('./TemplateLoader');
this.Templates = new TemplateLoader(gameSession.gameType, this.keystone, this.appRoot);
// Identify targets for socket events
this.players_id = gameSession.accessCode,
this.group_id = gameSession.accessCode + '-group';
// Get config for game
var queryConfig = GameConfig.findOne({gameType: new RegExp('^'+gameSession.gameType+'$', "i")}, {}, {});
// If no gametype, get singular config
if(!gameSession.gameType)
queryConfig = GameConfig.findOne({});
queryConfig.exec((err, resultConfig) => {
this._config = resultConfig;
callback(this._config);
});
}
/**
* Gets a player's object given their socket ID
*
* @param {String} Player socket ID
* @class Core
* @name GetPlayerById
* @return {Boolean} Player object, if found
*/
GetPlayerById(id) {
let player = _.findWhere(this._current_players, {socket_id: id});
if(!player) {
console.log('Could not find player with socket id %s', id);
return null;
}
return player;
}
/**
* Gets a player's object given their unique user ID
*
* @param {String} Player unique user ID
* @class Core
* @name GetPlayerByUserId
* @return {Boolean} Player object, if found
*/
GetPlayerByUserId(id) {
let player = _.findWhere(this._current_players, {uid: id});
if(!player) {
console.log('Could not find player with uid %s', id);
return null;
}
return player;
}
/**
* Gets the game's type
*
* @class Core
* @name GetGameType
* @return {String} Game's Type
*/
GetGameType() {
return this._game_session.gameType;
}
/**
* Gets if session is resetting
*
* @class Core
* @name IsRestarting
* @return {Boolean} Is session restarting?
*/
IsRestarting() {
return this._session_restarting;
}
/**
* Gets if game is full of players
*
* @class Core
* @name IsFull
* @return {Boolean} Is game entirely full?
*/
IsFull() {
return (Object.keys(this._current_players).length === 8);
}
/**
* Is username a player entered available?
*
* @param {String} name Username
* @class Core
* @name UsernameAvailable
* @return {Boolean} Is username available?
*/
UsernameAvailable(name) {
return (_.where(this._current_players, {username: name}).length === 0);
}
/**
* Is player whose UID is provided still active?
*
* @param {String} Player UID
* @class Core
* @name PlayerIsActive
* @return {Boolean} Is player active?
*/
PlayerIsActive(uid) {
// If game is not currently in session, no player is marked as active
// if(!this._game_in_session)
// return false;
return this._current_players[uid] !== undefined;
}
/**
* Get if session is currently active.
*
* @class Core
* @name GameInSession
* @return {Boolean} _game_in_session Is session active?
*/
GameInSession() {
return this._game_in_session;
}
/**
* Flag the session as in restarting state
*
* @class Core
* @name SetToRestarting
*/
SetToRestarting() {
this._session_restarting = true;
}
/**
* Reset session's state to default
*
* @class Core
* @name Reset
*/
Reset() {
// Stop countdown
clearInterval(this._countdown);
this._countdown = undefined;
this._countdown_paused = false;
this._current_players = {};
this._current_submissions = {};
this._players_submitted = [];
this._current_player_index = 0;
this._game_in_session = false;
console.info('Game "' + this._game_session.accessCode + '" ended! ');
}
/**
* Begin the game's tutorial.
* @param {Object} Group moderator socket
* @class Core
* @name StartTutorial
*/
StartTutorial(socket) {
// If there are (somehow) more than 8 players when START button is pressed, kick them out!
if (this._current_players.length >= 8) {
// TO DO: Kick out extra players
}
this.Templates.Load('partials/group/tutorial', undefined, (html) => {
socket.to(this.group_id).emit('game:tutorial', html);
});
}
/**
* Begin a cooldown clock for the session
*
* @param {Object} Group moderator socket
* @param {Object} Data object w/ duration, name of countdown
* @param {Boolean} Is countdown for players as well as group?
* @class Core
* @name Countdown
*/
Countdown(socket, data, forPlayers) {
if(this._countdown)
clearInterval(this._countdown);
// Use provided time limit if defined
if(data && data.timeLimit)
this._countdown_duration = data.timeLimit;
else
this._countdown_duration = this._config.timeLimit;
let halfway = this._countdown_duration/2;
let quarterway = halfway/2;
// Dispatch time to group view
let socketInfo = {duration: this._countdown_duration}
if(data && data.countdownName)
socketInfo.name = data.countdownName;
if(forPlayers)
socket.to(this.players_id).emit('game:countdown', socketInfo);
else
socket.to(this.group_id).emit('game:countdown', socketInfo);
// Start countdown
this._countdown = setInterval(() => {
if(this._countdown_paused)
return;
this._countdown_duration--;
if(this._countdown_duration === 0) {
// Tell the players time is up
if(forPlayers)
this._group_socket.to(this.players_id).emit('game:countdown_end', data.countdownName);
else
this._group_socket.to(this.group_id).emit('game:countdown_end', data.countdownName);
// Send the countdownEnded event to the game script
this.eventEmitter.emit('countdownEnded', data, socket);
// Clear the countdown
this.StopCountdown();
}
// TODO: This needs to be its own timeout given use of this method for a lot of game events
else if(this._countdown_duration === 15) {
// Dispatch countdown when running out of time for player
this.Templates.Load('partials/player/timerunningout', undefined, (html) => {
socket.to(this.players_id).emit('game:countdown_ending', {html: html, socket: this.players_id});
});
}
}, 1000);
}
/**
* Pause or resume session's current cooldown clock. For debug purposes only and disabled for production.
*
* @class Core
* @name PauseResumeCooldown
*/
PauseResumeCooldown() {
if(process.env.NODE_ENV === 'production')
return;
this._countdown_paused = !this._countdown_paused;
this._group_socket.to(this.group_id).emit('debug:pause');
}
/**
* Stop session's current cooldown clock.
*
* @class Core
* @name StopCountdown
*/
StopCountdown() {
clearInterval(this._countdown);
this.eventEmitter.removeAllListeners('countdownEnded');
}
/**
* Signaled when group moderator joins/re-joins session, setting up group socket and resuming game (if applicable)
*
* @param {Object} Group moderator's socket
* @class Core
* @name ModeratorJoin
*/
ModeratorJoin(socket) {
clearInterval(this._game_timeout);
// Setup group socket (used for some methods dispatched from emitter)
this._group_socket = socket;
// End restarting state
this._session_restarting = false;
// Inform players of resumed game (if applicable)
socket.to(this.PLAYERS_ID).emit('game:resumed');
}
/**
* Reset and delete this session, and force all players to disconnect. Optionally, wait a bit to end game in case moderator re-connects.
*
* @param {Object} Socket for group
* @param {Boolean} Wait xx seconds before ending game?
* @class Core
* @name End
*/
End(socket, noTimeout) {
if(!noTimeout) {
var timeoutTime = 30;
console.info('Game "' + this._game_session.accessCode + '" is timing out! ');
this._game_timeout = setInterval(() => {
timeoutTime--;
if(timeoutTime === 0) {
clearInterval(this._game_timeout);
this.Reset();
this.Session.Delete(this.players_id);
this.Templates.Load('partials/player/gameended', undefined, (html) => {
socket.to(this.players_id).emit('game:ended', html);
this._objLastTemplate = html;
this._strLastEventId = 'game:ended';
// Force all players to disconnect
for(let player in this._current_players)
socket.sockets.sockets[player.socket_id].disconnect(true);
});
}
else {
// Dispatch countdown for game timeout
this.Templates.Load('partials/player/gameending', {time: timeoutTime}, (html) => {
socket.to(this.players_id).emit('game:ending', html);
this._objLastTemplate = html;
this._strLastEventId = 'game:ending';
});
}
}, 1000);
this._game_in_session = false;
}
else {
this.Reset();
this.Session.Delete(this.players_id);
// Dispatch countdown for game timeout
this.Templates.Load('partials/player/gameended', {time: timeoutTime}, (html) => {
socket.to(this.players_id).emit('game:ended', html);
socket.to(this.group_id).emit('game:ended', html);
this._objLastTemplate = html;
this._strLastEventId = 'game:ended';
// Force all players to disconnect
for(let player in this._current_players)
socket.sockets.sockets[player.socket_id].disconnect(true);
});
}
}
/**
* Join player to session, or re-connect them and sync s/he to session.
*
* @param {Object} The player object
* @param {Object} The player's socket
* @class Core
* @name PlayerReady
*/
PlayerReady(player, socket) {
if (this._current_player_cap >= 8) {
socket.to(player.socket_id).emit('game:error', "Uh oh, looks like this game is full! Removing you from the game...");
return;
}
// If player is re-connecting, set them back to connected, and re-broadcast the last update
if(this._current_players[player.uid]) {
this._current_players[player.uid].connected = true;
this._current_players[player.uid].socket_id = player.socket_id;
console.info(player.username + ' has re-joined the game and has uid ' + player.uid);
socket.emit(this._strLastEventId, {waitForLoad: true, html: this._objLastTemplate});
}
else {
this._current_players[player.uid] = {
username: player.username,
socket_id: player.socket_id,
uid: player.uid,
index: this._current_player_index,
submitted: false,
connected: true
};
console.info(player.username + ' has joined the game and has uid ' + player.uid, '('+this._game_session.accessCode+')');
this._current_player_index++;
socket.to(this.group_id).emit('players:update', {players: _.sortBy(this._current_players, function(player) {return player.index}), state: 'gained_player'});
}
// Get current # of players
this._current_player_cap = Object.keys(this._current_players).length;
}
/**
* Deactivate player for now and start cooldown for them to re-join within, after which they're removed from session.
*
* @param {String} The player's socket ID
* @class Core
* @name PlayerLost
*/
PlayerLost(playerSocketId) {
let thisPlayer = this.GetPlayerById(playerSocketId)
if(!thisPlayer)
return;
thisPlayer.connected = false;
// Decrease current # of players
this._current_player_cap--;
// If game is currently in session, give player 10s to refresh before booting them...
if(this._game_in_session) {
setTimeout(() => {
this.PlayerRemove(thisPlayer);
}, this._player_timeout_duration);
}
// ...otherwise, kick 'em out now
else
this.PlayerRemove(thisPlayer);
}
/**
* Remove the given player from the game and broadcast new player list.
*
* @param {Object} The player
* @class Core
* @name PlayerRemove
*/
PlayerRemove(player) {
// If player has not managed to re-connect...
if (!player.connected) {
delete this._current_players[player.uid];
this._group_socket.to(this.group_id).emit(
'players:update',
{ players: _.sortBy(this._current_players, function(player) {return player.index}),
state: 'lost_player'
}
);
// If only one player left, end the game now | return;
}
this.End(this._group_socket, true);
}
}
}
/**
* Advance session's round while saving its data to DB.
*
* @class Core
* @name AdvanceRound
*/
AdvanceRound(socket) {
this._showing_results = false;
// Reset players state for next round
_.each(this._current_players, (playerId, index) => {
this._current_players[index] = _.omit(this._current_players[index], 'score');
this._current_players[index].submitted = false;
});
this.SaveSession();
socket.emit('game:advance');
// Advance round
this._current_round++;
}
/**
* Display survey for all players, if one if enabled for this game.
*
* @class Core
* @name DisplaySurvey
*/
DisplaySurvey(socket) {
if(this._config.survey)
socket.to(this.players_id).emit('game:survey');
}
/**
* Calculate/tally player's current round and total score.
*
* @param {Object} The player
* @param {Boolean} Current points value
* @class Core
* @name CalcPlayerScore
*/
CalcPlayerScore(currentPlayer, points) {
if(currentPlayer.socket_id === this.realId)
return;
// Set points for this round
if (!currentPlayer.score)
currentPlayer.score = points;
else
currentPlayer.score += points;
// Set total points
if(!currentPlayer.score_total)
currentPlayer.score_total = points;
else
currentPlayer.score_total += points;
logger.info(currentPlayer.username + ' points this round are ' + currentPlayer.score);
logger.info(currentPlayer.username + ' score is now ' + currentPlayer.score_total);
return points;
}
/**
* Save the current 'state' of all players. When a player re-joins, we retrieve this state for them.
*
* @param {String} Event ID
* @param {Object} The event's rendered template
* @class Core
* @name SaveState
*/
SaveState(strEventId, objTemplate) {
this._strLastEventId = strEventId;
this._objLastTemplate = objTemplate;
// Save debug data?
if(process.env.NODE_ENV !== 'production') {
if(!this._game_session.debugData)
this._game_session.debugData = {};
this._game_session.debugData[strEventId] = objTemplate;
this.SaveSession();
}
}
/**
* Save the session's current data to Mongo
*
* @class Core
* @name SaveSession
*/
SaveSession() {
this.Session.Save(this._game_session);
}
}
module.exports.Core = Core,
module.exports.SessionManager = require('./SessionManager');
module.exports.TemplateLoader = require('./TemplateLoader');
module.exports.ShuffleUtil = require('./ShuffleUtil'); | if(Object.keys(this._current_players).length <= 1 && this._game_in_session) {
if (this._showing_results && (this._current_round === this._config.roundNumber -1)){ |
AdvML_Week6_ex2.py | #!/usr/bin/env python
# coding: utf-8
# In[8]:
## Advanced Course in Machine Learning
## Week 6
## Exercise 2 / Random forest
import numpy as np
import scipy
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from numpy import linalg as LA
from sklearn import decomposition
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import pairwise_distances
from sklearn.manifold import TSNE
import math
import sys
import mnist
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import cross_val_score
sns.set_style("darkgrid")
# In[4]:
x_train, t_train, x_test, t_test = mnist.load()
# In[48]:
x_train = x_train[0:50000,:]
t_train = t_train[0:50000]
# In[49]:
print(x_train.shape)
print(t_train.shape)
print(x_test.shape)
print(t_test.shape)
# In[69]:
startTestIx = 0
endTestIx = 100
# clf.classes_
# clf.feature_importances_
# print(clf.max_features_)
# print(clf.n_classes_)
# print(clf.n_features_)
# print(clf.n_outputs_)
# #clf.tree_
# In[70]:
# Randomly select the samples and features for the tree
def sample(n, k, x_train, t_train):
idx = np.random.randint(x_train.shape[0], size=n)
fidx = np.random.randint(x_train.shape[1], size=k)
x = x_train[idx, :]
x = x[:, fidx]
y = t_train[idx]
return x, y, idx, fidx
#print("Rows: ", idx, ", features ", fidx)
#print(x.shape)
#print(y.shape)
# In[71]:
def trainTree(x_train, t_train):
|
#cross_val_score(clf, x_train, t_train, cv=10)
# In[72]:
def ensureAllClasses(newPred, clf):
for i in range(10):
if i not in clf.classes_:
newPred = np.insert(newPred, i, 0, axis=1)
return newPred
# In[75]:
# Main loop
def main(M, n, k):
pred = np.zeros(shape = (endTestIx - startTestIx, 10), dtype = 'float32')
for m in range(M):
x, y, idx, fidx = sample(n, k, x_train, t_train)
clf = trainTree(x, y)
newPred = clf.predict_proba(x_test[startTestIx:endTestIx,fidx])
newPred = ensureAllClasses(newPred, clf)
pred = np.add(pred, newPred)
pred_classes = np.argmax(pred, axis=1)
correct = pred_classes == t_test[startTestIx:endTestIx]
acc = sum(correct)/len(correct)
#print(pred_classes)
#print (acc)
return acc
# In[85]:
Mmax = 100
n = 1000
k = 20
accs = list()
for m in range(1, Mmax):
accs.append(main(m, n, k))
plt.figure(num=None, figsize=(8, 6), dpi=100, facecolor='w', edgecolor='k')
sns.lineplot(range(1,Mmax), accs)
plt.xlabel('Number of trees (M)')
plt.ylabel('Accuracy of predictions (%)')
plt.title('Number of trees vs. accuracy, n = {0}, k = {1}'.format(n, k))
plt.show()
# In[80]:
M = 100
n = 1000
kmax = 200
accs = list()
for k in range(1, kmax, 10):
accs.append(main(M, n, k))
plt.figure(num=None, figsize=(8, 6), dpi=100, facecolor='w', edgecolor='k')
sns.lineplot(range(1,kmax,10), accs)
plt.xlabel('Number of features per tree (k)')
plt.ylabel('Accuracy of predictions (%)')
plt.title('Number of features per tree vs. accuracy, M = {0}, n = {1}'.format(M, n))
plt.show()
# In[81]:
M = 100
nmax = 5000
k = 50
accs = list()
for n in range(1, nmax, 100):
accs.append(main(M, n, k))
plt.figure(num=None, figsize=(8, 6), dpi=100, facecolor='w', edgecolor='k')
sns.lineplot(range(1, nmax, 100), accs)
plt.xlabel('Number of samples per tree (n)')
plt.ylabel('Accuracy of predictions (%)')
plt.title('Number of samples per tree vs. accuracy, M = {0}, k = {1}'.format(M, k))
plt.show()
# In[84]:
M = 100
n = 1000
k = 50
repeats = 50
accs = list()
for i in range(50):
accs.append(main(M, n, k))
avAcc = sum(accs)/len(accs)
print(avAcc)
| clf = DecisionTreeClassifier(random_state=0)
clf = clf.fit(x_train, t_train)
return clf |
lib.rs | // Copyright 2020 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
use crypto::SignatureType;
use jsonrpc_v2::Error as JsonRpcError;
use jsonwebtoken::errors::Result as JWTResult;
use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header};
use rand::Rng;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use wallet::KeyInfo;
/// constant string that is used to identify the JWT secret key in KeyStore
pub const JWT_IDENTIFIER: &str = "auth-jwt-private";
/// Admin permissions
pub const ADMIN: [&str; 4] = ["read", "write", "sign", "admin"];
/// Signing permissions
pub const SIGN: [&str; 3] = ["read", "write", "sign"];
/// Writing permissions
pub const WRITE: [&str; 2] = ["read", "write"];
/// Reading permissions
pub const READ: [&str; 1] = ["read"];
/// All methods that require write permission
pub const WRITE_ACCESS: [&str; 6] = [
"Filecoin.MpoolPush",
"Filecoin.WalletNew",
"Filecoin.WalletHas",
"Filecoin.WalletList",
"Filecoin.WalletDefaultAddress",
"Filecoin.WalletList",
];
/// Error Enum for Authentification
#[derive(Debug, Error, Serialize, Deserialize)]
pub enum Error {
/// Filecoin Method does not exist
#[error("Filecoin method does not exist")]
MethodParam,
/// Invalid permissions to use specified method
#[error("Incorrect permissions to access method")]
InvalidPermissions,
/// Missing authentication header
#[error("Missing authentication header")]
NoAuthHeader,
#[error("{0}")]
Other(String),
}
/// Claim struct for JWT Tokens
#[derive(Debug, Serialize, Deserialize)]
struct | {
#[serde(rename = "Allow")]
allow: Vec<String>,
}
/// Create a new JWT Token
pub fn create_token(perms: Vec<String>, key: &[u8]) -> JWTResult<String> {
let payload = Claims { allow: perms };
encode(&Header::default(), &payload, &EncodingKey::from_secret(key))
}
/// Verify JWT Token and return the allowed permissions from token
pub fn verify_token(token: &str, key: &[u8]) -> JWTResult<Vec<String>> {
let validation = jsonwebtoken::Validation {
validate_exp: false,
..Default::default()
};
let token = decode::<Claims>(token, &DecodingKey::from_secret(key), &validation)?;
Ok(token.claims.allow)
}
/// Check whether or not header has required permissions
pub fn has_perms(header_raw: String, required: &str, key: &[u8]) -> Result<(), JsonRpcError> {
if header_raw.starts_with("Bearer: ") {
let token = header_raw.trim_start_matches("Bearer: ");
let perms = verify_token(token, key).map_err(|err| Error::Other(err.to_string()))?;
if !perms.contains(&required.to_string()) {
return Err(JsonRpcError::from(Error::InvalidPermissions));
}
}
Ok(())
}
pub fn generate_priv_key() -> KeyInfo {
let priv_key = rand::thread_rng().gen::<[u8; 32]>();
// TODO temp use of bls key as placeholder, need to update keyinfo to use string instead of keyinfo
// for key type
KeyInfo::new(SignatureType::BLS, priv_key.to_vec())
}
| Claims |
network.go | // Copyright 2018 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package main
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"time"
toxiproxy "github.com/Shopify/toxiproxy/client"
"github.com/cockroachdb/cockroach/pkg/util/httputil"
_ "github.com/lib/pq"
)
// runNetworkSanity is just a sanity check to make sure we're setting up toxiproxy
// correctly. It injects latency between the nodes and verifies that we're not
// seeing the latency on the client connection running `SELECT 1` on each node.
func runNetworkSanity(ctx context.Context, t *test, origC *cluster, nodes int) {
origC.Put(ctx, cockroach, "./cockroach", origC.All())
c, err := Toxify(ctx, origC, origC.All())
if err != nil {
t.Fatal(err)
}
c.Start(ctx, t, c.All())
db := c.Conn(ctx, 1) // unaffected by toxiproxy
defer db.Close()
waitForFullReplication(t, db)
// NB: we're generous with latency in this test because we're checking that
// the upstream connections aren't affected by latency below, but the fixed
// cost of starting the binary and processing the query is already close to
// 100ms.
const latency = 300 * time.Millisecond
for i := 1; i <= nodes; i++ {
// NB: note that these latencies only apply to connections *to* the node
// on which the toxic is active. That is, if n1 has a (down or upstream)
// latency toxic of 100ms, then none of its outbound connections are
// affected but any connections made to it by other nodes will.
// In particular, it's difficult to simulate intricate network partitions
// as there's no way to activate toxics only for certain peers.
proxy := c.Proxy(i)
if _, err := proxy.AddToxic("", "latency", "downstream", 1, toxiproxy.Attributes{
"latency": latency / (2 * time.Millisecond), // ms
}); err != nil {
t.Fatal(err)
}
if _, err := proxy.AddToxic("", "latency", "upstream", 1, toxiproxy.Attributes{
"latency": latency / (2 * time.Millisecond), // ms
}); err != nil {
t.Fatal(err)
}
}
m := newMonitor(ctx, c.cluster, c.All())
m.Go(func(ctx context.Context) error {
c.Measure(ctx, 1, `SET CLUSTER SETTING trace.debug.enable = true`)
c.Measure(ctx, 1, "CREATE DATABASE test")
c.Measure(ctx, 1, `CREATE TABLE test.commit (a INT, b INT, v INT, PRIMARY KEY (a, b))`)
for i := 0; i < 10; i++ {
duration := c.Measure(ctx, 1, fmt.Sprintf(
"BEGIN; INSERT INTO test.commit VALUES (2, %[1]d), (1, %[1]d), (3, %[1]d); COMMIT",
i,
))
c.l.Printf("%s\n", duration)
}
c.Measure(ctx, 1, `
set tracing=on;
insert into test.commit values(3,1000), (1,1000), (2,1000);
select age, message from [ show trace for session ];
`)
for i := 1; i <= origC.spec.NodeCount; i++ {
if dur := c.Measure(ctx, i, `SELECT 1`); dur > latency {
t.Fatalf("node %d unexpectedly affected by latency: select 1 took %.2fs", i, dur.Seconds())
}
}
return nil
})
m.Wait()
}
func runNetworkTPCC(ctx context.Context, t *test, origC *cluster, nodes int) |
func registerNetwork(r *testRegistry) {
const numNodes = 4
r.Add(testSpec{
Name: fmt.Sprintf("network/sanity/nodes=%d", numNodes),
Owner: OwnerKV,
Cluster: makeClusterSpec(numNodes),
Run: func(ctx context.Context, t *test, c *cluster) {
runNetworkSanity(ctx, t, c, numNodes)
},
})
r.Add(testSpec{
Name: fmt.Sprintf("network/tpcc/nodes=%d", numNodes),
Owner: OwnerKV,
Cluster: makeClusterSpec(numNodes),
Run: func(ctx context.Context, t *test, c *cluster) {
runNetworkTPCC(ctx, t, c, numNodes)
},
})
}
| {
n := origC.spec.NodeCount
serverNodes, workerNode := origC.Range(1, n-1), origC.Node(n)
origC.Put(ctx, cockroach, "./cockroach", origC.All())
origC.Put(ctx, workload, "./workload", origC.All())
c, err := Toxify(ctx, origC, serverNodes)
if err != nil {
t.Fatal(err)
}
const warehouses = 1
c.Start(ctx, t, serverNodes)
c.Run(ctx, workerNode, fmt.Sprintf(
`./workload fixtures load tpcc --warehouses=%d {pgurl:1}`, warehouses,
))
db := c.Conn(ctx, 1)
defer db.Close()
waitForFullReplication(t, db)
duration := time.Hour
if local {
// NB: this is really just testing the test with this duration, it won't
// be able to detect slow goroutine leaks.
duration = 5 * time.Minute
}
// Run TPCC, but don't give it the first node (or it basically won't do anything).
m := newMonitor(ctx, c.cluster, serverNodes)
m.Go(func(ctx context.Context) error {
t.WorkerStatus("running tpcc")
cmd := fmt.Sprintf(
"./workload run tpcc --warehouses=%d --wait=false"+
" --histograms="+perfArtifactsDir+"/stats.json"+
" --duration=%s {pgurl:2-%d}",
warehouses, duration, c.spec.NodeCount-1)
return c.RunE(ctx, workerNode, cmd)
})
checkGoroutines := func(ctx context.Context) int {
// NB: at the time of writing, the goroutine count would quickly
// stabilize near 230 when the network is partitioned, and around 270
// when it isn't. Experimentally a past "slow" goroutine leak leaked ~3
// goroutines every minute (though it would likely be more with the tpcc
// workload above), which over the duration of an hour would easily push
// us over the threshold.
const thresh = 350
uiAddrs := c.ExternalAdminUIAddr(ctx, serverNodes)
var maxSeen int
// The goroutine dump may take a while to generate, maybe more
// than the 3 second timeout of the default http client.
httpClient := httputil.NewClientWithTimeout(15 * time.Second)
for _, addr := range uiAddrs {
url := "http://" + addr + "/debug/pprof/goroutine?debug=2"
resp, err := httpClient.Get(ctx, url)
if err != nil {
t.Fatal(err)
}
content, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
t.Fatal(err)
}
numGoroutines := bytes.Count(content, []byte("goroutine "))
if numGoroutines >= thresh {
t.Fatalf("%s shows %d goroutines (expected <%d)", url, numGoroutines, thresh)
}
if maxSeen < numGoroutines {
maxSeen = numGoroutines
}
}
return maxSeen
}
m.Go(func(ctx context.Context) error {
time.Sleep(10 * time.Second) // give tpcc a head start
// Give n1 a network partition from the remainder of the cluster. Note that even though it affects
// both the "upstream" and "downstream" directions, this is in fact an asymmetric partition since
// it only affects connections *to* the node. n1 itself can connect to the cluster just fine.
proxy := c.Proxy(1)
c.l.Printf("letting inbound traffic to first node time out")
for _, direction := range []string{"upstream", "downstream"} {
if _, err := proxy.AddToxic("", "timeout", direction, 1, toxiproxy.Attributes{
"timeout": 0, // forever
}); err != nil {
t.Fatal(err)
}
}
t.WorkerStatus("checking goroutines")
done := time.After(duration)
var maxSeen int
for {
cur := checkGoroutines(ctx)
if maxSeen < cur {
c.l.Printf("new goroutine peak: %d", cur)
maxSeen = cur
}
select {
case <-done:
c.l.Printf("done checking goroutines, repairing network")
// Repair the network. Note that the TPCC workload would never
// finish (despite the duration) without this. In particular,
// we don't want to m.Wait() before we do this.
toxics, err := proxy.Toxics()
if err != nil {
t.Fatal(err)
}
for _, toxic := range toxics {
if err := proxy.RemoveToxic(toxic.Name); err != nil {
t.Fatal(err)
}
}
c.l.Printf("network is repaired")
// Verify that goroutine count doesn't spike.
for i := 0; i < 20; i++ {
nowGoroutines := checkGoroutines(ctx)
c.l.Printf("currently at most %d goroutines per node", nowGoroutines)
time.Sleep(time.Second)
}
return nil
default:
time.Sleep(3 * time.Second)
}
}
})
m.Wait()
} |
clusterconfig.go | /*
Copyright AppsCode Inc. and Contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by lister-gen. DO NOT EDIT.
package v1alpha1
import (
v1alpha1 "kubeform.dev/provider-mongodbatlas-api/apis/global/v1alpha1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/tools/cache"
)
// ClusterConfigLister helps list ClusterConfigs.
// All objects returned here must be treated as read-only.
type ClusterConfigLister interface {
// List lists all ClusterConfigs in the indexer.
// Objects returned here must be treated as read-only.
List(selector labels.Selector) (ret []*v1alpha1.ClusterConfig, err error)
// ClusterConfigs returns an object that can list and get ClusterConfigs.
ClusterConfigs(namespace string) ClusterConfigNamespaceLister | type clusterConfigLister struct {
indexer cache.Indexer
}
// NewClusterConfigLister returns a new ClusterConfigLister.
func NewClusterConfigLister(indexer cache.Indexer) ClusterConfigLister {
return &clusterConfigLister{indexer: indexer}
}
// List lists all ClusterConfigs in the indexer.
func (s *clusterConfigLister) List(selector labels.Selector) (ret []*v1alpha1.ClusterConfig, err error) {
err = cache.ListAll(s.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*v1alpha1.ClusterConfig))
})
return ret, err
}
// ClusterConfigs returns an object that can list and get ClusterConfigs.
func (s *clusterConfigLister) ClusterConfigs(namespace string) ClusterConfigNamespaceLister {
return clusterConfigNamespaceLister{indexer: s.indexer, namespace: namespace}
}
// ClusterConfigNamespaceLister helps list and get ClusterConfigs.
// All objects returned here must be treated as read-only.
type ClusterConfigNamespaceLister interface {
// List lists all ClusterConfigs in the indexer for a given namespace.
// Objects returned here must be treated as read-only.
List(selector labels.Selector) (ret []*v1alpha1.ClusterConfig, err error)
// Get retrieves the ClusterConfig from the indexer for a given namespace and name.
// Objects returned here must be treated as read-only.
Get(name string) (*v1alpha1.ClusterConfig, error)
ClusterConfigNamespaceListerExpansion
}
// clusterConfigNamespaceLister implements the ClusterConfigNamespaceLister
// interface.
type clusterConfigNamespaceLister struct {
indexer cache.Indexer
namespace string
}
// List lists all ClusterConfigs in the indexer for a given namespace.
func (s clusterConfigNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.ClusterConfig, err error) {
err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {
ret = append(ret, m.(*v1alpha1.ClusterConfig))
})
return ret, err
}
// Get retrieves the ClusterConfig from the indexer for a given namespace and name.
func (s clusterConfigNamespaceLister) Get(name string) (*v1alpha1.ClusterConfig, error) {
obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.NewNotFound(v1alpha1.Resource("clusterconfig"), name)
}
return obj.(*v1alpha1.ClusterConfig), nil
} | ClusterConfigListerExpansion
}
// clusterConfigLister implements the ClusterConfigLister interface. |
tab_header.rs | use druid::{
kurbo::Line, BoxConstraints, Command, Env, Event, EventCtx, LayoutCtx,
LifeCycle, LifeCycleCtx, MouseEvent, PaintCtx, Point, RenderContext, Size,
Target, UpdateCtx, Widget, WidgetId, WidgetPod,
};
use lapce_data::{
command::{
CommandTarget, LapceCommand, LapceCommandNew, LapceUICommand,
LAPCE_NEW_COMMAND, LAPCE_UI_COMMAND,
},
config::LapceTheme,
data::LapceTabData,
svg::get_svg,
};
use crate::{
editor::tab_header_content::LapceEditorTabHeaderContent, scroll::LapceScrollNew,
tab::LapceIcon,
};
pub struct LapceEditorTabHeader {
pub widget_id: WidgetId,
pub content: WidgetPod<
LapceTabData,
LapceScrollNew<LapceTabData, LapceEditorTabHeaderContent>,
>,
icons: Vec<LapceIcon>,
mouse_pos: Point,
is_hot: bool,
}
impl LapceEditorTabHeader {
pub fn new(widget_id: WidgetId) -> Self {
let content =
LapceScrollNew::new(LapceEditorTabHeaderContent::new(widget_id))
.horizontal();
Self {
widget_id,
content: WidgetPod::new(content),
icons: Vec::new(),
mouse_pos: Point::ZERO,
is_hot: false,
}
}
fn icon_hit_test(&self, mouse_event: &MouseEvent) -> bool {
for icon in self.icons.iter() {
if icon.rect.contains(mouse_event.pos) {
return true;
}
}
false
}
fn mouse_down(&self, ctx: &mut EventCtx, mouse_event: &MouseEvent) {
for icon in self.icons.iter() {
if icon.rect.contains(mouse_event.pos) {
ctx.submit_command(icon.command.clone());
}
}
}
}
impl Widget<LapceTabData> for LapceEditorTabHeader {
fn id(&self) -> Option<WidgetId> {
Some(self.widget_id)
}
fn event(
&mut self,
ctx: &mut EventCtx,
event: &Event,
data: &mut LapceTabData,
env: &Env,
) {
match event {
Event::MouseMove(mouse_event) => {
self.mouse_pos = mouse_event.pos;
if self.icon_hit_test(mouse_event) {
ctx.set_cursor(&druid::Cursor::Pointer);
} else {
ctx.clear_cursor();
}
ctx.request_paint();
}
Event::MouseDown(mouse_event) => {
self.mouse_down(ctx, mouse_event);
}
Event::Command(cmd) if cmd.is(LAPCE_UI_COMMAND) => {
let command = cmd.get_unchecked(LAPCE_UI_COMMAND);
if let LapceUICommand::EnsureEditorTabActiveVisble = command {
let editor_tab =
data.main_split.editor_tabs.get(&self.widget_id).unwrap();
let active = editor_tab.active;
if active < self.content.widget().child().rects.len() {
let rect = self.content.widget().child().rects[active].rect;
if self.content.widget_mut().scroll_to_visible(rect, env) {
self.content
.widget_mut()
.scroll_component
.reset_scrollbar_fade(|d| ctx.request_timer(d), env);
}
}
}
}
_ => (),
}
self.content.event(ctx, event, data, env);
}
fn lifecycle(
&mut self,
ctx: &mut LifeCycleCtx,
event: &LifeCycle,
data: &LapceTabData,
env: &Env,
) {
if let LifeCycle::HotChanged(is_hot) = event {
self.is_hot = *is_hot;
ctx.request_layout();
}
self.content.lifecycle(ctx, event, data, env);
}
fn update(
&mut self,
ctx: &mut UpdateCtx,
_old_data: &LapceTabData,
data: &LapceTabData,
env: &Env,
) |
fn layout(
&mut self,
ctx: &mut LayoutCtx,
bc: &BoxConstraints,
data: &LapceTabData,
env: &Env,
) -> Size {
self.icons.clear();
let size = if data.config.editor.show_tab {
let height = 30.0;
let size = Size::new(bc.max().width, height);
let editor_tab =
data.main_split.editor_tabs.get(&self.widget_id).unwrap();
if self.is_hot || *editor_tab.content_is_hot.borrow() {
let icon_size = 24.0;
let gap = (height - icon_size) / 2.0;
let x =
size.width - ((self.icons.len() + 1) as f64) * (gap + icon_size);
let icon = LapceIcon {
icon: "close.svg".to_string(),
rect: Size::new(icon_size, icon_size)
.to_rect()
.with_origin(Point::new(x, gap)),
command: Command::new(
LAPCE_UI_COMMAND,
LapceUICommand::SplitClose,
Target::Widget(self.widget_id),
),
};
self.icons.push(icon);
let x =
size.width - ((self.icons.len() + 1) as f64) * (gap + icon_size);
let icon = LapceIcon {
icon: "split-horizontal.svg".to_string(),
rect: Size::new(icon_size, icon_size)
.to_rect()
.with_origin(Point::new(x, gap)),
command: Command::new(
LAPCE_NEW_COMMAND,
LapceCommandNew {
cmd: LapceCommand::SplitVertical.to_string(),
data: None,
palette_desc: None,
target: CommandTarget::Focus,
},
Target::Widget(self.widget_id),
),
};
self.icons.push(icon);
}
size
} else {
Size::new(bc.max().width, 0.0)
};
self.content.layout(
ctx,
&BoxConstraints::tight(Size::new(
size.width - self.icons.len() as f64 * size.height,
size.height,
)),
data,
env,
);
self.content.set_origin(ctx, data, env, Point::ZERO);
size
}
fn paint(&mut self, ctx: &mut PaintCtx, data: &LapceTabData, env: &Env) {
let size = ctx.size();
let rect = size.to_rect();
ctx.fill(
rect,
data.config
.get_color_unchecked(LapceTheme::PANEL_BACKGROUND),
);
ctx.stroke(
Line::new(
Point::new(0.0, size.height - 0.5),
Point::new(size.width, size.height - 0.5),
),
data.config.get_color_unchecked(LapceTheme::LAPCE_BORDER),
1.0,
);
self.content.paint(ctx, data, env);
let svg_padding = 4.0;
for icon in self.icons.iter() {
if icon.rect.contains(self.mouse_pos) {
ctx.fill(
&icon.rect,
data.config
.get_color_unchecked(LapceTheme::EDITOR_CURRENT_LINE),
);
}
if let Some(svg) = get_svg(&icon.icon) {
ctx.draw_svg(
&svg,
icon.rect.inflate(-svg_padding, -svg_padding),
Some(
data.config
.get_color_unchecked(LapceTheme::EDITOR_FOREGROUND),
),
);
}
}
if !self.icons.is_empty() {
let x = size.width - self.icons.len() as f64 * size.height - 0.5;
ctx.stroke(
Line::new(Point::new(x, 0.0), Point::new(x, size.height)),
data.config.get_color_unchecked(LapceTheme::LAPCE_BORDER),
1.0,
);
}
}
}
| {
self.content.update(ctx, data, env);
} |
category.component.ts | import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
import { CategoryService } from '../services/category.service';
import { ToastComponent } from '../shared/toast/toast.component';
@Component({
selector: 'app-category',
templateUrl: './category.component.html',
styleUrls: ['./category.component.scss']
})
export class CategoryComponent implements OnInit {
category = {};
categories = [];
isLoading = true;
isEditing = false;
addCategoryForm: FormGroup;
name = new FormControl('', Validators.required);
constructor(private categoryService: CategoryService,
private formBuilder: FormBuilder,
public toast: ToastComponent) { }
ngOnInit() {
this.getCategoryList();
this.addCategoryForm = this.formBuilder.group({
name: this.name
});
}
getCategoryList() {
this.categoryService.getCategoryList().subscribe(
res => {
this.categories = res.data.categories;
},
error => console.log(error),
() => this.isLoading = false
);
} |
addCategory() {
this.categoryService.addCategory(this.addCategoryForm.value).subscribe(
res => {
const newCategory = res.data.category;
this.categories.push(newCategory);
this.addCategoryForm.reset();
this.toast.setMessage('Thêm danh mục mới thành công', 'success');
},
error => console.log(error)
);
}
enableEditing(category) {
this.isEditing = true;
this.category = category;
}
cancelEditing() {
this.isEditing = false;
this.category = {};
this.toast.setMessage('Hủy chỉnh sửa thông tin danh mục', 'warning');
// reload the cats to reset the editing
this.getCategoryList();
}
updateCategory(category) {
this.categoryService.updateCategory(category).subscribe(
res => {
this.isEditing = false;
this.category = category;
this.toast.setMessage('Chỉnh sửa thông tin danh mục thành công', 'success');
},
error => console.log(error)
);
}
deactiveCategory(category) {
this.categoryService.setActive(category, false).subscribe(
res => {
this.category = category;
category.active = false;
this.toast.setMessage('Danh mục đã được deactive', 'success');
},
error => console.log(error)
);
}
activeCategory(category) {
this.categoryService.setActive(category, true).subscribe(
res => {
this.category = category;
category.active = true;
this.toast.setMessage('Danh mục đã được active', 'success');
},
error => console.log(error)
);
}
} | |
rbflayer.py | import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow.keras.layers import Layer
from tensorflow.keras.initializers import RandomUniform, Initializer, Constant
import numpy as np
class InitCentersRandom(Initializer):
""" Initializer for initialization of centers of RBF network
as random samples from the given data set.
# Arguments
X: matrix, dataset to choose the centers from (random rows
are taken as centers)
"""
def __init__(self, X):
self.X = X
def __call__(self, shape, dtype=None):
assert shape[1] == self.X.shape[1]
idx = tf.constant( np.random.randint(self.X.shape[0], size=shape[0]) )
return self.X[idx, :]
class | (Layer):
""" Layer of Gaussian RBF units.
# Example
```python
model = Sequential()
model.add(RBFLayer(10,
initializer=InitCentersRandom(X),
betas=1.0,
input_shape=(1,)))
model.add(Dense(1))
```
# Arguments
output_dim: number of hidden units (i.e. number of outputs of the
layer)
initializer: instance of initiliazer to initialize centers
betas: float, initial value for betas
"""
def __init__(self, output_dim, initializer=None, betas=1.0, **kwargs):
self.output_dim = output_dim
self.init_betas = betas
if not initializer:
self.initializer = RandomUniform(0.0, 1.0)
else:
self.initializer = initializer
super(RBFLayer, self).__init__(**kwargs)
def build(self, input_shape):
self.centers = self.add_weight(name='centers',
shape=(self.output_dim, input_shape[1]),
initializer=self.initializer,
trainable=True)
self.betas = self.add_weight(name='betas',
shape=(self.output_dim,),
initializer=Constant(
value=self.init_betas),
# initializer='ones',
trainable=True)
super(RBFLayer, self).build(input_shape)
def call(self, x):
C = K.expand_dims(self.centers)
H = K.transpose(C-K.transpose(x))
return K.exp(-self.betas * K.sum(H**2, axis=1))
# C = self.centers[np.newaxis, :, :]
# X = x[:, np.newaxis, :]
# diffnorm = K.sum((C-X)**2, axis=-1)
# ret = K.exp( - self.betas * diffnorm)
# return ret
def compute_output_shape(self, input_shape):
return (input_shape[0], self.output_dim)
def get_config(self):
# have to define get_config to be able to use model_from_json
config = {
'output_dim': self.output_dim
}
base_config = super(RBFLayer, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
| RBFLayer |
resource_type.go | /*
Copyright (c) 2020 Red Hat, 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.
*/
// IMPORTANT: This file has been generated automatically, refrain from modifying it manually as all
// your changes will be lost when the file is generated again.
package v1 // github.com/openshift-online/ocm-sdk-go/accountsmgmt/v1
// ResourceKind is the name of the type used to represent objects
// of type 'resource'.
const ResourceKind = "Resource"
// ResourceLinkKind is the name of the type used to represent links
// to objects of type 'resource'.
const ResourceLinkKind = "ResourceLink"
// ResourceNilKind is the name of the type used to nil references
// to objects of type 'resource'.
const ResourceNilKind = "ResourceNil"
// Resource represents the values of the 'resource' type.
//
// Identifies computing resources
type Resource struct {
id *string
href *string
link bool
byoc *bool
sku *string
allowed *int
availabilityZoneType *string
resourceName *string
resourceType *string
}
// Kind returns the name of the type of the object.
func (o *Resource) Kind() string {
if o == nil {
return ResourceNilKind
}
if o.link {
return ResourceLinkKind
}
return ResourceKind
}
// ID returns the identifier of the object.
func (o *Resource) ID() string {
if o != nil && o.id != nil {
return *o.id
}
return ""
}
// GetID returns the identifier of the object and a flag indicating if the
// identifier has a value.
func (o *Resource) GetID() (value string, ok bool) {
ok = o != nil && o.id != nil
if ok |
return
}
// Link returns true iif this is a link.
func (o *Resource) Link() bool {
return o != nil && o.link
}
// HREF returns the link to the object.
func (o *Resource) HREF() string {
if o != nil && o.href != nil {
return *o.href
}
return ""
}
// GetHREF returns the link of the object and a flag indicating if the
// link has a value.
func (o *Resource) GetHREF() (value string, ok bool) {
ok = o != nil && o.href != nil
if ok {
value = *o.href
}
return
}
// Empty returns true if the object is empty, i.e. no attribute has a value.
func (o *Resource) Empty() bool {
return o == nil || (o.id == nil &&
o.byoc == nil &&
o.sku == nil &&
o.allowed == nil &&
o.availabilityZoneType == nil &&
o.resourceName == nil &&
o.resourceType == nil &&
true)
}
// BYOC returns the value of the 'BYOC' attribute, or
// the zero value of the type if the attribute doesn't have a value.
//
//
func (o *Resource) BYOC() bool {
if o != nil && o.byoc != nil {
return *o.byoc
}
return false
}
// GetBYOC returns the value of the 'BYOC' attribute and
// a flag indicating if the attribute has a value.
//
//
func (o *Resource) GetBYOC() (value bool, ok bool) {
ok = o != nil && o.byoc != nil
if ok {
value = *o.byoc
}
return
}
// SKU returns the value of the 'SKU' attribute, or
// the zero value of the type if the attribute doesn't have a value.
//
//
func (o *Resource) SKU() string {
if o != nil && o.sku != nil {
return *o.sku
}
return ""
}
// GetSKU returns the value of the 'SKU' attribute and
// a flag indicating if the attribute has a value.
//
//
func (o *Resource) GetSKU() (value string, ok bool) {
ok = o != nil && o.sku != nil
if ok {
value = *o.sku
}
return
}
// Allowed returns the value of the 'allowed' attribute, or
// the zero value of the type if the attribute doesn't have a value.
//
// Number of allowed nodes
func (o *Resource) Allowed() int {
if o != nil && o.allowed != nil {
return *o.allowed
}
return 0
}
// GetAllowed returns the value of the 'allowed' attribute and
// a flag indicating if the attribute has a value.
//
// Number of allowed nodes
func (o *Resource) GetAllowed() (value int, ok bool) {
ok = o != nil && o.allowed != nil
if ok {
value = *o.allowed
}
return
}
// AvailabilityZoneType returns the value of the 'availability_zone_type' attribute, or
// the zero value of the type if the attribute doesn't have a value.
//
//
func (o *Resource) AvailabilityZoneType() string {
if o != nil && o.availabilityZoneType != nil {
return *o.availabilityZoneType
}
return ""
}
// GetAvailabilityZoneType returns the value of the 'availability_zone_type' attribute and
// a flag indicating if the attribute has a value.
//
//
func (o *Resource) GetAvailabilityZoneType() (value string, ok bool) {
ok = o != nil && o.availabilityZoneType != nil
if ok {
value = *o.availabilityZoneType
}
return
}
// ResourceName returns the value of the 'resource_name' attribute, or
// the zero value of the type if the attribute doesn't have a value.
//
// platform-specific name, such as "M5.2Xlarge" for a type of EC2 node
func (o *Resource) ResourceName() string {
if o != nil && o.resourceName != nil {
return *o.resourceName
}
return ""
}
// GetResourceName returns the value of the 'resource_name' attribute and
// a flag indicating if the attribute has a value.
//
// platform-specific name, such as "M5.2Xlarge" for a type of EC2 node
func (o *Resource) GetResourceName() (value string, ok bool) {
ok = o != nil && o.resourceName != nil
if ok {
value = *o.resourceName
}
return
}
// ResourceType returns the value of the 'resource_type' attribute, or
// the zero value of the type if the attribute doesn't have a value.
//
//
func (o *Resource) ResourceType() string {
if o != nil && o.resourceType != nil {
return *o.resourceType
}
return ""
}
// GetResourceType returns the value of the 'resource_type' attribute and
// a flag indicating if the attribute has a value.
//
//
func (o *Resource) GetResourceType() (value string, ok bool) {
ok = o != nil && o.resourceType != nil
if ok {
value = *o.resourceType
}
return
}
// ResourceListKind is the name of the type used to represent list of objects of
// type 'resource'.
const ResourceListKind = "ResourceList"
// ResourceListLinkKind is the name of the type used to represent links to list
// of objects of type 'resource'.
const ResourceListLinkKind = "ResourceListLink"
// ResourceNilKind is the name of the type used to nil lists of objects of
// type 'resource'.
const ResourceListNilKind = "ResourceListNil"
// ResourceList is a list of values of the 'resource' type.
type ResourceList struct {
href *string
link bool
items []*Resource
}
// Kind returns the name of the type of the object.
func (l *ResourceList) Kind() string {
if l == nil {
return ResourceListNilKind
}
if l.link {
return ResourceListLinkKind
}
return ResourceListKind
}
// Link returns true iif this is a link.
func (l *ResourceList) Link() bool {
return l != nil && l.link
}
// HREF returns the link to the list.
func (l *ResourceList) HREF() string {
if l != nil && l.href != nil {
return *l.href
}
return ""
}
// GetHREF returns the link of the list and a flag indicating if the
// link has a value.
func (l *ResourceList) GetHREF() (value string, ok bool) {
ok = l != nil && l.href != nil
if ok {
value = *l.href
}
return
}
// Len returns the length of the list.
func (l *ResourceList) Len() int {
if l == nil {
return 0
}
return len(l.items)
}
// Empty returns true if the list is empty.
func (l *ResourceList) Empty() bool {
return l == nil || len(l.items) == 0
}
// Get returns the item of the list with the given index. If there is no item with
// that index it returns nil.
func (l *ResourceList) Get(i int) *Resource {
if l == nil || i < 0 || i >= len(l.items) {
return nil
}
return l.items[i]
}
// Slice returns an slice containing the items of the list. The returned slice is a
// copy of the one used internally, so it can be modified without affecting the
// internal representation.
//
// If you don't need to modify the returned slice consider using the Each or Range
// functions, as they don't need to allocate a new slice.
func (l *ResourceList) Slice() []*Resource {
var slice []*Resource
if l == nil {
slice = make([]*Resource, 0)
} else {
slice = make([]*Resource, len(l.items))
copy(slice, l.items)
}
return slice
}
// Each runs the given function for each item of the list, in order. If the function
// returns false the iteration stops, otherwise it continues till all the elements
// of the list have been processed.
func (l *ResourceList) Each(f func(item *Resource) bool) {
if l == nil {
return
}
for _, item := range l.items {
if !f(item) {
break
}
}
}
// Range runs the given function for each index and item of the list, in order. If
// the function returns false the iteration stops, otherwise it continues till all
// the elements of the list have been processed.
func (l *ResourceList) Range(f func(index int, item *Resource) bool) {
if l == nil {
return
}
for index, item := range l.items {
if !f(index, item) {
break
}
}
}
| {
value = *o.id
} |
cabal.py | # -*- coding: utf-8 -*-
'''
Installation of Cabal Packages
==============================
.. versionadded:: 2015.8.0
These states manage the installed packages for Haskell using
cabal. Note that cabal-install must be installed for these states to
be available, so cabal states should include a requisite to a
pkg.installed state for the package which provides cabal
(``cabal-install`` in case of Debian based distributions). Example::
.. code-block:: yaml
cabal-install:
pkg.installed
ShellCheck:
cabal.installed:
- require:
- pkg: cabal-install
'''
from __future__ import absolute_import
from salt.exceptions import CommandExecutionError, CommandNotFoundError
import salt.utils
def __virtual__():
'''
Only work when cabal-install is installed.
'''
return (salt.utils.which('cabal') is not None) and \
(salt.utils.which('ghc-pkg') is not None)
def _parse_pkg_string(pkg):
'''
Parse pkg string and return a tuple of packge name, separator, and
package version.
Cabal support install package with following format:
* foo-1.0
* foo < 1.2
* foo > 1.3
For the sake of simplicity only the first form is supported,
support for other forms can be added later.
'''
pkg_name, separator, pkg_ver = pkg.partition('-')
return (pkg_name.strip(), separator, pkg_ver.strip())
def | (name,
pkgs=None,
user=None,
install_global=False,
env=None):
'''
Verify that the given package is installed and is at the correct version
(if specified).
.. code-block:: yaml
ShellCheck-0.3.5:
cabal:
- installed:
name
The package to install
user
The user to run cabal install with
install_global
Install package globally instead of locally
env
A list of environment variables to be set prior to execution. The
format is the same as the :py:func:`cmd.run <salt.states.cmd.run>`.
state function.
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
try:
call = __salt__['cabal.update']()
except (CommandNotFoundError, CommandExecutionError) as err:
ret['result'] = False
ret['comment'] = 'Could not run cabal update {0}'.format(err)
if pkgs is not None:
pkg_list = pkgs
else:
pkg_list = [name]
try:
installed_pkgs = __salt__['cabal.list'](
user=user, installed=True, env=env)
except (CommandNotFoundError, CommandExecutionError) as err:
ret['result'] = False
ret['comment'] = 'Error looking up {0!r}: {1}'.format(name, err)
pkgs_satisfied = []
pkgs_to_install = []
for pkg in pkg_list:
pkg_name, _, pkg_ver = _parse_pkg_string(pkg)
if pkg_name not in installed_pkgs:
pkgs_to_install.append(pkg)
else:
if pkg_ver: # version is specified
if installed_pkgs[pkg_name] != pkg_ver:
pkgs_to_install.append(pkg)
else:
pkgs_satisfied.append(pkg)
else:
pkgs_satisfied.append(pkg)
if __opts__['test']:
ret['result'] = None
comment_msg = []
if pkgs_to_install:
comment_msg.append(
'Packages(s) {0!r} are set to be installed'.format(
', '.join(pkgs_to_install)))
if pkgs_satisfied:
comment_msg.append(
'Packages(s) {0!r} satisfied by {1}'.format(
', '.join(pkg_list), ', '.join(pkgs_satisfied)))
ret['comment'] = '. '.join(comment_msg)
return ret
if not pkgs_to_install:
ret['result'] = True
ret['comment'] = ('Packages(s) {0!r} satisfied by {1}'.format(
', '.join(pkg_list), ', '.join(pkgs_satisfied)))
return ret
try:
call = __salt__['cabal.install'](pkgs=pkg_list,
user=user,
install_global=install_global,
env=env)
except (CommandNotFoundError, CommandExecutionError) as err:
ret['result'] = False
ret['comment'] = 'Error installing {0!r}: {1}'.format(
', '.join(pkg_list), err)
return ret
if call and isinstance(call, dict):
ret['result'] = True
ret['changes'] = {'old': [], 'new': pkgs_to_install}
ret['comment'] = 'Packages(s) {0!r} successfully installed'.format(
', '.join(pkgs_to_install))
else:
ret['result'] = False
ret['comment'] = 'Could not install packages(s) {0!r}'.format(
', '.join(pkg_list))
return ret
def removed(name,
user=None,
env=None):
'''
Verify that given package is not installed.
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
try:
installed_pkgs = __salt__['cabal.list'](
user=user, installed=True, env=env)
except (CommandNotFoundError, CommandExecutionError) as err:
ret['result'] = False
ret['comment'] = 'Error looking up {0!r}: {1}'.format(name, err)
if name not in installed_pkgs:
ret['result'] = True
ret['comment'] = 'Package {0!r} is not installed'.format(name)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Package {0!r} is set to be removed'.format(name)
return ret
if __salt__['cabal.uninstall'](pkg=name, user=user, env=env):
ret['result'] = True
ret['changes'][name] = 'Removed'
ret['comment'] = 'Package {0!r} was successfully removed'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Error removing package {0!r}'.format(name)
return ret
| installed |
e2e_test.go | /*
Copyright 2019 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT 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 e2e
import (
"testing"
_ "github.com/kubernetes-sigs/kube-storage-version-migrator/test/e2e/tests"
"github.com/onsi/ginkgo"
"k8s.io/klog"
)
func TestE2E(t *testing.T) {
RunE2ETests(t)
}
func | (t *testing.T) {
klog.InitFlags(nil)
klog.Infof("Starting e2e run")
ginkgo.RunSpecs(t, "Kubernetes Storage Version Migrator e2e suite")
}
| RunE2ETests |
ui_element.rs | use std::{
thread,
time::{Duration, Instant},
};
use accessibility_sys::{
pid_t, AXUIElementCopyActionNames, AXUIElementCopyAttributeNames,
AXUIElementCopyAttributeValue, AXUIElementCreateApplication, AXUIElementCreateSystemWide,
AXUIElementGetTypeID, AXUIElementPerformAction, AXUIElementRef, AXUIElementSetAttributeValue,
};
use cocoa::{
base::{id, nil},
foundation::{NSAutoreleasePool, NSFastEnumeration, NSString},
};
use core_foundation::{
array::CFArray,
base::{TCFType, TCFTypeRef},
declare_TCFType, impl_CFTypeDescription, impl_TCFType,
string::CFString,
};
use objc::{class, msg_send, rc::autoreleasepool, sel, sel_impl};
use crate::{
util::{ax_call, ax_call_void},
AXAttribute, Error,
};
declare_TCFType!(AXUIElement, AXUIElementRef);
impl_TCFType!(AXUIElement, AXUIElementRef, AXUIElementGetTypeID);
impl_CFTypeDescription!(AXUIElement);
impl AXUIElement {
pub fn system_wide() -> Self {
unsafe { Self::wrap_under_create_rule(AXUIElementCreateSystemWide()) }
}
pub fn application(pid: pid_t) -> Self {
unsafe { Self::wrap_under_create_rule(AXUIElementCreateApplication(pid)) }
}
pub fn application_with_bundle(bundle_id: &str) -> Result<Self, Error> |
pub fn application_with_bundle_timeout(
bundle_id: &str,
timeout: Duration,
) -> Result<Self, Error> {
let deadline = Instant::now() + timeout;
loop {
match Self::application_with_bundle(bundle_id) {
Ok(result) => return Ok(result),
Err(e) => {
let now = Instant::now();
if now >= deadline {
return Err(e);
} else {
let time_left = deadline.saturating_duration_since(now);
thread::sleep(std::cmp::min(time_left, Duration::from_millis(250)));
}
}
}
}
}
pub fn attribute_names(&self) -> Result<CFArray<CFString>, Error> {
unsafe {
Ok(CFArray::wrap_under_create_rule(
ax_call(|x| AXUIElementCopyAttributeNames(self.0, x)).map_err(Error::Ax)?,
))
}
}
pub fn attribute<T: TCFType>(&self, attribute: &AXAttribute<T>) -> Result<T, Error> {
unsafe {
Ok(T::wrap_under_create_rule(T::Ref::from_void_ptr(
ax_call(|x| {
AXUIElementCopyAttributeValue(
self.0,
attribute.as_CFString().as_concrete_TypeRef(),
x,
)
})
.map_err(Error::Ax)?,
)))
}
}
pub fn set_attribute<T: TCFType>(
&self,
attribute: &AXAttribute<T>,
value: impl Into<T>,
) -> Result<(), Error> {
let value = value.into();
unsafe {
Ok(ax_call_void(|| {
AXUIElementSetAttributeValue(
self.0,
attribute.as_CFString().as_concrete_TypeRef(),
value.as_CFTypeRef(),
)
})
.map_err(Error::Ax)?)
}
}
pub fn action_names(&self) -> Result<CFArray<CFString>, Error> {
unsafe {
Ok(CFArray::wrap_under_create_rule(
ax_call(|x| AXUIElementCopyActionNames(self.0, x)).map_err(Error::Ax)?,
))
}
}
pub fn perform_action(&self, name: &CFString) -> Result<(), Error> {
unsafe {
Ok(
ax_call_void(|| AXUIElementPerformAction(self.0, name.as_concrete_TypeRef()))
.map_err(Error::Ax)?,
)
}
}
}
| {
unsafe {
autoreleasepool(|| {
let bundle_id_str = NSString::alloc(nil).init_str(bundle_id).autorelease();
let apps: id = msg_send![
class![NSRunningApplication],
runningApplicationsWithBundleIdentifier: bundle_id_str
];
if let Some(app) = apps.iter().next() {
let pid: pid_t = msg_send![app, processIdentifier];
Ok(Self::wrap_under_create_rule(AXUIElementCreateApplication(
pid,
)))
} else {
Err(Error::NotFound)
}
})
}
} |
ScratchJr.js | import Project from './ui/Project';
import ScratchAudio from '../utils/ScratchAudio';
import Paint from '../painteditor/Paint';
import Prims from './engine/Prims';
import Undo from './ui/Undo';
import Alert from './ui/Alert';
import Palette from './ui/Palette';
import Record from './ui/Record';
import IO from '../tablet/IO';
import OS from '../tablet/OS';
import UI from './ui/UI';
import Menu from './blocks/Menu';
import Library from './ui/Library';
import Grid from './ui/Grid';
import ScriptsPane from './ui/ScriptsPane';
import Events from '../utils/Events';
import BlockSpecs from './blocks/BlockSpecs';
import Runtime from './engine/Runtime';
import Localization from '../utils/Localization';
import {libInit, gn, scaleMultiplier, newHTML,
isAndroid, isTablet, getUrlVars, CSSTransition3D, frame, onTouchStartBind, onTouchEndBind} from '../utils/lib';
let workingCanvas = document.createElement('canvas');
let workingCanvas2 = document.createElement('canvas');
let activeFocus = undefined;
let changed = false;
// Our behavior for story-starters are slightly different from changed
// e.g. moving a script around doesn't "start a story" while we would want it
// to save a normal user project.
let storyStarted = false;
let runtime = undefined;
let stage = undefined;
let inFullscreen = false;
let keypad = undefined;
let textForm = undefined;
let editfirst = false;
let stagecolor;
let defaultSprite;
///////////////////////////////////////////
//Layers definitions for the whole site
///////////////////////////////////////////
//layaring variables
let layerTop = 10;
let layerAboveBottom = 4;
let dragginLayer = 7000;
let currentProject = undefined; //项目ID
let filepath = undefined;
let editmode;
let isDebugging = false;
let time;
let userStart = false;
let onHold = false;
let shaking = undefined;
let stopShaking = undefined;
let version = undefined;
let autoSaveEnabled = true;
let autoSaveSetInterval = null;
let onBackButtonCallback = [];
export default class ScratchJr {
static get workingCanvas () {
return workingCanvas;
}
static get workingCanvas2 () {
return workingCanvas2;
}
static get activeFocus () {
return activeFocus;
}
static set activeFocus (newActiveFocus) {
activeFocus = newActiveFocus;
}
static set changed (newChanged) {
changed = newChanged;
}
static set storyStarted (newStoryStarted) {
storyStarted = newStoryStarted;
}
static get runtime () {
return runtime;
}
static get stage () {
return stage;
}
static set stage (newStage) {
stage = newStage;
}
static get inFullscreen () {
return inFullscreen;
}
static get stagecolor () {
return stagecolor;
}
static get defaultSprite () {
return defaultSprite;
}
static get layerTop () {
return layerTop;
}
static get layerAboveBottom () {
return layerAboveBottom;
}
static get dragginLayer () {
return dragginLayer;
}
static get currentProject () {
return currentProject;
}
static set currentProject(v){
currentProject = v;
}
static get filepath(){
return filepath;
}
static get editmode () {
return editmode;
}
static set editmode (newEditmode) {
editmode = newEditmode;
}
static set time (newTime) {
time = newTime;
}
static set userStart (newUserStart) {
userStart = newUserStart;
}
static get onHold () {
return onHold;
}
static set onHold (newOnHold) {
onHold = newOnHold;
}
static get shaking () {
return shaking;
}
static set shaking (newShaking) {
shaking = newShaking;
}
static get stopShaking () {
return stopShaking;
}
static set stopShaking (newStopShaking) {
stopShaking = newStopShaking;
}
static get version () {
return version;
}
static get onBackButtonCallback () {
return onBackButtonCallback;
}
static appinit (v) {
stagecolor = window.Settings.stageColor;
defaultSprite = window.Settings.defaultSprite;
version = v;
document.body.scrollTop = 0;
time = (new Date()) - 0;
var urlvars = getUrlVars();
OS.hascamera();
ScratchJr.log('starting the app');
BlockSpecs.initBlocks();
Project.loadIcon = document.createElement('img');
Project.loadIcon.src = 'assets/loading.png';
ScratchJr.log('blocks init', ScratchJr.getTime(), 'sec', BlockSpecs.loadCount);
currentProject = urlvars.pmd5;
if("filepath" in urlvars){
filepath = urlvars.filepath
}
editmode = urlvars.mode;
libInit();
Project.init();
ScratchJr.log('Start ui init', ScratchJr.getTime(), 'sec');
Project.setProgress(10);
ScratchAudio.init();
Library.init();
Paint.init();
Record.init();
Prims.init();
runtime = new Runtime();
Undo.init();
ScratchJr.editorEvents();
Project.load();
Events.init();
if (window.Settings.autoSaveInterval > 0) {
autoSaveSetInterval = window.setInterval(function () {
if (autoSaveEnabled && !onHold && !Project.saving && !UI.infoBoxOpen) {
ScratchJr.saveProject(null, function () {
Alert.close();
});
}
}, window.Settings.autoSaveInterval);
}
}
//获取Sjr项目文件
static getProjectSjr(cb){
let md5 = ScratchJr.currentProject + ""
Project.prepareToSave(md5, function () {
IO.zipProject(md5, function (contents) {
ScratchJr.onHold = false;
cb(contents, IO.zipFileName)
});
});
}
//加载网络Sjr文件
static loadProjectSjr(url){
Project.downloadProject(url, (md5)=>{
// window.location.href = 'editor.html?pmd5=' + md5 + '&mode=edit';
ScratchJr.currentProject = md5
IO.getObject(md5+"", Project.dataRecieved);
});
}
//获取项目截图base64
static getProjectCover(cb){
Project.getThumbnailPNG(ScratchJr.stage.pages[0], 192, 144, cb)
}
// Event handler for when a story is started
// When called and enabled, this will trigger sample projects to save copies
// Here for debugging, run-time filtering, etc.
static storyStart (/*eventName*/) {
// console.log("Story started: " + eventName);
storyStarted = true;
}
static editorEvents () {
document.ongesturestart = undefined;
onTouchStartBind(window, ScratchJr.unfocus);
if (isTablet) {
window.ontouchend = undefined;
} else {
window.onmouseup = undefined;
}
}
static unfocus (evt) {
if (Palette.helpballoon) {
Palette.helpballoon.parentNode.removeChild(Palette.helpballoon);
Palette.helpballoon = undefined;
}
if (document.forms.editable) {
if (evt && (evt.target == document.forms.editable.field)) {
return;
} // block is being edit
}
if (document.forms.activetextbox) {
if (evt && (evt.target == document.forms.activetextbox.typing)) {
return;
} // stage text box
}
if (document.forms.projectname) {
if (evt && (evt.target == document.forms.projectname.myproject)) {
return;
} // infobox text box
}
if (document.activeElement.tagName.toLowerCase() == 'input') {
document.activeElement.blur();
}
ScratchJr.clearSelection();
ScratchJr.blur();
}
static clearSelection () {
if (shaking) {
stopShaking(shaking);
}
}
static blur () {
if (ScratchAudio.firstTime) {
ScratchAudio.firstClick();
}
ScratchJr.editDone();
Menu.closeMyOpenMenu();
}
static getSprite () {
if (!stage.currentPage.currentSpriteName) {
return undefined;
}
if (!gn(stage.currentPage.currentSpriteName)) {
return undefined;
}
return gn(stage.currentPage.currentSpriteName).owner;
}
static gestureStart (e) {
e.preventDefault();
if (ScratchAudio.firstTime) {
ScratchAudio.firstClick();
}
}
static log () {
if (!isDebugging) {
return;
}
var len = arguments.length;
var res = '';
for (var i = 0; i < len - 1; i++) {
res = res + arguments[i] + ' ';
}
res += arguments[len - 1];
console.log(res); //eslint-disable-line no-console
}
static getTime () {
return ((new Date()) - time) / 1000;
}
static isSampleOrStarter () {
return editmode == 'look' || editmode == 'storyStarter';
}
static isEditable () {
return editmode != 'look';
}
// Called when ScratchJr is brought back to focus
// Here, we fix up some UI elements that may not have been properly shut down when the app was paused.
// Note that on Android Lollipop and up we have much more limited
// opportunity to save progress, etc. before the app is
// paused, and so we just suspend the whole webview and then restore it here.
static onResume () {
// no nothing special, for now.
if (Record.dialogOpen) {
Record.recordError();
}
// Re-enable autosaves
autoSaveEnabled = true;
autoSaveSetInterval = window.setInterval(function () {
if (autoSaveEnabled && !onHold && !Project.saving && !UI.infoBoxOpen) {
ScratchJr.saveProject(null, function () {
Alert.close();
});
}
}, window.Settings.autoSaveInterval);
}
static onPause () {
autoSaveEnabled = false;
window.clearInterval(autoSaveSetInterval);
}
static saveProject (e, onDone) {
if (ScratchJr.isEditable() && editmode == 'storyStarter' && storyStarted && !Project.error) {
OS.analyticsEvent('samples', 'story_starter_edited', Project.metadata.name);
// Localize sample project names
var sampleName = Localization.localize('SAMPLE_' + Project.metadata.name);
// Get the new project name
IO.uniqueProjectName({
name: sampleName
}, function (jsonData) {
var newName = jsonData.name;
Project.metadata.name = newName;
// Create the new project
IO.createProject({
name: newName,
version: version,
mtime: (new Date()).getTime().toString()
}, function (md5) {
// Save project data
currentProject = md5;
// Switch out of story-starter mode to avoid creating new projects
editmode = 'edit';
Project.prepareToSave(currentProject, onDone);
});
}, true);
} else if (ScratchJr.isEditable() && currentProject && !Project.error && changed) {
Project.prepareToSave(currentProject, onDone);
} else {
if (onDone) {
onDone();
}
}
}
//保存并返回菜单
static saveAndFlip (e) {
onHold = true;
ScratchJr.stopStripsFromTop(e);
ScratchJr.unfocus(e);
ScratchJr.saveProject(e, ScratchJr.flippage);
OS.analyticsEvent('editor', 'project_editor_close');
}
static flippage () {
Alert.close();
OS.cleanassets('wav', doNext);
function doNext () {
OS.cleanassets('svg', ScratchJr.switchPage);
}
}
static switchPage () {
window.location.href = ScratchJr.getGotoLink();
}
static getGotoLink () {
if (editmode == 'storyStarter') {
if (!storyStarted) {
return 'home.html?place=help';
} else {
return 'home.html?place=home';
}
}
if (!currentProject && !filepath) {
return 'home.html?place=home';
}
if (Project.metadata.gallery == 'samples') {
return 'home.html?place=help';
} else {
return 'home.html?place=home×tamp=' + new Date().getTime();
}
}
static updateRunStopButtons () {
var isOff = runtime.inactive();
if (inFullscreen) {
gn('go').className = isOff ? 'go on presentationmode' : 'go off presentationmode';
UI.updatePageControls();
} else {
gn('go').className = isOff ? 'go on' : 'go off';
Grid.updateCursor();
}
if (ScratchJr.getSprite()) {
if (isOff && !inFullscreen) {
ScratchJr.getSprite().select();
} else {
ScratchJr.getSprite().unselect();
}
}
if (isOff && userStart) {
stage.currentPage.updateThumb();
// ScratchJr.log ('total time', ScratchJr.getTime(), 'sec');
userStart = false;
}
}
static runStrips (e) {
ScratchJr.stopStripsFromTop(e);
ScratchJr.unfocus(e);
ScratchJr.startGreenFlagThreads();
userStart = true;
// time = (new Date()) - 0;
}
static startGreenFlagThreads () {
ScratchJr.resetSprites();
ScratchJr.startCurrentPageStrips(['onflag', 'ontouch']);
}
static startCurrentPageStrips (list) {
var page = stage.currentPage.div;
for (var i = 0; i < page.childElementCount; i++) {
var spr = page.childNodes[i].owner;
if (!spr) {
continue;
}
if (!gn(spr.id + '_scripts')) {
continue;
} // text case
ScratchJr.startScriptsFor(spr, list);
}
}
static startScriptsFor (spr, list) {
var sc = gn(spr.id + '_scripts');
var topblocks = sc.owner.getBlocksType(list);
for (var j = 0; j < topblocks.length; j++) {
var b = topblocks[j];
runtime.addRunScript(spr, b);
}
}
static stopStripsFromTop (e) {
e.preventDefault();
e.stopPropagation();
ScratchJr.unfocus(e);
ScratchJr.stopStrips();
userStart = false;
}
static stopStrips () {
runtime.stopThreads();
stage.currentPage.updateThumb();
}
static resetSprites () {
stage.resetPage(stage.currentPage);
}
static fullScreen (e) {
if (gn('full').className == 'fullscreen') {
onBackButtonCallback.push(function () {
var fakeEvent = document.createEvent('TouchEvent');
fakeEvent.initTouchEvent();
ScratchJr.quitFullScreen(fakeEvent);
});
ScratchJr.enterFullScreen(e);
} else {
ScratchJr.quitFullScreen(e);
}
}
static displayStatus (type) {
var ids = ['topsection', 'blockspalette', 'scripts', 'flip', 'projectinfo'];
for (var i = 0; i < ids.length; i++) {
if (gn(ids[i])) {
gn(ids[i]).style.display = type;
}
}
}
static enterFullScreen (e) {
if (onHold) {
return;
}
e.preventDefault();
e.stopPropagation();
ScratchJr.unfocus(e);
ScratchJr.displayStatus('none');
inFullscreen = true;
UI.enterFullScreen();
OS.analyticsEvent('editor', 'full_screen_entered');
document.body.style.background = 'black';
}
static quitFullScreen (e) {
// time = (new Date()) - 0;
e.preventDefault();
e.stopPropagation();
ScratchJr.displayStatus('block');
inFullscreen = false;
UI.quitFullScreen();
onBackButtonCallback.pop();
OS.analyticsEvent('editor', 'full_screen_exited');
document.body.style.background = 'white';
}
/////////////////////////////////////////
//UI calls
/////////////////////////////////////////
static getActiveScript () {
var str = stage.currentPage.currentSpriteName + '_scripts';
return gn(str);
}
static getBlocks () {
return ScratchJr.getActiveScript().owner.getBlocks();
}
/////////////////////////////////////////////////
//Setup editable field
static setupEditableField () {
textForm = newHTML('form', 'textform', frame);
textForm.name = 'editable';
var ti = newHTML('input', 'textinput', textForm);
ti.name = 'field';
ti.onkeypress = function (evt) {
handleKeyPress(evt);
};
textForm.onsubmit = function (evt) {
submitOverride(evt);
};
function handleKeyPress (e) {
var key = e.keyCode || e.which;
if (key == 13) {
submitOverride(e);
}
}
function submitOverride (e) {
e.preventDefault();
e.stopPropagation();
var input = e.target;
input.blur();
// Hitting enter does not trigger editDone()
// so you need to pop the queue here.
onBackButtonCallback.pop();
}
ti.maxLength = 50;
ti.onfocus = ScratchJr.handleTextFieldFocus;
ti.onblur = ScratchJr.handleTextFieldBlur;
}
/////////////////////////////////////////////////
//Argument Clicked
static editArg (e, ti) {
e.preventDefault();
e.stopPropagation();
if (ti && ti.owner.isText()) {
ScratchJr.textClicked(e, ti);
} else {
ScratchJr.numberClicked(e, ti);
}
onBackButtonCallback.push(function () {
ScratchJr.editDone();
});
}
static textClicked (e, div) {
var b = div.owner; // b is a BlockArg
activeFocus = b;
var pt = b.getScreenPt();
var sc = ScratchJr.getActiveScript();
div = sc.parentNode;
var w = div.offsetWidth;
var h = div.offsetHeight;
var dx = ((pt.x + 480 * scaleMultiplier) > w) ? (w - 486 * scaleMultiplier) : pt.x - 6 * scaleMultiplier;
var ti = document.forms.editable.field;
ti.style.textAlign = 'center';
document.forms.editable.style.left = dx + 'px';
var top = pt.y + 55 * scaleMultiplier;
document.forms.editable.style.top = top + 'px';
if (isAndroid) {
AndroidInterface.scratchjr_setsoftkeyboardscrolllocation(
top * window.devicePixelRatio, (top + h) * window.devicePixelRatio
);
}
document.forms.editable.className = 'textform on';
ti.value = b.argValue;
if (isAndroid) {
AndroidInterface.scratchjr_forceShowKeyboard();
}
ti.focus();
}
static handleTextFieldFocus (e) {
e.preventDefault();
e.stopPropagation();
activeFocus.oldvalue = activeFocus.input.textContent;
}
static handleTextFieldBlur (e) {
onBackButtonCallback.pop();
e.preventDefault();
e.stopPropagation();
var ti = document.forms.editable.field;
var str = ti.value.substring(0, ti.maxLength);
activeFocus.argValue = str;
activeFocus.setValue(str);
document.forms.editable.className = 'textform off';
if (activeFocus.daddy.div.parentNode) {
var spr = activeFocus.daddy.div.parentNode.owner.spr;
var action = {
action: 'scripts',
where: spr.div.parentNode.owner.id,
who: spr.id
};
if (activeFocus.input.textContent != activeFocus.oldvalue) {
Undo.record(action);
ScratchJr.storyStart('ScratchJr.handleTextFieldBlur');
}
}
activeFocus = undefined;
document.body.scrollTop = 0;
document.body.scrollLeft = 0;
if (isAndroid) {
AndroidInterface.scratchjr_forceHideKeyboard();
}
}
/////////////////////////////////////////
//Numeric keyboard
/////////////////////////////////////////
static setupKeypad () {
keypad = newHTML('div', 'picokeyboard', frame);
onTouchStartBind(keypad,ScratchJr.eatEvent);
var pad = newHTML('div', 'insidekeyboard', keypad);
for (var i = 1; i < 10; i++) {
ScratchJr.keyboardAddKey(pad, i, 'onekey');
}
ScratchJr.keyboardAddKey(pad, '-', 'onekey minus');
// ScratchJr.keyboardAddKey (pad, undefined, 'onekey space');
ScratchJr.keyboardAddKey(pad, '0', 'onekey');
ScratchJr.keyboardAddKey(pad, undefined, 'onekey delete');
// var keym = newHTML("div", 'onkey' ,pad);
}
static eatEvent (e) {
e.preventDefault();
e.stopPropagation();
}
static keyboardAddKey (p, str, c) {
var keym = newHTML('div', c, p);
var mk = newHTML('span', undefined, keym);
mk.textContent = str ? str : '';
onTouchStartBind(keym,ScratchJr.numEditKey);
}
/////////////////////////////////////////////////
//Number Clicked
static numberClicked (e, ti) {
var delta = (activeFocus) ? activeFocus.delta : 0;
if (activeFocus && (activeFocus.type == 'blockarg')) {
activeFocus.div.className = 'numfield off';
ScratchJr.numEditDone();
}
var b = ti.owner; // b is a BlockArg
activeFocus = b;
activeFocus.delta = delta;
b.oldvalue = ti.textContent;
activeFocus.div.className = 'numfield on';
keypad.className = 'picokeyboard on';
editfirst = true;
var p = ti.parentNode.parentNode.owner;
if (Number(p.min) < 0) {
ScratchJr.setMinusKey();
} else {
ScratchJr.setSpaceKey();
}
if (delta == 0) {
ScratchJr.needsToScroll(b);
}
}
static needsToScroll (b) {
// needs scroll
var look = ScratchJr.getActiveScript(); // look canvas
var dx = b.daddy.div.left + b.daddy.div.offsetWidth + look.left;
var w = window.innerWidth - keypad.offsetWidth - 10;
var delta = (dx > w) ? (w - dx) : 0;
if (delta < 0) {
var transition = {
duration: 0.5,
transition: 'ease-out',
style: {
left: (look.left + delta) + 'px'
},
onComplete: function () {
ScriptsPane.scroll.refresh();
}
};
CSSTransition3D(look, transition);
}
activeFocus.delta = delta;
}
static numEditKey (e) {
e.preventDefault();
e.stopPropagation();
var t = e.target;
if (!t) {
return;
}
if (t.className == '') {
t = t.parentNode;
}
if (t.className != 'onekey space') {
ScratchAudio.sndFX('keydown.wav');
}
var c = t.textContent;
var input = activeFocus.input;
if (!c) {
if ((t.parentNode.className == 'onekey delete') || (t.className == 'onekey delete')) {
ScratchJr.numEditDelete();
}
return;
}
var val = input.textContent;
if (editfirst) {
editfirst = false;
val = '0';
}
if ((c == '-') && (val != '0')) {
ScratchAudio.sndFX('boing.wav');
return;
}
if (val == '0') {
val = c;
} else {
val += c;
}
if ((Number(val).toString() != 'NaN') && ((Number(val) > 99) || (Number(val) < -99))) {
ScratchAudio.sndFX('boing.wav');
} else {
activeFocus.setValue(val);
}
}
static setSpaceKey () {
keypad.childNodes[0].childNodes[9].className = 'onekey space';
keypad.childNodes[0].childNodes[9].childNodes[0].textContent = '';
}
static setMinusKey () {
keypad.childNodes[0].childNodes[9].className = 'onekey minus';
keypad.childNodes[0].childNodes[9].childNodes[0].textContent = '-';
}
static validateNumber (val) {
return Number(val);
}
static revokeInput (val) {
return val;
}
static numEditDelete () {
var val = activeFocus.input.textContent;
if (val.length != 0) {
val = val.substring(0, val.length - 1);
}
if (val.length == 0) {
val = '0';
}
activeFocus.setValue(val);
}
static editDone () {
if (document.activeElement.tagName === 'INPUT') {
document.activeElement.blur();
}
if (activeFocus == undefined) {
return;
}
if (activeFocus.type != 'blockarg') {
return;
}
if (activeFocus.isText()) {
document.forms.editable.field.blur();
} else {
ScratchJr.closeNumberEdit();
onBackButtonCallback.pop();
}
}
static closeNumberEdit () {
ScratchJr.numEditDone();
ScratchJr.resetScroll();
keypad.className = 'picokeyboard off';
activeFocus.div.className = 'numfield off';
activeFocus = undefined;
}
static numEditDone () {
var val = activeFocus.input.textContent;
if (val == '-') {
val = 0;
}
if (val == '-0') {
val = 0;
}
val = ScratchJr.validateNumber(val);
var ba = activeFocus;
activeFocus.setValue(parseFloat(val));
ba.argValue = val;
if (ba.daddy && ba.daddy.div.parentNode.owner) {
var spr = ba.daddy.div.parentNode.owner.spr;
if (spr && spr.div.parentNode) {
var action = {
action: 'scripts',
where: spr.div.parentNode.owner.id,
who: spr.id
};
if (ba.argValue != ba.oldvalue) {
ScratchJr.storyStart('ScratchJr.numEditDone');
Undo.record(action);
}
}
}
}
static resetScroll () {
var delta = activeFocus.delta;
if (delta < 0) {
var look = ScratchJr.getActiveScript(); // look canvas
var transition = {
duration: 0.5,
transition: 'ease-out',
style: {
left: (look.left - delta) + 'px'
},
onComplete: function () {
ScriptsPane.scroll.refresh();
}
};
CSSTransition3D(look, transition);
}
}
static validate (str, name) {
var str2 = str.replace(/\s*/g, '');
if (str2.length == 0) {
return name;
}
return str;
}
/////////////////
//Application on the background
/**
* The functions that are invokved when the Android back button is clicked.
* Methods are called from the rear and popped off after each invocation.
*/
/**
* Handles updating the UI when the Android back button is clicked. This
* method invokes the methods defined at {@link onBackButtonCallback}
* if not empty, otherwise it invokes {@link ScratchJr.saveAndFlip}. The
* back button callback is set by UI components when they initialize a modal
* or popup, so it is the responsibility of popup components to correctly cleanup
* the onBackButtonCallback.
*/
static goBack () {
if (onBackButtonCallback.length === 0) {
var e = document.createEvent('TouchEvent'); | e.stopPropagation();
ScratchJr.saveAndFlip(e);
} else {
var callbackReference = onBackButtonCallback[onBackButtonCallback.length - 1];
callbackReference();
}
}
}
// Expose ScratchJr to global
window.ScratchJr = ScratchJr; | e.initTouchEvent();
e.preventDefault(); |
index.d.ts | // Type definitions for Apple Pay JS 1.0
// Project: https://developer.apple.com/reference/applepayjs
// Definitions by: Martin Costello <https://martincostello.com/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/**
* A session object for managing the payment process on the web.
*/
declare class | extends EventTarget {
/**
* Creates a new instance of the ApplePaySession class.
* @param version - The version of the ApplePay JS API you are using.
* @param paymentRequest - An ApplePayPaymentRequest object that contains the information that is displayed on the Apple Pay payment sheet.
*/
constructor(version: number, paymentRequest: ApplePayJS.ApplePayPaymentRequest);
/**
* A callback function that is automatically called when the payment UI is dismissed with an error.
*/
oncancel: (event: ApplePayJS.Event) => void;
/**
* A callback function that is automatically called when the user has authorized the Apple Pay payment, typically via TouchID.
*/
onpaymentauthorized: (event: ApplePayJS.ApplePayPaymentAuthorizedEvent) => void;
/**
* A callback function that is automatically called when a new payment method is selected.
*/
onpaymentmethodselected: (event: ApplePayJS.ApplePayPaymentMethodSelectedEvent) => void;
/**
* A callback function that is called when a shipping contact is selected in the payment sheet.
*/
onshippingcontactselected: (event: ApplePayJS.ApplePayShippingContactSelectedEvent) => void;
/**
* A callback function that is automatically called when a shipping method is selected.
*/
onshippingmethodselected: (event: ApplePayJS.ApplePayShippingMethodSelectedEvent) => void;
/**
* A callback function that is automatically called when the payment sheet is displayed.
*/
onvalidatemerchant: (event: ApplePayJS.ApplePayValidateMerchantEvent) => void;
/**
* Indicates whether or not the device supports Apple Pay.
* @returns true if the device supports making payments with Apple Pay; otherwise, false.
*/
static canMakePayments(): boolean;
/**
* Indicates whether or not the device supports Apple Pay and if the user has an active card in Wallet.
* @param merchantIdentifier - The merchant ID received when the merchant enrolled in Apple Pay.
* @returns true if the device supports Apple Pay and there is at least one active card in Wallet; otherwise, false.
*/
static canMakePaymentsWithActiveCard(merchantIdentifier: string): Promise<boolean>;
/**
* Displays the Set up Apple Pay button.
* @param merchantIdentifier - The merchant ID received when the merchant enrolled in Apple Pay.
* @returns A boolean value indicating whether setup was successful.
*/
static openPaymentSetup(merchantIdentifier: string): Promise<boolean>;
/**
* Verifies if a web browser supports a given Apple Pay JS API version.
* @param version - A number representing the Apple Pay JS API version being checked. The initial version is 1.
* @returns A boolean value indicating whether the web browser supports the given API version. Returns false if the web browser does not support the specified version.
*/
static supportsVersion(version: number): boolean;
/**
* Aborts the current Apple Pay session.
*/
abort(): void;
/**
* Begins the merchant validation process.
*/
begin(): void;
/**
* Call after the merchant has been validated.
* @param merchantSession - An opaque message session object.
*/
completeMerchantValidation(merchantSession: any): void;
/**
* Call when a payment has been authorized.
* @param status - The status of the payment.
*/
completePayment(status: number): void;
/**
* Call after a payment method has been selected.
* @param newTotal - An ApplePayLineItem dictionary representing the total price for the purchase.
* @param newLineItems - A sequence of ApplePayLineItem dictionaries.
*/
completePaymentMethodSelection(newTotal: ApplePayJS.ApplePayLineItem, newLineItems: ApplePayJS.ApplePayLineItem[]): void;
/**
* Call after a shipping contact has been selected.
* @param status - The status of the shipping contact update.
* @param newShippingMethods - A sequence of ApplePayShippingMethod dictionaries.
* @param newTotal - An ApplePayLineItem dictionary representing the total price for the purchase.
* @param newLineItems - A sequence of ApplePayLineItem dictionaries.
*/
completeShippingContactSelection(
status: number,
newShippingMethods: ApplePayJS.ApplePayShippingMethod[],
newTotal: ApplePayJS.ApplePayLineItem,
newLineItems: ApplePayJS.ApplePayLineItem[]): void;
/**
* Call after the shipping method has been selected.
* @param status - The status of the shipping method update.
* @param newTotal - An ApplePayLineItem dictionary representing the total price for the purchase.
* @param newLineItems - A sequence of ApplePayLineItem dictionaries.
*/
completeShippingMethodSelection(status: number, newTotal: ApplePayJS.ApplePayLineItem, newLineItems: ApplePayJS.ApplePayLineItem[]): void;
/**
* The requested action succeeded.
*/
static readonly STATUS_SUCCESS: number;
/**
* The requested action failed.
*/
static readonly STATUS_FAILURE: number;
/**
* The billing address is not valid.
*/
static readonly STATUS_INVALID_BILLING_POSTAL_ADDRESS: number;
/**
* The shipping address is not valid.
*/
static readonly STATUS_INVALID_SHIPPING_POSTAL_ADDRESS: number;
/**
* The shipping contact information is not valid.
*/
static readonly STATUS_INVALID_SHIPPING_CONTACT: number;
/**
* The PIN information is not valid. Cards on the China Union Pay network may require a PIN.
*/
static readonly STATUS_PIN_INCORRECT: number;
/**
* The maximum number of tries for a PIN has been reached and the user has been locked out. Cards on the China Union Pay network may require a PIN.
*/
static readonly STATUS_PIN_LOCKOUT: number;
/**
* The required PIN information was not provided. Cards on the China Union Pay payment network may require a PIN to authenticate the transaction.
*/
static readonly STATUS_PIN_REQUIRED: number;
}
declare namespace ApplePayJS {
/**
* Defines a line item in a payment request - for example, total, tax, discount, or grand total.
*/
interface ApplePayLineItem {
/**
* A short, localized description of the line item.
*/
label: string;
/**
* The line item's amount.
*/
amount: string;
/**
* A value that indicates if the line item is final or pending.
*/
type?: string;
}
/**
* Represents the result of authorizing a payment request and contains encrypted payment information.
*/
interface ApplePayPayment {
/**
* The encrypted token for an authorized payment.
*/
token: ApplePayPaymentToken;
/**
* The billing contact selected by the user for this transaction.
*/
billingContact?: ApplePayPaymentContact;
/**
* The shipping contact selected by the user for this transaction.
*/
shippingContact?: ApplePayPaymentContact;
}
/**
* The ApplePayPaymentAuthorizedEvent class defines the attributes contained by the ApplePaySession.onpaymentauthorized callback function.
*/
abstract class ApplePayPaymentAuthorizedEvent extends Event {
/**
* The payment token used to authorize a payment.
*/
readonly payment: ApplePayPayment;
}
/**
* Encapsulates contact information needed for billing and shipping.
*/
interface ApplePayPaymentContact {
/**
* An email address for the contact.
*/
emailAddress: string;
/**
* The contact's family name.
*/
familyName: string;
/**
* The contact's given name.
*/
givenName: string;
/**
* A phone number for the contact.
*/
phoneNumber: string;
/**
* The address for the contact.
*/
addressLines: string[];
/**
* The city for the contact.
*/
locality: string;
/**
* The state for the contact.
*/
administrativeArea: string;
/**
* The zip code, where applicable, for the contact.
*/
postalCode: string;
/**
* The colloquial country name for the contact.
*/
country: string;
/**
* The contact's ISO country code.
*/
countryCode: string;
}
/**
* Contains information about an Apple Pay payment card.
*/
interface ApplePayPaymentMethod {
/**
* A string, suitable for display, that describes the card.
*/
displayName: string;
/**
* A string, suitable for display, that is the name of the payment network backing the card.
* The value is one of the supported networks specified in the supportedNetworks property of the ApplePayPaymentRequest.
*/
network: string;
/**
* A value representing the card's type of payment.
*/
type: string;
/**
* The payment pass object associated with the payment.
*/
paymentPass: ApplePayPaymentPass;
}
/**
* The ApplePayPaymentMethodSelectedEvent class defines the attributes contained by the ApplePaySession.onpaymentmethodselected callback function.
*/
abstract class ApplePayPaymentMethodSelectedEvent extends Event {
/**
* The card used to complete a payment.
*/
readonly paymentMethod: ApplePayPaymentMethod;
}
/**
* Represents a provisioned payment card for Apple Pay payments.
*/
interface ApplePayPaymentPass {
/**
* The unique identifier for the primary account number for the payment card.
*/
primaryAccountIdentifier: string;
/**
* A version of the primary account number suitable for display in your UI.
*/
primaryAccountNumberSuffix: string;
/**
* The unique identifier for the device-specific account number.
*/
deviceAccountIdentifier?: string;
/**
* A version of the device account number suitable for display in your UI.
*/
deviceAccountNumberSuffix?: string;
/**
* The activation state of the pass.
*/
activationState: string;
}
/**
* Encapsulates a request for payment, including information about payment processing capabilities, the payment amount, and shipping information.
*/
interface ApplePayPaymentRequest {
/**
* The merchant's two-letter ISO 3166 country code.
*/
countryCode: string;
/**
* The three-letter ISO 4217 currency code for the payment.
*/
currencyCode: string;
/**
* A set of line items that explain recurring payments and/or additional charges.
*/
lineItems?: ApplePayLineItem[];
/**
* The payment capabilities supported by the merchant.
* The value must at least contain ApplePayMerchantCapability.supports3DS.
*/
merchantCapabilities: string[];
/**
* The payment networks supported by the merchant.
*/
supportedNetworks: string[];
/**
* A line item representing the total for the payment.
*/
total: ApplePayLineItem;
/**
* Billing contact information for the user.
*/
billingContact?: ApplePayPaymentContact;
/**
* The billing information that you require from the user in order to process the transaction.
*/
requiredBillingContactFields?: string[];
/**
* The shipping information that you require from the user in order to fulfill the order.
*/
requiredShippingContactFields?: string[];
/**
* Shipping contact information for the user.
*/
shippingContact?: ApplePayPaymentContact;
/**
* A set of shipping method objects that describe the available shipping methods.
*/
shippingMethods?: ApplePayShippingMethod[];
/**
* How the items are to be shipped.
*/
shippingType?: string;
/**
* Optional user-defined data.
*/
applicationData?: string;
}
/**
* Contains the user's payment credentials.
*/
interface ApplePayPaymentToken {
/**
* An object containing the encrypted payment data.
*/
paymentData: any;
/**
* Information about the card used in the transaction.
*/
paymentMethod: ApplePayPaymentMethod;
/**
* A unique identifier for this payment.
*/
transactionIdentifier: string;
}
/**
* The ApplePayShippingContactSelectedEvent class defines the attributes contained by the ApplePaySession.onshippingcontactselected callback function.
*/
abstract class ApplePayShippingContactSelectedEvent extends Event {
/**
* The shipping address selected by the user.
*/
readonly shippingContact: ApplePayPaymentContact;
}
/**
* Defines a shipping method for delivering physical goods.
*/
interface ApplePayShippingMethod {
/**
* A short description of the shipping method.
*/
label: string;
/**
* A further description of the shipping method.
*/
detail?: string;
/**
* The amount associated with this shipping method.
*/
amount: string;
/**
* A client-defined identifier.
*/
identifier?: string;
}
/**
* The ApplePayShippingMethodSelectedEvent class defines the attribute contained by the ApplePaySession.onshippingmethodselected callback function.
*/
abstract class ApplePayShippingMethodSelectedEvent extends Event {
/**
* The shipping method selected by the user.
*/
readonly shippingMethod: ApplePayShippingMethod;
}
/**
* The ApplePayValidateMerchantEvent class defines the attributes contained by the ApplePaySession.onvalidatemerchant callback function.
*/
abstract class ApplePayValidateMerchantEvent extends Event {
/**
* The URL used to validate the merchant server.
*/
readonly validationURL: string;
}
abstract class Event {
readonly bubbles: boolean;
cancelBubble: boolean;
readonly cancelable: boolean;
readonly composed: boolean;
readonly currentTarget: EventTarget;
readonly defaultPrevented: boolean;
readonly eventPhase: number;
readonly isTrusted: boolean;
returnValue: boolean;
readonly srcElement: EventTarget;
readonly target: EventTarget;
readonly timeStamp: string;
readonly type: string;
composedPath(): Node[];
initEvent(type?: string, bubbles?: boolean, cancelable?: boolean): void;
preventDefault(): void;
stopImmediatePropagation(): void;
stopPropagation(): void;
static readonly AT_TARGET: number;
static readonly BLUR: number;
static readonly BUBBLING_PHASE: number;
static readonly CAPTURING_PHASE: number;
static readonly CHANGE: number;
static readonly CLICK: number;
static readonly DBLCLICK: number;
static readonly DRAGDROP: number;
static readonly FOCUS: number;
static readonly KEYDOWN: number;
static readonly KEYPRESS: number;
static readonly KEYUP: number;
static readonly MOUSEDOWN: number;
static readonly MOUSEDRAG: number;
static readonly MOUSEMOVE: number;
static readonly MOUSEOUT: number;
static readonly MOUSEOVER: number;
static readonly MOUSEUP: number;
static readonly NONE: number;
static readonly SELECT: number;
}
}
| ApplePaySession |
main.py | import argparse
import os
import requests
from git import Repo
def main():
parser = argparse.ArgumentParser(description="A tool to clone github only repositories of user or group")
parser.add_argument("--u", help="target of massive download",
dest='target', required=True)
parser.add_argument("--o", help="Directory to save repos at",
dest='out', required=False)
args = parser.parse_args()
target = args.target
if not target:
print("ERROR: You need to specify target, ex: gitdown -u dex73r")
return 1
output = args.out
if not output: | pageNumber = 1
while (pageNumber > 0):
url = ("https://api.github.com/users/%s/repos?page=%i&per_page=100" % (target, pageNumber))
j = requests.get(url).json()
pageCount = len(j)
if (pageCount < 1):
pageNumber = -1
for el in j:
print(el["git_url"])
gitlink = el["git_url"]
out_name = os.path.join(output, el["name"])
if os.path.isdir(out_name):
repo = Repo(out_name)
repo.remotes.origin.pull()
else:
Repo.clone_from(gitlink, out_name)
pageNumber = pageNumber + 1
return 1337
if __name__ == "__main__":
main() | output = target |
number-complement.py | """
First, we convert the num to its birary. | >>> bin(5)
>>> '0b101'
```
Second, we need to return the base10 of binary's the complement.
Complement is easy `'101' => '010'`.
Turn to base10:
```
'010' => 0*pow(2, 2) + 1*pow(2, 1) + 0*pow(2, 0)
'11011' => 1*pow(2, 4) + 1*pow(2, 3) + 0*pow(2, 2) + 1*pow(2, 1) + 1*pow(2, 0)
```
Basics bit manipulation.
<https://www.youtube.com/watch?v=NLKQEOgBAnw>
"""
class Solution(object):
def findComplement(self, num):
b = bin(num)[2:]
opt = 0
for i, c in enumerate(reversed(b)):
if c=='0': opt+=pow(2, i)
return opt | ``` |
store.rs | //! Storage caches and trait(s)
use std::borrow::Cow;
use std::collections::HashMap;
use borsh::{BorshDeserialize, BorshSerialize};
use exonum_crypto::Hash;
use exonum_merkledb::{BinaryValue, Fork, Snapshot};
use crate::schema;
/// Track changes in the cache. Assume payload is already encoded.
#[derive(Debug)]
pub enum ViewChange {
Add(Vec<u8>),
Remove,
}
impl ViewChange {
/// Extract the value
pub fn get(&self) -> Option<&Vec<u8>> {
match self {
ViewChange::Add(v) => Some(&v),
ViewChange::Remove => None,
}
}
}
/// Hashmap cache used by check/deliver. Note keys are hashed.
pub(crate) type Cache = HashMap<Hash, ViewChange>;
/// StoreKey used to prefix each key based on the store.name()
#[derive(Debug, Clone, PartialEq, BorshSerialize, BorshDeserialize, Default)]
pub(crate) struct StoreKey<K> {
prefix: String,
key: K,
}
impl<K> StoreKey<K>
where
K: BorshSerialize + BorshDeserialize,
{
pub fn create<P: Into<String>>(prefix: P, key: K) -> Self {
Self {
prefix: prefix.into(),
key,
}
}
pub fn hash(&self) -> Hash {
exonum_crypto::hash(&self.try_to_vec().unwrap())
}
}
/// Provides cached access to a store with a snapshot of the last committed data
#[derive(Debug)]
pub struct StoreView<'a> {
cache: Cache,
access: &'a Box<dyn Snapshot>,
}
impl<'a> StoreView<'a> {
/// Return a new view with the previous cache
pub(crate) fn wrap(db: &'a Box<dyn Snapshot>, cache: Cache) -> Self {
StoreView {
access: db,
cache: cache,
}
}
/// Return a view when we only want the latest snapshot
pub(crate) fn wrap_snapshot(db: &'a Box<dyn Snapshot>) -> Self {
StoreView {
access: db,
cache: Default::default(),
}
}
/// Consume the cache
pub(crate) fn into_cache(self) -> Cache {
self.cache
}
pub fn exists(&self, key: &Hash) -> bool {
self.cache.contains_key(&key)
}
/// Check the cache
pub fn get(&self, key: &Hash) -> Option<&Vec<u8>> {
if let Some(cv) = self.cache.get(&key) {
return cv.get();
}
None
}
/// Skip the cache and check the last committed state
pub fn get_from_store(&self, key: &Hash) -> Option<Vec<u8>> {
schema::get_store(self.access).get(&key)
}
/// Put a new view change into the cache
pub fn put(&mut self, key: Hash, value: impl BinaryValue) {
self.cache.insert(key, ViewChange::Add(value.to_bytes()));
}
/// Remove an item
pub fn remove(&mut self, key: Hash) {
self.cache.insert(key, ViewChange::Remove);
}
/// Called on abci.commit to write all changes to the merkle store.
/// Only called by the deliver_tx cache
pub(crate) fn commit(&self, fork: &Fork) {
let mut store = schema::get_store(fork);
for (k, cv) in &self.cache {
match cv {
ViewChange::Add(value) => store.put(k, value.to_owned()),
ViewChange::Remove => store.remove(k),
}
}
}
}
/// Implement this trait to create a store for your application.
/// Common operations such as put, get, etc... are provided.
/// Primarily all you need to do is set the Key,Value type and return
/// a name (via name()) that will be used as a prefix to the key.
pub trait Store: Sync + Send {
/// Specify the key used for this store.
/// A key can be any type that is supported by Borsh.
type Key: BorshSerialize + BorshDeserialize;
/// Specify what will be stored. The value must fulfill the
/// BinaryValue trait. Use the macro: `impl_store_values()` to do so.
type Value: BinaryValue;
/// Return a unique name for the store. Recommend using 'appname.name'.
/// For example, if the appname is 'example' and you define a store for 'People'
/// values, `name()` should return: 'example.people'. This value must be unique as
// it's used as a prefix to the key name in the Merkle Tree.
fn name(&self) -> String;
/// Put a value in the store
fn put(&self, key: Self::Key, v: Self::Value, view: &mut StoreView) {
let hash = StoreKey::create(self.name(), key).hash();
view.put(hash, v)
}
/// Get a value from the store
fn get(&self, key: Self::Key, view: &StoreView) -> Option<Self::Value> {
let hash = StoreKey::create(self.name(), key).hash();
// Check the cache first
if let Some(v) = view.get(&hash) {
return match Self::Value::from_bytes(Cow::Owned(v.clone())) {
Ok(r) => Some(r),
_ => None,
};
}
// Not in the cache, check the latest snapshot of committed values
if let Some(v) = view.get_from_store(&hash) {
return match Self::Value::from_bytes(Cow::Owned(v.clone())) {
Ok(r) => Some(r),
_ => None,
};
}
None
}
/// Query the latest committed data for the value
fn query(&self, key: Self::Key, view: &StoreView) -> Option<Self::Value> {
let hash = StoreKey::create(self.name(), key).hash();
if let Some(v) = view.get_from_store(&hash) {
return match Self::Value::from_bytes(Cow::Owned(v.clone())) {
Ok(r) => Some(r),
_ => None,
};
}
None
}
/// Remove a value
fn remove(&self, key: Self::Key, view: &mut StoreView) {
let hash = StoreKey::create(self.name(), key).hash();
view.remove(hash)
}
/// Does the give key exists?
fn contains_key(&self, key: Self::Key, view: &StoreView) -> bool {
let hash = StoreKey::create(self.name(), key).hash();
view.exists(&hash)
}
// TODO:
//fn get_proof(&self, key: &Vec<u8>);
}
mod tests {
use super::*;
#[derive(Debug, Clone, PartialEq, BorshSerialize, BorshDeserialize, Default)]
pub struct Person {
name: String,
age: u8,
}
impl_store_values!(Person);
// Add BinaryKey as a type also?
pub struct MyStore;
impl Store for MyStore {
type Key = String;
type Value = Person;
fn | (&self) -> String {
"mystore".into()
}
}
#[test]
fn test_store_basic() {
let db: Box<dyn exonum_merkledb::Database> = Box::new(exonum_merkledb::TemporaryDB::new());
let snap = db.snapshot();
let mut c1 = StoreView::wrap(&snap, Default::default());
let store = MyStore {};
store.put(
"bob".into(),
Person {
name: "bob".into(),
age: 1u8,
},
&mut c1,
);
store.put(
"carl".into(),
Person {
name: "carl".into(),
age: 2u8,
},
&mut c1,
);
// This passes because we haven't committed
assert!(store.get("bob".into(), &mut c1).is_some());
assert!(store.get("bad".into(), &mut c1).is_none());
let t = c1.into_cache();
println!("{:?}", t);
}
}
| name |
config.py | # -*- coding: utf-8 -*-
"""
flask.config
~~~~~~~~~~~~
Implements the configuration related objects.
:copyright: (c) 2015 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import os
import types
import errno
from werkzeug.utils import import_string
from ._compat import string_types, iteritems
from . import json
class ConfigAttribute(object):
"""Makes an attribute forward to the config"""
def __init__(self, name, get_converter=None):
self.__name__ = name
self.get_converter = get_converter
def __get__(self, obj, type=None):
if obj is None:
return self
rv = obj.config[self.__name__]
if self.get_converter is not None:
rv = self.get_converter(rv)
return rv
def __set__(self, obj, value):
obj.config[self.__name__] = value
class Config(dict):
"""Works exactly like a dict but provides ways to fill it from files
or special dictionaries. There are two common patterns to populate the
config.
Either you can fill the config from a config file::
app.config.from_pyfile('yourconfig.cfg')
Or alternatively you can define the configuration options in the
module that calls :meth:`from_object` or provide an import path to
a module that should be loaded. It is also possible to tell it to
use the same module and with that provide the configuration values
just before the call::
DEBUG = True
SECRET_KEY = 'development key'
app.config.from_object(__name__)
In both cases (loading from any Python file or loading from modules),
only uppercase keys are added to the config. This makes it possible to use
lowercase values in the config file for temporary values that are not added
to the config or to define the config keys in the same file that implements
the application.
Probably the most interesting way to load configurations is from an
environment variable pointing to a file::
app.config.from_envvar('YOURAPPLICATION_SETTINGS')
In this case before launching the application you have to set this
environment variable to the file you want to use. On Linux and OS X
use the export statement::
export YOURAPPLICATION_SETTINGS='/path/to/config/file'
On windows use `set` instead.
:param root_path: path to which files are read relative from. When the
config object is created by the application, this is
the application's :attr:`~flask.Flask.root_path`.
:param defaults: an optional dictionary of default values
"""
def __init__(self, root_path, defaults=None):
dict.__init__(self, defaults or {})
self.root_path = root_path
def from_envvar(self, variable_name, silent=False):
|
def from_pyfile(self, filename, silent=False):
"""Updates the values in the config from a Python file. This function
behaves as if the file was imported as module with the
:meth:`from_object` function.
:param filename: the filename of the config. This can either be an
absolute filename or a filename relative to the
root path.
:param silent: set to ``True`` if you want silent failure for missing
files.
.. versionadded:: 0.7
`silent` parameter.
"""
filename = os.path.join(self.root_path, filename)
d = types.ModuleType('config')
d.__file__ = filename
try:
with open(filename, mode='rb') as config_file:
exec(compile(config_file.read(), filename, 'exec'), d.__dict__)
except IOError as e:
if silent and e.errno in (
errno.ENOENT, errno.EISDIR, errno.ENOTDIR
):
return False
e.strerror = 'Unable to load configuration file (%s)' % e.strerror
raise
self.from_object(d)
return True
def from_object(self, obj):
"""Updates the values from the given object. An object can be of one
of the following two types:
- a string: in this case the object with that name will be imported
- an actual object reference: that object is used directly
Objects are usually either modules or classes. :meth:`from_object`
loads only the uppercase attributes of the module/class. A ``dict``
object will not work with :meth:`from_object` because the keys of a
``dict`` are not attributes of the ``dict`` class.
Example of module-based configuration::
app.config.from_object('yourapplication.default_config')
from yourapplication import default_config
app.config.from_object(default_config)
You should not use this function to load the actual configuration but
rather configuration defaults. The actual config should be loaded
with :meth:`from_pyfile` and ideally from a location not within the
package because the package might be installed system wide.
See :ref:`config-dev-prod` for an example of class-based configuration
using :meth:`from_object`.
:param obj: an import name or object
"""
if isinstance(obj, string_types):
obj = import_string(obj)
for key in dir(obj):
if key.isupper():
self[key] = getattr(obj, key)
def from_json(self, filename, silent=False):
"""Updates the values in the config from a JSON file. This function
behaves as if the JSON object was a dictionary and passed to the
:meth:`from_mapping` function.
:param filename: the filename of the JSON file. This can either be an
absolute filename or a filename relative to the
root path.
:param silent: set to ``True`` if you want silent failure for missing
files.
.. versionadded:: 0.11
"""
filename = os.path.join(self.root_path, filename)
try:
with open(filename) as json_file:
obj = json.loads(json_file.read())
except IOError as e:
if silent and e.errno in (errno.ENOENT, errno.EISDIR):
return False
e.strerror = 'Unable to load configuration file (%s)' % e.strerror
raise
return self.from_mapping(obj)
def from_mapping(self, *mapping, **kwargs):
"""Updates the config like :meth:`update` ignoring items with non-upper
keys.
.. versionadded:: 0.11
"""
mappings = []
if len(mapping) == 1:
if hasattr(mapping[0], 'items'):
mappings.append(mapping[0].items())
else:
mappings.append(mapping[0])
elif len(mapping) > 1:
raise TypeError(
'expected at most 1 positional argument, got %d' % len(mapping)
)
mappings.append(kwargs.items())
for mapping in mappings:
for (key, value) in mapping:
if key.isupper():
self[key] = value
return True
def get_namespace(self, namespace, lowercase=True, trim_namespace=True):
"""Returns a dictionary containing a subset of configuration options
that match the specified namespace/prefix. Example usage::
app.config['IMAGE_STORE_TYPE'] = 'fs'
app.config['IMAGE_STORE_PATH'] = '/var/app/images'
app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'
image_store_config = app.config.get_namespace('IMAGE_STORE_')
The resulting dictionary `image_store_config` would look like::
{
'type': 'fs',
'path': '/var/app/images',
'base_url': 'http://img.website.com'
}
This is often useful when configuration options map directly to
keyword arguments in functions or class constructors.
:param namespace: a configuration namespace
:param lowercase: a flag indicating if the keys of the resulting
dictionary should be lowercase
:param trim_namespace: a flag indicating if the keys of the resulting
dictionary should not include the namespace
.. versionadded:: 0.11
"""
rv = {}
for k, v in iteritems(self):
if not k.startswith(namespace):
continue
if trim_namespace:
key = k[len(namespace):]
else:
key = k
if lowercase:
key = key.lower()
rv[key] = v
return rv
def __repr__(self):
return '<%s %s>' % (self.__class__.__name__, dict.__repr__(self))
| """Loads a configuration from an environment variable pointing to
a configuration file. This is basically just a shortcut with nicer
error messages for this line of code::
app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])
:param variable_name: name of the environment variable
:param silent: set to ``True`` if you want silent failure for missing
files.
:return: bool. ``True`` if able to load config, ``False`` otherwise.
"""
rv = os.environ.get(variable_name)
if not rv:
if silent:
return False
raise RuntimeError('The environment variable %r is not set '
'and as such configuration could not be '
'loaded. Set this variable and make it '
'point to a configuration file' %
variable_name)
return self.from_pyfile(rv, silent=silent) |
useGeolocationEvents.spec.js | import React from 'react';
import { render, cleanup as cleanupReact } from '@testing-library/react';
import { renderHook, cleanup as cleanupHooks } from '@testing-library/react-hooks';
import useGeolocationEvents from '../dist/useGeolocationEvents';
import GeoLocationApiMock, { watchPositionSpy } from './mocks/GeoLocationApi.mock';
describe('useGeolocationEvents', () => {
before(() => {
window.navigator.geolocation = GeoLocationApiMock;
});
beforeEach(() => {
cleanupReact();
cleanupHooks();
sinon.reset();
});
after(() => {
delete window.navigator.geolocation;
});
it('should be a function', () => {
expect(useGeolocationEvents).to.be.a('function');
});
it('should return an object of geolocation-related callback setters', () => {
const { result } = renderHook(() => useGeolocationEvents());
expect(result.current).to.be.an('object').that.has.all.deep.keys('isSupported', 'onChange', 'onError');
expect(result.current).to.be.frozen;
});
it('should perform the onChange callback when geolocation changes', () => {
const onChangeSpy = sinon.spy();
const onErrorSpy = sinon.spy();
const TestComponent = () => {
const { onChange, onError } = useGeolocationEvents();
onChange(onChangeSpy);
onError(onErrorSpy);
return <div />;
};
render(<TestComponent />);
GeoLocationApiMock.listeners.s();
GeoLocationApiMock.listeners.e();
expect(onChangeSpy.called).to.be.true;
});
it('should accept an options object to be used as a parameter when calling watchPosition', () => {
const optionsMock = { foo: 'bar' }; | return <div>{isSupported}</div>;
};
render(<TestComponent />);
GeoLocationApiMock.listeners.s();
GeoLocationApiMock.listeners.e();
expect(watchPositionSpy.called).to.be.true;
const lastOptions = watchPositionSpy.args[watchPositionSpy.callCount - 1][0];
expect(lastOptions).to.equal(optionsMock);
});
it('if the geolocation API is not supported should return a throwing method', () => {
delete window.navigator.geolocation; // delete for test purposes
const { result } = renderHook(() => useGeolocationEvents());
window.navigator.geolocation = GeoLocationApiMock; // reset to the "original" mocks
expect(result.current.onSomething).to.throw();
expect(result.current.proprety).to.be.an('object').that.has.key('error');
});
}); |
const TestComponent = () => {
const { isSupported } = useGeolocationEvents(optionsMock);
|
index.d.ts | // Type definitions for TOAST UI Grid v4.19.2
// TypeScript Version: 3.9.5
import { CellValue, RowKey, Row, SortState, RowSpan, InvalidRow } from './store/data';
import { SummaryColumnContentMap, SummaryValueMap } from './store/summary';
import { ColumnInfo } from './store/column';
import { Range } from './store/selection';
import {
Dictionary,
GridEventName,
GridEventListener,
OptThemePresetNames,
OptPreset,
OptI18nData,
OptGrid,
OptAppendRow,
OptPrependRow,
OptRemoveRow,
OptHeader,
OptRow,
OptColumn,
ResetOptions,
OptMoveRow,
} from './options';
import {
ModifiedRowsOptions,
ModifiedRows,
Params,
RequestType,
ModificationTypeCode,
RequestOptions,
} from './dataSource';
import { FilterOptionType, Filter, FilterState } from './store/filterLayerState';
import { MenuItem } from './store/contextMenu';
import { OptExport } from './store/export';
type InternalProp =
| 'sortKey'
| 'uniqueKey'
| 'rowSpanMap'
| '_relationListItemMap'
| '_disabledPriority';
export interface Pagination {
getCurrentPage(): number;
movePageTo(targetPage: number): void;
reset(totalItems: number): void;
setItemsPerPage(itemCount: number): void;
setTotalItems(itemCount: number): void;
on(eventType: string, callback: (evt: any) => void): void;
off(eventType: string): void;
}
declare namespace tui {
export class Grid {
public static applyTheme(presetName: OptThemePresetNames, extOptions?: OptPreset): void;
public static setLanguage(localeCode: string, data?: OptI18nData): void;
constructor(optGrid: OptGrid);
public setWidth(width: number): void;
public setHeight(height: number): void;
public setBodyHeight(bodyHeight: number): void;
public setHeader({ height, complexColumns }: OptHeader): void;
public setFrozenColumnCount(count: number): void;
public hideColumn(columnName: string): void;
public showColumn(columnName: string): void;
public setSelectionRange(range: { start: Range; end: Range }): void;
public getFocusedCell(): {
rowKey: string | number | null;
columnName: string | null;
value: CellValue;
};
public blur(): void;
public focus(rowKey: RowKey, columnName: string, setScroll?: boolean): boolean;
public focusAt(rowIndex: number, columnIndex: number, setScroll?: boolean): boolean;
public activateFocus(): void;
public startEditing(rowKey: RowKey, columnName: string, setScroll?: boolean): void;
public startEditingAt(rowIndex: number, columnIndex: number, setScroll?: boolean): void;
public finishEditing(rowKey?: RowKey, columnName?: string, value?: string): void;
public setValue(rowKey: RowKey, columnName: string, value: CellValue): void;
public getValue(rowKey: RowKey, columnName: string): CellValue | null;
public setColumnValues(
columnName: string,
columnValue: CellValue,
checkCellState?: boolean |
public getElement(rowKey: RowKey, columnName: string): Element | null;
public setSummaryColumnContent(
columnName: string,
columnContent: string | SummaryColumnContentMap
): void;
public getSummaryValues(columnName: string): SummaryValueMap | null;
public getColumns(): ColumnInfo[];
public setColumns(columns: OptColumn[]): void;
public setColumnHeaders(columnsMap: Dictionary<string>): void;
public resetColumnWidths(widths: number[]): void;
public getColumnValues(columnName: string): CellValue[];
public getIndexOfColumn(columnName: string): number;
public check(rowKey: RowKey): void;
public uncheck(rowKey: RowKey): void;
public checkAll(): void;
public uncheckAll(): void;
public getCheckedRowKeys(): RowKey[];
public getCheckedRows(): Row[];
public findRows(conditions: ((row: Row) => boolean) | Dictionary<any>): Row[];
public sort(columnName: string, ascending: boolean, multiple?: boolean): void;
public unsort(columnName?: string): void;
public getSortState(): SortState;
public copyToClipboard(): void;
public validate(): InvalidRow[];
public enable(): void;
public disable(): void;
public disableRow(rowKey: RowKey, withCheckbox?: boolean): void;
public enableRow(rowKey: RowKey, withCheckbox?: boolean): void;
public disableColumn(columnName: string): void;
public enableColumn(columnName: string): void;
public disableRowCheck(rowKey: RowKey): void;
public enableRowCheck(rowKey: RowKey): void;
public appendRow(row?: OptRow, options?: OptAppendRow): void;
public prependRow(row: OptRow, options?: OptPrependRow): void;
public removeRow(rowKey: RowKey, options?: OptRemoveRow): void;
public getRow(rowKey: RowKey): Row | null;
public getRowAt(rowIdx: number): Row | null;
public getIndexOfRow(rowKey: RowKey): number;
public getData(): Omit<Row, InternalProp>[];
public getRowCount(): number;
public clear(): void;
public resetData(data: OptRow[], options?: ResetOptions): void;
public addCellClassName(rowKey: RowKey, columnName: string, className: string): void;
public addRowClassName(rowKey: RowKey, className: string): void;
public removeCellClassName(rowKey: RowKey, columnName: string, className: string): void;
public removeRowClassName(rowKey: RowKey, className: string): void;
public on(eventName: GridEventName, fn: GridEventListener): void;
public off(eventName: GridEventName, fn?: GridEventListener): void;
public getPagination(): Pagination | null;
public setPerPage(perPage: number): void;
public isModified(): boolean;
public getModifiedRows(options?: ModifiedRowsOptions): ModifiedRows;
public readData(page: number, data?: Params, resetData?: boolean): void;
public request(requestType: RequestType, options?: RequestOptions): void;
public reloadData(): void;
public restore(): void;
public expand(rowKey: RowKey, recursive?: boolean): void;
public expandAll(): void;
public collapse(rowKey: RowKey, recursive?: boolean): void;
public collapseAll(): void;
public getParentRow(rowKey: RowKey): Row | null;
public getChildRows(rowKey: RowKey): Row[];
public getAncestorRows(rowKey: RowKey): Row[];
public getDescendantRows(rowKey: RowKey): Row[];
public getDepth(rowKey: RowKey): number;
public getRowSpanData(rowKey: RowKey, columnName: string): RowSpan | null;
public resetOriginData(): void;
public removeCheckedRows(showConfirm?: boolean): boolean;
public refreshLayout(): void;
public destroy(): void;
public setFilter(
columnName: string,
filterOptionType: FilterOptionType | FilterOptionType
): void;
public getFilterState(): Filter[] | null;
public filter(columnName: string, state: FilterState[]): void;
public unfilter(columnName?: string): void;
public addColumnClassName(columnName: string, className: string): void;
public removeColumnClassName(columnName: string, className: string): void;
public setRow(rowKey: RowKey, row: OptRow): void;
public moveRow(rowKey: RowKey, targetIndex: number, options: OptMoveRow): void;
public setRequestParams(params: Dictionary<any>): void;
public clearModifiedData(type?: ModificationTypeCode): void;
public appendRows(data: OptRow[]): void;
public getFormattedValue(rowKey: RowKey, columnName: string): string | null;
public setPaginationTotalCount(totalCount: number): void;
public getPaginationTotalCount(): number;
public export(format: 'csv' | 'xlsx', options?: OptExport): void;
}
}
// typesciprt doesn't support the nested namespace
// export as namespace tui.Grid;
export {
CellValue,
RowKey,
Row,
SortState,
RowSpan,
InvalidRow,
SummaryColumnContentMap,
SummaryValueMap,
ColumnInfo,
Range,
Dictionary,
GridEventName,
GridEventListener,
OptThemePresetNames as ThemePresetNameOptions,
OptPreset as PresetOptions,
OptI18nData as I18nDataOptions,
OptGrid as GridOptions,
OptAppendRow as AppendRowOptions,
OptPrependRow as PrependRowOptions,
OptRemoveRow as RemoveRowOptions,
OptHeader as HeaderOptions,
OptRow as RowOptions,
OptColumn as ColumnOptions,
OptExport as ExportOptions,
ModifiedRowsOptions,
ModifiedRows,
Params,
RequestType,
ModificationTypeCode,
RequestOptions,
FilterOptionType,
Filter,
FilterState,
MenuItem,
};
export default tui.Grid; | ): void; |
registry_interface.rs | extern crate environment;
extern crate hyper;
extern crate rand;
extern crate reqwest;
extern crate serde_json;
#[cfg(test)]
mod common;
#[cfg(test)]
mod interface_tests {
use environment::Environment;
use crate::common;
use reqwest;
use reqwest::StatusCode;
use serde_json;
use std::fs::{self, File};
use std::io::{BufReader, Read};
use std::process::Child;
use std::process::Command;
use std::thread;
use std::time::Duration;
use trow::types::{HealthResponse, ReadinessResponse, RepoCatalog, RepoName, TagList};
use trow_server::{digest, manifest};
const TROW_ADDRESS: &str = "https://trow.test:8443";
const DIST_API_HEADER: &str = "Docker-Distribution-API-Version";
struct TrowInstance {
pid: Child,
}
/// Call out to cargo to start trow.
/// Seriously considering moving to docker run.
async fn start_trow() -> TrowInstance {
let mut child = Command::new("cargo")
.arg("run")
.env_clear()
.envs(Environment::inherit().compile())
.spawn()
.expect("failed to start");
let mut timeout = 100;
let mut buf = Vec::new();
File::open("./certs/domain.crt")
.unwrap()
.read_to_end(&mut buf)
.unwrap();
let cert = reqwest::Certificate::from_pem(&buf).unwrap();
// get a client builder
let client = reqwest::Client::builder()
.add_root_certificate(cert)
.danger_accept_invalid_certs(true)
.build()
.unwrap();
let mut response = client.get(TROW_ADDRESS).send().await;
while timeout > 0 && (response.is_err() || (response.unwrap().status() != StatusCode::OK)) {
thread::sleep(Duration::from_millis(100));
response = client.get(TROW_ADDRESS).send().await;
timeout -= 1;
}
if timeout == 0 {
child.kill().unwrap();
panic!("Failed to start Trow");
}
TrowInstance { pid: child }
}
impl Drop for TrowInstance {
fn drop(&mut self) {
common::kill_gracefully(&self.pid);
}
}
async fn get_main(cl: &reqwest::Client) {
let resp = cl.get(TROW_ADDRESS).send().await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.headers().get(DIST_API_HEADER).unwrap(), "registry/2.0");
//All v2 registries should respond with a 200 to this
let resp = cl
.get(&(TROW_ADDRESS.to_owned() + "/v2/"))
.send()
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.headers().get(DIST_API_HEADER).unwrap(), "registry/2.0");
}
async fn get_non_existent_blob(cl: &reqwest::Client) {
let resp = cl
.get(&(TROW_ADDRESS.to_owned() + "/v2/test/test/blobs/not-an-entry"))
.send()
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
async fn get_manifest(cl: &reqwest::Client, name: &str, tag: &str) {
//Might need accept headers here
let resp = cl
.get(&format!("{}/v2/{}/manifests/{}", TROW_ADDRESS, name, tag))
.send()
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let mani: manifest::ManifestV2 = resp.json().await.unwrap();
assert_eq!(mani.schema_version, 2);
}
async fn | (cl: &reqwest::Client, name: &str, tag: &str) {
//Might need accept headers here
let resp = cl
.get(&format!("{}/v2/{}/manifests/{}", TROW_ADDRESS, name, tag))
.send()
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
async fn check_repo_catalog(cl: &reqwest::Client, rc: &RepoCatalog) {
let resp = cl
.get(&format!("{}/v2/_catalog", TROW_ADDRESS))
.send()
.await
.unwrap();
let rc_resp: RepoCatalog = serde_json::from_str(&resp.text().await.unwrap()).unwrap();
assert_eq!(rc, &rc_resp);
}
async fn check_tag_list(cl: &reqwest::Client, tl: &TagList) {
let resp = cl
.get(&format!("{}/v2/{}/tags/list", TROW_ADDRESS, tl.repo_name()))
.send()
.await
.unwrap();
let tl_resp: TagList = serde_json::from_str(&resp.text().await.unwrap()).unwrap();
assert_eq!(tl, &tl_resp);
}
async fn check_tag_list_n_last(cl: &reqwest::Client, n: u32, last: &str, tl: &TagList) {
let resp = cl
.get(&format!(
"{}/v2/{}/tags/list?last={}&n={}",
TROW_ADDRESS,
tl.repo_name(),
last,
n
))
.send()
.await
.unwrap();
let tl_resp: TagList = serde_json::from_str(&resp.text().await.unwrap()).unwrap();
assert_eq!(tl, &tl_resp);
}
async fn upload_with_put(cl: &reqwest::Client, name: &str) {
let resp = cl
.post(&format!("{}/v2/{}/blobs/uploads/", TROW_ADDRESS, name))
.send()
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::ACCEPTED);
let uuid = resp
.headers()
.get(common::UPLOAD_HEADER)
.unwrap()
.to_str()
.unwrap();
//used by oci_manifest_test
let config = "{}\n".as_bytes();
let digest = digest::sha256_tag_digest(BufReader::new(config)).unwrap();
let loc = &format!(
"{}/v2/{}/blobs/uploads/{}?digest={}",
TROW_ADDRESS, name, uuid, digest
);
let resp = cl.put(loc).body(config.clone()).send().await.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
}
async fn upload_with_post(cl: &reqwest::Client, name: &str) {
let config = "{ }\n".as_bytes();
let digest = digest::sha256_tag_digest(BufReader::new(config)).unwrap();
let resp = cl
.post(&format!(
"{}/v2/{}/blobs/uploads/?digest={}",
TROW_ADDRESS, name, digest
))
.body(config.clone())
.send()
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
}
async fn push_oci_manifest(cl: &reqwest::Client, name: &str, tag: &str) -> String {
//Note config was uploaded as blob in earlier test
let config = "{}\n".as_bytes();
let config_digest = digest::sha256_tag_digest(BufReader::new(config)).unwrap();
let manifest = format!(
r#"{{ "mediaType": "application/vnd.oci.image.manifest.v1+json",
"config": {{ "digest": "{}",
"mediaType": "application/vnd.oci.image.config.v1+json",
"size": {} }},
"layers": [], "schemaVersion": 2 }}"#,
config_digest,
config.len()
);
let bytes = manifest.clone();
let resp = cl
.put(&format!("{}/v2/{}/manifests/{}", TROW_ADDRESS, name, tag))
.body(bytes)
.send()
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
// Try pulling by digest
let digest = digest::sha256_tag_digest(BufReader::new(manifest.as_bytes())).unwrap();
digest
}
async fn push_manifest_list(
cl: &reqwest::Client,
digest: &str,
name: &str,
tag: &str,
) -> String {
let manifest = format!(
r#"{{
"schemaVersion": 2,
"mediaType": "application/vnd.docker.distribution.manifest.list.v2+json",
"manifests": [
{{
"mediaType": "application/vnd.docker.distribution.manifest.v2+json",
"size": 7143,
"digest": "{}",
"platform": {{
"architecture": "ppc64le",
"os": "linux"
}}
}}
]
}}
"#,
digest
);
let bytes = manifest.clone();
let resp = cl
.put(&format!("{}/v2/{}/manifests/{}", TROW_ADDRESS, name, tag))
.body(bytes)
.send()
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
// Try pulling by digest
let digest = digest::sha256_tag_digest(BufReader::new(manifest.as_bytes())).unwrap();
digest
}
async fn push_oci_manifest_with_foreign_blob(
cl: &reqwest::Client,
name: &str,
tag: &str,
) -> String {
//Note config was uploaded as blob in earlier test
let config = "{}\n".as_bytes();
let config_digest = digest::sha256_tag_digest(BufReader::new(config)).unwrap();
let manifest = format!(
r#"{{ "mediaType": "application/vnd.oci.image.manifest.v1+json",
"config": {{ "digest": "{}",
"mediaType": "application/vnd.oci.image.config.v1+json",
"size": {} }},
"layers": [
{{
"mediaType": "application/vnd.docker.image.rootfs.foreign.diff.tar.gzip",
"size": 1612893008,
"digest": "sha256:9038b92872bc268d5c975e84dd94e69848564b222ad116ee652c62e0c2f894b2",
"urls": [
"https://mcr.microsoft.com/v2/windows/servercore/blobs/sha256:9038b92872bc268d5c975e84dd94e69848564b222ad116ee652c62e0c2f894b2"
]
}}
], "schemaVersion": 2 }}"#,
config_digest,
config.len()
);
let bytes = manifest.clone();
let resp = cl
.put(&format!("{}/v2/{}/manifests/{}", TROW_ADDRESS, name, tag))
.body(bytes)
.send()
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
// Try pulling by digest
let digest = digest::sha256_tag_digest(BufReader::new(manifest.as_bytes())).unwrap();
digest
}
async fn delete_manifest(cl: &reqwest::Client, name: &str, digest: &str) {
let resp = cl
.delete(&format!(
"{}/v2/{}/manifests/{}",
TROW_ADDRESS, name, digest
))
.send()
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::ACCEPTED);
}
async fn delete_non_existent_manifest(cl: &reqwest::Client, name: &str) {
let resp = cl
.delete(&format!(
"{}/v2/{}/manifests/{}",
TROW_ADDRESS,
name,
"sha256:9038b92872bc268d5c975e84dd94e69848564b222ad116ee652c62e0c2f894b2"
))
.send()
.await
.unwrap();
// If it doesn't exist, that's kinda the same as deleted, right?
assert_eq!(resp.status(), StatusCode::ACCEPTED);
}
async fn attempt_delete_by_tag(cl: &reqwest::Client, name: &str, tag: &str) {
let resp = cl
.delete(&format!("{}/v2/{}/manifests/{}", TROW_ADDRESS, name, tag))
.send()
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
}
async fn delete_config_blob(cl: &reqwest::Client, name: &str) {
//Deletes blob uploaded in config test
let config = "{}\n".as_bytes();
let config_digest = digest::sha256_tag_digest(BufReader::new(config)).unwrap();
let resp = cl
.delete(&format!(
"{}/v2/{}/blobs/{}",
TROW_ADDRESS, name, config_digest
))
.send()
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::ACCEPTED);
}
async fn test_5level_error(cl: &reqwest::Client) {
let name = "one/two/three/four/five";
let resp = cl
.post(&format!("{}/v2/{}/blobs/uploads/", TROW_ADDRESS, name))
.send()
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
async fn get_health(cl: &reqwest::Client) {
let resp = cl
.get(&format!("{}/healthz", TROW_ADDRESS))
.send()
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let hr: HealthResponse = resp.json().await.unwrap();
assert_eq!(hr.is_healthy, true);
}
async fn get_readiness(cl: &reqwest::Client) {
let resp = cl
.get(&format!("{}/readiness", TROW_ADDRESS))
.send()
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let rr: ReadinessResponse = resp.json().await.unwrap();
assert_eq!(rr.is_ready, true);
}
async fn get_metrics(cl: &reqwest::Client) {
let resp = cl
.get(&format!("{}/metrics", TROW_ADDRESS))
.send()
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let body = resp.text().await.unwrap();
assert!(body.contains("available_space"));
assert!(body.contains("free_space"));
assert!(body.contains("total_space"));
assert!(body.contains("total_manifest_requests{type=\"manifests\"} 6"));
assert!(body.contains("total_blob_requests{type=\"blobs\"} 8"));
get_manifest(&cl, "onename", "tag").await;
let manifest_response = cl
.get(&format!("{}/metrics", TROW_ADDRESS))
.send()
.await
.unwrap();
let manifest_body = manifest_response.text().await.unwrap();
assert!(manifest_body.contains("total_manifest_requests{type=\"manifests\"} 7"));
get_non_existent_blob(&cl).await;
let blob_response = cl
.get(&format!("{}/metrics", TROW_ADDRESS))
.send()
.await
.unwrap();
assert_eq!(blob_response.status(), StatusCode::OK);
let blob_body = blob_response.text().await.unwrap();
assert!(blob_body.contains("total_blob_requests{type=\"blobs\"} 9"));
}
#[tokio::test]
async fn test_runner() {
//Need to start with empty repo
fs::remove_dir_all("./data").unwrap_or(());
//Had issues with stopping and starting trow causing test fails.
//It might be possible to improve things with a thread_local
let _trow = start_trow().await;
let mut buf = Vec::new();
File::open("./certs/domain.crt")
.unwrap()
.read_to_end(&mut buf)
.unwrap();
let cert = reqwest::Certificate::from_pem(&buf).unwrap();
// get a client builder
let client = reqwest::Client::builder()
.add_root_certificate(cert)
.danger_accept_invalid_certs(true)
.build()
.unwrap();
println!("Running get_main()");
get_main(&client).await;
println!("Running get_blob()");
get_non_existent_blob(&client).await;
println!("Running upload_layer(fourth/repo/image/test:tag)");
common::upload_layer(&client, "fourth/repo/image/test", "tag").await;
println!("Running upload_layer(repo/image/test:tag)");
common::upload_layer(&client, "repo/image/test", "tag").await;
println!("Running upload_layer(image/test:latest)");
common::upload_layer(&client, "image/test", "latest").await;
println!("Running upload_layer(onename:tag)");
common::upload_layer(&client, "onename", "tag").await;
println!("Running upload_layer(onename:latest)");
common::upload_layer(&client, "onename", "latest").await;
println!("Running upload_with_put()");
upload_with_put(&client, "puttest").await;
println!("Running upload_with_post");
upload_with_post(&client, "posttest").await;
println!("Running test_5level_error()");
test_5level_error(&client).await;
println!("Running push_oci_manifest()");
let digest = push_oci_manifest(&client, "puttest", "puttest1").await;
println!("Running push_manifest_list()");
let digest_list = push_manifest_list(&client, &digest, "listtest", "listtest1").await;
println!("Running get_manifest(puttest:puttest1)");
get_manifest(&client, "puttest", "puttest1").await;
println!("Running delete_manifest(puttest:digest)");
delete_manifest(&client, "puttest", &digest).await;
println!("Running delete_manifest(listtest)");
delete_manifest(&client, "listtest", &digest_list).await;
println!("Running delete_non_existent_manifest(onename)");
delete_non_existent_manifest(&client, "onename").await;
println!("Running attempt_delete_by_tag(onename:tag)");
attempt_delete_by_tag(&client, "onename", "tag").await;
println!("Running get_non_existent_manifest(puttest:puttest1)");
get_non_existent_manifest(&client, "puttest", "puttest1").await;
println!("Running get_non_existent_manifest(puttest:digest)");
get_non_existent_manifest(&client, "puttest", &digest).await;
println!("Running push_oci_manifest_with_foreign_blob()");
let digest = push_oci_manifest_with_foreign_blob(&client, "foreigntest", "blobtest1").await;
delete_manifest(&client, "foreigntest", &digest).await;
println!("Running delete_config_blob");
delete_config_blob(&client, "puttest").await;
println!("Running get_manifest(onename:tag)");
get_manifest(&client, "onename", "tag").await;
println!("Running get_manifest(image/test:latest)");
get_manifest(&client, "image/test", "latest").await;
println!("Running get_manifest(repo/image/test:tag)");
get_manifest(&client, "repo/image/test", "tag").await;
let mut rc = RepoCatalog::new();
rc.insert(RepoName("fourth/repo/image/test".to_string()));
rc.insert(RepoName("repo/image/test".to_string()));
rc.insert(RepoName("image/test".to_string()));
rc.insert(RepoName("onename".to_string()));
println!("Running check_repo_catalog");
check_repo_catalog(&client, &rc).await;
let mut tl = TagList::new(RepoName("repo/image/test".to_string()));
tl.insert("tag".to_string());
println!("Running check_tag_list 1");
check_tag_list(&client, &tl).await;
common::upload_layer(&client, "onename", "three").await;
common::upload_layer(&client, "onename", "four").await;
// list, in order should be [four, latest, tag, three]
let mut tl2 = TagList::new(RepoName("onename".to_string()));
tl2.insert("four".to_string());
tl2.insert("latest".to_string());
tl2.insert("tag".to_string());
tl2.insert("three".to_string());
println!("Running check_tag_list 2");
check_tag_list(&client, &tl2).await;
let mut tl3 = TagList::new(RepoName("onename".to_string()));
tl3.insert("four".to_string());
tl3.insert("latest".to_string());
println!("Running check_tag_list_n_last 3");
check_tag_list_n_last(&client, 2, "", &tl3).await;
let mut tl4 = TagList::new(RepoName("onename".to_string()));
tl4.insert("tag".to_string());
tl4.insert("three".to_string());
println!("Running check_tag_list_n_last 4");
check_tag_list_n_last(&client, 2, "latest", &tl4).await;
println!("Running get_readiness");
get_readiness(&client).await;
println!("Running get_health");
get_health(&client).await;
println!("Running get_metrics");
get_metrics(&client).await;
check_tag_list_n_last(&client, 2, "latest", &tl4).await;
}
}
| get_non_existent_manifest |
game.ts | import { useMemo } from "react";
import { useQuery, useMutation, OperationVariables, useSubscription } from "@apollo/client";
import {
GET_WORD_CATEGORIES,
GET_GAME_ROUNDS,
GET_ROUND_ANSWERS,
} from "../lib/graphql/queries/game";
import {
INSERT_NEW_GAME,
INSERT_GAME_ROUNDS,
INSERT_ROUND_ANSWERS,
} from "../lib/graphql/mutations/game";
import { GET_CURRENT_LIVE_GAME } from "../lib/graphql/subscriptions/game";
import {
InsertGameRoundsMutation,
InsertNewGameMutation,
InsertGameRoundsMutationVariables,
InsertNewGameMutationVariables,
InsertRoundAnswersMutation,
InsertRoundAnswersMutationVariables,
} from "../lib/graphql/mutations/__generated__/game";
import {
GetWordCategoriesQuery,
GetWordCategoriesQueryVariables,
} from "../lib/graphql/queries/__generated__/game";
import { GetCurrentLiveGameSubscription, GetCurrentLiveGameSubscriptionVariables } from "../lib/graphql/subscriptions/__generated__/game";
export const useGetWordCategories = () => {
const { error, data, loading } = useQuery<
GetWordCategoriesQuery,
GetWordCategoriesQueryVariables
>(GET_WORD_CATEGORIES);
return useMemo(
() => ({
loadingCategories: loading,
wordCategories: data?.word_categories,
error,
}),
[loading, data?.word_categories, error]
);
};
export const useInsertGame = () => {
const [insertGame, { data, loading, error }] = useMutation<
InsertNewGameMutation,
InsertNewGameMutationVariables
>(INSERT_NEW_GAME);
return useMemo(
() => ({
loading,
error,
game: data?.insert_rooms_games_one,
insertGame: (game: OperationVariables) => {
return insertGame({ variables: { game } }).then(
({ data }) => data?.insert_rooms_games_one
);
},
}),
[loading, error, data?.insert_rooms_games_one, insertGame]
);
};
export const useInsertGameRounds = () => {
const [insertGameRounds, { data, loading, error }] = useMutation<
InsertGameRoundsMutation,
InsertGameRoundsMutationVariables
>(INSERT_GAME_ROUNDS);
return useMemo(
() => ({
loading,
error,
game: data?.insert_games_rounds,
insertGameRounds: (rounds: OperationVariables) => {
return insertGameRounds({ variables: { rounds } }).then(
({ data }) => data?.insert_games_rounds
);
},
}),
[loading, error, data?.insert_games_rounds, insertGameRounds]
);
};
export const useGetCurrentGame = (roomId: string) => {
const { error, data, loading } = useSubscription<
GetCurrentLiveGameSubscription,
GetCurrentLiveGameSubscriptionVariables
>(GET_CURRENT_LIVE_GAME, {
variables: {
roomId,
},
});
return useMemo(
() => ({
loadingGame: loading,
game: data?.rooms_games,
error,
}),
[loading, data?.rooms_games, error]
);
};
export const useInsertRoundAnswers = () => {
const [insertAnswers, { data, loading, error }] = useMutation<
InsertRoundAnswersMutation,
InsertRoundAnswersMutationVariables
>(INSERT_ROUND_ANSWERS);
return useMemo(
() => ({
loadingAnswers: loading,
error,
answers: data?.insert_rounds_answers,
insertAnswers: (answers: OperationVariables) => {
return insertAnswers({ variables: { answers } }).then(
({ data }) => data?.insert_rounds_answers
);
},
}),
[loading, error, data?.insert_rounds_answers, insertAnswers]
);
};
export const useGetGameRounds = (gameId: string) => {
const { error, data, loading } = useQuery(GET_GAME_ROUNDS, {
variables: {
gameId,
},
});
return useMemo(
() => ({
loadingRounds: loading,
rounds: data?.games_rounds,
error,
}), | [loading, data?.games_rounds, error]
);
};
export const useCheckRoundAnswers = () => {
const { data, loading, error } = useQuery(GET_ROUND_ANSWERS);
return useMemo(
() => ({
loadingResults: loading,
results: data?.animals,
error,
}),
[loading, data?.animals, error]
);
}; | |
views.py | from bfstpw.models import ForumThread, ForumPost
from datetime import datetime
from django.conf import settings
from django.core.paginator import Paginator
from django.core.urlresolvers import reverse
from django.db.models import Count
from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.template import Context
import django.utils.timezone
from markdown import markdown
def threadlist(request):
c = Context({"threadlist" :
[{"id":t.id
,"name":t.thread_title
,"poster":t.getOriginalPost().poster
,"replycount":t.postcount
,"lastpage":(t.postcount / getattr(settings, 'BFSTPW_MAX_POSTS_PER_PAGE', 20))+1 | } for t in
ForumThread.objects.sortByLastPost().annotate(postcount=Count('forumpost'))]})
return render(request, 'bfstpw/threadlist.html', c)
def thread(request, thread_id, message=''):
current_thread = get_object_or_404(ForumThread, id=thread_id)
max_posts_per_page = getattr(settings, 'BFSTPW_MAX_POSTS_PER_PAGE', 20)
paginator = Paginator(current_thread.forumpost_set.order_by('date_posted'), max_posts_per_page)
c = Context(
{"threadlist" :
[{"id":t.id
,"name":t.thread_title
} for t in ForumThread.objects.sortByLastPost()],
"thread" : current_thread,
"posts" : paginator.page(request.GET.get('page',1)),
"pages" : paginator.page_range,
"message" : message
})
return render(request, 'bfstpw/thread.html', c)
def post(request, thread_id):
t = get_object_or_404(ForumThread, id=thread_id)
posts = t.forumpost_set
"""
# TODO: don't let users post too quickly
session = request.session
current_time = time()
if (session.get('lastposttime',0) + 10) < current_time:
message_html = markdown(request.POST['message'], safe_mode='escape')
posts.create(poster=request.POST['name'],message_body=message_html,date_posted=datetime.now())
msg = ''
session['lastposttime'] = current_time
else:
msg = "Error: you must wait 10 seconds before posting"
"""
message_html = markdown(request.POST['message'], safe_mode='escape')
posts.create(poster=request.POST['name'], message_body=message_html,
date_posted=django.utils.timezone.now())
pagenum = (posts.count() / getattr(settings, 'BFSTPW_MAX_POSTS_PER_PAGE', 20))+1
return HttpResponseRedirect(reverse('bfstpw-thread', args=(t.id,))+'?page=%d' % pagenum)
def newthreadmake(request):
t = ForumThread(thread_title=request.POST['threadname'])
t.save()
message_html = markdown(request.POST['message'], safe_mode='escape')
t.forumpost_set.create(poster=request.POST['name'],
message_body=message_html,
date_posted=django.utils.timezone.now())
return HttpResponseRedirect(reverse('bfstpw-thread', args=(t.id,))) | ,"date":t.mostrecent
,"lastposter":t.getLatestPost().poster |
gdbroot.py | #!/usr/bin/python3
'''
Server for tracing patched sudo. run it with sudo or as root.
Requires 'cmds' file as gdb comamnds in current directory.
Running command:
python gdbroot.py
'''
import os
import time
FIFO_PATH = "/tmp/gdbsudo"
try:
os.unlink(FIFO_PATH)
except:
pass
os.umask(0)
os.mkfifo(FIFO_PATH, 0o666)
while True:
fifo = open(FIFO_PATH, "r")
pid = int(fifo.read())
fifo.close()
cmd = 'gdb -q -p %d < cmds > log 2>&1' % pid
print('\n=== got: %d. sleep 0.5s' % pid) | #time.sleep(0.5)
print(cmd)
os.system(cmd)
print('done') | |
util.go | package goutil
import (
"golang.org/x/sys/unix"
)
func uname2str(u []byte) string {
str := ""
for _, v := range u {
m := int(v)
if m <= 0 {
break
}
str += string(m)
}
return str
}
func GetUnixVer() (string, error) {
var uname unix.Utsname
if err := unix.Uname(&uname); err != nil {
return "", err
}
return uname2str(uname.Version[:]), nil
}
func getUnixSysName() (string, error) {
var uname unix.Utsname
if err := unix.Uname(&uname); err != nil |
return uname2str(uname.Sysname[:]), nil
}
func getUnixNodeName() (string, error) {
var uname unix.Utsname
if err := unix.Uname(&uname); err != nil {
return "", err
}
return uname2str(uname.Nodename[:]), nil
}
func getUnixMachineName() (string, error) {
var uname unix.Utsname
if err := unix.Uname(&uname); err != nil {
return "", err
}
return uname2str(uname.Machine[:]), nil
}
func getUnixRelease() (string, error) {
var uname unix.Utsname
if err := unix.Uname(&uname); err != nil {
return "", err
}
return uname2str(uname.Release[:]), nil
}
| {
return "", err
} |
index.tsx | import Taro, { Component } from "@tarojs/taro"
import { View,Text } from '@tarojs/components';
import './index.less';
interface Props { | onClose: () => void,
name: String,
url: String,
order: Number
}
export default class QRModal extends Component<Props> {
componentDidMount() {
let ele = document.getElementById('modal');
if(this.props.isShow) {
ele.style.display = "flex";
}else {
ele.style.display = "none";
}
}
componentWillReceiveProps(nextProps: any) {
console.log(nextProps)
if (nextProps.isShow) {
let ele = document.getElementById('modal');
ele.style.display = 'flex';
}
}
handleClose = () => {
let ele = document.getElementById('modal');
ele.style.display = "none";
this.props.onClose && this.props.onClose()
}
render() {
return (
<View id="modal" className="modal">
<View className="modal_content">
<View className="qr_code_content" style={{ flex: 8 }}>
<View className="store_name">{this.props.name}</View>
{/* <img className="qr_code" src={this.props.url} alt="" /> */}
<View className="order_num">订单号:{this.props.order}</View>
<View className="gift_step">请向工作人员展示二维码领取礼品</View>
</View>
<View style={{ flex: 1 }}></View>
<View style={{ flex: 1 }}>
<View className="close_modal" onClick={this.handleClose.bind(this)}> x </View>
</View>
</View>
</View>
)
}
} | isShow: Boolean, |
recipe-65251.py | def CalculateApacheIpHits(logfile_pathname):
# make a dictionary to store Ip's and their hit counts and read the
# contents of the logfile line by line
|
# example usage
HitsDictionary = CalculateApacheIpHits("/usr/local/nusphere/apache/logs/access_log")
print HitsDictionary["127.0.0.1"]
| IpHitListing = {}
Contents = open(logfile_pathname, "r").readlines()
# go through each line of the logfile
for line in Contents:
#split the string to isolate the ip
Ip = line.split(" ")[0]
# ensure length of the ip is proper: see discussion
if 6 < len(Ip) < 15:
# Increase by 1 if ip exists else hit count = 1
IpHitListing[Ip] = IpHitListing.get(Ip, 0) + 1
return IpHitListing |
history_test.go | package history
import (
"strings"
"testing"
"github.com/itchyny/bed/buffer"
)
func TestHistoryUndo(t *testing.T) {
history := NewHistory()
b, index, offset, cursor := history.Undo()
if b != nil {
t.Errorf("history.Undo should return nil buffer but got %q", b)
}
if index != -1 {
t.Errorf("history.Undo should return index -1 but got %d", index)
}
if offset != 0 {
t.Errorf("history.Undo should return offset 0 but got %d", offset)
}
if cursor != 0 {
t.Errorf("history.Undo should return cursor 0 but got %d", cursor)
}
buffer1 := buffer.NewBuffer(strings.NewReader("test1"))
history.Push(buffer1, 2, 1)
buffer2 := buffer.NewBuffer(strings.NewReader("test2"))
history.Push(buffer2, 3, 2)
buf := make([]byte, 8)
b, index, offset, cursor = history.Undo()
b.Read(buf)
if string(buf) != "test1\x00\x00\x00" {
t.Errorf("buf should be %q but got %q", "test1\x00\x00\x00", string(buf))
}
if index != 0 {
t.Errorf("push should return index 0 but got %d", index)
}
if offset != 2 {
t.Errorf("push should return offset 2 but got %d", offset) | t.Errorf("push should return cursor 1 but got %d", cursor)
}
buf = make([]byte, 8)
b, offset, cursor = history.Redo()
b.Read(buf)
if string(buf) != "test2\x00\x00\x00" {
t.Errorf("buf should be %q but got %q", "test2\x00\x00\x00", string(buf))
}
if offset != 3 {
t.Errorf("history.Redo should return offset 3 but got %d", offset)
}
if cursor != 2 {
t.Errorf("history.Redo should return cursor 2 but got %d", cursor)
}
history.Undo()
buffer3 := buffer.NewBuffer(strings.NewReader("test2"))
history.Push(buffer3, 3, 2)
b, offset, cursor = history.Redo()
if b != nil {
t.Errorf("history.Redo should return nil buffer but got %q", b)
}
if offset != 0 {
t.Errorf("history.Redo should return offset 0 but got %d", offset)
}
if cursor != 0 {
t.Errorf("history.Redo should return cursor 0 but got %d", cursor)
}
} | }
if cursor != 1 { |
benchmark_bundle.js | // 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":227}],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":228,"@stdlib/constants/int16/min":229}],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":230,"@stdlib/constants/int32/min":231}],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":232,"@stdlib/constants/int8/min":233}],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":389}],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 | () {
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":157,"@stdlib/constants/uint16/max":234}],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":159,"@stdlib/constants/uint32/max":235}],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":161,"@stdlib/constants/uint8/max":236}],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":163}],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":357}],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":235,"@stdlib/math/base/assert/is-integer":239}],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":221,"@stdlib/math/base/assert/is-integer":239}],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":357}],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":312}],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":357}],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":222,"@stdlib/math/base/assert/is-integer":239}],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":150}],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":323,"@stdlib/utils/native-class":357}],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":357}],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":357}],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":384}],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":357}],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":357}],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":357}],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":312}],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":226,"@stdlib/constants/float64/pinf":227,"@stdlib/math/base/assert/is-integer":239}],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":312}],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":241}],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":241}],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":168,"@stdlib/utils/define-nonenumerable-read-only-property":312}],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":312}],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":312}],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":312}],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":250,"@stdlib/utils/native-class":357}],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":250}],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":166,"@stdlib/utils/define-nonenumerable-read-only-property":312}],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":323,"@stdlib/utils/native-class":357}],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":312}],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":357}],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":150,"@stdlib/assert/tools/array-function":166,"@stdlib/utils/define-nonenumerable-read-only-property":312}],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.
*/
/* eslint-disable no-new-wrappers, no-undefined, no-empty-function */
'use strict';
// MODULES //
var bench = require( '@stdlib/bench' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var pkg = require( './../package.json' ).name;
var isString = require( './../lib' );
// MAIN //
bench( pkg+'::primitives', function benchmark( b ) {
var values;
var bool;
var i;
values = [
'5',
5,
NaN,
true,
false,
null,
undefined
];
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
bool = isString( values[ i % values.length ] );
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+'::objects', function benchmark( b ) {
var values;
var bool;
var i;
values = [
[],
{},
function noop() {},
new String( 'beep' )
];
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
bool = isString( values[ i % values.length ] );
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+'::primitives:isPrimitive', function benchmark( b ) {
var values;
var bool;
var i;
values = [
'5',
5,
NaN,
true,
false,
null,
undefined
];
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
bool = isString.isPrimitive( values[ i % values.length ] );
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+'::objects:isPrimitive', function benchmark( b ) {
var values;
var bool;
var i;
values = [
[],
{},
function noop() {},
new String( 'beep' )
];
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
bool = isString.isPrimitive( values[ i % values.length ] );
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+'::primitives:isObject', function benchmark( b ) {
var values;
var bool;
var i;
values = [
'5',
5,
NaN,
true,
false,
null,
undefined
];
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
bool = isString.isObject( values[ i % values.length ] );
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+'::objects:isObject', function benchmark( b ) {
var values;
var bool;
var i;
values = [
[],
{},
function noop() {},
new String( 'beep' )
];
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
bool = isString.isObject( values[ i % values.length ] );
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();
});
},{"./../lib":150,"./../package.json":156,"@stdlib/assert/is-boolean":72,"@stdlib/bench":213}],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';
/**
* 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":151,"./object.js":152,"./primitive.js":153,"@stdlib/utils/define-nonenumerable-read-only-property":312}],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 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":152,"./primitive.js":153}],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';
// 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":154,"@stdlib/assert/has-tostringtag-support":50,"@stdlib/utils/native-class":357}],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';
/**
* 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;
},{}],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';
// 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":155}],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';
// eslint-disable-next-line stdlib/no-redeclare
var valueOf = String.prototype.valueOf; // non-generic
// EXPORTS //
module.exports = valueOf;
},{}],156:[function(require,module,exports){
module.exports={
"name": "@stdlib/assert/is-string",
"version": "0.0.0",
"description": "Test if a value is a string.",
"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",
"stdassert",
"assertion",
"assert",
"utilities",
"utility",
"utils",
"util",
"string",
"str",
"is",
"isstring",
"type",
"check",
"primitive",
"object",
"valid",
"validate",
"test",
"isvalid"
]
}
},{}],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 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":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 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":357}],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 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":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 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":357}],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 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":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 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":357}],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';
/**
* 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":164}],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';
// 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":357}],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 isArray = require( '@stdlib/assert/is-array' );
var format = require( '@stdlib/string/format' );
// 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( format( 'invalid argument. Must provide a function. Value: `%s`.', 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,"@stdlib/string/format":289}],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 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":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 isArrayLike = require( '@stdlib/assert/is-array-like' );
var format = require( '@stdlib/string/format' );
// 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( format( 'invalid argument. Must provide a function. Value: `%s`.', 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,"@stdlib/string/format":289}],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';
/**
* 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":167}],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';
// 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 format = require( '@stdlib/string/format' );
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( format( 'invalid argument. Must provide a function. Value: `%s`.', 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":191,"./harness":192,"@stdlib/assert/is-function":93,"@stdlib/streams/node/transform":275,"@stdlib/string/format":289,"@stdlib/utils/define-nonenumerable-read-only-property":312}],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 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}],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';
// EXPORTS //
module.exports = clearTimeout;
},{}],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 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":259,"@stdlib/string/replace":294,"@stdlib/string/trim":296}],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 //
/**
* 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;
},{}],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';
// 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":211}],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 //
/**
* 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;
},{}],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 //
/**
* 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;
},{}],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';
// 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;
},{}],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 //
/**
* 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;
},{}],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';
// 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":170,"./comment.js":172,"./deep_equal.js":173,"./end.js":174,"./ended.js":175,"./equal.js":176,"./exit.js":177,"./fail.js":178,"./not_deep_equal.js":180,"./not_equal.js":181,"./not_ok.js":182,"./ok.js":183,"./pass.js":184,"./run.js":185,"./skip.js":187,"./todo.js":188,"@stdlib/time/tic":298,"@stdlib/time/toc":302,"@stdlib/utils/define-nonenumerable-read-only-property":312,"@stdlib/utils/define-property":317,"@stdlib/utils/inherit":336,"events":390}],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 `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;
},{}],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 `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;
},{}],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 //
/**
* 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;
},{}],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';
// 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;
},{}],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';
// 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;
},{}],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';
// 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":171,"./set_timeout.js":186}],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';
// EXPORTS //
module.exports = setTimeout;
},{}],187:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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;
},{}],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';
// 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;
},{}],189:[function(require,module,exports){
module.exports={
"skip": false,
"iterations": null,
"repeats": 3,
"timeout": 300000
}
},{}],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 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 format = require( '@stdlib/string/format' );
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( format( 'invalid argument. Must provide either an options object or a function. Value: `%s`.', arguments[ 0 ] ) );
}
} else {
options = arguments[ 0 ];
if ( !isObject( options ) ) {
throw new TypeError( format( 'invalid argument. First argument must be an object. Value: `%s`.', options ) );
}
clbk = arguments[ 1 ];
if ( !isFunction( clbk ) ) {
throw new TypeError( format( 'invalid argument. Second argument must be a function. Value: `%s`.', clbk ) );
}
}
opts = {};
if ( hasOwnProp( options, 'autoclose' ) ) {
opts.autoclose = options.autoclose;
if ( !isBoolean( opts.autoclose ) ) {
throw new TypeError( format( 'invalid option. `%s` option must be a boolean. Option: `%s`.', 'autoclose', opts.autoclose ) );
}
}
if ( hasOwnProp( options, 'stream' ) ) {
opts.stream = options.stream;
if ( !isNodeWritableStreamLike( opts.stream ) ) {
throw new TypeError( format( 'invalid option. `%s` option must be a writable stream. Option: `%s`.', 'stream', 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":192,"./log":198,"./utils/can_emit_exit.js":209,"./utils/process.js":212,"@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/string/format":289,"@stdlib/utils/noop":364,"@stdlib/utils/omit":366,"@stdlib/utils/pick":368}],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 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":190,"./utils/can_emit_exit.js":209}],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 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 format = require( '@stdlib/string/format' );
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( format( 'invalid argument. Must provide either an options object or a function. Value: `%s`.', options ) );
}
} else if ( arguments.length > 1 ) {
if ( !isObject( options ) ) {
throw new TypeError( format( 'invalid argument. First argument must be an object. Value: `%s`.', options ) );
}
if ( hasOwnProp( options, 'autoclose' ) ) {
opts.autoclose = options.autoclose;
if ( !isBoolean( opts.autoclose ) ) {
throw new TypeError( format( 'invalid option. `%s` option must be a boolean. Option: `%s`.', 'autoclose', opts.autoclose ) );
}
}
cb = clbk;
if ( !isFunction( cb ) ) {
throw new TypeError( format( 'invalid argument. Second argument must be a function. Value: `%s`.', 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( format( 'invalid argument. First argument must be a string. Value: `%s`.', 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( format( 'invalid argument. Third argument must be a function. Value: `%s`.', 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":179,"./../defaults.json":189,"./../runner":206,"./../utils/next_tick.js":211,"./init.js":193,"./validate.js":196,"@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":150,"@stdlib/string/format":289,"@stdlib/utils/copy":308,"@stdlib/utils/define-nonenumerable-read-only-accessor":310,"@stdlib/utils/define-nonenumerable-read-only-property":312}],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 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":194,"./pretest.js":195}],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 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":179,"@stdlib/assert/is-string":150,"@stdlib/utils/copy":308}],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';
// 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( 'unexpected 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( 'unexpected error. Invalid benchmark.' );
}
if ( err ) {
return clbk( err );
}
return clbk();
}
}
// EXPORTS //
module.exports = pretest;
},{"./../benchmark-class":179,"@stdlib/assert/is-string":150,"@stdlib/utils/copy":308}],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 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;
var format = require( '@stdlib/string/format' );
// 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( format( 'invalid argument. Options argument must be an object. Value: `%s`.', options ) );
}
if ( hasOwnProp( options, 'skip' ) ) {
opts.skip = options.skip;
if ( !isBoolean( opts.skip ) ) {
return new TypeError( format( 'invalid option. `%s` option must be a boolean. Option: `%s`.', 'skip', opts.skip ) );
}
}
if ( hasOwnProp( options, 'iterations' ) ) {
opts.iterations = options.iterations;
if (
!isPositiveInteger( opts.iterations ) &&
!isNull( opts.iterations )
) {
return new TypeError( format( 'invalid option. `%s` option must be either a positive integer or null. Option: `%s`.', 'iterations', opts.iterations ) );
}
}
if ( hasOwnProp( options, 'repeats' ) ) {
opts.repeats = options.repeats;
if ( !isPositiveInteger( opts.repeats ) ) {
return new TypeError( format( 'invalid option. `%s` option must be a positive integer. Option: `%s`.', 'repeats', opts.repeats ) );
}
}
if ( hasOwnProp( options, 'timeout' ) ) {
opts.timeout = options.timeout;
if ( !isPositiveInteger( opts.timeout ) ) {
return new TypeError( format( 'invalid option. `%s` option must be a positive integer. Option: `%s`.', 'timeout', 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,"@stdlib/string/format":289}],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';
/**
* 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":169}],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';
// 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":199,"@stdlib/streams/node/transform":275,"@stdlib/string/from-code-point":292}],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 //
/**
* 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;
},{}],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.
*/
'use strict';
// MAIN //
/**
* Removes any pending benchmarks.
*
* @private
*/
function clear() {
/* eslint-disable no-invalid-this */
this._benchmarks.length = 0;
}
// EXPORTS //
module.exports = clear;
},{}],201:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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;
},{}],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.
*/
/* 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":211,"@stdlib/assert/is-string":150,"@stdlib/streams/node/transform":275}],203:[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 RE_EOL = require( '@stdlib/regexp/eol' ).REGEXP;
// 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( 'unexpected 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( RE_EOL );
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":259,"@stdlib/string/replace":294}],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';
// 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;
},{}],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.
*/
'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;
},{}],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';
// 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":200,"./close.js":201,"./create_stream.js":202,"./exit.js":205,"./push.js":207,"./run.js":208,"@stdlib/streams/node/transform":275,"@stdlib/utils/define-property":317,"@stdlib/utils/inherit":336,"events":390}],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.
*/
/* 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":203,"./encode_result.js":204,"@stdlib/assert/is-string":150}],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';
// MAIN //
/**
* Runs pending benchmarks.
*
* @private
*/
function run() {
/* eslint-disable no-invalid-this */
this.emit( '_run' );
}
// EXPORTS //
module.exports = run;
},{}],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';
// 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":210,"@stdlib/assert/is-browser":78}],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.js' );
// MAIN //
var bool = ( proc && typeof proc.exit === 'function' );
// EXPORTS //
module.exports = bool;
},{"./process.js":212}],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';
// 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;
},{}],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';
// MODULES //
var proc = require( 'process' );
// EXPORTS //
module.exports = proc;
},{"process":399}],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';
/**
* 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":197}],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';
// MAIN //
var ctor = require( 'buffer' ).Buffer; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{"buffer":389}],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';
/**
* 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":214,"./polyfill.js":216,"@stdlib/assert/has-node-buffer-support":44}],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';
// TODO: write (browser) polyfill
// MAIN //
/**
* Buffer constructor.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],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 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":215}],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';
/**
* 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":217,"./main.js":219,"./polyfill.js":220}],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';
// MODULES //
var isBuffer = require( '@stdlib/assert/is-buffer' );
var format = require( '@stdlib/string/format' );
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( format( 'invalid argument. Must provide a Buffer. Value: `%s`.', buffer ) );
}
return Buffer.from( buffer );
}
// EXPORTS //
module.exports = fromBuffer;
},{"@stdlib/assert/is-buffer":79,"@stdlib/buffer/ctor":215,"@stdlib/string/format":289}],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';
// MODULES //
var isBuffer = require( '@stdlib/assert/is-buffer' );
var format = require( '@stdlib/string/format' );
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( format( 'invalid argument. Must provide a Buffer. Value: `%s`.', buffer ) );
}
return new Buffer( buffer ); // eslint-disable-line no-buffer-constructor
}
// EXPORTS //
module.exports = fromBuffer;
},{"@stdlib/assert/is-buffer":79,"@stdlib/buffer/ctor":215,"@stdlib/string/format":289}],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';
/**
* 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;
},{}],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';
/**
* 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;
},{}],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';
/**
* 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;
},{}],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';
/**
* 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;
},{}],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';
/**
* 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;
},{}],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';
/**
* 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":250}],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';
/**
* 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;
},{}],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 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;
},{}],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 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;
},{}],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 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;
},{}],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 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;
},{}],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 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;
},{}],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';
/**
* 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;
},{}],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 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;
},{}],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 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;
},{}],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 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;
},{}],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';
/**
* 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;
},{}],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';
/**
* 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;
},{}],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 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":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';
// 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":243}],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';
/**
* 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":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';
// 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;
},{}],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';
/**
* 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":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';
// 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;
},{}],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';
/**
* 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":246}],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';
// 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":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';
// 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":223,"@stdlib/constants/float64/high-word-exponent-mask":224,"@stdlib/constants/float64/high-word-significand-mask":225,"@stdlib/constants/float64/pinf":227,"@stdlib/math/base/assert/is-nan":241,"@stdlib/number/float64/base/from-words":252,"@stdlib/number/float64/base/to-words":255}],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';
// 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":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';
// 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;
},{}],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';
/**
* 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":251}],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';
// EXPORTS //
module.exports = Number; // eslint-disable-line stdlib/require-globals
},{}],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';
/**
* 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":254}],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';
// 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}],254:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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":253,"@stdlib/array/float64":5,"@stdlib/array/uint32":19}],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';
/**
* 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":257}],256:[function(require,module,exports){
arguments[4][253][0].apply(exports,arguments)
},{"@stdlib/assert/is-little-endian":107,"dup":253}],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';
// 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":258}],258:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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":256,"@stdlib/array/float64":5,"@stdlib/array/uint32":19}],259:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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":260,"./regexp.js":261,"./regexp_capture.js":262,"@stdlib/utils/define-nonenumerable-read-only-property":312}],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 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":263}],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 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":260}],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';
// 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":260}],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';
// 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;
var format = require( '@stdlib/string/format' );
// 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( format( 'invalid argument. Options argument must be an object. Value: `%s`.', options ) );
}
if ( hasOwnProp( options, 'flags' ) ) {
opts.flags = options.flags;
if ( !isString( opts.flags ) ) {
return new TypeError( format( 'invalid option. `%s` option must be a string. Option: `%s`.', 'flags', opts.flags ) );
}
}
if ( hasOwnProp( options, 'capture' ) ) {
opts.capture = options.capture;
if ( !isBoolean( opts.capture ) ) {
return new TypeError( format( 'invalid option. `%s` option must be a boolean. Option: `%s`.', 'capture', 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":150,"@stdlib/string/format":289}],264:[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":265,"./regexp.js":266,"@stdlib/utils/define-nonenumerable-read-only-property":312}],265:[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;
},{}],266:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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":265}],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';
/**
* 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":268,"./regexp.js":269,"@stdlib/utils/define-nonenumerable-read-only-property":312}],268:[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;
},{}],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 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":268}],270:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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":393}],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 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":270,"./defaults.json":272,"./destroy.js":273,"./validate.js":278,"@stdlib/utils/copy":308,"@stdlib/utils/inherit":336,"debug":393,"readable-stream":410}],272:[function(require,module,exports){
module.exports={
"objectMode": false,
"encoding": null,
"allowHalfOpen": false,
"decodeStrings": true
}
},{}],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';
// 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":362,"debug":393}],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 isObject = require( '@stdlib/assert/is-plain-object' );
var format = require( '@stdlib/string/format' );
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( format( 'invalid argument. Options argument must be an object. Value: `%s`.', 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":276,"@stdlib/assert/is-plain-object":138,"@stdlib/string/format":289,"@stdlib/utils/copy":308}],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';
/**
* 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":271,"./factory.js":274,"./main.js":276,"./object_mode.js":277,"@stdlib/utils/define-nonenumerable-read-only-property":312}],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 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":270,"./defaults.json":272,"./destroy.js":273,"./validate.js":278,"@stdlib/utils/copy":308,"@stdlib/utils/inherit":336,"debug":393,"readable-stream":410}],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';
// MODULES //
var isObject = require( '@stdlib/assert/is-plain-object' );
var format = require( '@stdlib/string/format' );
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( format( 'invalid argument. Options argument must be an object. Value: `%s`.', options ) );
}
opts = copy( options );
} else {
opts = {};
}
opts.objectMode = true;
return new Stream( opts );
}
// EXPORTS //
module.exports = objectMode;
},{"./main.js":276,"@stdlib/assert/is-plain-object":138,"@stdlib/string/format":289,"@stdlib/utils/copy":308}],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 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;
var format = require( '@stdlib/string/format' );
// 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( format( 'invalid argument. Options argument must be an object. Value: `%s`.', options ) );
}
if ( hasOwnProp( options, 'transform' ) ) {
opts.transform = options.transform;
if ( !isFunction( opts.transform ) ) {
return new TypeError( format( 'invalid option. `%s` option must be a function. Option: `%s`.', 'transform', opts.transform ) );
}
}
if ( hasOwnProp( options, 'flush' ) ) {
opts.flush = options.flush;
if ( !isFunction( opts.flush ) ) {
return new TypeError( format( 'invalid option. `%s` option must be a function. Option: `%s`.', 'flush', opts.flush ) );
}
}
if ( hasOwnProp( options, 'objectMode' ) ) {
opts.objectMode = options.objectMode;
if ( !isBoolean( opts.objectMode ) ) {
return new TypeError( format( 'invalid option. `%s` option must be a boolean. Option: `%s`.', 'objectMode', opts.objectMode ) );
}
}
if ( hasOwnProp( options, 'encoding' ) ) {
opts.encoding = options.encoding;
if ( !isString( opts.encoding ) ) {
return new TypeError( format( 'invalid option. `%s` option must be a string. Option: `%s`.', 'encoding', opts.encoding ) );
}
}
if ( hasOwnProp( options, 'allowHalfOpen' ) ) {
opts.allowHalfOpen = options.allowHalfOpen;
if ( !isBoolean( opts.allowHalfOpen ) ) {
return new TypeError( format( 'invalid option. `%s` option must be a boolean. Option: `%s`.', 'allowHalfOpen', opts.allowHalfOpen ) );
}
}
if ( hasOwnProp( options, 'highWaterMark' ) ) {
opts.highWaterMark = options.highWaterMark;
if ( !isNonNegative( opts.highWaterMark ) ) {
return new TypeError( format( 'invalid option. `%s` option must be a nonnegative number. Option: `%s`.', 'highWaterMark', opts.highWaterMark ) );
}
}
if ( hasOwnProp( options, 'decodeStrings' ) ) {
opts.decodeStrings = options.decodeStrings;
if ( !isBoolean( opts.decodeStrings ) ) {
return new TypeError( format( 'invalid option. `%s` option must be a boolean. Option: `%s`.', 'decodeStrings', 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":150,"@stdlib/string/format":289}],279:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2022 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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( './is_number.js' );
// NOTE: for the following, we explicitly avoid using stdlib packages in this particular package in order to avoid circular dependencies.
var abs = Math.abs; // eslint-disable-line stdlib/no-builtin-math
var lowercase = String.prototype.toLowerCase;
var uppercase = String.prototype.toUpperCase;
var replace = String.prototype.replace;
// VARIABLES //
var RE_EXP_POS_DIGITS = /e\+(\d)$/;
var RE_EXP_NEG_DIGITS = /e-(\d)$/;
var RE_ONLY_DIGITS = /^(\d+)$/;
var RE_DIGITS_BEFORE_EXP = /^(\d+)e/;
var RE_TRAILING_PERIOD_ZERO = /\.0$/;
var RE_PERIOD_ZERO_EXP = /\.0*e/;
var RE_ZERO_BEFORE_EXP = /(\..*[^0])0*e/;
// MAIN //
/**
* Formats a token object argument as a floating-point number.
*
* @private
* @param {Object} token - token object
* @throws {Error} must provide a valid floating-point number
* @returns {string} formatted token argument
*/
function formatDouble( token ) {
var digits;
var out;
var f = parseFloat( token.arg );
if ( !isFinite( f ) ) { // NOTE: We use the global `isFinite` function here instead of `@stdlib/math/base/assert/is-finite` in order to avoid circular dependencies.
if ( !isNumber( token.arg ) ) {
throw new Error( 'invalid floating-point number. Value: ' + out );
}
// Case: NaN, Infinity, or -Infinity
f = token.arg;
}
switch ( token.specifier ) {
case 'e':
case 'E':
out = f.toExponential( token.precision );
break;
case 'f':
case 'F':
out = f.toFixed( token.precision );
break;
case 'g':
case 'G':
if ( abs( f ) < 0.0001 ) {
digits = token.precision;
if ( digits > 0 ) {
digits -= 1;
}
out = f.toExponential( digits );
} else {
out = f.toPrecision( token.precision );
}
if ( !token.alternate ) {
out = replace.call( out, RE_ZERO_BEFORE_EXP, '$1e' );
out = replace.call( out, RE_PERIOD_ZERO_EXP, 'e');
out = replace.call( out, RE_TRAILING_PERIOD_ZERO, '' );
}
break;
default:
throw new Error( 'invalid double notation. Value: ' + token.specifier );
}
out = replace.call( out, RE_EXP_POS_DIGITS, 'e+0$1' );
out = replace.call( out, RE_EXP_NEG_DIGITS, 'e-0$1' );
if ( token.alternate ) {
out = replace.call( out, RE_ONLY_DIGITS, '$1.' );
out = replace.call( out, RE_DIGITS_BEFORE_EXP, '$1.e' );
}
if ( f >= 0 && token.sign ) {
out = token.sign + out;
}
out = ( token.specifier === uppercase.call( token.specifier ) ) ?
uppercase.call( out ) :
lowercase.call( out );
return out;
}
// EXPORTS //
module.exports = formatDouble;
},{"./is_number.js":282}],280:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2022 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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( './is_number.js' );
var zeroPad = require( './zero_pad.js' );
// NOTE: for the following, we explicitly avoid using stdlib packages in this particular package in order to avoid circular dependencies.
var lowercase = String.prototype.toLowerCase;
var uppercase = String.prototype.toUpperCase;
// MAIN //
/**
* Formats a token object argument as an integer.
*
* @private
* @param {Object} token - token object
* @throws {Error} must provide a valid integer
* @returns {string} formatted token argument
*/
function formatInteger( token ) {
var base;
var out;
var i;
switch ( token.specifier ) {
case 'b':
// Case: %b (binary)
base = 2;
break;
case 'o':
// Case: %o (octal)
base = 8;
break;
case 'x':
case 'X':
// Case: %x, %X (hexadecimal)
base = 16;
break;
case 'd':
case 'i':
case 'u':
default:
// Case: %d, %i, %u (decimal)
base = 10;
break;
}
out = token.arg;
i = parseInt( out, 10 );
if ( !isFinite( i ) ) { // NOTE: We use the global `isFinite` function here instead of `@stdlib/math/base/assert/is-finite` in order to avoid circular dependencies.
if ( !isNumber( out ) ) {
throw new Error( 'invalid integer. Value: ' + out );
}
i = 0;
}
if ( i < 0 && ( token.specifier === 'u' || base !== 10 ) ) {
i = 0xffffffff + i + 1;
}
if ( i < 0 ) {
out = ( -i ).toString( base );
if ( token.precision ) {
out = zeroPad( out, token.precision, token.padRight );
}
out = '-' + out;
} else {
out = i.toString( base );
if ( !i && !token.precision ) {
out = '';
} else if ( token.precision ) {
out = zeroPad( out, token.precision, token.padRight );
}
if ( token.sign ) {
out = token.sign + out;
}
}
if ( base === 16 ) {
if ( token.alternate ) {
out = '0x' + out;
}
out = ( token.specifier === uppercase.call( token.specifier ) ) ?
uppercase.call( out ) :
lowercase.call( out );
}
if ( base === 8 ) {
if ( token.alternate && out.charAt( 0 ) !== '0' ) {
out = '0' + out;
}
}
return out;
}
// EXPORTS //
module.exports = formatInteger;
},{"./is_number.js":282,"./zero_pad.js":286}],281:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2022 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
/**
* Generate string from a token array by interpolating values.
*
* @module @stdlib/string/base/format-interpolate
*
* @example
* var formatInterpolate = require( '@stdlib/string/base/format-interpolate' );
*
* var tokens = ['Hello ', { 'specifier': 's' }, '!' ];
* var out = formatInterpolate( tokens, 'World' );
* // returns 'Hello World!'
*/
// MODULES //
var formatInterpolate = require( './main.js' );
// EXPORTS //
module.exports = formatInterpolate;
},{"./main.js":284}],282:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2022 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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' ); // NOTE: we inline the `isNumber.isPrimitive` function from `@stdlib/assert/is-number` in order to avoid circular dependencies.
}
// EXPORTS //
module.exports = isNumber;
},{}],283:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2022 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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' ); // NOTE: we inline the `isString.isPrimitive` function from `@stdlib/assert/is-string` in order to avoid circular dependencies.
}
// EXPORTS //
module.exports = isString;
},{}],284:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2022 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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 formatInteger = require( './format_integer.js' );
var isString = require( './is_string.js' );
var formatDouble = require( './format_double.js' );
var spacePad = require( './space_pad.js' );
var zeroPad = require( './zero_pad.js' );
// VARIABLES //
var fromCharCode = String.fromCharCode;
var isnan = isNaN; // NOTE: We use the global `isNaN` function here instead of `@stdlib/math/base/assert/is-nan` to avoid circular dependencies.
var isArray = Array.isArray; // NOTE: We use the global `Array.isArray` function here instead of `@stdlib/assert/is-array` to avoid circular dependencies.
// FUNCTIONS //
/**
* Initializes token object with properties of supplied format identifier object or default values if not present.
*
* @private
* @param {Object} token - format identifier object
* @returns {Object} token object
*/
function initialize( token ) {
var out = {};
out.specifier = token.specifier;
out.precision = ( token.precision === void 0 ) ? 1 : token.precision;
out.width = token.width;
out.flags = token.flags || '';
out.mapping = token.mapping;
return out;
}
// MAIN //
/**
* Generates string from a token array by interpolating values.
*
* @param {Array} tokens - string parts and format identifier objects
* @param {Array} ...args - variable values
* @throws {TypeError} first argument must be an array
* @throws {Error} invalid flags
* @returns {string} formatted string
*
* @example
* var tokens = [ 'beep ', { 'specifier': 's' } ];
* var out = formatInterpolate( tokens, 'boop' );
* // returns 'beep boop'
*/
function formatInterpolate( tokens ) {
var hasPeriod;
var flags;
var token;
var flag;
var num;
var out;
var pos;
var i;
var j;
if ( !isArray( tokens ) ) {
throw new TypeError( 'invalid argument. First argument must be an array. Value: `' + tokens + '`.' );
}
out = '';
pos = 1;
for ( i = 0; i < tokens.length; i++ ) {
token = tokens[ i ];
if ( isString( token ) ) {
out += token;
} else {
hasPeriod = token.precision !== void 0;
token = initialize( token );
if ( !token.specifier ) {
throw new TypeError( 'invalid argument. Token is missing `specifier` property. Index: `'+ i +'`. Value: `' + token + '`.' );
}
if ( token.mapping ) {
pos = token.mapping;
}
flags = token.flags;
for ( j = 0; j < flags.length; j++ ) {
flag = flags.charAt( j );
switch ( flag ) {
case ' ':
token.sign = ' ';
break;
case '+':
token.sign = '+';
break;
case '-':
token.padRight = true;
token.padZeros = false;
break;
case '0':
token.padZeros = flags.indexOf( '-' ) < 0; // NOTE: We use built-in `Array.prototype.indexOf` here instead of `@stdlib/assert/contains` in order to avoid circular dependencies.
break;
case '#':
token.alternate = true;
break;
default:
throw new Error( 'invalid flag: ' + flag );
}
}
if ( token.width === '*' ) {
token.width = parseInt( arguments[ pos ], 10 );
pos += 1;
if ( isnan( token.width ) ) {
throw new TypeError( 'the argument for * width at position ' + pos + ' is not a number. Value: `' + token.width + '`.' );
}
if ( token.width < 0 ) {
token.padRight = true;
token.width = -token.width;
}
}
if ( hasPeriod ) {
if ( token.precision === '*' ) {
token.precision = parseInt( arguments[ pos ], 10 );
pos += 1;
if ( isnan( token.precision ) ) {
throw new TypeError( 'the argument for * precision at position ' + pos + ' is not a number. Value: `' + token.precision + '`.' );
}
if ( token.precision < 0 ) {
token.precision = 1;
hasPeriod = false;
}
}
}
token.arg = arguments[ pos ];
switch ( token.specifier ) {
case 'b':
case 'o':
case 'x':
case 'X':
case 'd':
case 'i':
case 'u':
// Case: %b (binary), %o (octal), %x, %X (hexadecimal), %d, %i (decimal), %u (unsigned decimal)
if ( hasPeriod ) {
token.padZeros = false;
}
token.arg = formatInteger( token );
break;
case 's':
// Case: %s (string)
token.maxWidth = ( hasPeriod ) ? token.precision : -1;
break;
case 'c':
// Case: %c (character)
if ( !isnan( token.arg ) ) {
num = parseInt( token.arg, 10 );
if ( num < 0 || num > 127 ) {
throw new Error( 'invalid character code. Value: ' + token.arg );
}
token.arg = ( isnan( num ) ) ?
String( token.arg ) :
fromCharCode( num );
}
break;
case 'e':
case 'E':
case 'f':
case 'F':
case 'g':
case 'G':
// Case: %e, %E (scientific notation), %f, %F (decimal floating point), %g, %G (uses the shorter of %e/E or %f/F)
if ( !hasPeriod ) {
token.precision = 6;
}
token.arg = formatDouble( token );
break;
default:
throw new Error( 'invalid specifier: ' + token.specifier );
}
// Fit argument into field width...
if ( token.maxWidth >= 0 && token.arg.length > token.maxWidth ) {
token.arg = token.arg.substring( 0, token.maxWidth );
}
if ( token.padZeros ) {
token.arg = zeroPad( token.arg, token.width || token.precision, token.padRight ); // eslint-disable-line max-len
} else if ( token.width ) {
token.arg = spacePad( token.arg, token.width, token.padRight );
}
out += token.arg || '';
pos += 1;
}
}
return out;
}
// EXPORTS //
module.exports = formatInterpolate;
},{"./format_double.js":279,"./format_integer.js":280,"./is_string.js":283,"./space_pad.js":285,"./zero_pad.js":286}],285:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2022 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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 //
/**
* Returns `n` spaces.
*
* @private
* @param {number} n - number of spaces
* @returns {string} string of spaces
*/
function spaces( n ) {
var out = '';
var i;
for ( i = 0; i < n; i++ ) {
out += ' ';
}
return out;
}
// MAIN //
/**
* Pads a token with spaces to the specified width.
*
* @private
* @param {string} str - token argument
* @param {number} width - token width
* @param {boolean} [right=false] - boolean indicating whether to pad to the right
* @returns {string} padded token argument
*/
function spacePad( str, width, right ) {
var pad = width - str.length;
if ( pad < 0 ) {
return str;
}
str = ( right ) ?
str + spaces( pad ) :
spaces( pad ) + str;
return str;
}
// EXPORTS //
module.exports = spacePad;
},{}],286:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2022 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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 //
/**
* Tests if a string starts with a minus sign (`-`).
*
* @private
* @param {string} str - input string
* @returns {boolean} boolean indicating if a string starts with a minus sign (`-`)
*/
function startsWithMinus( str ) {
return str[ 0 ] === '-';
}
/**
* Returns a string of `n` zeros.
*
* @private
* @param {number} n - number of zeros
* @returns {string} string of zeros
*/
function zeros( n ) {
var out = '';
var i;
for ( i = 0; i < n; i++ ) {
out += '0';
}
return out;
}
// MAIN //
/**
* Pads a token with zeros to the specified width.
*
* @private
* @param {string} str - token argument
* @param {number} width - token width
* @param {boolean} [right=false] - boolean indicating whether to pad to the right
* @returns {string} padded token argument
*/
function zeroPad( str, width, right ) {
var negative = false;
var pad = width - str.length;
if ( pad < 0 ) {
return str;
}
if ( startsWithMinus( str ) ) {
negative = true;
str = str.substr( 1 );
}
str = ( right ) ?
str + zeros( pad ) :
zeros( pad ) + str;
if ( negative ) {
str = '-' + str;
}
return str;
}
// EXPORTS //
module.exports = zeroPad;
},{}],287:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2022 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
/**
* Tokenize a string into an array of string parts and format identifier objects.
*
* @module @stdlib/string/base/format-tokenize
*
* @example
* var formatTokenize = require( '@stdlib/string/base/format-tokenize' );
*
* var str = 'Hello %s!';
* var tokens = formatTokenize( str );
* // returns [ 'Hello ', {...}, '!' ]
*/
// MODULES //
var formatTokenize = require( './main.js' );
// EXPORTS //
module.exports = formatTokenize;
},{"./main.js":288}],288:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2022 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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 RE = /%(?:([1-9]\d*)\$)?([0 +\-#]*)(\*|\d+)?(?:(\.)(\*|\d+)?)?[hlL]?([%A-Za-z])/g;
// FUNCTIONS //
/**
* Parses a delimiter.
*
* @private
* @param {Array} match - regular expression match
* @returns {Object} delimiter token object
*/
function parse( match ) {
var token = {
'mapping': ( match[ 1 ] ) ? parseInt( match[ 1 ], 10 ) : void 0,
'flags': match[ 2 ],
'width': match[ 3 ],
'precision': match[ 5 ],
'specifier': match[ 6 ]
};
if ( match[ 4 ] === '.' && match[ 5 ] === void 0 ) {
token.precision = '1';
}
return token;
}
// MAIN //
/**
* Tokenizes a string into an array of string parts and format identifier objects.
*
* @param {string} str - input string
* @returns {Array} tokens
*
* @example
* var tokens = formatTokenize( 'Hello %s!' );
* // returns [ 'Hello ', {...}, '!' ]
*/
function formatTokenize( str ) {
var content;
var tokens;
var match;
var prev;
tokens = [];
prev = 0;
match = RE.exec( str );
while ( match ) {
content = str.slice( prev, RE.lastIndex - match[ 0 ].length );
if ( content.length ) {
tokens.push( content );
}
tokens.push( parse( match ) );
prev = RE.lastIndex;
match = RE.exec( str );
}
content = str.slice( prev );
if ( content.length ) {
tokens.push( content );
}
return tokens;
}
// EXPORTS //
module.exports = formatTokenize;
},{}],289:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2022 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
/**
* Insert supplied variable values into a format string.
*
* @module @stdlib/string/format
*
* @example
* var format = require( '@stdlib/string/format' );
*
* var out = format( '%s %s!', 'Hello', 'World' );
* // returns 'Hello World!'
*
* out = format( 'Pi: ~%.2f', 3.141592653589793 );
* // returns 'Pi: ~3.14'
*/
// MODULES //
var format = require( './main.js' );
// EXPORTS //
module.exports = format;
},{"./main.js":291}],290:[function(require,module,exports){
arguments[4][283][0].apply(exports,arguments)
},{"dup":283}],291:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2022 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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 interpolate = require( '@stdlib/string/base/format-interpolate' );
var tokenize = require( '@stdlib/string/base/format-tokenize' );
var isString = require( './is_string.js' );
// MAIN //
/**
* Inserts supplied variable values into a format string.
*
* @param {string} str - input string
* @param {Array} ...args - variable values
* @throws {TypeError} first argument must be a string
* @throws {Error} invalid flags
* @returns {string} formatted string
*
* @example
* var str = format( 'Hello %s!', 'world' );
* // returns 'Hello world!'
*
* @example
* var str = format( 'Pi: ~%.2f', 3.141592653589793 );
* // returns 'Pi: ~3.14'
*/
function format( str ) {
var tokens;
var args;
var i;
if ( !isString( str ) ) {
throw new TypeError( format( 'invalid argument. First argument must be a string. Value: `%s`.', str ) );
}
tokens = tokenize( str );
args = new Array( arguments.length );
args[ 0 ] = tokens;
for ( i = 1; i < args.length; i++ ) {
args[ i ] = arguments[ i ];
}
return interpolate.apply( null, args );
}
// EXPORTS //
module.exports = format;
},{"./is_string.js":290,"@stdlib/string/base/format-interpolate":281,"@stdlib/string/base/format-tokenize":287}],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';
/**
* 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":293}],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';
// MODULES //
var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive;
var isCollection = require( '@stdlib/assert/is-collection' );
var format = require( '@stdlib/string/format' );
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 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( format( 'invalid argument. Must provide valid code points (i.e., nonnegative integers). Value: `%s`.', pt ) );
}
if ( pt > UNICODE_MAX ) {
throw new RangeError( format( 'invalid argument. Must provide a valid code point (cannot exceed max). Value: `%s`.', 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":238,"@stdlib/constants/unicode/max-bmp":237,"@stdlib/string/format":289}],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';
/**
* 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":295}],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';
// 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' );
var format = require( '@stdlib/string/format' );
// 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
* @throws {TypeError} second argument argument must be a string or regular expression
* @throws {TypeError} third argument must be a string 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( format( 'invalid argument. First argument must be a string. Value: `%s`.', str ) );
}
if ( isString( search ) ) {
search = rescape( search );
search = new RegExp( search, 'g' );
}
else if ( !isRegExp( search ) ) {
throw new TypeError( format( 'invalid argument. Second argument must be a string or regular expression. Value: `%s`.', search ) );
}
if ( !isString( newval ) && !isFunction( newval ) ) {
throw new TypeError( format( 'invalid argument. Third argument must be a string or replacement function. Value: `%s`.', newval ) );
}
return str.replace( search, newval );
}
// EXPORTS //
module.exports = replace;
},{"@stdlib/assert/is-function":93,"@stdlib/assert/is-regexp":145,"@stdlib/assert/is-string":150,"@stdlib/string/format":289,"@stdlib/utils/escape-regexp-string":319}],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';
/**
* 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":297}],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';
// MODULES //
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var replace = require( '@stdlib/string/replace' );
var format = require( '@stdlib/string/format' );
// 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( format( 'invalid argument. Must provide a string. Value: `%s`.', str ) );
}
return replace( str, RE, '$1' );
}
// EXPORTS //
module.exports = trim;
},{"@stdlib/assert/is-string":150,"@stdlib/string/format":289,"@stdlib/string/replace":294}],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 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":300,"@stdlib/assert/is-object":136,"@stdlib/math/base/special/modf":245,"@stdlib/math/base/special/round":248,"@stdlib/utils/global":329}],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';
// MODULES //
var isFunction = require( '@stdlib/assert/is-function' );
// MAIN //
var bool = isFunction( Date.now );
// EXPORTS //
module.exports = bool;
},{"@stdlib/assert/is-function":93}],300:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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":299,"./polyfill.js":301}],301:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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;
},{}],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';
/**
* 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":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.
*/
'use strict';
// MODULES //
var isNonNegativeIntegerArray = require( '@stdlib/assert/is-nonnegative-integer-array' ).primitives;
var format = require( '@stdlib/string/format' );
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( format( 'invalid argument. Must provide an array of nonnegative integers. Value: `%s`.', time ) );
}
if ( time.length !== 2 ) {
throw new RangeError( format( 'invalid argument. Input array must contain two elements. Value: `%s`.', time ) );
}
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/string/format":289,"@stdlib/time/tic":298}],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';
/**
* 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":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 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":264,"@stdlib/utils/native-class":357}],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 isArray = require( '@stdlib/assert/is-array' );
var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive;
var format = require( '@stdlib/string/format' );
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} second argument 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( format( 'invalid argument. Second argument must be a nonnegative integer. Value: `%s`.', 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":307,"@stdlib/assert/is-array":70,"@stdlib/assert/is-nonnegative-integer":118,"@stdlib/constants/float64/pinf":227,"@stdlib/string/format":289}],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 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":309,"@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":218,"@stdlib/utils/define-property":317,"@stdlib/utils/get-prototype-of":323,"@stdlib/utils/index-of":333,"@stdlib/utils/keys":350,"@stdlib/utils/property-descriptor":372,"@stdlib/utils/property-names":376,"@stdlib/utils/regexp-from-string":379,"@stdlib/utils/type-of":384}],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';
/**
* 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":306}],309:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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}],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';
/**
* 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":311}],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 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":317}],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';
/**
* 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":313}],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';
// 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":317}],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';
// 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;
},{}],315:[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;
},{}],316:[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":315}],317:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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":314,"./has_define_property_support.js":316,"./polyfill.js":318}],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.
*/
/* eslint-disable no-underscore-dangle, no-proto */
'use strict';
// MODULES //
var format = require( '@stdlib/string/format' );
// 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( format( 'invalid argument. First argument must be an object. Value: `%s`.', obj ) );
}
if ( typeof descriptor !== 'object' || descriptor === null || toStr.call( descriptor ) === '[object Array]' ) {
throw new TypeError( format( 'invalid argument. Property descriptor must be an object. Value: `%s`.', 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;
},{"@stdlib/string/format":289}],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';
/**
* 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":320}],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';
// MODULES //
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var format = require( '@stdlib/string/format' );
// 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
* @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( format( 'invalid argument. Must provide a regular expression string. Value: `%s`.', 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":150,"@stdlib/string/format":289}],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';
// 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":324,"./polyfill.js":325,"@stdlib/assert/is-function":93}],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';
// 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":321}],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';
/**
* 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":322}],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';
// MAIN //
var getProto = Object.getPrototypeOf;
// EXPORTS //
module.exports = getProto;
},{}],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';
// 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":326,"@stdlib/utils/native-class":357}],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';
/**
* 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;
},{}],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';
// 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;
},{}],328:[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 : {})
},{}],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';
/**
* 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":330}],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';
// MODULES //
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var format = require( '@stdlib/string/format' );
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( format( 'invalid argument. Must provide a boolean. Value: `%s`.', 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":327,"./global.js":328,"./self.js":331,"./window.js":332,"@stdlib/assert/is-boolean":72,"@stdlib/string/format":289}],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';
// MAIN //
var obj = ( typeof self === 'object' ) ? self : null;
// EXPORTS //
module.exports = obj;
},{}],332:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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;
},{}],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';
/**
* 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":334}],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 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;
var format = require( '@stdlib/string/format' );
// 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} third argument 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( format( 'invalid argument. First argument must be an array-like object. Value: `%s`.', arr ) );
}
len = arr.length;
if ( len === 0 ) {
return -1;
}
if ( arguments.length === 3 ) {
if ( !isInteger( fromIndex ) ) {
throw new TypeError( format( 'invalid argument. Third argument must be an integer. Value: `%s`.', 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":150,"@stdlib/string/format":289}],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';
// 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":338,"./polyfill.js":339}],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';
/**
* 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":337}],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 defineProperty = require( '@stdlib/utils/define-property' );
var format = require( '@stdlib/string/format' );
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( format( 'invalid argument. Second argument must have a prototype from which another object can inherit. Value: `%s`.', 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":335,"./validate.js":340,"@stdlib/string/format":289,"@stdlib/utils/define-property":317}],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';
// EXPORTS //
module.exports = Object.create;
},{}],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';
// 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;
},{}],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';
// MODULES //
var format = require( '@stdlib/string/format' );
// MAIN //
/**
* 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( format( 'invalid argument. A provided constructor must be either an object (except null) or a function. Value: `%s`.', value ) );
}
return null;
}
// EXPORTS //
module.exports = validate;
},{"@stdlib/string/format":289}],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';
// 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;
},{}],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 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":341,"@stdlib/assert/is-arguments":65}],343:[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"
]
},{}],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 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":341}],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';
// 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":343,"./is_constructor_prototype.js":351,"./window.js":356,"@stdlib/assert/has-own-property":46,"@stdlib/utils/index-of":333,"@stdlib/utils/type-of":384}],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';
// MAIN //
var bool = ( typeof Object.keys !== 'undefined' );
// EXPORTS //
module.exports = bool;
},{}],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 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":364}],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 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}],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 bool = ( typeof window !== 'undefined' );
// EXPORTS //
module.exports = bool;
},{}],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';
/**
* 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":353}],351:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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;
},{}],352:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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":345,"./has_window.js":349,"./is_constructor_prototype.js":351}],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';
// 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":341,"./builtin_wrapper.js":342,"./has_arguments_bug.js":344,"./has_builtin.js":346,"./polyfill.js":355}],354:[function(require,module,exports){
module.exports=[
"toString",
"toLocaleString",
"valueOf",
"hasOwnProperty",
"isPrototypeOf",
"propertyIsEnumerable",
"constructor"
]
},{}],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';
// 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":347,"./has_non_enumerable_properties_bug.js":348,"./is_constructor_prototype_wrapper.js":352,"./non_enumerable.json":354,"@stdlib/assert/has-own-property":46,"@stdlib/assert/is-arguments":65,"@stdlib/assert/is-object-like":134}],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';
// MAIN //
var w = ( typeof window === 'undefined' ) ? void 0 : window;
// EXPORTS //
module.exports = w;
},{}],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 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":358,"./polyfill.js":359,"@stdlib/assert/has-tostringtag-support":50}],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 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":360}],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';
// 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":360,"./tostringtag.js":361,"@stdlib/assert/has-own-property":46}],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 toStr = Object.prototype.toString;
// EXPORTS //
module.exports = toStr;
},{}],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';
// MAIN //
var toStrTag = ( typeof Symbol === 'function' ) ? Symbol.toStringTag : '';
// EXPORTS //
module.exports = toStrTag;
},{}],362:[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":363}],363:[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":399}],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';
/**
* 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":365}],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';
/**
* No operation.
*
* @example
* noop();
* // ...does nothing.
*/
function noop() {
// Empty function...
}
// EXPORTS //
module.exports = noop;
},{}],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';
/**
* 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":367}],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 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' );
var format = require( '@stdlib/string/format' );
// 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( format( 'invalid argument. First argument must be an object. Value: `%s`.', 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( format( 'invalid argument. Second argument must be either a string or an array of strings. Value: `%s`.', keys ) );
}
// EXPORTS //
module.exports = omit;
},{"@stdlib/assert/is-string":150,"@stdlib/assert/is-string-array":148,"@stdlib/string/format":289,"@stdlib/utils/index-of":333,"@stdlib/utils/keys":350}],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';
/**
* 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":369}],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 isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var isStringArray = require( '@stdlib/assert/is-string-array' ).primitives;
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var format = require( '@stdlib/string/format' );
// 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( format( 'invalid argument. First argument must be an object. Value: `%s`.', 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( format( 'invalid argument. Second argument must be either a string or an array of strings. Value: `%s`.', keys ) );
}
// EXPORTS //
module.exports = pick;
},{"@stdlib/assert/has-own-property":46,"@stdlib/assert/is-string":150,"@stdlib/assert/is-string-array":148,"@stdlib/string/format":289}],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';
// 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;
},{}],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';
// MAIN //
var bool = ( typeof Object.getOwnPropertyDescriptor !== 'undefined' );
// EXPORTS //
module.exports = bool;
},{}],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';
/**
* 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":370,"./has_builtin.js":371,"./polyfill.js":373}],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';
// 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}],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';
// 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;
},{}],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';
// MAIN //
var bool = ( typeof Object.getOwnPropertyNames !== 'undefined' );
// EXPORTS //
module.exports = bool;
},{}],376:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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":374,"./has_builtin.js":375,"./polyfill.js":377}],377:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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":350}],378:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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' );
var format = require( '@stdlib/string/format' );
// 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( format( 'invalid argument. Must provide a regular expression string. Value: `%s`.', 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":150,"@stdlib/regexp/regexp":267,"@stdlib/string/format":289}],379:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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":378}],380:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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":381,"./fixtures/re.js":382,"./fixtures/typedarray.js":383}],381:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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":329}],382:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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;
},{}],383:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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;
},{}],384:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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":380,"./polyfill.js":385,"./typeof.js":386}],385:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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":304}],386:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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":304}],387:[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('')
}
},{}],388:[function(require,module,exports){
},{}],389:[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":387,"buffer":389,"ieee754":395}],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.
'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);
}
}
},{}],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.
// 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 = require('buffer').Buffer.isBuffer;
function objectToString(o) {
return Object.prototype.toString.call(o);
}
},{"buffer":389}],392:[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';
}
},{}],393:[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":394,"_process":399}],394:[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":392}],395:[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
}
},{}],396:[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
}
}
}
},{}],397:[function(require,module,exports){
var toString = {}.toString;
module.exports = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';
};
},{}],398:[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":399}],399:[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; };
},{}],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.
// 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":402,"./_stream_writable":404,"core-util-is":391,"inherits":396,"process-nextick-args":398}],401:[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":403,"core-util-is":391,"inherits":396}],402:[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":400,"./internal/streams/BufferList":405,"./internal/streams/destroy":406,"./internal/streams/stream":407,"_process":399,"core-util-is":391,"events":390,"inherits":396,"isarray":397,"process-nextick-args":398,"safe-buffer":408,"string_decoder/":409,"util":388}],403:[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":400,"core-util-is":391,"inherits":396}],404:[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":400,"./internal/streams/destroy":406,"./internal/streams/stream":407,"_process":399,"core-util-is":391,"inherits":396,"process-nextick-args":398,"safe-buffer":408,"timers":411,"util-deprecate":412}],405:[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":408,"util":388}],406:[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":398}],407:[function(require,module,exports){
module.exports = require('events').EventEmitter;
},{"events":390}],408:[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":389}],409:[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":408}],410:[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":400,"./lib/_stream_passthrough.js":401,"./lib/_stream_readable.js":402,"./lib/_stream_transform.js":403,"./lib/_stream_writable.js":404}],411:[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":399,"timers":411}],412:[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 : {})
},{}]},{},[149]);
| hasSymbolSupport |
staticFsHandler.go | package main
import (
"os"
"time"
"github.com/pkg/errors"
"github.com/spf13/afero"
"github.com/tsingson/fastx/utils"
"github.com/valyala/fasthttp"
)
// StaticFsHandler
func StaticFsHandler(webRoot string) func(ctx *fasthttp.RequestCtx) {
fs := &fasthttp.FS{
// Path to directory to serve.
Root: webRoot, // "/var/www/static-site",
// Generate index pages if client requests directory contents.
GenerateIndexPages: false,
IndexNames: []string{"index.html"},
// Enable transparent compression to save network traffic.
Compress: true,
AcceptByteRange: true,
CacheDuration: 90 * time.Second,
}
// func New(fs *fasthttp.FS) func(ctx *fasthttp.RequestCtx, next func(error)) {
staticHandler := fs.NewRequestHandler()
return func(ctx *fasthttp.RequestCtx) {
//
var (
m, path string
afs afero.Fs
)
//
m = string(ctx.Method())
if m != "GET" && m != "HEAD" |
path = string(ctx.Path())
afs = afero.NewOsFs()
fileInfo, err := afs.Stat(utils.StrBuilder(fs.Root, path))
// if err != nil && os.IsNotExist(err) {
if err != nil {
ctx.Error("not Found", 500)
return
}
// An exist file
// fasthttp.FS handle it
if !fileInfo.IsDir() {
staticHandler(ctx)
return
}
staticHandler(ctx)
}
}
// fsHandler
func fsHandler(wwwroot string) fasthttp.RequestHandler {
fs := &fasthttp.FS{
// Path to directory to serve.
Root: wwwroot,
IndexNames: []string{"index.html"},
// Generate index pages if client requests directory contents.
GenerateIndexPages: false,
PathNotFound: pathNotFound,
// Enable transparent compression to save network traffic.
Compress: true,
AcceptByteRange: true,
CacheDuration: 90 * time.Second,
}
// Create request handler for serving static files.
return fs.NewRequestHandler()
}
// pathNotFound
func pathNotFound(ctx *fasthttp.RequestCtx) {
ctx.Error("", 500)
return
}
// filterPath
func filterPath(path string, index []string) error {
for _, v := range index {
_, err := os.Stat(path + v)
if err == nil {
return nil
}
}
return errors.New("Not found index page in directory: " + path)
}
// design and code by tsingson
| {
ctx.Error("not Allow Method", 500)
return
} |
AppFileWalker.d.ts | import { Filter } from "builder-util/out/fs";
import { Stats } from "fs-extra";
import { FileMatcher } from "../fileMatcher"; | export declare abstract class FileCopyHelper {
protected readonly matcher: FileMatcher;
readonly filter: Filter | null;
protected readonly packager: Packager;
readonly metadata: Map<string, Stats>;
protected constructor(matcher: FileMatcher, filter: Filter | null, packager: Packager);
protected handleFile(file: string, parent: string, fileStat: Stats): Promise<Stats | null> | null;
private handleSymlink;
} | import { Packager } from "../packager"; |
simple_generate.py | from generate import *
from datetime import datetime
def main():
''' e.g.
python ./generate.py --length=512
--nsamples=1
--prefix=[MASK]哈利站在窗边
--tokenizer_path cache/vocab_small.txt
--topk 40 --model_path model/model_epoch29
--save_samples --save_samples_path result/20210915_29_1135
--model_config model/model_epoch29/config.json --repetition_penalty 1.05 --temperature 1.1
'''
parser = argparse.ArgumentParser()
parser.add_argument('--key', default='intro', type=str, required=False, help='哪个模型')
parser.add_argument('--model_v', default='-1', type=str, required=False, help='第几个模型')
parser.add_argument('--device', default='0,1,2,3', type=str, required=False, help='生成设备')
parser.add_argument('--length', default=1024, type=int, required=False, help='生成长度')
parser.add_argument('--batch_size', default=1, type=int, required=False, help='生成的batch size')
parser.add_argument('--nsamples', default=1, type=int, required=False, help='生成几个样本')
parser.add_argument('--temperature', default=1.1, type=float, required=False, help='生成温度')
parser.add_argument('--topk', default=20, type=int, required=False, help='最高几选一')
parser.add_argument('--topp', default=0, type=float, required=False, help='最高积累概率')
parser.add_argument('--model_config', default='config/model_config_small.json', type=str, required=False,
help='模型参数')
parser.add_argument('--tokenizer_path', default='cache/vocab_small.txt', type=str, required=False, help='词表路径')
parser.add_argument('--model_path', default='model/final_model', type=str, required=False, help='模型路径')
parser.add_argument('--prefix', default='哈利站在窗边', type=str, required=False, help='生成文章的开头')
parser.add_argument('--no_wordpiece', action='store_true', help='不做word piece切词')
parser.add_argument('--segment', action='store_true', help='中文以词为单位')
parser.add_argument('--fast_pattern', action='store_true', help='采用更加快的方式生成文本')
parser.add_argument('--save_samples', default=True, help='保存产生的样本')
parser.add_argument('--save_samples_path', default='.', type=str, required=False, help="保存样本的路径")
parser.add_argument('--repetition_penalty', default=1.05, type=float, required=False)
args = parser.parse_args()
print('args:\n' + args.__repr__())
if args.model_v != '-1':
args.model_path = '{}/model_epoch{}'.format(args.model_path.split('/')[0], args.model_v)
else:
args.model_path = args.model_path
t = str(datetime.now()) | args.save_samples_path = 'result_{}/{}_v{}'.format(args.key, d, args.model_v)
Generate().run(args)
if __name__ == '__main__':
main() | d = ''.join('_'.join(''.join(t.split(":")[:-1]).split(' ')).split('-')) |
main.go | package main
import (
"fmt"
"log"
"net/http"
"strconv"
"github.com/Bimde/grpc-go-random/pb"
"github.com/gin-gonic/gin"
"google.golang.org/grpc"
)
func | () {
conn, err := grpc.Dial("gcd-service:3000", grpc.WithInsecure())
if err != nil {
log.Fatalf("Dial failed: %v", err)
}
gcdClient := pb.NewGCDServiceClient(conn)
r := gin.Default()
r.GET("/gcd/:a/:b", func(c *gin.Context) {
// Parse parameters
a, err := strconv.ParseUint(c.Param("a"), 10, 64)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid parameter A"})
return
}
b, err := strconv.ParseUint(c.Param("b"), 10, 64)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid parameter B"})
return
}
// Call GCD service
req := &pb.GCDRequest{A: a, B: b}
if res, err := gcdClient.Compute(c, req); err == nil {
c.JSON(http.StatusOK, gin.H{
"result": fmt.Sprint(res.Result),
})
} else {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
}
})
if err := r.Run(":3000"); err != nil {
log.Fatalf("Failed to run server: %v", err)
}
}
| main |
test_classical_names.py | from nose.tools import eq_
import inflect
def test_ancient_1():
p = inflect.engine()
# DEFAULT...
eq_(p.plural_noun("Sally"), "Sallys", msg="classical 'names' active")
eq_(p.plural_noun("Jones", 0), "Joneses", msg="classical 'names' active")
# "person" PLURALS ACTIVATED...
p.classical(names=True)
eq_(p.plural_noun("Sally"), "Sallys", msg="classical 'names' active") | # OTHER CLASSICALS NOT ACTIVATED...
eq_(p.plural_noun("wildebeest"), "wildebeests", msg="classical 'herd' not active")
eq_(p.plural_noun("formula"), "formulas", msg="classical 'ancient' active")
eq_(p.plural_noun("error", 0), "errors", msg="classical 'zero' not active")
eq_(p.plural_noun("brother"), "brothers", msg="classical 'all' not active")
eq_(p.plural_noun("person"), "people", msg="classical 'persons' not active") | eq_(p.plural_noun("Jones", 0), "Joneses", msg="classical 'names' active")
|
analysis.go | // Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This file is largely based on go/analysis/internal/checker/checker.go.
package source
import (
"context"
"fmt"
"go/token"
"go/types"
"log"
"reflect"
"sort"
"strings"
"sync"
"time"
"golang.org/x/sync/errgroup"
"golang.org/x/tools/go/analysis"
)
func analyze(ctx context.Context, v View, pkgs []Package, analyzers []*analysis.Analyzer) ([]*Action, error) {
if ctx.Err() != nil {
return nil, ctx.Err()
}
// Build nodes for initial packages.
var roots []*Action
for _, a := range analyzers {
for _, pkg := range pkgs {
root, err := pkg.GetActionGraph(ctx, a)
if err != nil {
return nil, err
}
root.isroot = true
root.view = v
roots = append(roots, root)
}
}
// Execute the graph in parallel.
if err := execAll(ctx, v.Session().Cache().FileSet(), roots); err != nil {
return nil, err
}
return roots, nil
}
// An action represents one unit of analysis work: the application of
// one analysis to one package. Actions form a DAG, both within a
// package (as different analyzers are applied, either in sequence or
// parallel), and across packages (as dependencies are analyzed).
type Action struct {
once sync.Once
Analyzer *analysis.Analyzer
Pkg Package
Deps []*Action
pass *analysis.Pass
isroot bool
objectFacts map[objectFactKey]analysis.Fact
packageFacts map[packageFactKey]analysis.Fact
inputs map[*analysis.Analyzer]interface{}
result interface{}
diagnostics []analysis.Diagnostic
err error
duration time.Duration
view View
}
type objectFactKey struct {
obj types.Object
typ reflect.Type
}
type packageFactKey struct {
pkg *types.Package
typ reflect.Type
}
func (act *Action) String() string {
return fmt.Sprintf("%s@%s", act.Analyzer, act.Pkg)
}
func execAll(ctx context.Context, fset *token.FileSet, actions []*Action) error {
g, ctx := errgroup.WithContext(ctx)
for _, act := range actions {
act := act
g.Go(func() error {
return act.exec(ctx, fset)
})
}
return g.Wait()
}
func (act *Action) exec(ctx context.Context, fset *token.FileSet) error {
var err error
act.once.Do(func() {
err = act.execOnce(ctx, fset)
})
return err
}
func (act *Action) execOnce(ctx context.Context, fset *token.FileSet) error {
// Analyze dependencies.
if err := execAll(ctx, fset, act.Deps); err != nil {
return err
}
// Report an error if any dependency failed.
var failed []string
for _, dep := range act.Deps {
if dep.err != nil {
failed = append(failed, dep.String())
}
}
if failed != nil |
// Plumb the output values of the dependencies
// into the inputs of this action. Also facts.
inputs := make(map[*analysis.Analyzer]interface{})
act.objectFacts = make(map[objectFactKey]analysis.Fact)
act.packageFacts = make(map[packageFactKey]analysis.Fact)
for _, dep := range act.Deps {
if dep.Pkg == act.Pkg {
// Same package, different analysis (horizontal edge):
// in-memory outputs of prerequisite analyzers
// become inputs to this analysis pass.
inputs[dep.Analyzer] = dep.result
} else if dep.Analyzer == act.Analyzer { // (always true)
// Same analysis, different package (vertical edge):
// serialized facts produced by prerequisite analysis
// become available to this analysis pass.
inheritFacts(act, dep)
}
}
// Run the analysis.
pass := &analysis.Pass{
Analyzer: act.Analyzer,
Fset: fset,
Files: act.Pkg.GetSyntax(),
Pkg: act.Pkg.GetTypes(),
TypesInfo: act.Pkg.GetTypesInfo(),
TypesSizes: act.Pkg.GetTypesSizes(),
ResultOf: inputs,
Report: func(d analysis.Diagnostic) { act.diagnostics = append(act.diagnostics, d) },
ImportObjectFact: act.importObjectFact,
ExportObjectFact: act.exportObjectFact,
ImportPackageFact: act.importPackageFact,
ExportPackageFact: act.exportPackageFact,
}
act.pass = pass
if len(act.Pkg.GetErrors()) > 0 && !pass.Analyzer.RunDespiteErrors {
act.err = fmt.Errorf("analysis skipped due to errors in package")
} else {
act.result, act.err = pass.Analyzer.Run(pass)
if act.err == nil {
if got, want := reflect.TypeOf(act.result), pass.Analyzer.ResultType; got != want {
act.err = fmt.Errorf(
"internal error: on package %s, analyzer %s returned a result of type %v, but declared ResultType %v",
pass.Pkg.Path(), pass.Analyzer, got, want)
}
}
}
// disallow calls after Run
pass.ExportObjectFact = nil
pass.ExportPackageFact = nil
return act.err
}
// inheritFacts populates act.facts with
// those it obtains from its dependency, dep.
func inheritFacts(act, dep *Action) {
for key, fact := range dep.objectFacts {
// Filter out facts related to objects
// that are irrelevant downstream
// (equivalently: not in the compiler export data).
if !exportedFrom(key.obj, dep.Pkg.GetTypes()) {
continue
}
act.objectFacts[key] = fact
}
for key, fact := range dep.packageFacts {
// TODO: filter out facts that belong to
// packages not mentioned in the export data
// to prevent side channels.
act.packageFacts[key] = fact
}
}
// exportedFrom reports whether obj may be visible to a package that imports pkg.
// This includes not just the exported members of pkg, but also unexported
// constants, types, fields, and methods, perhaps belonging to oether packages,
// that find there way into the API.
// This is an overapproximation of the more accurate approach used by
// gc export data, which walks the type graph, but it's much simpler.
//
// TODO(adonovan): do more accurate filtering by walking the type graph.
func exportedFrom(obj types.Object, pkg *types.Package) bool {
switch obj := obj.(type) {
case *types.Func:
return obj.Exported() && obj.Pkg() == pkg ||
obj.Type().(*types.Signature).Recv() != nil
case *types.Var:
return obj.Exported() && obj.Pkg() == pkg ||
obj.IsField()
case *types.TypeName, *types.Const:
return true
}
return false // Nil, Builtin, Label, or PkgName
}
// importObjectFact implements Pass.ImportObjectFact.
// Given a non-nil pointer ptr of type *T, where *T satisfies Fact,
// importObjectFact copies the fact value to *ptr.
func (act *Action) importObjectFact(obj types.Object, ptr analysis.Fact) bool {
if obj == nil {
panic("nil object")
}
key := objectFactKey{obj, factType(ptr)}
if v, ok := act.objectFacts[key]; ok {
reflect.ValueOf(ptr).Elem().Set(reflect.ValueOf(v).Elem())
return true
}
return false
}
// exportObjectFact implements Pass.ExportObjectFact.
func (act *Action) exportObjectFact(obj types.Object, fact analysis.Fact) {
if act.pass.ExportObjectFact == nil {
log.Panicf("%s: Pass.ExportObjectFact(%s, %T) called after Run", act, obj, fact)
}
if obj.Pkg() != act.Pkg.GetTypes() {
log.Panicf("internal error: in analysis %s of package %s: Fact.Set(%s, %T): can't set facts on objects belonging another package",
act.Analyzer, act.Pkg, obj, fact)
}
key := objectFactKey{obj, factType(fact)}
act.objectFacts[key] = fact // clobber any existing entry
}
// importPackageFact implements Pass.ImportPackageFact.
// Given a non-nil pointer ptr of type *T, where *T satisfies Fact,
// fact copies the fact value to *ptr.
func (act *Action) importPackageFact(pkg *types.Package, ptr analysis.Fact) bool {
if pkg == nil {
panic("nil package")
}
key := packageFactKey{pkg, factType(ptr)}
if v, ok := act.packageFacts[key]; ok {
reflect.ValueOf(ptr).Elem().Set(reflect.ValueOf(v).Elem())
return true
}
return false
}
// exportPackageFact implements Pass.ExportPackageFact.
func (act *Action) exportPackageFact(fact analysis.Fact) {
if act.pass.ExportPackageFact == nil {
log.Panicf("%s: Pass.ExportPackageFact(%T) called after Run", act, fact)
}
key := packageFactKey{act.pass.Pkg, factType(fact)}
act.packageFacts[key] = fact // clobber any existing entry
}
func factType(fact analysis.Fact) reflect.Type {
t := reflect.TypeOf(fact)
if t.Kind() != reflect.Ptr {
log.Fatalf("invalid Fact type: got %T, want pointer", t)
}
return t
}
| {
sort.Strings(failed)
act.err = fmt.Errorf("failed prerequisites: %s", strings.Join(failed, ", "))
return act.err
} |
validation.response.ts | import { NextFunction, Request, Response } from 'express';
import { validationResult } from 'express-validator';
class ValidationResponder {
constructor() {
}
static fieldValidationResponder() {
return (req: Request, res: Response, next: NextFunction) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).send(errors.array({ onlyFirstError: true })) | return next();
}
};
}
static unauthorizedValidationResponder() {
return (req: Request, res: Response, next: NextFunction) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(401).send(errors.array({ onlyFirstError: true }));
} else {
return next();
}
};
}
}
export { ValidationResponder }; | } else { |
multiplesigner.js | // Copyright 2014 Google Inc. All rights reserved
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd
/**
* @fileoverview A multiple gnubby signer wraps the process of opening a number
* of gnubbies, signing each challenge in an array of challenges until a
* success condition is satisfied, and yielding each succeeding gnubby.
*
*/
'use strict';
/**
* @typedef {{
* code: number,
* gnubbyId: GnubbyDeviceId,
* challenge: (SignHelperChallenge|undefined),
* info: (ArrayBuffer|undefined)
* }}
*/
var MultipleSignerResult;
/**
* Creates a new sign handler that manages signing with all the available
* gnubbies.
* @param {boolean} forEnroll Whether this signer is signing for an attempted
* enroll operation.
* @param {function(boolean)} allCompleteCb Called when this signer completes
* sign attempts, i.e. no further results will be produced. The parameter
* indicates whether any gnubbies are present that have not yet produced a
* final result.
* @param {function(MultipleSignerResult, boolean)} gnubbyCompleteCb
* Called with each gnubby/challenge that yields a final result, along with
* whether this signer expects to produce more results. The boolean is a
* hint rather than a promise: it's possible for this signer to produce
* further results after saying it doesn't expect more, or to fail to
* produce further results after saying it does.
* @param {number} timeoutMillis A timeout value, beyond whose expiration the
* signer will not attempt any new operations, assuming the caller is no
* longer interested in the outcome.
* @param {string=} opt_logMsgUrl A URL to post log messages to.
* @constructor
*/
function | (forEnroll, allCompleteCb, gnubbyCompleteCb,
timeoutMillis, opt_logMsgUrl) {
/** @private {boolean} */
this.forEnroll_ = forEnroll;
/** @private {function(boolean)} */
this.allCompleteCb_ = allCompleteCb;
/** @private {function(MultipleSignerResult, boolean)} */
this.gnubbyCompleteCb_ = gnubbyCompleteCb;
/** @private {string|undefined} */
this.logMsgUrl_ = opt_logMsgUrl;
/** @private {Array<SignHelperChallenge>} */
this.challenges_ = [];
/** @private {boolean} */
this.challengesSet_ = false;
/** @private {boolean} */
this.complete_ = false;
/** @private {number} */
this.numComplete_ = 0;
/** @private {!Object<string, GnubbyTracker>} */
this.gnubbies_ = {};
/** @private {Countdown} */
this.timer_ = DEVICE_FACTORY_REGISTRY.getCountdownFactory()
.createTimer(timeoutMillis);
/** @private {Countdown} */
this.reenumerateTimer_ = DEVICE_FACTORY_REGISTRY.getCountdownFactory()
.createTimer(timeoutMillis);
}
/**
* @typedef {{
* index: string,
* signer: SingleGnubbySigner,
* stillGoing: boolean,
* errorStatus: number
* }}
*/
var GnubbyTracker;
/**
* Closes this signer's gnubbies, if any are open.
*/
MultipleGnubbySigner.prototype.close = function() {
for (var k in this.gnubbies_) {
this.gnubbies_[k].signer.close();
}
this.reenumerateTimer_.clearTimeout();
this.timer_.clearTimeout();
if (this.reenumerateIntervalTimer_) {
this.reenumerateIntervalTimer_.clearTimeout();
}
};
/**
* Begins signing the given challenges.
* @param {Array<SignHelperChallenge>} challenges The challenges to sign.
* @return {boolean} whether the challenges were successfully added.
*/
MultipleGnubbySigner.prototype.doSign = function(challenges) {
if (this.challengesSet_) {
// Can't add new challenges once they're finalized.
return false;
}
if (challenges) {
for (var i = 0; i < challenges.length; i++) {
var decodedChallenge = {};
var challenge = challenges[i];
decodedChallenge['challengeHash'] =
B64_decode(challenge['challengeHash']);
decodedChallenge['appIdHash'] = B64_decode(challenge['appIdHash']);
decodedChallenge['keyHandle'] = B64_decode(challenge['keyHandle']);
if (challenge['version']) {
decodedChallenge['version'] = challenge['version'];
}
this.challenges_.push(decodedChallenge);
}
}
this.challengesSet_ = true;
this.enumerateGnubbies_();
return true;
};
/**
* Signals this signer to rescan for gnubbies. Useful when the caller has
* knowledge that the last device has been removed, and can notify this class
* before it will discover it on its own.
*/
MultipleGnubbySigner.prototype.reScanDevices = function() {
if (this.reenumerateIntervalTimer_) {
this.reenumerateIntervalTimer_.clearTimeout();
}
this.maybeReEnumerateGnubbies_(true);
};
/**
* Enumerates gnubbies.
* @private
*/
MultipleGnubbySigner.prototype.enumerateGnubbies_ = function() {
DEVICE_FACTORY_REGISTRY.getGnubbyFactory().enumerate(
this.enumerateCallback_.bind(this));
};
/**
* Called with the result of enumerating gnubbies.
* @param {number} rc The return code from enumerating.
* @param {Array<GnubbyDeviceId>} ids The gnubbies enumerated.
* @private
*/
MultipleGnubbySigner.prototype.enumerateCallback_ = function(rc, ids) {
if (this.complete_) {
return;
}
if (rc || !ids || !ids.length) {
this.maybeReEnumerateGnubbies_(true);
return;
}
for (var i = 0; i < ids.length; i++) {
this.addGnubby_(ids[i]);
}
this.maybeReEnumerateGnubbies_(false);
};
/**
* How frequently to reenumerate gnubbies when none are found, in milliseconds.
* @const
*/
MultipleGnubbySigner.ACTIVE_REENUMERATE_INTERVAL_MILLIS = 200;
/**
* How frequently to reenumerate gnubbies when some are found, in milliseconds.
* @const
*/
MultipleGnubbySigner.PASSIVE_REENUMERATE_INTERVAL_MILLIS = 3000;
/**
* Reenumerates gnubbies if there's still time.
* @param {boolean} activeScan Whether to poll more aggressively, e.g. if
* there are no devices present.
* @private
*/
MultipleGnubbySigner.prototype.maybeReEnumerateGnubbies_ =
function(activeScan) {
if (this.reenumerateTimer_.expired()) {
// If the timer is expired, call timeout_ if there aren't any still-running
// gnubbies. (If there are some still running, the last will call timeout_
// itself.)
if (!this.anyPending_()) {
this.timeout_(false);
}
return;
}
// Reenumerate more aggressively if there are no gnubbies present than if
// there are any.
var reenumerateTimeoutMillis;
if (activeScan) {
reenumerateTimeoutMillis =
MultipleGnubbySigner.ACTIVE_REENUMERATE_INTERVAL_MILLIS;
} else {
reenumerateTimeoutMillis =
MultipleGnubbySigner.PASSIVE_REENUMERATE_INTERVAL_MILLIS;
}
if (reenumerateTimeoutMillis >
this.reenumerateTimer_.millisecondsUntilExpired()) {
reenumerateTimeoutMillis =
this.reenumerateTimer_.millisecondsUntilExpired();
}
/** @private {Countdown} */
this.reenumerateIntervalTimer_ =
DEVICE_FACTORY_REGISTRY.getCountdownFactory().createTimer(
reenumerateTimeoutMillis, this.enumerateGnubbies_.bind(this));
};
/**
* Adds a new gnubby to this signer's list of gnubbies. (Only possible while
* this signer is still signing: without this restriction, the completed
* callback could be called more than once, in violation of its contract.)
* If this signer has challenges to sign, begins signing on the new gnubby with
* them.
* @param {GnubbyDeviceId} gnubbyId The id of the gnubby to add.
* @return {boolean} Whether the gnubby was added successfully.
* @private
*/
MultipleGnubbySigner.prototype.addGnubby_ = function(gnubbyId) {
var index = JSON.stringify(gnubbyId);
if (this.gnubbies_.hasOwnProperty(index)) {
// Can't add the same gnubby twice.
return false;
}
var tracker = {
index: index,
errorStatus: 0,
stillGoing: false,
signer: null
};
tracker.signer = new SingleGnubbySigner(
gnubbyId,
this.forEnroll_,
this.signCompletedCallback_.bind(this, tracker),
this.timer_.clone(),
this.logMsgUrl_);
this.gnubbies_[index] = tracker;
this.gnubbies_[index].stillGoing =
tracker.signer.doSign(this.challenges_);
if (!this.gnubbies_[index].errorStatus) {
this.gnubbies_[index].errorStatus = 0;
}
return true;
};
/**
* Called by a SingleGnubbySigner upon completion.
* @param {GnubbyTracker} tracker The tracker object of the gnubby whose result
* this is.
* @param {SingleSignerResult} result The result of the sign operation.
* @private
*/
MultipleGnubbySigner.prototype.signCompletedCallback_ =
function(tracker, result) {
console.log(
UTIL_fmt((result.code ? 'failure.' : 'success!') +
' gnubby ' + tracker.index +
' got code ' + result.code.toString(16)));
if (!tracker.stillGoing) {
console.log(UTIL_fmt('gnubby ' + tracker.index + ' no longer running!'));
// Shouldn't ever happen? Disregard.
return;
}
tracker.stillGoing = false;
tracker.errorStatus = result.code;
var moreExpected = this.tallyCompletedGnubby_();
switch (result.code) {
case DeviceStatusCodes.GONE_STATUS:
// Squelch removed gnubbies: the caller can't act on them. But if this
// was the last one, speed up reenumerating.
if (!moreExpected) {
this.maybeReEnumerateGnubbies_(true);
}
break;
default:
// Report any other results directly to the caller.
this.notifyGnubbyComplete_(tracker, result, moreExpected);
break;
}
if (!moreExpected && this.timer_.expired()) {
this.timeout_(false);
}
};
/**
* Counts another gnubby has having completed, and returns whether more results
* are expected.
* @return {boolean} Whether more gnubbies are still running.
* @private
*/
MultipleGnubbySigner.prototype.tallyCompletedGnubby_ = function() {
this.numComplete_++;
return this.anyPending_();
};
/**
* @return {boolean} Whether more gnubbies are still running.
* @private
*/
MultipleGnubbySigner.prototype.anyPending_ = function() {
return this.numComplete_ < Object.keys(this.gnubbies_).length;
};
/**
* Called upon timeout.
* @param {boolean} anyPending Whether any gnubbies are awaiting results.
* @private
*/
MultipleGnubbySigner.prototype.timeout_ = function(anyPending) {
if (this.complete_) return;
this.complete_ = true;
// Defer notifying the caller that all are complete, in case the caller is
// doing work in response to a gnubbyFound callback and has an inconsistent
// view of the state of this signer.
var self = this;
window.setTimeout(function() {
self.allCompleteCb_(anyPending);
}, 0);
};
/**
* @param {GnubbyTracker} tracker The tracker object of the gnubby whose result
* this is.
* @param {SingleSignerResult} result Result object.
* @param {boolean} moreExpected Whether more gnubbies may still produce an
* outcome.
* @private
*/
MultipleGnubbySigner.prototype.notifyGnubbyComplete_ =
function(tracker, result, moreExpected) {
console.log(UTIL_fmt('gnubby ' + tracker.index + ' complete (' +
result.code.toString(16) + ')'));
var signResult = {
'code': result.code,
'gnubby': result.gnubby,
'gnubbyId': tracker.signer.getDeviceId()
};
if (result['challenge'])
signResult['challenge'] = result['challenge'];
if (result['info'])
signResult['info'] = result['info'];
this.gnubbyCompleteCb_(signResult, moreExpected);
};
| MultipleGnubbySigner |
builtins.rs | use {
solana_runtime::{
bank::{Builtin, Builtins},
builtins::ActivationType,
},
safecoin_sdk::{feature_set, pubkey::Pubkey},
};
macro_rules! to_builtin {
($b:expr) => {
Builtin::new(&$b.0, $b.1, $b.2)
};
}
/// Builtin programs that are always available
fn genesis_builtins(bpf_jit: bool) -> Vec<Builtin> {
// Currently JIT is not supported on the BPF VM:
// !x86_64: https://github.com/qmonnet/rbpf/issues/48
// Windows: https://github.com/solana-labs/rbpf/issues/217
#[cfg(any(not(target_arch = "x86_64"), target_family = "windows"))]
let bpf_jit = {
if bpf_jit {
info!("BPF JIT is not supported on this target"); | }
false
};
vec![
to_builtin!(solana_bpf_loader_deprecated_program!()),
if bpf_jit {
to_builtin!(solana_bpf_loader_program_with_jit!())
} else {
to_builtin!(solana_bpf_loader_program!())
},
]
}
/// Builtin programs activated dynamically by feature
fn feature_builtins(bpf_jit: bool) -> Vec<(Builtin, Pubkey, ActivationType)> {
vec![(
if bpf_jit {
to_builtin!(solana_bpf_loader_upgradeable_program_with_jit!())
} else {
to_builtin!(solana_bpf_loader_upgradeable_program!())
},
feature_set::bpf_loader_upgradeable_program::id(),
ActivationType::NewProgram,
)]
}
pub(crate) fn get(bpf_jit: bool) -> Builtins {
Builtins {
genesis_builtins: genesis_builtins(bpf_jit),
feature_builtins: feature_builtins(bpf_jit),
}
} | |
raw-results-table.tsx | import * as React from "react";
import { renderLocation, ResultTableProps, zebraStripe, className, nextSortDirection } from "./result-table-utils";
import { RawTableResultSet, vscode } from "./results";
import { ResultValue } from "../adapt";
import { SortDirection, RAW_RESULTS_LIMIT, RawResultsSortState } from "../interface-types";
export type RawTableProps = ResultTableProps & {
resultSet: RawTableResultSet;
sortState?: RawResultsSortState;
};
export class RawTable extends React.Component<RawTableProps, {}> {
constructor(props: RawTableProps) {
super(props);
}
render(): React.ReactNode {
const { resultSet, databaseUri } = this.props;
let dataRows = this.props.resultSet.rows;
let numTruncatedResults = 0;
if (dataRows.length > RAW_RESULTS_LIMIT) {
numTruncatedResults = dataRows.length - RAW_RESULTS_LIMIT;
dataRows = dataRows.slice(0, RAW_RESULTS_LIMIT);
}
const tableRows = dataRows.map((row, rowIndex) =>
<tr key={rowIndex} {...zebraStripe(rowIndex)}>
{
[
<td key={-1}>{rowIndex + 1}</td>,
...row.map((value, columnIndex) =>
<td key={columnIndex}>
{
renderTupleValue(value, databaseUri)
}
</td>)
]
}
</tr>
);
if (numTruncatedResults > 0) {
const colSpan = dataRows[0].length + 1; // one row for each data column, plus index column
tableRows.push(<tr><td key={'message'} colSpan={colSpan} style={{ textAlign: 'center', fontStyle: 'italic' }}>
Too many results to show at once. {numTruncatedResults} result(s) omitted.
</td></tr>);
} | <tr>
{
[
<th key={-1}><b>#</b></th>,
...resultSet.schema.columns.map((col, index) => {
const displayName = col.name || `[${index}]`;
const sortDirection = this.props.sortState && index === this.props.sortState.columnIndex ? this.props.sortState.sortDirection : undefined;
return <th className={"sort-" + (sortDirection !== undefined ? SortDirection[sortDirection] : "none")} key={index} onClick={() => this.toggleSortStateForColumn(index)}><b>{displayName}</b></th>;
})
]
}
</tr>
</thead>
<tbody>
{tableRows}
</tbody>
</table>;
}
private toggleSortStateForColumn(index: number): void {
const sortState = this.props.sortState;
const prevDirection = sortState && sortState.columnIndex === index ? sortState.sortDirection : undefined;
const nextDirection = nextSortDirection(prevDirection);
const nextSortState = nextDirection === undefined ? undefined : {
columnIndex: index,
sortDirection: nextDirection
};
vscode.postMessage({
t: 'changeSort',
resultSetName: this.props.resultSet.schema.name,
sortState: nextSortState
});
}
}
/**
* Render one column of a tuple.
*/
function renderTupleValue(v: ResultValue, databaseUri: string): JSX.Element {
if (typeof v === 'string') {
return <span>{v}</span>;
}
else if ('uri' in v) {
return <a href={v.uri}>{v.uri}</a>;
}
else {
return renderLocation(v.location, v.label, databaseUri);
}
} |
return <table className={className}>
<thead> |
ExportsApi.ts | import {BaseAPI} from '../../common/BaseAPI';
import Configuration from '../../common/Configuration';
import {map, mapArray} from '../../common/Mapper';
import AnalyticsExportTask from '../../models/AnalyticsExportTask';
import PaginationResponse from '../../models/PaginationResponse';
import {AnalyticsExportTaskListQueryParams, AnalyticsExportTaskListQueryParamsBuilder} from './AnalyticsExportTaskListQueryParams';
/**
* ExportsApi - object-oriented interface
* @export
* @class ExportsApi
* @extends {BaseAPI}
*/
export default class ExportsApi extends BaseAPI {
constructor(configuration: Configuration) {
super(configuration);
}
/**
* @summary Create Export Task
* @param {AnalyticsExportTask} analyticsExportTask The export task to be created
* @throws {BitmovinError}
* @memberof ExportsApi
*/
public create(analyticsExportTask?: AnalyticsExportTask): Promise<AnalyticsExportTask> {
return this.restClient.post<AnalyticsExportTask>('/analytics/exports', {}, analyticsExportTask).then((response) => {
return map(response, AnalyticsExportTask); | }
/**
* @summary Get export task
* @param {string} exportTaskId Export task id
* @throws {BitmovinError}
* @memberof ExportsApi
*/
public get(exportTaskId: string): Promise<AnalyticsExportTask> {
const pathParamMap = {
export_task_id: exportTaskId
};
return this.restClient.get<AnalyticsExportTask>('/analytics/exports/{export_task_id}', pathParamMap).then((response) => {
return map(response, AnalyticsExportTask);
});
}
/**
* @summary List Export Tasks
* @param {*} [queryParameters] query parameters for filtering, sorting and pagination
* @throws {BitmovinError}
* @memberof ExportsApi
*/
public list(queryParameters?: AnalyticsExportTaskListQueryParams | ((q: AnalyticsExportTaskListQueryParamsBuilder) => AnalyticsExportTaskListQueryParamsBuilder)): Promise<PaginationResponse<AnalyticsExportTask>> {
let queryParams: AnalyticsExportTaskListQueryParams = {};
if (typeof queryParameters === 'function') {
queryParams = queryParameters(new AnalyticsExportTaskListQueryParamsBuilder()).buildQueryParams();
} else if (queryParameters) {
queryParams = queryParameters;
}
return this.restClient.get<PaginationResponse<AnalyticsExportTask>>('/analytics/exports', {}, queryParams).then((response) => {
return new PaginationResponse<AnalyticsExportTask>(response, AnalyticsExportTask);
});
}
} | }); |
future.rs | //! Asynchronous values.
use core::cell::Cell;
use core::marker::Unpin;
use core::ops::{Drop, Generator, GeneratorState};
use core::option::Option;
use core::pin::Pin;
use core::ptr::NonNull;
use core::task::{Context, Poll};
#[doc(inline)]
#[stable(feature = "futures_api", since = "1.36.0")]
pub use core::future::*;
/// Wrap a generator in a future.
///
/// This function returns a `GenFuture` underneath, but hides it in `impl Trait` to give
/// better error messages (`impl Future` rather than `GenFuture<[closure.....]>`).
#[doc(hidden)]
#[unstable(feature = "gen_future", issue = "50547")]
pub fn from_generator<T: Generator<Yield = ()>>(x: T) -> impl Future<Output = T::Return> {
GenFuture(x)
}
/// A wrapper around generators used to implement `Future` for `async`/`await` code.
#[doc(hidden)]
#[unstable(feature = "gen_future", issue = "50547")]
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
struct GenFuture<T: Generator<Yield = ()>>(T);
// We rely on the fact that async/await futures are immovable in order to create
// self-referential borrows in the underlying generator.
impl<T: Generator<Yield = ()>> !Unpin for GenFuture<T> {}
#[doc(hidden)]
#[unstable(feature = "gen_future", issue = "50547")]
impl<T: Generator<Yield = ()>> Future for GenFuture<T> {
type Output = T::Return;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
// Safe because we're !Unpin + !Drop mapping to a ?Unpin value
let gen = unsafe { Pin::map_unchecked_mut(self, |s| &mut s.0) };
let _guard = unsafe { set_task_context(cx) };
match gen.resume(
#[cfg(not(bootstrap))]
(),
) {
GeneratorState::Yielded(()) => Poll::Pending,
GeneratorState::Complete(x) => Poll::Ready(x),
}
}
}
thread_local! {
static TLS_CX: Cell<Option<NonNull<Context<'static>>>> = Cell::new(None);
}
struct SetOnDrop(Option<NonNull<Context<'static>>>);
impl Drop for SetOnDrop {
fn drop(&mut self) {
TLS_CX.with(|tls_cx| {
tls_cx.set(self.0.take());
});
}
}
// Safety: the returned guard must drop before `cx` is dropped and before
// any previous guard is dropped.
unsafe fn set_task_context(cx: &mut Context<'_>) -> SetOnDrop {
// transmute the context's lifetime to 'static so we can store it.
let cx = core::mem::transmute::<&mut Context<'_>, &mut Context<'static>>(cx);
let old_cx = TLS_CX.with(|tls_cx| tls_cx.replace(Some(NonNull::from(cx))));
SetOnDrop(old_cx)
}
#[doc(hidden)]
#[unstable(feature = "gen_future", issue = "50547")]
/// Polls a future in the current thread-local task waker.
pub fn | <F>(f: Pin<&mut F>) -> Poll<F::Output>
where
F: Future,
{
let cx_ptr = TLS_CX.with(|tls_cx| {
// Clear the entry so that nested `get_task_waker` calls
// will fail or set their own value.
tls_cx.replace(None)
});
let _reset = SetOnDrop(cx_ptr);
let mut cx_ptr = cx_ptr.expect(
"TLS Context not set. This is a rustc bug. \
Please file an issue on https://github.com/rust-lang/rust.",
);
// Safety: we've ensured exclusive access to the context by
// removing the pointer from TLS, only to be replaced once
// we're done with it.
//
// The pointer that was inserted came from an `&mut Context<'_>`,
// so it is safe to treat as mutable.
unsafe { F::poll(f, cx_ptr.as_mut()) }
}
| poll_with_tls_context |
diagnosticInformationMap.generated.ts | // <auto-generated />
/// <reference path="types.ts" />
/* @internal */
namespace ts {
export var Diagnostics = {
Unterminated_string_literal: { code: 1002, category: DiagnosticCategory.Error, key: "Unterminated string literal." },
Identifier_expected: { code: 1003, category: DiagnosticCategory.Error, key: "Identifier expected." },
_0_expected: { code: 1005, category: DiagnosticCategory.Error, key: "'{0}' expected." },
A_file_cannot_have_a_reference_to_itself: { code: 1006, category: DiagnosticCategory.Error, key: "A file cannot have a reference to itself." },
Trailing_comma_not_allowed: { code: 1009, category: DiagnosticCategory.Error, key: "Trailing comma not allowed." },
Asterisk_Slash_expected: { code: 1010, category: DiagnosticCategory.Error, key: "'*/' expected." },
Unexpected_token: { code: 1012, category: DiagnosticCategory.Error, key: "Unexpected token." },
A_rest_parameter_must_be_last_in_a_parameter_list: { code: 1014, category: DiagnosticCategory.Error, key: "A rest parameter must be last in a parameter list." },
Parameter_cannot_have_question_mark_and_initializer: { code: 1015, category: DiagnosticCategory.Error, key: "Parameter cannot have question mark and initializer." },
A_required_parameter_cannot_follow_an_optional_parameter: { code: 1016, category: DiagnosticCategory.Error, key: "A required parameter cannot follow an optional parameter." },
An_index_signature_cannot_have_a_rest_parameter: { code: 1017, category: DiagnosticCategory.Error, key: "An index signature cannot have a rest parameter." },
An_index_signature_parameter_cannot_have_an_accessibility_modifier: { code: 1018, category: DiagnosticCategory.Error, key: "An index signature parameter cannot have an accessibility modifier." },
An_index_signature_parameter_cannot_have_a_question_mark: { code: 1019, category: DiagnosticCategory.Error, key: "An index signature parameter cannot have a question mark." },
An_index_signature_parameter_cannot_have_an_initializer: { code: 1020, category: DiagnosticCategory.Error, key: "An index signature parameter cannot have an initializer." },
An_index_signature_must_have_a_type_annotation: { code: 1021, category: DiagnosticCategory.Error, key: "An index signature must have a type annotation." },
An_index_signature_parameter_must_have_a_type_annotation: { code: 1022, category: DiagnosticCategory.Error, key: "An index signature parameter must have a type annotation." },
An_index_signature_parameter_type_must_be_string_or_number: { code: 1023, category: DiagnosticCategory.Error, key: "An index signature parameter type must be 'string' or 'number'." },
Accessibility_modifier_already_seen: { code: 1028, category: DiagnosticCategory.Error, key: "Accessibility modifier already seen." },
_0_modifier_must_precede_1_modifier: { code: 1029, category: DiagnosticCategory.Error, key: "'{0}' modifier must precede '{1}' modifier." },
_0_modifier_already_seen: { code: 1030, category: DiagnosticCategory.Error, key: "'{0}' modifier already seen." },
_0_modifier_cannot_appear_on_a_class_element: { code: 1031, category: DiagnosticCategory.Error, key: "'{0}' modifier cannot appear on a class element." },
super_must_be_followed_by_an_argument_list_or_member_access: { code: 1034, category: DiagnosticCategory.Error, key: "'super' must be followed by an argument list or member access." },
Only_ambient_modules_can_use_quoted_names: { code: 1035, category: DiagnosticCategory.Error, key: "Only ambient modules can use quoted names." },
Statements_are_not_allowed_in_ambient_contexts: { code: 1036, category: DiagnosticCategory.Error, key: "Statements are not allowed in ambient contexts." },
A_declare_modifier_cannot_be_used_in_an_already_ambient_context: { code: 1038, category: DiagnosticCategory.Error, key: "A 'declare' modifier cannot be used in an already ambient context." },
Initializers_are_not_allowed_in_ambient_contexts: { code: 1039, category: DiagnosticCategory.Error, key: "Initializers are not allowed in ambient contexts." },
_0_modifier_cannot_be_used_in_an_ambient_context: { code: 1040, category: DiagnosticCategory.Error, key: "'{0}' modifier cannot be used in an ambient context." },
_0_modifier_cannot_be_used_with_a_class_declaration: { code: 1041, category: DiagnosticCategory.Error, key: "'{0}' modifier cannot be used with a class declaration." },
_0_modifier_cannot_be_used_here: { code: 1042, category: DiagnosticCategory.Error, key: "'{0}' modifier cannot be used here." },
_0_modifier_cannot_appear_on_a_data_property: { code: 1043, category: DiagnosticCategory.Error, key: "'{0}' modifier cannot appear on a data property." },
_0_modifier_cannot_appear_on_a_module_element: { code: 1044, category: DiagnosticCategory.Error, key: "'{0}' modifier cannot appear on a module element." },
A_0_modifier_cannot_be_used_with_an_interface_declaration: { code: 1045, category: DiagnosticCategory.Error, key: "A '{0}' modifier cannot be used with an interface declaration." },
A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file: { code: 1046, category: DiagnosticCategory.Error, key: "A 'declare' modifier is required for a top level declaration in a .d.ts file." },
A_rest_parameter_cannot_be_optional: { code: 1047, category: DiagnosticCategory.Error, key: "A rest parameter cannot be optional." },
A_rest_parameter_cannot_have_an_initializer: { code: 1048, category: DiagnosticCategory.Error, key: "A rest parameter cannot have an initializer." },
A_set_accessor_must_have_exactly_one_parameter: { code: 1049, category: DiagnosticCategory.Error, key: "A 'set' accessor must have exactly one parameter." },
A_set_accessor_cannot_have_an_optional_parameter: { code: 1051, category: DiagnosticCategory.Error, key: "A 'set' accessor cannot have an optional parameter." },
A_set_accessor_parameter_cannot_have_an_initializer: { code: 1052, category: DiagnosticCategory.Error, key: "A 'set' accessor parameter cannot have an initializer." },
A_set_accessor_cannot_have_rest_parameter: { code: 1053, category: DiagnosticCategory.Error, key: "A 'set' accessor cannot have rest parameter." },
A_get_accessor_cannot_have_parameters: { code: 1054, category: DiagnosticCategory.Error, key: "A 'get' accessor cannot have parameters." },
Type_0_is_not_a_valid_async_function_return_type: { code: 1055, category: DiagnosticCategory.Error, key: "Type '{0}' is not a valid async function return type." },
Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: { code: 1056, category: DiagnosticCategory.Error, key: "Accessors are only available when targeting ECMAScript 5 and higher." },
An_async_function_or_method_must_have_a_valid_awaitable_return_type: { code: 1057, category: DiagnosticCategory.Error, key: "An async function or method must have a valid awaitable return type." },
Operand_for_await_does_not_have_a_valid_callable_then_member: { code: 1058, category: DiagnosticCategory.Error, key: "Operand for 'await' does not have a valid callable 'then' member." },
Return_expression_in_async_function_does_not_have_a_valid_callable_then_member: { code: 1059, category: DiagnosticCategory.Error, key: "Return expression in async function does not have a valid callable 'then' member." },
Expression_body_for_async_arrow_function_does_not_have_a_valid_callable_then_member: { code: 1060, category: DiagnosticCategory.Error, key: "Expression body for async arrow function does not have a valid callable 'then' member." },
Enum_member_must_have_initializer: { code: 1061, category: DiagnosticCategory.Error, key: "Enum member must have initializer." },
_0_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: { code: 1062, category: DiagnosticCategory.Error, key: "{0} is referenced directly or indirectly in the fulfillment callback of its own 'then' method." },
An_export_assignment_cannot_be_used_in_a_namespace: { code: 1063, category: DiagnosticCategory.Error, key: "An export assignment cannot be used in a namespace." },
Ambient_enum_elements_can_only_have_integer_literal_initializers: { code: 1066, category: DiagnosticCategory.Error, key: "Ambient enum elements can only have integer literal initializers." },
Unexpected_token_A_constructor_method_accessor_or_property_was_expected: { code: 1068, category: DiagnosticCategory.Error, key: "Unexpected token. A constructor, method, accessor, or property was expected." },
A_0_modifier_cannot_be_used_with_an_import_declaration: { code: 1079, category: DiagnosticCategory.Error, key: "A '{0}' modifier cannot be used with an import declaration." },
Invalid_reference_directive_syntax: { code: 1084, category: DiagnosticCategory.Error, key: "Invalid 'reference' directive syntax." },
Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher: { code: 1085, category: DiagnosticCategory.Error, key: "Octal literals are not available when targeting ECMAScript 5 and higher." },
An_accessor_cannot_be_declared_in_an_ambient_context: { code: 1086, category: DiagnosticCategory.Error, key: "An accessor cannot be declared in an ambient context." },
_0_modifier_cannot_appear_on_a_constructor_declaration: { code: 1089, category: DiagnosticCategory.Error, key: "'{0}' modifier cannot appear on a constructor declaration." },
_0_modifier_cannot_appear_on_a_parameter: { code: 1090, category: DiagnosticCategory.Error, key: "'{0}' modifier cannot appear on a parameter." },
Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: { code: 1091, category: DiagnosticCategory.Error, key: "Only a single variable declaration is allowed in a 'for...in' statement." },
Type_parameters_cannot_appear_on_a_constructor_declaration: { code: 1092, category: DiagnosticCategory.Error, key: "Type parameters cannot appear on a constructor declaration." },
Type_annotation_cannot_appear_on_a_constructor_declaration: { code: 1093, category: DiagnosticCategory.Error, key: "Type annotation cannot appear on a constructor declaration." },
An_accessor_cannot_have_type_parameters: { code: 1094, category: DiagnosticCategory.Error, key: "An accessor cannot have type parameters." },
A_set_accessor_cannot_have_a_return_type_annotation: { code: 1095, category: DiagnosticCategory.Error, key: "A 'set' accessor cannot have a return type annotation." },
An_index_signature_must_have_exactly_one_parameter: { code: 1096, category: DiagnosticCategory.Error, key: "An index signature must have exactly one parameter." },
_0_list_cannot_be_empty: { code: 1097, category: DiagnosticCategory.Error, key: "'{0}' list cannot be empty." },
Type_parameter_list_cannot_be_empty: { code: 1098, category: DiagnosticCategory.Error, key: "Type parameter list cannot be empty." },
Type_argument_list_cannot_be_empty: { code: 1099, category: DiagnosticCategory.Error, key: "Type argument list cannot be empty." },
Invalid_use_of_0_in_strict_mode: { code: 1100, category: DiagnosticCategory.Error, key: "Invalid use of '{0}' in strict mode." },
with_statements_are_not_allowed_in_strict_mode: { code: 1101, category: DiagnosticCategory.Error, key: "'with' statements are not allowed in strict mode." },
delete_cannot_be_called_on_an_identifier_in_strict_mode: { code: 1102, category: DiagnosticCategory.Error, key: "'delete' cannot be called on an identifier in strict mode." },
A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: { code: 1104, category: DiagnosticCategory.Error, key: "A 'continue' statement can only be used within an enclosing iteration statement." },
A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: { code: 1105, category: DiagnosticCategory.Error, key: "A 'break' statement can only be used within an enclosing iteration or switch statement." },
Jump_target_cannot_cross_function_boundary: { code: 1107, category: DiagnosticCategory.Error, key: "Jump target cannot cross function boundary." },
A_return_statement_can_only_be_used_within_a_function_body: { code: 1108, category: DiagnosticCategory.Error, key: "A 'return' statement can only be used within a function body." },
Expression_expected: { code: 1109, category: DiagnosticCategory.Error, key: "Expression expected." },
Type_expected: { code: 1110, category: DiagnosticCategory.Error, key: "Type expected." },
A_class_member_cannot_be_declared_optional: { code: 1112, category: DiagnosticCategory.Error, key: "A class member cannot be declared optional." },
A_default_clause_cannot_appear_more_than_once_in_a_switch_statement: { code: 1113, category: DiagnosticCategory.Error, key: "A 'default' clause cannot appear more than once in a 'switch' statement." },
Duplicate_label_0: { code: 1114, category: DiagnosticCategory.Error, key: "Duplicate label '{0}'" },
A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement: { code: 1115, category: DiagnosticCategory.Error, key: "A 'continue' statement can only jump to a label of an enclosing iteration statement." },
A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement: { code: 1116, category: DiagnosticCategory.Error, key: "A 'break' statement can only jump to a label of an enclosing statement." },
An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode: { code: 1117, category: DiagnosticCategory.Error, key: "An object literal cannot have multiple properties with the same name in strict mode." },
An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name: { code: 1118, category: DiagnosticCategory.Error, key: "An object literal cannot have multiple get/set accessors with the same name." },
An_object_literal_cannot_have_property_and_accessor_with_the_same_name: { code: 1119, category: DiagnosticCategory.Error, key: "An object literal cannot have property and accessor with the same name." },
| Digit_expected: { code: 1124, category: DiagnosticCategory.Error, key: "Digit expected." },
Hexadecimal_digit_expected: { code: 1125, category: DiagnosticCategory.Error, key: "Hexadecimal digit expected." },
Unexpected_end_of_text: { code: 1126, category: DiagnosticCategory.Error, key: "Unexpected end of text." },
Invalid_character: { code: 1127, category: DiagnosticCategory.Error, key: "Invalid character." },
Declaration_or_statement_expected: { code: 1128, category: DiagnosticCategory.Error, key: "Declaration or statement expected." },
Statement_expected: { code: 1129, category: DiagnosticCategory.Error, key: "Statement expected." },
case_or_default_expected: { code: 1130, category: DiagnosticCategory.Error, key: "'case' or 'default' expected." },
Property_or_signature_expected: { code: 1131, category: DiagnosticCategory.Error, key: "Property or signature expected." },
Enum_member_expected: { code: 1132, category: DiagnosticCategory.Error, key: "Enum member expected." },
Variable_declaration_expected: { code: 1134, category: DiagnosticCategory.Error, key: "Variable declaration expected." },
Argument_expression_expected: { code: 1135, category: DiagnosticCategory.Error, key: "Argument expression expected." },
Property_assignment_expected: { code: 1136, category: DiagnosticCategory.Error, key: "Property assignment expected." },
Expression_or_comma_expected: { code: 1137, category: DiagnosticCategory.Error, key: "Expression or comma expected." },
Parameter_declaration_expected: { code: 1138, category: DiagnosticCategory.Error, key: "Parameter declaration expected." },
Type_parameter_declaration_expected: { code: 1139, category: DiagnosticCategory.Error, key: "Type parameter declaration expected." },
Type_argument_expected: { code: 1140, category: DiagnosticCategory.Error, key: "Type argument expected." },
String_literal_expected: { code: 1141, category: DiagnosticCategory.Error, key: "String literal expected." },
Line_break_not_permitted_here: { code: 1142, category: DiagnosticCategory.Error, key: "Line break not permitted here." },
or_expected: { code: 1144, category: DiagnosticCategory.Error, key: "'{' or ';' expected." },
Modifiers_not_permitted_on_index_signature_members: { code: 1145, category: DiagnosticCategory.Error, key: "Modifiers not permitted on index signature members." },
Declaration_expected: { code: 1146, category: DiagnosticCategory.Error, key: "Declaration expected." },
Import_declarations_in_a_namespace_cannot_reference_a_module: { code: 1147, category: DiagnosticCategory.Error, key: "Import declarations in a namespace cannot reference a module." },
Cannot_compile_modules_unless_the_module_flag_is_provided: { code: 1148, category: DiagnosticCategory.Error, key: "Cannot compile modules unless the '--module' flag is provided." },
File_name_0_differs_from_already_included_file_name_1_only_in_casing: { code: 1149, category: DiagnosticCategory.Error, key: "File name '{0}' differs from already included file name '{1}' only in casing" },
new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: { code: 1150, category: DiagnosticCategory.Error, key: "'new T[]' cannot be used to create an array. Use 'new Array<T>()' instead." },
const_declarations_must_be_initialized: { code: 1155, category: DiagnosticCategory.Error, key: "'const' declarations must be initialized" },
const_declarations_can_only_be_declared_inside_a_block: { code: 1156, category: DiagnosticCategory.Error, key: "'const' declarations can only be declared inside a block." },
let_declarations_can_only_be_declared_inside_a_block: { code: 1157, category: DiagnosticCategory.Error, key: "'let' declarations can only be declared inside a block." },
Unterminated_template_literal: { code: 1160, category: DiagnosticCategory.Error, key: "Unterminated template literal." },
Unterminated_regular_expression_literal: { code: 1161, category: DiagnosticCategory.Error, key: "Unterminated regular expression literal." },
An_object_member_cannot_be_declared_optional: { code: 1162, category: DiagnosticCategory.Error, key: "An object member cannot be declared optional." },
A_yield_expression_is_only_allowed_in_a_generator_body: { code: 1163, category: DiagnosticCategory.Error, key: "A 'yield' expression is only allowed in a generator body." },
Computed_property_names_are_not_allowed_in_enums: { code: 1164, category: DiagnosticCategory.Error, key: "Computed property names are not allowed in enums." },
A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol: { code: 1165, category: DiagnosticCategory.Error, key: "A computed property name in an ambient context must directly refer to a built-in symbol." },
A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol: { code: 1166, category: DiagnosticCategory.Error, key: "A computed property name in a class property declaration must directly refer to a built-in symbol." },
A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol: { code: 1168, category: DiagnosticCategory.Error, key: "A computed property name in a method overload must directly refer to a built-in symbol." },
A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol: { code: 1169, category: DiagnosticCategory.Error, key: "A computed property name in an interface must directly refer to a built-in symbol." },
A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol: { code: 1170, category: DiagnosticCategory.Error, key: "A computed property name in a type literal must directly refer to a built-in symbol." },
A_comma_expression_is_not_allowed_in_a_computed_property_name: { code: 1171, category: DiagnosticCategory.Error, key: "A comma expression is not allowed in a computed property name." },
extends_clause_already_seen: { code: 1172, category: DiagnosticCategory.Error, key: "'extends' clause already seen." },
extends_clause_must_precede_implements_clause: { code: 1173, category: DiagnosticCategory.Error, key: "'extends' clause must precede 'implements' clause." },
Classes_can_only_extend_a_single_class: { code: 1174, category: DiagnosticCategory.Error, key: "Classes can only extend a single class." },
implements_clause_already_seen: { code: 1175, category: DiagnosticCategory.Error, key: "'implements' clause already seen." },
Interface_declaration_cannot_have_implements_clause: { code: 1176, category: DiagnosticCategory.Error, key: "Interface declaration cannot have 'implements' clause." },
Binary_digit_expected: { code: 1177, category: DiagnosticCategory.Error, key: "Binary digit expected." },
Octal_digit_expected: { code: 1178, category: DiagnosticCategory.Error, key: "Octal digit expected." },
Unexpected_token_expected: { code: 1179, category: DiagnosticCategory.Error, key: "Unexpected token. '{' expected." },
Property_destructuring_pattern_expected: { code: 1180, category: DiagnosticCategory.Error, key: "Property destructuring pattern expected." },
Array_element_destructuring_pattern_expected: { code: 1181, category: DiagnosticCategory.Error, key: "Array element destructuring pattern expected." },
A_destructuring_declaration_must_have_an_initializer: { code: 1182, category: DiagnosticCategory.Error, key: "A destructuring declaration must have an initializer." },
An_implementation_cannot_be_declared_in_ambient_contexts: { code: 1184, category: DiagnosticCategory.Error, key: "An implementation cannot be declared in ambient contexts." },
Modifiers_cannot_appear_here: { code: 1184, category: DiagnosticCategory.Error, key: "Modifiers cannot appear here." },
Merge_conflict_marker_encountered: { code: 1185, category: DiagnosticCategory.Error, key: "Merge conflict marker encountered." },
A_rest_element_cannot_have_an_initializer: { code: 1186, category: DiagnosticCategory.Error, key: "A rest element cannot have an initializer." },
A_parameter_property_may_not_be_a_binding_pattern: { code: 1187, category: DiagnosticCategory.Error, key: "A parameter property may not be a binding pattern." },
Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: { code: 1188, category: DiagnosticCategory.Error, key: "Only a single variable declaration is allowed in a 'for...of' statement." },
The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: { code: 1189, category: DiagnosticCategory.Error, key: "The variable declaration of a 'for...in' statement cannot have an initializer." },
The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: { code: 1190, category: DiagnosticCategory.Error, key: "The variable declaration of a 'for...of' statement cannot have an initializer." },
An_import_declaration_cannot_have_modifiers: { code: 1191, category: DiagnosticCategory.Error, key: "An import declaration cannot have modifiers." },
Module_0_has_no_default_export: { code: 1192, category: DiagnosticCategory.Error, key: "Module '{0}' has no default export." },
An_export_declaration_cannot_have_modifiers: { code: 1193, category: DiagnosticCategory.Error, key: "An export declaration cannot have modifiers." },
Export_declarations_are_not_permitted_in_a_namespace: { code: 1194, category: DiagnosticCategory.Error, key: "Export declarations are not permitted in a namespace." },
Catch_clause_variable_name_must_be_an_identifier: { code: 1195, category: DiagnosticCategory.Error, key: "Catch clause variable name must be an identifier." },
Catch_clause_variable_cannot_have_a_type_annotation: { code: 1196, category: DiagnosticCategory.Error, key: "Catch clause variable cannot have a type annotation." },
Catch_clause_variable_cannot_have_an_initializer: { code: 1197, category: DiagnosticCategory.Error, key: "Catch clause variable cannot have an initializer." },
An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: { code: 1198, category: DiagnosticCategory.Error, key: "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive." },
Unterminated_Unicode_escape_sequence: { code: 1199, category: DiagnosticCategory.Error, key: "Unterminated Unicode escape sequence." },
Line_terminator_not_permitted_before_arrow: { code: 1200, category: DiagnosticCategory.Error, key: "Line terminator not permitted before arrow." },
Import_assignment_cannot_be_used_when_targeting_ECMAScript_6_or_higher_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_or_import_d_from_mod_instead: { code: 1202, category: DiagnosticCategory.Error, key: "Import assignment cannot be used when targeting ECMAScript 6 or higher. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"' or 'import d from \"mod\"' instead." },
Export_assignment_cannot_be_used_when_targeting_ECMAScript_6_or_higher_Consider_using_export_default_instead: { code: 1203, category: DiagnosticCategory.Error, key: "Export assignment cannot be used when targeting ECMAScript 6 or higher. Consider using 'export default' instead." },
Cannot_compile_modules_into_commonjs_amd_system_or_umd_when_targeting_ES6_or_higher: { code: 1204, category: DiagnosticCategory.Error, key: "Cannot compile modules into 'commonjs', 'amd', 'system' or 'umd' when targeting 'ES6' or higher." },
Decorators_are_only_available_when_targeting_ECMAScript_5_and_higher: { code: 1205, category: DiagnosticCategory.Error, key: "Decorators are only available when targeting ECMAScript 5 and higher." },
Decorators_are_not_valid_here: { code: 1206, category: DiagnosticCategory.Error, key: "Decorators are not valid here." },
Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: { code: 1207, category: DiagnosticCategory.Error, key: "Decorators cannot be applied to multiple get/set accessors of the same name." },
Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: { code: 1208, category: DiagnosticCategory.Error, key: "Cannot compile namespaces when the '--isolatedModules' flag is provided." },
Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided: { code: 1209, category: DiagnosticCategory.Error, key: "Ambient const enums are not allowed when the '--isolatedModules' flag is provided." },
Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: { code: 1210, category: DiagnosticCategory.Error, key: "Invalid use of '{0}'. Class definitions are automatically in strict mode." },
A_class_declaration_without_the_default_modifier_must_have_a_name: { code: 1211, category: DiagnosticCategory.Error, key: "A class declaration without the 'default' modifier must have a name" },
Identifier_expected_0_is_a_reserved_word_in_strict_mode: { code: 1212, category: DiagnosticCategory.Error, key: "Identifier expected. '{0}' is a reserved word in strict mode" },
Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: { code: 1213, category: DiagnosticCategory.Error, key: "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode." },
Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: { code: 1214, category: DiagnosticCategory.Error, key: "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode." },
Invalid_use_of_0_Modules_are_automatically_in_strict_mode: { code: 1215, category: DiagnosticCategory.Error, key: "Invalid use of '{0}'. Modules are automatically in strict mode." },
Export_assignment_is_not_supported_when_module_flag_is_system: { code: 1218, category: DiagnosticCategory.Error, key: "Export assignment is not supported when '--module' flag is 'system'." },
Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Specify_experimentalDecorators_to_remove_this_warning: { code: 1219, category: DiagnosticCategory.Error, key: "Experimental support for decorators is a feature that is subject to change in a future release. Specify '--experimentalDecorators' to remove this warning." },
Generators_are_only_available_when_targeting_ECMAScript_6_or_higher: { code: 1220, category: DiagnosticCategory.Error, key: "Generators are only available when targeting ECMAScript 6 or higher." },
Generators_are_not_allowed_in_an_ambient_context: { code: 1221, category: DiagnosticCategory.Error, key: "Generators are not allowed in an ambient context." },
An_overload_signature_cannot_be_declared_as_a_generator: { code: 1222, category: DiagnosticCategory.Error, key: "An overload signature cannot be declared as a generator." },
_0_tag_already_specified: { code: 1223, category: DiagnosticCategory.Error, key: "'{0}' tag already specified." },
Signature_0_must_have_a_type_predicate: { code: 1224, category: DiagnosticCategory.Error, key: "Signature '{0}' must have a type predicate." },
Cannot_find_parameter_0: { code: 1225, category: DiagnosticCategory.Error, key: "Cannot find parameter '{0}'." },
Type_predicate_0_is_not_assignable_to_1: { code: 1226, category: DiagnosticCategory.Error, key: "Type predicate '{0}' is not assignable to '{1}'." },
Parameter_0_is_not_in_the_same_position_as_parameter_1: { code: 1227, category: DiagnosticCategory.Error, key: "Parameter '{0}' is not in the same position as parameter '{1}'." },
A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: { code: 1228, category: DiagnosticCategory.Error, key: "A type predicate is only allowed in return type position for functions and methods." },
A_type_predicate_cannot_reference_a_rest_parameter: { code: 1229, category: DiagnosticCategory.Error, key: "A type predicate cannot reference a rest parameter." },
A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: { code: 1230, category: DiagnosticCategory.Error, key: "A type predicate cannot reference element '{0}' in a binding pattern." },
An_export_assignment_can_only_be_used_in_a_module: { code: 1231, category: DiagnosticCategory.Error, key: "An export assignment can only be used in a module." },
An_import_declaration_can_only_be_used_in_a_namespace_or_module: { code: 1232, category: DiagnosticCategory.Error, key: "An import declaration can only be used in a namespace or module." },
An_export_declaration_can_only_be_used_in_a_module: { code: 1233, category: DiagnosticCategory.Error, key: "An export declaration can only be used in a module." },
An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: { code: 1234, category: DiagnosticCategory.Error, key: "An ambient module declaration is only allowed at the top level in a file." },
A_namespace_declaration_is_only_allowed_in_a_namespace_or_module: { code: 1235, category: DiagnosticCategory.Error, key: "A namespace declaration is only allowed in a namespace or module." },
Experimental_support_for_async_functions_is_a_feature_that_is_subject_to_change_in_a_future_release_Specify_experimentalAsyncFunctions_to_remove_this_warning: { code: 1236, category: DiagnosticCategory.Error, key: "Experimental support for async functions is a feature that is subject to change in a future release. Specify '--experimentalAsyncFunctions' to remove this warning." },
with_statements_are_not_allowed_in_an_async_function_block: { code: 1300, category: DiagnosticCategory.Error, key: "'with' statements are not allowed in an async function block." },
await_expression_is_only_allowed_within_an_async_function: { code: 1308, category: DiagnosticCategory.Error, key: "'await' expression is only allowed within an async function." },
Async_functions_are_only_available_when_targeting_ECMAScript_6_and_higher: { code: 1311, category: DiagnosticCategory.Error, key: "Async functions are only available when targeting ECMAScript 6 and higher." },
The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: { code: 1236, category: DiagnosticCategory.Error, key: "The return type of a property decorator function must be either 'void' or 'any'." },
The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: { code: 1237, category: DiagnosticCategory.Error, key: "The return type of a parameter decorator function must be either 'void' or 'any'." },
Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: { code: 1238, category: DiagnosticCategory.Error, key: "Unable to resolve signature of class decorator when called as an expression." },
Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: { code: 1239, category: DiagnosticCategory.Error, key: "Unable to resolve signature of parameter decorator when called as an expression." },
Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: { code: 1240, category: DiagnosticCategory.Error, key: "Unable to resolve signature of property decorator when called as an expression." },
Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: { code: 1241, category: DiagnosticCategory.Error, key: "Unable to resolve signature of method decorator when called as an expression." },
abstract_modifier_can_only_appear_on_a_class_or_method_declaration: { code: 1242, category: DiagnosticCategory.Error, key: "'abstract' modifier can only appear on a class or method declaration." },
_0_modifier_cannot_be_used_with_1_modifier: { code: 1243, category: DiagnosticCategory.Error, key: "'{0}' modifier cannot be used with '{1}' modifier." },
Abstract_methods_can_only_appear_within_an_abstract_class: { code: 1244, category: DiagnosticCategory.Error, key: "Abstract methods can only appear within an abstract class." },
Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: { code: 1245, category: DiagnosticCategory.Error, key: "Method '{0}' cannot have an implementation because it is marked abstract." },
Duplicate_identifier_0: { code: 2300, category: DiagnosticCategory.Error, key: "Duplicate identifier '{0}'." },
Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: DiagnosticCategory.Error, key: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." },
Static_members_cannot_reference_class_type_parameters: { code: 2302, category: DiagnosticCategory.Error, key: "Static members cannot reference class type parameters." },
Circular_definition_of_import_alias_0: { code: 2303, category: DiagnosticCategory.Error, key: "Circular definition of import alias '{0}'." },
Cannot_find_name_0: { code: 2304, category: DiagnosticCategory.Error, key: "Cannot find name '{0}'." },
Module_0_has_no_exported_member_1: { code: 2305, category: DiagnosticCategory.Error, key: "Module '{0}' has no exported member '{1}'." },
File_0_is_not_a_module: { code: 2306, category: DiagnosticCategory.Error, key: "File '{0}' is not a module." },
Cannot_find_module_0: { code: 2307, category: DiagnosticCategory.Error, key: "Cannot find module '{0}'." },
An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: { code: 2309, category: DiagnosticCategory.Error, key: "An export assignment cannot be used in a module with other exported elements." },
Type_0_recursively_references_itself_as_a_base_type: { code: 2310, category: DiagnosticCategory.Error, key: "Type '{0}' recursively references itself as a base type." },
A_class_may_only_extend_another_class: { code: 2311, category: DiagnosticCategory.Error, key: "A class may only extend another class." },
An_interface_may_only_extend_a_class_or_another_interface: { code: 2312, category: DiagnosticCategory.Error, key: "An interface may only extend a class or another interface." },
Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list: { code: 2313, category: DiagnosticCategory.Error, key: "Constraint of a type parameter cannot reference any type parameter from the same type parameter list." },
Generic_type_0_requires_1_type_argument_s: { code: 2314, category: DiagnosticCategory.Error, key: "Generic type '{0}' requires {1} type argument(s)." },
Type_0_is_not_generic: { code: 2315, category: DiagnosticCategory.Error, key: "Type '{0}' is not generic." },
Global_type_0_must_be_a_class_or_interface_type: { code: 2316, category: DiagnosticCategory.Error, key: "Global type '{0}' must be a class or interface type." },
Global_type_0_must_have_1_type_parameter_s: { code: 2317, category: DiagnosticCategory.Error, key: "Global type '{0}' must have {1} type parameter(s)." },
Cannot_find_global_type_0: { code: 2318, category: DiagnosticCategory.Error, key: "Cannot find global type '{0}'." },
Named_property_0_of_types_1_and_2_are_not_identical: { code: 2319, category: DiagnosticCategory.Error, key: "Named property '{0}' of types '{1}' and '{2}' are not identical." },
Interface_0_cannot_simultaneously_extend_types_1_and_2: { code: 2320, category: DiagnosticCategory.Error, key: "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'." },
Excessive_stack_depth_comparing_types_0_and_1: { code: 2321, category: DiagnosticCategory.Error, key: "Excessive stack depth comparing types '{0}' and '{1}'." },
Type_0_is_not_assignable_to_type_1: { code: 2322, category: DiagnosticCategory.Error, key: "Type '{0}' is not assignable to type '{1}'." },
Property_0_is_missing_in_type_1: { code: 2324, category: DiagnosticCategory.Error, key: "Property '{0}' is missing in type '{1}'." },
Property_0_is_private_in_type_1_but_not_in_type_2: { code: 2325, category: DiagnosticCategory.Error, key: "Property '{0}' is private in type '{1}' but not in type '{2}'." },
Types_of_property_0_are_incompatible: { code: 2326, category: DiagnosticCategory.Error, key: "Types of property '{0}' are incompatible." },
Property_0_is_optional_in_type_1_but_required_in_type_2: { code: 2327, category: DiagnosticCategory.Error, key: "Property '{0}' is optional in type '{1}' but required in type '{2}'." },
Types_of_parameters_0_and_1_are_incompatible: { code: 2328, category: DiagnosticCategory.Error, key: "Types of parameters '{0}' and '{1}' are incompatible." },
Index_signature_is_missing_in_type_0: { code: 2329, category: DiagnosticCategory.Error, key: "Index signature is missing in type '{0}'." },
Index_signatures_are_incompatible: { code: 2330, category: DiagnosticCategory.Error, key: "Index signatures are incompatible." },
this_cannot_be_referenced_in_a_module_or_namespace_body: { code: 2331, category: DiagnosticCategory.Error, key: "'this' cannot be referenced in a module or namespace body." },
this_cannot_be_referenced_in_current_location: { code: 2332, category: DiagnosticCategory.Error, key: "'this' cannot be referenced in current location." },
this_cannot_be_referenced_in_constructor_arguments: { code: 2333, category: DiagnosticCategory.Error, key: "'this' cannot be referenced in constructor arguments." },
this_cannot_be_referenced_in_a_static_property_initializer: { code: 2334, category: DiagnosticCategory.Error, key: "'this' cannot be referenced in a static property initializer." },
super_can_only_be_referenced_in_a_derived_class: { code: 2335, category: DiagnosticCategory.Error, key: "'super' can only be referenced in a derived class." },
super_cannot_be_referenced_in_constructor_arguments: { code: 2336, category: DiagnosticCategory.Error, key: "'super' cannot be referenced in constructor arguments." },
Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: { code: 2337, category: DiagnosticCategory.Error, key: "Super calls are not permitted outside constructors or in nested functions inside constructors." },
super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: { code: 2338, category: DiagnosticCategory.Error, key: "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class." },
Property_0_does_not_exist_on_type_1: { code: 2339, category: DiagnosticCategory.Error, key: "Property '{0}' does not exist on type '{1}'." },
Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: { code: 2340, category: DiagnosticCategory.Error, key: "Only public and protected methods of the base class are accessible via the 'super' keyword." },
Property_0_is_private_and_only_accessible_within_class_1: { code: 2341, category: DiagnosticCategory.Error, key: "Property '{0}' is private and only accessible within class '{1}'." },
An_index_expression_argument_must_be_of_type_string_number_symbol_or_any: { code: 2342, category: DiagnosticCategory.Error, key: "An index expression argument must be of type 'string', 'number', 'symbol, or 'any'." },
Type_0_does_not_satisfy_the_constraint_1: { code: 2344, category: DiagnosticCategory.Error, key: "Type '{0}' does not satisfy the constraint '{1}'." },
Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: { code: 2345, category: DiagnosticCategory.Error, key: "Argument of type '{0}' is not assignable to parameter of type '{1}'." },
Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 2346, category: DiagnosticCategory.Error, key: "Supplied parameters do not match any signature of call target." },
Untyped_function_calls_may_not_accept_type_arguments: { code: 2347, category: DiagnosticCategory.Error, key: "Untyped function calls may not accept type arguments." },
Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: { code: 2348, category: DiagnosticCategory.Error, key: "Value of type '{0}' is not callable. Did you mean to include 'new'?" },
Cannot_invoke_an_expression_whose_type_lacks_a_call_signature: { code: 2349, category: DiagnosticCategory.Error, key: "Cannot invoke an expression whose type lacks a call signature." },
Only_a_void_function_can_be_called_with_the_new_keyword: { code: 2350, category: DiagnosticCategory.Error, key: "Only a void function can be called with the 'new' keyword." },
Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: { code: 2351, category: DiagnosticCategory.Error, key: "Cannot use 'new' with an expression whose type lacks a call or construct signature." },
Neither_type_0_nor_type_1_is_assignable_to_the_other: { code: 2352, category: DiagnosticCategory.Error, key: "Neither type '{0}' nor type '{1}' is assignable to the other." },
Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: { code: 2353, category: DiagnosticCategory.Error, key: "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'." },
No_best_common_type_exists_among_return_expressions: { code: 2354, category: DiagnosticCategory.Error, key: "No best common type exists among return expressions." },
A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_or_consist_of_a_single_throw_statement: { code: 2355, category: DiagnosticCategory.Error, key: "A function whose declared type is neither 'void' nor 'any' must return a value or consist of a single 'throw' statement." },
An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: { code: 2356, category: DiagnosticCategory.Error, key: "An arithmetic operand must be of type 'any', 'number' or an enum type." },
The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer: { code: 2357, category: DiagnosticCategory.Error, key: "The operand of an increment or decrement operator must be a variable, property or indexer." },
The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2358, category: DiagnosticCategory.Error, key: "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter." },
The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: { code: 2359, category: DiagnosticCategory.Error, key: "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type." },
The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: { code: 2360, category: DiagnosticCategory.Error, key: "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'." },
The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2361, category: DiagnosticCategory.Error, key: "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter" },
The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2362, category: DiagnosticCategory.Error, key: "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." },
The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2363, category: DiagnosticCategory.Error, key: "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." },
Invalid_left_hand_side_of_assignment_expression: { code: 2364, category: DiagnosticCategory.Error, key: "Invalid left-hand side of assignment expression." },
Operator_0_cannot_be_applied_to_types_1_and_2: { code: 2365, category: DiagnosticCategory.Error, key: "Operator '{0}' cannot be applied to types '{1}' and '{2}'." },
Type_parameter_name_cannot_be_0: { code: 2368, category: DiagnosticCategory.Error, key: "Type parameter name cannot be '{0}'" },
A_parameter_property_is_only_allowed_in_a_constructor_implementation: { code: 2369, category: DiagnosticCategory.Error, key: "A parameter property is only allowed in a constructor implementation." },
A_rest_parameter_must_be_of_an_array_type: { code: 2370, category: DiagnosticCategory.Error, key: "A rest parameter must be of an array type." },
A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: { code: 2371, category: DiagnosticCategory.Error, key: "A parameter initializer is only allowed in a function or constructor implementation." },
Parameter_0_cannot_be_referenced_in_its_initializer: { code: 2372, category: DiagnosticCategory.Error, key: "Parameter '{0}' cannot be referenced in its initializer." },
Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: { code: 2373, category: DiagnosticCategory.Error, key: "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it." },
Duplicate_string_index_signature: { code: 2374, category: DiagnosticCategory.Error, key: "Duplicate string index signature." },
Duplicate_number_index_signature: { code: 2375, category: DiagnosticCategory.Error, key: "Duplicate number index signature." },
A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: { code: 2376, category: DiagnosticCategory.Error, key: "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties." },
Constructors_for_derived_classes_must_contain_a_super_call: { code: 2377, category: DiagnosticCategory.Error, key: "Constructors for derived classes must contain a 'super' call." },
A_get_accessor_must_return_a_value_or_consist_of_a_single_throw_statement: { code: 2378, category: DiagnosticCategory.Error, key: "A 'get' accessor must return a value or consist of a single 'throw' statement." },
Getter_and_setter_accessors_do_not_agree_in_visibility: { code: 2379, category: DiagnosticCategory.Error, key: "Getter and setter accessors do not agree in visibility." },
get_and_set_accessor_must_have_the_same_type: { code: 2380, category: DiagnosticCategory.Error, key: "'get' and 'set' accessor must have the same type." },
A_signature_with_an_implementation_cannot_use_a_string_literal_type: { code: 2381, category: DiagnosticCategory.Error, key: "A signature with an implementation cannot use a string literal type." },
Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: { code: 2382, category: DiagnosticCategory.Error, key: "Specialized overload signature is not assignable to any non-specialized signature." },
Overload_signatures_must_all_be_exported_or_not_exported: { code: 2383, category: DiagnosticCategory.Error, key: "Overload signatures must all be exported or not exported." },
Overload_signatures_must_all_be_ambient_or_non_ambient: { code: 2384, category: DiagnosticCategory.Error, key: "Overload signatures must all be ambient or non-ambient." },
Overload_signatures_must_all_be_public_private_or_protected: { code: 2385, category: DiagnosticCategory.Error, key: "Overload signatures must all be public, private or protected." },
Overload_signatures_must_all_be_optional_or_required: { code: 2386, category: DiagnosticCategory.Error, key: "Overload signatures must all be optional or required." },
Function_overload_must_be_static: { code: 2387, category: DiagnosticCategory.Error, key: "Function overload must be static." },
Function_overload_must_not_be_static: { code: 2388, category: DiagnosticCategory.Error, key: "Function overload must not be static." },
Function_implementation_name_must_be_0: { code: 2389, category: DiagnosticCategory.Error, key: "Function implementation name must be '{0}'." },
Constructor_implementation_is_missing: { code: 2390, category: DiagnosticCategory.Error, key: "Constructor implementation is missing." },
Function_implementation_is_missing_or_not_immediately_following_the_declaration: { code: 2391, category: DiagnosticCategory.Error, key: "Function implementation is missing or not immediately following the declaration." },
Multiple_constructor_implementations_are_not_allowed: { code: 2392, category: DiagnosticCategory.Error, key: "Multiple constructor implementations are not allowed." },
Duplicate_function_implementation: { code: 2393, category: DiagnosticCategory.Error, key: "Duplicate function implementation." },
Overload_signature_is_not_compatible_with_function_implementation: { code: 2394, category: DiagnosticCategory.Error, key: "Overload signature is not compatible with function implementation." },
Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: { code: 2395, category: DiagnosticCategory.Error, key: "Individual declarations in merged declaration '{0}' must be all exported or all local." },
Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: { code: 2396, category: DiagnosticCategory.Error, key: "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters." },
Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: { code: 2399, category: DiagnosticCategory.Error, key: "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference." },
Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: { code: 2400, category: DiagnosticCategory.Error, key: "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference." },
Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: { code: 2401, category: DiagnosticCategory.Error, key: "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference." },
Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: { code: 2402, category: DiagnosticCategory.Error, key: "Expression resolves to '_super' that compiler uses to capture base class reference." },
Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: { code: 2403, category: DiagnosticCategory.Error, key: "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'." },
The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: { code: 2404, category: DiagnosticCategory.Error, key: "The left-hand side of a 'for...in' statement cannot use a type annotation." },
The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: { code: 2405, category: DiagnosticCategory.Error, key: "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'." },
Invalid_left_hand_side_in_for_in_statement: { code: 2406, category: DiagnosticCategory.Error, key: "Invalid left-hand side in 'for...in' statement." },
The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2407, category: DiagnosticCategory.Error, key: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter." },
Setters_cannot_return_a_value: { code: 2408, category: DiagnosticCategory.Error, key: "Setters cannot return a value." },
Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: { code: 2409, category: DiagnosticCategory.Error, key: "Return type of constructor signature must be assignable to the instance type of the class" },
All_symbols_within_a_with_block_will_be_resolved_to_any: { code: 2410, category: DiagnosticCategory.Error, key: "All symbols within a 'with' block will be resolved to 'any'." },
Property_0_of_type_1_is_not_assignable_to_string_index_type_2: { code: 2411, category: DiagnosticCategory.Error, key: "Property '{0}' of type '{1}' is not assignable to string index type '{2}'." },
Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: { code: 2412, category: DiagnosticCategory.Error, key: "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'." },
Numeric_index_type_0_is_not_assignable_to_string_index_type_1: { code: 2413, category: DiagnosticCategory.Error, key: "Numeric index type '{0}' is not assignable to string index type '{1}'." },
Class_name_cannot_be_0: { code: 2414, category: DiagnosticCategory.Error, key: "Class name cannot be '{0}'" },
Class_0_incorrectly_extends_base_class_1: { code: 2415, category: DiagnosticCategory.Error, key: "Class '{0}' incorrectly extends base class '{1}'." },
Class_static_side_0_incorrectly_extends_base_class_static_side_1: { code: 2417, category: DiagnosticCategory.Error, key: "Class static side '{0}' incorrectly extends base class static side '{1}'." },
Type_name_0_in_extends_clause_does_not_reference_constructor_function_for_0: { code: 2419, category: DiagnosticCategory.Error, key: "Type name '{0}' in extends clause does not reference constructor function for '{0}'." },
Class_0_incorrectly_implements_interface_1: { code: 2420, category: DiagnosticCategory.Error, key: "Class '{0}' incorrectly implements interface '{1}'." },
A_class_may_only_implement_another_class_or_interface: { code: 2422, category: DiagnosticCategory.Error, key: "A class may only implement another class or interface." },
Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: { code: 2423, category: DiagnosticCategory.Error, key: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor." },
Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: { code: 2424, category: DiagnosticCategory.Error, key: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property." },
Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: { code: 2425, category: DiagnosticCategory.Error, key: "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function." },
Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: { code: 2426, category: DiagnosticCategory.Error, key: "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function." },
Interface_name_cannot_be_0: { code: 2427, category: DiagnosticCategory.Error, key: "Interface name cannot be '{0}'" },
All_declarations_of_an_interface_must_have_identical_type_parameters: { code: 2428, category: DiagnosticCategory.Error, key: "All declarations of an interface must have identical type parameters." },
Interface_0_incorrectly_extends_interface_1: { code: 2430, category: DiagnosticCategory.Error, key: "Interface '{0}' incorrectly extends interface '{1}'." },
Enum_name_cannot_be_0: { code: 2431, category: DiagnosticCategory.Error, key: "Enum name cannot be '{0}'" },
In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: { code: 2432, category: DiagnosticCategory.Error, key: "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element." },
A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged: { code: 2433, category: DiagnosticCategory.Error, key: "A namespace declaration cannot be in a different file from a class or function with which it is merged" },
A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged: { code: 2434, category: DiagnosticCategory.Error, key: "A namespace declaration cannot be located prior to a class or function with which it is merged" },
Ambient_modules_cannot_be_nested_in_other_modules: { code: 2435, category: DiagnosticCategory.Error, key: "Ambient modules cannot be nested in other modules." },
Ambient_module_declaration_cannot_specify_relative_module_name: { code: 2436, category: DiagnosticCategory.Error, key: "Ambient module declaration cannot specify relative module name." },
Module_0_is_hidden_by_a_local_declaration_with_the_same_name: { code: 2437, category: DiagnosticCategory.Error, key: "Module '{0}' is hidden by a local declaration with the same name" },
Import_name_cannot_be_0: { code: 2438, category: DiagnosticCategory.Error, key: "Import name cannot be '{0}'" },
Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name: { code: 2439, category: DiagnosticCategory.Error, key: "Import or export declaration in an ambient module declaration cannot reference module through relative module name." },
Import_declaration_conflicts_with_local_declaration_of_0: { code: 2440, category: DiagnosticCategory.Error, key: "Import declaration conflicts with local declaration of '{0}'" },
Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module: { code: 2441, category: DiagnosticCategory.Error, key: "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module." },
Types_have_separate_declarations_of_a_private_property_0: { code: 2442, category: DiagnosticCategory.Error, key: "Types have separate declarations of a private property '{0}'." },
Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2: { code: 2443, category: DiagnosticCategory.Error, key: "Property '{0}' is protected but type '{1}' is not a class derived from '{2}'." },
Property_0_is_protected_in_type_1_but_public_in_type_2: { code: 2444, category: DiagnosticCategory.Error, key: "Property '{0}' is protected in type '{1}' but public in type '{2}'." },
Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses: { code: 2445, category: DiagnosticCategory.Error, key: "Property '{0}' is protected and only accessible within class '{1}' and its subclasses." },
Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: { code: 2446, category: DiagnosticCategory.Error, key: "Property '{0}' is protected and only accessible through an instance of class '{1}'." },
The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: { code: 2447, category: DiagnosticCategory.Error, key: "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead." },
Block_scoped_variable_0_used_before_its_declaration: { code: 2448, category: DiagnosticCategory.Error, key: "Block-scoped variable '{0}' used before its declaration." },
The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant: { code: 2449, category: DiagnosticCategory.Error, key: "The operand of an increment or decrement operator cannot be a constant." },
Left_hand_side_of_assignment_expression_cannot_be_a_constant: { code: 2450, category: DiagnosticCategory.Error, key: "Left-hand side of assignment expression cannot be a constant." },
Cannot_redeclare_block_scoped_variable_0: { code: 2451, category: DiagnosticCategory.Error, key: "Cannot redeclare block-scoped variable '{0}'." },
An_enum_member_cannot_have_a_numeric_name: { code: 2452, category: DiagnosticCategory.Error, key: "An enum member cannot have a numeric name." },
The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: { code: 2453, category: DiagnosticCategory.Error, key: "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly." },
Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0: { code: 2455, category: DiagnosticCategory.Error, key: "Type argument candidate '{1}' is not a valid type argument because it is not a supertype of candidate '{0}'." },
Type_alias_0_circularly_references_itself: { code: 2456, category: DiagnosticCategory.Error, key: "Type alias '{0}' circularly references itself." },
Type_alias_name_cannot_be_0: { code: 2457, category: DiagnosticCategory.Error, key: "Type alias name cannot be '{0}'" },
An_AMD_module_cannot_have_multiple_name_assignments: { code: 2458, category: DiagnosticCategory.Error, key: "An AMD module cannot have multiple name assignments." },
Type_0_has_no_property_1_and_no_string_index_signature: { code: 2459, category: DiagnosticCategory.Error, key: "Type '{0}' has no property '{1}' and no string index signature." },
Type_0_has_no_property_1: { code: 2460, category: DiagnosticCategory.Error, key: "Type '{0}' has no property '{1}'." },
Type_0_is_not_an_array_type: { code: 2461, category: DiagnosticCategory.Error, key: "Type '{0}' is not an array type." },
A_rest_element_must_be_last_in_an_array_destructuring_pattern: { code: 2462, category: DiagnosticCategory.Error, key: "A rest element must be last in an array destructuring pattern" },
A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: { code: 2463, category: DiagnosticCategory.Error, key: "A binding pattern parameter cannot be optional in an implementation signature." },
A_computed_property_name_must_be_of_type_string_number_symbol_or_any: { code: 2464, category: DiagnosticCategory.Error, key: "A computed property name must be of type 'string', 'number', 'symbol', or 'any'." },
this_cannot_be_referenced_in_a_computed_property_name: { code: 2465, category: DiagnosticCategory.Error, key: "'this' cannot be referenced in a computed property name." },
super_cannot_be_referenced_in_a_computed_property_name: { code: 2466, category: DiagnosticCategory.Error, key: "'super' cannot be referenced in a computed property name." },
A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type: { code: 2467, category: DiagnosticCategory.Error, key: "A computed property name cannot reference a type parameter from its containing type." },
Cannot_find_global_value_0: { code: 2468, category: DiagnosticCategory.Error, key: "Cannot find global value '{0}'." },
The_0_operator_cannot_be_applied_to_type_symbol: { code: 2469, category: DiagnosticCategory.Error, key: "The '{0}' operator cannot be applied to type 'symbol'." },
Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object: { code: 2470, category: DiagnosticCategory.Error, key: "'Symbol' reference does not refer to the global Symbol constructor object." },
A_computed_property_name_of_the_form_0_must_be_of_type_symbol: { code: 2471, category: DiagnosticCategory.Error, key: "A computed property name of the form '{0}' must be of type 'symbol'." },
Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: { code: 2472, category: DiagnosticCategory.Error, key: "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher." },
Enum_declarations_must_all_be_const_or_non_const: { code: 2473, category: DiagnosticCategory.Error, key: "Enum declarations must all be const or non-const." },
In_const_enum_declarations_member_initializer_must_be_constant_expression: { code: 2474, category: DiagnosticCategory.Error, key: "In 'const' enum declarations member initializer must be constant expression." },
const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment: { code: 2475, category: DiagnosticCategory.Error, key: "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment." },
A_const_enum_member_can_only_be_accessed_using_a_string_literal: { code: 2476, category: DiagnosticCategory.Error, key: "A const enum member can only be accessed using a string literal." },
const_enum_member_initializer_was_evaluated_to_a_non_finite_value: { code: 2477, category: DiagnosticCategory.Error, key: "'const' enum member initializer was evaluated to a non-finite value." },
const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: { code: 2478, category: DiagnosticCategory.Error, key: "'const' enum member initializer was evaluated to disallowed value 'NaN'." },
Property_0_does_not_exist_on_const_enum_1: { code: 2479, category: DiagnosticCategory.Error, key: "Property '{0}' does not exist on 'const' enum '{1}'." },
let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations: { code: 2480, category: DiagnosticCategory.Error, key: "'let' is not allowed to be used as a name in 'let' or 'const' declarations." },
Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: { code: 2481, category: DiagnosticCategory.Error, key: "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'." },
The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: { code: 2483, category: DiagnosticCategory.Error, key: "The left-hand side of a 'for...of' statement cannot use a type annotation." },
Export_declaration_conflicts_with_exported_declaration_of_0: { code: 2484, category: DiagnosticCategory.Error, key: "Export declaration conflicts with exported declaration of '{0}'" },
The_left_hand_side_of_a_for_of_statement_cannot_be_a_previously_defined_constant: { code: 2485, category: DiagnosticCategory.Error, key: "The left-hand side of a 'for...of' statement cannot be a previously defined constant." },
The_left_hand_side_of_a_for_in_statement_cannot_be_a_previously_defined_constant: { code: 2486, category: DiagnosticCategory.Error, key: "The left-hand side of a 'for...in' statement cannot be a previously defined constant." },
Invalid_left_hand_side_in_for_of_statement: { code: 2487, category: DiagnosticCategory.Error, key: "Invalid left-hand side in 'for...of' statement." },
Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2488, category: DiagnosticCategory.Error, key: "Type must have a '[Symbol.iterator]()' method that returns an iterator." },
An_iterator_must_have_a_next_method: { code: 2489, category: DiagnosticCategory.Error, key: "An iterator must have a 'next()' method." },
The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: { code: 2490, category: DiagnosticCategory.Error, key: "The type returned by the 'next()' method of an iterator must have a 'value' property." },
The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: { code: 2491, category: DiagnosticCategory.Error, key: "The left-hand side of a 'for...in' statement cannot be a destructuring pattern." },
Cannot_redeclare_identifier_0_in_catch_clause: { code: 2492, category: DiagnosticCategory.Error, key: "Cannot redeclare identifier '{0}' in catch clause" },
Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2: { code: 2493, category: DiagnosticCategory.Error, key: "Tuple type '{0}' with length '{1}' cannot be assigned to tuple with length '{2}'." },
Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher: { code: 2494, category: DiagnosticCategory.Error, key: "Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher." },
Type_0_is_not_an_array_type_or_a_string_type: { code: 2495, category: DiagnosticCategory.Error, key: "Type '{0}' is not an array type or a string type." },
The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression: { code: 2496, category: DiagnosticCategory.Error, key: "The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression." },
Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct: { code: 2497, category: DiagnosticCategory.Error, key: "Module '{0}' resolves to a non-module entity and cannot be imported using this construct." },
Module_0_uses_export_and_cannot_be_used_with_export_Asterisk: { code: 2498, category: DiagnosticCategory.Error, key: "Module '{0}' uses 'export =' and cannot be used with 'export *'." },
An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: { code: 2499, category: DiagnosticCategory.Error, key: "An interface can only extend an identifier/qualified-name with optional type arguments." },
A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: { code: 2500, category: DiagnosticCategory.Error, key: "A class can only implement an identifier/qualified-name with optional type arguments." },
A_rest_element_cannot_contain_a_binding_pattern: { code: 2501, category: DiagnosticCategory.Error, key: "A rest element cannot contain a binding pattern." },
_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: { code: 2502, category: DiagnosticCategory.Error, key: "'{0}' is referenced directly or indirectly in its own type annotation." },
Cannot_find_namespace_0: { code: 2503, category: DiagnosticCategory.Error, key: "Cannot find namespace '{0}'." },
No_best_common_type_exists_among_yield_expressions: { code: 2504, category: DiagnosticCategory.Error, key: "No best common type exists among yield expressions." },
A_generator_cannot_have_a_void_type_annotation: { code: 2505, category: DiagnosticCategory.Error, key: "A generator cannot have a 'void' type annotation." },
_0_is_referenced_directly_or_indirectly_in_its_own_base_expression: { code: 2506, category: DiagnosticCategory.Error, key: "'{0}' is referenced directly or indirectly in its own base expression." },
Type_0_is_not_a_constructor_function_type: { code: 2507, category: DiagnosticCategory.Error, key: "Type '{0}' is not a constructor function type." },
No_base_constructor_has_the_specified_number_of_type_arguments: { code: 2508, category: DiagnosticCategory.Error, key: "No base constructor has the specified number of type arguments." },
Base_constructor_return_type_0_is_not_a_class_or_interface_type: { code: 2509, category: DiagnosticCategory.Error, key: "Base constructor return type '{0}' is not a class or interface type." },
Base_constructors_must_all_have_the_same_return_type: { code: 2510, category: DiagnosticCategory.Error, key: "Base constructors must all have the same return type." },
Cannot_create_an_instance_of_the_abstract_class_0: { code: 2511, category: DiagnosticCategory.Error, key: "Cannot create an instance of the abstract class '{0}'." },
Overload_signatures_must_all_be_abstract_or_not_abstract: { code: 2512, category: DiagnosticCategory.Error, key: "Overload signatures must all be abstract or not abstract." },
Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: { code: 2513, category: DiagnosticCategory.Error, key: "Abstract method '{0}' in class '{1}' cannot be accessed via super expression." },
Classes_containing_abstract_methods_must_be_marked_abstract: { code: 2514, category: DiagnosticCategory.Error, key: "Classes containing abstract methods must be marked abstract." },
Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: { code: 2515, category: DiagnosticCategory.Error, key: "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'." },
All_declarations_of_an_abstract_method_must_be_consecutive: { code: 2516, category: DiagnosticCategory.Error, key: "All declarations of an abstract method must be consecutive." },
Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: { code: 2517, category: DiagnosticCategory.Error, key: "Cannot assign an abstract constructor type to a non-abstract constructor type." },
Only_an_ambient_class_can_be_merged_with_an_interface: { code: 2518, category: DiagnosticCategory.Error, key: "Only an ambient class can be merged with an interface." },
Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: { code: 2520, category: DiagnosticCategory.Error, key: "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions." },
Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: { code: 2521, category: DiagnosticCategory.Error, key: "Expression resolves to variable declaration '{0}' that compiler uses to support async functions." },
The_arguments_object_cannot_be_referenced_in_an_async_arrow_function_Consider_using_a_standard_async_function_expression: { code: 2522, category: DiagnosticCategory.Error, key: "The 'arguments' object cannot be referenced in an async arrow function. Consider using a standard async function expression." },
yield_expressions_cannot_be_used_in_a_parameter_initializer: { code: 2523, category: DiagnosticCategory.Error, key: "'yield' expressions cannot be used in a parameter initializer." },
await_expressions_cannot_be_used_in_a_parameter_initializer: { code: 2524, category: DiagnosticCategory.Error, key: "'await' expressions cannot be used in a parameter initializer." },
JSX_element_attributes_type_0_must_be_an_object_type: { code: 2600, category: DiagnosticCategory.Error, key: "JSX element attributes type '{0}' must be an object type." },
The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: DiagnosticCategory.Error, key: "The return type of a JSX element constructor must return an object type." },
JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: DiagnosticCategory.Error, key: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." },
Property_0_in_type_1_is_not_assignable_to_type_2: { code: 2603, category: DiagnosticCategory.Error, key: "Property '{0}' in type '{1}' is not assignable to type '{2}'" },
JSX_element_type_0_does_not_have_any_construct_or_call_signatures: { code: 2604, category: DiagnosticCategory.Error, key: "JSX element type '{0}' does not have any construct or call signatures." },
JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements: { code: 2605, category: DiagnosticCategory.Error, key: "JSX element type '{0}' is not a constructor function for JSX elements." },
Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property: { code: 2606, category: DiagnosticCategory.Error, key: "Property '{0}' of JSX spread attribute is not assignable to target property." },
JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: { code: 2607, category: DiagnosticCategory.Error, key: "JSX element class does not support attributes because it does not have a '{0}' property" },
The_global_type_JSX_0_may_not_have_more_than_one_property: { code: 2608, category: DiagnosticCategory.Error, key: "The global type 'JSX.{0}' may not have more than one property" },
Cannot_emit_namespaced_JSX_elements_in_React: { code: 2650, category: DiagnosticCategory.Error, key: "Cannot emit namespaced JSX elements in React" },
A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: { code: 2651, category: DiagnosticCategory.Error, key: "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums." },
Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: { code: 2652, category: DiagnosticCategory.Error, key: "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead." },
Import_declaration_0_is_using_private_name_1: { code: 4000, category: DiagnosticCategory.Error, key: "Import declaration '{0}' is using private name '{1}'." },
Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported class has or is using private name '{1}'." },
Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported interface has or is using private name '{1}'." },
Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4006, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'." },
Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4008, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of call signature from exported interface has or is using private name '{1}'." },
Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: { code: 4010, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of public static method from exported class has or is using private name '{1}'." },
Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: { code: 4012, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of public method from exported class has or is using private name '{1}'." },
Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: { code: 4014, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of method from exported interface has or is using private name '{1}'." },
Type_parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4016, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported function has or is using private name '{1}'." },
Implements_clause_of_exported_class_0_has_or_is_using_private_name_1: { code: 4019, category: DiagnosticCategory.Error, key: "Implements clause of exported class '{0}' has or is using private name '{1}'." },
Extends_clause_of_exported_class_0_has_or_is_using_private_name_1: { code: 4020, category: DiagnosticCategory.Error, key: "Extends clause of exported class '{0}' has or is using private name '{1}'." },
Extends_clause_of_exported_interface_0_has_or_is_using_private_name_1: { code: 4022, category: DiagnosticCategory.Error, key: "Extends clause of exported interface '{0}' has or is using private name '{1}'." },
Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4023, category: DiagnosticCategory.Error, key: "Exported variable '{0}' has or is using name '{1}' from external module {2} but cannot be named." },
Exported_variable_0_has_or_is_using_name_1_from_private_module_2: { code: 4024, category: DiagnosticCategory.Error, key: "Exported variable '{0}' has or is using name '{1}' from private module '{2}'." },
Exported_variable_0_has_or_is_using_private_name_1: { code: 4025, category: DiagnosticCategory.Error, key: "Exported variable '{0}' has or is using private name '{1}'." },
Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4026, category: DiagnosticCategory.Error, key: "Public static property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named." },
Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4027, category: DiagnosticCategory.Error, key: "Public static property '{0}' of exported class has or is using name '{1}' from private module '{2}'." },
Public_static_property_0_of_exported_class_has_or_is_using_private_name_1: { code: 4028, category: DiagnosticCategory.Error, key: "Public static property '{0}' of exported class has or is using private name '{1}'." },
Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4029, category: DiagnosticCategory.Error, key: "Public property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named." },
Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4030, category: DiagnosticCategory.Error, key: "Public property '{0}' of exported class has or is using name '{1}' from private module '{2}'." },
Public_property_0_of_exported_class_has_or_is_using_private_name_1: { code: 4031, category: DiagnosticCategory.Error, key: "Public property '{0}' of exported class has or is using private name '{1}'." },
Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4032, category: DiagnosticCategory.Error, key: "Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'." },
Property_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4033, category: DiagnosticCategory.Error, key: "Property '{0}' of exported interface has or is using private name '{1}'." },
Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4034, category: DiagnosticCategory.Error, key: "Parameter '{0}' of public static property setter from exported class has or is using name '{1}' from private module '{2}'." },
Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1: { code: 4035, category: DiagnosticCategory.Error, key: "Parameter '{0}' of public static property setter from exported class has or is using private name '{1}'." },
Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4036, category: DiagnosticCategory.Error, key: "Parameter '{0}' of public property setter from exported class has or is using name '{1}' from private module '{2}'." },
Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1: { code: 4037, category: DiagnosticCategory.Error, key: "Parameter '{0}' of public property setter from exported class has or is using private name '{1}'." },
Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4038, category: DiagnosticCategory.Error, key: "Return type of public static property getter from exported class has or is using name '{0}' from external module {1} but cannot be named." },
Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4039, category: DiagnosticCategory.Error, key: "Return type of public static property getter from exported class has or is using name '{0}' from private module '{1}'." },
Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0: { code: 4040, category: DiagnosticCategory.Error, key: "Return type of public static property getter from exported class has or is using private name '{0}'." },
Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4041, category: DiagnosticCategory.Error, key: "Return type of public property getter from exported class has or is using name '{0}' from external module {1} but cannot be named." },
Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4042, category: DiagnosticCategory.Error, key: "Return type of public property getter from exported class has or is using name '{0}' from private module '{1}'." },
Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0: { code: 4043, category: DiagnosticCategory.Error, key: "Return type of public property getter from exported class has or is using private name '{0}'." },
Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4044, category: DiagnosticCategory.Error, key: "Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'." },
Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0: { code: 4045, category: DiagnosticCategory.Error, key: "Return type of constructor signature from exported interface has or is using private name '{0}'." },
Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4046, category: DiagnosticCategory.Error, key: "Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'." },
Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0: { code: 4047, category: DiagnosticCategory.Error, key: "Return type of call signature from exported interface has or is using private name '{0}'." },
Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4048, category: DiagnosticCategory.Error, key: "Return type of index signature from exported interface has or is using name '{0}' from private module '{1}'." },
Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0: { code: 4049, category: DiagnosticCategory.Error, key: "Return type of index signature from exported interface has or is using private name '{0}'." },
Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4050, category: DiagnosticCategory.Error, key: "Return type of public static method from exported class has or is using name '{0}' from external module {1} but cannot be named." },
Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4051, category: DiagnosticCategory.Error, key: "Return type of public static method from exported class has or is using name '{0}' from private module '{1}'." },
Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0: { code: 4052, category: DiagnosticCategory.Error, key: "Return type of public static method from exported class has or is using private name '{0}'." },
Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4053, category: DiagnosticCategory.Error, key: "Return type of public method from exported class has or is using name '{0}' from external module {1} but cannot be named." },
Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4054, category: DiagnosticCategory.Error, key: "Return type of public method from exported class has or is using name '{0}' from private module '{1}'." },
Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0: { code: 4055, category: DiagnosticCategory.Error, key: "Return type of public method from exported class has or is using private name '{0}'." },
Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4056, category: DiagnosticCategory.Error, key: "Return type of method from exported interface has or is using name '{0}' from private module '{1}'." },
Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0: { code: 4057, category: DiagnosticCategory.Error, key: "Return type of method from exported interface has or is using private name '{0}'." },
Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4058, category: DiagnosticCategory.Error, key: "Return type of exported function has or is using name '{0}' from external module {1} but cannot be named." },
Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1: { code: 4059, category: DiagnosticCategory.Error, key: "Return type of exported function has or is using name '{0}' from private module '{1}'." },
Return_type_of_exported_function_has_or_is_using_private_name_0: { code: 4060, category: DiagnosticCategory.Error, key: "Return type of exported function has or is using private name '{0}'." },
Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4061, category: DiagnosticCategory.Error, key: "Parameter '{0}' of constructor from exported class has or is using name '{1}' from external module {2} but cannot be named." },
Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4062, category: DiagnosticCategory.Error, key: "Parameter '{0}' of constructor from exported class has or is using name '{1}' from private module '{2}'." },
Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1: { code: 4063, category: DiagnosticCategory.Error, key: "Parameter '{0}' of constructor from exported class has or is using private name '{1}'." },
Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4064, category: DiagnosticCategory.Error, key: "Parameter '{0}' of constructor signature from exported interface has or is using name '{1}' from private module '{2}'." },
Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4065, category: DiagnosticCategory.Error, key: "Parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'." },
Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4066, category: DiagnosticCategory.Error, key: "Parameter '{0}' of call signature from exported interface has or is using name '{1}' from private module '{2}'." },
Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4067, category: DiagnosticCategory.Error, key: "Parameter '{0}' of call signature from exported interface has or is using private name '{1}'." },
Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4068, category: DiagnosticCategory.Error, key: "Parameter '{0}' of public static method from exported class has or is using name '{1}' from external module {2} but cannot be named." },
Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4069, category: DiagnosticCategory.Error, key: "Parameter '{0}' of public static method from exported class has or is using name '{1}' from private module '{2}'." },
Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: { code: 4070, category: DiagnosticCategory.Error, key: "Parameter '{0}' of public static method from exported class has or is using private name '{1}'." },
Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4071, category: DiagnosticCategory.Error, key: "Parameter '{0}' of public method from exported class has or is using name '{1}' from external module {2} but cannot be named." },
Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4072, category: DiagnosticCategory.Error, key: "Parameter '{0}' of public method from exported class has or is using name '{1}' from private module '{2}'." },
Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: { code: 4073, category: DiagnosticCategory.Error, key: "Parameter '{0}' of public method from exported class has or is using private name '{1}'." },
Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4074, category: DiagnosticCategory.Error, key: "Parameter '{0}' of method from exported interface has or is using name '{1}' from private module '{2}'." },
Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: { code: 4075, category: DiagnosticCategory.Error, key: "Parameter '{0}' of method from exported interface has or is using private name '{1}'." },
Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4076, category: DiagnosticCategory.Error, key: "Parameter '{0}' of exported function has or is using name '{1}' from external module {2} but cannot be named." },
Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2: { code: 4077, category: DiagnosticCategory.Error, key: "Parameter '{0}' of exported function has or is using name '{1}' from private module '{2}'." },
Parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4078, category: DiagnosticCategory.Error, key: "Parameter '{0}' of exported function has or is using private name '{1}'." },
Exported_type_alias_0_has_or_is_using_private_name_1: { code: 4081, category: DiagnosticCategory.Error, key: "Exported type alias '{0}' has or is using private name '{1}'." },
Default_export_of_the_module_has_or_is_using_private_name_0: { code: 4082, category: DiagnosticCategory.Error, key: "Default export of the module has or is using private name '{0}'." },
Loop_contains_block_scoped_variable_0_referenced_by_a_function_in_the_loop_This_is_only_supported_in_ECMAScript_6_or_higher: { code: 4091, category: DiagnosticCategory.Error, key: "Loop contains block-scoped variable '{0}' referenced by a function in the loop. This is only supported in ECMAScript 6 or higher." },
The_current_host_does_not_support_the_0_option: { code: 5001, category: DiagnosticCategory.Error, key: "The current host does not support the '{0}' option." },
Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: DiagnosticCategory.Error, key: "Cannot find the common subdirectory path for the input files." },
Cannot_read_file_0_Colon_1: { code: 5012, category: DiagnosticCategory.Error, key: "Cannot read file '{0}': {1}" },
Unsupported_file_encoding: { code: 5013, category: DiagnosticCategory.Error, key: "Unsupported file encoding." },
Failed_to_parse_file_0_Colon_1: { code: 5014, category: DiagnosticCategory.Error, key: "Failed to parse file '{0}': {1}." },
Unknown_compiler_option_0: { code: 5023, category: DiagnosticCategory.Error, key: "Unknown compiler option '{0}'." },
Compiler_option_0_requires_a_value_of_type_1: { code: 5024, category: DiagnosticCategory.Error, key: "Compiler option '{0}' requires a value of type {1}." },
Could_not_write_file_0_Colon_1: { code: 5033, category: DiagnosticCategory.Error, key: "Could not write file '{0}': {1}" },
Option_project_cannot_be_mixed_with_source_files_on_a_command_line: { code: 5042, category: DiagnosticCategory.Error, key: "Option 'project' cannot be mixed with source files on a command line." },
Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES6_or_higher: { code: 5047, category: DiagnosticCategory.Error, key: "Option 'isolatedModules' can only be used when either option'--module' is provided or option 'target' is 'ES6' or higher." },
Option_inlineSources_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided: { code: 5051, category: DiagnosticCategory.Error, key: "Option 'inlineSources' can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided." },
Option_0_cannot_be_specified_without_specifying_option_1: { code: 5052, category: DiagnosticCategory.Error, key: "Option '{0}' cannot be specified without specifying option '{1}'." },
Option_0_cannot_be_specified_with_option_1: { code: 5053, category: DiagnosticCategory.Error, key: "Option '{0}' cannot be specified with option '{1}'." },
A_tsconfig_json_file_is_already_defined_at_Colon_0: { code: 5053, category: DiagnosticCategory.Error, key: "A 'tsconfig.json' file is already defined at: '{0}'." },
Concatenate_and_emit_output_to_single_file: { code: 6001, category: DiagnosticCategory.Message, key: "Concatenate and emit output to single file." },
Generates_corresponding_d_ts_file: { code: 6002, category: DiagnosticCategory.Message, key: "Generates corresponding '.d.ts' file." },
Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: DiagnosticCategory.Message, key: "Specifies the location where debugger should locate map files instead of generated locations." },
Specifies_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: { code: 6004, category: DiagnosticCategory.Message, key: "Specifies the location where debugger should locate TypeScript files instead of source locations." },
Watch_input_files: { code: 6005, category: DiagnosticCategory.Message, key: "Watch input files." },
Redirect_output_structure_to_the_directory: { code: 6006, category: DiagnosticCategory.Message, key: "Redirect output structure to the directory." },
Do_not_erase_const_enum_declarations_in_generated_code: { code: 6007, category: DiagnosticCategory.Message, key: "Do not erase const enum declarations in generated code." },
Do_not_emit_outputs_if_any_errors_were_reported: { code: 6008, category: DiagnosticCategory.Message, key: "Do not emit outputs if any errors were reported." },
Do_not_emit_comments_to_output: { code: 6009, category: DiagnosticCategory.Message, key: "Do not emit comments to output." },
Do_not_emit_outputs: { code: 6010, category: DiagnosticCategory.Message, key: "Do not emit outputs." },
Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES6_experimental: { code: 6015, category: DiagnosticCategory.Message, key: "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES6' (experimental)" },
Specify_module_code_generation_Colon_commonjs_amd_system_or_umd: { code: 6016, category: DiagnosticCategory.Message, key: "Specify module code generation: 'commonjs', 'amd', 'system' or 'umd'" },
Print_this_message: { code: 6017, category: DiagnosticCategory.Message, key: "Print this message." },
Print_the_compiler_s_version: { code: 6019, category: DiagnosticCategory.Message, key: "Print the compiler's version." },
Compile_the_project_in_the_given_directory: { code: 6020, category: DiagnosticCategory.Message, key: "Compile the project in the given directory." },
Syntax_Colon_0: { code: 6023, category: DiagnosticCategory.Message, key: "Syntax: {0}" },
options: { code: 6024, category: DiagnosticCategory.Message, key: "options" },
file: { code: 6025, category: DiagnosticCategory.Message, key: "file" },
Examples_Colon_0: { code: 6026, category: DiagnosticCategory.Message, key: "Examples: {0}" },
Options_Colon: { code: 6027, category: DiagnosticCategory.Message, key: "Options:" },
Version_0: { code: 6029, category: DiagnosticCategory.Message, key: "Version {0}" },
Insert_command_line_options_and_files_from_a_file: { code: 6030, category: DiagnosticCategory.Message, key: "Insert command line options and files from a file." },
File_change_detected_Starting_incremental_compilation: { code: 6032, category: DiagnosticCategory.Message, key: "File change detected. Starting incremental compilation..." },
KIND: { code: 6034, category: DiagnosticCategory.Message, key: "KIND" },
FILE: { code: 6035, category: DiagnosticCategory.Message, key: "FILE" },
VERSION: { code: 6036, category: DiagnosticCategory.Message, key: "VERSION" },
LOCATION: { code: 6037, category: DiagnosticCategory.Message, key: "LOCATION" },
DIRECTORY: { code: 6038, category: DiagnosticCategory.Message, key: "DIRECTORY" },
Compilation_complete_Watching_for_file_changes: { code: 6042, category: DiagnosticCategory.Message, key: "Compilation complete. Watching for file changes." },
Generates_corresponding_map_file: { code: 6043, category: DiagnosticCategory.Message, key: "Generates corresponding '.map' file." },
Compiler_option_0_expects_an_argument: { code: 6044, category: DiagnosticCategory.Error, key: "Compiler option '{0}' expects an argument." },
Unterminated_quoted_string_in_response_file_0: { code: 6045, category: DiagnosticCategory.Error, key: "Unterminated quoted string in response file '{0}'." },
Argument_for_module_option_must_be_commonjs_amd_system_or_umd: { code: 6046, category: DiagnosticCategory.Error, key: "Argument for '--module' option must be 'commonjs', 'amd', 'system' or 'umd'." },
Argument_for_target_option_must_be_ES3_ES5_or_ES6: { code: 6047, category: DiagnosticCategory.Error, key: "Argument for '--target' option must be 'ES3', 'ES5', or 'ES6'." },
Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: { code: 6048, category: DiagnosticCategory.Error, key: "Locale must be of the form <language> or <language>-<territory>. For example '{0}' or '{1}'." },
Unsupported_locale_0: { code: 6049, category: DiagnosticCategory.Error, key: "Unsupported locale '{0}'." },
Unable_to_open_file_0: { code: 6050, category: DiagnosticCategory.Error, key: "Unable to open file '{0}'." },
Corrupted_locale_file_0: { code: 6051, category: DiagnosticCategory.Error, key: "Corrupted locale file {0}." },
Raise_error_on_expressions_and_declarations_with_an_implied_any_type: { code: 6052, category: DiagnosticCategory.Message, key: "Raise error on expressions and declarations with an implied 'any' type." },
File_0_not_found: { code: 6053, category: DiagnosticCategory.Error, key: "File '{0}' not found." },
File_0_has_unsupported_extension_The_only_supported_extensions_are_1: { code: 6054, category: DiagnosticCategory.Error, key: "File '{0}' has unsupported extension. The only supported extensions are {1}." },
Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: { code: 6055, category: DiagnosticCategory.Message, key: "Suppress noImplicitAny errors for indexing objects lacking index signatures." },
Do_not_emit_declarations_for_code_that_has_an_internal_annotation: { code: 6056, category: DiagnosticCategory.Message, key: "Do not emit declarations for code that has an '@internal' annotation." },
Specifies_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: { code: 6058, category: DiagnosticCategory.Message, key: "Specifies the root directory of input files. Use to control the output directory structure with --outDir." },
File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files: { code: 6059, category: DiagnosticCategory.Error, key: "File '{0}' is not under 'rootDir' '{1}'. 'rootDir' is expected to contain all source files." },
Specifies_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: { code: 6060, category: DiagnosticCategory.Message, key: "Specifies the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)." },
NEWLINE: { code: 6061, category: DiagnosticCategory.Message, key: "NEWLINE" },
Argument_for_newLine_option_must_be_CRLF_or_LF: { code: 6062, category: DiagnosticCategory.Error, key: "Argument for '--newLine' option must be 'CRLF' or 'LF'." },
Specify_JSX_code_generation_Colon_preserve_or_react: { code: 6080, category: DiagnosticCategory.Message, key: "Specify JSX code generation: 'preserve' or 'react'" },
Argument_for_jsx_must_be_preserve_or_react: { code: 6081, category: DiagnosticCategory.Message, key: "Argument for '--jsx' must be 'preserve' or 'react'." },
Enables_experimental_support_for_ES7_decorators: { code: 6065, category: DiagnosticCategory.Message, key: "Enables experimental support for ES7 decorators." },
Enables_experimental_support_for_emitting_type_metadata_for_decorators: { code: 6066, category: DiagnosticCategory.Message, key: "Enables experimental support for emitting type metadata for decorators." },
Option_experimentalAsyncFunctions_cannot_be_specified_when_targeting_ES5_or_lower: { code: 6067, category: DiagnosticCategory.Message, key: "Option 'experimentalAsyncFunctions' cannot be specified when targeting ES5 or lower." },
Enables_experimental_support_for_ES7_async_functions: { code: 6068, category: DiagnosticCategory.Message, key: "Enables experimental support for ES7 async functions." },
Specifies_module_resolution_strategy_Colon_node_Node_or_classic_TypeScript_pre_1_6: { code: 6069, category: DiagnosticCategory.Message, key: "Specifies module resolution strategy: 'node' (Node) or 'classic' (TypeScript pre 1.6) ." },
Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file: { code: 6070, category: DiagnosticCategory.Message, key: "Initializes a TypeScript project and creates a tsconfig.json file." },
Successfully_created_a_tsconfig_json_file: { code: 6071, category: DiagnosticCategory.Message, key: "Successfully created a tsconfig.json file." },
Suppress_excess_property_checks_for_object_literals: { code: 6072, category: DiagnosticCategory.Message, key: "Suppress excess property checks for object literals." },
Variable_0_implicitly_has_an_1_type: { code: 7005, category: DiagnosticCategory.Error, key: "Variable '{0}' implicitly has an '{1}' type." },
Parameter_0_implicitly_has_an_1_type: { code: 7006, category: DiagnosticCategory.Error, key: "Parameter '{0}' implicitly has an '{1}' type." },
Member_0_implicitly_has_an_1_type: { code: 7008, category: DiagnosticCategory.Error, key: "Member '{0}' implicitly has an '{1}' type." },
new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type: { code: 7009, category: DiagnosticCategory.Error, key: "'new' expression, whose target lacks a construct signature, implicitly has an 'any' type." },
_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: { code: 7010, category: DiagnosticCategory.Error, key: "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type." },
Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: { code: 7011, category: DiagnosticCategory.Error, key: "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type." },
Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7013, category: DiagnosticCategory.Error, key: "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type." },
Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation: { code: 7016, category: DiagnosticCategory.Error, key: "Property '{0}' implicitly has type 'any', because its 'set' accessor lacks a type annotation." },
Index_signature_of_object_type_implicitly_has_an_any_type: { code: 7017, category: DiagnosticCategory.Error, key: "Index signature of object type implicitly has an 'any' type." },
Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: DiagnosticCategory.Error, key: "Object literal's property '{0}' implicitly has an '{1}' type." },
Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: DiagnosticCategory.Error, key: "Rest parameter '{0}' implicitly has an 'any[]' type." },
Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7020, category: DiagnosticCategory.Error, key: "Call signature, which lacks return-type annotation, implicitly has an 'any' return type." },
_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer: { code: 7022, category: DiagnosticCategory.Error, key: "'{0}' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer." },
_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: { code: 7023, category: DiagnosticCategory.Error, key: "'{0}' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions." },
Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: { code: 7024, category: DiagnosticCategory.Error, key: "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions." },
Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: { code: 7025, category: DiagnosticCategory.Error, key: "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type." },
JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: { code: 7026, category: DiagnosticCategory.Error, key: "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists" },
You_cannot_rename_this_element: { code: 8000, category: DiagnosticCategory.Error, key: "You cannot rename this element." },
You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: DiagnosticCategory.Error, key: "You cannot rename elements that are defined in the standard TypeScript library." },
import_can_only_be_used_in_a_ts_file: { code: 8002, category: DiagnosticCategory.Error, key: "'import ... =' can only be used in a .ts file." },
export_can_only_be_used_in_a_ts_file: { code: 8003, category: DiagnosticCategory.Error, key: "'export=' can only be used in a .ts file." },
type_parameter_declarations_can_only_be_used_in_a_ts_file: { code: 8004, category: DiagnosticCategory.Error, key: "'type parameter declarations' can only be used in a .ts file." },
implements_clauses_can_only_be_used_in_a_ts_file: { code: 8005, category: DiagnosticCategory.Error, key: "'implements clauses' can only be used in a .ts file." },
interface_declarations_can_only_be_used_in_a_ts_file: { code: 8006, category: DiagnosticCategory.Error, key: "'interface declarations' can only be used in a .ts file." },
module_declarations_can_only_be_used_in_a_ts_file: { code: 8007, category: DiagnosticCategory.Error, key: "'module declarations' can only be used in a .ts file." },
type_aliases_can_only_be_used_in_a_ts_file: { code: 8008, category: DiagnosticCategory.Error, key: "'type aliases' can only be used in a .ts file." },
_0_can_only_be_used_in_a_ts_file: { code: 8009, category: DiagnosticCategory.Error, key: "'{0}' can only be used in a .ts file." },
types_can_only_be_used_in_a_ts_file: { code: 8010, category: DiagnosticCategory.Error, key: "'types' can only be used in a .ts file." },
type_arguments_can_only_be_used_in_a_ts_file: { code: 8011, category: DiagnosticCategory.Error, key: "'type arguments' can only be used in a .ts file." },
parameter_modifiers_can_only_be_used_in_a_ts_file: { code: 8012, category: DiagnosticCategory.Error, key: "'parameter modifiers' can only be used in a .ts file." },
property_declarations_can_only_be_used_in_a_ts_file: { code: 8014, category: DiagnosticCategory.Error, key: "'property declarations' can only be used in a .ts file." },
enum_declarations_can_only_be_used_in_a_ts_file: { code: 8015, category: DiagnosticCategory.Error, key: "'enum declarations' can only be used in a .ts file." },
type_assertion_expressions_can_only_be_used_in_a_ts_file: { code: 8016, category: DiagnosticCategory.Error, key: "'type assertion expressions' can only be used in a .ts file." },
decorators_can_only_be_used_in_a_ts_file: { code: 8017, category: DiagnosticCategory.Error, key: "'decorators' can only be used in a .ts file." },
Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clauses: { code: 9002, category: DiagnosticCategory.Error, key: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses." },
class_expressions_are_not_currently_supported: { code: 9003, category: DiagnosticCategory.Error, key: "'class' expressions are not currently supported." },
JSX_attributes_must_only_be_assigned_a_non_empty_expression: { code: 17000, category: DiagnosticCategory.Error, key: "JSX attributes must only be assigned a non-empty 'expression'." },
JSX_elements_cannot_have_multiple_attributes_with_the_same_name: { code: 17001, category: DiagnosticCategory.Error, key: "JSX elements cannot have multiple attributes with the same name." },
Expected_corresponding_JSX_closing_tag_for_0: { code: 17002, category: DiagnosticCategory.Error, key: "Expected corresponding JSX closing tag for '{0}'." },
JSX_attribute_expected: { code: 17003, category: DiagnosticCategory.Error, key: "JSX attribute expected." },
Cannot_use_JSX_unless_the_jsx_flag_is_provided: { code: 17004, category: DiagnosticCategory.Error, key: "Cannot use JSX unless the '--jsx' flag is provided." },
A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: { code: 17005, category: DiagnosticCategory.Error, key: "A constructor cannot contain a 'super' call when its class extends 'null'" },
};
} | An_export_assignment_cannot_have_modifiers: { code: 1120, category: DiagnosticCategory.Error, key: "An export assignment cannot have modifiers." },
Octal_literals_are_not_allowed_in_strict_mode: { code: 1121, category: DiagnosticCategory.Error, key: "Octal literals are not allowed in strict mode." },
A_tuple_type_element_list_cannot_be_empty: { code: 1122, category: DiagnosticCategory.Error, key: "A tuple type element list cannot be empty." },
Variable_declaration_list_cannot_be_empty: { code: 1123, category: DiagnosticCategory.Error, key: "Variable declaration list cannot be empty." },
|
kraken.rs | #[macro_use]
mod utils;
use test_case::test_case;
use crypto_crawler::*;
use crypto_markets::MarketType;
use utils::parse;
const EXCHANGE_NAME: &str = "kraken";
#[test_case(MarketType::Spot, "XBT/USD")]
fn test_crawl_trade(market_type: MarketType, symbol: &str) {
test_one_symbol!(
crawl_trade,
EXCHANGE_NAME,
market_type,
symbol,
MessageType::Trade
)
}
#[test_case(MarketType::Spot, "XBT/USD")]
fn test_crawl_l2_event(market_type: MarketType, symbol: &str) {
test_one_symbol!(
crawl_l2_event,
EXCHANGE_NAME,
market_type,
symbol,
MessageType::L2Event
)
}
#[test_case(MarketType::Spot, "XBT/USD")]
fn test_crawl_bbo(market_type: MarketType, symbol: &str) {
test_one_symbol!(
crawl_bbo,
EXCHANGE_NAME,
market_type,
symbol,
MessageType::BBO
)
}
#[test_case(MarketType::Spot, "XBT/USD")]
fn test_crawl_l2_snapshot(market_type: MarketType, symbol: &str) {
test_one_symbol!(
crawl_l2_snapshot,
EXCHANGE_NAME,
market_type,
symbol,
MessageType::L2Snapshot
)
}
#[test_case(MarketType::Spot)]
fn test_crawl_l2_snapshot_without_symbol(market_type: MarketType) {
test_all_symbols!(
crawl_l2_snapshot,
EXCHANGE_NAME,
market_type,
MessageType::L2Snapshot
)
}
#[test_case(MarketType::Spot, "XBT/USD")]
fn test_crawl_ticker(market_type: MarketType, symbol: &str) {
test_one_symbol!(
crawl_ticker,
EXCHANGE_NAME,
market_type,
symbol,
MessageType::Ticker
)
}
#[test_case(MarketType::Spot)]
fn test_crawl_candlestick(market_type: MarketType) | {
gen_test_crawl_candlestick!(EXCHANGE_NAME, market_type)
} |
|
profile_unix.go | // Copyright 2020 Aleksandar Radivojevic
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// +build !windows
package firefox
import (
"github.com/sandorex/ebd/common"
"github.com/sandorex/ebd/profile"
"path/filepath"
"strconv"
"strings"
)
// extractPID extracts PID from string using format that Firefox lockfile uses
// 'ADDR:+PID' where ADDR is an IP4 address
func extractPID(linkTarget string) (int, error) {
index := strings.LastIndex(linkTarget, ":+")
if index == -1 |
return strconv.Atoi(linkTarget[index+2:])
}
// GetProfileState reads profile state by reading the lockfile link if the
// lockfile doesn't exist the profile is closed, if it does but the PID is not
// a valid process then the profile has crashed
func (p Profile) GetProfileState() (profile.State, error) {
return common.ReadProfileStateFromLockfile(filepath.Join(p.path, FileLockfile), extractPID)
}
| {
// ':+' has not been found
return -1, nil
} |
types.py | import unittest
from trove_classifiers import classifiers
from .. import types
class TypesTest(unittest.TestCase):
def test_classifiers_are_valid(self) -> None:
for license in types.KNOWN_LICENSES:
if license.trove_classifier:
with self.subTest(msg=license.shortname):
self.assertTrue(license.trove_classifier in classifiers)
def test_all_licenses_classifiers_covered(self) -> None:
covered_licenses = [
license.trove_classifier for license in types.KNOWN_LICENSES
]
# Below licenses are to broad, not a license or not part of SPDX-license list
not_covered = [
"License :: DFSG approved",
"License :: Free For Educational Use",
"License :: Free For Home Use",
"License :: Free for non-commercial use",
"License :: Free To Use But Restricted",
"License :: Freely Distributable",
"License :: Freeware",
"License :: GUST Font License 1.0",
"License :: GUST Font License 2006-09-30",
"License :: Nokia Open Source License (NOKOS)",
"License :: OSI Approved :: Eiffel Forum License",
"License :: OSI Approved :: Jabber Open Source License",
"License :: OSI Approved :: MITRE Collaborative Virtual Workspace License (CVW)",
"License :: Other/Proprietary License",
"License :: Public Domain",
"License :: Repoze Public License",
]
for classifier in classifiers:
if classifier.startswith("License ::") and classifier not in not_covered:
| with self.subTest(msg=classifier):
self.assertTrue(classifier in covered_licenses) |
|
WindingDW2L.py | # -*- coding: utf-8 -*-
# File generated according to Generator/ClassesRef/Machine/WindingDW2L.csv
# WARNING! All changes made in this file will be lost!
"""Method code available at https://github.com/Eomys/pyleecan/tree/master/pyleecan/Methods/Machine/WindingDW2L
"""
from os import linesep
from sys import getsizeof
from logging import getLogger
from ._check import check_var, raise_
from ..Functions.get_logger import get_logger
from ..Functions.save import save
from ..Functions.copy import copy
from ..Functions.load import load_init_dict
from ..Functions.Load.import_class import import_class
from .WindingDW1L import WindingDW1L
# Import all class method
# Try/catch to remove unnecessary dependencies in unused method
try:
from ..Methods.Machine.WindingDW2L.get_dim_wind import get_dim_wind
except ImportError as error:
get_dim_wind = error
from ._check import InitUnKnowClassError
from .Conductor import Conductor
class WindingDW2L(WindingDW1L):
"""double layer overlapping integral distributed winding, radial coil superposition"""
VERSION = 1
NAME = "double layer distributed"
# cf Methods.Machine.WindingDW2L.get_dim_wind
if isinstance(get_dim_wind, ImportError):
get_dim_wind = property(
fget=lambda x: raise_(
ImportError(
"Can't use WindingDW2L method get_dim_wind: " + str(get_dim_wind)
)
)
)
else:
get_dim_wind = get_dim_wind
# save and copy methods are available in all object
save = save
copy = copy
# get_logger method is available in all object
get_logger = get_logger
def __init__(
self,
coil_pitch=5,
is_reverse_wind=False,
Nslot_shift_wind=0,
qs=3,
Ntcoil=7,
Npcpp=2,
type_connection=0,
p=3,
Lewout=0.015,
conductor=-1,
init_dict=None,
init_str=None,
):
"""Constructor of the class. Can be use in three ways :
- __init__ (arg1 = 1, arg3 = 5) every parameters have name and default values
for pyleecan type, -1 will call the default constructor
- __init__ (init_dict = d) d must be a dictionnary with property names as keys
- __init__ (init_str = s) s must be a string
s is the file path to load
ndarray or list can be given for Vector and Matrix
object or dict can be given for pyleecan Object"""
if init_str is not None: # Load from a file
init_dict = load_init_dict(init_str)[1]
if init_dict is not None: # Initialisation by dict
assert type(init_dict) is dict
# Overwrite default value with init_dict content
if "coil_pitch" in list(init_dict.keys()):
coil_pitch = init_dict["coil_pitch"]
if "is_reverse_wind" in list(init_dict.keys()):
is_reverse_wind = init_dict["is_reverse_wind"]
if "Nslot_shift_wind" in list(init_dict.keys()):
Nslot_shift_wind = init_dict["Nslot_shift_wind"]
if "qs" in list(init_dict.keys()):
qs = init_dict["qs"]
if "Ntcoil" in list(init_dict.keys()):
Ntcoil = init_dict["Ntcoil"]
if "Npcpp" in list(init_dict.keys()):
Npcpp = init_dict["Npcpp"]
if "type_connection" in list(init_dict.keys()):
type_connection = init_dict["type_connection"]
if "p" in list(init_dict.keys()):
p = init_dict["p"]
if "Lewout" in list(init_dict.keys()):
Lewout = init_dict["Lewout"]
if "conductor" in list(init_dict.keys()):
conductor = init_dict["conductor"]
# Set the properties (value check and convertion are done in setter)
# Call WindingDW1L init
super(WindingDW2L, self).__init__(
coil_pitch=coil_pitch,
is_reverse_wind=is_reverse_wind,
Nslot_shift_wind=Nslot_shift_wind,
qs=qs,
Ntcoil=Ntcoil,
Npcpp=Npcpp,
type_connection=type_connection,
p=p,
Lewout=Lewout,
conductor=conductor,
)
# The class is frozen (in WindingDW1L init), for now it's impossible to
# add new properties
def __str__(self):
"""Convert this object in a readeable string (for print)"""
WindingDW2L_str = ""
# Get the properties inherited from WindingDW1L
WindingDW2L_str += super(WindingDW2L, self).__str__()
return WindingDW2L_str
def __eq__(self, other):
"""Compare two objects (skip parent)"""
if type(other) != type(self):
return False
# Check the properties inherited from WindingDW1L
if not super(WindingDW2L, self).__eq__(other):
return False
return True
def | (self, other, name="self"):
"""Compare two objects and return list of differences"""
if type(other) != type(self):
return ["type(" + name + ")"]
diff_list = list()
# Check the properties inherited from WindingDW1L
diff_list.extend(super(WindingDW2L, self).compare(other, name=name))
return diff_list
def __sizeof__(self):
"""Return the size in memory of the object (including all subobject)"""
S = 0 # Full size of the object
# Get size of the properties inherited from WindingDW1L
S += super(WindingDW2L, self).__sizeof__()
return S
def as_dict(self):
"""Convert this object in a json seriable dict (can be use in __init__)"""
# Get the properties inherited from WindingDW1L
WindingDW2L_dict = super(WindingDW2L, self).as_dict()
# The class name is added to the dict for deserialisation purpose
# Overwrite the mother class name
WindingDW2L_dict["__class__"] = "WindingDW2L"
return WindingDW2L_dict
def _set_None(self):
"""Set all the properties to None (except pyleecan object)"""
# Set to None the properties inherited from WindingDW1L
super(WindingDW2L, self)._set_None()
| compare |
escalate_tickets.py | #!/usr/bin/python
"""
django-helpdesk - A Django powered ticket tracker for small enterprise.
(c) Copyright 2008 Jutda. All Rights Reserved. See LICENSE for details.
scripts/escalate_tickets.py - Easy way to escalate tickets based on their age,
designed to be run from Cron or similar.
"""
from __future__ import print_function
from datetime import timedelta, date
import getopt
from optparse import make_option
import sys
from django.core.management.base import BaseCommand, CommandError
from django.db.models import Q
from django.utils.translation import ugettext as _
try:
from django.utils import timezone
except ImportError:
from datetime import datetime as timezone
from helpdesk.models import Queue, Ticket, FollowUp, EscalationExclusion, TicketChange
from helpdesk.lib import send_templated_mail, safe_template_context
class Command(BaseCommand):
def __init__(self):
BaseCommand.__init__(self)
self.option_list = (
make_option(
'--queues',
help='Queues to include (default: all). Use queue slugs'),
make_option(
'--verboseescalation',
action='store_true',
default=False,
help='Display a list of dates excluded'),
)
def handle(self, *args, **options):
verbose = False
queue_slugs = None
queues = []
if 'verboseescalation' in options:
verbose = True
if 'queues' in options:
queue_slugs = options['queues']
if queue_slugs is not None:
queue_set = queue_slugs.split(',')
for queue in queue_set:
try:
Queue.objects.get(slug__exact=queue)
except Queue.DoesNotExist:
raise CommandError("Queue %s does not exist." % queue)
queues.append(queue) |
escalate_tickets(queues=queues, verbose=verbose)
def escalate_tickets(queues, verbose):
""" Only include queues with escalation configured """
queryset = Queue.objects.filter(escalate_days__isnull=False).exclude(escalate_days=0)
if queues:
queryset = queryset.filter(slug__in=queues)
for q in queryset:
last = date.today() - timedelta(days=q.escalate_days)
today = date.today()
workdate = last
days = 0
while workdate < today:
if EscalationExclusion.objects.filter(date=workdate).count() == 0:
days += 1
workdate = workdate + timedelta(days=1)
req_last_escl_date = date.today() - timedelta(days=days)
if verbose:
print("Processing: %s" % q)
for t in q.ticket_set.filter(
Q(status=Ticket.OPEN_STATUS) |
Q(status=Ticket.REOPENED_STATUS)
).exclude(
priority=1
).filter(
Q(on_hold__isnull=True) |
Q(on_hold=False)
).filter(
Q(last_escalation__lte=req_last_escl_date) |
Q(last_escalation__isnull=True, created__lte=req_last_escl_date)
):
t.last_escalation = timezone.now()
t.priority -= 1
t.save()
context = safe_template_context(t)
if t.submitter_email:
send_templated_mail(
'escalated_submitter',
context,
recipients=t.submitter_email,
sender=t.queue.from_address,
fail_silently=True,
)
if t.queue.updated_ticket_cc:
send_templated_mail(
'escalated_cc',
context,
recipients=t.queue.updated_ticket_cc,
sender=t.queue.from_address,
fail_silently=True,
)
if t.assigned_to:
send_templated_mail(
'escalated_owner',
context,
recipients=t.assigned_to.email,
sender=t.queue.from_address,
fail_silently=True,
)
if verbose:
print(" - Esclating %s from %s>%s" % (
t.ticket,
t.priority + 1,
t.priority
)
)
f = FollowUp(
ticket=t,
title='Ticket Escalated',
date=timezone.now(),
public=True,
comment=_('Ticket escalated after %s days' % q.escalate_days),
)
f.save()
tc = TicketChange(
followup=f,
field=_('Priority'),
old_value=t.priority + 1,
new_value=t.priority,
)
tc.save()
def usage():
print("Options:")
print(" --queues: Queues to include (default: all). Use queue slugs")
print(" --verboseescalation: Display a list of dates excluded")
if __name__ == '__main__':
try:
opts, args = getopt.getopt(sys.argv[1:], ['queues=', 'verboseescalation'])
except getopt.GetoptError:
usage()
sys.exit(2)
verbose = False
queue_slugs = None
queues = []
for o, a in opts:
if o == '--verboseescalation':
verbose = True
if o == '--queues':
queue_slugs = a
if queue_slugs is not None:
queue_set = queue_slugs.split(',')
for queue in queue_set:
try:
q = Queue.objects.get(slug__exact=queue)
except Queue.DoesNotExist:
print("Queue %s does not exist." % queue)
sys.exit(2)
queues.append(queue)
escalate_tickets(queues=queues, verbose=verbose) | |
params.go | // Copyright (c) 2013-2016 The btcsuite developers
// Copyright (c) 2015-2017 The Decred developers
// Copyright (c) 2018-2020 The Hcd developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package main
import (
"github.com/coolsnady/hcd/chaincfg"
"github.com/coolsnady/hcd/wire"
)
// activeNetParams is a pointer to the parameters specific to the
// currently active decred network.
var activeNetParams = &mainNetParams
// params is used to group parameters for various networks such as the main
// network and test networks.
type params struct {
*chaincfg.Params
rpcPort string
}
// mainNetParams contains parameters specific to the main network
// (wire.MainNet). NOTE: The RPC port is intentionally different than the
// reference implementation because hcd does not handle wallet requests. The
// separate wallet process listens on the well-known port and forwards requests
// it does not handle on to hcd. This approach allows the wallet process
// to emulate the full reference implementation RPC API.
var mainNetParams = params{
Params: &chaincfg.MainNetParams,
rpcPort: "14009",
}
// testNet2Params contains parameters specific to the test network (version 2)
// (wire.TestNet2).
var testNet2Params = params{
Params: &chaincfg.TestNet2Params,
rpcPort: "12009",
}
// simNetParams contains parameters specific to the simulation test network
// (wire.SimNet).
var simNetParams = params{
Params: &chaincfg.SimNetParams,
rpcPort: "13009",
}
// netName returns the name used when referring to a decred network. At the
// time of writing, hcd currently places blocks for testnet version 0 in the
// data and log directory "testnet", which does not match the Name field of the
// chaincfg parameters. This function can be used to override this directory name
// as "testnet2" when the passed active network matches wire.TestNet2.
//
// A proper upgrade to move the data and log directories for this network to
// "testnet" is planned for the future, at which point this function can be
// removed and the network parameter's name used instead.
func netName(chainParams *params) string | {
switch chainParams.Net {
case wire.TestNet2:
return "testnet2"
default:
return chainParams.Name
}
} |
|
sender.go | package jshapi
import (
"net/http"
"github.com/derekdowling/go-json-spec-handler"
"github.com/derekdowling/go-stdlogger"
)
/*
Sender is a function type definition that allows consumers to customize how they
send and log API responses.
*/
type Sender func(http.ResponseWriter, *http.Request, jsh.Sendable)
/*
DefaultSender is the default sender that will log 5XX errors that it encounters
in the process of sending a response.
*/
func DefaultSender(logger std.Logger) Sender | {
return func(w http.ResponseWriter, r *http.Request, sendable jsh.Sendable) {
sendableError, isType := sendable.(jsh.ErrorType)
if isType && sendableError.StatusCode() >= 500 {
logger.Printf("Returning ISE: %s\n", sendableError.Error())
}
sendError := jsh.Send(w, r, sendable)
if sendError != nil && sendError.Status >= 500 {
logger.Printf("Error sending response: %s\n", sendError.Error())
}
}
} |
|
tftest.py | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Simple Python wrapper for Terraform test fixtures.
See documentation in the TerraformTest class for usage. Terraform wrapping
inspired by https://github.com/beelit94/python-terraform
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import collections
import itertools
import json
import logging
import os
import shutil
import subprocess
import tempfile
import weakref
__version__ = '1.5.3'
_LOGGER = logging.getLogger('tftest')
TerraformCommandOutput = collections.namedtuple(
'TerraformCommandOutput', 'retcode out err')
TerraformStateResource = collections.namedtuple(
'TerraformStateResource', 'key provider type attributes depends_on raw')
class TerraformTestError(Exception):
pass
def parse_args(init_vars=None, tf_vars=None, targets=None, **kw):
"""Convert method arguments for use in Terraform commands.
Args:
init_vars: dict of key/values converted to -backend-config='k=v' form, or
string argument converted to -backend-config=arg
tf_vars: dict of key/values converted to -var k=v form.
**kw: converted to the appropriate Terraform flag.
Returns:
A list of command arguments for use with subprocess.
"""
cmd_args = []
if kw.get('auto_approve'):
cmd_args.append('-auto-approve')
if kw.get('backend') is False:
cmd_args.append('-backend=false')
if kw.get('color') is False:
cmd_args.append('-no-color')
if kw.get('force_copy'):
cmd_args.append('-force-copy')
if kw.get('input') is False:
cmd_args.append('-input=false')
if kw.get('json_format') is True:
cmd_args.append('-json')
if kw.get('lock') is False:
cmd_args.append('-lock=false')
if kw.get('plugin_dir'):
cmd_args += ['-plugin-dir', kw['plugin_dir']]
if kw.get('refresh') is False:
cmd_args.append('-refresh=false')
if isinstance(init_vars, dict):
cmd_args += ['-backend-config=\'{}={}\''.format(k, v)
for k, v in init_vars.items()]
elif isinstance(init_vars, str):
cmd_args += ['-backend-config', '{}'.format(init_vars)]
if tf_vars:
cmd_args += list(itertools.chain.from_iterable(
("-var", "{}={}".format(k, v)) for k, v in tf_vars.items()
))
if targets:
cmd_args += [("-target={}".format(t)) for t in targets]
if kw.get('tf_var_file'):
cmd_args.append('-var-file={}'.format(kw['tf_var_file']))
return cmd_args
class TerraformJSONBase(object):
"Base class for JSON wrappers."
def __init__(self, raw):
self._raw = raw
def __bytes__(self):
return bytes(self._raw)
def __len__(self):
return len(self._raw)
def __str__(self):
return str(self._raw)
class TerraformValueDict(TerraformJSONBase):
"Minimal wrapper to directly expose outputs or variables."
def __init__(self, raw):
super(TerraformValueDict, self).__init__(raw)
# only matters for outputs
self.sensitive = tuple(k for k, v in raw.items() if v.get('sensitive'))
def __getattr__(self, name):
return getattr(self._raw, name)
def __getitem__(self, name):
return self._raw[name].get('value')
def __contains__(self, name):
return name in self._raw
def | (self):
return iter(self._raw)
class TerraformPlanModule(TerraformJSONBase):
"Minimal wrapper for parsed plan output modules."
def __init__(self, raw):
super(TerraformPlanModule, self).__init__(raw)
prefix = raw.get('address', '')
self._strip = 0 if not prefix else len(prefix) + 1
self._modules = self._resources = None
@property
def child_modules(self):
if self._modules is None:
self._modules = dict((mod['address'][self._strip:], TerraformPlanModule(
mod)) for mod in self._raw.get('child_modules'))
return self._modules
@property
def resources(self):
if self._resources is None:
self._resources = dict((res['address'][self._strip:], res)
for res in self._raw.get('resources', []))
return self._resources
def __getitem__(self, name):
return self._raw[name]
def __contains__(self, name):
return name in self._raw
class TerraformPlanOutput(TerraformJSONBase):
"Minimal wrapper for Terraform plan JSON output."
def __init__(self, raw):
super(TerraformPlanOutput, self).__init__(raw)
planned_values = raw.get('planned_values', {})
self.root_module = TerraformPlanModule(
planned_values.get('root_module', {}))
self.outputs = TerraformValueDict(planned_values.get('outputs', {}))
self.resource_changes = dict((v['address'], v)
for v in self._raw['resource_changes'])
# there might be no variables defined
self.variables = TerraformValueDict(raw.get('variables', {}))
@property
def resources(self):
return self.root_module.resources
@property
def modules(self):
return self.root_module.child_modules
def __getattr__(self, name):
return self._raw[name]
class TerraformState(TerraformJSONBase):
"Minimal wrapper for Terraform state JSON format."
def __init__(self, raw):
super(TerraformState, self).__init__(raw)
self.outputs = TerraformValueDict(raw.get('outputs', {}))
self._resources = None
@property
def resources(self):
if not self._resources:
resources = {}
for res in self._raw['resources']:
name = '%s.%s.%s' % (
res.get('module'), res.get('type'), res.get('name'))
resources[name] = res
self._resources = resources
return self._resources
def __getattr__(self, name):
return self._raw[name]
class TerraformTest(object):
"""Helper class for use in testing Terraform modules.
This helper class can be used to set up fixtures in Terraform tests, so that
the usual Terraform commands (init, plan, apply, output, destroy) can be run
on a module. Configuration is done at instantiation first, by passing in the
Terraform root module path, and then in the setup method through files that
will be temporarily linked in the module, and Terraform variables.
The standard way of using this is by calling setup to configure the module
through temporarily linked Terraform files and variables, run one or more
Terraform commands, then check command output, state, or created resources
from individual tests.
The local .terraform directory (including local state) and any linked file
are removed when the instance is garbage collected. Destroy needs to be
called explicitly using destroy().
Args:
tfdir: the Terraform module directory to test, either an absolute path, or
relative to basedir.
basedir: optional base directory to use for relative paths, defaults to the
directory above the one this module lives in.
terraform: path to the Terraform command.
env: a dict with custom environment variables to pass to terraform.
"""
def __init__(self, tfdir, basedir=None, terraform='terraform', env=None):
"""Set Terraform folder to operate on, and optional base directory."""
self._basedir = basedir or os.getcwd()
self.terraform = terraform
self.tfdir = self._abspath(tfdir)
self.env = os.environ.copy()
if env is not None:
self.env.update(env)
@classmethod
def _cleanup(cls, tfdir, filenames, deep=True):
"""Remove linked files and .terraform folder at instance deletion."""
_LOGGER.debug('cleaning up %s %s', tfdir, filenames)
for filename in filenames:
path = os.path.join(tfdir, filename)
if os.path.islink(path):
os.unlink(path)
if not deep:
return
path = os.path.join(tfdir, '.terraform')
if os.path.isdir(path):
shutil.rmtree(path)
path = os.path.join(tfdir, 'terraform.tfstate')
if os.path.isfile(path):
os.unlink(path)
def _abspath(self, path):
"""Make relative path absolute from base dir."""
return path if path.startswith('/') else os.path.join(self._basedir, path)
def setup(self, extra_files=None, plugin_dir=None, init_vars=None,
backend=True, cleanup_on_exit=True):
"""Setup method to use in test fixtures.
This method prepares a new Terraform environment for testing the module
specified at init time, and returns init output.
Args:
extra_files: list of absolute or relative to base paths to be linked in
the root module folder
plugin_dir: path to a plugin directory to be used for Terraform init, eg
built with terraform-bundle
init_vars: Terraform backend configuration variables
backend: Terraform backend argument
cleanup_on_exit: remove .terraform and terraform.tfstate files on exit
Returns:
Terraform init output.
"""
# link extra files inside dir
filenames = []
for link_src in (extra_files or []):
link_src = self._abspath(link_src)
filename = os.path.basename(link_src)
if os.path.isfile(link_src):
link_dst = os.path.join(self.tfdir, filename)
try:
os.symlink(link_src, link_dst)
except FileExistsError as e: # pylint:disable=undefined-variable
_LOGGER.warning(e)
else:
_LOGGER.debug('linked %s', link_src)
filenames.append(filename)
else:
_LOGGER.warning('no such file {}'.format(link_src))
self._finalizer = weakref.finalize(
self, self._cleanup, self.tfdir, filenames, deep=cleanup_on_exit)
return self.init(plugin_dir=plugin_dir, init_vars=init_vars, backend=backend)
def init(self, input=False, color=False, force_copy=False, plugin_dir=None,
init_vars=None, backend=True):
"""Run Terraform init command."""
cmd_args = parse_args(input=input, color=color, backend=backend,
force_copy=force_copy, plugin_dir=plugin_dir,
init_vars=init_vars)
return self.execute_command('init', *cmd_args).out
def plan(self, input=False, color=False, refresh=True, tf_vars=None, targets=None, output=False, tf_var_file=None):
"Run Terraform plan command, optionally returning parsed plan output."
cmd_args = parse_args(input=input, color=color,
refresh=refresh, tf_vars=tf_vars,
targets=targets, tf_var_file=tf_var_file)
if not output:
return self.execute_command('plan', *cmd_args).out
with tempfile.NamedTemporaryFile() as fp:
cmd_args.append('-out={}'.format(fp.name))
self.execute_command('plan', *cmd_args)
result = self.execute_command('show', '-no-color', '-json', fp.name)
try:
return TerraformPlanOutput(json.loads(result.out))
except json.JSONDecodeError as e:
raise TerraformTestError('Error decoding plan output: {}'.format(e))
def apply(self, input=False, color=False, auto_approve=True, tf_vars=None, targets=None, tf_var_file=None):
"""Run Terraform apply command."""
cmd_args = parse_args(input=input, color=color,
auto_approve=auto_approve, tf_vars=tf_vars,
targets=targets, tf_var_file=tf_var_file)
return self.execute_command('apply', *cmd_args).out
def output(self, name=None, color=False, json_format=True):
"""Run Terraform output command."""
cmd_args = []
if name:
cmd_args.append(name)
cmd_args += parse_args(color=color, json_format=json_format)
output = self.execute_command('output', *cmd_args).out
_LOGGER.debug('output %s', output)
if json_format:
try:
output = TerraformValueDict(json.loads(output))
except json.JSONDecodeError as e:
_LOGGER.warning('error decoding output: {}'.format(e))
return output
def destroy(self, color=False, auto_approve=True, tf_vars=None, targets=None, tf_var_file=None):
"""Run Terraform destroy command."""
cmd_args = parse_args(color=color, auto_approve=auto_approve,
tf_vars=tf_vars, targets=targets,
tf_var_file=tf_var_file)
return self.execute_command('destroy', *cmd_args).out
def refresh(self, color=False, lock=False, tf_vars=None, targets=None):
"""Run Terraform refresh command."""
cmd_args = parse_args(color=color, lock=lock,
tf_vars=tf_vars, targets=targets)
return self.execute_command('refresh', *cmd_args).out
def state_pull(self):
"""Pull state."""
state = self.execute_command('state', 'pull')
try:
state = TerraformState(json.loads(state.out))
except json.JSONDecodeError as e:
_LOGGER.warning('error decoding state: {}'.format(e))
return state
def execute_command(self, cmd, *cmd_args):
"""Run arbitrary Terraform command."""
_LOGGER.debug([cmd, cmd_args])
cmdline = [self.terraform, cmd]
cmdline += cmd_args
try:
p = subprocess.Popen(cmdline, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, cwd=self.tfdir, env=self.env)
except FileNotFoundError as e:
raise TerraformTestError('Terraform executable not found: %s' % e)
out, err = p.communicate()
out = out.decode('utf-8', errors='ignore')
err = err.decode('utf-8', errors='ignore')
retcode = p.returncode
if retcode == 1:
message = 'Error running command {command}: {retcode} {out} {err}'.format(
command=cmd, retcode=retcode, out=out, err=err)
_LOGGER.critical(message)
raise TerraformTestError(message)
return TerraformCommandOutput(retcode, out, err)
| __iter__ |
mod.rs | //! terminal helpers
//!
mod config;
pub mod emoji;
#[macro_use]
pub mod style;
use console;
use dialoguer;
use indicatif;
pub use self::config::{ColorChoice, Config};
use std::{
error::Error,
io::{self, Write},
};
pub const DEFAULT_TERM_WIDTH: usize = 80;
pub const DEFAULT_TERM_HEIGHT: usize = 24;
pub struct Style {
pub error: console::Style,
pub warning: console::Style,
pub success: console::Style,
pub info: console::Style,
}
impl Style {
fn new(color_choice: &ColorChoice) -> Self {
match color_choice {
ColorChoice::Auto => { /* do nothing */ }
ColorChoice::Never => console::set_colors_enabled(false),
ColorChoice::Always => console::set_colors_enabled(true),
};
Style {
error: console::Style::new().red().bold(),
warning: console::Style::new().red(),
success: console::Style::new().green(),
info: console::Style::new().cyan().italic(),
}
}
}
pub struct Term {
/// the user's configuration of the terminal
pub config: Config,
pub style: Style,
pub term: console::Term,
}
impl Term {
pub fn new(config: Config) -> Self {
// make sure we are using a terminal for now
if !console::user_attended() {
warn!("There might be issue with non user attended terminal");
}
let term = console::Term::stdout();
let style = Style::new(&config.color);
Term {
config,
term,
style,
}
}
pub fn progress_bar(&self, count: u64) -> indicatif::ProgressBar |
pub fn prompt(&mut self, prompt: &str) -> io::Result<String> {
dialoguer::Input::new().with_prompt(prompt).interact()
}
pub fn password(&mut self, prompt: &str) -> io::Result<String> {
#[cfg(windows)]
{
// TODO: there seems to be an issue with rust crate: console
// the password read line is not working or not returning
// at all on windows 10 's `cmd` or `PowerShell`
let line = dialoguer::Input::new()
.with_prompt(prompt)
.default("".to_owned())
.interact()?;
self.term.move_cursor_up(1)?;
self.term.clear_line()?;
Ok(line)
}
#[cfg(not(windows))]
{
dialoguer::PasswordInput::new()
.with_prompt(prompt)
.allow_empty_password(true)
.interact()
}
}
pub fn new_password(
&mut self,
prompt: &str,
confirmation: &str,
mismatch_err: &str,
) -> io::Result<String> {
#[cfg(windows)]
{
loop {
// TODO: there seems to be an issue with rust crate: console
// the password read line is not working or not returning
// at all on windows 10 's `cmd` or `PowerShell`
let line = dialoguer::Input::new()
.with_prompt(prompt)
.default("".to_owned())
.interact()?;
self.term.move_cursor_up(1)?;
self.term.clear_line()?;
let line2 = dialoguer::Input::new()
.with_prompt(confirmation)
.default("".to_owned())
.interact()?;
self.term.move_cursor_up(1)?;
self.term.clear_line()?;
if line == line2 {
return Ok(line);
}
self.error(mismatch_err)?;
}
}
#[cfg(not(windows))]
{
dialoguer::PasswordInput::new()
.with_prompt(prompt)
.allow_empty_password(true)
.with_confirmation(confirmation, mismatch_err)
.interact()
}
}
pub fn simply(&mut self, msg: &str) -> io::Result<()> {
write!(self, "{}", msg)
}
pub fn success(&mut self, msg: &str) -> io::Result<()> {
write!(&mut self.term, "{}", self.style.success.apply_to(msg))
}
pub fn info(&mut self, msg: &str) -> io::Result<()> {
write!(&mut self.term, "{}", self.style.info.apply_to(msg))
}
pub fn warn(&mut self, msg: &str) -> io::Result<()> {
write!(&mut self.term, "{}", self.style.warning.apply_to(msg))
}
pub fn error(&mut self, msg: &str) -> io::Result<()> {
write!(&mut self.term, "{}", self.style.error.apply_to(msg))
}
pub fn fail_with<E>(&mut self, e: E) -> !
where
E: Error,
{
let mut error: &Error = &e;
let formated = format!("{}", e);
writeln!(&mut self.term, "{}", self.style.error.apply_to(formated));
while let Some(err) = error.cause() {
error = err;
let formated = format!("{}", err);
writeln!(
&mut self.term,
" |-> {}",
self.style.warning.apply_to(formated)
);
}
::std::process::exit(1)
}
}
impl ::std::ops::Deref for Term {
type Target = console::Term;
fn deref(&self) -> &Self::Target {
&self.term
}
}
impl ::std::ops::DerefMut for Term {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.term
}
}
impl io::Write for Term {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
io::Write::write(&mut self.term, buf)
}
fn flush(&mut self) -> io::Result<()> {
io::Write::flush(&mut self.term)
}
}
impl io::Read for Term {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
io::Read::read(&mut self.term, buf)
}
}
| {
let pb = indicatif::ProgressBar::new(count);
pb.enable_steady_tick(100);
pb.set_style(
indicatif::ProgressStyle::default_bar()
.template(
"{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {pos}/{len} ({eta})",
)
.progress_chars("#>-"),
);
pb
} |
build_recorder.py | # SPDX-License-Identifier: Apache-2.0
#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
import logging
import os
import shutil
from build_workflow.build_artifact_checks import BuildArtifactChecks
from manifests.build_manifest import BuildManifest
class BuildRecorder:
def __init__(self, target):
self.build_manifest = self.BuildManifestBuilder(target)
self.target = target
self.name = target.name
def record_component(self, component_name, git_repo):
self.build_manifest.append_component(
component_name,
self.target.component_version,
git_repo.url,
git_repo.ref,
git_repo.sha,
)
def record_artifact(
self, component_name, artifact_type, artifact_path, artifact_file
):
logging.info(
f"Recording {artifact_type} artifact for {component_name}: {artifact_path} (from {artifact_file})"
)
# Ensure the target directory exists
dest_file = os.path.join(self.target.output_dir, artifact_path)
dest_dir = os.path.dirname(dest_file)
os.makedirs(dest_dir, exist_ok=True)
# Check artifact
BuildArtifactChecks.check(self.target, artifact_type, artifact_file)
# Copy the file
shutil.copyfile(artifact_file, dest_file)
# Notify the recorder
self.build_manifest.append_artifact(
component_name, artifact_type, artifact_path
)
def get_manifest(self):
|
def write_manifest(self):
manifest_path = os.path.join(self.target.output_dir, "manifest.yml")
self.get_manifest().to_file(manifest_path)
logging.info(f"Created build manifest {manifest_path}")
class BuildManifestBuilder:
def __init__(self, target):
self.data = {}
self.data["build"] = {}
self.data["build"]["id"] = target.build_id
self.data["build"]["name"] = target.name
self.data["build"]["version"] = target.opensearch_version
self.data["build"]["architecture"] = target.arch
self.data["schema-version"] = "1.1"
self.components_hash = {}
def append_component(self, name, version, repository_url, ref, commit_id):
component = {
"name": name,
"repository": repository_url,
"ref": ref,
"commit_id": commit_id,
"artifacts": {},
"version": version,
}
self.components_hash[name] = component
def append_artifact(self, component, type, path):
artifacts = self.components_hash[component]["artifacts"]
list = artifacts.get(type, [])
if len(list) == 0:
artifacts[type] = list
list.append(path)
def to_manifest(self):
# The build manifest expects `components` to be a list, not a hash, so we need to munge things a bit
components = self.components_hash.values()
if len(components) > 0:
self.data["components"] = list(components)
return BuildManifest(self.data)
| return self.build_manifest.to_manifest() |
demo1.py | # true if n is prime
def | (n):
if n <= 1 or int(n) != n:
return False
for x in range(2, int(n*.5)+1):
if n%x == 0:
return False
return True
| isPrime |
base.rs | pub(crate) mod shape;
use crate::context::CommandRegistry;
use crate::evaluate::evaluate_baseline_expr;
use bigdecimal::BigDecimal;
use chrono::{DateTime, Utc};
use derive_new::new;
use log::trace;
use nu_errors::ShellError;
use nu_parser::{hir, CompareOperator};
use nu_protocol::{
Evaluate, EvaluateTrait, Primitive, Scope, ShellTypeName, SpannedTypeName, TaggedDictBuilder,
UntaggedValue, Value,
};
use nu_source::{Tag, Text};
use nu_value_ext::ValueExt;
use num_bigint::BigInt;
use num_traits::Zero;
use query_interface::{interfaces, vtable_for, ObjectHash};
use serde::{Deserialize, Serialize};
use std::time::SystemTime;
#[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Clone, new, Serialize)]
pub struct Operation {
pub(crate) left: Value,
pub(crate) operator: CompareOperator,
pub(crate) right: Value,
}
#[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Clone, Hash, Serialize, Deserialize, new)]
pub struct Block {
pub(crate) expressions: Vec<hir::SpannedExpression>,
pub(crate) source: Text,
pub(crate) tag: Tag,
}
interfaces!(Block: dyn ObjectHash);
#[typetag::serde]
impl EvaluateTrait for Block {
fn invoke(&self, scope: &Scope) -> Result<Value, ShellError> {
if self.expressions.is_empty() {
return Ok(UntaggedValue::nothing().into_value(&self.tag));
}
let mut last = Ok(UntaggedValue::nothing().into_value(&self.tag));
trace!(
"EXPRS = {:?}",
self.expressions
.iter()
.map(|e| format!("{:?}", e))
.collect::<Vec<_>>()
);
for expr in self.expressions.iter() {
last = evaluate_baseline_expr(&expr, &CommandRegistry::empty(), &scope, &self.source)
}
last
}
fn clone_box(&self) -> Evaluate {
let block = self.clone();
Evaluate::new(block)
}
}
#[derive(Serialize, Deserialize)]
pub enum Switch {
Present,
Absent,
}
impl std::convert::TryFrom<Option<&Value>> for Switch {
type Error = ShellError;
fn try_from(value: Option<&Value>) -> Result<Switch, ShellError> {
match value {
None => Ok(Switch::Absent),
Some(value) => match &value.value {
UntaggedValue::Primitive(Primitive::Boolean(true)) => Ok(Switch::Present),
_ => Err(ShellError::type_error("Boolean", value.spanned_type_name())),
},
}
}
}
#[allow(unused)]
pub(crate) fn select_fields(obj: &Value, fields: &[String], tag: impl Into<Tag>) -> Value {
let mut out = TaggedDictBuilder::new(tag);
let descs = obj.data_descriptors();
for column_name in fields {
match descs.iter().find(|d| *d == column_name) {
None => out.insert_untagged(column_name, UntaggedValue::nothing()),
Some(desc) => out.insert_value(desc.clone(), obj.get_data(desc).borrow().clone()),
}
}
out.into_value()
}
pub(crate) fn reject_fields(obj: &Value, fields: &[String], tag: impl Into<Tag>) -> Value {
let mut out = TaggedDictBuilder::new(tag);
let descs = obj.data_descriptors();
for desc in descs {
if fields.iter().any(|field| *field == desc) {
continue;
} else {
out.insert_value(desc.clone(), obj.get_data(&desc).borrow().clone())
}
}
out.into_value()
}
pub(crate) enum CompareValues {
Ints(BigInt, BigInt),
Decimals(BigDecimal, BigDecimal),
String(String, String),
Date(DateTime<Utc>, DateTime<Utc>),
DateDuration(DateTime<Utc>, u64),
}
impl CompareValues {
pub fn compare(&self) -> std::cmp::Ordering {
match self {
CompareValues::Ints(left, right) => left.cmp(right),
CompareValues::Decimals(left, right) => left.cmp(right),
CompareValues::String(left, right) => left.cmp(right),
CompareValues::Date(left, right) => left.cmp(right),
CompareValues::DateDuration(left, right) => {
use std::time::Duration;
// Create the datetime we're comparing against, as duration is an offset from now
let right: DateTime<Utc> = (SystemTime::now() - Duration::from_secs(*right)).into();
right.cmp(left)
}
}
}
}
pub(crate) fn coerce_compare(
left: &UntaggedValue,
right: &UntaggedValue,
) -> Result<CompareValues, (&'static str, &'static str)> {
match (left, right) {
(UntaggedValue::Primitive(left), UntaggedValue::Primitive(right)) => {
coerce_compare_primitive(left, right)
}
_ => Err((left.type_name(), right.type_name())),
}
}
fn coerce_compare_primitive(
left: &Primitive,
right: &Primitive,
) -> Result<CompareValues, (&'static str, &'static str)> {
use Primitive::*;
Ok(match (left, right) {
(Int(left), Int(right)) => CompareValues::Ints(left.clone(), right.clone()),
(Int(left), Decimal(right)) => {
CompareValues::Decimals(BigDecimal::zero() + left, right.clone())
}
(Int(left), Bytes(right)) => CompareValues::Ints(left.clone(), BigInt::from(*right)),
(Decimal(left), Decimal(right)) => CompareValues::Decimals(left.clone(), right.clone()),
(Decimal(left), Int(right)) => {
CompareValues::Decimals(left.clone(), BigDecimal::zero() + right)
}
(Decimal(left), Bytes(right)) => {
CompareValues::Decimals(left.clone(), BigDecimal::from(*right))
}
(Bytes(left), Int(right)) => CompareValues::Ints(BigInt::from(*left), right.clone()),
(Bytes(left), Decimal(right)) => {
CompareValues::Decimals(BigDecimal::from(*left), right.clone())
}
(String(left), String(right)) => CompareValues::String(left.clone(), right.clone()),
(Line(left), String(right)) => CompareValues::String(left.clone(), right.clone()),
(String(left), Line(right)) => CompareValues::String(left.clone(), right.clone()),
(Line(left), Line(right)) => CompareValues::String(left.clone(), right.clone()),
(Date(left), Date(right)) => CompareValues::Date(*left, *right),
(Date(left), Duration(right)) => CompareValues::DateDuration(*left, *right),
_ => return Err((left.type_name(), right.type_name())),
})
}
#[cfg(test)]
mod tests {
use indexmap::IndexMap;
use nu_errors::ShellError;
use nu_protocol::{ColumnPath as ColumnPathValue, PathMember, UntaggedValue, Value};
use nu_source::*;
use nu_value_ext::{as_column_path, ValueExt};
use num_bigint::BigInt;
fn string(input: impl Into<String>) -> Value {
UntaggedValue::string(input.into()).into_untagged_value()
}
fn int(input: impl Into<BigInt>) -> Value {
UntaggedValue::int(input.into()).into_untagged_value()
}
fn row(entries: IndexMap<String, Value>) -> Value {
UntaggedValue::row(entries).into_untagged_value()
}
fn table(list: &[Value]) -> Value {
UntaggedValue::table(list).into_untagged_value()
}
fn error_callback(
reason: &'static str,
) -> impl FnOnce((&Value, &PathMember, ShellError)) -> ShellError {
move |(_obj_source, _column_path_tried, _err)| ShellError::unimplemented(reason)
}
fn column_path(paths: &[Value]) -> Result<Tagged<ColumnPathValue>, ShellError> {
as_column_path(&table(paths))
}
#[test]
fn gets_matching_field_from_a_row() -> Result<(), ShellError> {
let row = UntaggedValue::row(indexmap! {
"amigos".into() => table(&[string("andres"),string("jonathan"),string("yehuda")])
})
.into_untagged_value();
assert_eq!(
row.get_data_by_key("amigos".spanned_unknown())
.ok_or_else(|| ShellError::unexpected("Failure during testing"))?,
table(&[string("andres"), string("jonathan"), string("yehuda")])
);
Ok(())
}
#[test]
fn gets_matching_field_from_nested_rows_inside_a_row() -> Result<(), ShellError> {
let field_path = column_path(&[string("package"), string("version")]);
let (version, tag) = string("0.4.0").into_parts();
let value = UntaggedValue::row(indexmap! {
"package".into() =>
row(indexmap! {
"name".into() => string("nu"),
"version".into() => string("0.4.0")
})
});
assert_eq!(
*value.into_value(tag).get_data_by_column_path(
&field_path?.item,
Box::new(error_callback("package.version"))
)?,
version
);
Ok(())
}
#[test]
fn gets_first_matching_field_from_rows_with_same_field_inside_a_table() -> Result<(), ShellError>
{
let field_path = column_path(&[string("package"), string("authors"), string("name")]);
let (_, tag) = string("Andrés N. Robalino").into_parts();
let value = UntaggedValue::row(indexmap! {
"package".into() => row(indexmap! {
"name".into() => string("nu"),
"version".into() => string("0.4.0"),
"authors".into() => table(&[
row(indexmap!{"name".into() => string("Andrés N. Robalino")}),
row(indexmap!{"name".into() => string("Jonathan Turner")}),
row(indexmap!{"name".into() => string("Yehuda Katz")})
])
})
});
assert_eq!(
value.into_value(tag).get_data_by_column_path(
&field_path?.item,
Box::new(error_callback("package.authors.name"))
)?,
table(&[
string("Andrés N. Robalino"),
string("Jonathan Turner"),
string("Yehuda Katz")
])
);
Ok(())
}
#[test]
fn col | -> Result<(), ShellError> {
let field_path = column_path(&[string("package"), string("authors"), int(0)]);
let (_, tag) = string("Andrés N. Robalino").into_parts();
let value = UntaggedValue::row(indexmap! {
"package".into() => row(indexmap! {
"name".into() => string("nu"),
"version".into() => string("0.4.0"),
"authors".into() => table(&[
row(indexmap!{"name".into() => string("Andrés N. Robalino")}),
row(indexmap!{"name".into() => string("Jonathan Turner")}),
row(indexmap!{"name".into() => string("Yehuda Katz")})
])
})
});
assert_eq!(
*value.into_value(tag).get_data_by_column_path(
&field_path?.item,
Box::new(error_callback("package.authors.0"))
)?,
UntaggedValue::row(indexmap! {
"name".into() => string("Andrés N. Robalino")
})
);
Ok(())
}
#[test]
fn column_path_that_contains_just_a_number_gets_a_row_from_a_row() -> Result<(), ShellError> {
let field_path = column_path(&[string("package"), string("authors"), string("0")]);
let (_, tag) = string("Andrés N. Robalino").into_parts();
let value = UntaggedValue::row(indexmap! {
"package".into() => row(indexmap! {
"name".into() => string("nu"),
"version".into() => string("0.4.0"),
"authors".into() => row(indexmap! {
"0".into() => row(indexmap!{"name".into() => string("Andrés N. Robalino")}),
"1".into() => row(indexmap!{"name".into() => string("Jonathan Turner")}),
"2".into() => row(indexmap!{"name".into() => string("Yehuda Katz")}),
})
})
});
assert_eq!(
*value.into_value(tag).get_data_by_column_path(
&field_path?.item,
Box::new(error_callback("package.authors.\"0\""))
)?,
UntaggedValue::row(indexmap! {
"name".into() => string("Andrés N. Robalino")
})
);
Ok(())
}
#[test]
fn replaces_matching_field_from_a_row() -> Result<(), ShellError> {
let field_path = column_path(&[string("amigos")]);
let sample = UntaggedValue::row(indexmap! {
"amigos".into() => table(&[
string("andres"),
string("jonathan"),
string("yehuda"),
]),
});
let replacement = string("jonas");
let actual = sample
.into_untagged_value()
.replace_data_at_column_path(&field_path?.item, replacement)
.ok_or_else(|| ShellError::untagged_runtime_error("Could not replace column"))?;
assert_eq!(actual, row(indexmap! {"amigos".into() => string("jonas")}));
Ok(())
}
#[test]
fn replaces_matching_field_from_nested_rows_inside_a_row() -> Result<(), ShellError> {
let field_path = column_path(&[
string("package"),
string("authors"),
string("los.3.caballeros"),
]);
let sample = UntaggedValue::row(indexmap! {
"package".into() => row(indexmap! {
"authors".into() => row(indexmap! {
"los.3.mosqueteros".into() => table(&[string("andres::yehuda::jonathan")]),
"los.3.amigos".into() => table(&[string("andres::yehuda::jonathan")]),
"los.3.caballeros".into() => table(&[string("andres::yehuda::jonathan")])
})
})
});
let replacement = table(&[string("yehuda::jonathan::andres")]);
let tag = replacement.tag.clone();
let actual = sample
.into_value(&tag)
.replace_data_at_column_path(&field_path?.item, replacement.clone())
.ok_or_else(|| {
ShellError::labeled_error(
"Could not replace column",
"could not replace column",
&tag,
)
})?;
assert_eq!(
actual,
UntaggedValue::row(indexmap! {
"package".into() => row(indexmap! {
"authors".into() => row(indexmap! {
"los.3.mosqueteros".into() => table(&[string("andres::yehuda::jonathan")]),
"los.3.amigos".into() => table(&[string("andres::yehuda::jonathan")]),
"los.3.caballeros".into() => replacement})})})
.into_value(tag)
);
Ok(())
}
#[test]
fn replaces_matching_field_from_rows_inside_a_table() -> Result<(), ShellError> {
let field_path = column_path(&[
string("shell_policy"),
string("releases"),
string("nu.version.arepa"),
]);
let sample = UntaggedValue::row(indexmap! {
"shell_policy".into() => row(indexmap! {
"releases".into() => table(&[
row(indexmap! {
"nu.version.arepa".into() => row(indexmap! {
"code".into() => string("0.4.0"), "tag_line".into() => string("GitHub-era")
})
}),
row(indexmap! {
"nu.version.taco".into() => row(indexmap! {
"code".into() => string("0.3.0"), "tag_line".into() => string("GitHub-era")
})
}),
row(indexmap! {
"nu.version.stable".into() => row(indexmap! {
"code".into() => string("0.2.0"), "tag_line".into() => string("GitHub-era")
})
})
])
})
});
let replacement = row(indexmap! {
"code".into() => string("0.5.0"),
"tag_line".into() => string("CABALLEROS")
});
let tag = replacement.tag.clone();
let actual = sample
.into_value(tag.clone())
.replace_data_at_column_path(&field_path?.item, replacement.clone())
.ok_or_else(|| {
ShellError::labeled_error(
"Could not replace column",
"could not replace column",
&tag,
)
})?;
assert_eq!(
actual,
UntaggedValue::row(indexmap! {
"shell_policy".into() => row(indexmap! {
"releases".into() => table(&[
row(indexmap! {
"nu.version.arepa".into() => replacement
}),
row(indexmap! {
"nu.version.taco".into() => row(indexmap! {
"code".into() => string("0.3.0"), "tag_line".into() => string("GitHub-era")
})
}),
row(indexmap! {
"nu.version.stable".into() => row(indexmap! {
"code".into() => string("0.2.0"), "tag_line".into() => string("GitHub-era")
})
})
])
})
}).into_value(&tag)
);
Ok(())
}
}
| umn_path_that_contains_just_a_number_gets_a_row_from_a_table() |
TodoFilters.js | // @ts-check
/* global HTMLUListElement */
/* global location */
/* global self */
/**
* TodoFilters are the filters All, Active and Completed
*
* @export
* @class TodoFilters
*/
export default class | extends HTMLUListElement {
constructor () {
super()
this.hashchangeListener = event => this.as.forEach(a => a.classList[location.hash === a.getAttribute('href') ? 'add' : 'remove']('selected'))
}
connectedCallback () {
self.addEventListener('hashchange', this.hashchangeListener)
this.hashchangeListener()
}
disconnectedCallback () {
self.removeEventListener('hashchange', this.hashchangeListener)
}
get as () {
return Array.from(this.querySelectorAll('a'))
}
}
| TodoFilters |
process_results_impl.rs | /// An iterator that produces only the `T` values as long as the
/// inner iterator produces `Ok(T)`.
///
/// Used by [`process_results`](../fn.process_results.html), see its docs
/// for more information.
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
#[derive(Debug)]
pub struct ProcessResults<'a, I, E: 'a> {
error: &'a mut Result<(), E>,
iter: I,
}
impl<'a, I, T, E> Iterator for ProcessResults<'a, I, E>
where I: Iterator<Item = Result<T, E>>
{
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
match self.iter.next() {
Some(Ok(x)) => Some(x),
Some(Err(e)) => {
*self.error = Err(e);
None
}
None => None,
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let (_, hi) = self.iter.size_hint();
(0, hi)
}
}
/// “Lift” a function of the values of an iterator so that it can process
/// an iterator of `Result` values instead.
///
/// `iterable` is an iterator or iterable with `Result<T, E>` elements, where
/// `T` is the value type and `E` the error type.
///
/// `processor` is a closure that receives an adapted version of the iterable
/// as the only argument — the adapted iterator produces elements of type `T`,
/// as long as the original iterator produces `Ok` values.
/// | /// iterator ends and the `process_results` function will return the
/// error iself.
///
/// Otherwise, the return value from the closure is returned wrapped
/// inside `Ok`.
///
/// # Example
///
/// ```
/// use itertools::process_results;
///
/// type R = Result<i32, &'static str>;
///
/// let first_values: Vec<R> = vec![Ok(1), Ok(0), Ok(3)];
/// let second_values: Vec<R> = vec![Ok(2), Ok(1), Err("overflow")];
///
/// // “Lift” the iterator .max() method to work on the values in Results using process_results
///
/// let first_max = process_results(first_values, |iter| iter.max().unwrap_or(0));
/// let second_max = process_results(second_values, |iter| iter.max().unwrap_or(0));
///
/// assert_eq!(first_max, Ok(3));
/// assert!(second_max.is_err());
/// ```
pub fn process_results<I, F, T, E, R>(iterable: I, processor: F) -> Result<R, E>
where I: IntoIterator<Item = Result<T, E>>,
F: FnOnce(ProcessResults<I::IntoIter, E>) -> R
{
let iter = iterable.into_iter();
let mut error = Ok(());
let result = processor(ProcessResults { error: &mut error, iter: iter });
error.map(|_| result)
} | /// If the original iterable produces an error at any point, the adapted |
genome.rs | use crate::{NeatParams, NeuralNetwork};
/// Implementing `Genome` conceptually means that the implementor "has a
/// genome", and the implementor can be called an "organism".
pub trait Genome: Clone + Default + Send + std::fmt::Debug {
/// Returns a new organism which is a clone of `&self` apart from possible
/// mutations
fn mutate(&mut self, innovation_id: &mut usize, p: &NeatParams);
/// `fittest` is true if `other` is more fit.
fn mate(&self, other: &Self, fittest: bool, p: &NeatParams) -> Self;
/// TODO: how should it be implemented for e.g. a composed organism?
fn distance(&self, other: &Self, p: &NeatParams) -> f64;
/// Compare another Genome for species equality
// TODO This should be impl Eq
fn is_same_specie(&self, other: &Self, p: &NeatParams) -> bool {
self.distance(other, p) < p.compatibility_threshold
}
}
/// Used in algorithm just to group an organism (genome) with its fitness, and
/// also in the interface to get the fitness of organisms
#[derive(Default, Clone, Debug)]
pub struct Organism<G = NeuralNetwork> {
/// The genome of this organism
pub genome: G,
/// The fitness calculated as part of the NEAT algorithm
pub fitness: f64,
}
impl<G: Genome> Organism<G> {
/// Create a new organism with fitness 0.0.
pub fn new(organism: G) -> Organism<G> {
Organism {
genome: organism,
fitness: 0.0,
}
}
/// Returns a cloned `Organism` with a mutated genome
pub fn mutate(&mut self, innovation_id: &mut usize, p: &NeatParams) {
self.genome.mutate(innovation_id, p)
}
/// Mate with another organism -- this mates the two genomes.
pub fn | (&self, other: &Self, p: &NeatParams) -> Organism<G> {
Organism::new(
self.genome
.mate(&other.genome, self.fitness > other.fitness, p),
)
}
///
pub fn distance(&self, other: &Self, p: &NeatParams) -> f64 {
self.genome.distance(&other.genome, p)
}
}
| mate |
growing.py | from manimlib.animation.transform import Transform
from manimlib.basic.basic_function import to_expand_lists, to_get_point
from manimlib.constants import PI
from manimlib.utils.config_ops import generate_args, merge_config_kwargs
class GrowFromPoint(Transform):
def __init__(self, mobject, mobject_or_point="get_center()", *args, **kwargs):
self.mobject_or_point = to_get_point(mobject_or_point, mobject)
self.args_name = ["point_color", "scale"]
self.args = [None, 0]
[self.point_color, self.scale] = \
generate_args(self, args, self.args)
kwargs = merge_config_kwargs(self, kwargs, self.args_name)
super().__init__(mobject, **kwargs)
def create_target(self):
return self.mobject
def create_starting_mobject(self):
mobject = self.create_initial_mobject()
mobject.set_stroke(
width=(mobject.stroke_width*self.scale))
if self.point_color:
mobject.set_color(self.point_color)
return mobject
def create_initial_mobject(self):
mobject = super().create_starting_mobject()
return mobject.scale(self.scale).move_to(self.mobject_or_point)
class GrowFromCenter(GrowFromPoint):
def __init__(self, mobject, *args, **kwargs):
super().__init__(mobject, mobject.get_center(), *args, **kwargs)
class GrowFromEdge(GrowFromPoint):
def __init__(self, mobject, edge=[-1, 1, 0], *args, **kwargs):
super().__init__(mobject, mobject.get_critical_point(edge), *args, **kwargs)
class GrowFromSide(GrowFromPoint):
def __init__(self, mobject, side=[0, 1, 0], center=False, *args, **kwargs):
self.side = side
self.center = center
super().__init__(mobject, mobject.get_critical_point(side), *args, **kwargs)
def create_initial_mobject(self):
mobject = self.mobject.copy()
dim = [i for i, each in enumerate(self.side) if each]
mobject.stretch_to_fit(to_expand_lists(self.scale, dim), dim)
if not self.center:
mobject.move_to(self.mobject_or_point)
else:
mobject.move_to(self.mobject.get_center())
return mobject
class DiminishToPoint(GrowFromPoint):
def __init__(self, mobject, mobject_or_point="get_center()", *args, **kwargs):
super().__init__(mobject, mobject_or_point, *args, **kwargs)
def create_target(self):
mobject = self.create_final_mobject()
mobject.set_stroke(
width=(mobject.stroke_width*self.scale))
if self.point_color:
mobject.set_color(self.point_color)
return mobject
def create_starting_mobject(self):
mobject = self.mobject.copy()
return mobject
def create_final_mobject(self):
mobject = self.mobject.copy()
return mobject.scale(self.scale).move_to(self.mobject_or_point)
class DiminishToCenter(DiminishToPoint):
def __init__(self, mobject, *args, **kwargs):
super().__init__(mobject, mobject.get_center(), *args, **kwargs)
class DiminishToEdge(DiminishToPoint):
def __init__(self, mobject, edge=[-1, 1, 0], *args, **kwargs):
super().__init__(mobject, mobject.get_critical_point(edge), *args, **kwargs)
class DiminishToSide(DiminishToPoint):
def __init__(self, mobject, side=[0, 1, 0], center=False, *args, **kwargs):
self.side = side
self.center = center
super().__init__(mobject, mobject.get_critical_point(side), *args, **kwargs)
def create_final_mobject(self):
mobject = self.mobject.copy()
dim = [i for i, each in enumerate(self.side) if each]
mobject.stretch_to_fit(to_expand_lists(self.scale, dim), dim)
if not self.center:
mobject.move_to(self.mobject_or_point)
else:
mobject.move_to(self.mobject.get_center())
return mobject
class GrowArrow(GrowFromPoint):
def __init__(self, arrow, point_by_ratio=0, *args, **kwargs):
super().__init__(arrow, point_by_ratio, *args, **kwargs)
class ExpandArrow(GrowArrow):
def __init__(self, arrow, point_by_ratio=1, *args, **kwargs):
super().__init__(arrow, point_by_ratio, *args, **kwargs)
class DiminishArrow(DiminishToPoint):
def | (self, arrow, point_by_ratio=1, *args, **kwargs):
super().__init__(arrow, point_by_ratio, *args, **kwargs)
class RetractArrow(DiminishToPoint):
def __init__(self, arrow, point_by_ratio=0, *args, **kwargs):
super().__init__(arrow, point_by_ratio, *args, **kwargs)
class SpinInFromNothing(GrowFromCenter):
CONFIG = {
"path_arc": PI,
}
class SpinInFrom(GrowFromPoint):
CONFIG = {
"path_arc": PI,
}
def __init__(self, mobject, point="get_center()", *args, **kwargs):
super().__init__(mobject, point, *args, **kwargs)
class SpinOutFrom(SpinInFrom):
CONFIG = {
"path_arc": -PI,
}
class SpinInTo(DiminishToPoint):
CONFIG = {
"path_arc": PI,
}
def __init__(self, mobject, point="get_center()", *args, **kwargs):
super().__init__(mobject, point, *args, **kwargs)
class SpinOutTo(SpinInTo):
CONFIG = {
"path_arc": -PI,
}
| __init__ |
lib_test.go | package snowflake_client
import (
"fmt"
"net"
"testing"
"time"
. "github.com/smartystreets/goconvey/convey"
)
type FakeDialer struct {
max int
}
func (w FakeDialer) Catch() (*WebRTCPeer, error) {
fmt.Println("Caught a dummy snowflake.")
return &WebRTCPeer{closed: make(chan struct{})}, nil
}
func (w FakeDialer) GetMax() int {
return w.max
}
type FakeSocksConn struct {
net.Conn
rejected bool
}
func (f FakeSocksConn) Reject() error {
f.rejected = true
return nil
}
func (f FakeSocksConn) Grant(addr *net.TCPAddr) error { return nil }
func | (t *testing.T) {
Convey("Peers", t, func() {
Convey("Can construct", func() {
d := &FakeDialer{max: 1}
p, _ := NewPeers(d)
So(p.Tongue.GetMax(), ShouldEqual, 1)
So(p.snowflakeChan, ShouldNotBeNil)
So(cap(p.snowflakeChan), ShouldEqual, 1)
})
Convey("Collecting a Snowflake requires a Tongue.", func() {
p, err := NewPeers(nil)
So(err, ShouldNotBeNil)
// Set the dialer so that collection is possible.
d := &FakeDialer{max: 1}
p, err = NewPeers(d)
_, err = p.Collect()
So(err, ShouldBeNil)
So(p.Count(), ShouldEqual, 1)
// S
_, err = p.Collect()
})
Convey("Collection continues until capacity.", func() {
c := 5
p, _ := NewPeers(FakeDialer{max: c})
// Fill up to capacity.
for i := 0; i < c; i++ {
fmt.Println("Adding snowflake ", i)
_, err := p.Collect()
So(err, ShouldBeNil)
So(p.Count(), ShouldEqual, i+1)
}
// But adding another gives an error.
So(p.Count(), ShouldEqual, c)
_, err := p.Collect()
So(err, ShouldNotBeNil)
So(p.Count(), ShouldEqual, c)
// But popping allows it to continue.
s := p.Pop()
s.Close()
So(s, ShouldNotBeNil)
So(p.Count(), ShouldEqual, c-1)
_, err = p.Collect()
So(err, ShouldBeNil)
So(p.Count(), ShouldEqual, c)
})
Convey("Count correctly purges peers marked for deletion.", func() {
p, _ := NewPeers(FakeDialer{max: 5})
p.Collect()
p.Collect()
p.Collect()
p.Collect()
So(p.Count(), ShouldEqual, 4)
s := p.Pop()
s.Close()
So(p.Count(), ShouldEqual, 3)
s = p.Pop()
s.Close()
So(p.Count(), ShouldEqual, 2)
})
Convey("End Closes all peers.", func() {
cnt := 5
p, _ := NewPeers(FakeDialer{max: cnt})
for i := 0; i < cnt; i++ {
p.activePeers.PushBack(&WebRTCPeer{closed: make(chan struct{})})
}
So(p.Count(), ShouldEqual, cnt)
p.End()
<-p.Melted()
So(p.Count(), ShouldEqual, 0)
})
Convey("Pop skips over closed peers.", func() {
p, _ := NewPeers(FakeDialer{max: 4})
wc1, _ := p.Collect()
wc2, _ := p.Collect()
wc3, _ := p.Collect()
So(wc1, ShouldNotBeNil)
So(wc2, ShouldNotBeNil)
So(wc3, ShouldNotBeNil)
wc1.Close()
r := p.Pop()
So(p.Count(), ShouldEqual, 2)
So(r, ShouldEqual, wc2)
wc4, _ := p.Collect()
wc2.Close()
wc3.Close()
r = p.Pop()
So(r, ShouldEqual, wc4)
})
Convey("Terminate Connect() loop", func() {
p, _ := NewPeers(FakeDialer{max: 4})
go func() {
for {
p.Collect()
select {
case <-p.Melted():
return
default:
}
}
}()
<-time.After(10 * time.Second)
p.End()
<-p.Melted()
So(p.Count(), ShouldEqual, 0)
})
})
Convey("Dialers", t, func() {
Convey("Can construct WebRTCDialer.", func() {
broker := &BrokerChannel{}
d := NewWebRTCDialer(broker, nil, 1)
So(d, ShouldNotBeNil)
So(d.BrokerChannel, ShouldNotBeNil)
})
SkipConvey("WebRTCDialer can Catch a snowflake.", func() {
broker := &BrokerChannel{}
d := NewWebRTCDialer(broker, nil, 1)
conn, err := d.Catch()
So(conn, ShouldBeNil)
So(err, ShouldNotBeNil)
})
})
}
func TestWebRTCPeer(t *testing.T) {
Convey("WebRTCPeer", t, func(c C) {
p := &WebRTCPeer{closed: make(chan struct{})}
Convey("checks for staleness", func() {
go p.checkForStaleness(time.Second)
<-time.After(2 * time.Second)
So(p.Closed(), ShouldEqual, true)
})
})
}
func TestICEServerParser(t *testing.T) {
Convey("Test parsing of ICE servers", t, func() {
for _, test := range []struct {
input []string
urls [][]string
length int
}{
{
[]string{"stun:stun.l.google.com:19302"},
[][]string{[]string{"stun:stun.l.google.com:19302"}},
1,
},
{
[]string{"stun:stun.l.google.com:19302", "stun.ekiga.net"},
[][]string{[]string{"stun:stun.l.google.com:19302"}, []string{"stun.ekiga.net"}},
2,
},
{
[]string{"stun:stun.l.google.com:19302", "stun.ekiga.net"},
[][]string{[]string{"stun:stun.l.google.com:19302"}, []string{"stun.ekiga.net"}},
2,
},
} {
servers := parseIceServers(test.input)
if test.urls == nil {
So(servers, ShouldBeNil)
} else {
So(servers, ShouldNotBeNil)
}
So(len(servers), ShouldEqual, test.length)
for _, server := range servers {
So(test.urls, ShouldContain, server.URLs)
}
}
})
}
| TestSnowflakeClient |
routes.rs | use std::{
fs::File,
io::{BufWriter, Write},
path::PathBuf,
sync::Arc,
};
use byteorder::{LittleEndian, WriteBytesExt};
use bytes::Bytes;
use chrono::Utc;
use http::header::{HeaderValue, CONTENT_TYPE};
use parking_lot::RwLock;
use rav1e_by_gop::{
decompress_frame,
EncodeState,
GetInfoResponse,
GetProgressResponse,
PostEnqueueResponse,
PostSegmentMessage,
SegmentFrameData,
SerializableProgressInfo,
SlotRequestMessage,
};
use uuid::{v1::Timestamp, Uuid};
use warp::{http::StatusCode, reply::Response, Filter, Rejection, Reply};
use crate::{
server::{
helpers::{
handle_rejection_types,
json_body,
require_auth,
with_state,
ClientVersionMismatch,
},
CLIENT_VERSION_REQUIRED,
},
try_or_500,
EncodeItem,
ENCODER_QUEUE,
UUID_CONTEXT,
UUID_NODE_ID,
};
pub fn get_routes(
temp_dir: Option<PathBuf>,
worker_threads: usize,
) -> impl Filter<Extract = impl Reply, Error = Rejection> + Clone {
warp::path!("info")
.and(warp::get())
.and(require_auth())
.and(with_state(worker_threads))
.and_then(get_info)
.or(warp::path!("enqueue" / Uuid)
.and(warp::get())
.and(require_auth())
.and_then(get_enqueue))
.or(warp::path!("enqueue")
.and(warp::post())
.and(require_auth())
.and(json_body())
.and_then(post_enqueue))
.or(warp::path!("segment" / Uuid)
.and(warp::post())
.and(require_auth())
.and(json_body())
.and_then(post_segment))
.or(warp::path!("segment_data" / Uuid)
.and(warp::post())
.and(require_auth())
.and(warp::body::bytes())
.and(with_state(temp_dir))
.and_then(post_segment_data))
.or(warp::path!("segment" / Uuid)
.and(warp::get())
.and(require_auth())
.and_then(get_segment))
.or(warp::path!("segment_data" / Uuid)
.and(warp::get())
.and(require_auth())
.and_then(get_segment_data))
.recover(handle_rejection_types)
}
async fn get_info(_auth: (), worker_threads: usize) -> Result<impl Reply, Rejection> {
Ok(warp::reply::with_status(
warp::reply::json(&GetInfoResponse {
worker_count: worker_threads,
}),
StatusCode::NOT_FOUND,
))
}
// this endpoint tells a client if their slot is ready
async fn get_enqueue(request_id: Uuid, _auth: ()) -> Result<impl Reply, Rejection> {
let reader = ENCODER_QUEUE.read();
let item = reader.get(&request_id);
if let Some(item) = item {
match item.read().state {
EncodeState::Enqueued => Ok(warp::reply::with_status(
warp::reply::json(&()),
StatusCode::ACCEPTED,
)),
EncodeState::AwaitingInfo { .. } | EncodeState::AwaitingData { .. } => Ok(
warp::reply::with_status(warp::reply::json(&()), StatusCode::OK),
),
_ => Ok(warp::reply::with_status(
warp::reply::json(&()),
StatusCode::GONE,
)),
}
} else {
Ok(warp::reply::with_status(
warp::reply::json(&()),
StatusCode::NOT_FOUND,
))
}
}
// client hits this endpoint to say that they want to request a slot
// returns a JSON body with a request ID
async fn post_enqueue(_auth: (), body: SlotRequestMessage) -> Result<impl Reply, Rejection> {
if !CLIENT_VERSION_REQUIRED.matches(&body.client_version) {
return Err(warp::reject::custom(ClientVersionMismatch));
}
let ts = Timestamp::from_unix(&*UUID_CONTEXT, 1497624119, 1234);
let request_id = try_or_500!(Uuid::new_v1(ts, &UUID_NODE_ID));
ENCODER_QUEUE.write().insert(
request_id,
RwLock::new(EncodeItem::new(body.options, body.video_info)),
);
Ok(warp::reply::with_status(
warp::reply::json(&PostEnqueueResponse { request_id }),
StatusCode::ACCEPTED,
))
}
async fn post_segment(
request_id: Uuid,
_auth: (),
body: PostSegmentMessage,
) -> Result<impl Reply, Rejection> {
if let Some(item) = ENCODER_QUEUE.read().get(&request_id) {
let mut item_handle = item.write();
match item_handle.state {
EncodeState::AwaitingInfo { .. } => (),
_ => {
return Ok(warp::reply::with_status(
warp::reply::json(&()),
StatusCode::GONE,
));
}
};
item_handle.state = EncodeState::AwaitingData {
keyframe_number: body.keyframe_number,
segment_idx: body.segment_idx,
next_analysis_frame: body.next_analysis_frame,
time_ready: Utc::now(),
};
return Ok(warp::reply::with_status(
warp::reply::json(&()),
StatusCode::OK,
));
}
Ok(warp::reply::with_status(
warp::reply::json(&()),
StatusCode::NOT_FOUND,
))
}
// client sends raw video data via this endpoint
async fn post_segment_data(
request_id: Uuid,
_auth: (),
body: Bytes,
temp_dir: Option<PathBuf>,
) -> Result<impl Reply, Rejection> |
// returns progress on currently encoded segment
async fn get_segment(request_id: Uuid, _auth: ()) -> Result<impl Reply, Rejection> {
if let Some(item) = ENCODER_QUEUE.read().get(&request_id) {
let item_reader = item.read();
match item_reader.state {
EncodeState::InProgress { ref progress, .. } => Ok(warp::reply::with_status(
warp::reply::json(&GetProgressResponse {
progress: SerializableProgressInfo::from(&*progress),
done: false,
}),
StatusCode::OK,
)),
EncodeState::EncodingDone { ref progress, .. } => Ok(warp::reply::with_status(
warp::reply::json(&GetProgressResponse {
progress: SerializableProgressInfo::from(&*progress),
done: true,
}),
StatusCode::OK,
)),
_ => Ok(warp::reply::with_status(
warp::reply::json(&()),
StatusCode::GONE,
)),
}
} else {
Ok(warp::reply::with_status(
warp::reply::json(&()),
StatusCode::NOT_FOUND,
))
}
}
// if segment is ready, sends client the encoded video data
async fn get_segment_data(request_id: Uuid, _auth: ()) -> Result<impl Reply, Rejection> {
// Check first without mutating the state
let mut can_send_data = false;
if let Some(item) = ENCODER_QUEUE.read().get(&request_id) {
if let EncodeState::EncodingDone { .. } = item.read().state {
can_send_data = true;
}
}
if !can_send_data {
return Ok(warp::reply::with_status(
Response::new(Vec::new().into()),
StatusCode::NOT_FOUND,
));
}
// Now pop it from the queue and send it, freeing the resources simultaneously
let item = {
let mut queue_handle = ENCODER_QUEUE.write();
queue_handle.remove(&request_id)
};
if let Some(item) = item {
if let EncodeState::EncodingDone { encoded_data, .. } = item.into_inner().state {
return Ok(warp::reply::with_status(
{
let mut response = Response::new(encoded_data.into());
response.headers_mut().insert(
CONTENT_TYPE,
HeaderValue::from_static("application/octet-stream"),
);
response
},
StatusCode::OK,
));
}
}
unreachable!()
}
| {
if let Some(item) = ENCODER_QUEUE.read().get(&request_id) {
let mut item_handle = item.write();
let frame_data;
let keyframe_number_outer;
let next_analysis_frame_outer;
let segment_idx_outer;
if let EncodeState::AwaitingData {
keyframe_number,
next_analysis_frame,
segment_idx,
..
} = &mut item_handle.state
{
keyframe_number_outer = *keyframe_number;
next_analysis_frame_outer = *next_analysis_frame;
segment_idx_outer = *segment_idx;
let compressed_frames: Vec<Vec<u8>> = try_or_500!(bincode::deserialize(&body));
frame_data = match temp_dir {
Some(temp_dir) => {
let frame_count = compressed_frames.len();
let mut temp_path = temp_dir;
temp_path.push(request_id.to_hyphenated().to_string());
temp_path.set_extension("py4m");
let file = File::create(&temp_path).unwrap();
let mut writer = BufWriter::new(file);
for frame in compressed_frames {
let frame_data = if item_handle.video_info.bit_depth == 8 {
bincode::serialize(&decompress_frame::<u8>(&frame)).unwrap()
} else {
bincode::serialize(&decompress_frame::<u16>(&frame)).unwrap()
};
writer
.write_u32::<LittleEndian>(frame_data.len() as u32)
.unwrap();
writer.write_all(&frame_data).unwrap();
}
writer.flush().unwrap();
SegmentFrameData::Y4MFile {
path: temp_path,
frame_count,
}
}
None => SegmentFrameData::CompressedFrames(compressed_frames),
}
} else {
return Ok(warp::reply::with_status(
warp::reply::json(&()),
StatusCode::NOT_FOUND,
));
}
item_handle.state = EncodeState::Ready {
keyframe_number: keyframe_number_outer,
next_analysis_frame: next_analysis_frame_outer,
segment_idx: segment_idx_outer,
raw_frames: Arc::new(frame_data),
};
return Ok(warp::reply::with_status(
warp::reply::json(&()),
StatusCode::OK,
));
}
Ok(warp::reply::with_status(
warp::reply::json(&()),
StatusCode::NOT_FOUND,
))
} |
imageverify.go | // Copyright (c) 2019, Sylabs Inc. All rights reserved.
// This software is licensed under a 3-clause BSD license. Please consult the
// LICENSE.md file distributed with the sources of this project regarding your
// rights to use or distribute this software.
package e2e
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"testing"
"github.com/buger/jsonparser"
"github.com/hpcng/singularity/internal/pkg/test/tool/exec"
"github.com/hpcng/singularity/internal/pkg/util/fs"
)
// ImageVerify checks for an image integrity.
func (env TestEnv) ImageVerify(t *testing.T, imagePath string, profile Profile) {
tt := []struct {
name string
argv []string
exit int
}{
{
name: "False",
argv: []string{imagePath, "false"},
exit: 1,
},
{
name: "RunScript",
argv: []string{imagePath, "test", "-f", "/.singularity.d/runscript"},
exit: 0,
},
{
name: "OneBase",
argv: []string{imagePath, "test", "-f", "/.singularity.d/env/01-base.sh"},
exit: 0,
},
{
name: "ActionsShell",
argv: []string{imagePath, "test", "-f", "/.singularity.d/actions/shell"},
exit: 0,
},
{
name: "ActionsExec",
argv: []string{imagePath, "test", "-f", "/.singularity.d/actions/exec"},
exit: 0,
},
{
name: "ActionsRun",
argv: []string{imagePath, "test", "-f", "/.singularity.d/actions/run"},
exit: 0,
},
{
name: "Environment",
argv: []string{imagePath, "test", "-L", "/environment"},
exit: 0,
},
{
name: "Singularity",
argv: []string{imagePath, "test", "-L", "/singularity"},
exit: 0,
},
}
for _, tc := range tt {
env.RunSingularity(
t,
AsSubtest(tc.name),
WithProfile(profile),
WithCommand("exec"),
WithArgs(tc.argv...),
ExpectExit(tc.exit),
)
}
tests := []struct {
name string
jsonPath []string
expectOut string
}{
{
name: "LabelCheckType",
jsonPath: []string{"type"},
expectOut: "container",
},
{
name: "LabelCheckSchemaVersion",
jsonPath: []string{"data", "attributes", "labels", "org.label-schema.schema-version"},
expectOut: "1.0",
},
}
// Verify the label partition
for _, tt := range tests {
verifyOutput := func(t *testing.T, r *SingularityCmdResult) {
jsonOut, err := jsonparser.GetString(r.Stdout, tt.jsonPath...)
if err != nil {
t.Fatalf("unable to get expected output from json: %v", err)
}
if jsonOut != tt.expectOut {
t.Fatalf("unexpected failure: got: '%s', expecting: '%s'", jsonOut, tt.expectOut)
}
}
env.RunSingularity(
t,
AsSubtest(tt.name),
WithProfile(UserProfile),
WithCommand("inspect"),
WithArgs([]string{"--json", "--labels", imagePath}...),
ExpectExit(0, verifyOutput),
)
}
}
// DefinitionImageVerify checks for image correctness based off off supplied DefFileDetail
func DefinitionImageVerify(t *testing.T, cmdPath, imagePath string, dfd DefFileDetails) {
if dfd.Help != nil {
helpPath := filepath.Join(imagePath, `/.singularity.d/runscript.help`)
if !fs.IsFile(helpPath) {
t.Fatalf("unexpected failure: Script %v does not exist in container", helpPath)
}
if err := verifyHelp(t, helpPath, dfd.Help); err != nil {
t.Fatalf("unexpected failure: help message: %v", err)
}
}
if dfd.Env != nil {
if err := verifyEnv(t, cmdPath, imagePath, dfd.Env, nil); err != nil {
t.Fatalf("unexpected failure: Env in container is incorrect: %v", err)
}
}
// verify %files section works correctly | for _, p := range dfd.Files {
var file string
if p.Dst == "" {
file = p.Src
} else {
file = p.Dst
}
if !fs.IsFile(filepath.Join(imagePath, file)) {
t.Fatalf("unexpected failure: File %v does not exist in container", file)
}
if err := verifyFile(t, p.Src, filepath.Join(imagePath, file)); err != nil {
t.Fatalf("unexpected failure: File %v: %v", file, err)
}
}
if dfd.RunScript != nil {
scriptPath := filepath.Join(imagePath, `/.singularity.d/runscript`)
if !fs.IsFile(scriptPath) {
t.Fatalf("unexpected failure: Script %v does not exist in container", scriptPath)
}
if err := verifyScript(t, scriptPath, dfd.RunScript); err != nil {
t.Fatalf("unexpected failure: runscript: %v", err)
}
}
if dfd.StartScript != nil {
scriptPath := filepath.Join(imagePath, `/.singularity.d/startscript`)
if !fs.IsFile(scriptPath) {
t.Fatalf("unexpected failure: Script %v does not exist in container", scriptPath)
}
if err := verifyScript(t, scriptPath, dfd.StartScript); err != nil {
t.Fatalf("unexpected failure: startscript: %v", err)
}
}
if dfd.Test != nil {
scriptPath := filepath.Join(imagePath, `/.singularity.d/test`)
if !fs.IsFile(scriptPath) {
t.Fatalf("unexpected failure: Script %v does not exist in container", scriptPath)
}
if err := verifyScript(t, scriptPath, dfd.Test); err != nil {
t.Fatalf("unexpected failure: test script: %v", err)
}
}
for _, file := range dfd.Pre {
if !fs.IsFile(file) {
t.Fatalf("unexpected failure: %%Pre generated file %v does not exist on host", file)
}
if err := os.Remove(file); err != nil {
t.Fatalf("could not remove %s: %s", file, err)
}
}
for _, file := range dfd.Setup {
if !fs.IsFile(file) {
t.Fatalf("unexpected failure: %%Setup generated file %v does not exist on host", file)
}
if err := os.Remove(file); err != nil {
t.Fatalf("could not remove %s: %s", file, err)
}
}
for _, file := range dfd.Post {
if !fs.IsFile(filepath.Join(imagePath, file)) {
t.Fatalf("unexpected failure: %%Post generated file %v does not exist in container", file)
}
}
// Verify any apps
for _, app := range dfd.Apps {
// %apphelp
if app.Help != nil {
helpPath := filepath.Join(imagePath, `/scif/apps/`, app.Name, `/scif/runscript.help`)
if !fs.IsFile(helpPath) {
t.Fatalf("unexpected failure in app %v: Script %v does not exist in app", app.Name, helpPath)
}
if err := verifyHelp(t, helpPath, app.Help); err != nil {
t.Fatalf("unexpected failure in app %v: app help message: %v", app.Name, err)
}
}
// %appenv
if app.Env != nil {
if err := verifyEnv(t, cmdPath, imagePath, app.Env, []string{"--app", app.Name}); err != nil {
t.Fatalf("unexpected failure in app %v: Env in app is incorrect: %v", app.Name, err)
}
}
// %appfiles
for _, p := range app.Files {
var file string
if p.Src == "" {
file = p.Src
} else {
file = p.Dst
}
if !fs.IsFile(filepath.Join(imagePath, "/scif/apps/", app.Name, file)) {
t.Fatalf("unexpected failure in app %v: File %v does not exist in app", app.Name, file)
}
if err := verifyFile(t, p.Src, filepath.Join(imagePath, "/scif/apps/", app.Name, file)); err != nil {
t.Fatalf("unexpected failure in app %v: File %v: %v", app.Name, file, err)
}
}
// %appInstall
for _, file := range app.Install {
if !fs.IsFile(filepath.Join(imagePath, "/scif/apps/", app.Name, file)) {
t.Fatalf("unexpected failure in app %v: %%Install generated file %v does not exist in container", app.Name, file)
}
}
// %appRun
if app.Run != nil {
scriptPath := filepath.Join(imagePath, "/scif/apps/", app.Name, "scif/runscript")
if !fs.IsFile(scriptPath) {
t.Fatalf("unexpected failure in app %v: Script %v does not exist in app", app.Name, scriptPath)
}
if err := verifyScript(t, scriptPath, app.Run); err != nil {
t.Fatalf("unexpected failure in app %v: runscript: %v", app.Name, err)
}
}
// %appTest
if app.Test != nil {
scriptPath := filepath.Join(imagePath, "/scif/apps/", app.Name, "scif/test")
if !fs.IsFile(scriptPath) {
t.Fatalf("unexpected failure in app %v: Script %v does not exist in app", app.Name, scriptPath)
}
if err := verifyScript(t, scriptPath, app.Test); err != nil {
t.Fatalf("unexpected failure in app %v: test script: %v", app.Name, err)
}
}
}
}
func verifyFile(t *testing.T, original, copy string) error {
ofi, err := os.Stat(original)
if err != nil {
t.Fatalf("While getting file info: %v", err)
}
cfi, err := os.Stat(copy)
if err != nil {
t.Fatalf("While getting file info: %v", err)
}
if ofi.Size() != cfi.Size() {
return fmt.Errorf("Incorrect file sizes. Original: %v, Copy: %v", ofi.Size(), cfi.Size())
}
if ofi.Mode() != cfi.Mode() {
return fmt.Errorf("Incorrect file modes. Original: %v, Copy: %v", ofi.Mode(), cfi.Mode())
}
o, err := ioutil.ReadFile(original)
if err != nil {
t.Fatalf("While reading file: %v", err)
}
c, err := ioutil.ReadFile(copy)
if err != nil {
t.Fatalf("While reading file: %v", err)
}
if !bytes.Equal(o, c) {
return fmt.Errorf("Incorrect file content")
}
return nil
}
func verifyHelp(t *testing.T, fileName string, contents []string) error {
fi, err := os.Stat(fileName)
if err != nil {
t.Fatalf("While getting file info: %v", err)
}
// do perm check
if fi.Mode().Perm() != 0644 {
return fmt.Errorf("Incorrect help script perms: %v", fi.Mode().Perm())
}
s, err := ioutil.ReadFile(fileName)
if err != nil {
t.Fatalf("While reading file: %v", err)
}
helpScript := string(s)
for _, c := range contents {
if !strings.Contains(helpScript, c) {
return fmt.Errorf("Missing help script content")
}
}
return nil
}
func verifyScript(t *testing.T, fileName string, contents []string) error {
fi, err := os.Stat(fileName)
if err != nil {
t.Fatalf("While getting file info: %v", err)
}
// do perm check
if fi.Mode().Perm() != 0755 {
return fmt.Errorf("Incorrect script perms: %v", fi.Mode().Perm())
}
s, err := ioutil.ReadFile(fileName)
if err != nil {
t.Fatalf("While reading file: %v", err)
}
script := string(s)
for _, c := range contents {
if !strings.Contains(script, c) {
return fmt.Errorf("Missing script content")
}
}
return nil
}
func verifyEnv(t *testing.T, cmdPath, imagePath string, env []string, flags []string) error {
args := []string{"exec"}
if flags != nil {
args = append(args, flags...)
}
args = append(args, imagePath, "env")
cmd := exec.Command(cmdPath, args...)
res := cmd.Run(t)
if res.Error != nil {
t.Fatalf("Error running command.\n%s", res)
}
out := res.Stdout()
for _, e := range env {
if !strings.Contains(out, e) {
return fmt.Errorf("Environment is missing: %v", e)
}
}
return nil
} | |
helpers.js | import { FIGHTERS } from '../../common/fighters';
import { random } from '../../common/array';
export const pickRandomFighter = (index) => { | return random(fighters);
}; | if (index) {
return FIGHTERS[index];
}
const fighters = FIGHTERS.filter(f => f.pickable); |
types_test.go | /*
Copyright 2017 Nike Inc.
Licensed under the Apache License, Version 2.0 (the License); | http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an AS IS BASIS,
WITHOUT 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 api
import (
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func TestErrorResponse(t *testing.T) {
var fakeError = ErrorResponse{
ErrorID: "test-error-id",
Errors: []ErrorDetail{
ErrorDetail{
Code: 12345,
Message: "Test error message.",
Metadata: map[string]interface{}{
"fields": "test",
},
},
},
}
Convey("A valid ErrorResponse Error method call", t, func() {
stringErr := fakeError.Error()
Convey("Should give a valid string", func() {
So(stringErr, ShouldStartWith, "Error from API. Error ID: test-error-id")
})
})
} | you may not use this file except in compliance with the License.
You may obtain a copy of the License at
|
embedding.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import seaborn as sns
import matplotlib.pylab as plt
import numpy as np
# TODO 所有循环结构应该呈现灵活性,每一层都不能一样!
activation_dict = {"relu" : nn.ReLU,
"leakyrelu" : nn.LeakyReLU,
"prelu" : nn.PReLU,
"rrelu" : nn.RReLU,
"elu" : nn.ELU,
"gelu" : nn.GELU,
"hardswish" : nn.Hardswish,
"mish" : nn.Mish}
Norm_dict = {"layer" : nn.LayerNorm,
"batch" : nn.BatchNorm1d}
class DW_PW_projection(nn.Module):
def __init__(self, c_in, c_out, kernel_size, stride=1, bias = False, padding_mode = "replicate"):
super(DW_PW_projection, self).__init__()
self.dw_conv1d = nn.Conv1d(in_channels = c_in,
out_channels = c_in,
kernel_size = kernel_size,
padding = int(kernel_size/2),
groups = c_in,
stride = stride,
bias = bias,
padding_mode = padding_mode)
self.pw_conv1d = nn.Conv1d(in_channels = c_in,
out_channels = c_out,
kernel_size = 1,
padding = 0,
groups = 1,
bias = bias,
padding_mode = padding_mode)
def forward(self, x):
x = self.dw_conv1d(x)
x = self.pw_conv1d(x)
return x
class Forward_block(nn.Module):
def __init__(self,
c_in,
c_out,
kernel_size,
stride = 1,
conv_bias = False,
activation = "relu",
norm_type = "batch",
max_pool = False,
pooling_kernel_size = 3,
pooling_stride = 2,
pooling_padding = 1,
padding_mode = 'replicate',
light_weight = False):
"""
embedding的block 由 conv --> norm --> activation --> maxpooling组成
"""
super(Forward_block, self).__init__()
if light_weight:
self.conv = DW_PW_projection(c_in = c_in,
c_out = c_out,
kernel_size = kernel_size,
stride = stride,
bias = conv_bias,
padding_mode = padding_mode)
else:
self.conv = nn.Conv1d(in_channels = c_in,
out_channels = c_out,
kernel_size = kernel_size,
padding = int(kernel_size/2),
stride = stride,
bias = conv_bias,
padding_mode = padding_mode)
self.norm_type = norm_type
self.norm = Norm_dict[norm_type](c_out)
self.activation = activation_dict[activation]()
self.max_pool = max_pool
if max_pool:
self.maxpooling = nn.MaxPool1d(kernel_size = pooling_kernel_size,
stride = pooling_stride,
padding = pooling_padding)
def forward(self, x):
x = self.conv(x.permute(0, 2, 1)).permute(0, 2, 1)
if self.norm_type == "layer":
x = self.activation(self.norm(x))
else :
x = self.activation(self.norm(x.permute(0, 2, 1)).permute(0, 2, 1))
if self.max_pool:
x = self.maxpooling(x.permute(0, 2, 1)).permute(0, 2, 1)
return x
class Freq_Forward_block(nn.Module):
def __init__(self,
c_in,
c_out, # 主要是把channel的dim压平
kernel_size,
stride=1,
bias = False,
padding_mode = "replicate"):
super(Freq_Forward_block, self).__init__()
# depthwise
self.dw_conv = nn.Conv2d(in_channels = c_in,
out_channels = c_in,
kernel_size = [kernel_size,kernel_size],
padding = [int(kernel_size/2),int(kernel_size/2)],
groups = c_in,
stride = [1,stride], #缩短长度
bias = bias,
padding_mode = padding_mode)
self.batch_norm_1 = nn.BatchNorm2d(c_in)
self.act_1 = nn.ReLU()
# pointwise
self.pw_conv = nn.Conv2d(in_channels = c_in,
out_channels = c_out, # 压平
kernel_size = 1,
padding = 0,
stride = 1,
bias = bias,
padding_mode = padding_mode)
self.batch_norm_2 = nn.BatchNorm2d(c_out)
self.act_2 = nn.ReLU()
def forward(self, x):
x = self.dw_conv(x)
x = self.batch_norm_1(x)
x = self.act_1(x)
x = self.pw_conv(x)
x = self.batch_norm_2(x)
x = self.act_2(x)
return x
class TokenEmbedding(nn.Module):
def __init__(self,
c_in,
| en_d_model,
kernel_size = 3,
stride = 1,
conv_bias = False,
activation = "relu",
norm_type = "batch",
n_conv_layers = 1,
in_planes = None,
max_pool = False,
pooling_kernel_size = 3,
pooling_stride = 2,
pooling_padding = 1,
padding_mode = 'replicate',
light_weight = False):
"""
c_in : 模型输入的维度
token_d_model : embedding的维度 TODO看看后面是需要被相加还是被cat
kernel_size : 每一层conv的kernel大小
"""
super(TokenEmbedding, self).__init__()
in_planes = in_planes or int(token_d_model/2)
n_filter_list = [c_in] + [in_planes for _ in range(n_conv_layers - 1)] + [token_d_model]
padding = int(kernel_size/2)
self.conv_layers = []
for i in range(n_conv_layers):
self.conv_layers.append(Forward_block(c_in = n_filter_list[i],
c_out = n_filter_list[i + 1],
kernel_size = kernel_size,
stride = stride,
conv_bias = conv_bias,
activation = activation,
norm_type = norm_type,
max_pool = max_pool,
pooling_kernel_size = pooling_kernel_size,
pooling_stride = pooling_stride,
pooling_padding = pooling_padding,
padding_mode = padding_mode,
light_weight = light_weight))
self.conv_layers = nn.ModuleList(self.conv_layers)
#for m in self.modules():
# if isinstance(m, nn.Conv1d):
# nn.init.kaiming_normal_(m.weight)
def forward(self, x):
for layer in self.conv_layers:
x = layer(x)
return x
def sequence_length(self, length=100, n_channels=3):
return self.forward(torch.zeros((1, length,n_channels))).shape[1]
class Freq_TokenEmbedding(nn.Module):
def __init__(self,
c_in,
token_d_model,
kernel_size = 3,
stride = 1, #横向方向缩短距离
conv_bias = False,
n_conv_layers = 1,
f_max = 100,
padding_mode = 'replicate',
light_weight = False):
"""
c_in : 模型输入的维度
token_d_model : embedding的维度 TODO看看后面是需要被相加还是被cat
kernel_size : 每一层conv的kernel大小
"""
super(Freq_TokenEmbedding, self).__init__()
n_filter_list = [c_in] + [max(1,int(c_in/2**(i+1))) for i in range(n_conv_layers - 1)] + [1]
print(n_filter_list)
self.conv_layers = []
for i in range(n_conv_layers):
self.conv_layers.append(Freq_Forward_block(c_in = n_filter_list[i],
c_out = n_filter_list[i + 1], # 主要是把channel的dim压平
kernel_size = kernel_size,
stride = stride,
bias = conv_bias,
padding_mode = padding_mode))
self.conv_layers = nn.ModuleList(self.conv_layers)
self.conv = nn.Conv1d(in_channels = self.channel(c_in = c_in, freq = int(f_max/2), length=100),
out_channels = token_d_model,
kernel_size = kernel_size,
padding = int(kernel_size/2),
stride = 1,
bias = conv_bias,
padding_mode = padding_mode)
self.norm = nn.LayerNorm(token_d_model)
self.activation = nn.ReLU()
def forward(self, x):
for layer in self.conv_layers:
x = layer(x)
x = torch.squeeze(x, 1)
x = self.conv(x) # B C L
x = self.activation(self.norm(x.permute(0, 2, 1)))
return x
def sequence_length(self, c_in = 100, freq = 50, length=100):
x = torch.rand(1,c_in,freq,length).float()
for layer in self.conv_layers:
x = layer(x)
return x.shape[3]
def channel(self, c_in = 100, freq = 50, length=100):
x = torch.rand(1,c_in,freq,length).float()
for layer in self.conv_layers:
x = layer(x)
print("channel ,", x.shape[2])
return x.shape[2]
class PositionalEmbedding(nn.Module):
"""
input shape should be (batch, seq_length, feature_channel)
"""
def __init__(self, pos_d_model, max_len=5000):
super(PositionalEmbedding, self).__init__()
# Compute the positional encodings once in log space.
pe = torch.zeros(max_len, pos_d_model).float()
pe.require_grad = False
position = torch.arange(0, max_len).float().unsqueeze(1)
div_term = (torch.arange(0, pos_d_model, 2).float() * -(math.log(10000.0) / pos_d_model)).exp()
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
pe = pe.unsqueeze(0)# [1, max_len, pos_d_model]
self.register_buffer('pe', pe)
def forward(self, x):
return self.pe[:, :x.size(1)] # select the the length same as input
def vis_pos_heat(self, length):
heat = self.pe[:, :length]
plt.figure(figsize=(15,5))
sns.heatmap(heat.detach().numpy()[0], linewidth=0)
plt.ylabel("length")
plt.xlabel("embedding")
| tok |
list_utils_test.py | import pytest
from list_utils import *
from oracle import ColumnRecommendation, ColumnClassification
def test_find_one():
needle = 1
none = [0, 0, 5, 's']
beginning = [1, None, 9, 6, 0, 0]
end = ['x', '0', 1]
several = [0, 0, 3, 4, 1, 3, 2, 1, 3, 4]
assert find_one(none, needle) == False
assert find_one(beginning, needle)
assert find_one(end, needle)
assert find_one(several, needle)
def test_find_n():
assert find_n([2, 3, 4, 5, 6], 2, -1) == False
assert find_n([1, 2, 3, 4, 5], 42, 2) == False
assert find_n([1, 2, 3, 4, 5], 1, 2) == False
assert find_n([1, 2, 3, 2, 4, 5], 2, 2) | assert find_n([1, 2, 3, 4, 5, 4, 6, 4, 7, 4, 6], 4, 2)
assert find_n([1, 2, 3, 4], 'x', 0) == True
def test_find_streak():
assert find_streak([1, 2, 3, 4, 5], 4, -1) == False
assert find_streak([1, 2, 3, 4, 5], 42, 2) == False
assert find_streak([1, 2, 3, 4], 4, 1)
assert find_streak([1, 2, 3, 1, 2], 2, 2) == False
assert find_streak([1, 2, 3, 4, 5, 5, 5], 5, 3)
assert find_streak([5, 5, 5, 1, 2, 3, 4], 5, 3)
assert find_streak([1, 2, 5, 5, 5, 3, 4], 5, 3)
assert find_streak([1, 2, 3, 4, 5, 5, 5], 5, 4) == False
def test_first_elements():
original = [[0, 7, 3], [4, 0, 1]]
assert first_elements(original) == [0, 4]
def test_transpose():
original = [[0, 7, 3], [4, 0, 1]]
transposed = [[0, 4], [7, 0], [3, 1]]
assert transpose(original) == transposed
assert transpose(transpose(original)) == original
def test_zero_distance_displace():
l1 = [1, 2, 3, 4, 5, 6]
l2 = [1]
l3 = [[4, 5], ['x', 'o', 'c']]
assert displace([], 0) == []
assert displace(l1, 0) == l1
assert displace(l2, 0) == l2
assert displace(l3, 0) == l3
def test_positive_distance_displace():
l1 = [1, 2, 3, 4, 5, 6]
l2 = [1]
l3 = [[4, 5], ['x', 'o', 'c']]
l4 = [9, 6, 5]
assert displace([], 2) == []
assert displace(l1, 2) == [None, None, 1, 2, 3, 4]
assert displace(l2, 3, '-') == ['-']
assert displace(l3, 1, '#') == ['#', [4, 5]]
assert displace(l4, 3, 0) == [0, 0, 0]
def test_negative_distance_displace():
l1 = [1, 2, 3, 4, 5, 6]
l2 = [1]
l3 = [[4, 5], ['x', 'o', 'c']]
l4 = [9, 6, 5]
assert displace([], -2) == []
assert displace(l1, -2) == [3, 4, 5, 6, None, None]
assert displace(l2, -3, '-') == ['-']
assert displace(l3, -1, '#') == [['x', 'o', 'c'], '#']
assert displace(l4, -3, 0) == [0, 0, 0]
def test_reverse_list():
assert reverse_list([]) == []
assert reverse_list([1, 2, 3, 4, 5, 6]) == [6, 5, 4, 3, 2, 1]
def test_reverse_matrix():
assert reverse_matrix([]) == []
assert reverse_matrix([[0, 1, 2, 3], [0, 1, 2, 3]]) == [
[3, 2, 1, 0], [3, 2, 1, 0]]
def test_all_same():
assert all_same([9, 1, 2, 3, 4]) == False
assert all_same([[], [], []])
assert all_same([])
assert all_same([ColumnRecommendation(0, ColumnClassification.WIN),
ColumnRecommendation(2, ColumnClassification.WIN)])
assert all_same([ColumnRecommendation(0, ColumnClassification.MAYBE),
ColumnRecommendation(0, ColumnClassification.WIN)]) == False
def test_collapse_list():
assert collapse_list([]) == ''
assert collapse_list(['o', 'x', 'x', 'o']) == 'oxxo'
assert collapse_list(['x', 'x', None, None, None]) == 'xx...'
def test_collapse_matrix():
assert collapse_matrix([]) == ''
assert collapse_matrix([['x', 'x', None],
['o', 'x', 'x'],
['o', None, None]]) == 'xx.|oxx|o..'
def test_replace_all_in_list():
assert replace_all_in_list([None, 3, '546', 33, None], None, '#') == [
'#', 3, '546', 33, '#']
assert replace_all_in_list([1, 2, 3, 4, 5], 'e', 42) == [1, 2, 3, 4, 5]
assert replace_all_in_list([], 34, 43) == []
def test_replace_all_in_matrix():
# caso normal: tiene lo viejo
assert replace_all_in_matrix([[1, 2, 3, 'n', 'n', None],
[4, 5, 'n']], 'n', '#') == [[1, 2, 3, '#', '#', None], [4, 5, '#']]
# caso raro: no tiene lo viejo
assert replace_all_in_matrix([[None, None, 2, True], [4, 5, '#']], 'k', 42) == [[
None, None, 2, True], [4, 5, '#']]
# caso más raro: lista de listas vacías
assert replace_all_in_matrix([], None, 7) == []
assert replace_all_in_matrix([[], []], None, 7) == [[], []] | |
reader.rs | // Read side of server.
use anyhow::{anyhow, Context, Result};
use crate::storage;
use crate::writer;
use crate::msg;
use crate::msgmacros::*;
macro_rules! respond {
($sender: expr, $id: expr, $data: expr) => (
$sender.send(msg::Zeo::Raw(response!($id, $data))).context("send response")?
)
}
macro_rules! error {
($sender: expr, $id: expr, $data: expr) => (
$sender
.send(msg::Zeo::Raw(error_response!($id, $data)))
.context("send error response")?
)
}
pub fn | <R: std::io::Read>(
fs: std::sync::Arc<storage::FileStorage<writer::Client>>,
reader: R,
sender: std::sync::mpsc::Sender<msg::Zeo>)
-> Result<()> {
let mut it = msg::ZeoIter::new(reader);
// handshake
if it.next_vec()? != b"M5".to_vec() {
return Err(anyhow!("Bad handshake"))?
}
// register(storage_id, read_only)
loop {
match it.next()? {
msg::Zeo::Register(id, storage, read_only) => {
if &storage != "1" {
error!(sender, id,
("builtins.ValueError", ("Invalid storage",)))
}
respond!(sender, id, msg::bytes(&fs.last_transaction()));
break; // onward
},
msg::Zeo::End => {
sender.send(msg::Zeo::End);
return Ok(())
},
_ => return Err(anyhow!("bad method"))?
}
}
// Main loop. We spend most of our time here.
loop {
let message = it.next()?;
match message {
msg::Zeo::LoadBefore(id, oid, before) => {
use storage::LoadBeforeResult::*;
match fs.load_before(&oid, &before)? {
Loaded(data, tid, Some(end)) => {
respond!(
sender, id,
(msg::bytes(&data), msg::bytes(&tid), msg::bytes(&end)));
},
Loaded(data, tid, None) => {
respond!(
sender, id,
(msg::bytes(&data), msg::bytes(&tid), msg::NIL));
},
NoneBefore => {
respond!(sender, id, msg::NIL);
},
PosKeyError => {
error!(sender, id,
("ZODB.POSException.POSKeyError",
(msg::bytes(&oid),)));
},
}
},
msg::Zeo::Ping(id) => {
respond!(sender, id, msg::NIL);
},
msg::Zeo::NewOids(id) => {
let oids = fs.new_oids();
let oids: Vec<serde::bytes::Bytes> =
oids.iter().map(| oid | msg::bytes(oid)).collect();
respond!(sender, id, oids)
},
msg::Zeo::GetInfo(id) => { // TODO, don't punt :)
respond!(sender, id, std::collections::BTreeMap::<String, i64>::new())
},
msg::Zeo::TpcBegin(_, _, _, _) | msg::Zeo::Storea(_, _, _, _) |
msg::Zeo::Vote(_, _) | msg::Zeo::TpcFinish(_, _) | msg::Zeo::TpcAbort(_, _)
=>
sender
.send(message)
.context("send error")?, // Forward these
msg::Zeo::End => {
sender.send(msg::Zeo::End);
return Ok(())
},
_ => return Err(anyhow!("bad method"))
}
}
}
| reader |
chunks.py | #!/usr/bin/env python
import argparse
import math
import matplotlib.pyplot as plt
def file_count(shape, chunkXY, chunkZ=1, chunkT=1, chunkC=1):
t, c, z, y, x = shape
return (
math.ceil(x / chunkXY)
* math.ceil(y / chunkXY)
* math.ceil(z / chunkZ)
* math.ceil(t / chunkT)
* math.ceil(c / chunkC)
)
def plot(ax, twoD=True, font=16):
|
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("filename")
ns = parser.parse_args()
# fig = plt.figure()
# ax2D = fig.add_subplot(2, 1, 1)
# ax3D = fig.add_subplot(2, 1, 2)
fig, ax = plt.subplots(1, 2, figsize=(12, 5))
plot(ax[1], False)
plot(ax[0], True)
plt.savefig(ns.filename)
| if twoD:
shape = (1, 8, 1, 2 ** 16, 2 ** 16)
chunkSizesXY = [32, 1024]
chunkSizesOther = (1, 2, 4, 8)
else:
shape = (100, 1, 1024, 1024, 1024)
chunkSizesXY = (16, 32, 64, 128)
chunkSizesOther = (1, 10, 100)
ax.set_ylabel("Number of chunks")
ax.set_yscale("log")
ax.set_xscale("log")
ax.set(xlim=(10, 2 * 10 ** 3), ylim=(10, 10 ** 8))
if twoD:
ax.set_xlabel("Chunk size (X and Y)")
ax.set_title("XYZCT: (64k, 64k, 1, 8, 1)")
chunkDim = "C"
annTitle = "Chosen chunk size:\n(256, 256, 1, 1, 1)"
xy = ((256), file_count(shape, 256))
else:
ax.set_xlabel("Chunk size (XYZ)")
ax.set_title("XYZCT: (1k, 1k, 1k, 1, 100)")
chunkDim = "T"
annTitle = "Chosen chunk size:\n(32, 32, 32, 1, 1)"
xy = ((32), file_count(shape, 32, chunkZ=32))
for item in (
[ax.title, ax.xaxis.label, ax.yaxis.label]
+ ax.get_xticklabels()
+ ax.get_yticklabels()
):
item.set_fontsize(font)
styles = ["solid", "dashed", "dashdot", "dotted"]
for whichChunk, chunkOther in enumerate(chunkSizesOther):
numFiles = []
fileSize = []
for i in chunkSizesXY:
if twoD:
count = file_count(shape, i, **{f"chunk{chunkDim}": chunkOther})
else:
# Could be simpler
count = file_count(
shape, i, chunkZ=i, **{f"chunk{chunkDim}": chunkOther}
)
numFiles.append(count)
fileSize.append(i)
ax.plot(
fileSize,
numFiles,
linewidth=0.5,
label=f"{chunkOther}",
linestyle=styles.pop(0),
)
ax.annotate(
annTitle,
xy=xy,
xycoords="data",
xytext=(0, 40),
textcoords="offset points",
arrowprops=dict(facecolor="black", shrink=0.05),
horizontalalignment="left",
verticalalignment="center",
fontsize=font - 4,
)
leg = ax.legend(
loc="lower left",
title=f"Chunk size ({chunkDim})",
frameon=False,
prop={"size": font},
)
for legobj in leg.legendHandles:
legobj.set_linewidth(0.5)
for axis in ["top", "bottom", "left", "right"]:
ax.spines[axis].set_linewidth(0.5)
return fig |
dce_rpc.pac | %include binpac.pac
%include zeek.pac
%extern{
#include "analyzer/protocol/dce-rpc/consts.bif.h"
#include "analyzer/protocol/dce-rpc/types.bif.h"
#include "analyzer/protocol/dce-rpc/events.bif.h" | flow : DCE_RPC_Flow;
};
connection DCE_RPC_Conn(zeek_analyzer: ZeekAnalyzer) {
upflow = DCE_RPC_Flow(true);
downflow = DCE_RPC_Flow(false);
};
%include dce_rpc-protocol.pac
%include endpoint-atsvc.pac
%include endpoint-epmapper.pac
%include dce_rpc-analyzer.pac
%include dce_rpc-auth.pac | %}
analyzer DCE_RPC withcontext {
connection : DCE_RPC_Conn; |
buJinPattern.js | /* --- AUTOGENERATED FILE -----------------------------
* If you make changes to this file delete this comment.
* Otherwise the file may be overwritten in the future.
* --------------------------------------------------- */
const { mergeLocMatchGroups } = require('../lib/matching/utils');
const { regexMatchLocs } = require('../lib/matching/regexMatch');
const allSetSrc = {
type: 'website',
url: 'https://resources.allsetlearning.com/chinese/grammar/ASGJ1VZQ',
name: 'AllSet Chinese Grammar Wiki',
};
module.exports = {
id: 'buJin',
structures: ['Subj. + 不仅 / 不但 / 不只 + ⋯⋯,而且 / 还 / 也 + ⋯⋯'],
description:
'We\'ve seen 不但⋯⋯而且 in B1, but other than that there are a number of other structures which can be used to express "not only...but also." 不但 can be substituted with 不仅(bù jǐn) and 不只 (bù zhǐ), all meaning "not only," and can be followed by 而且 (ér qiě) , 还 (hái), or 也 (yě) \nOther than 不但⋯⋯而且 being more common than the others, they are all pretty similar in usage and meaning.',
sources: [allSetSrc],
match: sentence =>
mergeLocMatchGroups([
regexMatchLocs(sentence.text, /((?:不仅|不但|不只))[^而且还也]+((?:而且|还|也))/),
]),
examples: [
{
zh: '这篇文章不仅结构清楚,而且思想先进。',
en: 'This essay is not only written clearly, but is also well-developed.',
src: allSetSrc,
},
{
zh: '他不仅喜欢吃中国菜,而且也会做几个中国菜!',
en: 'He not only likes to eat Chinese food, but he can make some as well!',
src: allSetSrc,
},
{ | },
{
zh: '他不但聪明还很善良。难怪他这么受大家的喜爱!',
en: "He's not only smart, but also kind. No wonder everyone loves him.",
src: allSetSrc,
},
],
}; | zh: '这个外国人不只会唱民歌,还会说方言,真是了不起!',
en:
"Not only can this foreigner sing folk songs, but he can also speak the dialect. That's really amazing!",
src: allSetSrc, |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.