prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>tests.py<|end_file_name|><|fim▁begin|># coding=utf-8 import random import time import threading import unittest from lru_cache import LruCache class TesLruCache(unittest.TestCase): def test_cache_normal(self): a = [] @LruCache(maxsize=2, timeout=1) def foo(num): a.append(num) return num foo(1) foo(1) self.assertEqual(a, [1]) def test_cache_none(self): a = [] @LruCache(maxsize=2, timeout=1) def foo(num): a.append(num) return None foo(1) foo(1) self.assertEqual(a, [1]) def test_cache_when_timeout(self): a = [] @LruCache(maxsize=2, timeout=1) def foo(num): a.append(num) return num foo(2) time.sleep(2) foo(2) self.assertEqual(a, [2, 2]) def test_cache_when_cache_is_full(self): a = [] @LruCache(maxsize=2, timeout=1) def foo(num): a.append(num) return num foo(1) foo(2) foo(3) foo(1) self.assertEqual(a, [1, 2, 3, 1]) def test_cache_with_multi_thread(self): a = [] @LruCache(maxsize=10, timeout=1) def foo(num): a.append(num) return num for i in xrange(10): threading.Thread(target=foo, args=(i, )).start() main_thread = threading.currentThread() for t in threading.enumerate(): if t is not main_thread: t.join() foo(random.randint(0, 9)) self.assertEqual(set(a), set(range(10))) def test_cache_with_multi_thread_two_func(self): a = [] @LruCache(maxsize=10, timeout=1) def foo(num): a.append(num) return num b = [] @LruCache(maxsize=10, timeout=1) def bar(num): b.append(num) return num + 1 for i in xrange(10): threading.Thread(target=foo, args=(i, )).start() threading.Thread(target=bar, args=(i, )).start() main_thread = threading.currentThread() for t in threading.enumerate(): if t is not main_thread: t.join() feed = random.randint(0, 9) self.assertEqual(foo(feed), feed) self.assertEqual(bar(feed), feed + 1) self.assertEqual(set(a), set(range(10))) self.assertEqual(set(b), set(range(10))) def test_cache_when_timeout_and_maxsize_is_none(self): a = [] <|fim▁hole|> foo(1) foo(1) self.assertEqual(a, [1]) def test_cache_when_timeout_is_none(self): a = [] @LruCache(maxsize=10) def foo(num): a.append(num) return num foo(1) foo(1) self.assertEqual(a, [1]) def test_cache_when_only_maxsize_is_none_normal(self): a = [] @LruCache(timeout=2) def foo(num): a.append(num) return num foo(1) foo(1) self.assertEqual(a, [1]) def test_cache_when_only_maxsize_is_none_timeout(self): a = [] @LruCache(timeout=1) def foo(num): a.append(num) return num foo(1) time.sleep(2) foo(1) self.assertEqual(a, [1, 1]) def test_cache_when_only_maxsize_is_none_normal_method(self): a = [] class Func(object): @LruCache(timeout=2) def foo(self, num): a.append(num) return num fun = Func() fun.foo(1) fun.foo(1) self.assertEqual(a, [1]) def test_cache_when_only_maxsize_is_none_normal_method_timeout(self): a = [] class Func(object): @LruCache(timeout=1) def foo(self, num): a.append(num) return num fun = Func() fun.foo(1) time.sleep(2) fun.foo(1) self.assertEqual(a, [1, 1]) def test_invalidate(self): a = [] @LruCache() def foo(num): a.append(num) return num foo(1) foo(1) self.assertEqual(a, [1]) foo.invalidate(1) foo(1) self.assertEqual(a, [1, 1]) if __name__ == "__main__": unittest.main()<|fim▁end|>
@LruCache() def foo(num): a.append(num) return num
<|file_name|>S11.2.4_A1.1_T1.js<|end_file_name|><|fim▁begin|>// Copyright 2009 the Sputnik authors. All rights reserved. /** * Arguments : () * * @path ch11/11.2/11.2.4/S11.2.4_A1.1_T1.js * @description Function is declared with no FormalParameterList */ function f_arg() { return arguments;<|fim▁hole|> //CHECK#1 if (f_arg().length !== 0) { $ERROR('#1: function f_arg() {return arguments;} f_arg().length === 0. Actual: ' + (f_arg().length)); } //CHECK#2 if (f_arg()[0] !== undefined) { $ERROR('#2: function f_arg() {return arguments;} f_arg()[0] === undefined. Actual: ' + (f_arg()[0])); }<|fim▁end|>
}
<|file_name|>conf.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # # pyspark documentation build configuration file, created by # sphinx-quickstart on Thu Aug 28 15:17:47 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os import shutil import errno # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('.')) # Remove previously generated rst files. Ignore errors just in case it stops # generating whole docs. shutil.rmtree( "%s/reference/api" % os.path.dirname(os.path.abspath(__file__)), ignore_errors=True) shutil.rmtree( "%s/reference/pyspark.pandas/api" % os.path.dirname(os.path.abspath(__file__)), ignore_errors=True) try: os.mkdir("%s/reference/api" % os.path.dirname(os.path.abspath(__file__))) except OSError as e: if e.errno != errno.EEXIST: raise try: os.mkdir("%s/reference/pyspark.pandas/api" % os.path.dirname( os.path.abspath(__file__))) except OSError as e: if e.errno != errno.EEXIST: raise # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. needs_sphinx = '1.2' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.mathjax', 'sphinx.ext.autosummary', 'nbsphinx', # Converts Jupyter Notebook to reStructuredText files for Sphinx. # For ipython directive in reStructuredText files. It is generated by the notebook. 'IPython.sphinxext.ipython_console_highlighting', 'numpydoc', # handle NumPy documentation formatted docstrings. 'sphinx_plotly_directive', # For visualize plot result ] # plotly plot directive plotly_include_source = True plotly_html_show_formats = False plotly_html_show_source_link = False plotly_pre_code = """import numpy as np import pandas as pd import pyspark.pandas as ps""" numpydoc_show_class_members = False # Links used globally in the RST files. # These are defined here to allow link substitutions dynamically. rst_epilog = """ .. |binder| replace:: Live Notebook .. _binder: https://mybinder.org/v2/gh/apache/spark/{0}?filepath=python%2Fdocs%2Fsource%2Fgetting_started%2Fquickstart.ipynb .. |examples| replace:: Examples .. _examples: https://github.com/apache/spark/tree/{0}/examples/src/main/python .. |downloading| replace:: Downloading .. _downloading: https://spark.apache.org/docs/{1}/building-spark.html .. |building_spark| replace:: Building Spark .. _building_spark: https://spark.apache.org/docs/{1}/#downloading """.format( os.environ.get("GIT_HASH", "master"), os.environ.get("RELEASE_VERSION", "latest"), ) # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = 'PySpark' copyright = '' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = 'master' # The full version, including alpha/beta/rc tags. release = os.environ.get('RELEASE_VERSION', version) # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build', '.DS_Store', '**.ipynb_checkpoints'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for autodoc -------------------------------------------------- # Look at the first line of the docstring for function and method signatures. autodoc_docstring_signature = True autosummary_generate = True # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'pydata_sphinx_theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. html_logo = "../../../docs/img/spark-logo-reverse.png" # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] html_css_files = [ 'css/pyspark.css', ] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. html_domain_indices = False # If false, no index is generated. html_use_index = False # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'pysparkdoc' <|fim▁hole|># -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'pyspark.tex', 'pyspark Documentation', 'Author', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'pyspark', 'pyspark Documentation', ['Author'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'pyspark', 'pyspark Documentation', 'Author', 'pyspark', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False # -- Options for Epub output ---------------------------------------------- # Bibliographic Dublin Core info. epub_title = 'pyspark' epub_author = 'Author' epub_publisher = 'Author' epub_copyright = '2014, Author' # The basename for the epub file. It defaults to the project name. #epub_basename = 'pyspark' # The HTML theme for the epub output. Since the default themes are not optimized # for small screen space, using the same theme for HTML and epub output is # usually not wise. This defaults to 'epub', a theme designed to save visual # space. #epub_theme = 'epub' # The language of the text. It defaults to the language option # or en if the language is not set. #epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. #epub_scheme = '' # The unique identifier of the text. This can be a ISBN number # or the project homepage. #epub_identifier = '' # A unique identification for the text. #epub_uid = '' # A tuple containing the cover image and cover page html template filenames. #epub_cover = () # A sequence of (type, uri, title) tuples for the guide element of content.opf. #epub_guide = () # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_pre_files = [] # HTML files shat should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_post_files = [] # A list of files that should not be packed into the epub file. epub_exclude_files = ['search.html'] # The depth of the table of contents in toc.ncx. #epub_tocdepth = 3 # Allow duplicate toc entries. #epub_tocdup = True # Choose between 'default' and 'includehidden'. #epub_tocscope = 'default' # Fix unsupported image types using the PIL. #epub_fix_images = False # Scale large images. #epub_max_image_width = 0 # How to display URL addresses: 'footnote', 'no', or 'inline'. #epub_show_urls = 'inline' # If false, no index is generated. #epub_use_index = True def setup(app): # The app.add_javascript() is deprecated. getattr(app, "add_js_file", getattr(app, "add_javascript"))('copybutton.js') # Skip sample endpoint link (not expected to resolve) linkcheck_ignore = [r'https://kinesis.us-east-1.amazonaws.com']<|fim▁end|>
<|file_name|>test-011-child-table.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # # Copyright (c) 2018, The OpenThread Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. Neither the name of the copyright holder nor the<|fim▁hole|># THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. import wpan from wpan import verify # ----------------------------------------------------------------------------------------------------------------------- # Test description: Child-table and child recovery # test_name = __file__[:-3] if __file__.endswith('.py') else __file__ print('-' * 120) print('Starting \'{}\''.format(test_name)) # ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances speedup = 4 wpan.Node.set_time_speedup_factor(speedup) NUM_CHILDREN = 7 router = wpan.Node() children = [] for i in range(NUM_CHILDREN): children.append(wpan.Node()) all_nodes = [router] + children # ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() # ----------------------------------------------------------------------------------------------------------------------- # Build network topology router.form('child-table') for child in children: child.join_node(router, node_type=wpan.JOIN_TYPE_SLEEPY_END_DEVICE) child.set(wpan.WPAN_POLL_INTERVAL, '1000') # ----------------------------------------------------------------------------------------------------------------------- # Test implementation # Get the child table and verify all children are in the table. child_table = wpan.parse_child_table_result( router.get(wpan.WPAN_THREAD_CHILD_TABLE) ) verify(len(child_table) == len(children)) for child in children: ext_addr = child.get(wpan.WPAN_EXT_ADDRESS)[1:-1] for entry in child_table: if entry.ext_address == ext_addr: break else: print( 'Failed to find a child entry for extended address {} in table'.format( ext_addr ) ) exit(1) verify( int(entry.rloc16, 16) == int(child.get(wpan.WPAN_THREAD_RLOC16), 16) ) verify(int(entry.timeout, 0) == 120) verify(entry.is_rx_on_when_idle() is False) verify(entry.is_ftd() is False) # ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() print('\'{}\' passed.'.format(test_name))<|fim▁end|>
# names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. #
<|file_name|>cache.rs<|end_file_name|><|fim▁begin|>use criterion::{criterion_group, criterion_main, Criterion}; use once_cell::sync::Lazy; use rusttype::gpu_cache::*;<|fim▁hole|> /// Busy wait 2us fn mock_gpu_upload(_region: Rect<u32>, _bytes: &[u8]) { use std::time::{Duration, Instant}; let now = Instant::now(); while now.elapsed() < Duration::from_micros(2) {} } fn test_glyphs<'a>(font: &Font<'a>, string: &str) -> Vec<PositionedGlyph<'a>> { let mut glyphs = vec![]; // Set of scales, found through brute force, to reproduce GlyphNotCached issue // Cache settings also affect this, it occurs when position_tolerance is < 1.0 for scale in &[25_f32, 24.5, 25.01, 24.7, 24.99] { for glyph in layout_paragraph(font, Scale::uniform(*scale), 500, string) { glyphs.push(glyph); } } glyphs } fn layout_paragraph<'a>( font: &Font<'a>, scale: Scale, width: u32, text: &str, ) -> Vec<PositionedGlyph<'a>> { let mut result = Vec::new(); let v_metrics = font.v_metrics(scale); let advance_height = v_metrics.ascent - v_metrics.descent + v_metrics.line_gap; let mut caret = point(0.0, v_metrics.ascent); let mut last_glyph_id = None; for c in text.chars() { if c.is_control() { if c == '\n' { caret = point(0.0, caret.y + advance_height) } continue; } let base_glyph = font.glyph(c); if let Some(id) = last_glyph_id.take() { caret.x += font.pair_kerning(scale, id, base_glyph.id()); } last_glyph_id = Some(base_glyph.id()); let mut glyph = base_glyph.scaled(scale).positioned(caret); if let Some(bb) = glyph.pixel_bounding_box() { if bb.max.x > width as i32 { caret = point(0.0, caret.y + advance_height); glyph.set_position(caret); last_glyph_id = None; } } caret.x += glyph.unpositioned().h_metrics().advance_width; result.push(glyph); } result } static FONTS: Lazy<Vec<Font<'static>>> = Lazy::new(|| { vec![ include_bytes!("../fonts/wqy-microhei/WenQuanYiMicroHei.ttf") as &[u8], include_bytes!("../fonts/opensans/OpenSans-Italic.ttf") as &[u8], include_bytes!("../fonts/Exo2-Light.otf") as &[u8], ] .into_iter() .map(|bytes| Font::try_from_bytes(bytes).unwrap()) .collect() }); const TEST_STR: &str = include_str!("../tests/lipsum.txt"); // ************************************************************************** // General use benchmarks. // ************************************************************************** /// Benchmark using a single font at "don't care" position tolerance fn bench_high_position_tolerance(c: &mut Criterion) { let font_id = 0; let glyphs = test_glyphs(&FONTS[font_id], TEST_STR); let mut cache = Cache::builder() .dimensions(1024, 1024) .scale_tolerance(0.1) .position_tolerance(1.0) .build(); c.bench_function("high_position_tolerance", |b| { b.iter(|| { for glyph in &glyphs { cache.queue_glyph(font_id, glyph.clone()); } cache.cache_queued(|_, _| {}).expect("cache_queued"); for (index, glyph) in glyphs.iter().enumerate() { let rect = cache.rect_for(font_id, glyph); assert!( rect.is_ok(), "Gpu cache rect lookup failed ({:?}) for glyph index {}, id {}", rect, index, glyph.id().0 ); } }) }); } /// Benchmark using a single font with default tolerances fn bench_single_ttf(c: &mut Criterion) { let font_id = 0; let glyphs = test_glyphs(&FONTS[font_id], TEST_STR); let mut cache = Cache::builder().dimensions(1024, 1024).build(); c.bench_function("single_ttf", |b| { b.iter(|| { for glyph in &glyphs { cache.queue_glyph(font_id, glyph.clone()); } cache.cache_queued(|_, _| {}).expect("cache_queued"); for (index, glyph) in glyphs.iter().enumerate() { let rect = cache.rect_for(font_id, glyph); assert!( rect.is_ok(), "Gpu cache rect lookup failed ({:?}) for glyph index {}, id {}", rect, index, glyph.id().0 ); } }) }); } /// Benchmark using a single font with default tolerances fn bench_single_otf(c: &mut Criterion) { let font_id = 2; let glyphs = test_glyphs(&FONTS[font_id], TEST_STR); let mut cache = Cache::builder().dimensions(1024, 1024).build(); c.bench_function("single_otf", |b| { b.iter(|| { for glyph in &glyphs { cache.queue_glyph(font_id, glyph.clone()); } cache.cache_queued(|_, _| {}).expect("cache_queued"); for (index, glyph) in glyphs.iter().enumerate() { let rect = cache.rect_for(font_id, glyph); assert!( rect.is_ok(), "Gpu cache rect lookup failed ({:?}) for glyph index {}, id {}", rect, index, glyph.id().0 ); } }) }); } /// Benchmark using multiple fonts with default tolerances fn bench_multi_font(c: &mut Criterion) { // Use a smaller amount of the test string, to offset the extra font-glyph // bench load let up_to_index = TEST_STR .char_indices() .nth(TEST_STR.chars().count() / FONTS.len()) .unwrap() .0; let string = &TEST_STR[..up_to_index]; let font_glyphs: Vec<_> = FONTS .iter() .enumerate() .map(|(id, font)| (id, test_glyphs(font, string))) .collect(); let mut cache = Cache::builder().dimensions(1024, 1024).build(); c.bench_function("mutli_font", |b| { b.iter(|| { for &(font_id, ref glyphs) in &font_glyphs { for glyph in glyphs { cache.queue_glyph(font_id, glyph.clone()); } } cache.cache_queued(|_, _| {}).expect("cache_queued"); for &(font_id, ref glyphs) in &font_glyphs { for (index, glyph) in glyphs.iter().enumerate() { let rect = cache.rect_for(font_id, glyph); assert!( rect.is_ok(), "Gpu cache rect lookup failed ({:?}) for font {} glyph index {}, id {}", rect, font_id, index, glyph.id().0 ); } } }) }); } /// Benchmark using multiple fonts with default tolerances, clears the /// cache each run to test the population "first run" performance fn bench_multi_font_population(c: &mut Criterion) { // Use a much smaller amount of the test string, to offset the extra font-glyph // bench load & much slower performance of fresh population each run let up_to_index = TEST_STR.char_indices().nth(70).unwrap().0; let string = &TEST_STR[..up_to_index]; let font_glyphs: Vec<_> = FONTS .iter() .enumerate() .map(|(id, font)| (id, test_glyphs(font, string))) .collect(); c.bench_function("multi_font_population", |b| { b.iter(|| { let mut cache = Cache::builder().dimensions(1024, 1024).build(); for &(font_id, ref glyphs) in &font_glyphs { for glyph in glyphs { cache.queue_glyph(font_id, glyph.clone()); } } cache.cache_queued(|_, _| {}).expect("cache_queued"); for &(font_id, ref glyphs) in &font_glyphs { for (index, glyph) in glyphs.iter().enumerate() { let rect = cache.rect_for(font_id, glyph); assert!( rect.is_ok(), "Gpu cache rect lookup failed ({:?}) for font {} glyph index {}, id {}", rect, font_id, index, glyph.id().0 ); } } }) }); } /// Benchmark using multiple fonts and a different text group of glyphs /// each run fn bench_moving_text(c: &mut Criterion) { let chars: Vec<_> = TEST_STR.chars().collect(); let subsection_len = chars.len() / FONTS.len(); let distinct_subsection: Vec<_> = chars.windows(subsection_len).collect(); let mut first_glyphs = vec![]; let mut middle_glyphs = vec![]; let mut last_glyphs = vec![]; for (id, font) in FONTS.iter().enumerate() { let first_str: String = distinct_subsection[0].iter().collect(); first_glyphs.push((id, test_glyphs(font, &first_str))); let middle_str: String = distinct_subsection[distinct_subsection.len() / 2] .iter() .collect(); middle_glyphs.push((id, test_glyphs(font, &middle_str))); let last_str: String = distinct_subsection[distinct_subsection.len() - 1] .iter() .collect(); last_glyphs.push((id, test_glyphs(font, &last_str))); } let test_variants = [first_glyphs, middle_glyphs, last_glyphs]; let mut test_variants = test_variants.iter().cycle(); let mut cache = Cache::builder() .dimensions(1500, 1500) .scale_tolerance(0.1) .position_tolerance(0.1) .build(); c.bench_function("moving_text", |b| { b.iter(|| { // switch text variant each run to force cache to deal with moving text // requirements let glyphs = test_variants.next().unwrap(); for &(font_id, ref glyphs) in glyphs { for glyph in glyphs { cache.queue_glyph(font_id, glyph.clone()); } } cache.cache_queued(|_, _| {}).expect("cache_queued"); for &(font_id, ref glyphs) in glyphs { for (index, glyph) in glyphs.iter().enumerate() { let rect = cache.rect_for(font_id, glyph); assert!( rect.is_ok(), "Gpu cache rect lookup failed ({:?}) for font {} glyph index {}, id {}", rect, font_id, index, glyph.id().0 ); } } }) }); } // ************************************************************************** // Benchmarks for cases that should generally be avoided by the cache user if // at all possible (ie by picking a better initial cache size). // ************************************************************************** /// Cache isn't large enough for a queue so a new cache is created to hold /// the queue. fn bench_resizing(c: &mut Criterion) { let up_to_index = TEST_STR.char_indices().nth(120).unwrap().0; let string = &TEST_STR[..up_to_index]; let font_glyphs: Vec<_> = FONTS .iter() .enumerate() .map(|(id, font)| (id, test_glyphs(font, string))) .collect(); c.bench_function("resizing", |b| { b.iter(|| { let mut cache = Cache::builder().dimensions(256, 256).build(); for &(font_id, ref glyphs) in &font_glyphs { for glyph in glyphs { cache.queue_glyph(font_id, glyph.clone()); } } cache .cache_queued(mock_gpu_upload) .expect_err("shouldn't fit"); cache.to_builder().dimensions(512, 512).rebuild(&mut cache); cache.cache_queued(mock_gpu_upload).expect("should fit now"); for &(font_id, ref glyphs) in &font_glyphs { for (index, glyph) in glyphs.iter().enumerate() { let rect = cache.rect_for(font_id, glyph); assert!( rect.is_ok(), "Gpu cache rect lookup failed ({:?}) for font {} glyph index {}, id {}", rect, font_id, index, glyph.id().0 ); } } }) }); } /// Benchmark using multiple fonts and a different text group of glyphs /// each run. The cache is only large enough to fit each run if it is /// cleared and re-built. fn bench_moving_text_thrashing(c: &mut Criterion) { let chars: Vec<_> = TEST_STR.chars().collect(); let subsection_len = 60; let distinct_subsection: Vec<_> = chars.windows(subsection_len).collect(); let mut first_glyphs = vec![]; let mut middle_glyphs = vec![]; let mut last_glyphs = vec![]; for (id, font) in FONTS.iter().enumerate() { let first_str: String = distinct_subsection[0].iter().collect(); first_glyphs.push((id, test_glyphs(font, &first_str))); let middle_str: String = distinct_subsection[distinct_subsection.len() / 2] .iter() .collect(); middle_glyphs.push((id, test_glyphs(font, &middle_str))); let last_str: String = distinct_subsection[distinct_subsection.len() - 1] .iter() .collect(); last_glyphs.push((id, test_glyphs(font, &last_str))); } let test_variants = [first_glyphs, middle_glyphs, last_glyphs]; // Cache is only a little larger than each variants size meaning a lot of // re-ordering, re-rasterization & re-uploading has to occur. let mut cache = Cache::builder() .dimensions(320, 320) .scale_tolerance(0.1) .position_tolerance(0.1) .build(); c.bench_function("moving_text_thrashing", |b| { b.iter(|| { // switch text variant each run to force cache to deal with moving text // requirements for glyphs in &test_variants { for &(font_id, ref glyphs) in glyphs { for glyph in glyphs { cache.queue_glyph(font_id, glyph.clone()); } } cache.cache_queued(mock_gpu_upload).expect("cache_queued"); for &(font_id, ref glyphs) in glyphs { for (index, glyph) in glyphs.iter().enumerate() { let rect = cache.rect_for(font_id, glyph); assert!( rect.is_ok(), "Gpu cache rect lookup failed ({:?}) for font {} glyph index {}, id {}", rect, font_id, index, glyph.id().0 ); } } } }) }); } criterion_group!( benches, bench_high_position_tolerance, bench_single_ttf, bench_single_otf, bench_multi_font, bench_multi_font_population, bench_moving_text, bench_resizing, bench_moving_text_thrashing, ); criterion_main!(benches);<|fim▁end|>
use rusttype::*;
<|file_name|>error.rs<|end_file_name|><|fim▁begin|>use rocket::http::Status; use rocket::response::{Response, Responder, status}; use rocket_contrib::JSON;<|fim▁hole|>#[derive(Debug)] pub enum ApiError { MultipleError(MultipleError), } impl<'r> Responder<'r> for ApiError { fn respond(self) -> Result<Response<'r>, Status> { match self { ApiError::MultipleError(e) => { status::Custom(Status::from_code(422).unwrap(), JSON(e)).respond() } } } } impl From<MultipleError> for ApiError { fn from(e: MultipleError) -> ApiError { ApiError::MultipleError(e) } }<|fim▁end|>
use accord::MultipleError;
<|file_name|>forms.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from django import forms from django.utils.translation import ugettext_lazy as _ from taggit.forms import TagField from places_core.forms import BootstrapBaseForm<|fim▁hole|> from .models import Category, News class NewsForm(forms.ModelForm, BootstrapBaseForm): """ Edit/update/create blog entry. """ title = forms.CharField( label=_(u"Da tytuł"), max_length=64, widget=forms.TextInput(attrs={ 'class': 'form-control', 'maxlength': '64',})) tags = TagField(required=False, label= _(u"Tags")) def clean_title(self): title = self.cleaned_data['title'] return title class Meta: model = News exclude = ('edited', 'slug', 'creator',) widgets = { 'content': forms.Textarea(attrs={'class': 'form-control custom-wysiwyg'}), 'category': forms.Select(attrs={'class': 'form-control'}), 'location': forms.HiddenInput(), 'image': forms.ClearableFileInput(attrs={'class': 'civ-img-input', }), }<|fim▁end|>
<|file_name|>noop_waker.rs<|end_file_name|><|fim▁begin|>//! Utilities for creating zero-cost wakers that don't do anything. use core::task::{RawWaker, RawWakerVTable, Waker}; use core::ptr::null; #[cfg(feature = "std")] use core::cell::UnsafeCell; unsafe fn noop_clone(_data: *const ()) -> RawWaker { noop_raw_waker() } unsafe fn noop(_data: *const ()) {} const NOOP_WAKER_VTABLE: RawWakerVTable = RawWakerVTable::new(noop_clone, noop, noop, noop); fn noop_raw_waker() -> RawWaker { RawWaker::new(null(), &NOOP_WAKER_VTABLE) } /// Create a new [`Waker`] which does /// nothing when `wake()` is called on it. /// /// # Examples /// /// ``` /// use futures::task::noop_waker; /// let waker = noop_waker(); /// waker.wake(); /// ``` #[inline] pub fn noop_waker() -> Waker { unsafe { Waker::from_raw(noop_raw_waker()) } } /// Get a static reference to a [`Waker`] which /// does nothing when `wake()` is called on it. /// /// # Examples /// /// ``` /// use futures::task::noop_waker_ref; /// let waker = noop_waker_ref(); /// waker.wake_by_ref(); /// ``` #[inline] #[cfg(feature = "std")] pub fn noop_waker_ref() -> &'static Waker {<|fim▁hole|> } NOOP_WAKER_INSTANCE.with(|l| unsafe { &*l.get() }) }<|fim▁end|>
thread_local! { static NOOP_WAKER_INSTANCE: UnsafeCell<Waker> = UnsafeCell::new(noop_waker());
<|file_name|>script3.py<|end_file_name|><|fim▁begin|>def ContinueCurse():<|fim▁hole|> test_note_2 = (int(input("Type Second Test Value: "))) tmp_note = (((test_note_1 + test_note_2)/2)*0.6) if ((3 - tmp_note)/0.4) <= 5: print "Keep Studying :D" else: print "Cancel course :/" print "=== Program Finished ===" print " ==== Starting the -ContinueCourse- Script ====" ContinueCurse()<|fim▁end|>
test_note_1 = (int(input("Type first Test Value: ")))
<|file_name|>kernel_ridge_regression.py<|end_file_name|><|fim▁begin|>from pylab import figure,pcolor,scatter,contour,colorbar,show,subplot,plot,connect from numpy import array,meshgrid,reshape,linspace,min,max from numpy import concatenate,transpose,ravel from modshogun import * from modshogun import * from modshogun import * import util util.set_title('KernelRidgeRegression') width=20 # positive examples pos=util.get_realdata(True) plot(pos[0,:], pos[1,:], "r.") # negative examples neg=util.get_realdata(False) plot(neg[0,:], neg[1,:], "b.") # train svm labels = util.get_labels(type='regression') train = util.get_realfeatures(pos, neg) gk=GaussianKernel(train, train, width) krr = KernelRidgeRegression() krr.set_labels(labels) krr.set_kernel(gk) krr.set_tau(1e-3) krr.train() # compute output plot iso-lines x, y, z=util.compute_output_plot_isolines(krr, gk, train, regression=True) <|fim▁hole|>connect('key_press_event', util.quit) show()<|fim▁end|>
pcolor(x, y, z, shading='interp') contour(x, y, z, linewidths=1, colors='black', hold=True)
<|file_name|>test_views.py<|end_file_name|><|fim▁begin|>from s3authbasic.testing import BaseAppTest, AUTH_ENVIRON class ViewsTests(BaseAppTest): def test_validpath(self): for (path, expect) in ( ('/', 'home'), ('/index.html', 'home'), ('/level1', 'level 1'), ('/level1/', 'level 1'), ('/level1/index.html', 'level 1'), ('/level1/other.html', 'other'), ('/level1/level2', 'level 2'), ('/level1/level2/index.html', 'level 2'), ('/blue%20child', 'whitespace'), ('/blue%20child/index.html', 'whitespace'), ): result = self.testapp.get(path, extra_environ=AUTH_ENVIRON, status=200) self.assertTrue(expect in result.body) def test_not_validpath(self): for path in ( '/other.html', '/index', '/level1/index', '/level3/', ): self.testapp.get(path, extra_environ=AUTH_ENVIRON, status=404)<|fim▁hole|> def test_mimetypes(self): for (path, mimetype) in ( ('/', 'text/html'), ('/index.html', 'text/html'), ('/example.jpeg', 'image/jpeg'), ): result = self.testapp.get(path, extra_environ=AUTH_ENVIRON) self.assertEqual(result.content_type, mimetype)<|fim▁end|>
class MimeTypeTests(BaseAppTest):
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from d51.django.auth.decorators import auth_required from django.contrib.sites.models import Site from django.http import Http404, HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from django.core.exceptions import ImproperlyConfigured from .services import load_service, SharingServiceInvalidForm from .models import URL SHARE_KEY='u' @auth_required() def share_url(request, service_name): # TODO: this view needs testing response = HttpResponseRedirect(request.GET.get('next', '/')) url_to_share = request.GET.get(SHARE_KEY, None)<|fim▁hole|> else: full_url_to_share = 'http://%s%s' % ((Site.objects.get_current().domain, url_to_share)) if url_to_share.find(':') == -1 else url_to_share url, created = URL.objects.get_or_create( url=full_url_to_share, ) try: url.send(service_name, request.user, request.POST) except SharingServiceInvalidForm: service = load_service(service_name, url) input = [] if request.method != 'POST' else [request.POST] form = service.get_form_class()(*input) templates, context = [ 'sharing/%s/prompt.html'%service_name, 'sharing/prompt.html' ],{ 'service_name':service_name, 'form': form, 'url':url_to_share, 'SHARE_KEY':SHARE_KEY, 'next':request.GET.get('next','/') } response = render_to_response(templates, context, context_instance=RequestContext(request)) except ImproperlyConfigured: raise Http404 return response<|fim▁end|>
if url_to_share is None: # TODO change to a 400 raise Http404
<|file_name|>clientset_generated.go<|end_file_name|><|fim▁begin|>package fake import ( clientset "github.com/openshift/origin/pkg/image/generated/clientset" imagev1 "github.com/openshift/origin/pkg/image/generated/clientset/typed/image/v1" fakeimagev1 "github.com/openshift/origin/pkg/image/generated/clientset/typed/image/v1/fake" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/discovery" fakediscovery "k8s.io/client-go/discovery/fake" "k8s.io/client-go/testing" ) // NewSimpleClientset returns a clientset that will respond with the provided objects. // It's backed by a very simple object tracker that processes creates, updates and deletions as-is, // without applying any validations and/or defaults. It shouldn't be considered a replacement // for a real clientset and is mostly useful in simple unit tests. func NewSimpleClientset(objects ...runtime.Object) *Clientset { o := testing.NewObjectTracker(registry, scheme, codecs.UniversalDecoder()) for _, obj := range objects { if err := o.Add(obj); err != nil {<|fim▁hole|> panic(err) } } fakePtr := testing.Fake{} fakePtr.AddReactor("*", "*", testing.ObjectReaction(o, registry.RESTMapper())) fakePtr.AddWatchReactor("*", testing.DefaultWatchReactor(watch.NewFake(), nil)) return &Clientset{fakePtr} } // Clientset implements clientset.Interface. Meant to be embedded into a // struct to get a default implementation. This makes faking out just the method // you want to test easier. type Clientset struct { testing.Fake } func (c *Clientset) Discovery() discovery.DiscoveryInterface { return &fakediscovery.FakeDiscovery{Fake: &c.Fake} } var _ clientset.Interface = &Clientset{} // ImageV1 retrieves the ImageV1Client func (c *Clientset) ImageV1() imagev1.ImageV1Interface { return &fakeimagev1.FakeImageV1{Fake: &c.Fake} } // Image retrieves the ImageV1Client func (c *Clientset) Image() imagev1.ImageV1Interface { return &fakeimagev1.FakeImageV1{Fake: &c.Fake} }<|fim▁end|>
<|file_name|>set_default_list.go<|end_file_name|><|fim▁begin|>package lists // This file is generated by methodGenerator. // DO NOT MOTIFY THIS FILE. import ( "net/url" "github.com/kawaken/go-rtm/methods" ) // SetDefaultList returns "rtm.lists.setDefaultList" method instance. func SetDefaultList(timeline string, listID string) *methods.Method { name := "rtm.lists.setDefaultList" p := url.Values{} p.Add("method", name) p.Add("timeline", timeline) p.Add("list_id", listID)<|fim▁hole|><|fim▁end|>
return &methods.Method{Name: name, Params: p} }
<|file_name|>VisualisationFragment.java<|end_file_name|><|fim▁begin|>package uq.androidhack.flashspeak; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import java.io.File; import java.io.InputStream; import java.net.URI; import uq.androidhack.flashspeak.interfaces.TargetFileListener; import uq.androidhack.flashspeak.interfaces.TrialFileListener; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link VisualisationFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link VisualisationFragment#newInstance} factory method to * create an instance of this fragment. */ public class VisualisationFragment extends Fragment implements TargetFileListener,TrialFileListener{ private OnFragmentInteractionListener mListener; //Here is your URL defined String url = "http://vprbbc.streamguys.net/vprbbc24.mp3"; /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @return A new instance of fragment VisualisationFragment. */ public static VisualisationFragment newInstance() { VisualisationFragment fragment = new VisualisationFragment(); Bundle args = new Bundle(); //args.putString(ARG_PARAM1, param1); //args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } public VisualisationFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_visualisation, container, false); } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnFragmentInteractionListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public void onFileChange(String uri) { File file = new File (uri); ImageView ogAudioSampleImageView = (ImageView)getView().findViewById(R.id.originalAudioSampleVisualisation); ogAudioSampleImageView.setImageDrawable(Drawable.createFromPath(file.getAbsolutePath())); } @Override public void onRecording(URI uri) { ImageView targetAudioSampleImageView = (ImageView)getView().findViewById(R.id.usersAudioSampleVisualisation); targetAudioSampleImageView.setImageResource(android.R.color.transparent); } @Override public void onFinishProcessing(String b) { Log.i("VISUALIZER", "in HERE!"); ImageView ogAudioSampleImageView = (ImageView)getView().findViewById(R.id.originalAudioSampleVisualisation); //ogAudioSampleImageView.setImageURI(new URI(b)); new DownloadImageTask(ogAudioSampleImageView).execute(b); } private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { ImageView bmImage; public DownloadImageTask(ImageView bmImage) { this.bmImage = bmImage; } protected Bitmap doInBackground(String... urls) { String urldisplay = urls[0]; Bitmap mIcon11 = null; try { InputStream in = new java.net.URL(urldisplay).openStream(); mIcon11 = BitmapFactory.decodeStream(in); } catch (Exception e) { Log.e("Error", e.getMessage()); e.printStackTrace(); } return mIcon11; } protected void onPostExecute(Bitmap result) { bmImage.setImageBitmap(result); } }<|fim▁hole|> * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p/> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { public void onFragmentInteraction(Bitmap uri); } }<|fim▁end|>
/** * This interface must be implemented by activities that contain this
<|file_name|>LupusDataset.py<|end_file_name|><|fim▁begin|>import abc import math import numpy from scipy.io import loadmat from Configs import Configs from Paths import Paths from datasets.LupusFilter import VisitsFilter, \ NullFIlter, TemporalSpanFilter from infos.Info import Info, NullInfo from infos.InfoElement import SimpleDescription, PrintableInfoElement from infos.InfoGroup import InfoGroup from infos.InfoList import InfoList from datasets.Batch import Batch from datasets.Dataset import Dataset import os # TO CHECK normalization, selected features class BuildBatchStrategy(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def build_batch(self, patience): """build up a batch according to the strategy""" @abc.abstractmethod def keys(self) -> list: """return the keys of the sets to be used with this strategy""" @abc.abstractmethod def n_in(self, num_pat_feats): """returns the number of features each batch is composed of given the number of features of each visits of a patience""" class PerVisitTargets(BuildBatchStrategy): def n_in(self, num_pat_feats): return num_pat_feats def __init__(self): pass def keys(self) -> list: return ['early_pos', 'late_pos', 'neg'] def build_batch(self, patience): feats = patience['features'] targets = patience['targets'] n_visits = len(targets) mask = numpy.ones_like(feats) return feats[0:n_visits - 1, :], targets[1:n_visits, :], mask class PerPatienceTargets(BuildBatchStrategy): def n_in(self, num_pat_feats): return num_pat_feats def keys(self) -> list: return ['neg', 'late_pos'] def build_batch(self, patience): feats = patience['features'] targets = patience['targets'] non_zero_indexes = numpy.where(targets > 0)[0] if len(non_zero_indexes) > 0: first_positive_idx = numpy.min(non_zero_indexes) assert (first_positive_idx > 0) outputs = numpy.zeros(shape=(first_positive_idx, 1), dtype=Configs.floatType) outputs[-1] = 1 inputs = feats[0:first_positive_idx, :] else: inputs = feats[0:-1, :] outputs = targets[0:-1, :] mask = numpy.zeros_like(outputs) mask[-1, :] = 1 return inputs, outputs, mask class TemporalDifferenceTargets(BuildBatchStrategy): def n_in(self, num_pat_feats): return num_pat_feats def keys(self) -> list: return ['neg', 'late_pos'] def build_batch(self, patience):<|fim▁hole|> outputs = numpy.zeros(shape=(1, 1), dtype=Configs.floatType) inputs = numpy.zeros(shape=(1, feats.shape[1]), dtype=Configs.floatType) non_zero_indexes = numpy.where(targets > 0)[0] if len(non_zero_indexes) > 0: first_positive_idx = numpy.min(non_zero_indexes) assert (first_positive_idx > 0) outputs[0, :] = 1 inputs[0, :] = feats[first_positive_idx - 1, :] - feats[0, :] else: inputs[0, :] = feats[-2, :] - feats[0, :] outputs[0, :] = targets[-2, :] mask = numpy.zeros_like(outputs) mask[0, :] = 1 return inputs, outputs, mask class LastAndFirstVisitsTargets(BuildBatchStrategy): def n_in(self, num_pat_feats): return num_pat_feats * 2 def keys(self) -> list: return ['neg', 'late_pos'] def build_batch(self, patience): feats = patience['features'] targets = patience['targets'] outputs = numpy.zeros(shape=(1, 1), dtype=Configs.floatType) inputs = numpy.zeros(shape=(1, feats.shape[1] * 2), dtype=Configs.floatType) non_zero_indexes = numpy.where(targets > 0)[0] if len(non_zero_indexes) > 0: first_positive_idx = numpy.min(non_zero_indexes) assert (first_positive_idx > 0) outputs[0, :] = 1 inputs[0, :] = numpy.concatenate((feats[first_positive_idx - 1, :], feats[0, :]), axis=0) else: inputs[0, :] = numpy.concatenate((feats[-2, :], feats[0, :]), axis=0) outputs[0, :] = targets[-2, :] mask = numpy.zeros_like(outputs) mask[0, :] = 1 return inputs, outputs, mask class LupusDataset(Dataset): @staticmethod def parse_mat(mat_file: str, feature_names:list=None): mat_obj = loadmat(mat_file) positive_patients = mat_obj['pazientiPositivi'] negative_patients = mat_obj['pazientiNegativi'] features_struct = mat_obj['selectedFeatures'] # features_struct = mat_obj['featuresVip7'] features_names = LupusDataset.__find_features_names(features_struct) if feature_names is None else feature_names # features_names = ['DNA', 'arthritis', 'c3level', 'c4level', 'hematological', 'skinrash', 'sledai2kInferred'] # # features_names = ['APS', 'DNA', 'FM', 'Hashimoto', 'MyasteniaGravis', 'SdS', # 'arterialthrombosis', 'arthritis', 'c3level', 'c4level', 'dislipidemia', 'hcv', # 'hematological', 'hypertension', 'hypothyroidism', 'kidney', 'mthfr', 'npsle', # 'pregnancypathology', 'serositis', 'sex', 'skinrash', 'sledai2kInferred', # 'venousthrombosis'] # first 10 in ranking # features_names = ["c4level", "c3level", "arthritis", "arterialthrombosis", "SdS", "MyasteniaGravis", "Hashimoto", "FM", "DNA", "APS"] # last 10 in ranking # features_names = ["venousthrombosis", "sledai2kInferred", "skinrash", "sex", "serositis", "pregnancypathology", # "npsle", "mthfr", "kidney", "hypothyroidism"] # last 10 without sledai # features_names = ["venousthrombosis", "serositis", "pregnancypathology", "mthfr", "kidney", "hypothyroidism"] # in-between # features_names = ["hypertension", "hematological", "hcv", "dislipidemia"] # features_names = ['APS' 'DNA' 'FM' 'Hashimoto' 'MyasteniaGravis' 'SdS' 'age' # 'arterialthrombosis' 'arthritis' 'c3level' 'c4level' 'dislipidemia' 'hcv' # 'hematological' 'hypertension' 'hypothyroidism' 'kidney' 'mthfr' 'npsle' # 'pregnancypathology' 'serositis' 'sex' 'skinrash' 'sledai2kInferred' # 'venousthrombosis' 'yearOfDisease'] # features_names = ['age', 'MyasteniaGravis', 'arthritis', 'c3level', 'c4level', 'hematological', 'skinrash', 'sledai2kInferred'] return positive_patients, negative_patients, features_names @staticmethod def load_mat(mat_file: str, visit_selector: VisitsFilter = NullFIlter(), seed=Configs.seed, features_names:list=None): positive_patients, negative_patients, features_names = LupusDataset.parse_mat(mat_file=mat_file, feature_names=features_names) data = numpy.concatenate((positive_patients, negative_patients), axis=0) features_normalizations = LupusDataset.__find_normalization_factors(features_names, data) result = LupusDataset.__process_patients(data, features_names, features_normalizations, visit_selector=visit_selector) #################### # folder = '/home/giulio' # os.makedirs(folder, exist_ok=True) # prefix = folder + '/' # file = open(prefix + "visits_pos.txt", "w") # exs = result["late_pos"] # for i in range(len(exs)): # pat = LupusDataset.__get_patience_descr(exs[i]) + "\n" # file.write(pat) # file.close() #################### early_positives = result["early_pos"] late_positives = result["late_pos"] negatives = result["neg"] rng = numpy.random.RandomState(seed) rng.shuffle(early_positives) rng.shuffle(late_positives) rng.shuffle(negatives) infos = InfoGroup('Lupus Dataset', InfoList(PrintableInfoElement('features', '', features_names), PrintableInfoElement('normalizations', '', features_normalizations), PrintableInfoElement('early positives', ':d', len(early_positives)), PrintableInfoElement('late positives', ':d', len(late_positives)), PrintableInfoElement('negatives', ':d', len(negatives)), visit_selector.infos)) return early_positives, late_positives, negatives, result["max_visits_late_pos"], result[ "max_visits_neg"], features_names, infos @staticmethod def __split_set(set, i, k): n = len(set) m = int(float(n) / k) start = m * i end = int(start + m if i < k - 1 else n) return set[0:start] + set[end:], set[start:end] @staticmethod def no_test_dataset(mat_file: str, strategy: BuildBatchStrategy = PerVisitTargets, seed: int = Configs.seed, visit_selector: VisitsFilter = NullFIlter(), feats: list = None): early_positives, late_positives, negatives, max_visits_pos, max_visits_neg, features_names, infos = LupusDataset.load_mat( mat_file, visit_selector=visit_selector, features_names=feats) train_set = dict(early_pos=early_positives, late_pos=late_positives, neg=negatives, max_pos=max_visits_pos, max_neg=max_visits_neg) data_dict = dict(train=train_set, test=train_set, features=features_names) return LupusDataset(data=data_dict, infos=infos, seed=seed, strategy=strategy, feats=feats) @staticmethod def k_fold_test_datasets(mat_file: str, k: int = 1, strategy: BuildBatchStrategy = PerVisitTargets(), seed: int = Configs.seed, visit_selector: VisitsFilter = NullFIlter(), feats: list = None): early_positives, late_positives, negatives, max_visits_pos, max_visits_neg, features_names, infos = LupusDataset.load_mat( mat_file, visit_selector=visit_selector, features_names=feats) for i in range(k): eptr, epts = LupusDataset.__split_set(early_positives, i=i, k=k) lptr, lpts = LupusDataset.__split_set(late_positives, i=i, k=k) ntr, nts = LupusDataset.__split_set(negatives, i=i, k=k) train_set = dict(early_pos=eptr, late_pos=lptr, neg=ntr, max_pos=max_visits_pos, max_neg=max_visits_neg) test_set = dict(early_pos=epts, late_pos=lpts, neg=nts, max_pos=max_visits_pos, max_neg=max_visits_neg) data_dict = dict(train=train_set, test=test_set, features=features_names) yield LupusDataset(data=data_dict, infos=infos, seed=seed, strategy=strategy, feats=feats) @staticmethod def get_set_info(set): return InfoList(PrintableInfoElement('early_pos', ':d', len(set['early_pos'])), PrintableInfoElement('late_pos', ':d', len(set['late_pos'])), PrintableInfoElement('neg', ':d', len(set['neg']))) def __init__(self, data: dict, infos: Info = NullInfo(), strategy: BuildBatchStrategy = PerVisitTargets(), seed: int = Configs.seed, feats: list = None): self.__train = data['train'] self.__test = data['test'] self.__features = data['features'] if feats is None else feats self.__rng = numpy.random.RandomState(seed) self.__n_in = strategy.n_in(len(self.__features)) self.__n_out = 1 self.__build_batch_strategy = strategy # TODO add infos split_info = InfoGroup('split', InfoList(InfoGroup('train', InfoList(LupusDataset.get_set_info(self.__train))), InfoGroup('test', InfoList(LupusDataset.get_set_info(self.__test))))) self.__infos = InfoList(infos, split_info) def format_row(self, row): s = str(row).replace("[", '').replace("]", "") return ' '.join(s.split()) + "\n" def write_to_file(self, batch: Batch, folder: str, name: str): os.makedirs(folder, exist_ok=True) prefix = folder + '/' + name feats_file = open(prefix + "_features.txt", "w") labels_file = open(prefix + "_labels_txt", "w") for i in range(batch.inputs.shape[2]): example = batch.inputs[0, :, i] feats_file.write(self.format_row(example)) labels_file.write(self.format_row(batch.outputs[0, :, i])) feats_file.close() labels_file.close() @staticmethod def __find_features_names(features): names = [] if isinstance(features, numpy.ndarray) or isinstance(features, numpy.void): for obj in features: names.extend(LupusDataset.__find_features_names(obj)) return numpy.unique(names) elif isinstance(features, numpy.str_): return [str(features)] else: raise TypeError('got type: {}, expected type is "numpy.str_"', type(features)) @staticmethod def __find_normalization_factors(fetures_names, data): vals = dict() for f in fetures_names: data_f = data[f] vals[f] = (dict(min=min(data_f).item().item(), max=max(data_f).item().item())) return vals # # @staticmethod # def __split_positive(positives): # # early_positives = [] # late_positives = [] # # for p in positives: # targets = p['targets'] # assert (sum(targets) > 0) # if targets[0] > 0: # early_positives.append(p) # else: # late_positives.append(p) # # return early_positives, late_positives @staticmethod def __process_patients(mat_data, features_names, features_normalizations, visit_selector) -> dict: result = dict(early_pos=[], late_pos=[], neg=[], max_visits_late_pos=0, max_visits_neg=0) n_features = len(features_names) patients_ids = numpy.unique(mat_data['PazienteId']) for id in patients_ids: visits_indexes = mat_data['PazienteId'] == id.item() visits = mat_data[visits_indexes] visits = sorted(visits, key=lambda visit: visit['numberVisit'].item()) visits = visit_selector.select_visits(visits) n_visits = len(visits) if n_visits > 0: pat_matrix = numpy.zeros(shape=(n_visits, n_features)) target_vec = numpy.zeros(shape=(n_visits, 1)) for j in range(n_visits): target_vec[j] = 1 if visits[j]['sdi'] > 0 else 0 # sdi is greater than one for positive patients for k in range(n_features): f_name = features_names[k] a = features_normalizations[f_name]['min'] b = features_normalizations[f_name]['max'] pat_matrix[j, k] = (visits[j][f_name].item() - a) / (b - a) # nomalization # pat_matrix[j, k] = visits[j][f_name].item() # nomalization d = dict(features=pat_matrix, targets=target_vec) if visits[0]['sdi'] > 0: result["early_pos"].append(d) elif visits[-1]['sdi'] > 0: result["late_pos"].append(d) result["max_visits_late_pos"] = max(result["max_visits_late_pos"], n_visits) else: result["neg"].append(d) result["max_visits_neg"] = max(result["max_visits_neg"], n_visits) return result @staticmethod def __get_patience_descr(pat_dict): features = pat_dict['features'] targets = pat_dict['targets'] n_visits = len(targets) assert (n_visits == features.shape[0]) visits_descr = [] for i in range(n_visits): visits_descr.append('Visit {}:\n features: {}\t targets(sdi): {}\n'.format(i, features[i, :], targets[i])) return ''.join(visits_descr) @staticmethod def print_results(patient_number, batch, y): n_visits = int(sum(sum(batch.mask[:, :, patient_number])).item()) print('Patient {}: number of visits: {}'.format(patient_number, n_visits)) print('Net output,\tLabel') for i in range(n_visits): print('\t{:01.2f},\t {:01.0f}'.format(y[i, :, patient_number].item(), batch.outputs[i, :, patient_number].item())) def __build_batch(self, indexes, sets, max_length) -> Batch: max_length -= 1 n_sets = len(sets) n_batch_examples = 0 for i in indexes: n_batch_examples += len(i) inputs = numpy.zeros(shape=(max_length, self.__n_in, n_batch_examples)) outputs = numpy.zeros(shape=(max_length, self.__n_out, n_batch_examples)) mask = numpy.zeros_like(outputs) partial_idx = 0 for i in range(n_sets): bs = len(indexes[i]) for j in range(bs): idx = indexes[i][j] pat = sets[i][idx] feats, targets, pat_mask = self.__build_batch_strategy.build_batch(pat) n = feats.shape[0] assert (n == targets.shape[0]) index = partial_idx + j inputs[0:n, :, index] = feats outputs[0:n, :, index] = targets mask[0:n, :, index] = pat_mask partial_idx += bs return Batch(inputs, outputs, mask) def __sets_from_keys(self, data): sets = [] for key in self.__build_batch_strategy.keys(): sets.append(data[key]) return sets # def get_train_batch(self, batch_size:int): # exs = self.__sets_from_keys(self.__train) # pool = [] # for e in exs: # pool += e # # indexes = self.__rng.randint(size=(batch_size, 1), low=0, high=len(pool)) # max_length = len(pool[max(indexes, key=lambda i: len(pool[i]['targets']))]['targets']) # return self.__build_batch([indexes], [pool], max_length) def get_train_batch(self, batch_size: int) -> Batch: """return a 'Batch' of size 'batch_size'""" exs = self.__sets_from_keys(self.__train) bs = int(math.ceil(float(batch_size) / len(exs))) indexes = [] max_length = 0 for e in exs: e_indexes = self.__rng.randint(size=(bs, 1), low=0, high=len(e)) indexes.append(e_indexes) max_length = max(len(e[max(e_indexes, key=lambda i: len(e[i]['targets']))]['targets']), max_length) return self.__build_batch(indexes, exs, max_length) @property def n_in(self): return self.__n_in @property def n_out(self): return self.__n_out def __get_batch_from_whole_sets(self, sets: list, max_length: int) -> Batch: indexes = [] for e in sets: indexes.append(range(len(e))) return self.__build_batch(indexes, sets, max_length) def __get_set(self, set, mode): max_length = max(set['max_pos'], set['max_neg']) if mode == 'whole': sets = self.__sets_from_keys(set) return [self.__get_batch_from_whole_sets(sets, max_length)] elif mode == 'split': keys = self.__build_batch_strategy.keys() splits = self.__sets_from_keys(set) assert (len(keys) == len(splits)) d = dict() for i in range(len(keys)): d[keys[i]] = self.__get_batch_from_whole_sets([splits[i]], max_length=max_length) return d else: raise ValueError('unsupported value') # TODO @property def test_set(self): return self.__get_set(self.__test, mode='whole') @property def train_set(self): return self.__get_set(self.__train, mode='whole') @property def split_train(self): return self.__get_set(self.__train, mode='split') @property def split_test(self): return self.__get_set(self.__test, mode='split') @staticmethod def correct_prediction(y): """correct the prediction in such a way that the probabilities are monotonic non decreasing""" max_val = 0. result_y = y for i in range(y.shape[0]): i_val = result_y[i] result_y[i] = max(i_val, max_val) max_val = max(max_val, i_val) return result_y @staticmethod def get_scores_visits(y, t, mask): n_examples = y.shape[2] n_visits_max = n_examples * y.shape[0] reduced_mask = numpy.sum(mask, axis=1) scores = numpy.zeros(shape=(n_visits_max, 1), dtype=Configs.floatType) labels = numpy.zeros_like(scores) visit_count = 0 for i in range(n_examples): n_visits = sum(reduced_mask[:, i]) y_filtered = y[0:n_visits, :, i] t_filtered = t[0:n_visits, :, i] scores[visit_count:visit_count + n_visits] = y_filtered labels[visit_count:visit_count + n_visits] = t_filtered visit_count += n_visits return scores[0:visit_count], labels[0:visit_count] @staticmethod def get_scores_patients(y, t, mask): if numpy.sum(numpy.sum(numpy.sum(t))) <= 0: print('t', t) print('t_size ', t.shape) assert (numpy.sum(numpy.sum(numpy.sum(t))) > 0) n_examples = y.shape[2] reduced_mask = numpy.sum(mask, axis=1) scores = numpy.zeros(shape=(n_examples, 1), dtype=Configs.floatType) labels = numpy.zeros_like(scores) for i in range(n_examples): non_zero_indexes = numpy.where(reduced_mask[:, i] > 0)[0] idx = numpy.min(non_zero_indexes) scores[i] = y[idx, :, i] labels[i] = t[idx, :, i] assert (numpy.sum(scores) > 0 and numpy.sum(scores) != len(scores)) return scores, labels @staticmethod def get_scores(y, t, mask): n_examples = y.shape[2] reduced_mask = numpy.sum(mask, axis=1) scores = numpy.zeros(shape=(n_examples, 1), dtype=Configs.floatType) labels = numpy.zeros_like(scores) for i in range(n_examples): n_visits = sum(reduced_mask[:, i]) y_filtered = y[0:n_visits, :, i] t_filtered = t[0:n_visits, :, i] non_zero_indexes = numpy.nonzero(t_filtered)[0] zero_indexes = numpy.nonzero(t_filtered < 1)[0] n_non_zero = non_zero_indexes.shape[0] n_zero = zero_indexes.shape[0] assert (n_zero + n_non_zero == n_visits) if n_non_zero > 0 and n_zero > 0 and numpy.min(y_filtered[non_zero_indexes]) < numpy.max( y_filtered[zero_indexes]): # in this case the prediction is non consistent whatever the threshold is scores[i] = -1. labels[i] = 1 else: # in this case the probability are consistent, hence we choose as score (and label) # for the patience that of the visit which has the farthest score from the label to_compare_index = [] to_compare_values = [] if n_non_zero > 0: p1_index = numpy.argmin(y_filtered[non_zero_indexes]) p1 = 1. - y_filtered[p1_index] to_compare_index.append(p1_index) to_compare_values.append(p1) if n_zero > 0: p2_index = numpy.argmax(y_filtered[zero_indexes]) p2 = y_filtered[p2_index] to_compare_index.append(p2_index) to_compare_values.append(p2) j = to_compare_index[numpy.argmin(to_compare_values).item()] scores[i] = y_filtered[j].item() labels[i] = t_filtered[j].item() return scores, labels @property def infos(self): return self.__infos if __name__ == '__main__': filter = TemporalSpanFilter(min_age_span_upper=2, min_age_span_lower=2, min_visits_neg=4) dataset = LupusDataset.no_test_dataset(Paths.lupus_path, seed=13, strategy=PerPatienceTargets(), visit_selector=filter) print(dataset.infos) batch = dataset.get_train_batch(batch_size=3) print(str(batch)) # XXX REMOVEME strategy = TemporalDifferenceTargets() id = 0 for dataset in LupusDataset.k_fold_test_datasets(Paths.lupus_path, k=8, strategy=strategy, visit_selector=TemporalSpanFilter( min_age_span_upper=2, min_age_span_lower=2, min_visits_neg=5, min_visits_pos=1)): dataset.write_to_file(dataset.train_set[0], '/home/giulio', 'train_' + str(id)) dataset.write_to_file(dataset.test_set[0], '/home/giulio', 'test_' + str(id)) id += 1 a = dataset.train_set[0].inputs b = dataset.test_set[0].inputs c = numpy.concatenate((a, b), axis=2) stats = numpy.zeros(shape=(c.shape[1],)) for i in range(c.shape[2]): for j in range(c.shape[1]): a = c[:, j, i] if len(set(a)) > 1: stats[j] += 1 print('stats', stats)<|fim▁end|>
feats = patience['features'] targets = patience['targets']
<|file_name|>EpworthSleepAssessmentVo.java<|end_file_name|><|fim▁begin|>//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.generalmedical.vo; /** * Linked to core.clinical.EpworthSleepAssessment business object (ID: 1003100055). */ public class EpworthSleepAssessmentVo extends ims.core.clinical.vo.EpworthSleepAssessmentRefVo implements ims.vo.ImsCloneable, Comparable { private static final long serialVersionUID = 1L; public EpworthSleepAssessmentVo() { } public EpworthSleepAssessmentVo(Integer id, int version) { super(id, version); } public EpworthSleepAssessmentVo(ims.generalmedical.vo.beans.EpworthSleepAssessmentVoBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.chanceofsleep = bean.getChanceOfSleep() == null ? null : ims.spinalinjuries.vo.lookups.SleepEpworthChanceOfSleep.buildLookup(bean.getChanceOfSleep()); this.sleepscore = bean.getSleepScore() == null ? null : ims.spinalinjuries.vo.lookups.SleepEpworthScore.buildLookup(bean.getSleepScore()); } public void populate(ims.vo.ValueObjectBeanMap map, ims.generalmedical.vo.beans.EpworthSleepAssessmentVoBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.chanceofsleep = bean.getChanceOfSleep() == null ? null : ims.spinalinjuries.vo.lookups.SleepEpworthChanceOfSleep.buildLookup(bean.getChanceOfSleep()); this.sleepscore = bean.getSleepScore() == null ? null : ims.spinalinjuries.vo.lookups.SleepEpworthScore.buildLookup(bean.getSleepScore()); } public ims.vo.ValueObjectBean getBean() { return this.getBean(new ims.vo.ValueObjectBeanMap()); } public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map) { ims.generalmedical.vo.beans.EpworthSleepAssessmentVoBean bean = null; if(map != null) bean = (ims.generalmedical.vo.beans.EpworthSleepAssessmentVoBean)map.getValueObjectBean(this); if (bean == null) { bean = new ims.generalmedical.vo.beans.EpworthSleepAssessmentVoBean(); map.addValueObjectBean(this, bean); bean.populate(map, this); } return bean; } public Object getFieldValueByFieldName(String fieldName) { if(fieldName == null) throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name"); fieldName = fieldName.toUpperCase(); if(fieldName.equals("CHANCEOFSLEEP")) return getChanceOfSleep(); if(fieldName.equals("SLEEPSCORE")) return getSleepScore(); return super.getFieldValueByFieldName(fieldName); } public boolean getChanceOfSleepIsNotNull() { return this.chanceofsleep != null; } public ims.spinalinjuries.vo.lookups.SleepEpworthChanceOfSleep getChanceOfSleep() { return this.chanceofsleep; } public void setChanceOfSleep(ims.spinalinjuries.vo.lookups.SleepEpworthChanceOfSleep value) { this.isValidated = false; this.chanceofsleep = value; } public boolean getSleepScoreIsNotNull() { return this.sleepscore != null; } public ims.spinalinjuries.vo.lookups.SleepEpworthScore getSleepScore() { return this.sleepscore; } public void setSleepScore(ims.spinalinjuries.vo.lookups.SleepEpworthScore value) { this.isValidated = false; this.sleepscore = value; } public boolean isValidated() { if(this.isBusy) return true; this.isBusy = true; if(!this.isValidated) { this.isBusy = false; return false; } this.isBusy = false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(this.isBusy) return null; this.isBusy = true; java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>();<|fim▁hole|> { listOfErrors.add(existingErrors[x]); } } int errorCount = listOfErrors.size(); if(errorCount == 0) { this.isBusy = false; this.isValidated = true; return null; } String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); this.isBusy = false; this.isValidated = false; return result; } public void clearIDAndVersion() { this.id = null; this.version = 0; } public Object clone() { if(this.isBusy) return this; this.isBusy = true; EpworthSleepAssessmentVo clone = new EpworthSleepAssessmentVo(this.id, this.version); if(this.chanceofsleep == null) clone.chanceofsleep = null; else clone.chanceofsleep = (ims.spinalinjuries.vo.lookups.SleepEpworthChanceOfSleep)this.chanceofsleep.clone(); if(this.sleepscore == null) clone.sleepscore = null; else clone.sleepscore = (ims.spinalinjuries.vo.lookups.SleepEpworthScore)this.sleepscore.clone(); clone.isValidated = this.isValidated; this.isBusy = false; return clone; } public int compareTo(Object obj) { return compareTo(obj, true); } public int compareTo(Object obj, boolean caseInsensitive) { if (obj == null) { return -1; } if(caseInsensitive); // this is to avoid eclipse warning only. if (!(EpworthSleepAssessmentVo.class.isAssignableFrom(obj.getClass()))) { throw new ClassCastException("A EpworthSleepAssessmentVo object cannot be compared an Object of type " + obj.getClass().getName()); } EpworthSleepAssessmentVo compareObj = (EpworthSleepAssessmentVo)obj; int retVal = 0; if (retVal == 0) { if(this.getID_EpworthSleepAssessment() == null && compareObj.getID_EpworthSleepAssessment() != null) return -1; if(this.getID_EpworthSleepAssessment() != null && compareObj.getID_EpworthSleepAssessment() == null) return 1; if(this.getID_EpworthSleepAssessment() != null && compareObj.getID_EpworthSleepAssessment() != null) retVal = this.getID_EpworthSleepAssessment().compareTo(compareObj.getID_EpworthSleepAssessment()); } return retVal; } public synchronized static int generateValueObjectUniqueID() { return ims.vo.ValueObject.generateUniqueID(); } public int countFieldsWithValue() { int count = 0; if(this.chanceofsleep != null) count++; if(this.sleepscore != null) count++; return count; } public int countValueObjectFields() { return 2; } protected ims.spinalinjuries.vo.lookups.SleepEpworthChanceOfSleep chanceofsleep; protected ims.spinalinjuries.vo.lookups.SleepEpworthScore sleepscore; private boolean isValidated = false; private boolean isBusy = false; }<|fim▁end|>
if(existingErrors != null) { for(int x = 0; x < existingErrors.length; x++)
<|file_name|>test_modeling_mobilebert.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2020 The HuggingFace Team. 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. import unittest from transformers import MobileBertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ..test_configuration_common import ConfigTester from ..test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, MobileBertModel, ) class MobileBertModelTester: def __init__( self, parent, batch_size=13, seq_length=7, is_training=True, use_input_mask=True, use_token_type_ids=True, use_labels=True, vocab_size=99, hidden_size=64, embedding_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37, hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=16, type_sequence_label_size=2, initializer_range=0.02, num_labels=3, num_choices=4, scope=None, ): self.parent = parent self.batch_size = batch_size self.seq_length = seq_length self.is_training = is_training self.use_input_mask = use_input_mask self.use_token_type_ids = use_token_type_ids self.use_labels = use_labels self.vocab_size = vocab_size self.hidden_size = hidden_size self.embedding_size = embedding_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.intermediate_size = intermediate_size self.hidden_act = hidden_act self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.max_position_embeddings = max_position_embeddings self.type_vocab_size = type_vocab_size self.type_sequence_label_size = type_sequence_label_size self.initializer_range = initializer_range self.num_labels = num_labels self.num_choices = num_choices self.scope = scope def prepare_config_and_inputs(self): input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) input_mask = None if self.use_input_mask: input_mask = random_attention_mask([self.batch_size, self.seq_length]) token_type_ids = None if self.use_token_type_ids: token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) sequence_labels = None token_labels = None choice_labels = None if self.use_labels: sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) choice_labels = ids_tensor([self.batch_size], self.num_choices) config = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def get_config(self): return MobileBertConfig( vocab_size=self.vocab_size, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, embedding_size=self.embedding_size, hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, type_vocab_size=self.type_vocab_size, is_decoder=False, initializer_range=self.initializer_range, ) def create_and_check_mobilebert_model( self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels ): model = MobileBertModel(config=config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids) result = model(input_ids, token_type_ids=token_type_ids) result = model(input_ids) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size)) def create_and_check_mobilebert_for_masked_lm( self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels ): model = MobileBertForMaskedLM(config=config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) def create_and_check_mobilebert_for_next_sequence_prediction( self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels ): model = MobileBertForNextSentencePrediction(config=config) model.to(torch_device) model.eval() result = model( input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=sequence_labels, ) self.parent.assertEqual(result.logits.shape, (self.batch_size, 2)) def create_and_check_mobilebert_for_pretraining( self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels ): model = MobileBertForPreTraining(config=config) model.to(torch_device) model.eval() result = model( input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels, next_sentence_label=sequence_labels, ) self.parent.assertEqual(result.prediction_logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) self.parent.assertEqual(result.seq_relationship_logits.shape, (self.batch_size, 2)) def create_and_check_mobilebert_for_question_answering( self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels ): model = MobileBertForQuestionAnswering(config=config) model.to(torch_device) model.eval() result = model( input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, start_positions=sequence_labels, end_positions=sequence_labels, ) self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length)) def create_and_check_mobilebert_for_sequence_classification( self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels ): config.num_labels = self.num_labels model = MobileBertForSequenceClassification(config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=sequence_labels) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))<|fim▁hole|> def create_and_check_mobilebert_for_token_classification( self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels ): config.num_labels = self.num_labels model = MobileBertForTokenClassification(config=config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels)) def create_and_check_mobilebert_for_multiple_choice( self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels ): config.num_choices = self.num_choices model = MobileBertForMultipleChoice(config=config) model.to(torch_device) model.eval() multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() multiple_choice_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() result = model( multiple_choice_inputs_ids, attention_mask=multiple_choice_input_mask, token_type_ids=multiple_choice_token_type_ids, labels=choice_labels, ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices)) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, ) = config_and_inputs inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class MobileBertModelTest(ModelTesterMixin, unittest.TestCase): all_model_classes = ( ( MobileBertModel, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, ) if is_torch_available() else () ) fx_compatible = True # special case for ForPreTraining model def _prepare_for_class(self, inputs_dict, model_class, return_labels=False): inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels) if return_labels: if model_class in get_values(MODEL_FOR_PRETRAINING_MAPPING): inputs_dict["labels"] = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device ) inputs_dict["next_sentence_label"] = torch.zeros( self.model_tester.batch_size, dtype=torch.long, device=torch_device ) return inputs_dict def setUp(self): self.model_tester = MobileBertModelTester(self) self.config_tester = ConfigTester(self, config_class=MobileBertConfig, hidden_size=37) def test_config(self): self.config_tester.run_common_tests() def test_mobilebert_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_model(*config_and_inputs) def test_for_masked_lm(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_masked_lm(*config_and_inputs) def test_for_multiple_choice(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_multiple_choice(*config_and_inputs) def test_for_next_sequence_prediction(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*config_and_inputs) def test_for_pretraining(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_pretraining(*config_and_inputs) def test_for_question_answering(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_question_answering(*config_and_inputs) def test_for_sequence_classification(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_sequence_classification(*config_and_inputs) def test_for_token_classification(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_token_classification(*config_and_inputs) def _long_tensor(tok_lst): return torch.tensor( tok_lst, dtype=torch.long, device=torch_device, ) TOLERANCE = 1e-3 @require_torch @require_sentencepiece @require_tokenizers class MobileBertModelIntegrationTests(unittest.TestCase): @slow def test_inference_no_head(self): model = MobileBertModel.from_pretrained("google/mobilebert-uncased").to(torch_device) input_ids = _long_tensor([[101, 7110, 1005, 1056, 2023, 11333, 17413, 1029, 102]]) with torch.no_grad(): output = model(input_ids)[0] expected_shape = torch.Size((1, 9, 512)) self.assertEqual(output.shape, expected_shape) expected_slice = torch.tensor( [ [ [-2.4736526e07, 8.2691656e04, 1.6521838e05], [-5.7541704e-01, 3.9056022e00, 4.4011507e00], [2.6047359e00, 1.5677652e00, -1.7324188e-01], ] ], device=torch_device, ) # MobileBERT results range from 10e0 to 10e8. Even a 0.0000001% difference with a value of 10e8 results in a # ~1 difference, it's therefore not a good idea to measure using addition. # Here, we instead divide the expected result with the result in order to obtain ~1. We then check that the # result is held between bounds: 1 - TOLERANCE < expected_result / result < 1 + TOLERANCE lower_bound = torch.all((expected_slice / output[..., :3, :3]) >= 1 - TOLERANCE) upper_bound = torch.all((expected_slice / output[..., :3, :3]) <= 1 + TOLERANCE) self.assertTrue(lower_bound and upper_bound)<|fim▁end|>
<|file_name|>scenarios.js<|end_file_name|><|fim▁begin|>'use strict'; /* http://docs.angularjs.org/guide/dev_guide.e2e-testing */<|fim▁hole|>describe('my app', function() { beforeEach(function() { browser().navigateTo('app/index-old.html'); }); it('should automatically redirect to /view1 when location hash/fragment is empty', function() { expect(browser().location().url()).toBe("/view1"); }); describe('view1', function() { beforeEach(function() { browser().navigateTo('#/view1'); }); it('should render view1 when user navigates to /view1', function() { expect(element('[ng-view] p:first').text()). toMatch(/partial for view 1/); }); }); describe('view2', function() { beforeEach(function() { browser().navigateTo('#/view2'); }); it('should render view2 when user navigates to /view2', function() { expect(element('[ng-view] p:first').text()). toMatch(/partial for view 2/); }); }); });<|fim▁end|>
<|file_name|>policies.py<|end_file_name|><|fim▁begin|># Copyright 2013-2016 DataStax, 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. from itertools import islice, cycle, groupby, repeat import logging from random import randint from threading import Lock import socket from cassandra import ConsistencyLevel, OperationTimedOut log = logging.getLogger(__name__) class HostDistance(object): """ A measure of how "distant" a node is from the client, which may influence how the load balancer distributes requests and how many connections are opened to the node. """ IGNORED = -1 """ A node with this distance should never be queried or have connections opened to it. """ LOCAL = 0 """ Nodes with ``LOCAL`` distance will be preferred for operations under some load balancing policies (such as :class:`.DCAwareRoundRobinPolicy`) and will have a greater number of connections opened against them by default. This distance is typically used for nodes within the same datacenter as the client. """ REMOTE = 1 """ Nodes with ``REMOTE`` distance will be treated as a last resort by some load balancing policies (such as :class:`.DCAwareRoundRobinPolicy`) and will have a smaller number of connections opened against them by default. This distance is typically used for nodes outside of the datacenter that the client is running in. """ class HostStateListener(object): def on_up(self, host): """ Called when a node is marked up. """ raise NotImplementedError() def on_down(self, host): """ Called when a node is marked down. """ raise NotImplementedError() def on_add(self, host): """ Called when a node is added to the cluster. The newly added node should be considered up. """ raise NotImplementedError() def on_remove(self, host): """ Called when a node is removed from the cluster. """ raise NotImplementedError() class LoadBalancingPolicy(HostStateListener): """ Load balancing policies are used to decide how to distribute requests among all possible coordinator nodes in the cluster. In particular, they may focus on querying "near" nodes (those in a local datacenter) or on querying nodes who happen to be replicas for the requested data. You may also use subclasses of :class:`.LoadBalancingPolicy` for custom behavior. """ _hosts_lock = None def __init__(self): self._hosts_lock = Lock() def distance(self, host): """ Returns a measure of how remote a :class:`~.pool.Host` is in terms of the :class:`.HostDistance` enums. """ raise NotImplementedError() def populate(self, cluster, hosts): """ This method is called to initialize the load balancing policy with a set of :class:`.Host` instances before its first use. The `cluster` parameter is an instance of :class:`.Cluster`. """ raise NotImplementedError() def make_query_plan(self, working_keyspace=None, query=None): """ Given a :class:`~.query.Statement` instance, return a iterable of :class:`.Host` instances which should be queried in that order. A generator may work well for custom implementations of this method. Note that the `query` argument may be :const:`None` when preparing statements. `working_keyspace` should be the string name of the current keyspace, as set through :meth:`.Session.set_keyspace()` or with a ``USE`` statement. """ raise NotImplementedError() def check_supported(self): """ This will be called after the cluster Metadata has been initialized. If the load balancing policy implementation cannot be supported for some reason (such as a missing C extension), this is the point at which it should raise an exception. """ pass class RoundRobinPolicy(LoadBalancingPolicy): """ A subclass of :class:`.LoadBalancingPolicy` which evenly distributes queries across all nodes in the cluster, regardless of what datacenter the nodes may be in. This load balancing policy is used by default. """ _live_hosts = frozenset(()) def populate(self, cluster, hosts): self._live_hosts = frozenset(hosts) if len(hosts) <= 1: self._position = 0 else: self._position = randint(0, len(hosts) - 1) def distance(self, host): return HostDistance.LOCAL def make_query_plan(self, working_keyspace=None, query=None): # not thread-safe, but we don't care much about lost increments # for the purposes of load balancing pos = self._position self._position += 1 hosts = self._live_hosts length = len(hosts) if length: pos %= length return islice(cycle(hosts), pos, pos + length) else: return [] def on_up(self, host): with self._hosts_lock: self._live_hosts = self._live_hosts.union((host, )) def on_down(self, host): with self._hosts_lock: self._live_hosts = self._live_hosts.difference((host, )) def on_add(self, host): with self._hosts_lock: self._live_hosts = self._live_hosts.union((host, )) def on_remove(self, host): with self._hosts_lock: self._live_hosts = self._live_hosts.difference((host, )) class DCAwareRoundRobinPolicy(LoadBalancingPolicy): """ Similar to :class:`.RoundRobinPolicy`, but prefers hosts in the local datacenter and only uses nodes in remote datacenters as a last resort. """ local_dc = None used_hosts_per_remote_dc = 0 def __init__(self, local_dc='', used_hosts_per_remote_dc=0): """ The `local_dc` parameter should be the name of the datacenter (such as is reported by ``nodetool ring``) that should be considered local. If not specified, the driver will choose a local_dc based on the first host among :attr:`.Cluster.contact_points` having a valid DC. If relying on this mechanism, all specified contact points should be nodes in a single, local DC. `used_hosts_per_remote_dc` controls how many nodes in each remote datacenter will have connections opened against them. In other words, `used_hosts_per_remote_dc` hosts will be considered :attr:`~.HostDistance.REMOTE` and the rest will be considered :attr:`~.HostDistance.IGNORED`. By default, all remote hosts are ignored. """ self.local_dc = local_dc self.used_hosts_per_remote_dc = used_hosts_per_remote_dc self._dc_live_hosts = {} self._position = 0 self._contact_points = [] LoadBalancingPolicy.__init__(self) def _dc(self, host): return host.datacenter or self.local_dc def populate(self, cluster, hosts): for dc, dc_hosts in groupby(hosts, lambda h: self._dc(h)): self._dc_live_hosts[dc] = tuple(set(dc_hosts)) if not self.local_dc: self._contact_points = cluster.contact_points_resolved self._position = randint(0, len(hosts) - 1) if hosts else 0 def distance(self, host): dc = self._dc(host) if dc == self.local_dc: return HostDistance.LOCAL if not self.used_hosts_per_remote_dc: return HostDistance.IGNORED else: dc_hosts = self._dc_live_hosts.get(dc) if not dc_hosts: return HostDistance.IGNORED if host in list(dc_hosts)[:self.used_hosts_per_remote_dc]: return HostDistance.REMOTE else: return HostDistance.IGNORED def make_query_plan(self, working_keyspace=None, query=None): # not thread-safe, but we don't care much about lost increments # for the purposes of load balancing pos = self._position self._position += 1 local_live = self._dc_live_hosts.get(self.local_dc, ()) pos = (pos % len(local_live)) if local_live else 0 for host in islice(cycle(local_live), pos, pos + len(local_live)): yield host # the dict can change, so get candidate DCs iterating over keys of a copy other_dcs = [dc for dc in self._dc_live_hosts.copy().keys() if dc != self.local_dc] for dc in other_dcs: remote_live = self._dc_live_hosts.get(dc, ()) for host in remote_live[:self.used_hosts_per_remote_dc]: yield host def on_up(self, host): # not worrying about threads because this will happen during # control connection startup/refresh if not self.local_dc and host.datacenter: if host.address in self._contact_points: self.local_dc = host.datacenter log.info("Using datacenter '%s' for DCAwareRoundRobinPolicy (via host '%s'); " "if incorrect, please specify a local_dc to the constructor, " "or limit contact points to local cluster nodes" % (self.local_dc, host.address)) del self._contact_points dc = self._dc(host) with self._hosts_lock: current_hosts = self._dc_live_hosts.get(dc, ()) if host not in current_hosts: self._dc_live_hosts[dc] = current_hosts + (host, ) def on_down(self, host): dc = self._dc(host) with self._hosts_lock: current_hosts = self._dc_live_hosts.get(dc, ()) if host in current_hosts: hosts = tuple(h for h in current_hosts if h != host) if hosts: self._dc_live_hosts[dc] = hosts else: del self._dc_live_hosts[dc] def on_add(self, host): self.on_up(host) def on_remove(self, host): self.on_down(host) class TokenAwarePolicy(LoadBalancingPolicy): """ A :class:`.LoadBalancingPolicy` wrapper that adds token awareness to a child policy. This alters the child policy's behavior so that it first attempts to send queries to :attr:`~.HostDistance.LOCAL` replicas (as determined by the child policy) based on the :class:`.Statement`'s :attr:`~.Statement.routing_key`. Once those hosts are exhausted, the remaining hosts in the child policy's query plan will be used. If no :attr:`~.Statement.routing_key` is set on the query, the child policy's query plan will be used as is. """ _child_policy = None _cluster_metadata = None def __init__(self, child_policy): self._child_policy = child_policy def populate(self, cluster, hosts): self._cluster_metadata = cluster.metadata self._child_policy.populate(cluster, hosts) def check_supported(self): if not self._cluster_metadata.can_support_partitioner(): raise RuntimeError( '%s cannot be used with the cluster partitioner (%s) because ' 'the relevant C extension for this driver was not compiled. ' 'See the installation instructions for details on building ' 'and installing the C extensions.' % (self.__class__.__name__, self._cluster_metadata.partitioner)) def distance(self, *args, **kwargs): return self._child_policy.distance(*args, **kwargs) def make_query_plan(self, working_keyspace=None, query=None): if query and query.keyspace: keyspace = query.keyspace else: keyspace = working_keyspace child = self._child_policy if query is None: for host in child.make_query_plan(keyspace, query): yield host else: routing_key = query.routing_key if routing_key is None or keyspace is None: for host in child.make_query_plan(keyspace, query): yield host else: replicas = self._cluster_metadata.get_replicas(keyspace, routing_key) for replica in replicas: if replica.is_up and \ child.distance(replica) == HostDistance.LOCAL: yield replica for host in child.make_query_plan(keyspace, query): # skip if we've already listed this host if host not in replicas or \ child.distance(host) == HostDistance.REMOTE: yield host def on_up(self, *args, **kwargs): return self._child_policy.on_up(*args, **kwargs) def on_down(self, *args, **kwargs): return self._child_policy.on_down(*args, **kwargs) def on_add(self, *args, **kwargs): return self._child_policy.on_add(*args, **kwargs) def on_remove(self, *args, **kwargs): return self._child_policy.on_remove(*args, **kwargs) class WhiteListRoundRobinPolicy(RoundRobinPolicy): """ A subclass of :class:`.RoundRobinPolicy` which evenly distributes queries across all nodes in the cluster, regardless of what datacenter the nodes may be in, but only if that node exists in the list of allowed nodes This policy is addresses the issue described in https://datastax-oss.atlassian.net/browse/JAVA-145 Where connection errors occur when connection attempts are made to private IP addresses remotely """ def __init__(self, hosts): """ The `hosts` parameter should be a sequence of hosts to permit connections to. """ self._allowed_hosts = hosts self._allowed_hosts_resolved = [endpoint[4][0] for a in self._allowed_hosts for endpoint in socket.getaddrinfo(a, None, socket.AF_UNSPEC, socket.SOCK_STREAM)] RoundRobinPolicy.__init__(self) def populate(self, cluster, hosts): self._live_hosts = frozenset(h for h in hosts if h.address in self._allowed_hosts_resolved) if len(hosts) <= 1: self._position = 0 else: self._position = randint(0, len(hosts) - 1) def distance(self, host): if host.address in self._allowed_hosts_resolved: return HostDistance.LOCAL else: return HostDistance.IGNORED def on_up(self, host): if host.address in self._allowed_hosts_resolved: RoundRobinPolicy.on_up(self, host) def on_add(self, host): if host.address in self._allowed_hosts_resolved: RoundRobinPolicy.on_add(self, host) class ConvictionPolicy(object): """ A policy which decides when hosts should be considered down based on the types of failures and the number of failures. If custom behavior is needed, this class may be subclassed. """ def __init__(self, host): """ `host` is an instance of :class:`.Host`. """ self.host = host def add_failure(self, connection_exc): """ Implementations should return :const:`True` if the host should be convicted, :const:`False` otherwise. """ raise NotImplementedError() def reset(self): """ Implementations should clear out any convictions or state regarding the host. """ raise NotImplementedError() class SimpleConvictionPolicy(ConvictionPolicy): """ The default implementation of :class:`ConvictionPolicy`, which simply marks a host as down after the first failure of any kind. """ def add_failure(self, connection_exc): return not isinstance(connection_exc, OperationTimedOut) def reset(self): pass class ReconnectionPolicy(object): """ This class and its subclasses govern how frequently an attempt is made to reconnect to nodes that are marked as dead. If custom behavior is needed, this class may be subclassed. """ def new_schedule(self): """ This should return a finite or infinite iterable of delays (each as a floating point number of seconds) inbetween each failed reconnection attempt. Note that if the iterable is finite, reconnection attempts will cease once the iterable is exhausted. """ raise NotImplementedError() class ConstantReconnectionPolicy(ReconnectionPolicy): """ A :class:`.ReconnectionPolicy` subclass which sleeps for a fixed delay inbetween each reconnection attempt. """ def __init__(self, delay, max_attempts=64): """ `delay` should be a floating point number of seconds to wait inbetween each attempt. `max_attempts` should be a total number of attempts to be made before giving up, or :const:`None` to continue reconnection attempts forever. The default is 64. """ if delay < 0: raise ValueError("delay must not be negative") if max_attempts is not None and max_attempts < 0: raise ValueError("max_attempts must not be negative") self.delay = delay self.max_attempts = max_attempts def new_schedule(self): if self.max_attempts: return repeat(self.delay, self.max_attempts) return repeat(self.delay) class ExponentialReconnectionPolicy(ReconnectionPolicy): """ A :class:`.ReconnectionPolicy` subclass which exponentially increases the length of the delay inbetween each reconnection attempt up to a set maximum delay. """ # TODO: max_attempts is 64 to preserve legacy default behavior # consider changing to None in major release to prevent the policy # giving up forever def __init__(self, base_delay, max_delay, max_attempts=64): """ `base_delay` and `max_delay` should be in floating point units of seconds. `max_attempts` should be a total number of attempts to be made before giving up, or :const:`None` to continue reconnection attempts forever. The default is 64. """ if base_delay < 0 or max_delay < 0: raise ValueError("Delays may not be negative") if max_delay < base_delay: raise ValueError("Max delay must be greater than base delay") if max_attempts is not None and max_attempts < 0: raise ValueError("max_attempts must not be negative") self.base_delay = base_delay self.max_delay = max_delay self.max_attempts = max_attempts def new_schedule(self): i = 0 while self.max_attempts is None or i < self.max_attempts: yield min(self.base_delay * (2 ** i), self.max_delay) i += 1 class WriteType(object): """ For usage with :class:`.RetryPolicy`, this describe a type of write operation. """ SIMPLE = 0 """ A write to a single partition key. Such writes are guaranteed to be atomic and isolated. """ BATCH = 1 """ A write to multiple partition keys that used the distributed batch log to ensure atomicity. """ UNLOGGED_BATCH = 2 """ A write to multiple partition keys that did not use the distributed batch log. Atomicity for such writes is not guaranteed. """ COUNTER = 3 """ A counter write (for one or multiple partition keys). Such writes should not be replayed in order to avoid overcount. """ BATCH_LOG = 4 """ The initial write to the distributed batch log that Cassandra performs internally before a BATCH write. """ CAS = 5 """ A lighweight-transaction write, such as "DELETE ... IF EXISTS". """ WriteType.name_to_value = { 'SIMPLE': WriteType.SIMPLE, 'BATCH': WriteType.BATCH, 'UNLOGGED_BATCH': WriteType.UNLOGGED_BATCH, 'COUNTER': WriteType.COUNTER, 'BATCH_LOG': WriteType.BATCH_LOG, 'CAS': WriteType.CAS } class RetryPolicy(object): """ A policy that describes whether to retry, rethrow, or ignore coordinator timeout and unavailable failures. These are failures reported from the server side. Timeouts are configured by `settings in cassandra.yaml <https://github.com/apache/cassandra/blob/cassandra-2.1.4/conf/cassandra.yaml#L568-L584>`_. Unavailable failures occur when the coordinator cannot acheive the consistency level for a request. For further information see the method descriptions below. To specify a default retry policy, set the :attr:`.Cluster.default_retry_policy` attribute to an instance of this class or one of its subclasses. To specify a retry policy per query, set the :attr:`.Statement.retry_policy` attribute to an instance of this class or one of its subclasses. If custom behavior is needed for retrying certain operations, this class may be subclassed. """ RETRY = 0 """ This should be returned from the below methods if the operation should be retried on the same connection. """ RETHROW = 1 """ This should be returned from the below methods if the failure should be propagated and no more retries attempted. """<|fim▁hole|> should be ignored but no more retries should be attempted. """ RETRY_NEXT_HOST = 3 """ This should be returned from the below methods if the operation should be retried on another connection. """ def on_read_timeout(self, query, consistency, required_responses, received_responses, data_retrieved, retry_num): """ This is called when a read operation times out from the coordinator's perspective (i.e. a replica did not respond to the coordinator in time). It should return a tuple with two items: one of the class enums (such as :attr:`.RETRY`) and a :class:`.ConsistencyLevel` to retry the operation at or :const:`None` to keep the same consistency level. `query` is the :class:`.Statement` that timed out. `consistency` is the :class:`.ConsistencyLevel` that the operation was attempted at. The `required_responses` and `received_responses` parameters describe how many replicas needed to respond to meet the requested consistency level and how many actually did respond before the coordinator timed out the request. `data_retrieved` is a boolean indicating whether any of those responses contained data (as opposed to just a digest). `retry_num` counts how many times the operation has been retried, so the first time this method is called, `retry_num` will be 0. By default, operations will be retried at most once, and only if a sufficient number of replicas responded (with data digests). """ if retry_num != 0: return self.RETHROW, None elif received_responses >= required_responses and not data_retrieved: return self.RETRY, consistency else: return self.RETHROW, None def on_write_timeout(self, query, consistency, write_type, required_responses, received_responses, retry_num): """ This is called when a write operation times out from the coordinator's perspective (i.e. a replica did not respond to the coordinator in time). `query` is the :class:`.Statement` that timed out. `consistency` is the :class:`.ConsistencyLevel` that the operation was attempted at. `write_type` is one of the :class:`.WriteType` enums describing the type of write operation. The `required_responses` and `received_responses` parameters describe how many replicas needed to acknowledge the write to meet the requested consistency level and how many replicas actually did acknowledge the write before the coordinator timed out the request. `retry_num` counts how many times the operation has been retried, so the first time this method is called, `retry_num` will be 0. By default, failed write operations will retried at most once, and they will only be retried if the `write_type` was :attr:`~.WriteType.BATCH_LOG`. """ if retry_num != 0: return self.RETHROW, None elif write_type == WriteType.BATCH_LOG: return self.RETRY, consistency else: return self.RETHROW, None def on_unavailable(self, query, consistency, required_replicas, alive_replicas, retry_num): """ This is called when the coordinator node determines that a read or write operation cannot be successful because the number of live replicas are too low to meet the requested :class:`.ConsistencyLevel`. This means that the read or write operation was never forwared to any replicas. `query` is the :class:`.Statement` that failed. `consistency` is the :class:`.ConsistencyLevel` that the operation was attempted at. `required_replicas` is the number of replicas that would have needed to acknowledge the operation to meet the requested consistency level. `alive_replicas` is the number of replicas that the coordinator considered alive at the time of the request. `retry_num` counts how many times the operation has been retried, so the first time this method is called, `retry_num` will be 0. By default, no retries will be attempted and the error will be re-raised. """ return (self.RETRY_NEXT_HOST, consistency) if retry_num == 0 else (self.RETHROW, None) class FallthroughRetryPolicy(RetryPolicy): """ A retry policy that never retries and always propagates failures to the application. """ def on_read_timeout(self, *args, **kwargs): return self.RETHROW, None def on_write_timeout(self, *args, **kwargs): return self.RETHROW, None def on_unavailable(self, *args, **kwargs): return self.RETHROW, None class DowngradingConsistencyRetryPolicy(RetryPolicy): """ A retry policy that sometimes retries with a lower consistency level than the one initially requested. **BEWARE**: This policy may retry queries using a lower consistency level than the one initially requested. By doing so, it may break consistency guarantees. In other words, if you use this retry policy, there are cases (documented below) where a read at :attr:`~.QUORUM` *may not* see a preceding write at :attr:`~.QUORUM`. Do not use this policy unless you have understood the cases where this can happen and are ok with that. It is also recommended to subclass this class so that queries that required a consistency level downgrade can be recorded (so that repairs can be made later, etc). This policy implements the same retries as :class:`.RetryPolicy`, but on top of that, it also retries in the following cases: * On a read timeout: if the number of replicas that responded is greater than one but lower than is required by the requested consistency level, the operation is retried at a lower consistency level. * On a write timeout: if the operation is an :attr:`~.UNLOGGED_BATCH` and at least one replica acknowledged the write, the operation is retried at a lower consistency level. Furthermore, for other write types, if at least one replica acknowledged the write, the timeout is ignored. * On an unavailable exception: if at least one replica is alive, the operation is retried at a lower consistency level. The reasoning behind this retry policy is as follows: if, based on the information the Cassandra coordinator node returns, retrying the operation with the initially requested consistency has a chance to succeed, do it. Otherwise, if based on that information we know the initially requested consistency level cannot be achieved currently, then: * For writes, ignore the exception (thus silently failing the consistency requirement) if we know the write has been persisted on at least one replica. * For reads, try reading at a lower consistency level (thus silently failing the consistency requirement). In other words, this policy implements the idea that if the requested consistency level cannot be achieved, the next best thing for writes is to make sure the data is persisted, and that reading something is better than reading nothing, even if there is a risk of reading stale data. """ def _pick_consistency(self, num_responses): if num_responses >= 3: return self.RETRY, ConsistencyLevel.THREE elif num_responses >= 2: return self.RETRY, ConsistencyLevel.TWO elif num_responses >= 1: return self.RETRY, ConsistencyLevel.ONE else: return self.RETHROW, None def on_read_timeout(self, query, consistency, required_responses, received_responses, data_retrieved, retry_num): if retry_num != 0: return self.RETHROW, None elif received_responses < required_responses: return self._pick_consistency(received_responses) elif not data_retrieved: return self.RETRY, consistency else: return self.RETHROW, None def on_write_timeout(self, query, consistency, write_type, required_responses, received_responses, retry_num): if retry_num != 0: return self.RETHROW, None if write_type in (WriteType.SIMPLE, WriteType.BATCH, WriteType.COUNTER): if received_responses > 0: # persisted on at least one replica return self.IGNORE, None else: return self.RETHROW, None elif write_type == WriteType.UNLOGGED_BATCH: return self._pick_consistency(received_responses) elif write_type == WriteType.BATCH_LOG: return self.RETRY, consistency return self.RETHROW, None def on_unavailable(self, query, consistency, required_replicas, alive_replicas, retry_num): if retry_num != 0: return self.RETHROW, None else: return self._pick_consistency(alive_replicas) class AddressTranslator(object): """ Interface for translating cluster-defined endpoints. The driver discovers nodes using server metadata and topology change events. Normally, the endpoint defined by the server is the right way to connect to a node. In some environments, these addresses may not be reachable, or not preferred (public vs. private IPs in cloud environments, suboptimal routing, etc). This interface allows for translating from server defined endpoints to preferred addresses for driver connections. *Note:* :attr:`~Cluster.contact_points` provided while creating the :class:`~.Cluster` instance are not translated using this mechanism -- only addresses received from Cassandra nodes are. """ def translate(self, addr): """ Accepts the node ip address, and returns a translated address to be used connecting to this node. """ raise NotImplementedError class IdentityTranslator(AddressTranslator): """ Returns the endpoint with no translation """ def translate(self, addr): return addr<|fim▁end|>
IGNORE = 2 """ This should be returned from the below methods if the failure
<|file_name|>param_vasicek.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ Vasicek parameter class ~~~~~~~~~~~~~~~~~~~~~~~ """ from __future__ import print_function, division import numpy as np from .param_generic import GenericParam __all__ = ['VasicekParam'] class VasicekParam(GenericParam): """Parameter storage for Vasicek model. Attributes ---------- mean : float Mean of the process kappa : float Mean reversion speed eta : float Instantaneous standard deviation measure : str Under which measure (P or Q) """ def __init__(self, mean=.5, kappa=1.5, eta=.1, measure='P'): """Initialize class. Parameters ---------- mean : float Mean of the process<|fim▁hole|> kappa : float Mean reversion speed eta : float Instantaneous standard deviation measure : str Under which measure: - 'P' : physical measure - 'Q' : risk-neutral """ self.mean = mean self.kappa = kappa self.eta = eta self.measure = 'P' self.update_ajd() def is_valid(self): """Check validity of parameters. Returns ------- bool True for valid parameters, False for invalid """ return (self.kappa > 0) & (self.eta > 0) def update_ajd(self): """Update AJD representation. """ # AJD parameters self.mat_k0 = self.kappa * self.mean self.mat_k1 = -self.kappa self.mat_h0 = self.eta**2 self.mat_h1 = 0 @classmethod def from_theta(cls, theta): """Initialize parameters from parameter vector. Parameters ---------- theta : (nparams, ) array Parameter vector """ param = cls(mean=theta[0], kappa=theta[1], eta=theta[2]) param.update_ajd() return param def update(self, theta): """Update attributes from parameter vector. Parameters ---------- theta : (nparams, ) array Parameter vector """ self.mean, self.kappa, self.eta = theta self.update_ajd() @staticmethod def get_model_name(): """Return model name. Returns ------- str Parameter vector """ return 'Vasicek' @staticmethod def get_names(subset='all', measure='PQ'): """Return parameter names. Returns ------- (3, ) list of str Parameter names """ return ['mean', 'kappa', 'eta'] def get_theta(self, subset='all', measure='PQ'): """Return vector of parameters. Returns ------- (3, ) array Parameter vector """ return np.array([self.mean, self.kappa, self.eta])<|fim▁end|>
<|file_name|>grading.py<|end_file_name|><|fim▁begin|># pylint: disable=C0111 # pylint: disable=W0621 from lettuce import world, step from common import * from terrain.steps import reload_the_page from selenium.common.exceptions import ( InvalidElementStateException, WebDriverException) from nose.tools import assert_in, assert_not_in, assert_equal, assert_not_equal # pylint: disable=E0611 @step(u'I am viewing the grading settings') def view_grading_settings(step): world.click_course_settings() link_css = 'li.nav-course-settings-grading a' world.css_click(link_css) @step(u'I add "([^"]*)" new grade') def add_grade(step, many): grade_css = '.new-grade-button' for i in range(int(many)): world.css_click(grade_css) @step(u'I delete a grade') def delete_grade(step): #grade_css = 'li.grade-specific-bar > a.remove-button' #range_css = '.grade-specific-bar' #world.css_find(range_css)[1].mouseover() #world.css_click(grade_css) world.browser.execute_script('document.getElementsByClassName("remove-button")[0].click()') @step(u'I see I now have "([^"]*)" grades$') def view_grade_slider(step, how_many): grade_slider_css = '.grade-specific-bar' all_grades = world.css_find(grade_slider_css) assert_equal(len(all_grades), int(how_many)) @step(u'I move a grading section') def move_grade_slider(step): moveable_css = '.ui-resizable-e' f = world.css_find(moveable_css).first f.action_chains.drag_and_drop_by_offset(f._element, 100, 0).perform() @step(u'I see that the grade range has changed') def confirm_change(step): range_css = '.range' all_ranges = world.css_find(range_css) for i in range(len(all_ranges)): assert_not_equal(world.css_html(range_css, index=i), '0-50') @step(u'I change assignment type "([^"]*)" to "([^"]*)"$') def change_assignment_name(step, old_name, new_name): name_id = '#course-grading-assignment-name' index = get_type_index(old_name) f = world.css_find(name_id)[index] assert_not_equal(index, -1) for count in range(len(old_name)): f._element.send_keys(Keys.END, Keys.BACK_SPACE) f._element.send_keys(new_name) @step(u'I go back to the main course page') def main_course_page(step): course_name = world.scenario_dict['COURSE'].display_name.replace(' ', '_') main_page_link = '/course/{org}.{number}.{name}/branch/draft/block/{name}'.format( org=world.scenario_dict['COURSE'].org, number=world.scenario_dict['COURSE'].number, name=course_name ) world.visit(main_page_link) assert_in('Course Outline', world.css_text('h1.page-header')) @step(u'I do( not)? see the assignment name "([^"]*)"$') def see_assignment_name(step, do_not, name): assignment_menu_css = 'ul.menu > li > a' # First assert that it is there, make take a bit to redraw assert_true( world.css_find(assignment_menu_css), msg="Could not find assignment menu" ) assignment_menu = world.css_find(assignment_menu_css) allnames = [item.html for item in assignment_menu] if do_not: assert_not_in(name, allnames) else: assert_in(name, allnames) @step(u'I delete the assignment type "([^"]*)"$') def delete_assignment_type(step, to_delete): delete_css = '.remove-grading-data' world.css_click(delete_css, index=get_type_index(to_delete)) @step(u'I add a new assignment type "([^"]*)"$') def add_assignment_type(step, new_name): add_button_css = '.add-grading-data' world.css_click(add_button_css) name_id = '#course-grading-assignment-name' new_assignment = world.css_find(name_id)[-1] new_assignment._element.send_keys(new_name) @step(u'I set the assignment weight to "([^"]*)"$')<|fim▁hole|> weight_id = '#course-grading-assignment-gradeweight' weight_field = world.css_find(weight_id)[-1] old_weight = world.css_value(weight_id, -1) for count in range(len(old_weight)): weight_field._element.send_keys(Keys.END, Keys.BACK_SPACE) weight_field._element.send_keys(weight) @step(u'the assignment weight is displayed as "([^"]*)"$') def verify_weight(step, weight): weight_id = '#course-grading-assignment-gradeweight' assert_equal(world.css_value(weight_id, -1), weight) @step(u'I have populated the course') def populate_course(step): step.given('I have added a new section') step.given('I have added a new subsection') @step(u'I do not see the changes persisted on refresh$') def changes_not_persisted(step): reload_the_page(step) name_id = '#course-grading-assignment-name' assert_equal(world.css_value(name_id), 'Homework') @step(u'I see the assignment type "(.*)"$') def i_see_the_assignment_type(_step, name): assignment_css = '#course-grading-assignment-name' assignments = world.css_find(assignment_css) types = [ele['value'] for ele in assignments] assert_in(name, types) @step(u'I change the highest grade range to "(.*)"$') def change_grade_range(_step, range_name): range_css = 'span.letter-grade' grade = world.css_find(range_css).first grade.value = range_name @step(u'I see the highest grade range is "(.*)"$') def i_see_highest_grade_range(_step, range_name): range_css = 'span.letter-grade' grade = world.css_find(range_css).first assert_equal(grade.value, range_name) @step(u'I cannot edit the "Fail" grade range$') def cannot_edit_fail(_step): range_css = 'span.letter-grade' ranges = world.css_find(range_css) assert_equal(len(ranges), 2) assert_not_equal(ranges.last.value, 'Failure') # try to change the grade range -- this should throw an exception try: ranges.last.value = 'Failure' except (InvalidElementStateException): pass # We should get this exception on failing to edit the element # check to be sure that nothing has changed ranges = world.css_find(range_css) assert_equal(len(ranges), 2) assert_not_equal(ranges.last.value, 'Failure') @step(u'I change the grace period to "(.*)"$') def i_change_grace_period(_step, grace_period): grace_period_css = '#course-grading-graceperiod' ele = world.css_find(grace_period_css).first # Sometimes it takes a moment for the JavaScript # to populate the field. If we don't wait for # this to happen, then we can end up with # an invalid value (e.g. "00:0048:00") # which prevents us from saving. assert_true(world.css_has_value(grace_period_css, "00:00")) # Set the new grace period ele.value = grace_period @step(u'I see the grace period is "(.*)"$') def the_grace_period_is(_step, grace_period): grace_period_css = '#course-grading-graceperiod' # The default value is 00:00 # so we need to wait for it to change world.wait_for( lambda _: world.css_has_value(grace_period_css, grace_period) ) def get_type_index(name): name_id = '#course-grading-assignment-name' all_types = world.css_find(name_id) for index in range(len(all_types)): if world.css_value(name_id, index=index) == name: return index return -1<|fim▁end|>
def set_weight(step, weight):
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import unittest from fire_risk.models import DIST class TestDISTModel(unittest.TestCase): def test_dist_import(self):<|fim▁hole|> 'beyond': 108959L, 'object_of_origin': 383787L, 'room_of_origin': 507378L, 'building_of_origin': 529300L} dist = DIST(floor_extent=floor_extent, **results) self.assertAlmostEqual(dist.gibbs_sample(), 32.0, delta=4) if __name__ == '__main__': unittest.main()<|fim▁end|>
floor_extent = False results = {'floor_of_origin': 126896L,
<|file_name|>number_op.py<|end_file_name|><|fim▁begin|># encoding: utf-8 # # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http:# mozilla.org/MPL/2.0/. # # Contact: Kyle Lahnakoski ([email protected]) # from __future__ import absolute_import, division, unicode_literals <|fim▁hole|>from mo_sql import sql_coalesce class NumberOp(NumberOp_): @check def to_sql(self, schema, not_null=False, boolean=False): value = SQLang[self.term].to_sql(schema, not_null=True) acc = [] for c in value: for t, v in c.sql.items(): if t == "s": acc.append("CAST(" + v + " as FLOAT)") else: acc.append(v) if not acc: return wrap([]) elif len(acc) == 1: return wrap([{"name": ".", "sql": {"n": acc[0]}}]) else: return wrap([{"name": ".", "sql": {"n": sql_coalesce(acc)}}]) _utils.NumberOp = NumberOp<|fim▁end|>
from jx_base.expressions import NumberOp as NumberOp_ from jx_sqlite.expressions import _utils from jx_sqlite.expressions._utils import SQLang, check from mo_dots import wrap
<|file_name|>no_0350_intersection_of_two_arrays_ii.rs<|end_file_name|><|fim▁begin|>struct Solution; impl Solution { pub fn intersect(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> { // key => num, value => 出现的次数 let mut map = std::collections::HashMap::with_capacity(nums1.len()); for num in nums1 { let v = map.entry(num).or_insert(0); *v += 1; } let mut ans = Vec::new(); for num in nums2 { if let Some(count) = map.get_mut(&num) { if *count > 0 { *count -= 1; ans.push(num); } } } ans } // 题意理解错了 // 这个解法求的是连续出现的,题目是可以不连续的,而且顺序也无关。 pub fn intersect_failed(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> { // 练习下动态规划 let (m, n) = (nums1.len(), nums2.len()); let mut dp = vec![vec![0; n + 1]; m + 1]; let mut max_len = 0; let mut pos = (0, 0); for i in (0..m).rev() { for j in (0..n).rev() { if nums1[i] == nums2[j] { dp[i][j] = dp[i + 1][j + 1] + 1; } else { dp[i][j] = 0; } if max_len <= dp[i][j] { max_len = dp[i][j]; pos = (i, j); } } } nums1<|fim▁hole|> .map(|x| x.iter().map(|x| *x).collect()) .unwrap_or(Vec::new()) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_intersect1() { let mut res = Solution::intersect(vec![1, 2, 2, 1], vec![2, 2]); res.sort(); assert_eq!(res, vec![2, 2]); } #[test] fn test_intersect2() { let mut res = Solution::intersect(vec![4, 9, 5], vec![9, 4, 9, 8, 4]); res.sort(); assert_eq!(res, vec![4, 9]); } #[test] fn test_intersect3() { let mut res = Solution::intersect(vec![1, 2], vec![2, 1]); res.sort(); assert_eq!(res, vec![1, 2]); } }<|fim▁end|>
.get(pos.0..(pos.0 + max_len))
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! This module contains traits in script used generically in the rest of Servo. //! The traits are here instead of in script so that these modules won't have //! to depend on script. #![feature(custom_derive, plugin)] #![plugin(serde_macros)] #![deny(missing_docs)] <|fim▁hole|>extern crate msg; extern crate net_traits; extern crate profile_traits; extern crate serde; extern crate util; extern crate url; use devtools_traits::ScriptToDevtoolsControlMsg; use ipc_channel::ipc::{IpcReceiver, IpcSender}; use libc::c_void; use msg::compositor_msg::{Epoch, LayerId, ScriptToCompositorMsg}; use msg::constellation_msg::{ConstellationChan, PipelineId, Failure, WindowSizeData}; use msg::constellation_msg::{LoadData, SubpageId, Key, KeyState, KeyModifiers}; use msg::constellation_msg::{MozBrowserEvent, PipelineExitType}; use msg::webdriver_msg::WebDriverScriptCommand; use net_traits::ResourceTask; use net_traits::image_cache_task::ImageCacheTask; use net_traits::storage_task::StorageTask; use profile_traits::{mem, time}; use std::any::Any; use std::sync::mpsc::{Receiver, Sender}; use url::Url; use util::geometry::Au; use euclid::point::Point2D; use euclid::rect::Rect; /// The address of a node. Layout sends these back. They must be validated via /// `from_untrusted_node_address` before they can be used, because we do not trust layout. #[allow(raw_pointer_derive)] #[derive(Copy, Clone, Debug)] pub struct UntrustedNodeAddress(pub *const c_void); unsafe impl Send for UntrustedNodeAddress {} /// Messages sent to the layout task from the constellation and/or compositor. #[derive(Deserialize, Serialize)] pub enum LayoutControlMsg { /// Requests that this layout task exit. ExitNow(PipelineExitType), /// Requests the current epoch (layout counter) from this layout. GetCurrentEpoch(IpcSender<Epoch>), /// Asks layout to run another step in its animation. TickAnimations, /// Informs layout as to which regions of the page are visible. SetVisibleRects(Vec<(LayerId, Rect<Au>)>), } /// The initial data associated with a newly-created framed pipeline. pub struct NewLayoutInfo { /// Id of the parent of this new pipeline. pub containing_pipeline_id: PipelineId, /// Id of the newly-created pipeline. pub new_pipeline_id: PipelineId, /// Id of the new frame associated with this pipeline. pub subpage_id: SubpageId, /// Network request data which will be initiated by the script task. pub load_data: LoadData, /// The paint channel, cast to `Box<Any>`. /// /// TODO(pcwalton): When we convert this to use IPC, this will need to become an /// `IpcAnySender`. pub paint_chan: Box<Any + Send>, /// Information on what to do on task failure. pub failure: Failure, /// A port on which layout can receive messages from the pipeline. pub pipeline_port: IpcReceiver<LayoutControlMsg>, /// A shutdown channel so that layout can notify others when it's done. pub layout_shutdown_chan: Sender<()>, } /// `StylesheetLoadResponder` is used to notify a responder that a style sheet /// has loaded. pub trait StylesheetLoadResponder { /// Respond to a loaded style sheet. fn respond(self: Box<Self>); } /// Used to determine if a script has any pending asynchronous activity. #[derive(Copy, Clone, Debug, PartialEq)] pub enum ScriptState { /// The document has been loaded. DocumentLoaded, /// The document is still loading. DocumentLoading, } /// Messages sent from the constellation to the script task pub enum ConstellationControlMsg { /// Gives a channel and ID to a layout task, as well as the ID of that layout's parent AttachLayout(NewLayoutInfo), /// Window resized. Sends a DOM event eventually, but first we combine events. Resize(PipelineId, WindowSizeData), /// Notifies script that window has been resized but to not take immediate action. ResizeInactive(PipelineId, WindowSizeData), /// Notifies the script that a pipeline should be closed. ExitPipeline(PipelineId, PipelineExitType), /// Sends a DOM event. SendEvent(PipelineId, CompositorEvent), /// Notifies script that reflow is finished. ReflowComplete(PipelineId, u32), /// Notifies script of the viewport. Viewport(PipelineId, Rect<f32>), /// Requests that the script task immediately send the constellation the title of a pipeline. GetTitle(PipelineId), /// Notifies script task to suspend all its timers Freeze(PipelineId), /// Notifies script task to resume all its timers Thaw(PipelineId), /// Notifies script task that a url should be loaded in this iframe. Navigate(PipelineId, SubpageId, LoadData), /// Requests the script task forward a mozbrowser event to an iframe it owns MozBrowserEvent(PipelineId, SubpageId, MozBrowserEvent), /// Updates the current subpage id of a given iframe UpdateSubpageId(PipelineId, SubpageId, SubpageId), /// Set an iframe to be focused. Used when an element in an iframe gains focus. FocusIFrame(PipelineId, SubpageId), /// Passes a webdriver command to the script task for execution WebDriverScriptCommand(PipelineId, WebDriverScriptCommand), /// Notifies script task that all animations are done TickAllAnimations(PipelineId), /// Notifies script that a stylesheet has finished loading. StylesheetLoadComplete(PipelineId, Url, Box<StylesheetLoadResponder + Send>), /// Get the current state of the script task for a given pipeline. GetCurrentState(Sender<ScriptState>, PipelineId), } /// The mouse button involved in the event. #[derive(Clone, Debug)] pub enum MouseButton { /// The left mouse button. Left, /// The middle mouse button. Middle, /// The right mouse button. Right, } /// Events from the compositor that the script task needs to know about pub enum CompositorEvent { /// The window was resized. ResizeEvent(WindowSizeData), /// A point was clicked. ClickEvent(MouseButton, Point2D<f32>), /// A mouse button was pressed on a point. MouseDownEvent(MouseButton, Point2D<f32>), /// A mouse button was released on a point. MouseUpEvent(MouseButton, Point2D<f32>), /// The mouse was moved over a point. MouseMoveEvent(Point2D<f32>), /// A key was pressed. KeyEvent(Key, KeyState, KeyModifiers), } /// An opaque wrapper around script<->layout channels to avoid leaking message types into /// crates that don't need to know about them. pub struct OpaqueScriptLayoutChannel(pub (Box<Any + Send>, Box<Any + Send>)); /// Data needed to construct a script thread. pub struct InitialScriptState { /// The ID of the pipeline with which this script thread is associated. pub id: PipelineId, /// The subpage ID of this pipeline to create in its pipeline parent. /// If `None`, this is the root. pub parent_info: Option<(PipelineId, SubpageId)>, /// The compositor. pub compositor: IpcSender<ScriptToCompositorMsg>, /// A channel with which messages can be sent to us (the script task). pub control_chan: Sender<ConstellationControlMsg>, /// A port on which messages sent by the constellation to script can be received. pub control_port: Receiver<ConstellationControlMsg>, /// A channel on which messages can be sent to the constellation from script. pub constellation_chan: ConstellationChan, /// Information that script sends out when it panics. pub failure_info: Failure, /// A channel to the resource manager task. pub resource_task: ResourceTask, /// A channel to the storage task. pub storage_task: StorageTask, /// A channel to the image cache task. pub image_cache_task: ImageCacheTask, /// A channel to the time profiler thread. pub time_profiler_chan: time::ProfilerChan, /// A channel to the memory profiler thread. pub mem_profiler_chan: mem::ProfilerChan, /// A channel to the developer tools, if applicable. pub devtools_chan: Option<IpcSender<ScriptToDevtoolsControlMsg>>, /// Information about the initial window size. pub window_size: Option<WindowSizeData>, } /// This trait allows creating a `ScriptTask` without depending on the `script` /// crate. pub trait ScriptTaskFactory { /// Create a `ScriptTask`. fn create(_phantom: Option<&mut Self>, state: InitialScriptState, layout_chan: &OpaqueScriptLayoutChannel, load_data: LoadData); /// Create a script -> layout channel (`Sender`, `Receiver` pair). fn create_layout_channel(_phantom: Option<&mut Self>) -> OpaqueScriptLayoutChannel; /// Clone the `Sender` in `pair`. fn clone_layout_channel(_phantom: Option<&mut Self>, pair: &OpaqueScriptLayoutChannel) -> Box<Any + Send>; }<|fim▁end|>
extern crate devtools_traits; extern crate euclid; extern crate ipc_channel; extern crate libc;
<|file_name|>AndroidGenerateDynamicMacros.ts<|end_file_name|><|fim▁begin|>import { Command } from '@expo/commander'; import path from 'path'; import { generateDynamicMacrosAsync } from '../dynamic-macros/generateDynamicMacros'; import { Directories } from '../expotools';<|fim▁hole|>const GENERATED_DIR = path.join(ANDROID_DIR, 'expoview/src/main/java/host/exp/exponent/generated'); const TEMPLATE_FILES_DIR = path.join(EXPO_DIR, 'template-files'); async function generateAction(options): Promise<void> { const buildConstantsPath = options.buildConstantsPath || path.join(GENERATED_DIR, 'ExponentBuildConstants.java'); const configuration = options.configuration || process.env.CONFIGURATION || 'release'; await generateDynamicMacrosAsync({ buildConstantsPath, platform: 'android', expoKitPath: EXPO_DIR, templateFilesPath: TEMPLATE_FILES_DIR, bareExpo: options.bare, configuration, }); } export default (program: Command) => { program .command('android-generate-dynamic-macros') .option( '--buildConstantsPath [string]', 'Path to ExponentBuildConstants.java relative to `android` folder. Optional.' ) .option( '--configuration [string]', 'Build configuration. Defaults to `process.env.CONFIGURATION` or "debug".' ) .option('--bare', 'Generate macros only for the bare-expo project.') .description('Generates dynamic macros for Android client.') .asyncAction(generateAction); };<|fim▁end|>
const EXPO_DIR = Directories.getExpoRepositoryRootDir(); const ANDROID_DIR = Directories.getAndroidDir();
<|file_name|>CollectionCodexTest.java<|end_file_name|><|fim▁begin|>/* * #%L * FlatPack serialization code * %% * Copyright (C) 2012 Perka 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. * #L% */ package com.getperka.flatpack.codex; import static org.junit.Assert.assertArrayEquals;<|fim▁hole|>import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import javax.inject.Inject; import org.junit.Test; import com.getperka.flatpack.FlatPackTest; import com.getperka.flatpack.HasUuid; import com.getperka.flatpack.codexes.ArrayCodex; import com.getperka.flatpack.codexes.ListCodex; import com.getperka.flatpack.codexes.SetCodex; import com.getperka.flatpack.domain.Employee; import com.getperka.flatpack.domain.Person; import com.getperka.flatpack.util.FlatPackCollections; import com.google.inject.TypeLiteral; /** * Tests serializing collections of things. */ public class CollectionCodexTest extends FlatPackTest { @Inject private TypeLiteral<ArrayCodex<Person>> arrayPerson; @Inject private TypeLiteral<ArrayCodex<String>> arrayString; @Inject private TypeLiteral<ListCodex<Person>> listPerson; @Inject private TypeLiteral<ListCodex<String>> listString; @Inject private TypeLiteral<SetCodex<String>> setString; @Inject private Employee employee; @Test public void testArray() { String[] in = { "Hello", " ", "", null, "World!" }; String[] out = testCodex(arrayString, in); assertArrayEquals(in, out); Set<HasUuid> scanned = FlatPackCollections.setForIteration(); Employee[] in2 = { employee, null, employee }; Person[] out2 = testCodex(arrayPerson, in2, scanned); assertEquals(Collections.singleton(employee), scanned); /* * Because we're testing without a full flatpack structure, all we can expect is that a HasUuid * is created with the same UUID. The concrete type would normally be specified in the data * section, however it is missing, so we expect the configured type of the codex instead. */ Person p = out2[0]; assertNotNull(p); assertEquals(Person.class, p.getClass()); assertEquals(employee.getUuid(), p.getUuid()); } @Test public void testList() { List<String> in = Arrays.asList("Hello", " ", "", null, "World!"); Collection<String> out = testCodex(listString, in); assertEquals(in, out); Set<HasUuid> scanned = FlatPackCollections.setForIteration(); List<Person> in2 = Arrays.<Person> asList(employee, null, employee); Collection<Person> out2 = testCodex(listPerson, in2, scanned); assertEquals(Collections.singleton(employee), scanned); /* * Because we're testing without a full flatpack structure, all we can expect is that a HasUuid * is created with the same UUID. The concrete type would normally be specified in the data * section, however it is missing, so we expect the configured type of the codex instead. */ Person p = ((List<Person>) out2).get(0); assertNotNull(p); assertEquals(Person.class, p.getClass()); assertEquals(employee.getUuid(), p.getUuid()); } @Test public void testNull() { assertNull(testCodex(arrayString, null)); assertNull(testCodex(listString, null)); assertNull(testCodex(setString, null)); } @Test public void testSet() { Set<String> in = new LinkedHashSet<String>(Arrays.asList("Hello", " ", "", null, "World!")); Set<String> out = testCodex(setString, in); assertEquals(in, out); } }<|fim▁end|>
<|file_name|>issue-41803.rs<|end_file_name|><|fim▁begin|>// run-pass /// A compile-time map from identifiers to arbitrary (heterogeneous) expressions macro_rules! ident_map { ( $name:ident = { $($key:ident => $e:expr,)* } ) => { macro_rules! $name { $( ( $key ) => { $e }; )* // Empty invocation expands to nothing. Needed when the map is empty. () => {}; } }; }<|fim▁hole|>}); fn main() { my_map!(main); }<|fim▁end|>
ident_map!(my_map = { main => 0,
<|file_name|>RecomputeParameters.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- #-----------------------------------------------------------------------# # # # This file is part of the Parametric Workbench # # # # Copyright (C) 2015 Mundo Reader S.L. # # # # Author: David Estévez Fernández <[email protected]> # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # #<|fim▁hole|># # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # #-----------------------------------------------------------------------# __author__ = "David Estévez Fernández <[email protected]>" __license__ = "GNU General Public License v3 http://www.gnu.org/licenses/gpl.html" import os import FreeCAD, FreeCADGui import Parameter class RecomputeParameters: """Creates a new parameter""" def GetResources(self): icon_path = os.path.join(os.path.realpath(os.path.dirname(__file__)), 'Gui', 'Resources', 'icons', 'Force_Recompute.png') return {'Pixmap' : icon_path, # the name of a svg file available in the resources 'MenuText': 'Recompute parameters', 'ToolTip' : 'Recompute all parameters in the document'} def Activated(self): for obj in Parameter.Parameter.getAvailableParameters(): obj.touch() FreeCAD.ActiveDocument.recompute() return True def IsActive(self): """ Active only when there is a document, and Parameters have been created """ if not FreeCAD.ActiveDocument: return False else: if Parameter.Parameter.getAvailableParameters(): return True else: return False FreeCADGui.addCommand('RecomputeParameters', RecomputeParameters())<|fim▁end|>
# This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. #
<|file_name|>Options.java<|end_file_name|><|fim▁begin|>/** * * This file is part of Disco. * * Disco is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Disco is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Disco. If not, see <http://www.gnu.org/licenses/>. */ package eu.diversify.disco.cloudml; import eu.diversify.disco.population.diversity.TrueDiversity; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Options { private static final String JSON_FILE_NAME = "[^\\.]*\\.json$"; private static final String DOUBLE_LITERAL = "((\\+|-)?([0-9]+)(\\.[0-9]+)?)|((\\+|-)?\\.?[0-9]+)"; public static final String ENABLE_GUI = "-gui"; public static Options fromCommandLineArguments(String... arguments) { Options extracted = new Options(); for (String argument : arguments) { if (isJsonFile(argument)) { extracted.addDeploymentModel(argument); } else if (isDouble(argument)) { extracted.setReference(Double.parseDouble(argument)); } else if (isEnableGui(argument)) { extracted.setGuiEnabled(true); } else { throw new IllegalArgumentException("Unknown argument: " + argument); } } return extracted; } private static boolean isJsonFile(String argument) { return argument.matches(JSON_FILE_NAME); } private static boolean isDouble(String argument) { return argument.matches(DOUBLE_LITERAL); } private static boolean isEnableGui(String argument) { return argument.matches(ENABLE_GUI); } private boolean guiEnabled; private final List<String> deploymentModels; private double reference; public Options() { this.guiEnabled = false; this.deploymentModels = new ArrayList<String>(); this.reference = 0.75; } public boolean isGuiEnabled() { return guiEnabled; } public void setGuiEnabled(boolean guiEnabled) { this.guiEnabled = guiEnabled; } public double getReference() { return reference; } public void setReference(double setPoint) { this.reference = setPoint; } public List<String> getDeploymentModels() { return Collections.unmodifiableList(deploymentModels); } public void addDeploymentModel(String pathToModel) { this.deploymentModels.add(pathToModel); } public void launchDiversityController() { final CloudMLController controller = new CloudMLController(new TrueDiversity().normalise()); if (guiEnabled) { startGui(controller); } else { startCommandLine(controller); } } private void startGui(final CloudMLController controller) { java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { final Gui gui = new Gui(controller); gui.setReference(reference); gui.setFileToLoad(deploymentModels.get(0));<|fim▁hole|> } private void startCommandLine(final CloudMLController controller) { final CommandLine commandLine = new CommandLine(controller); for (String deployment : getDeploymentModels()) { commandLine.controlDiversity(deployment, reference); } } }<|fim▁end|>
gui.setVisible(true); } });
<|file_name|>model_tests.py<|end_file_name|><|fim▁begin|>from datetime import datetime, timedelta import json from django.contrib.contenttypes.models import ContentType from django.test import TestCase from django_dynamic_fixture import G, N from freezegun import freeze_time from mock import patch from issue.models import ( Assertion, ExtendedEnum, Issue, IssueAction, IssueStatus, ModelAssertion, ModelIssue, Responder, ResponderAction, load_function, ) from issue.tests.models import TestModel def function_to_load(self, *args, **kwargs): pass def is_even_number(record): return ((int(record.name) % 2) == 0, {}) class LoadFucntionTests(TestCase): def test_load_class_instance(self): func = load_function('issue.tests.model_tests.function_to_load') self.assertEqual(func, function_to_load) class ExtendedEnumTests(TestCase): class TestEnum(ExtendedEnum): red = 1 blue = 3 green = 2 def test_name_to_value(self): self.assertEqual(2, ExtendedEnumTests.TestEnum.name_to_value('green')) def test_choices(self): self.assertEqual( set([(1, 'red'), (2, 'green'), (3, 'blue')]), set(ExtendedEnumTests.TestEnum.choices())) class IssueManagerTests(TestCase): def test_get_open_issues(self): i = G(Issue) G(Issue, status=IssueStatus.Resolved.value) i3 = G(Issue) self.assertEqual(set(Issue.objects.get_open_issues()), set([i, i3])) def test_reopen_issue(self): mi = G(Issue, status=IssueStatus.Resolved.value) Issue.objects.reopen_issue(name=mi.name) self.assertEqual(IssueStatus.Open.value, Issue.objects.get(pk=mi.pk).status) def test_is_wont_fix(self): mi = G(Issue, status=IssueStatus.Wont_fix.value) self.assertTrue(Issue.objects.is_wont_fix(name=mi.name)) def test_maybe_open_issue_when_none_exists(self): """ Verify that maybe_open_issue will create a new Issue when none like it exists. """ (issue, created) = Issue.objects.maybe_open_issue(name='falafel') self.assertTrue(created) self.assertEqual(IssueStatus.Open.value, Issue.objects.get(name=issue.name).status) def test_maybe_open_issue_when_it_is_marked_as_wont_fix(self): """ Verify that maybe_open_issue will not create or return an Issue when it exists and is marked as WONT_FIX. """ issue = G(Issue, status=IssueStatus.Wont_fix.value) self.assertEqual((None, False), Issue.objects.maybe_open_issue(name=issue.name)) self.assertEqual(IssueStatus.Wont_fix.value, Issue.objects.get(pk=issue.pk).status) self.assertEqual(1, Issue.objects.filter(name=issue.name).count()) def test_maybe_open_issue_returns_already_open_issue(self): """ Verify that maybe_open_issue will return a the extant Issue of hte provided name when it is open. """ issue = G(Issue, status=IssueStatus.Open.value) (issue2, created) = Issue.objects.maybe_open_issue(name=issue.name) self.assertFalse(created) self.assertEqual(IssueStatus.Open.value, Issue.objects.get(pk=issue.pk).status) self.assertEqual(1, Issue.objects.filter(name=issue.name).count()) def maybe_open_issue_when_it_is_marked_as_resolved(self): """ Verify that maybe_open_issue will create a new issue when a Resolved one exists with the same name. """ issue = G(Issue, status=IssueStatus.Resolved.value) (issue2, created) = Issue.objects.maybe_open_issue(name=issue.name) self.assertTrue(created) self.assertEqual(IssueStatus.Open.value, Issue.objects.get(pk=issue2.pk).status) self.assertEqual(2, Issue.objects.get(name=issue2.name)) def test_resolve_open_issue(self): a = G(Assertion) issue = G(Issue, name=a.name, status=IssueStatus.Open.value) a._resolve_open_issue() self.assertEqual(IssueStatus.Resolved.value, Issue.objects.get(pk=issue.pk).status) class ModelIssueManagerTests(TestCase): def test_replace_record_with_content_type(self): record = N(TestModel) kwargs = { 'record': record, } expected_kwargs = { 'record_id': record.id, 'record_type': ContentType.objects.get_for_model(record), } self.assertEqual( expected_kwargs, ModelIssue.objects._replace_record_with_content_type(kwargs)) def test_replace_record_with_content_type_with_no_record(self): self.assertEqual({}, ModelIssue.objects._replace_record_with_content_type({})) def test_reopen_issue(self): record = G(TestModel) mi = G( ModelIssue, record_id=record.id, record_type=ContentType.objects.get_for_model(record), status=IssueStatus.Resolved.value) ModelIssue.objects.reopen_issue(name=mi.name, record=mi.record) self.assertEqual(IssueStatus.Open.value, ModelIssue.objects.get(pk=mi.pk).status) def test_is_wont_fix(self): record = G(TestModel) mi = G( ModelIssue, record_id=record.id, record_type=ContentType.objects.get_for_model(record), status=IssueStatus.Wont_fix.value) self.assertTrue(ModelIssue.objects.is_wont_fix(name=mi.name, record=mi.record)) class IssueTests(TestCase): def test__str__(self): i = Issue(name='an-issue', status=IssueStatus.Resolved.value) self.assertEqual('Issue: an-issue - IssueStatus.Resolved', str(i)) def test__is_open(self): i = N(Issue, status=IssueStatus.Open.value) self.assertTrue(i.is_open) self.assertFalse(i.is_resolved) self.assertFalse(i.is_wont_fix) def test__is_resolved(self): i = N(Issue, status=IssueStatus.Resolved.value) self.assertTrue(i.is_resolved) self.assertFalse(i.is_open) self.assertFalse(i.is_wont_fix) def test__is_wont_fix(self): i = N(Issue, status=IssueStatus.Wont_fix.value) self.assertTrue(i.is_wont_fix) self.assertFalse(i.is_resolved) self.assertFalse(i.is_open) class IssueActionTests(TestCase): def test__str__(self): ia = N(IssueAction) self.assertEqual( 'IssueResponse: {self.issue.name} - {self.responder_action} - ' '{self.success} at {self.execution_time}'.format(self=ia), str(ia) ) class ResponderTests(TestCase): def test__str__(self): self.assertEqual( 'Responder: error-.*', str(Responder(watch_pattern='error-.*')) ) @patch('issue.models.load_function', spec_set=True) def test_respond(self, load_function): # Setup the scenario target_function = 'do' issue = G(Issue, name='error-42') responder = G(Responder, issue=issue, watch_pattern='error-\d+') G(ResponderAction, responder=responder, target_function=target_function, delay_sec=0) # Run the code r = responder.respond(issue) # Verify expectations self.assertTrue(r) load_function.assert_called_with(target_function) @patch('issue.models.load_function', spec_set=True) def test_respond_ignores_non_watching_pattern(self, load_function): # Setup the scenario issue = G(Issue, name='success') responder = G(Responder, issue=issue, watch_pattern='error-\d+') G(ResponderAction, responder=responder, target_function='do') # Run the code r = responder.respond(issue) # Verify expectations self.assertFalse(r) self.assertFalse(load_function.called) def test__match(self): r = Responder(watch_pattern='error-.*') self.assertTrue(r._match('error-42')) self.assertFalse(r._match('success')) def test__get_pending_actions_for_issue(self): # Setup the scenario now = datetime(2014, 8, 11, 15, 0, 0) delta = timedelta(minutes=30) r = G(Responder) ra = G(ResponderAction, responder=r, delay_sec=delta.total_seconds()) issue = G(Issue, creation_time=now - (delta * 2)) # Run the code and verify expectation self.assertEqual(ra, r._get_pending_actions_for_issue(issue).get()) def test__get_pending_actions_for_issue_ignores_executed_actions(self): # Setup the scenario now = datetime(2014, 8, 11, 15, 0, 0) delta = timedelta(minutes=30) r = G(Responder) ra = G(ResponderAction, responder=r, delay_sec=delta.total_seconds()) issue = G(Issue, creation_time=now - (delta * 2)) G(IssueAction, issue=issue, responder_action=ra) # Run the code and verify expectation self.assertFalse(r._get_pending_actions_for_issue(issue).exists()) @patch('issue.models.load_function', spec_set=True) def test__execute_all_success(self, load_function): # Setup the scenario issue = G(Issue) responder = G(Responder, issue=issue) # Note: we don't care what the target_function path is since we patch the load_function function ra = G(ResponderAction, responder=responder, delay_sec=0) ra2 = G(ResponderAction, responder=responder, delay_sec=0) ra3 = G(ResponderAction, responder=responder, delay_sec=0) self.do_call_time = None self.do_2_call_time = None self.do_3_call_time = None def do_1(*args, **kwargs): self.do_call_time = datetime.utcnow() return True def do_2(*args, **kwargs): self.do_2_call_time = datetime.utcnow() return True def do_3(*args, **kwargs): self.do_3_call_time = datetime.utcnow() return True load_function.side_effect = [do_1, do_2, do_3] # Run the code responder._execute(issue) # Verify expectations self.assertTrue(self.do_call_time < self.do_2_call_time) self.assertTrue(self.do_2_call_time < self.do_3_call_time) self.assertTrue(IssueAction.objects.filter(issue=issue, responder_action=ra).exists()) self.assertTrue(IssueAction.objects.filter(issue=issue, responder_action=ra2).exists()) self.assertTrue(IssueAction.objects.filter(issue=issue, responder_action=ra3).exists()) @patch('issue.models.load_function', spec_set=True) def test__execute_stops_when_some_actions_are_not_yet_executable(self, load_function): # Setup the scenario delta = timedelta(seconds=30) issue = G(Issue, creation_time=datetime.utcnow() - (2 * delta)) responder = G(Responder, issue=issue) ra = G(ResponderAction, responder=responder, delay_sec=0, target_function='do_1') ra2 = G(ResponderAction, responder=responder, delay_sec=0, target_function='do_2') ra3 = G(ResponderAction, responder=responder, delay_sec=30, target_function='do_3') self.do_call_time = None self.do_2_call_time = None self.do_3_call_time = None def do_1(*args, **kwargs): self.do_call_time = datetime.utcnow() return True def do_2(*args, **kwargs): self.do_2_call_time = datetime.utcnow() return True def do_3(*args, **kwargs): self.do_3_call_time = datetime.utcnow() return True load_function.side_effect = lambda tf: {'do_1': do_1, 'do_2': do_2}[tf] # Run the code responder._execute(issue) # Verify expectations self.assertTrue(self.do_call_time < self.do_2_call_time) self.assertIsNone(self.do_3_call_time) self.assertTrue(IssueAction.objects.filter(issue=issue, responder_action=ra).exists()) self.assertTrue(IssueAction.objects.filter(issue=issue, responder_action=ra2).exists()) self.assertTrue(IssueAction.objects.filter(issue=issue, responder_action=ra3).exists()) @freeze_time(datetime(2014, 8, 13, 12)) @patch('issue.models.load_function', spec_set=True) def test__execute_resumes_after_sufficient_time(self, load_function): # Setup the scenario delta = timedelta(seconds=30) issue = G(Issue, creation_time=datetime.utcnow() - (2 * delta)) responder = G(Responder, issue=issue) ra = G(ResponderAction, responder=responder, delay_sec=0, target_function='do_1') ra2 = G(ResponderAction, responder=responder, delay_sec=delta.total_seconds(), target_function='do_2') G(IssueAction, issue=issue, responder_action=ra) self.do_called = False self.do_2_called = False def do_1(*args, **kwargs): self.do_called = True return True def do_2(*args, **kwargs): self.do_2_called = True return True load_function.side_effect = lambda tf: {'do_1': do_1, 'do_2': do_2}[tf] # Run the code responder._execute(issue) # Verify expectations self.assertFalse(self.do_called) self.assertTrue(self.do_2_called) self.assertTrue(IssueAction.objects.filter(issue=issue, responder_action=ra).exists()) self.assertTrue(IssueAction.objects.filter(issue=issue, responder_action=ra2).exists()) @patch('issue.models.load_function', spec_set=True) def test__execute_failure_does_not_stop_other_actions(self, load_function): # Setup the scenario delta = timedelta(seconds=30) issue = G(Issue, creation_time=datetime.utcnow() - (2 * delta)) responder = G(Responder, issue=issue) # Note: we don't care what the target_function path is since we patch the load_function function ra = G(ResponderAction, responder=responder, delay_sec=0) ra2 = G(ResponderAction, responder=responder, delay_sec=0) ra3 = G(ResponderAction, responder=responder, delay_sec=30) self.do_call_time = None self.do_2_call_time = None self.do_3_call_time = None def do_1(*args, **kwargs): self.do_call_time = datetime.utcnow() return None def do_2(*args, **kwargs): self.do_2_call_time = datetime.utcnow() raise Exception('what-an-exceptional-message') def do_3(*args, **kwargs): self.do_3_call_time = datetime.utcnow() return None load_function.side_effect = [do_1, do_2, do_3] # Run the code responder._execute(issue) # Verify expectations self.assertTrue(self.do_call_time < self.do_2_call_time) self.assertTrue(self.do_2_call_time < self.do_3_call_time) self.assertTrue(IssueAction.objects.filter(issue=issue, responder_action=ra).exists()) self.assertTrue(IssueAction.objects.filter(issue=issue, responder_action=ra2).exists()) self.assertTrue(IssueAction.objects.filter(issue=issue, responder_action=ra3).exists()) self.assertEqual( json.dumps(str(Exception('what-an-exceptional-message'))), IssueAction.objects.get(issue=issue, responder_action=ra2).details) class ResponderActionTests(TestCase): def test__str__(self): r = G(ResponderAction) self.assertEqual( 'ResponderAction: {responder} - {target_function} - {function_kwargs}'.format( responder=r.responder, target_function=r.target_function, function_kwargs=r.function_kwargs), str(r) ) def test_is_time_to_execute(self): # Setup the scenario now = datetime(2014, 8, 11, 15, 0, 0) delta = timedelta(minutes=30) ra = G(ResponderAction, delay_sec=delta.total_seconds()) # Run the code and verify expectation issue = N(Issue, creation_time=now - (delta * 2)) with freeze_time(now): self.assertTrue(ra.is_time_to_execute(issue)) def test_is_time_to_execute_when_not_enough_time_has_passed(self): # Setup the scenario now = datetime(2014, 8, 11, 15, 0, 0) delta = timedelta(minutes=30) ra = G(ResponderAction, delay_sec=delta.total_seconds()) # Run the code and verify expectation issue = N(Issue, creation_time=now - (delta / 2)) with freeze_time(now): self.assertFalse(ra.is_time_to_execute(issue)) @patch('issue.models.load_function', spec_set=True) def test_execute(self, load_function): # Setup the scenario target_function = 'do' issue = G(Issue) r = G(ResponderAction, target_function=target_function, function_kwargs={'foo': 'bar'}) now = datetime(2014, 8, 11, 15, 0, 0) self.assertEqual(0, IssueAction.objects.count()) load_function.return_value.return_value = None # Run the code with freeze_time(now): ia = r.execute(issue) ia.save() self.assertTrue(isinstance(ia, IssueAction)) # Verify expectations expected_issue_action_kwargs = { 'success': True, 'execution_time': now, 'responder_action': r, } load_function.assert_called_with(target_function) load_function.return_value.assert_called_with(issue, foo='bar') self.assertTrue(IssueAction.objects.filter(issue=issue, **expected_issue_action_kwargs).exists()) # The 'None' that is stored as the details is first json encoded self.assertEqual(json.dumps(None), IssueAction.objects.get().details) @patch('issue.models.load_function', spec_set=True) def test_execute_with_failure(self, load_function): # Setup the scenario target_function = 'fail' issue = G(Issue) r = G(ResponderAction, target_function=target_function, function_kwargs={'foo': 'bar'}) now = datetime(2014, 8, 11, 15, 0, 0) self.assertEqual(0, IssueAction.objects.count()) load_function.return_value.side_effect = Exception('what-an-exceptional-message') # Run the code with freeze_time(now): ia = r.execute(issue) ia.save() self.assertTrue(isinstance(ia, IssueAction)) # Verify expectations expected_issue_action_kwargs = { 'success': False, 'execution_time': now, 'responder_action': r, } load_function.assert_called_with(target_function) load_function.return_value.assert_called_with(issue, foo='bar') self.assertTrue(IssueAction.objects.filter(issue=issue, **expected_issue_action_kwargs).exists()) self.assertEqual(json.dumps(str(Exception('what-an-exceptional-message'))), IssueAction.objects.get().details) class AssertionTests(TestCase): @patch.object(Assertion, '_resolve_open_issue', spec_set=True) @patch('issue.models.load_function', spec_set=True) def test_check_when_all_is_well(self, load_function, resolve_open_issue): issue_details = { 'narg': 'baz', } load_function.return_value.return_value = (True, issue_details) assertion = G(Assertion, check_function='issue.tests.model_tests.load_function') self.assertTrue(assertion.check_assertion()) self.assertTrue(resolve_open_issue.called) @patch.object(Assertion, '_open_or_update_issue', spec_set=True) @patch('issue.models.load_function', spec_set=True) def test_check_when_all_is_not_well(self, load_function, open_or_update_issue): issue_details = { 'narg': 'baz', } load_function.return_value.return_value = (False, issue_details) assertion = G(Assertion, check_function='issue.tests.model_tests.load_function') self.assertFalse(assertion.check_assertion()) open_or_update_issue.assert_called_with(details=issue_details) def test__open_or_update_issue_when_none_exists(self): a = G(Assertion) a._open_or_update_issue({}) self.assertEqual(IssueStatus.Open.value, Issue.objects.get(name=a.name).status) def test__open_or_update_issue_when_it_is_marked_as_wont_fix(self): a = G(Assertion) issue = G(Issue, name=a.name, status=IssueStatus.Wont_fix.value) a._open_or_update_issue({}) self.assertEqual(IssueStatus.Wont_fix.value, Issue.objects.get(pk=issue.pk).status) def test__open_or_update_issue_when_it_is_marked_as_resolved(self): a = G(Assertion) G(Issue, name=a.name, status=IssueStatus.Resolved.value) issue2 = a._open_or_update_issue({}) self.assertEqual(IssueStatus.Open.value, Issue.objects.get(pk=issue2.pk).status) def test_resolve_open_issue(self): a = G(Assertion) issue = G(Issue, name=a.name, status=IssueStatus.Open.value) a._resolve_open_issue()<|fim▁hole|>class ModelAssertionTests(TestCase): def test_queryset(self): am = G(TestModel) am2 = G(TestModel) ma = N(ModelAssertion, model_type=ContentType.objects.get_for_model(TestModel)) self.assertEqual(set(ma.queryset), set([am, am2])) def test_check_all_pass(self): G(TestModel, name='0') G(TestModel, name='2') G(TestModel, name='4') ma = N( ModelAssertion, model_type=ContentType.objects.get_for_model(TestModel), check_function='issue.tests.model_tests.is_even_number') # Run the code r = ma.check_assertion() # Verify expectations self.assertTrue(r) self.assertEqual(0, ModelIssue.objects.count()) def test_check_one_fails(self): am1 = G(TestModel, name='1') G(Issue, name='0') G(Issue, name='1') ma = N( ModelAssertion, model_type=ContentType.objects.get_for_model(TestModel), check_function='issue.tests.model_tests.is_even_number') # Run the code r = ma.check_assertion() # Verify expectations self.assertFalse(r) self.assertEqual(1, ModelIssue.objects.count()) self.assertTrue( ModelIssue.objects.filter( record_id=am1.id, record_type=ContentType.objects.get_for_model(TestModel)).exists())<|fim▁end|>
self.assertEqual(IssueStatus.Resolved.value, Issue.objects.get(pk=issue.pk).status)
<|file_name|>VaultManager.py<|end_file_name|><|fim▁begin|>import os from PyQt4 import QtCore, QtGui from Extensions.Global import sizeformat class SearchWidget(QtGui.QLabel): def __init__(self, parent): QtGui.QLabel.__init__(self, parent) self._parent = parent self.setStyleSheet("""background: rgba(0, 0, 0, 50); border-radius: 0px;""") self.setFixedSize(300, 28) self.setPixmap(QtGui.QPixmap("Icons\\line")) self.setScaledContents(True) self.searchTimer = QtCore.QTimer() self.searchTimer.setSingleShot(True) self.searchTimer.setInterval(200) self.searchTimer.timeout.connect(self.gotoText) self.textFindLine = QtGui.QLineEdit(self) self.textFindLine.setStyleSheet("background: white; border-radius: 0px;") self.textFindLine.setGeometry(3, 2, 270, 23) self.textFindLine.grabKeyboard() self.textFindLine.setTextMargins(2, 1, 22, 1) self.textFindLine.textChanged.connect(self.show) self.textFindLine.textChanged.connect(self.searchTimer.start) self.clearTextFindLineButton = QtGui.QPushButton(self.textFindLine) self.clearTextFindLineButton.setGeometry(250, 2, 15, 15) self.clearTextFindLineButton.setFlat(True) self.clearTextFindLineButton.setIcon(QtGui.QIcon("Icons\\clearLeft")) self.clearTextFindLineButton.setStyleSheet("background: white; border: none;") self.clearTextFindLineButton.clicked.connect(self.textFindLine.clear) self.finderCloseButton = QtGui.QToolButton(self) self.finderCloseButton.setStyleSheet("background: none;") self.finderCloseButton.setGeometry(278, 6, 15, 15) self.finderCloseButton.setAutoRaise(True) self.finderCloseButton.setIconSize(QtCore.QSize(25, 25)) self.finderCloseButton.setIcon(QtGui.QIcon("Icons\\Cross")) self.finderCloseButton.clicked.connect(self.hide) def gotoText(self): text = self.textFindLine.text() self._parent.gotoText(text) class VaultManager(QtGui.QListWidget): def __init__(self, vaultItemCountLabel, sizeLabel, busyIndicatorWidget, parent): QtGui.QListWidget.__init__(self, parent) self.redCenter = parent self.setLayoutMode(1) self.setBatchSize(1) self.setUniformItemSizes(True) self.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection) self.setAlternatingRowColors(True) self.setIconSize(QtCore.QSize(30, 30)) self.itemSelectionChanged.connect(self.selectionMade) searchWidget = SearchWidget(self) searchWidget.move(80, 0) searchWidget.hide() self.vaultItemCountLabel = vaultItemCountLabel<|fim▁hole|> self.vaultZeroContentLabel = QtGui.QLabel("Empty", self) self.vaultZeroContentLabel.setGeometry(150, 20, 100, 50) self.vaultZeroContentLabel.setAlignment(QtCore.Qt.AlignCenter) self.vaultZeroContentLabel.setStyleSheet("background: none; font: 20px; color: lightgrey;") self.vaultZeroContentLabel.hide() self.vaultCleanUp() def gotoText(self, text): for i in self.vaultKeyList: if self.logDict[i].split('|')[0].startswith(text): index = self.vaultKeyList.index(i) self.setCurrentRow(index) break def loadVault(self): try: logList = [] self.vaultKeyList = [] file = open("Vault\\LOG","r") for i in file.readlines(): if i.strip() == '': pass else: logList.append(tuple(i.strip().split('||'))) file.close() self.logDict = dict(logList) self.vaultContentsSize = 0 self.clear() size = QtCore.QSize() size.setHeight(40) for key, property in self.logDict.items(): self.vaultKeyList.append(key) ## extract attributes attrib = self.logDict[key].split('|') # get locking time time_split = key.split('=')[0].split('-') date = QtCore.QDate(int(time_split[0]), int(time_split[1]), int(time_split[3])).toString() item = QtGui.QListWidgetItem(attrib[0]) item.setToolTip('Original Location: ' + attrib[2] + '\nModified: ' + date) item.setSizeHint(size) # assign icon if attrib[1] == "exec": item.setIcon(QtGui.QIcon("Icons\\executable")) else: item.setIcon(QtGui.QIcon("Icons\\unknown")) self.addItem(item) self.vaultContentsSize += int(attrib[3]) self.vaultItemCountLabel.setText("Items: " + str(len(self.logDict))) # display size of total files self.sizeLabel.setText(sizeformat(self.vaultContentsSize)) self.showVaultEmptyLabel() except: self.redCenter.showMessage("Problem loading items in the vault.") self.redCenter.hideMessage() def showVaultEmptyLabel(self): if self.count() > 0: self.vaultZeroContentLabel.hide() else: self.vaultZeroContentLabel.show() def selectionMade(self): self.selected = self.selectedItems() if len(self.selected) > 0: self.redCenter.unlockButton.setEnabled(True) self.redCenter.deleteButton.setEnabled(True) else: self.redCenter.unlockButton.setEnabled(False) self.redCenter.deleteButton.setEnabled(False) def vaultCleanUp(self): logList = [] file = open("Vault\\LOG","r") for i in file.readlines(): if i.strip() == '': pass else: logList.append(tuple(i.strip().split('||'))) file.close() logDict = dict(logList) filesList = os.listdir("Vault\\Files") bookedFilesList = [] for i, v in logDict.items(): bookedFilesList.append(i) for i in filesList: if i not in bookedFilesList: path = os.path.join("Vault\\Files", i) try: os.remove(path) except: pass<|fim▁end|>
self.sizeLabel = sizeLabel self.busyIndicatorWidget = busyIndicatorWidget
<|file_name|>symbols.py<|end_file_name|><|fim▁begin|>import re import abc from collections import deque from copy import copy from rdp.ast import Node from rdp.exceptions import ParseError, UnexpectedToken from rdp.utils import chain def to_symbol(str_or_symbol, copy_if_not_created=False): if isinstance(str_or_symbol, Symbol): if copy_if_not_created: return copy(str_or_symbol) return str_or_symbol if isinstance(str_or_symbol, str): return Terminal(str_or_symbol) raise TypeError("str or Symbol expected") def flatten(symbol): symbol = to_symbol(symbol, True) symbol.flatten = True return symbol def drop(symbol): symbol = to_symbol(symbol, True) symbol.drop = True return symbol def keep(symbol): symbol = to_symbol(symbol, True) symbol.drop = False return symbol def group(symbol): if isinstance(symbol, CompoundSymbol): symbol.grouped = True return symbol class Symbol(metaclass=abc.ABCMeta): def __init__(self, name=None): self.flatten = False self.transform = lambda x: x self.drop = None self.position = -1 self._name = name def named(self, name): if self._name: return Alias(self, name) self._name = name return self @property def name(self): return self._name @abc.abstractmethod def __call__(self, parser): assert False def __iter__(self): yield from () def __str__(self): return '<{0}>'.format(self.name) def __add__(self, other): return Sequence([self, to_symbol(other)]) def __radd__(self, other): return to_symbol(other) + self def __or__(self, other): return OneOf([self, to_symbol(other)]) def __ror__(self, other): return to_symbol(other) | self def __ge__(self, func): clone = copy(self) clone.transform = chain(func, self.transform) return clone def __pos__(self): return NonEmpty(self) def iter(self): visited = set() next_symbols = deque([self]) while next_symbols: next_symbol = next_symbols.popleft() if next_symbol in visited: continue yield next_symbol visited.add(next_symbol) next_symbols.extend(next_symbol) def terminals(self): return (symbol for symbol in self.iter() if isinstance(symbol, Terminal)) def apply_transform(self, node): return self.transform(node) def is_rule(self): return bool(self.name) class Terminal(Symbol): def __init__(self, lexeme, name=''): super(Terminal, self).__init__(name=name) self.lexeme = lexeme self.priority = -1 @property def pattern(self): return re.escape(self.lexeme) def apply_transform(self, node): return self.transform(node.token.lexeme) def __call__(self, parser): token = parser.read() if token.symbol != self: raise UnexpectedToken(token, self) yield parser.node(self, token, -1) def __pos__(self): return self def __repr__(self): name = '{0}='.format(self.name) if self.name else '' return '<{0} {1}{2}>'.format( self.__class__.__name__, name,<|fim▁hole|> ) def __str__(self): if self.name: return '<{0}>'.format(self.name) return repr(self.lexeme) def __eq__(self, other): return isinstance(other, type(self)) and self.lexeme == other.lexeme def __hash__(self): return hash(self.lexeme) class Marker(Terminal): def __init__(self, name): super().__init__('', name=name) @property def pattern(self): return None def __pos__(self): raise InvalidGrammar('Marker symbols cannot be non-empty') class Epsilon(Marker): def __call__(self, parser): yield parser.node(self) epsilon = Epsilon('') empty_match = Node(None, None) class Regexp(Terminal): def __init__(self, pattern): if re.match(pattern, ''): raise ValueError('Regexp terminals may not match the empty string, use rdp.epsilon instead') super().__init__(pattern) @property def pattern(self): return self.lexeme def __pos__(self): return self class CompoundSymbol(Symbol): repr_sep = ', ' def __init__(self, symbols): super().__init__() self.symbols = symbols self.grouped = False def __iter__(self): yield from self.symbols def __repr__(self): name = '{0} = '.format(self.name) if self.name else '' return '<{0} {1}{2}>'.format( self.__class__.__name__, name, self.repr_sep.join(repr(symbol) for symbol in self.symbols), ) def apply_transform(self, node): return self.transform([child.transform() for child in node]) class OneOf(CompoundSymbol): repr_sep = ' | ' def __call__(self, parser): node = parser.node(self) longest_match_error = None for symbol in self.symbols: try: child = yield symbol node.append(child) yield node except ParseError as e: if not longest_match_error or longest_match_error < e: longest_match_error = e continue raise longest_match_error def __or__(self, other): if self.grouped: return super().__or__(other) return self.__class__(self.symbols + [to_symbol(other)]) def apply_transform(self, node): return self.transform(node.children[0].transform()) class Sequence(CompoundSymbol): repr_sep = ' + ' def __call__(self, parser): node = parser.node(self) for symbol in self.symbols: value = yield symbol node.append(value) yield node def __add__(self, other): if self.grouped: return super().__add__(other) return self.__class__(self.symbols + [to_symbol(other)]) class Repeat(Symbol): def __init__(self, symbol, min_matches=0): super().__init__() self.symbol = to_symbol(symbol) self.min_matches = min_matches def __iter__(self): yield self.symbol def __pos__(self): if self.min_matches > 0: return self clone = copy(self) clone.min_matches = 1 return clone def __call__(self, parser): node = parser.node(self) n = 0 while True: try: child = yield self.symbol n += 1 node.append(child) except ParseError: break if n < self.min_matches: raise ParseError("too few {0}".format(self.symbol)) yield node def apply_transform(self, node): return self.transform([child.transform() for child in node]) def repeat(symbol, separator=None, leading=False, trailing=False, min_matches=0): if not separator: return Repeat(symbol) separator = to_symbol(separator) tail = Repeat(flatten(separator + symbol), min_matches=max(min_matches - 1, 0)) r = group(symbol) + flatten(tail) if leading: r = Optional(separator) + flatten(r) if trailing: r = flatten(r) + Optional(separator) if min_matches > 0: return r return flatten(r) | drop(epsilon) class SymbolWrapper(Symbol): def __init__(self, symbol, name=''): super().__init__(name=name) self.symbol = None if symbol is None else to_symbol(symbol) def __iter__(self): yield self.symbol def apply_transform(self, node): return self.transform(self.symbol.transform()) class SymbolProxy(SymbolWrapper): def __init__(self, symbol=None, name=None): super().__init__(symbol=symbol, name=name) def __call__(self, parser): node = yield self.symbol yield node def __str__(self): return '<SymbolProxy {0}>'.format(self.symbol) def __eq__(self, other): return isinstance(other, SymbolProxy) and self.symbol == other.symbol def __hash__(self): return hash(self.symbol) @property def name(self): return self.symbol.name def is_rule(self): return False class Alias(SymbolProxy): def __init__(self, symbol, name): super().__init__(symbol) self.alias = name @property def name(self): return self.alias def named(self, name): return Alias(self.symbol, name) def __call__(self, parser): node = yield self.symbol if node.symbol == self.symbol: node.symbol = self yield node class Optional(SymbolWrapper): def __call__(self, parser): try: node = yield self.symbol except ParseError: node = empty_match yield node class Lookahead(SymbolWrapper): def __call__(self, parser): node = yield self.symbol parser.backtrack(node) yield empty_match def __pos__(self): raise InvalidGrammar('Lookahead cannot be non-empty') class NonEmpty(SymbolWrapper): def __call__(self, parser): node = yield self.symbol if not node: raise ParseError('non-empty match expected') yield node<|fim▁end|>
repr(self.lexeme)
<|file_name|>loader.cpp<|end_file_name|><|fim▁begin|>/* * Copyright (C) 2015 the authors * * This file is part of usb_warrior. * * usb_warrior is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * usb_warrior is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with usb_warrior. If not, see <http://www.gnu.org/licenses/>. */ #include "game.h" #include "image_manager.h" #include "loader.h" Loader::Loader(Game* game) : _game(game) { } void Loader::addImage(const std::string& filename) { _imageMap.emplace(filename, nullptr); } void Loader::addSound(const std::string& filename) { _soundMap.emplace(filename, nullptr); } void Loader::addMusic(const std::string& filename) { _musicMap.emplace(filename, nullptr); } void Loader::addFont(const std::string& filename) { _fontMap.emplace(filename, nullptr); } const Image* Loader::getImage(const std::string& filename) { return _imageMap.at(filename); } const Sound* Loader::getSound(const std::string& filename) { return _soundMap.at(filename); } const Music* Loader::getMusic(const std::string& filename) { return _musicMap.at(filename); } Font Loader::getFont(const std::string& filename) { return Font(_fontMap.at(filename)); } unsigned Loader::loadAll() { unsigned err = 0; for(auto& file: _imageMap) { file.second = _game->images()->loadImage(file.first); if(!file.second) { err++; } } for(auto& file: _soundMap) { file.second = _game->sounds()->loadSound(file.first); if(!file.second) { err++; } } for(auto& file: _musicMap) { file.second = _game->sounds()->loadMusic(file.first); if(!file.second) { err++; } } for(auto& file: _fontMap) { file.second = _game->fonts()->loadFont(file.first); if(!file.second) { err++; } } return err; } void Loader::releaseAll() {<|fim▁hole|> file.second = nullptr; } } for(auto& file: _soundMap) { if(file.second) { _game->sounds()->releaseSound(file.second); file.second = nullptr; } } for(auto& file: _musicMap) { if(file.second) { _game->sounds()->releaseMusic(file.second); file.second = nullptr; } } for(auto& file: _fontMap) { if(file.second) { _game->fonts()->releaseFont(file.second); file.second = nullptr; } } }<|fim▁end|>
for(auto& file: _imageMap) { if(file.second) { _game->images()->releaseImage(file.second);
<|file_name|>counts.rs<|end_file_name|><|fim▁begin|>use comment::Comment; use config::{Config, Utf8Rule}; use count::Count; use error::{CliError, CliResult}; use fmt::{self, Format}; use fsutil; use gitignore; use language::Language; use regex::Regex; use std::env; use std::f64; use std::fs::File; use std::io::{self, Read, Write}; use std::path::{Path, PathBuf}; use tabwriter::TabWriter; pub struct Counts<'c> { cfg: &'c Config<'c>, counts: Vec<Count>, tot: usize, tot_lines: u64, tot_comments: u64, tot_blanks: u64, tot_code: u64, tot_usafe: u64, } impl<'c> Counts<'c> { pub fn new(cfg: &'c Config) -> Self { Counts { cfg: cfg, counts: vec![], tot: 0, tot_lines: 0, tot_comments: 0, tot_blanks: 0, tot_code: 0, tot_usafe: 0, } } pub fn fill_from(&mut self) { debugln!("executing; fill_from; cfg={:?}", self.cfg); let cd; let gitignore = if self.cfg.all { None } else { cd = env::current_dir().unwrap().join(".gitignore"); gitignore::File::new(&cd).ok() }; for path in &self.cfg.to_count { debugln!("iter; path={:?};", path); let mut files = vec![]; fsutil::get_all_files(&mut files, path, &self.cfg.exclude, self.cfg.follow_links, &gitignore); for file in files { debugln!("iter; file={:?};", file); let extension = match Path::new(&file).extension() { Some(result) => { if let Some(ref exts) = self.cfg.exts { if !exts.contains(&result.to_str().unwrap_or("")) { continue; } } result.to_str().unwrap() } None => continue, }; debugln!("found extension: {:?}", extension); if let Some(pos_lang) = Language::from_ext(extension) { debugln!("Extension is valid"); let mut found = false; debugln!("Searching for previous entries of that type"); for l in self.counts.iter_mut() { if l.lang == pos_lang { debugln!("Found"); found = true; l.add_file(PathBuf::from(&file)); break; } } if !found { debugln!("Not found, creating new"); let mut c = Count::new(pos_lang, self.cfg.thousands); c.add_file(PathBuf::from(&file)); self.counts.push(c); } } else { debugln!("extension wasn't valid"); } } } } #[cfg_attr(feature = "lints", allow(cyclomatic_complexity, trivial_regex))] pub fn count(&mut self) -> CliResult<()> { for count in self.counts.iter_mut() { debugln!("iter; count={:?};", count); let re = if let Some(kw) = count.lang.unsafe_keyword() { Regex::new(&*format!("(.*?)([:^word:]{}[:^word:])(.*)", kw)).unwrap() } else { Regex::new("").unwrap() }; for file in count.files.iter() { debugln!("iter; file={:?};", file); let mut buffer = String::new(); let mut file_ref = cli_try!(File::open(&file)); match self.cfg.utf8_rule { Utf8Rule::Ignore => { if let Err(..) = file_ref.read_to_string(&mut buffer) { continue; } } Utf8Rule::Lossy => { let mut vec_buf = vec![]; cli_try!(file_ref.read_to_end(&mut vec_buf)); buffer = String::from_utf8_lossy(&vec_buf).into_owned(); } Utf8Rule::Strict => { cli_try!(file_ref.read_to_string(&mut buffer)); } } let mut is_in_comments = false; let mut is_in_unsafe = false; let mut bracket_count: i64 = 0; 'new_line: for line in buffer.lines() { let line = line.trim(); debugln!("iter; line={:?};", line); count.lines += 1; if is_in_comments { debugln!("still in comments"); if line.contains(count.multi_end().unwrap()) { debugln!("line contained ending comment, stopping comments"); is_in_comments = false; } count.comments += 1; continue; } debugln!("not in comments"); if line.trim().is_empty() { debugln!("line was empty"); count.blanks += 1; continue; } debugln!("Line isn't empty"); if let Some(ms) = count.multi_start() { debugln!("This file type has a multi start of: {:?}", ms); if line.starts_with(ms) { debugln!("line starts with multi comment"); count.comments += 1; is_in_comments = !line.contains(count.multi_end().unwrap()); debugln!("line also contained a multi end: {:?}", is_in_comments); continue; } else if line.contains(ms) { debugln!("line contains a multi start"); is_in_comments = !line.contains(count.multi_end().unwrap()); debugln!("line also contained a multi end: {:?}", is_in_comments); if is_in_comments { continue; } } } else { debugln!("No multi line comments for this type"); } debugln!("No multi line comments for this line"); if let Some(single_comments) = count.single() { debugln!("This type has single line comments: {:?}", single_comments); for single in single_comments { if line.starts_with(single) { debugln!("Line started with a comment"); count.comments += 1; continue 'new_line; } else { debugln!("Line dind't start with a comment"); } } } else { debugln!("No single line comments for this type"); } if self.cfg.usafe && count.lang.is_unsafe() { debugln!("Calculating --unsafe-statistics"); debugln!("The language is not safe"); if let Some(..) = count.lang.unsafe_keyword() { debugln!("There is a keyword"); debugln!("line={:?}", line); if is_in_unsafe { debugln!("It didn't contain the keyword, but we are still in \ unsafe"); count.usafe += 1; bracket_count = Counts::count_brackets(line, Some(bracket_count)); is_in_unsafe = bracket_count > 0; debugln!("after counting brackets; is_in_unsafe={:?}; \ bracket_count={:?}", is_in_unsafe, bracket_count); } else if let Some(caps) = re.captures(line) { let mut should_count = true; if let Some(before) = caps.at(1) { if let Some(single_v) = count.lang.single() { for s in single_v { if before.contains(s) { should_count = false; break; } } } if let Some(multi) = count.lang.multi_start() { if before.contains(multi) && !before.contains(count.lang.multi_end().unwrap()) { should_count = false; } } } if should_count { debugln!("It contained the keyword; usafe_line={:?}", line); count.usafe += 1; if let Some(after) = caps.at(3) { debugln!("after_usafe={:?}", after); bracket_count = Counts::count_brackets(after, None); is_in_unsafe = bracket_count > 0; debugln!("after counting brackets; is_in_unsafe={:?}; \ bracket_count={:?}", is_in_unsafe, bracket_count); } } } else { debugln!("It didn't contain the keyword, and we are not in unsafe"); } if bracket_count < 0 { debugln!("bracket_count < 0; resetting"); bracket_count = 0 } } else { debugln!("Language is unsafe, incing the count"); count.usafe += 1; } } count.code += 1; } } self.tot += count.files.len(); self.tot_lines += count.lines; self.tot_comments += count.comments; self.tot_blanks += count.blanks; self.tot_code += count.code; self.tot_usafe += count.usafe; } <|fim▁hole|> pub fn write_results(&mut self) -> CliResult<()> { let mut w = TabWriter::new(vec![]); cli_try!(write!(w, "\tLanguage\tFiles\tLines\tBlanks\tComments\tCode{}\n", if self.cfg.usafe { "\tUnsafe (%)" } else { "" })); cli_try!(write!(w, "\t--------\t-----\t-----\t------\t--------\t----{}\n", if self.cfg.usafe { "\t----------" } else { "" })); for count in &self.counts { if self.cfg.usafe { let usafe_per = if count.code != 0 { (count.usafe as f64 / count.code as f64) * 100.00f64 } else { 0f64 }; cli_try!(write!(w, "\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n", count.lang.name(), count.total_files(), count.lines(), count.blanks(), count.comments(), count.code(), if (usafe_per - 00f64).abs() < f64::EPSILON { "".to_owned() } else { format!("{} ({:.2}%)", count.usafe(), usafe_per) })); } else { cli_try!(write!(w, "\t{}\n", count)); } } cli_try!(write!(w, "\t--------\t-----\t-----\t------\t--------\t----{}\n", if self.cfg.usafe { "\t----------" } else { "" })); cli_try!(write!(w, "{}\t\t{}\t{}\t{}\t{}\t{}{}\n", "Totals:", fmt::format_number(self.tot as u64, self.cfg.thousands), fmt::format_number(self.tot_lines, self.cfg.thousands), fmt::format_number(self.tot_blanks, self.cfg.thousands), fmt::format_number(self.tot_comments, self.cfg.thousands), fmt::format_number(self.tot_code, self.cfg.thousands), if self.cfg.usafe { format!("\t{} ({:.2}%)", fmt::format_number(self.tot_usafe, self.cfg.thousands), (self.tot_usafe as f64 / self.tot_code as f64) * 100.00f64) } else { "".to_owned() })); cli_try!(w.flush()); verboseln!(self.cfg, "{} {}", Format::Good("Displaying"), "the results:"); if self.tot > 0 { write!(io::stdout(), "{}", String::from_utf8(w.unwrap()).ok().expect("failed to get valid UTF-8 String")) .expect("failed to write output"); } else { println!("\n\tNo source files were found matching the specified criteria"); } Ok(()) } fn count_brackets(line: &str, count: Option<i64>) -> i64 { let mut b: i64 = count.unwrap_or(0); for c in line.chars() { match c { '{' => b += 1, '}' => b -= 1, _ => (), } } b } }<|fim▁end|>
Ok(()) }
<|file_name|>photo_shadow.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## def convert_catalog(from_file, to_file, size=220) : return __convert(from_file, to_file, size) def convert(from_file, to_file): size = 95 __convert(from_file, to_file, size=95) def __convert(from_file, to_file, size=95): from PIL import Image, ImageDraw, ImageFilter im = Image.open(from_file) if float(im.size[1]/im.size[0])>2: im = im.resize((im.size[0]*size/im.size[1], size)) else: im = im.resize((size,im.size[1]*size/im.size[0])) newimg = Image.new('RGB', (im.size[0]+8,im.size[1]+8), (255,255,255) ) draw = ImageDraw.Draw(newimg) draw.rectangle((6, im.size[1]-5, im.size[0], im.size[1]+5), fill=(90,90,90)) draw.rectangle((im.size[0]-5, 6, im.size[0]+5, im.size[1]), fill=(90,90,90)) del draw newimg = newimg.filter(ImageFilter.BLUR) newimg = newimg.filter(ImageFilter.BLUR) newimg = newimg.filter(ImageFilter.BLUR) newimg.paste(im, (0,0)) draw = ImageDraw.Draw(newimg) draw.rectangle((0, 0, im.size[0], im.size[1]), outline=(0,0,0)) del draw to_fp = file(to_file, 'wb') newimg.save(to_fp, "JPEG")<|fim▁hole|> del newimg return res # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:<|fim▁end|>
to_fp.close() res = newimg.size del im
<|file_name|>json_test.py<|end_file_name|><|fim▁begin|># Rekall Memory Forensics # Copyright 2014 Google Inc. All Rights Reserved. # # Author: Michael Cohen [email protected] # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # """Tests for json encoding/decoding.""" import json import logging from rekall import testlib from rekall.ui import json_renderer class JsonTest(testlib.RekallBaseUnitTestCase): """Test the Json encode/decoder.""" PLUGIN = "json_render" def setUp(self): self.session = self.MakeUserSession() self.renderer = json_renderer.JsonRenderer(session=self.session) self.encoder = self.renderer.encoder self.decoder = self.renderer.decoder def testObjectRenderer(self): cases = [ ('\xff\xff\x00\x00', {'mro': u'str:basestring:object', 'b64': u'//8AAA=='}), ("hello", u'hello'), # A string is converted into unicode if # possible. (1, 1), # Ints are already JSON serializable. (dict(foo=2), {'foo': 2}), (set([1, 2, 3]), {'mro': u'set:object', 'data': [1, 2, 3]}), ([1, 2, 3], [1, 2, 3]), ([1, "\xff\xff\x00\x00", 3], [1, {'mro': u'str:basestring:object', 'b64': u'//8AAA=='}, 3]), ] for case in cases: encoded = self.encoder.Encode(case[0]) self.assertEqual(encoded, case[1]) def testProperSerialization(self): """Test that serializing simple python objects with json works. NOTE: Json is not intrinsically a fully functional serialization format - it is unable to serialize many common python primitives (e.g. strings, dicts with numeric keys etc). This tests that our wrapping around the json format allows the correct serialization of python primitives. """ for case in [ [1, 2], [1, "hello"], ["1", "2"], ["hello", u'Gr\xfcetzi'], "hello", u'Gr\xfcetzi', dict(a="hello"), dict(b=dict(a="hello")), # Nested dict. ]: self.encoder.flush() data = self.encoder.Encode(case) logging.debug("%s->%s" % (case, data)) # Make sure the data is JSON serializable. self.assertEqual(data, json.loads(json.dumps(data))) self.decoder.SetLexicon(self.encoder.GetLexicon()) self.assertEqual(case, self.decoder.Decode(data)) def testObjectSerization(self): """Serialize _EPROCESS objects. We check that the deserialized object is an exact replica of the original - this includes the same address spaces, profile and offset. Having the objects identical allows us to dereference object members seamlessly. """ for task in self.session.plugins.pslist().filter_processes(): self.encoder.flush() data = self.encoder.Encode(task) logging.debug("%r->%s" % (task, data)) # Make sure the data is JSON serializable. self.assertEqual(data, json.loads(json.dumps(data))) self.decoder.SetLexicon(self.encoder.GetLexicon()) decoded_task = self.decoder.Decode(data) self.assertEqual(task.obj_offset, decoded_task.obj_offset) self.assertEqual(task.obj_name, decoded_task.obj_name) self.assertEqual(task.obj_vm.name, decoded_task.obj_vm.name) # Check the process name is the same - this tests subfield # dereferencing. self.assertEqual(task.name, decoded_task.name) self.assertEqual(task.pid, decoded_task.pid) <|fim▁hole|> self.CheckObjectSerization(self.session.profile) self.CheckObjectSerization(self.session.kernel_address_space) self.CheckObjectSerization(self.session.physical_address_space) # Some native types. self.CheckObjectSerization(set([1, 2, 3])) self.CheckObjectSerization(dict(a=1, b=dict(a=1))) def CheckObjectSerization(self, obj): object_renderer_cls = json_renderer.JsonObjectRenderer.ForTarget( obj, "JsonRenderer") renderer = json_renderer.JsonRenderer(session=self.session) object_renderer = object_renderer_cls( session=self.session, renderer=renderer) encoded = object_renderer.EncodeToJsonSafe(obj, strict=True) # Make sure it is json safe. json.dumps(encoded) # Now decode it. decoding_object_renderer_cls = json_renderer.JsonObjectRenderer.FromEncoded( encoded, "JsonRenderer") self.assertEqual(decoding_object_renderer_cls, object_renderer_cls) decoded = object_renderer.DecodeFromJsonSafe(encoded, {}) self.assertEqual(decoded, obj) # Now check the DataExportRenderer. object_renderer_cls = json_renderer.JsonObjectRenderer.ForTarget( obj, "DataExportRenderer") object_renderer = object_renderer_cls(session=self.session, renderer="DataExportRenderer") encoded = object_renderer.EncodeToJsonSafe(obj, strict=True) # Make sure it is json safe. json.dumps(encoded) # Data Export is not decodable.<|fim▁end|>
def testAllObjectSerialization(self): for vtype in self.session.profile.vtypes: obj = self.session.profile.Object(vtype) self.CheckObjectSerization(obj)
<|file_name|>add_rack_bunker.py<|end_file_name|><|fim▁begin|># -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2018 Contributor # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains the logic for `aq add rack --bunker`.""" from aquilon.worker.broker import BrokerCommand # pylint: disable=W0611 from aquilon.worker.commands.add_rack import CommandAddRack <|fim▁hole|><|fim▁end|>
class CommandAddRackBunker(CommandAddRack): required_parameters = ["bunker", "row", "column"]
<|file_name|>sky.cpp<|end_file_name|><|fim▁begin|>/** * Sky profile implementation * * ICRAR - International Centre for Radio Astronomy Research * (c) UWA - The University of Western Australia, 2016 * Copyright by UWA (in the framework of the ICRAR) * All rights reserved * * Contributed by Aaron Robotham, Rodrigo Tobar * * This file is part of libprofit. * * libprofit is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * libprofit is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with libprofit. If not, see <http://www.gnu.org/licenses/>. */ #include <vector> #include "profit/common.h" #include "profit/model.h" #include "profit/sky.h" <|fim▁hole|>namespace profit { void SkyProfile::validate() { /* no-op for the time being, probably check value in range, etc */ } void SkyProfile::adjust_for_finesampling(unsigned int finesampling) { bg = requested_bg / (finesampling * finesampling); } void SkyProfile::evaluate(Image &image, const Mask &mask, const PixelScale & /*scale*/, const Point &/*offset*/, double /*magzero*/) { /* In case we need to mask some pixels out */ auto mask_it = mask.begin(); /* Fill the image with the background value */ for(auto &pixel: image) { /* Check the calculation mask and avoid pixel if necessary */ if( mask && !*mask_it++ ) { continue; } pixel += this->bg; } } SkyProfile::SkyProfile(const Model &model, const std::string &name) : Profile(model, name), bg(0.), requested_bg(0.) { register_parameter("bg", requested_bg); } } /* namespace profit */<|fim▁end|>
<|file_name|>DisplayBar.java<|end_file_name|><|fim▁begin|>package com.tiketal.overwatch.util; import org.bukkit.Bukkit; import org.bukkit.boss.BarColor; import org.bukkit.boss.BarStyle; import org.bukkit.boss.BossBar; import org.bukkit.entity.Player; public class DisplayBar { private BossBar bar; public DisplayBar(String name, String color, String style) { color = color.toUpperCase(); style = style.toUpperCase(); try { bar = Bukkit.createBossBar(name, BarColor.valueOf(color), BarStyle.valueOf(style)); } catch (Exception e) { bar = Bukkit.createBossBar(name, BarColor.WHITE, BarStyle.SOLID); } bar.setVisible(true); } public void show(Player player) { bar.addPlayer(player); } public void hide(Player player) { bar.removePlayer(player); } <|fim▁hole|> } public void setVisible(boolean visible) { bar.setVisible(visible); } public void setColor(String color) { try { bar.setColor(BarColor.valueOf(color.toUpperCase())); } catch (Exception e) { bar.setColor(BarColor.WHITE); } } public void setStyle(String style) { try { bar.setStyle(BarStyle.valueOf(style.toUpperCase())); } catch (Exception e) { bar.setStyle(BarStyle.SOLID); } } public void progress(double amt) { if (amt < 0) amt *= -1; if (amt > 1) amt = 1; bar.setProgress(amt); } public void reset() { for (Player player : bar.getPlayers()) { bar.removePlayer(player); } } }<|fim▁end|>
public void setTitle(String title) { bar.setTitle(title);
<|file_name|>d0.js<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
module.exports = function(){ return 'd0' }
<|file_name|>test_cantact.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """ Tests for CANtact interfaces """ import unittest import can from can.interfaces import cantact<|fim▁hole|> class CantactTest(unittest.TestCase): def test_bus_creation(self): bus = can.Bus(channel=0, bustype="cantact", _testing=True) self.assertIsInstance(bus, cantact.CantactBus) cantact.MockInterface.set_bitrate.assert_called() cantact.MockInterface.set_bit_timing.assert_not_called() cantact.MockInterface.set_enabled.assert_called() cantact.MockInterface.set_monitor.assert_called() cantact.MockInterface.start.assert_called() def test_bus_creation_bittiming(self): cantact.MockInterface.set_bitrate.reset_mock() bt = can.BitTiming(tseg1=13, tseg2=2, brp=6, sjw=1) bus = can.Bus(channel=0, bustype="cantact", bit_timing=bt, _testing=True) self.assertIsInstance(bus, cantact.CantactBus) cantact.MockInterface.set_bitrate.assert_not_called() cantact.MockInterface.set_bit_timing.assert_called() cantact.MockInterface.set_enabled.assert_called() cantact.MockInterface.set_monitor.assert_called() cantact.MockInterface.start.assert_called() def test_transmit(self): bus = can.Bus(channel=0, bustype="cantact", _testing=True) msg = can.Message( arbitration_id=0xC0FFEF, data=[1, 2, 3, 4, 5, 6, 7, 8], is_extended_id=True ) bus.send(msg) cantact.MockInterface.send.assert_called() def test_recv(self): bus = can.Bus(channel=0, bustype="cantact", _testing=True) frame = bus.recv(timeout=0.5) cantact.MockInterface.recv.assert_called() self.assertIsInstance(frame, can.Message) def test_recv_timeout(self): bus = can.Bus(channel=0, bustype="cantact", _testing=True) frame = bus.recv(timeout=0.0) cantact.MockInterface.recv.assert_called() self.assertIsNone(frame) def test_shutdown(self): bus = can.Bus(channel=0, bustype="cantact", _testing=True) bus.shutdown() cantact.MockInterface.stop.assert_called()<|fim▁end|>
<|file_name|>show_hostlink_hostlink.py<|end_file_name|><|fim▁begin|># -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2012,2013 Contributor #<|fim▁hole|># # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from aquilon.worker.broker import BrokerCommand # pylint: disable=W0611 from aquilon.worker.commands.show_hostlink import CommandShowHostlink class CommandShowHostlinkHostlink(CommandShowHostlink): required_parameters = ["hostlink"]<|fim▁end|>
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>// Mandelbrot set in rust // // This code shows how to calculate the set in serial and parallel. // More parallel versions will be added in the future. // // Written by Willi Kappler, [email protected] // // License: MIT // //#![feature(plugin)] // //#![plugin(clippy)] // External crates extern crate time; extern crate rayon; // Internal crates extern crate mandel_util; extern crate mandel_method; // External modules use time::{now}; // Internal modules use mandel_util::{parse_arguments, do_run, compiler_version}; use mandel_method::*; fn main() { // For example run with: // cargo run --release -- --re1=-2.0 --re2=1.0 --img1=-1.5 --img2=1.5 // --max_iter=2048 --img_size=1024 --num_threads=2 // // Or just using the default values: // cargo run --release -- --num_threads=2 // // Note that the image size must be a power of two let mandel_config = parse_arguments(); let version = env!("CARGO_PKG_VERSION"); println!("mandel-rust version: {}", version); println!("Number of repetitive runs: {}", mandel_config.num_of_runs); println!("Rustc version: {}", compiler_version); // Get current date and time once and pass it to the individual runs for the image filename. let tm = now(); let tm = tm.strftime("%Y_%m_%d__%H_%M_%S").unwrap(); let time_now = format!("{}", &tm); // vec! macro expects usize<|fim▁hole|> do_run("serial", &serial, &mandel_config, &mut image, &time_now); do_run("scoped_thread_pool", &scoped_thread_pool_, &mandel_config, &mut image, &time_now); // Make sure this is only called once match rayon::initialize(rayon::Configuration::new().set_num_threads(mandel_config.num_threads as usize)) { Ok(_) => { do_run("rayon_join", &rayon_join, &mandel_config, &mut image, &time_now); do_run("rayon_par_iter", &rayon_par_iter, &mandel_config, &mut image, &time_now); }, Err(e) => println!("Rayon error: set number of threads failed: {}", e) } do_run("rust_scoped_pool", &rust_scoped_pool, &mandel_config, &mut image, &time_now); do_run("job_steal", &job_steal, &mandel_config, &mut image, &time_now); do_run("job_steal_join", &job_steal_join, &mandel_config, &mut image, &time_now); // do_run("kirk_crossbeam", &kirk_crossbeam, &mandel_config, &mut image, &time_now); }<|fim▁end|>
let mut image: Vec<u32> = vec![0; (mandel_config.img_size * mandel_config.img_size) as usize];
<|file_name|>property_tree_builder.cc<|end_file_name|><|fim▁begin|>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "cc/trees/property_tree_builder.h" #include <stddef.h> #include <map> #include <set> #include "cc/base/math_util.h" #include "cc/layers/layer.h" #include "cc/layers/layer_impl.h" #include "cc/trees/draw_property_utils.h" #include "cc/trees/layer_tree_host.h" #include "cc/trees/layer_tree_impl.h" #include "ui/gfx/geometry/point_f.h" #include "ui/gfx/geometry/vector2d_conversions.h" namespace cc { class LayerTreeHost; namespace { static const int kInvalidPropertyTreeNodeId = -1; static const int kRootPropertyTreeNodeId = 0; template <typename LayerType> struct DataForRecursion { TransformTree* transform_tree; ClipTree* clip_tree; EffectTree* effect_tree; ScrollTree* scroll_tree; LayerType* transform_tree_parent; LayerType* transform_fixed_parent; int render_target; int clip_tree_parent; int effect_tree_parent; int scroll_tree_parent; const LayerType* page_scale_layer; const LayerType* inner_viewport_scroll_layer; const LayerType* outer_viewport_scroll_layer; const LayerType* overscroll_elasticity_layer; gfx::Vector2dF elastic_overscroll; float page_scale_factor; bool in_subtree_of_page_scale_layer; bool affected_by_inner_viewport_bounds_delta; bool affected_by_outer_viewport_bounds_delta; bool should_flatten; bool target_is_clipped; bool is_hidden; uint32_t main_thread_scrolling_reasons; bool scroll_tree_parent_created_by_uninheritable_criteria; const gfx::Transform* device_transform; gfx::Vector2dF scroll_compensation_adjustment; gfx::Transform compound_transform_since_render_target; bool axis_align_since_render_target; int sequence_number; SkColor safe_opaque_background_color; }; template <typename LayerType> struct DataForRecursionFromChild { int num_copy_requests_in_subtree; DataForRecursionFromChild() : num_copy_requests_in_subtree(0) {} void Merge(const DataForRecursionFromChild& data) { num_copy_requests_in_subtree += data.num_copy_requests_in_subtree; } }; template <typename LayerType> static LayerType* GetTransformParent(const DataForRecursion<LayerType>& data, LayerType* layer) { return layer->position_constraint().is_fixed_position() ? data.transform_fixed_parent : data.transform_tree_parent; } template <typename LayerType> static ClipNode* GetClipParent(const DataForRecursion<LayerType>& data, LayerType* layer) { const bool inherits_clip = !layer->clip_parent(); const int id = inherits_clip ? data.clip_tree_parent : layer->clip_parent()->clip_tree_index(); return data.clip_tree->Node(id); } template <typename LayerType> static bool LayerClipsSubtree(LayerType* layer) { return layer->masks_to_bounds() || layer->mask_layer(); } template <typename LayerType> static int GetScrollParentId(const DataForRecursion<LayerType>& data, LayerType* layer) { const bool inherits_scroll = !layer->scroll_parent(); const int id = inherits_scroll ? data.scroll_tree_parent : layer->scroll_parent()->scroll_tree_index(); return id; } template <typename LayerType> void AddClipNodeIfNeeded(const DataForRecursion<LayerType>& data_from_ancestor, LayerType* layer, bool created_render_surface, bool created_transform_node, DataForRecursion<LayerType>* data_for_children) { ClipNode* parent = GetClipParent(data_from_ancestor, layer); int parent_id = parent->id; bool is_root = !layer->parent(); // Whether we have an ancestor clip that we might need to apply. bool ancestor_clips_subtree = is_root || parent->data.layers_are_clipped; bool layers_are_clipped = false; bool has_unclipped_surface = false; if (created_render_surface) { // Clips can usually be applied to a surface's descendants simply by // clipping the surface (or applied implicitly by the surface's bounds). // However, if the surface has unclipped descendants (layers that aren't // affected by the ancestor clip), we cannot clip the surface itself, and // must instead apply clips to the clipped descendants. if (ancestor_clips_subtree && layer->num_unclipped_descendants() > 0) { layers_are_clipped = true; } else if (!ancestor_clips_subtree) { // When there are no ancestor clips that need to be applied to a render // surface, we reset clipping state. The surface might contribute a clip // of its own, but clips from ancestor nodes don't need to be considered // when computing clip rects or visibility. has_unclipped_surface = true; DCHECK(!parent->data.applies_local_clip); } // A surface with unclipped descendants cannot be clipped by its ancestor // clip at draw time since the unclipped descendants aren't affected by the // ancestor clip. data_for_children->target_is_clipped = ancestor_clips_subtree && !layer->num_unclipped_descendants(); } else { // Without a new render surface, layer clipping state from ancestors needs // to continue to propagate. data_for_children->target_is_clipped = data_from_ancestor.target_is_clipped; layers_are_clipped = ancestor_clips_subtree; } bool layer_clips_subtree = LayerClipsSubtree(layer); if (layer_clips_subtree) layers_are_clipped = true; // Without surfaces, all non-viewport clips have to be applied using layer // clipping. bool layers_are_clipped_when_surfaces_disabled = layer_clips_subtree || parent->data.layers_are_clipped_when_surfaces_disabled; // Render surface's clip is needed during hit testing. So, we need to create // a clip node for every render surface. bool requires_node = layer_clips_subtree || created_render_surface; if (!requires_node) { data_for_children->clip_tree_parent = parent_id; DCHECK_EQ(layers_are_clipped, parent->data.layers_are_clipped); DCHECK_EQ(layers_are_clipped_when_surfaces_disabled, parent->data.layers_are_clipped_when_surfaces_disabled); } else { LayerType* transform_parent = data_for_children->transform_tree_parent; if (layer->position_constraint().is_fixed_position() && !created_transform_node) { transform_parent = data_for_children->transform_fixed_parent; } ClipNode node; node.data.clip = gfx::RectF(gfx::PointF() + layer->offset_to_transform_parent(), gfx::SizeF(layer->bounds())); node.data.transform_id = transform_parent->transform_tree_index(); node.data.target_id = data_for_children->effect_tree->Node(data_for_children->render_target) ->data.transform_id; node.owner_id = layer->id(); if (ancestor_clips_subtree || layer_clips_subtree) { // Surfaces reset the rect used for layer clipping. At other nodes, layer // clipping state from ancestors must continue to get propagated. node.data.layer_clipping_uses_only_local_clip = created_render_surface || !ancestor_clips_subtree; } else { // Otherwise, we're either unclipped, or exist only in order to apply our // parent's clips in our space. node.data.layer_clipping_uses_only_local_clip = false; } node.data.applies_local_clip = layer_clips_subtree; node.data.resets_clip = has_unclipped_surface; node.data.target_is_clipped = data_for_children->target_is_clipped; node.data.layers_are_clipped = layers_are_clipped; node.data.layers_are_clipped_when_surfaces_disabled = layers_are_clipped_when_surfaces_disabled; data_for_children->clip_tree_parent = data_for_children->clip_tree->Insert(node, parent_id); } layer->SetClipTreeIndex(data_for_children->clip_tree_parent); // TODO(awoloszyn): Right now when we hit a node with a replica, we reset the // clip for all children since we may need to draw. We need to figure out a // better way, since we will need both the clipped and unclipped versions. } template <typename LayerType> static inline bool IsAtBoundaryOf3dRenderingContext(LayerType* layer) { return layer->parent() ? layer->parent()->sorting_context_id() != layer->sorting_context_id() : layer->Is3dSorted(); } template <typename LayerType> bool AddTransformNodeIfNeeded( const DataForRecursion<LayerType>& data_from_ancestor, LayerType* layer, bool created_render_surface, DataForRecursion<LayerType>* data_for_children) { const bool is_root = !layer->parent(); const bool is_page_scale_layer = layer == data_from_ancestor.page_scale_layer; const bool is_overscroll_elasticity_layer = layer == data_from_ancestor.overscroll_elasticity_layer; const bool is_scrollable = layer->scrollable(); const bool is_fixed = layer->position_constraint().is_fixed_position(); const bool has_significant_transform = !layer->transform().IsIdentityOr2DTranslation(); const bool has_potentially_animated_transform = layer->HasPotentiallyRunningTransformAnimation(); // A transform node is needed even for a finished animation, since differences // in the timing of animation state updates can mean that an animation that's // in the Finished state at tree-building time on the main thread is still in // the Running state right after commit on the compositor thread. const bool has_any_transform_animation = layer->HasAnyAnimationTargetingProperty(TargetProperty::TRANSFORM); const bool has_surface = created_render_surface; // A transform node is needed to change the render target for subtree when // a scroll child's render target is different from the scroll parent's render // target. const bool scroll_child_has_different_target = layer->scroll_parent() && layer->parent()->effect_tree_index() != layer->scroll_parent()->effect_tree_index(); const bool is_at_boundary_of_3d_rendering_context = IsAtBoundaryOf3dRenderingContext(layer); bool requires_node = is_root || is_scrollable || has_significant_transform || has_any_transform_animation || has_surface || is_fixed || is_page_scale_layer || is_overscroll_elasticity_layer || scroll_child_has_different_target || is_at_boundary_of_3d_rendering_context; LayerType* transform_parent = GetTransformParent(data_from_ancestor, layer); DCHECK(is_root || transform_parent); int parent_index = kRootPropertyTreeNodeId; if (transform_parent) parent_index = transform_parent->transform_tree_index(); int source_index = parent_index; gfx::Vector2dF source_offset; if (transform_parent) { if (layer->scroll_parent()) { LayerType* source = layer->parent(); source_offset += source->offset_to_transform_parent(); source_index = source->transform_tree_index(); } else if (!is_fixed) { source_offset = transform_parent->offset_to_transform_parent(); } else { source_offset = data_from_ancestor.transform_tree_parent ->offset_to_transform_parent(); source_index = data_from_ancestor.transform_tree_parent->transform_tree_index(); source_offset += data_from_ancestor.scroll_compensation_adjustment; } } if (layer->IsContainerForFixedPositionLayers() || is_root) { data_for_children->affected_by_inner_viewport_bounds_delta = layer == data_from_ancestor.inner_viewport_scroll_layer; data_for_children->affected_by_outer_viewport_bounds_delta = layer == data_from_ancestor.outer_viewport_scroll_layer; if (is_scrollable) { DCHECK(!is_root); DCHECK(layer->transform().IsIdentity()); data_for_children->transform_fixed_parent = layer->parent(); } else { data_for_children->transform_fixed_parent = layer; } } data_for_children->transform_tree_parent = layer; if (layer->IsContainerForFixedPositionLayers() || is_fixed) data_for_children->scroll_compensation_adjustment = gfx::Vector2dF(); if (!requires_node) { data_for_children->should_flatten |= layer->should_flatten_transform(); gfx::Vector2dF local_offset = layer->position().OffsetFromOrigin() + layer->transform().To2dTranslation(); gfx::Vector2dF source_to_parent; if (source_index != parent_index) { gfx::Transform to_parent; data_from_ancestor.transform_tree->ComputeTransform( source_index, parent_index, &to_parent); source_to_parent = to_parent.To2dTranslation(); } layer->set_offset_to_transform_parent(source_offset + source_to_parent + local_offset); layer->set_should_flatten_transform_from_property_tree( data_from_ancestor.should_flatten); layer->SetTransformTreeIndex(parent_index); if (layer->mask_layer()) layer->mask_layer()->SetTransformTreeIndex(parent_index); return false; } data_for_children->transform_tree->Insert(TransformNode(), parent_index); TransformNode* node = data_for_children->transform_tree->back(); layer->SetTransformTreeIndex(node->id); if (layer->mask_layer()) layer->mask_layer()->SetTransformTreeIndex(node->id); node->data.scrolls = is_scrollable; node->data.flattens_inherited_transform = data_for_children->should_flatten; node->data.sorting_context_id = layer->sorting_context_id(); if (layer == data_from_ancestor.page_scale_layer) data_for_children->in_subtree_of_page_scale_layer = true; node->data.in_subtree_of_page_scale_layer = data_for_children->in_subtree_of_page_scale_layer; // Surfaces inherently flatten transforms. data_for_children->should_flatten = layer->should_flatten_transform() || has_surface; DCHECK_GT(data_from_ancestor.effect_tree->size(), 0u); node->data.target_id = data_for_children->effect_tree->Node(data_from_ancestor.render_target) ->data.transform_id; node->data.content_target_id = data_for_children->effect_tree->Node(data_for_children->render_target) ->data.transform_id; DCHECK_NE(node->data.target_id, kInvalidPropertyTreeNodeId); node->data.is_animated = has_potentially_animated_transform; if (has_potentially_animated_transform) { float maximum_animation_target_scale = 0.f; if (layer->MaximumTargetScale(&maximum_animation_target_scale)) { node->data.local_maximum_animation_target_scale = maximum_animation_target_scale; } float starting_animation_scale = 0.f; if (layer->AnimationStartScale(&starting_animation_scale)) { node->data.local_starting_animation_scale = starting_animation_scale; } node->data.has_only_translation_animations = layer->HasOnlyTranslationTransforms(); } float post_local_scale_factor = 1.0f; if (is_root) post_local_scale_factor = data_for_children->transform_tree->device_scale_factor(); if (is_page_scale_layer) { post_local_scale_factor *= data_from_ancestor.page_scale_factor; data_for_children->transform_tree->set_page_scale_factor( data_from_ancestor.page_scale_factor); } if (has_surface && !is_root) node->data.needs_sublayer_scale = true; node->data.source_node_id = source_index; node->data.post_local_scale_factor = post_local_scale_factor; if (is_root) { data_for_children->transform_tree->SetDeviceTransform( *data_from_ancestor.device_transform, layer->position()); data_for_children->transform_tree->SetDeviceTransformScaleFactor( *data_from_ancestor.device_transform); } else { node->data.source_offset = source_offset; node->data.update_post_local_transform(layer->position(), layer->transform_origin()); } if (is_overscroll_elasticity_layer) { DCHECK(!is_scrollable); node->data.scroll_offset = gfx::ScrollOffset(data_from_ancestor.elastic_overscroll); } else if (!layer->scroll_parent()) { node->data.scroll_offset = layer->CurrentScrollOffset(); } if (is_fixed) { if (data_from_ancestor.affected_by_inner_viewport_bounds_delta) { node->data.affected_by_inner_viewport_bounds_delta_x = layer->position_constraint().is_fixed_to_right_edge(); node->data.affected_by_inner_viewport_bounds_delta_y = layer->position_constraint().is_fixed_to_bottom_edge(); if (node->data.affected_by_inner_viewport_bounds_delta_x || node->data.affected_by_inner_viewport_bounds_delta_y) { data_for_children->transform_tree ->AddNodeAffectedByInnerViewportBoundsDelta(node->id); } } else if (data_from_ancestor.affected_by_outer_viewport_bounds_delta) { node->data.affected_by_outer_viewport_bounds_delta_x = layer->position_constraint().is_fixed_to_right_edge(); node->data.affected_by_outer_viewport_bounds_delta_y = layer->position_constraint().is_fixed_to_bottom_edge(); if (node->data.affected_by_outer_viewport_bounds_delta_x || node->data.affected_by_outer_viewport_bounds_delta_y) { data_for_children->transform_tree ->AddNodeAffectedByOuterViewportBoundsDelta(node->id); } } } node->data.local = layer->transform(); node->data.update_pre_local_transform(layer->transform_origin()); node->data.needs_local_transform_update = true; data_from_ancestor.transform_tree->UpdateTransforms(node->id); layer->set_offset_to_transform_parent(gfx::Vector2dF()); // Flattening (if needed) will be handled by |node|. layer->set_should_flatten_transform_from_property_tree(false); data_for_children->scroll_compensation_adjustment += layer->ScrollCompensationAdjustment() - node->data.scroll_snap; node->owner_id = layer->id(); return true; } bool IsAnimatingOpacity(Layer* layer) { return layer->HasPotentiallyRunningOpacityAnimation() || layer->OpacityCanAnimateOnImplThread(); } bool IsAnimatingOpacity(LayerImpl* layer) { return layer->HasPotentiallyRunningOpacityAnimation(); } template <typename LayerType> static inline bool LayerIsInExisting3DRenderingContext(LayerType* layer) { return layer->Is3dSorted() && layer->parent() && layer->parent()->Is3dSorted() && (layer->parent()->sorting_context_id() == layer->sorting_context_id()); } template <typename LayerType> bool ShouldCreateRenderSurface(LayerType* layer, gfx::Transform current_transform, bool axis_aligned) { const bool preserves_2d_axis_alignment = (current_transform * layer->transform()).Preserves2dAxisAlignment() && axis_aligned && layer->AnimationsPreserveAxisAlignment(); const bool is_root = !layer->parent(); if (is_root) return true; // If the layer uses a mask and the layer is not a replica layer. // TODO(weiliangc): After slimming paint there won't be replica layers. if (layer->mask_layer() && layer->parent()->replica_layer() != layer) { return true; } // If the layer has a reflection. if (layer->replica_layer()) { return true; } // If the layer uses a CSS filter. if (!layer->filters().IsEmpty() || !layer->background_filters().IsEmpty()) { return true; } // If the layer will use a CSS filter. In this case, the animation // will start and add a filter to this layer, so it needs a surface. if (layer->HasPotentiallyRunningFilterAnimation()) { return true; } int num_descendants_that_draw_content = layer->NumDescendantsThatDrawContent(); // If the layer flattens its subtree, but it is treated as a 3D object by its // parent (i.e. parent participates in a 3D rendering context). if (LayerIsInExisting3DRenderingContext(layer) && layer->should_flatten_transform() && num_descendants_that_draw_content > 0) { TRACE_EVENT_INSTANT0( "cc", "PropertyTreeBuilder::ShouldCreateRenderSurface flattening", TRACE_EVENT_SCOPE_THREAD); return true; } // If the layer has blending. // TODO(rosca): this is temporary, until blending is implemented for other // types of quads than RenderPassDrawQuad. Layers having descendants that draw // content will still create a separate rendering surface. if (!layer->uses_default_blend_mode()) { TRACE_EVENT_INSTANT0( "cc", "PropertyTreeBuilder::ShouldCreateRenderSurface blending", TRACE_EVENT_SCOPE_THREAD); return true; } // If the layer clips its descendants but it is not axis-aligned with respect // to its parent. bool layer_clips_external_content = LayerClipsSubtree(layer); if (layer_clips_external_content && !preserves_2d_axis_alignment && num_descendants_that_draw_content > 0) { TRACE_EVENT_INSTANT0( "cc", "PropertyTreeBuilder::ShouldCreateRenderSurface clipping", TRACE_EVENT_SCOPE_THREAD); return true; } // If the layer has some translucency and does not have a preserves-3d // transform style. This condition only needs a render surface if two or more // layers in the subtree overlap. But checking layer overlaps is unnecessarily // costly so instead we conservatively create a surface whenever at least two // layers draw content for this subtree. bool at_least_two_layers_in_subtree_draw_content = num_descendants_that_draw_content > 0 && (layer->DrawsContent() || num_descendants_that_draw_content > 1); if (layer->EffectiveOpacity() != 1.f && layer->should_flatten_transform() && at_least_two_layers_in_subtree_draw_content) { TRACE_EVENT_INSTANT0( "cc", "PropertyTreeBuilder::ShouldCreateRenderSurface opacity", TRACE_EVENT_SCOPE_THREAD); DCHECK(!is_root); return true; } // If the layer has isolation. // TODO(rosca): to be optimized - create separate rendering surface only when // the blending descendants might have access to the content behind this layer // (layer has transparent background or descendants overflow). // https://code.google.com/p/chromium/issues/detail?id=301738 if (layer->is_root_for_isolated_group()) { TRACE_EVENT_INSTANT0( "cc", "PropertyTreeBuilder::ShouldCreateRenderSurface isolation", TRACE_EVENT_SCOPE_THREAD); return true; } // If we force it. if (layer->force_render_surface()) return true; // If we'll make a copy of the layer's contents. if (layer->HasCopyRequest()) return true; return false; } template <typename LayerType> bool AddEffectNodeIfNeeded( const DataForRecursion<LayerType>& data_from_ancestor, LayerType* layer, DataForRecursion<LayerType>* data_for_children) { const bool is_root = !layer->parent(); const bool has_transparency = layer->EffectiveOpacity() != 1.f; const bool has_animated_opacity = IsAnimatingOpacity(layer); const bool should_create_render_surface = ShouldCreateRenderSurface( layer, data_from_ancestor.compound_transform_since_render_target, data_from_ancestor.axis_align_since_render_target); data_for_children->axis_align_since_render_target &= layer->AnimationsPreserveAxisAlignment(); bool requires_node = is_root || has_transparency || has_animated_opacity || should_create_render_surface; int parent_id = data_from_ancestor.effect_tree_parent; if (!requires_node) { layer->SetEffectTreeIndex(parent_id); data_for_children->effect_tree_parent = parent_id; data_for_children->compound_transform_since_render_target *= layer->transform(); return false; } EffectNode node; node.owner_id = layer->id(); node.data.opacity = layer->EffectiveOpacity(); node.data.has_render_surface = should_create_render_surface; node.data.has_copy_request = layer->HasCopyRequest(); node.data.has_background_filters = !layer->background_filters().IsEmpty(); node.data.has_animated_opacity = has_animated_opacity; if (!is_root) { // The effect node's transform id is used only when we create a render // surface. So, we can leave the default value when we don't create a render // surface. if (should_create_render_surface) { // In this case, we will create a transform node, so it's safe to use the // next available id from the transform tree as this effect node's // transform id. node.data.transform_id = data_from_ancestor.transform_tree->next_available_id(); } node.data.clip_id = data_from_ancestor.clip_tree_parent; } else { // Root render surface acts the unbounded and untransformed to draw content // into. Transform node created from root layer (includes device scale // factor) and clip node created from root layer (include viewports) applies // to root render surface's content, but not root render surface itself. node.data.transform_id = kRootPropertyTreeNodeId; node.data.clip_id = kRootPropertyTreeNodeId; } data_for_children->effect_tree_parent = data_for_children->effect_tree->Insert(node, parent_id); layer->SetEffectTreeIndex(data_for_children->effect_tree_parent); if (should_create_render_surface) { data_for_children->compound_transform_since_render_target = gfx::Transform(); data_for_children->axis_align_since_render_target = true; } return should_create_render_surface; } template <typename LayerType> void AddScrollNodeIfNeeded( const DataForRecursion<LayerType>& data_from_ancestor, LayerType* layer, DataForRecursion<LayerType>* data_for_children) { int parent_id = GetScrollParentId(data_from_ancestor, layer); bool is_root = !layer->parent(); bool scrollable = layer->scrollable(); bool contains_non_fast_scrollable_region = !layer->non_fast_scrollable_region().IsEmpty(); uint32_t main_thread_scrolling_reasons = layer->main_thread_scrolling_reasons(); bool scroll_node_uninheritable_criteria = is_root || scrollable || contains_non_fast_scrollable_region; bool has_different_main_thread_scrolling_reasons = main_thread_scrolling_reasons != data_from_ancestor.main_thread_scrolling_reasons; bool requires_node = scroll_node_uninheritable_criteria || (main_thread_scrolling_reasons != MainThreadScrollingReason::kNotScrollingOnMain && (has_different_main_thread_scrolling_reasons || data_from_ancestor .scroll_tree_parent_created_by_uninheritable_criteria)); if (!requires_node) { data_for_children->scroll_tree_parent = parent_id; } else { ScrollNode node; node.owner_id = layer->id(); node.data.scrollable = scrollable; node.data.main_thread_scrolling_reasons = main_thread_scrolling_reasons; node.data.contains_non_fast_scrollable_region = contains_non_fast_scrollable_region; gfx::Size clip_bounds; if (layer->scroll_clip_layer()) { clip_bounds = layer->scroll_clip_layer()->bounds(); DCHECK(layer->scroll_clip_layer()->transform_tree_index() != kInvalidPropertyTreeNodeId); node.data.max_scroll_offset_affected_by_page_scale = !data_from_ancestor.transform_tree ->Node(layer->scroll_clip_layer()->transform_tree_index()) ->data.in_subtree_of_page_scale_layer && data_from_ancestor.in_subtree_of_page_scale_layer; } node.data.scroll_clip_layer_bounds = clip_bounds; node.data.is_inner_viewport_scroll_layer = layer == data_from_ancestor.inner_viewport_scroll_layer; node.data.is_outer_viewport_scroll_layer = layer == data_from_ancestor.outer_viewport_scroll_layer; node.data.bounds = layer->bounds(); node.data.offset_to_transform_parent = layer->offset_to_transform_parent(); node.data.should_flatten = layer->should_flatten_transform_from_property_tree(); node.data.user_scrollable_horizontal = layer->user_scrollable_horizontal(); node.data.user_scrollable_vertical = layer->user_scrollable_vertical(); node.data.element_id = layer->element_id(); node.data.transform_id = data_for_children->transform_tree_parent->transform_tree_index(); data_for_children->scroll_tree_parent = data_for_children->scroll_tree->Insert(node, parent_id); data_for_children->main_thread_scrolling_reasons = node.data.main_thread_scrolling_reasons; data_for_children->scroll_tree_parent_created_by_uninheritable_criteria = scroll_node_uninheritable_criteria; if (node.data.scrollable) { data_for_children->scroll_tree->synced_scroll_offset(layer->id()) ->PushFromMainThread(layer->CurrentScrollOffset()); } } layer->SetScrollTreeIndex(data_for_children->scroll_tree_parent); } template <typename LayerType> void SetBackfaceVisibilityTransform(LayerType* layer, bool created_transform_node) { const bool is_at_boundary_of_3d_rendering_context = IsAtBoundaryOf3dRenderingContext(layer); if (layer->use_parent_backface_visibility()) { DCHECK(!is_at_boundary_of_3d_rendering_context); DCHECK(layer->parent()); DCHECK(!layer->parent()->use_parent_backface_visibility()); layer->SetUseLocalTransformForBackfaceVisibility( layer->parent()->use_local_transform_for_backface_visibility()); layer->SetShouldCheckBackfaceVisibility( layer->parent()->should_check_backface_visibility()); } else { // The current W3C spec on CSS transforms says that backface visibility // should be determined differently depending on whether the layer is in a // "3d rendering context" or not. For Chromium code, we can determine // whether we are in a 3d rendering context by checking if the parent // preserves 3d. const bool use_local_transform = !layer->Is3dSorted() || (layer->Is3dSorted() && is_at_boundary_of_3d_rendering_context); layer->SetUseLocalTransformForBackfaceVisibility(use_local_transform); // A double-sided layer's backface can been shown when its visibile. if (layer->double_sided()) layer->SetShouldCheckBackfaceVisibility(false); // The backface of a layer that uses local transform for backface visibility // is not visible when it does not create a transform node as its local // transform is identity or 2d translation and is not animating. else if (use_local_transform && !created_transform_node) layer->SetShouldCheckBackfaceVisibility(false); else layer->SetShouldCheckBackfaceVisibility(true); } } template <typename LayerType> void SetSafeOpaqueBackgroundColor( const DataForRecursion<LayerType>& data_from_ancestor, LayerType* layer, DataForRecursion<LayerType>* data_for_children) {<|fim▁hole|> ? background_color : data_from_ancestor.safe_opaque_background_color; layer->SetSafeOpaqueBackgroundColor( data_for_children->safe_opaque_background_color); } static void SetLayerPropertyChangedForChild(Layer* parent, Layer* child) { if (parent->subtree_property_changed()) child->SetSubtreePropertyChanged(); } static void SetLayerPropertyChangedForChild(LayerImpl* parent, LayerImpl* child) {} template <typename LayerType> void BuildPropertyTreesInternal( LayerType* layer, const DataForRecursion<LayerType>& data_from_parent, DataForRecursionFromChild<LayerType>* data_to_parent) { layer->set_property_tree_sequence_number(data_from_parent.sequence_number); if (layer->mask_layer()) layer->mask_layer()->set_property_tree_sequence_number( data_from_parent.sequence_number); DataForRecursion<LayerType> data_for_children(data_from_parent); bool created_render_surface = AddEffectNodeIfNeeded(data_from_parent, layer, &data_for_children); if (created_render_surface) { data_for_children.render_target = data_for_children.effect_tree_parent; layer->set_draw_blend_mode(SkXfermode::kSrcOver_Mode); } else { layer->set_draw_blend_mode(layer->blend_mode()); } bool created_transform_node = AddTransformNodeIfNeeded( data_from_parent, layer, created_render_surface, &data_for_children); AddClipNodeIfNeeded(data_from_parent, layer, created_render_surface, created_transform_node, &data_for_children); AddScrollNodeIfNeeded(data_from_parent, layer, &data_for_children); SetBackfaceVisibilityTransform(layer, created_transform_node); SetSafeOpaqueBackgroundColor(data_from_parent, layer, &data_for_children); for (size_t i = 0; i < layer->children().size(); ++i) { SetLayerPropertyChangedForChild(layer, layer->child_at(i)); if (!layer->child_at(i)->scroll_parent()) { DataForRecursionFromChild<LayerType> data_from_child; BuildPropertyTreesInternal(layer->child_at(i), data_for_children, &data_from_child); data_to_parent->Merge(data_from_child); } else { // The child should be included in its scroll parent's list of scroll // children. DCHECK(layer->child_at(i)->scroll_parent()->scroll_children()->count( layer->child_at(i))); } } if (layer->scroll_children()) { for (LayerType* scroll_child : *layer->scroll_children()) { DCHECK_EQ(scroll_child->scroll_parent(), layer); DataForRecursionFromChild<LayerType> data_from_child; DCHECK(scroll_child->parent()); data_for_children.render_target = scroll_child->parent()->effect_tree_index(); BuildPropertyTreesInternal(scroll_child, data_for_children, &data_from_child); data_to_parent->Merge(data_from_child); } } if (layer->has_replica()) { DataForRecursionFromChild<LayerType> data_from_child; BuildPropertyTreesInternal(layer->replica_layer(), data_for_children, &data_from_child); data_to_parent->Merge(data_from_child); } if (layer->HasCopyRequest()) data_to_parent->num_copy_requests_in_subtree++; if (data_for_children.effect_tree->Node(data_for_children.effect_tree_parent) ->owner_id == layer->id()) data_for_children.effect_tree->Node(data_for_children.effect_tree_parent) ->data.num_copy_requests_in_subtree = data_to_parent->num_copy_requests_in_subtree; } } // namespace template <typename LayerType> void BuildPropertyTreesTopLevelInternal( LayerType* root_layer, const LayerType* page_scale_layer, const LayerType* inner_viewport_scroll_layer, const LayerType* outer_viewport_scroll_layer, const LayerType* overscroll_elasticity_layer, const gfx::Vector2dF& elastic_overscroll, float page_scale_factor, float device_scale_factor, const gfx::Rect& viewport, const gfx::Transform& device_transform, PropertyTrees* property_trees, SkColor color) { if (!property_trees->needs_rebuild) { draw_property_utils::UpdatePageScaleFactor( property_trees, page_scale_layer, page_scale_factor, device_scale_factor, device_transform); draw_property_utils::UpdateElasticOverscroll( property_trees, overscroll_elasticity_layer, elastic_overscroll); property_trees->clip_tree.SetViewportClip(gfx::RectF(viewport)); property_trees->transform_tree.SetDeviceTransform(device_transform, root_layer->position()); return; } property_trees->sequence_number++; DataForRecursion<LayerType> data_for_recursion; data_for_recursion.transform_tree = &property_trees->transform_tree; data_for_recursion.clip_tree = &property_trees->clip_tree; data_for_recursion.effect_tree = &property_trees->effect_tree; data_for_recursion.scroll_tree = &property_trees->scroll_tree; data_for_recursion.transform_tree_parent = nullptr; data_for_recursion.transform_fixed_parent = nullptr; data_for_recursion.render_target = kRootPropertyTreeNodeId; data_for_recursion.clip_tree_parent = kRootPropertyTreeNodeId; data_for_recursion.effect_tree_parent = kInvalidPropertyTreeNodeId; data_for_recursion.scroll_tree_parent = kRootPropertyTreeNodeId; data_for_recursion.page_scale_layer = page_scale_layer; data_for_recursion.inner_viewport_scroll_layer = inner_viewport_scroll_layer; data_for_recursion.outer_viewport_scroll_layer = outer_viewport_scroll_layer; data_for_recursion.overscroll_elasticity_layer = overscroll_elasticity_layer; data_for_recursion.elastic_overscroll = elastic_overscroll; data_for_recursion.page_scale_factor = page_scale_factor; data_for_recursion.in_subtree_of_page_scale_layer = false; data_for_recursion.affected_by_inner_viewport_bounds_delta = false; data_for_recursion.affected_by_outer_viewport_bounds_delta = false; data_for_recursion.should_flatten = false; data_for_recursion.target_is_clipped = false; data_for_recursion.is_hidden = false; data_for_recursion.main_thread_scrolling_reasons = MainThreadScrollingReason::kNotScrollingOnMain; data_for_recursion.scroll_tree_parent_created_by_uninheritable_criteria = true; data_for_recursion.device_transform = &device_transform; data_for_recursion.transform_tree->clear(); data_for_recursion.clip_tree->clear(); data_for_recursion.effect_tree->clear(); data_for_recursion.scroll_tree->clear(); data_for_recursion.compound_transform_since_render_target = gfx::Transform(); data_for_recursion.axis_align_since_render_target = true; data_for_recursion.sequence_number = property_trees->sequence_number; data_for_recursion.transform_tree->set_device_scale_factor( device_scale_factor); data_for_recursion.safe_opaque_background_color = color; ClipNode root_clip; root_clip.data.resets_clip = true; root_clip.data.applies_local_clip = true; root_clip.data.clip = gfx::RectF(viewport); root_clip.data.transform_id = kRootPropertyTreeNodeId; data_for_recursion.clip_tree_parent = data_for_recursion.clip_tree->Insert(root_clip, kRootPropertyTreeNodeId); DataForRecursionFromChild<LayerType> data_from_child; BuildPropertyTreesInternal(root_layer, data_for_recursion, &data_from_child); property_trees->needs_rebuild = false; // The transform tree is kept up-to-date as it is built, but the // combined_clips stored in the clip tree and the screen_space_opacity and // is_drawn in the effect tree aren't computed during tree building. property_trees->transform_tree.set_needs_update(false); property_trees->clip_tree.set_needs_update(true); property_trees->effect_tree.set_needs_update(true); property_trees->scroll_tree.set_needs_update(false); } void PropertyTreeBuilder::BuildPropertyTrees( Layer* root_layer, const Layer* page_scale_layer, const Layer* inner_viewport_scroll_layer, const Layer* outer_viewport_scroll_layer, const Layer* overscroll_elasticity_layer, const gfx::Vector2dF& elastic_overscroll, float page_scale_factor, float device_scale_factor, const gfx::Rect& viewport, const gfx::Transform& device_transform, PropertyTrees* property_trees) { property_trees->is_main_thread = true; property_trees->is_active = false; SkColor color = root_layer->layer_tree_host()->background_color(); if (SkColorGetA(color) != 255) color = SkColorSetA(color, 255); BuildPropertyTreesTopLevelInternal( root_layer, page_scale_layer, inner_viewport_scroll_layer, outer_viewport_scroll_layer, overscroll_elasticity_layer, elastic_overscroll, page_scale_factor, device_scale_factor, viewport, device_transform, property_trees, color); } void PropertyTreeBuilder::BuildPropertyTrees( LayerImpl* root_layer, const LayerImpl* page_scale_layer, const LayerImpl* inner_viewport_scroll_layer, const LayerImpl* outer_viewport_scroll_layer, const LayerImpl* overscroll_elasticity_layer, const gfx::Vector2dF& elastic_overscroll, float page_scale_factor, float device_scale_factor, const gfx::Rect& viewport, const gfx::Transform& device_transform, PropertyTrees* property_trees) { property_trees->is_main_thread = false; property_trees->is_active = root_layer->IsActive(); SkColor color = root_layer->layer_tree_impl()->background_color(); if (SkColorGetA(color) != 255) color = SkColorSetA(color, 255); BuildPropertyTreesTopLevelInternal( root_layer, page_scale_layer, inner_viewport_scroll_layer, outer_viewport_scroll_layer, overscroll_elasticity_layer, elastic_overscroll, page_scale_factor, device_scale_factor, viewport, device_transform, property_trees, color); } } // namespace cc<|fim▁end|>
SkColor background_color = layer->background_color(); data_for_children->safe_opaque_background_color = SkColorGetA(background_color) == 255
<|file_name|>SendDatagramMessage.java<|end_file_name|><|fim▁begin|>package pl.edu.mimuw.cloudatlas.agent.modules.network; import java.net.InetAddress; import pl.edu.mimuw.cloudatlas.agent.modules.framework.SimpleMessage; public final class SendDatagramMessage extends SimpleMessage<byte[]> { private InetAddress target; private int port; public SendDatagramMessage(byte[] content, InetAddress target, int port) { super(content); this.target = target; this.port = port; } public InetAddress getTarget() { return target; } public int getPort() { return port; }<|fim▁hole|><|fim▁end|>
}
<|file_name|>ofQuickTimeGrabber.cpp<|end_file_name|><|fim▁begin|>#include "ofQuickTimeGrabber.h" #include "ofUtils.h" #if !defined(TARGET_LINUX) && !defined(MAC_OS_X_VERSION_10_7) //--------------------------------- #ifdef OF_VIDEO_CAPTURE_QUICKTIME //--------------------------------- //-------------------------------------------------------------- static ComponentResult frameIsGrabbedProc(SGChannel sgChan, short nBufferNum, Boolean *pbDone, long lRefCon); static ComponentResult frameIsGrabbedProc(SGChannel sgChan, short nBufferNum, Boolean *pbDone, long lRefCon){ ComponentResult err = SGGrabFrameComplete( sgChan, nBufferNum, pbDone ); bool * havePixChanged = (bool *)lRefCon; *havePixChanged = true; return err; } //--------------------------------- #endif //--------------------------------- //-------------------------------------------------------------------- ofQuickTimeGrabber::ofQuickTimeGrabber(){ //--------------------------------- #ifdef OF_VIDEO_CAPTURE_QUICKTIME //--------------------------------- initializeQuicktime(); bSgInited = false; gSeqGrabber = nullptr; offscreenGWorldPixels = nullptr; //--------------------------------- #endif //--------------------------------- // common bIsFrameNew = false; bVerbose = false; bGrabberInited = false; bChooseDevice = false; deviceID = 0; //width = 320; // default setting //height = 240; // default setting //pixels = nullptr; attemptFramerate = -1; } //-------------------------------------------------------------------- ofQuickTimeGrabber::~ofQuickTimeGrabber(){ close(); //--------------------------------- #ifdef OF_VIDEO_CAPTURE_QUICKTIME //--------------------------------- if (offscreenGWorldPixels != nullptr){ delete[] offscreenGWorldPixels; offscreenGWorldPixels = nullptr; } //--------------------------------- #endif //--------------------------------- } //-------------------------------------------------------------------- void ofQuickTimeGrabber::setVerbose(bool bTalkToMe){ bVerbose = bTalkToMe; } //-------------------------------------------------------------------- void ofQuickTimeGrabber::setDeviceID(int _deviceID){ deviceID = _deviceID; bChooseDevice = true; } //-------------------------------------------------------------------- void ofQuickTimeGrabber::setDesiredFrameRate(int framerate){ attemptFramerate = framerate; } //--------------------------------------------------------------------------- bool ofQuickTimeGrabber::setPixelFormat(ofPixelFormat pixelFormat){ //note as we only support RGB we are just confirming that this pixel format is supported if( pixelFormat == OF_PIXELS_RGB ){ return true; } ofLogWarning("ofQuickTimeGrabber") << "setPixelFormat(): requested pixel format " << pixelFormat << " not supported"; return false; } //--------------------------------------------------------------------------- ofPixelFormat ofQuickTimeGrabber::getPixelFormat() const { //note if you support more than one pixel format you will need to return a ofPixelFormat variable. return OF_PIXELS_RGB; } //-------------------------------------------------------------------- bool ofQuickTimeGrabber::setup(int w, int h){ //--------------------------------- #ifdef OF_VIDEO_CAPTURE_QUICKTIME //--------------------------------- //---------------------------------- 1 - open the sequence grabber if( !qtInitSeqGrabber() ){ ofLogError("ofQuickTimeGrabber") << "initGrabber(): unable to initialize the seq grabber"; return false; } //---------------------------------- 2 - set the dimensions //width = w; //height = h; MacSetRect(&videoRect, 0, 0, w, h); //---------------------------------- 3 - buffer allocation // Create a buffer big enough to hold the video data, // make sure the pointer is 32-byte aligned. // also the rgb image that people will grab offscreenGWorldPixels = (unsigned char*)malloc(4 * w * h + 32); pixels.allocate(w, h, OF_IMAGE_COLOR); #if defined(TARGET_OSX) && defined(__BIG_ENDIAN__) QTNewGWorldFromPtr (&(videogworld), k32ARGBPixelFormat, &(videoRect), nullptr, nullptr, 0, (offscreenGWorldPixels), 4 * w); #else QTNewGWorldFromPtr (&(videogworld), k24RGBPixelFormat, &(videoRect), nullptr, nullptr, 0, (pixels.getPixels()), 3 * w); #endif LockPixels(GetGWorldPixMap(videogworld)); SetGWorld (videogworld, nullptr); SGSetGWorld(gSeqGrabber, videogworld, nil); //---------------------------------- 4 - device selection bool didWeChooseADevice = bChooseDevice; bool deviceIsSelected = false; //if we have a device selected then try first to setup //that device if(didWeChooseADevice){ deviceIsSelected = qtSelectDevice(deviceID, true); if(!deviceIsSelected && bVerbose) ofLogError("ofQuickTimeGrabber") << "initGrabber(): unable to open device[" << deviceID << "], will attempt other devices"; } //if we couldn't select our required device //or we aren't specifiying a device to setup //then lets try to setup ANY device! if(deviceIsSelected == false){ //lets list available devices listDevices(); setDeviceID(0); deviceIsSelected = qtSelectDevice(deviceID, false); } //if we still haven't been able to setup a device //we should error and stop! if( deviceIsSelected == false){ goto bail; } //---------------------------------- 5 - final initialization steps OSStatus err; err = SGSetChannelUsage(gVideoChannel,seqGrabPreview); if ( err != noErr ) goto bail; //----------------- callback method for notifying new frame err = SGSetChannelRefCon(gVideoChannel, (long)&bHavePixelsChanged ); if(!err) { VideoBottles vb; /* get the current bottlenecks */ vb.procCount = 9; err = SGGetVideoBottlenecks(gVideoChannel, &vb); if (!err) { myGrabCompleteProc = NewSGGrabCompleteBottleUPP(frameIsGrabbedProc); vb.grabCompleteProc = myGrabCompleteProc; /* add our GrabFrameComplete function */ err = SGSetVideoBottlenecks(gVideoChannel, &vb); } } err = SGSetChannelBounds(gVideoChannel, &videoRect); if ( err != noErr ) goto bail; err = SGPrepare(gSeqGrabber, true, false); //theo swapped so preview is true and capture is false if ( err != noErr ) goto bail; err = SGStartPreview(gSeqGrabber); if ( err != noErr ) goto bail; bGrabberInited = true; loadSettings(); if( attemptFramerate >= 0 ){ err = SGSetFrameRate(gVideoChannel, IntToFixed(attemptFramerate) ); if ( err != noErr ){ ofLogError("ofQuickTimeGrabber") << "initGrabber: couldn't setting framerate to " << attemptFramerate << ": OSStatus " << err; } } ofLogNotice("ofQuickTimeGrabber") << " inited grabbed "; ofLogNotice("ofQuickTimeGrabber") << "-------------------------------------"; // we are done return true; //--------------------- (bail) something's wrong ----- bail: ofLogError("ofQuickTimeGrabber") << "***** ofQuickTimeGrabber error *****"; ofLogError("ofQuickTimeGrabber") << "------------------------------------"; //if we don't close this - it messes up the next device! if(bSgInited) qtCloseSeqGrabber(); bGrabberInited = false; return false; //--------------------------------- #else //--------------------------------- return false; //--------------------------------- #endif //--------------------------------- } //-------------------------------------------------------------------- bool ofQuickTimeGrabber::isInitialized() const{ return bGrabberInited; } //-------------------------------------------------------------------- vector<ofVideoDevice> ofQuickTimeGrabber::listDevices() const{ vector <ofVideoDevice> devices; //--------------------------------- #ifdef OF_VIDEO_CAPTURE_QUICKTIME //--------------------------------- bool bNeedToInitGrabberFirst = false; if (!bSgInited) bNeedToInitGrabberFirst = true; //if we need to initialize the grabbing component then do it if( bNeedToInitGrabberFirst ){ if( !qtInitSeqGrabber() ){ return devices; } } ofLogNotice("ofQuickTimeGrabber") << "-------------------------------------"; /* //input selection stuff (ie multiple webcams) //from http://developer.apple.com/samplecode/SGDevices/listing13.html //and originally http://lists.apple.com/archives/QuickTime-API/2008/Jan/msg00178.html */ SGDeviceList deviceList; SGGetChannelDeviceList (gVideoChannel, sgDeviceListIncludeInputs, &deviceList); unsigned char pascalName[64]; unsigned char pascalNameInput[64]; //this is our new way of enumerating devices //quicktime can have multiple capture 'inputs' on the same capture 'device' //ie the USB Video Class Video 'device' - can have multiple usb webcams attached on what QT calls 'inputs' //The isight for example will show up as: //USB Video Class Video - Built-in iSight ('input' 1 of the USB Video Class Video 'device') //Where as another webcam also plugged whill show up as //USB Video Class Video - Philips SPC 1000NC Webcam ('input' 2 of the USB Video Class Video 'device') //this means our the device ID we use for selection has to count both capture 'devices' and their 'inputs' //this needs to be the same in our init grabber method so that we select the device we ask for int deviceCount = 0; ofLogNotice("ofQuickTimeGrabber") << "listing available capture devices"; for(int i = 0 ; i < (*deviceList)->count ; ++i) { SGDeviceName nameRec; nameRec = (*deviceList)->entry[i]; SGDeviceInputList deviceInputList = nameRec.inputs; int numInputs = 0; if( deviceInputList ) numInputs = ((*deviceInputList)->count); memcpy(pascalName, (*deviceList)->entry[i].name, sizeof(char) * 64); //this means we can use the capture method if(nameRec.flags != sgDeviceNameFlagDeviceUnavailable){ //if we have a capture 'device' (qt's word not mine - I would prefer 'system' ) that is ready to be used //we go through its inputs to list all physical devices - as there could be more than one! for(int j = 0; j < numInputs; j++){ //if our 'device' has inputs we get their names here if( deviceInputList ){ SGDeviceInputName inputNameRec = (*deviceInputList)->entry[j]; memcpy(pascalNameInput, inputNameRec.name, sizeof(char) * 64); } ofLogNotice() << "device [" << deviceCount << "] " << p2cstr(pascalName) << " - " << p2cstr(pascalNameInput); ofVideoDevice vd; vd.id = deviceCount; vd.deviceName = p2cstr(pascalName); vd.bAvailable = true; devices.push_back(vd); //we count this way as we need to be able to distinguish multiple inputs as devices deviceCount++; } }else{ ofLogNotice("ofQuickTimeGrabber") << "(unavailable) device [" << deviceCount << "] " << p2cstr(pascalName); ofVideoDevice vd; vd.id = deviceCount; vd.deviceName = p2cstr(pascalName); vd.bAvailable = false; devices.push_back(vd); deviceCount++; } } ofLogNotice("ofQuickTimeGrabber") << "-------------------------------------"; //if we initialized the grabbing component then close it if( bNeedToInitGrabberFirst ){ qtCloseSeqGrabber(); } //--------------------------------- #endif //--------------------------------- return devices; } //-------------------------------------------------------------------- void ofQuickTimeGrabber::update(){ //--------------------------------- #ifdef OF_VIDEO_CAPTURE_QUICKTIME //--------------------------------- if (bGrabberInited == true){ SGIdle(gSeqGrabber); // set the top pixel alpha = 0, so we can know if it // was a new frame or not.. // or else we will process way more than necessary // (ie opengl is running at 60fps +, capture at 30fps) if (bHavePixelsChanged){ #if defined(TARGET_OSX) && defined(__BIG_ENDIAN__) convertPixels(offscreenGWorldPixels, pixels.getPixels(), width, height); #endif } } // newness test for quicktime: if (bGrabberInited == true){ bIsFrameNew = false; if (bHavePixelsChanged == true){ bIsFrameNew = true; bHavePixelsChanged = false; } } //--------------------------------- #endif //--------------------------------- } //--------------------------------------------------------------------------- ofPixels& ofQuickTimeGrabber::getPixels(){ return pixels; } //--------------------------------------------------------------------------- const ofPixels& ofQuickTimeGrabber::getPixels() const { return pixels; } //--------------------------------------------------------------------------- bool ofQuickTimeGrabber::isFrameNew() const { return bIsFrameNew; } //-------------------------------------------------------------------- float ofQuickTimeGrabber::getWidth() const { return pixels.getWidth(); } //-------------------------------------------------------------------- float ofQuickTimeGrabber::getHeight() const { return pixels.getHeight(); } //-------------------------------------------------------------------- void ofQuickTimeGrabber::clearMemory(){ pixels.clear(); } //-------------------------------------------------------------------- void ofQuickTimeGrabber::close(){ //--------------------------------- #ifdef OF_VIDEO_CAPTURE_QUICKTIME //--------------------------------- qtCloseSeqGrabber(); DisposeSGGrabCompleteBottleUPP(myGrabCompleteProc); //--------------------------------- #endif //--------------------------------- clearMemory(); } //-------------------------------------------------------------------- void ofQuickTimeGrabber::videoSettings(void){ //--------------------------------- #ifdef OF_VIDEO_CAPTURE_QUICKTIME //--------------------------------- Rect curBounds, curVideoRect; ComponentResult err; // Get our current state err = SGGetChannelBounds (gVideoChannel, &curBounds); if (err != noErr){ ofLogError("ofQuickTimeGrabber") << "videoSettings(): couldn't get get channel bounds: ComponentResult " << err; return; } err = SGGetVideoRect (gVideoChannel, &curVideoRect); if (err != noErr){ ofLogError("ofQuickTimeGrabber") << "videoSettings(): couldn't get video rect: ComponentResult " << err; return; } // Pause err = SGPause (gSeqGrabber, true); if (err != noErr){ ofLogError("ofQuickTimeGrabber") << "videoSettings(): couldn't set pause: ComponentResult " << err; return; } #ifdef TARGET_OSX //load any saved camera settings from file loadSettings(); static SGModalFilterUPP gSeqGrabberModalFilterUPP = NewSGModalFilterUPP(SeqGrabberModalFilterUPP); ComponentResult result = SGSettingsDialog(gSeqGrabber, gVideoChannel, 0, nil, 0, gSeqGrabberModalFilterUPP, nil); if (result != noErr){ ofLogError("ofQuickTimeGrabber") << "videoSettings(): settings dialog error: ComponentResult " << err; return; } //save any changed settings to file saveSettings(); #else SGSettingsDialog(gSeqGrabber, gVideoChannel, 0, nil, seqGrabSettingsPreviewOnly, nullptr, 0); #endif SGSetChannelBounds(gVideoChannel, &videoRect); SGPause (gSeqGrabber, false); //--------------------------------- #endif //--------------------------------- } //-------------------------------------------------------------------- #ifdef TARGET_OSX //-------------------------------------------------------------------- //--------------------------------------------------------------------- bool ofQuickTimeGrabber::saveSettings(){ if (bGrabberInited != true) return false; ComponentResult err; UserData mySGVideoSettings = nullptr; // get the SGChannel settings cofigured by the user err = SGGetChannelSettings(gSeqGrabber, gVideoChannel, &mySGVideoSettings, 0); if ( err != noErr ){ ofLogError("ofQuickTimeGrabber") << "saveSettings(): couldn't get camera settings: ComponentResult " << err; return false; } string pref = "ofVideoSettings-"+deviceName; CFStringRef cameraString = CFStringCreateWithCString(kCFAllocatorDefault,pref.c_str(),kCFStringEncodingMacRoman); //get the settings using the key "ofVideoSettings-the name of the device" SaveSettingsPreference( cameraString, mySGVideoSettings); DisposeUserData(mySGVideoSettings); return true; } //--------------------------------------------------------------------- bool ofQuickTimeGrabber::loadSettings(){ if (bGrabberInited != true || deviceName.length() == 0) return false; ComponentResult err; UserData mySGVideoSettings = nullptr; // get the settings using the key "ofVideoSettings-the name of the device" string pref = "ofVideoSettings-"+deviceName; CFStringRef cameraString = CFStringCreateWithCString(kCFAllocatorDefault,pref.c_str(),kCFStringEncodingMacRoman); GetSettingsPreference(cameraString, &mySGVideoSettings); if (mySGVideoSettings){ Rect curBounds, curVideoRect; //we need to make sure the dimensions don't get effected //by our preferences // Get our current state err = SGGetChannelBounds (gVideoChannel, &curBounds); if (err != noErr){ ofLogError("ofQuickTimeGrabber") << "loadSettings(): couldn't set channel bounds: ComponentResult " << err; } err = SGGetVideoRect (gVideoChannel, &curVideoRect); if (err != noErr){ ofLogError("ofQuickTimeGrabber") << "loadSettings(): couldn't set video rect: ComponentResult " << err; } // use the saved settings preference to configure the SGChannel err = SGSetChannelSettings(gSeqGrabber, gVideoChannel, mySGVideoSettings, 0); if ( err != noErr ) { ofLogError("ofQuickTimeGrabber") << "loadSettings(): couldn't set channel settings: ComponentResult " << err; return false; } DisposeUserData(mySGVideoSettings); // Pause err = SGPause (gSeqGrabber, true); if (err != noErr){ ofLogError("ofQuickTimeGrabber") << "loadSettings(): couldn't set pause: ComponentResult " << err; } SGSetChannelBounds(gVideoChannel, &videoRect); SGPause (gSeqGrabber, false); }else{ ofLogWarning("ofQuickTimeGrabber") << "loadSettings(): no camera settings to load"; return false; } return true; } //------------------------------------------------------ bool ofQuickTimeGrabber::qtInitSeqGrabber(){ if (bSgInited != true){ OSErr err = noErr; ComponentDescription theDesc; Component sgCompID; // this crashes when we get to // SGNewChannel // we get -9405 as error code for the channel // ----------------------------------------- // gSeqGrabber = OpenDefaultComponent(SeqGrabComponentType, 0); // this seems to work instead (got it from hackTV) // ----------------------------------------- theDesc.componentType = SeqGrabComponentType; theDesc.componentSubType = nullptr; theDesc.componentManufacturer = 'appl'; theDesc.componentFlags = nullptr; theDesc.componentFlagsMask = nullptr; sgCompID = FindNextComponent (nullptr, &theDesc); // ----------------------------------------- if (sgCompID == nullptr){ ofLogError("ofQuickTimeGrabber") << "qtInitSeqGrabber(): findNextComponent did not return a valid component"; return false; } gSeqGrabber = OpenComponent(sgCompID); err = GetMoviesError(); if (gSeqGrabber == nullptr || err) { ofLogError("ofQuickTimeGrabber") << "qtInitSeqGrabber(): couldn't get default sequence grabber component: OSErr " << err; return false; } err = SGInitialize(gSeqGrabber); if (err != noErr) { ofLogError("ofQuickTimeGrabber") << "qtInitSeqGrabber(): can't initialize sequence grabber component: OSErr " << err; return false; } err = SGSetDataRef(gSeqGrabber, 0, 0, seqGrabDontMakeMovie); if (err != noErr) { ofLogError("ofQuickTimeGrabber") << "qtInitSeqGrabber(): can't set the destination data reference: OSErr " << err; return false; } // windows crashes w/ out gworld, make a dummy for now... // this took a long time to figure out. err = SGSetGWorld(gSeqGrabber, 0, 0); if (err != noErr) { ofLogError("ofQuickTimeGrabber") << "qtInitSeqGrabber(): setting up the gworld: OSErr " << err; return false; } err = SGNewChannel(gSeqGrabber, VideoMediaType, &(gVideoChannel)); if (err != noErr) { ofLogError("ofQuickTimeGrabber") << "qtInitSeqGrabber(): couldn't create a new channel: OSErr " << err; ofLogError("ofQuickTimeGrabber") << "qtInitSeqGrabber(): check if you have any qt capable cameras attached"; return false; } bSgInited = true; return true; } return false; } //-------------------------------------------------------------------- bool ofQuickTimeGrabber::qtCloseSeqGrabber(){ if (gSeqGrabber != nullptr){ SGStop (gSeqGrabber); CloseComponent (gSeqGrabber); gSeqGrabber = nullptr; bSgInited = false; return true; } return false; } //-------------------------------------------------------------------- bool ofQuickTimeGrabber::qtSelectDevice(int deviceNumber, bool didWeChooseADevice){ //note - check for memory freeing possibly needed for the all SGGetChannelDeviceList mac stuff // also see notes in listDevices() regarding new enunemeration method. //Generate a device list and enumerate //all devices availble to the channel SGDeviceList deviceList; SGGetChannelDeviceList(gVideoChannel, sgDeviceListIncludeInputs, &deviceList); unsigned char pascalName[64]; unsigned char pascalNameInput[64]; int numDevices = (*deviceList)->count; if(numDevices == 0){ ofLogError("ofQuickTimeGrabber") << "no capture devices found"; return false; } int deviceCount = 0; for(int i = 0 ; i < numDevices; ++i) { SGDeviceName nameRec; nameRec = (*deviceList)->entry[i]; SGDeviceInputList deviceInputList = nameRec.inputs; int numInputs = 0; if( deviceInputList ) numInputs = ((*deviceInputList)->count); memcpy(pascalName, (*deviceList)->entry[i].name, sizeof(char) * 64); memset(pascalNameInput, 0, sizeof(char)*64); //this means we can use the capture method if(nameRec.flags != sgDeviceNameFlagDeviceUnavailable){<|fim▁hole|> //if we have a capture 'device' (qt's word not mine - I would prefer 'system' ) that is ready to be used //we go through its inputs to list all physical devices - as there could be more than one! for(int j = 0; j < numInputs; j++){ //if our 'device' has inputs we get their names here if( deviceInputList ){ SGDeviceInputName inputNameRec = (*deviceInputList)->entry[j]; memcpy(pascalNameInput, inputNameRec.name, sizeof(char) * 64); } //if the device number matches we try and setup the device //if we didn't specifiy a device then we will try all devices till one works! if( deviceCount == deviceNumber || !didWeChooseADevice ){ ofLogNotice("ofQuickTimeGrabber") << "attempting to open device [" << deviceCount << "] " << p2cstr(pascalName) << " - " << p2cstr(pascalNameInput); OSErr err1 = SGSetChannelDevice(gVideoChannel, pascalName); OSErr err2 = SGSetChannelDeviceInput(gVideoChannel, j); int successLevel = 0; //if there were no errors then we have opened the device without issue if ( err1 == noErr && err2 == noErr){ successLevel = 2; } //parameter errors are not fatal so we will try and open but will caution the user else if ( (err1 == paramErr || err1 == noErr) && (err2 == noErr || err2 == paramErr) ){ successLevel = 1; } //the device is opened! if ( successLevel > 0 ){ deviceName = (char *)p2cstr(pascalName); deviceName += "-"; deviceName += (char *)p2cstr(pascalNameInput); if(successLevel == 2){ ofLogNotice("ofQuickTimeGrabber") << "device " << deviceName << " opened successfully"; } else{ ofLogWarning("ofQuickTimeGrabber") << "device " << deviceName << " opened with some paramater errors, should be fine though!"; } //no need to keep searching - return that we have opened a device! return true; }else{ //if we selected a device in particular but failed we want to go through the whole list again - starting from 0 and try any device. //so we return false - and try one more time without a preference if( didWeChooseADevice ){ ofLogWarning("ofQuickTimeGrabber") << "problems setting device [" << deviceNumber << "] " << p2cstr(pascalName) << " - " << p2cstr(pascalNameInput) << " *****"; return false; }else{ ofLogWarning("ofQuickTimeGrabber") << "unable to open device, trying next device"; } } } //we count this way as we need to be able to distinguish multiple inputs as devices deviceCount++; } }else{ //ofLogError("ofQuickTimeGrabber") << "(unavailable) device [" << deviceCount << "] " << p2cstr(pascalName); deviceCount++; } } return false; } //--------------------------------- #endif //--------------------------------- #endif<|fim▁end|>
<|file_name|>use.rs<|end_file_name|><|fim▁begin|>extern crate proc_macro_examples; use proc_macro_examples::make_answer; make_answer!();<|fim▁hole|>fn main() { assert_eq!(42, answer()); }<|fim▁end|>
<|file_name|>linesearch_step.py<|end_file_name|><|fim▁begin|># Copyright 2020 Tensorforce Team. 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. # ============================================================================== import tensorflow as tf from tensorforce import TensorforceError from tensorforce.core import TensorDict, TensorSpec, TensorsSpec, tf_function, tf_util from tensorforce.core.optimizers import UpdateModifier from tensorforce.core.optimizers.solvers import solver_modules class LinesearchStep(UpdateModifier): """ Line-search-step update modifier, which performs a line search on the update step returned by the given optimizer to find a potentially superior smaller step size (specification key: `linesearch_step`). Args: optimizer (specification): Optimizer configuration (<span style="color:#C00000"><b>required</b></span>). max_iterations (parameter, int >= 1): Maximum number of line search iterations (<span style="color:#C00000"><b>required</b></span>). backtracking_factor (parameter, 0.0 < float < 1.0): Line search backtracking factor (<span style="color:#00C000"><b>default</b></span>: 0.75). name (string): (<span style="color:#0000C0"><b>internal use</b></span>).<|fim▁hole|> def __init__( self, *, optimizer, max_iterations, backtracking_factor=0.75, name=None, arguments_spec=None ): super().__init__(optimizer=optimizer, name=name, arguments_spec=arguments_spec) self.line_search = self.submodule( name='line_search', module='line_search', modules=solver_modules, max_iterations=max_iterations, backtracking_factor=backtracking_factor ) def initialize_given_variables(self, *, variables): super().initialize_given_variables(variables=variables) self.line_search.complete_initialize( arguments_spec=self.arguments_spec, values_spec=self.variables_spec ) @tf_function(num_args=1) def step(self, *, arguments, variables, fn_loss, **kwargs): loss_before = fn_loss(**arguments.to_kwargs()) with tf.control_dependencies(control_inputs=(loss_before,)): deltas = self.optimizer.step( arguments=arguments, variables=variables, fn_loss=fn_loss, **kwargs ) with tf.control_dependencies(control_inputs=deltas): def linesearch(): loss_after = fn_loss(**arguments.to_kwargs()) with tf.control_dependencies(control_inputs=(loss_after,)): # Replace "/" with "_" to ensure TensorDict is flat _deltas = TensorDict(( (var.name[:-2].replace('/', '_'), delta) for var, delta in zip(variables, deltas) )) # TODO: should be moved to initialize_given_variables, but fn_loss... def evaluate_step(arguments, deltas): assignments = list() for variable, delta in zip(variables, deltas.values()): assignments.append(variable.assign_add(delta=delta, read_value=False)) with tf.control_dependencies(control_inputs=assignments): return fn_loss(**arguments.to_kwargs()) _deltas = self.line_search.solve( arguments=arguments, x_init=_deltas, base_value=loss_before, zero_value=loss_after, fn_x=evaluate_step ) return tuple(_deltas.values()) num_nonzero = list() for delta in deltas: num_nonzero.append(tf.math.count_nonzero(input=delta)) num_nonzero = tf.math.add_n(inputs=num_nonzero) return tf.cond(pred=(num_nonzero == 0), true_fn=(lambda: deltas), false_fn=linesearch)<|fim▁end|>
arguments_spec (specification): <span style="color:#0000C0"><b>internal use</b></span>. """
<|file_name|>stored_values.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python ''' @author Luke C @date Mon Mar 25 09:57:59 EDT 2013 @file ion/util/stored_values.py ''' from pyon.core.exception import NotFound import gevent class StoredValueManager(object): def __init__(self, container): self.store = container.object_store def stored_value_cas(self, doc_key, document_updates): ''' Performs a check and set for a lookup_table in the object store for the given key ''' try: doc = self.store.read_doc(doc_key) except NotFound: doc_id, rev = self.store.create_doc(document_updates, object_id=doc_key)<|fim▁hole|> doc_id, rev = self.store.create_doc(document_updates, object_id=doc_key) return doc_id, rev for k,v in document_updates.iteritems(): doc[k] = v doc_id, rev = self.store.update_doc(doc) return doc_id, rev def read_value(self, doc_key): doc = self.store.read_doc(doc_key) return doc def read_value_mult(self, doc_keys, strict=False): doc_list = self.store.read_doc_mult(doc_keys, strict=strict) return doc_list def delete_stored_value(self, doc_key): self.store.delete_doc(doc_key)<|fim▁end|>
return doc_id, rev except KeyError as e: if 'http' in e.message:
<|file_name|>signals.py<|end_file_name|><|fim▁begin|>""".. Ignore pydocstyle D400. =============== Signal Handlers =============== """ from asgiref.sync import async_to_sync<|fim▁hole|> from django.conf import settings from django.db import transaction from django.db.models.signals import post_delete, post_save from django.dispatch import receiver from resolwe.flow.managers import manager from resolwe.flow.models import Data, Relation from resolwe.flow.models.entity import RelationPartition def commit_signal(data_id): """Nudge manager at the end of every Data object save event.""" if not getattr(settings, "FLOW_MANAGER_DISABLE_AUTO_CALLS", False): immediate = getattr(settings, "FLOW_MANAGER_SYNC_AUTO_CALLS", False) async_to_sync(manager.communicate)(data_id=data_id, run_sync=immediate) @receiver(post_save, sender=Data) def manager_post_save_handler(sender, instance, created, **kwargs): """Run newly created (spawned) processes.""" if ( instance.status == Data.STATUS_DONE or instance.status == Data.STATUS_ERROR or created ): # Run manager at the end of the potential transaction. Otherwise # tasks are send to workers before transaction ends and therefore # workers cannot access objects created inside transaction. transaction.on_commit(lambda: commit_signal(instance.id)) # NOTE: m2m_changed signal cannot be used because of a bug: # https://code.djangoproject.com/ticket/17688 @receiver(post_delete, sender=RelationPartition) def delete_relation(sender, instance, **kwargs): """Delete the Relation object when the last Entity is removed.""" def process_signal(relation_id): """Get the relation and delete it if it has no entities left.""" try: relation = Relation.objects.get(pk=relation_id) except Relation.DoesNotExist: return if relation.entities.count() == 0: relation.delete() # Wait for partitions to be recreated. transaction.on_commit(lambda: process_signal(instance.relation_id))<|fim▁end|>
<|file_name|>test_optimization.py<|end_file_name|><|fim▁begin|># Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import gast import pytest from tangent import optimization from tangent import quoting def test_assignment_propagation(): def f(x): y = x z = y return z node = quoting.parse_function(f) node = optimization.assignment_propagation(node) assert len(node.body[0].body) == 2 def test_dce(): def f(x): y = 2 * x return x node = quoting.parse_function(f) node = optimization.dead_code_elimination(node) assert isinstance(node.body[0].body[0], gast.Return) def test_fixed_point(): def f(x): y = g(x) z = h(y) return x node = quoting.parse_function(f) node = optimization.optimize(node) assert isinstance(node.body[0].body[0], gast.Return)<|fim▁hole|> def test_constant_folding(): def f(x): x = 1 * x x = 0 * x x = x * 1 x = x * 0 x = x * 2 x = 2 * x x = 2 * 3 x = 1 + x x = 0 + x x = x + 1 x = x + 0 x = x + 2 x = 2 + x x = 2 + 3 x = 1 - x x = 0 - x x = x - 1 x = x - 0 x = x - 2 x = 2 - x x = 2 - 3 x = 1 / x x = 0 / x x = x / 1 x = x / 0 x = x / 2 x = 2 / x x = 2 / 8 x = 1 ** x x = 0 ** x x = x ** 1 x = x ** 0 x = x ** 2 x = 2 ** x x = 2 ** 3 def f_opt(x): x = x x = 0 x = x x = 0 x = x * 2 x = 2 * x x = 6 x = 1 + x x = x x = x + 1 x = x x = x + 2 x = 2 + x x = 5 x = 1 - x x = -x x = x - 1 x = x x = x - 2 x = 2 - x x = -1 x = 1 / x x = 0 / x x = x x = x / 0 x = x / 2 x = 2 / x x = 0.25 x = 1 x = 0 x = x x = 1 x = x ** 2 x = 2 ** x x = 8 node = quoting.parse_function(f) node = optimization.constant_folding(node) node_opt = quoting.parse_function(f_opt) lines = quoting.to_source(node).strip().split('\n')[1:] lines_opt = quoting.to_source(node_opt).strip().split('\n')[1:] # In Python 2 integer division could be on, in which case... if 1 / 2 == 0: lines_opt[27] = ' x = 0' assert lines == lines_opt if __name__ == '__main__': assert not pytest.main([__file__])<|fim▁end|>
<|file_name|>SumLines.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ *************************************************************************** SumLines.py --------------------- Date : August 2012<|fim▁hole|>*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * *************************************************************************** """ __author__ = 'Victor Olaya' __date__ = 'August 2012' __copyright__ = '(C) 2012, Victor Olaya' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' import os from qgis.PyQt.QtGui import QIcon from qgis.core import QgsFeature, QgsGeometry, QgsFeatureRequest, QgsDistanceArea from processing.core.GeoAlgorithm import GeoAlgorithm from processing.core.parameters import ParameterVector from processing.core.parameters import ParameterString from processing.core.outputs import OutputVector from processing.tools import dataobjects, vector pluginPath = os.path.split(os.path.split(os.path.dirname(__file__))[0])[0] class SumLines(GeoAlgorithm): LINES = 'LINES' POLYGONS = 'POLYGONS' LEN_FIELD = 'LEN_FIELD' COUNT_FIELD = 'COUNT_FIELD' OUTPUT = 'OUTPUT' def getIcon(self): return QIcon(os.path.join(pluginPath, 'images', 'ftools', 'sum_lines.png')) def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('Sum line lengths') self.group, self.i18n_group = self.trAlgorithm('Vector analysis tools') self.addParameter(ParameterVector(self.LINES, self.tr('Lines'), [ParameterVector.VECTOR_TYPE_LINE])) self.addParameter(ParameterVector(self.POLYGONS, self.tr('Polygons'), [ParameterVector.VECTOR_TYPE_POLYGON])) self.addParameter(ParameterString(self.LEN_FIELD, self.tr('Lines length field name', 'LENGTH'))) self.addParameter(ParameterString(self.COUNT_FIELD, self.tr('Lines count field name', 'COUNT'))) self.addOutput(OutputVector(self.OUTPUT, self.tr('Line length'))) def processAlgorithm(self, progress): lineLayer = dataobjects.getObjectFromUri(self.getParameterValue(self.LINES)) polyLayer = dataobjects.getObjectFromUri(self.getParameterValue(self.POLYGONS)) lengthFieldName = self.getParameterValue(self.LEN_FIELD) countFieldName = self.getParameterValue(self.COUNT_FIELD) polyProvider = polyLayer.dataProvider() (idxLength, fieldList) = vector.findOrCreateField(polyLayer, polyLayer.pendingFields(), lengthFieldName) (idxCount, fieldList) = vector.findOrCreateField(polyLayer, fieldList, countFieldName) writer = self.getOutputFromName(self.OUTPUT).getVectorWriter( fieldList.toList(), polyProvider.geometryType(), polyProvider.crs()) spatialIndex = vector.spatialindex(lineLayer) ftLine = QgsFeature() ftPoly = QgsFeature() outFeat = QgsFeature() inGeom = QgsGeometry() outGeom = QgsGeometry() distArea = QgsDistanceArea() features = vector.features(polyLayer) total = 100.0 / len(features) hasIntersections = False for current, ftPoly in enumerate(features): inGeom = QgsGeometry(ftPoly.geometry()) attrs = ftPoly.attributes() count = 0 length = 0 hasIntersections = False lines = spatialIndex.intersects(inGeom.boundingBox()) if len(lines) > 0: hasIntersections = True if hasIntersections: for i in lines: request = QgsFeatureRequest().setFilterFid(i) ftLine = lineLayer.getFeatures(request).next() tmpGeom = QgsGeometry(ftLine.geometry()) if inGeom.intersects(tmpGeom): outGeom = inGeom.intersection(tmpGeom) length += distArea.measure(outGeom) count += 1 outFeat.setGeometry(inGeom) if idxLength == len(attrs): attrs.append(length) else: attrs[idxLength] = length if idxCount == len(attrs): attrs.append(count) else: attrs[idxCount] = count outFeat.setAttributes(attrs) writer.addFeature(outFeat) progress.setPercentage(int(current * total)) del writer<|fim▁end|>
Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com
<|file_name|>confirm-export.ts<|end_file_name|><|fim▁begin|>import require from 'require'; function getDescriptor(obj: Record<string, unknown>, path: string) { let parts = path.split('.'); let value: unknown = obj; for (let i = 0; i < parts.length - 1; i++) { let part = parts[i]!; // NOTE: This isn't entirely safe since we could have a null! value = (value as Record<string, unknown>)[part]; if (!value) { return undefined; } } let last = parts[parts.length - 1]!; return Object.getOwnPropertyDescriptor(value, last); } export default function confirmExport( Ember: Record<string, unknown>, assert: QUnit['assert'], path: string, moduleId: string, exportName: string | { value: unknown; get: string; set: string } ) { try { let desc: PropertyDescriptor | null | undefined; if (path !== null) { desc = getDescriptor(Ember, path); assert.ok(desc, `the ${path} property exists on the Ember global`); } else {<|fim▁hole|> if (desc == null) { let mod = require(moduleId); assert.notEqual( mod[exportName as string], undefined, `${moduleId}#${exportName} is not \`undefined\`` ); } else if (typeof exportName === 'string') { let mod = require(moduleId); let value = 'value' in desc ? desc.value : desc.get!.call(Ember); assert.equal(value, mod[exportName], `Ember.${path} is exported correctly`); assert.notEqual(mod[exportName], undefined, `Ember.${path} is not \`undefined\``); } else if ('value' in desc) { assert.equal(desc.value, exportName.value, `Ember.${path} is exported correctly`); } else { let mod = require(moduleId); assert.equal(desc.get, mod[exportName.get], `Ember.${path} getter is exported correctly`); assert.notEqual(desc.get, undefined, `Ember.${path} getter is not undefined`); if (exportName.set) { assert.equal(desc.set, mod[exportName.set], `Ember.${path} setter is exported correctly`); assert.notEqual(desc.set, undefined, `Ember.${path} setter is not undefined`); } } } catch (error) { assert.pushResult({ result: false, message: `An error occurred while testing ${path} is exported from ${moduleId}`, actual: error, expected: undefined, }); } }<|fim▁end|>
desc = null; }
<|file_name|>ReferenceToLineMapping.java<|end_file_name|><|fim▁begin|>package hu.eltesoft.modelexecution.m2t.smap.emf; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.Vector; /** * Maps qualified EMF object references to virtual line numbers. Line numbering * starts from one, and incremented by one when a new reference inserted. */ class ReferenceToLineMapping implements Serializable { private static final long serialVersionUID = 303577619348585564L; private final Vector<QualifiedReference> lineNumberToReference = new Vector<>(); private final Map<QualifiedReference, Integer> referenceToLineNumber = new HashMap<>();<|fim▁hole|> Integer result = toLineNumber(reference); if (null != result) { return result; } lineNumberToReference.add(reference); int lineNumber = lineNumberToReference.size(); referenceToLineNumber.put(reference, lineNumber); return lineNumber; } public Integer toLineNumber(QualifiedReference reference) { return referenceToLineNumber.get(reference); } public QualifiedReference fromLineNumber(int lineNumber) { // Vectors are indexed from zero, while lines from one int index = lineNumber - 1; if (index < 0 || lineNumberToReference.size() <= index) { return null; } return lineNumberToReference.get(index); } @Override public String toString() { return referenceToLineNumber.toString() + ";" + lineNumberToReference.toString(); } }<|fim▁end|>
public int addLineNumber(QualifiedReference reference) {
<|file_name|>test_server.py<|end_file_name|><|fim▁begin|># Copyright The Cloud Custodian Authors. # SPDX-License-Identifier: Apache-2.0 from common_openstack import OpenStackTest class ServerTest(OpenStackTest): def test_server_query(self): factory = self.replay_flight_data() p = self.load_policy({ 'name': 'all-servers', 'resource': 'openstack.server'}, session_factory=factory) resources = p.run() self.assertEqual(len(resources), 2) def test_server_filter_name(self): factory = self.replay_flight_data() policy = { 'name': 'get-server-c7n-test-1', 'resource': 'openstack.server', 'filters': [ { "type": "value",<|fim▁hole|> "value": "c7n-test-1", }, ], } p = self.load_policy(policy, session_factory=factory) resources = p.run() self.assertEqual(len(resources), 1) self.assertEqual(resources[0].name, "c7n-test-1") def test_server_filter_flavor(self): factory = self.replay_flight_data() policy = { 'name': 'get-server-c7n-test-1', 'resource': 'openstack.server', 'filters': [ { "type": "flavor", "flavor_name": "m1.tiny", }, ], } p = self.load_policy(policy, session_factory=factory) resources = p.run() self.assertEqual(len(resources), 1) self.assertEqual(resources[0].name, "c7n-test-1") def test_server_filter_tags(self): factory = self.replay_flight_data() policy = { 'name': 'get-server-c7n-test-1', 'resource': 'openstack.server', 'filters': [ { "type": "tags", "tags": [ { "key": "a", "value": "a", }, { "key": "b", "value": "b", }, ], "op": "all", }, ], } p = self.load_policy(policy, session_factory=factory) resources = p.run() self.assertEqual(len(resources), 1) self.assertEqual(resources[0].name, "c7n-test-2")<|fim▁end|>
"key": "name",
<|file_name|>0002_post_slug.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Generated by Django 1.9.3 on 2016-03-03 01:08 from __future__ import unicode_literals from django.db import migrations, models from blog.models import Post def slugify_all_posts(*args): for post in Post.objects.all(): post.save() class Migration(migrations.Migration): dependencies = [ ('blog', '0001_initial'), ] operations = [ migrations.AddField(<|fim▁hole|> migrations.RunPython(slugify_all_posts) ]<|fim▁end|>
model_name='post', name='slug', field=models.SlugField(default='', max_length=100), ),
<|file_name|>base.py<|end_file_name|><|fim▁begin|>import os from configurations import values from django.conf import global_settings class DjangoSettings(object): BASE_DIR = os.path.dirname(os.path.dirname(__file__)) SECRET_KEY = values.SecretValue() DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ) MIDDLEWARE_CLASSES = (<|fim▁hole|> 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = '{{ project_name }}.urls' WSGI_APPLICATION = '{{ project_name }}.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' class BaseSettings(DjangoSettings): pass<|fim▁end|>
<|file_name|>msi.py<|end_file_name|><|fim▁begin|>"""SCons.Tool.packaging.msi The msi packager. """ # # Copyright (c) 2001 - 2014 The SCons Foundation # # 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. __revision__ = "src/engine/SCons/Tool/packaging/msi.py 2014/07/05 09:42:21 garyo" import os import SCons from SCons.Action import Action from SCons.Builder import Builder from xml.dom.minidom import * from xml.sax.saxutils import escape from SCons.Tool.packaging import stripinstallbuilder # # Utility functions # def convert_to_id(s, id_set): """ Some parts of .wxs need an Id attribute (for example: The File and Directory directives. The charset is limited to A-Z, a-z, digits, underscores, periods. Each Id must begin with a letter or with a underscore. Google for "CNDL0015" for information about this. Requirements: * the string created must only contain chars from the target charset. * the string created must have a minimal editing distance from the original string. * the string created must be unique for the whole .wxs file. Observation: * There are 62 chars in the charset. Idea: * filter out forbidden characters. Check for a collision with the help of the id_set. Add the number of the number of the collision at the end of the created string. Furthermore care for a correct start of the string. """ charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxyz0123456789_.' if s[0] in '0123456789.': s += '_'+s id = [c for c in s if c in charset] # did we already generate an id for this file? try: return id_set[id][s] except KeyError: # no we did not so initialize with the id if id not in id_set: id_set[id] = { s : id } # there is a collision, generate an id which is unique by appending # the collision number else: id_set[id][s] = id + str(len(id_set[id])) return id_set[id][s] def is_dos_short_file_name(file): """ examine if the given file is in the 8.3 form. """ fname, ext = os.path.splitext(file) proper_ext = len(ext) == 0 or (2 <= len(ext) <= 4) # the ext contains the dot proper_fname = file.isupper() and len(fname) <= 8 return proper_ext and proper_fname def gen_dos_short_file_name(file, filename_set): """ see http://support.microsoft.com/default.aspx?scid=kb;en-us;Q142982 These are no complete 8.3 dos short names. The ~ char is missing and replaced with one character from the filename. WiX warns about such filenames, since a collision might occur. Google for "CNDL1014" for more information. """ # guard this to not confuse the generation if is_dos_short_file_name(file): return file fname, ext = os.path.splitext(file) # ext contains the dot # first try if it suffices to convert to upper file = file.upper() if is_dos_short_file_name(file): return file # strip forbidden characters. forbidden = '."/[]:;=, ' fname = [c for c in fname if c not in forbidden] # check if we already generated a filename with the same number: # thisis1.txt, thisis2.txt etc. duplicate, num = not None, 1 while duplicate: shortname = "%s%s" % (fname[:8-len(str(num))].upper(),\ str(num)) if len(ext) >= 2: shortname = "%s%s" % (shortname, ext[:4].upper()) duplicate, num = shortname in filename_set, num+1 assert( is_dos_short_file_name(shortname) ), 'shortname is %s, longname is %s' % (shortname, file) filename_set.append(shortname) return shortname def create_feature_dict(files): """ X_MSI_FEATURE and doc FileTag's can be used to collect files in a hierarchy. This function collects the files into this hierarchy. """ dict = {} def add_to_dict( feature, file ): if not SCons.Util.is_List( feature ): feature = [ feature ] for f in feature: if f not in dict: dict[ f ] = [ file ] else: dict[ f ].append( file ) for file in files: if hasattr( file, 'PACKAGING_X_MSI_FEATURE' ): add_to_dict(file.PACKAGING_X_MSI_FEATURE, file) elif hasattr( file, 'PACKAGING_DOC' ): add_to_dict( 'PACKAGING_DOC', file ) else: add_to_dict( 'default', file ) return dict def generate_guids(root): """ generates globally unique identifiers for parts of the xml which need them. Component tags have a special requirement. Their UUID is only allowed to change if the list of their contained resources has changed. This allows for clean removal and proper updates. To handle this requirement, the uuid is generated with an md5 hashing the whole subtree of a xml node. """ from hashlib import md5 # specify which tags need a guid and in which attribute this should be stored. needs_id = { 'Product' : 'Id', 'Package' : 'Id', 'Component' : 'Guid', } # find all XMl nodes matching the key, retrieve their attribute, hash their # subtree, convert hash to string and add as a attribute to the xml node. for (key,value) in needs_id.items(): node_list = root.getElementsByTagName(key) attribute = value for node in node_list: hash = md5(node.toxml()).hexdigest() hash_str = '%s-%s-%s-%s-%s' % ( hash[:8], hash[8:12], hash[12:16], hash[16:20], hash[20:] ) node.attributes[attribute] = hash_str def string_wxsfile(target, source, env): return "building WiX file %s"%( target[0].path ) def build_wxsfile(target, source, env): """ compiles a .wxs file from the keywords given in env['msi_spec'] and by analyzing the tree of source nodes and their tags. """ file = open(target[0].abspath, 'w') try: # Create a document with the Wix root tag doc = Document() root = doc.createElement( 'Wix' ) root.attributes['xmlns']='http://schemas.microsoft.com/wix/2003/01/wi' doc.appendChild( root ) filename_set = [] # this is to circumvent duplicates in the shortnames id_set = {} # this is to circumvent duplicates in the ids # Create the content build_wxsfile_header_section(root, env) build_wxsfile_file_section(root, source, env['NAME'], env['VERSION'], env['VENDOR'], filename_set, id_set) generate_guids(root) build_wxsfile_features_section(root, source, env['NAME'], env['VERSION'], env['SUMMARY'], id_set) build_wxsfile_default_gui(root) build_license_file(target[0].get_dir(), env) # write the xml to a file file.write( doc.toprettyxml() ) # call a user specified function if 'CHANGE_SPECFILE' in env: env['CHANGE_SPECFILE'](target, source) except KeyError, e: raise SCons.Errors.UserError( '"%s" package field for MSI is missing.' % e.args[0] ) # # setup function # def create_default_directory_layout(root, NAME, VERSION, VENDOR, filename_set): """ Create the wix default target directory layout and return the innermost directory. We assume that the XML tree delivered in the root argument already contains the Product tag. Everything is put under the PFiles directory property defined by WiX. After that a directory with the 'VENDOR' tag is placed and then a directory with the name of the project and its VERSION. This leads to the following TARGET Directory Layout: C:\<PFiles>\<Vendor>\<Projectname-Version>\ Example: C:\Programme\Company\Product-1.2\ """ doc = Document() d1 = doc.createElement( 'Directory' ) d1.attributes['Id'] = 'TARGETDIR' d1.attributes['Name'] = 'SourceDir' d2 = doc.createElement( 'Directory' ) d2.attributes['Id'] = 'ProgramFilesFolder' d2.attributes['Name'] = 'PFiles' d3 = doc.createElement( 'Directory' ) d3.attributes['Id'] = 'VENDOR_folder' d3.attributes['Name'] = escape( gen_dos_short_file_name( VENDOR, filename_set ) ) d3.attributes['LongName'] = escape( VENDOR ) d4 = doc.createElement( 'Directory' ) project_folder = "%s-%s" % ( NAME, VERSION ) d4.attributes['Id'] = 'MY_DEFAULT_FOLDER' d4.attributes['Name'] = escape( gen_dos_short_file_name( project_folder, filename_set ) ) d4.attributes['LongName'] = escape( project_folder ) d1.childNodes.append( d2 ) d2.childNodes.append( d3 ) d3.childNodes.append( d4 ) root.getElementsByTagName('Product')[0].childNodes.append( d1 ) return d4 # # mandatory and optional file tags # def build_wxsfile_file_section(root, files, NAME, VERSION, VENDOR, filename_set, id_set): """ builds the Component sections of the wxs file with their included files. Files need to be specified in 8.3 format and in the long name format, long filenames will be converted automatically. Features are specficied with the 'X_MSI_FEATURE' or 'DOC' FileTag. """ root = create_default_directory_layout( root, NAME, VERSION, VENDOR, filename_set ) components = create_feature_dict( files ) factory = Document() def get_directory( node, dir ): """ returns the node under the given node representing the directory. Returns the component node if dir is None or empty. """ if dir == '' or not dir: return node Directory = node dir_parts = dir.split(os.path.sep) # to make sure that our directory ids are unique, the parent folders are # consecutively added to upper_dir upper_dir = '' # walk down the xml tree finding parts of the directory dir_parts = [d for d in dir_parts if d != ''] for d in dir_parts[:]: already_created = [c for c in Directory.childNodes if c.nodeName == 'Directory' and c.attributes['LongName'].value == escape(d)] if already_created != []: Directory = already_created[0] dir_parts.remove(d) upper_dir += d else: break for d in dir_parts: nDirectory = factory.createElement( 'Directory' ) nDirectory.attributes['LongName'] = escape( d ) nDirectory.attributes['Name'] = escape( gen_dos_short_file_name( d, filename_set ) ) upper_dir += d nDirectory.attributes['Id'] = convert_to_id( upper_dir, id_set ) Directory.childNodes.append( nDirectory ) Directory = nDirectory return Directory for file in files: drive, path = os.path.splitdrive( file.PACKAGING_INSTALL_LOCATION ) filename = os.path.basename( path ) dirname = os.path.dirname( path ) h = { # tagname : default value 'PACKAGING_X_MSI_VITAL' : 'yes', 'PACKAGING_X_MSI_FILEID' : convert_to_id(filename, id_set), 'PACKAGING_X_MSI_LONGNAME' : filename, 'PACKAGING_X_MSI_SHORTNAME' : gen_dos_short_file_name(filename, filename_set), 'PACKAGING_X_MSI_SOURCE' : file.get_path(), } # fill in the default tags given above. for k,v in [ (k, v) for (k,v) in h.items() if not hasattr(file, k) ]: setattr( file, k, v ) File = factory.createElement( 'File' ) File.attributes['LongName'] = escape( file.PACKAGING_X_MSI_LONGNAME ) File.attributes['Name'] = escape( file.PACKAGING_X_MSI_SHORTNAME ) File.attributes['Source'] = escape( file.PACKAGING_X_MSI_SOURCE ) File.attributes['Id'] = escape( file.PACKAGING_X_MSI_FILEID ) File.attributes['Vital'] = escape( file.PACKAGING_X_MSI_VITAL ) # create the <Component> Tag under which this file should appear Component = factory.createElement('Component') Component.attributes['DiskId'] = '1' Component.attributes['Id'] = convert_to_id( filename, id_set ) # hang the component node under the root node and the file node # under the component node. Directory = get_directory( root, dirname ) Directory.childNodes.append( Component ) Component.childNodes.append( File ) # # additional functions # def build_wxsfile_features_section(root, files, NAME, VERSION, SUMMARY, id_set): """ This function creates the <features> tag based on the supplied xml tree. This is achieved by finding all <component>s and adding them to a default target.<|fim▁hole|> It should be called after the tree has been built completly. We assume that a MY_DEFAULT_FOLDER Property is defined in the wxs file tree. Furthermore a top-level with the name and VERSION of the software will be created. An PACKAGING_X_MSI_FEATURE can either be a string, where the feature DESCRIPTION will be the same as its title or a Tuple, where the first part will be its title and the second its DESCRIPTION. """ factory = Document() Feature = factory.createElement('Feature') Feature.attributes['Id'] = 'complete' Feature.attributes['ConfigurableDirectory'] = 'MY_DEFAULT_FOLDER' Feature.attributes['Level'] = '1' Feature.attributes['Title'] = escape( '%s %s' % (NAME, VERSION) ) Feature.attributes['Description'] = escape( SUMMARY ) Feature.attributes['Display'] = 'expand' for (feature, files) in create_feature_dict(files).items(): SubFeature = factory.createElement('Feature') SubFeature.attributes['Level'] = '1' if SCons.Util.is_Tuple(feature): SubFeature.attributes['Id'] = convert_to_id( feature[0], id_set ) SubFeature.attributes['Title'] = escape(feature[0]) SubFeature.attributes['Description'] = escape(feature[1]) else: SubFeature.attributes['Id'] = convert_to_id( feature, id_set ) if feature=='default': SubFeature.attributes['Description'] = 'Main Part' SubFeature.attributes['Title'] = 'Main Part' elif feature=='PACKAGING_DOC': SubFeature.attributes['Description'] = 'Documentation' SubFeature.attributes['Title'] = 'Documentation' else: SubFeature.attributes['Description'] = escape(feature) SubFeature.attributes['Title'] = escape(feature) # build the componentrefs. As one of the design decision is that every # file is also a component we walk the list of files and create a # reference. for f in files: ComponentRef = factory.createElement('ComponentRef') ComponentRef.attributes['Id'] = convert_to_id( os.path.basename(f.get_path()), id_set ) SubFeature.childNodes.append(ComponentRef) Feature.childNodes.append(SubFeature) root.getElementsByTagName('Product')[0].childNodes.append(Feature) def build_wxsfile_default_gui(root): """ this function adds a default GUI to the wxs file """ factory = Document() Product = root.getElementsByTagName('Product')[0] UIRef = factory.createElement('UIRef') UIRef.attributes['Id'] = 'WixUI_Mondo' Product.childNodes.append(UIRef) UIRef = factory.createElement('UIRef') UIRef.attributes['Id'] = 'WixUI_ErrorProgressText' Product.childNodes.append(UIRef) def build_license_file(directory, spec): """ creates a License.rtf file with the content of "X_MSI_LICENSE_TEXT" in the given directory """ name, text = '', '' try: name = spec['LICENSE'] text = spec['X_MSI_LICENSE_TEXT'] except KeyError: pass # ignore this as X_MSI_LICENSE_TEXT is optional if name!='' or text!='': file = open( os.path.join(directory.get_path(), 'License.rtf'), 'w' ) file.write('{\\rtf') if text!='': file.write(text.replace('\n', '\\par ')) else: file.write(name+'\\par\\par') file.write('}') file.close() # # mandatory and optional package tags # def build_wxsfile_header_section(root, spec): """ Adds the xml file node which define the package meta-data. """ # Create the needed DOM nodes and add them at the correct position in the tree. factory = Document() Product = factory.createElement( 'Product' ) Package = factory.createElement( 'Package' ) root.childNodes.append( Product ) Product.childNodes.append( Package ) # set "mandatory" default values if 'X_MSI_LANGUAGE' not in spec: spec['X_MSI_LANGUAGE'] = '1033' # select english # mandatory sections, will throw a KeyError if the tag is not available Product.attributes['Name'] = escape( spec['NAME'] ) Product.attributes['Version'] = escape( spec['VERSION'] ) Product.attributes['Manufacturer'] = escape( spec['VENDOR'] ) Product.attributes['Language'] = escape( spec['X_MSI_LANGUAGE'] ) Package.attributes['Description'] = escape( spec['SUMMARY'] ) # now the optional tags, for which we avoid the KeyErrror exception if 'DESCRIPTION' in spec: Package.attributes['Comments'] = escape( spec['DESCRIPTION'] ) if 'X_MSI_UPGRADE_CODE' in spec: Package.attributes['X_MSI_UPGRADE_CODE'] = escape( spec['X_MSI_UPGRADE_CODE'] ) # We hardcode the media tag as our current model cannot handle it. Media = factory.createElement('Media') Media.attributes['Id'] = '1' Media.attributes['Cabinet'] = 'default.cab' Media.attributes['EmbedCab'] = 'yes' root.getElementsByTagName('Product')[0].childNodes.append(Media) # this builder is the entry-point for .wxs file compiler. wxs_builder = Builder( action = Action( build_wxsfile, string_wxsfile ), ensure_suffix = '.wxs' ) def package(env, target, source, PACKAGEROOT, NAME, VERSION, DESCRIPTION, SUMMARY, VENDOR, X_MSI_LANGUAGE, **kw): # make sure that the Wix Builder is in the environment SCons.Tool.Tool('wix').generate(env) # get put the keywords for the specfile compiler. These are the arguments # given to the package function and all optional ones stored in kw, minus # the the source, target and env one. loc = locals() del loc['kw'] kw.update(loc) del kw['source'], kw['target'], kw['env'] # strip the install builder from the source files target, source = stripinstallbuilder(target, source, env) # put the arguments into the env and call the specfile builder. env['msi_spec'] = kw specfile = wxs_builder(* [env, target, source], **kw) # now call the WiX Tool with the built specfile added as a source. msifile = env.WiX(target, specfile) # return the target and source tuple. return (msifile, source+[specfile]) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:<|fim▁end|>
<|file_name|>styles.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright © 2014-2018 GWHAT Project Contributors # https://github.com/jnsebgosselin/gwhat # # This file is part of GWHAT (Ground-Water Hydrograph Analysis Toolbox). # Licensed under the terms of the GNU General Public License. # Standard library imports : import platform # Third party imports : from PyQt5.QtGui import QIcon, QFont, QFontDatabase from PyQt5.QtCore import QSize class StyleDB(object): def __init__(self): # ---- frame self.frame = 22 self.HLine = 52 self.VLine = 53 self.sideBarWidth = 275 # ----- colors self.red = '#C83737' self.lightgray = '#E6E6E6' self.rain = '#0000CC' self.snow = '0.7' self.wlvl = '#0000CC' # '#000099' if platform.system() == 'Windows': self.font1 = QFont('Segoe UI', 11) # Calibri, Cambria self.font_console = QFont('Segoe UI', 9) self.font_menubar = QFont('Segoe UI', 10) elif platform.system() == 'Linux': self.font1 = QFont('Ubuntu', 11) self.font_console = QFont('Ubuntu', 9) self.font_menubar = QFont('Ubuntu', 10) <|fim▁hole|> if platform.system() == 'Windows': self.fontfamily = "Segoe UI" # "Cambria" #"Calibri" #"Segoe UI"" elif platform.system() == 'Linux': self.fontfamily = "Ubuntu" # self.fontSize1.setPointSize(11) # 17 = QtGui.QFrame.Box | QtGui.QFrame.Plain # 22 = QtGui.QFrame.StyledPanel | QtGui.QFrame.Plain # 20 = QtGui.QFrame.HLine | QtGui.QFrame.Plain # 52 = QtGui.QFrame.HLine | QtGui.QFrame.Sunken # 53 = QtGui.QFrame.VLine | QtGui.QFrame.Sunken<|fim▁end|>
# database = QFontDatabase() # print database.families()
<|file_name|>index.ts<|end_file_name|><|fim▁begin|>export * from "./assignment_service_to_authorization_group"; export * from "./authorization_check_field"; export * from "./authorization_group"; export * from "./authorization_object_class"; export * from "./authorization_object"; export * from "./behavior_definition"; export * from "./bsp_application"; export * from "./business_add_in_implementation"; export * from "./business_configuration_set"; export * from "./business_object_model"; export * from "./cds_metadata_extension"; export * from "./chapter_of_book_structure"; export * from "./checkpoint_group"; export * from "./class"; export * from "./classification"; export * from "./composite_enhancement_implementation"; export * from "./customizing_img_activity"; export * from "./customizing_transaction"; export * from "./data_control"; export * from "./data_definition"; export * from "./data_element"; export * from "./dialog_module"; export * from "./documentation"; export * from "./domain"; export * from "./ecatt_test_data_container"; export * from "./enhancement_implementation"; export * from "./enhancement_spot"; export * from "./extension_index"; export * from "./form_object_form"; export * from "./form_object_interface"; export * from "./function_group"; export * from "./gateway_model_metadata"; export * from "./gateway_model"; export * from "./gateway_project"; export * from "./gateway_service_groups_metadata"; export * from "./gateway_service"; export * from "./gateway_vocabulary_annotation"; export * from "./general_hierarchy_storage_extrension_name"; export * from "./general_storage_structure"; export * from "./general_text"; export * from "./icf_service"; export * from "./idoc_extension"; export * from "./idoc"; export * from "./interface"; export * from "./lock_object"; export * from "./maintenance_and_transport_object"; export * from "./message_class"; export * from "./messaging_channel"; export * from "./mime_object"; export * from "./number_range"; export * from "./object_characteristic"; export * from "./package_interface"; export * from "./package"; export * from "./parameter"; export * from "./program"; export * from "./proxy_object"; export * from "./push_channel"; export * from "./rfc_service"; export * from "./sapscript"; export * from "./search_help"; export * from "./service_definition"; export * from "./shared_memory"; export * from "./smart_form"; export * from "./smart_style"; export * from "./table_type"; export * from "./table"; export * from "./transaction"; export * from "./transformation"; export * from "./type_pool"; export * from "./view_cluster";<|fim▁hole|>export * from "./view"; export * from "./virtual_end_point"; export * from "./web_dynpro_application_configuration"; export * from "./web_dynpro_application"; export * from "./web_dynpro_component_configuration"; export * from "./web_dynpro_component"; export * from "./web_mime";<|fim▁end|>
<|file_name|>bootstrap.test.js<|end_file_name|><|fim▁begin|>/** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ /* eslint-disable max-nested-callbacks */ define([ 'jquery', 'mage/backend/bootstrap' ], function ($) { 'use strict'; describe('mage/backend/bootstrap', function () { var $pageMainActions; beforeEach(function () { $pageMainActions = $('<div class="page-main-actions"></div>'); }); afterEach(function () { $pageMainActions.remove(); }); describe('"sendPostponeRequest" method', function () { it('should insert "Error" notification if request failed', function () { $pageMainActions.appendTo('body'); $('body').notification(); $.ajaxSettings.error(); expect($('.message-error').length).toBe(1); expect( $('body:contains("A technical problem with the server created an error")').length<|fim▁hole|> }); });<|fim▁end|>
).toBe(1); }); });
<|file_name|>twoview.cpp<|end_file_name|><|fim▁begin|>///////////////////////////////////////////////////////////////////////////////// // // Multilayer Feature Graph (MFG), version 1.0 // Copyright (C) 2011-2015 Yan Lu, Dezhen Song // Netbot Laboratory, Texas A&M University, USA // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // ///////////////////////////////////////////////////////////////////////////////// /******************************************************************************** * Estimate rotation/translation between two views ********************************************************************************/ #include <iostream> #include <opencv2/highgui/highgui.hpp> #include <opencv2/calib3d/calib3d.hpp> // replaced with: #ifdef __APPLE__ #include <GLUT/glut.h> #include <OpenGL/gl.h> #elif __linux__ #include <GL/glut.h> #include <GL/gl.h> #else #include <gl/glut.h> #include <gl/gl.h> #endif #include <math.h> #include <fstream> #include "utils.h" #include "consts.h" #include "mfgutils.h" #include "levmar.h" #include "view.h" #include "features2d.h" #include "features3d.h" using namespace std; struct Data_optimizeRt_withVP { vector<vector<cv::Point2d>> pointPairs; cv::Mat K; vector<vector<cv::Mat>> vpPairs; double weightVP; }; void costFun_optimizeRt_withVP(double *p, double *error, int N, int M, void *adata) // M measurement size // N para size { struct Data_optimizeRt_withVP *dptr = (struct Data_optimizeRt_withVP *) adata; Eigen::Quaterniond q(p[0], p[1], p[2], p[3]); q.normalize(); cv::Mat R = (cv::Mat_<double>(3, 3) << q.matrix()(0, 0), q.matrix()(0, 1), q.matrix()(0, 2), q.matrix()(1, 0), q.matrix()(1, 1), q.matrix()(1, 2), q.matrix()(2, 0), q.matrix()(2, 1), q.matrix()(2, 2)); double t_norm = sqrt(p[4] * p[4] + p[5] * p[5] + p[6] * p[6]); p[4] = p[4] / t_norm; p[5] = p[5] / t_norm; p[6] = p[6] / t_norm; cv::Mat t = (cv::Mat_<double>(3, 1) << p[4], p[5], p[6]); cv::Mat K = dptr->K; double weightVp = dptr->weightVP; double cost = 0; int errEndIdx = 0; cv::Mat F = K.t().inv() * (vec2SkewMat(t) * R) * K.inv(); for (int i = 0; i < dptr->pointPairs.size(); ++i, ++errEndIdx) { error[errEndIdx] = sqrt(fund_samperr(cvpt2mat(dptr->pointPairs[i][0]), cvpt2mat(dptr->pointPairs[i][1]), F)); cost += error[errEndIdx] * error[errEndIdx]; } for (int i = 0; i < dptr->vpPairs.size(); ++i, ++errEndIdx) { cv::Mat vp1 = K.inv() * dptr->vpPairs[i][0]; cv::Mat vp2 = R.t() * K.inv() * dptr->vpPairs[i][1]; vp1 = vp1 / cv::norm(vp1); vp2 = vp2 / cv::norm(vp2); error[errEndIdx] = cv::norm(vp1.cross(vp2)) * weightVp; cost = cost + error[errEndIdx] * error[errEndIdx]; } // cout<<cost<<'\t'; } void optimizeRt_withVP(cv::Mat K, vector<vector<cv::Mat>> vppairs, double weightVP, vector<vector<cv::Point2d>> &featPtMatches, cv::Mat R, cv::Mat t) // optimize relative pose (from 5-point alg) using vanishing point correspondences // input: K, vppairs, featPtMatches // output: R, t { int numMeasure = vppairs.size() + featPtMatches.size(); double *measurement = new double[numMeasure]; for (int i = 0; i < numMeasure; ++i) measurement[i] = 0; double opts[LM_OPTS_SZ], info[LM_INFO_SZ]; opts[0] = LM_INIT_MU; // opts[1] = 1E-15; opts[2] = 1E-50; // original 1e-50 opts[3] = 1E-20; opts[4] = -LM_DIFF_DELTA; int maxIter = 5000; Eigen::Matrix3d Rx; Rx << R.at<double>(0, 0), R.at<double>(0, 1), R.at<double>(0, 2), R.at<double>(1, 0), R.at<double>(1, 1), R.at<double>(1, 2), R.at<double>(2, 0), R.at<double>(2, 1), R.at<double>(2, 2); Eigen::Quaterniond q(Rx); int numPara = 7 ; double *para = new double[numPara]; para[0] = q.w(); para[1] = q.x(); para[2] = q.y(); para[3] = q.z(); para[4] = t.at<double>(0); para[5] = t.at<double>(1); para[6] = t.at<double>(2); // --- pass additional data --- Data_optimizeRt_withVP data; data.pointPairs = featPtMatches; data.K = K; data.vpPairs = vppairs; data.weightVP = weightVP; int ret = dlevmar_dif(costFun_optimizeRt_withVP, para, measurement, numPara, numMeasure, maxIter, opts, info, NULL, NULL, (void *)&data); delete[] measurement; q.w() = para[0]; q.x() = para[1]; q.y() = para[2]; q.z() = para[3]; q.normalize(); for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) R.at<double>(i, j) = q.matrix()(i, j); t.at<double>(0) = para[4]; t.at<double>(1) = para[5]; t.at<double>(2) = para[6]; } struct Data_optimize_t_givenR { vector<vector<cv::Point2d>> pointPairs; cv::Mat K, R; }; void costFun_optimize_t_givenR(double *p, double *error, int N, int M, void *adata) // M measurement size // N para size { struct Data_optimize_t_givenR *dptr = (struct Data_optimize_t_givenR *) adata; cv::Mat R = dptr->R; double t_norm = sqrt(p[0] * p[0] + p[1] * p[1] + p[2] * p[2]); p[0] = p[0] / t_norm; p[1] = p[1] / t_norm; p[2] = p[2] / t_norm; cv::Mat t = (cv::Mat_<double>(3, 1) << p[0], p[1], p[2]); cv::Mat K = dptr->K; double cost = 0; int errEndIdx = 0; cv::Mat F = K.t().inv() * (vec2SkewMat(t) * R) * K.inv(); for (int i = 0; i < dptr->pointPairs.size(); ++i, ++errEndIdx) { error[errEndIdx] = sqrt(fund_samperr(cvpt2mat(dptr->pointPairs[i][0]), cvpt2mat(dptr->pointPairs[i][1]), F)); cost += error[errEndIdx] * error[errEndIdx]; } cout << cost << '\t'; } void optimize_t_givenR(cv::Mat K, cv::Mat R, vector<vector<cv::Point2d>> &featPtMatches, cv::Mat t) // optimize relative pose (from 5-point alg) using vanishing point correspondences // input: K, R, vppairs, featPtMatches // output: t { int numMeasure = featPtMatches.size(); double *measurement = new double[numMeasure]; for (int i = 0; i < numMeasure; ++i) measurement[i] = 0; double opts[LM_OPTS_SZ], info[LM_INFO_SZ]; opts[0] = LM_INIT_MU; //<|fim▁hole|> int maxIter = 1000; int numPara = 3; double *para = new double[numPara]; para[0] = t.at<double>(0); para[1] = t.at<double>(1); para[2] = t.at<double>(2); // --- pass additional data --- Data_optimize_t_givenR data; data.pointPairs = featPtMatches; data.K = K; data.R = R; int ret = dlevmar_dif(costFun_optimize_t_givenR, para, measurement, numPara, numMeasure, maxIter, opts, info, NULL, NULL, (void *)&data); delete[] measurement; t.at<double>(0) = para[0]; t.at<double>(1) = para[1]; t.at<double>(2) = para[2]; }<|fim▁end|>
opts[1] = 1E-15; opts[2] = 1E-50; // original 1e-50 opts[3] = 1E-20; opts[4] = -LM_DIFF_DELTA;
<|file_name|>linq-vsdoc.js<|end_file_name|><|fim▁begin|>/*-------------------------------------------------------------------------- * linq-vsdoc.js - LINQ for JavaScript * ver 2.2.0.2 (Jan. 21th, 2011) * * created and maintained by neuecc <[email protected]> * licensed under Microsoft Public License(Ms-PL) * http://neue.cc/ * http://linqjs.codeplex.com/ *--------------------------------------------------------------------------*/ Enumerable = (function () { var Enumerable = function (getEnumerator) { this.GetEnumerator = getEnumerator; } Enumerable.Choice = function (Params_Contents) { /// <summary>Random choice from arguments. /// Ex: Choice(1,2,3) - 1,3,2,3,3,2,1...</summary> /// <param type="T" name="Params_Contents" parameterArray="true">Array or Params Contents</param> /// <returns type="Enumerable"></returns> } Enumerable.Cycle = function (Params_Contents) { /// <summary>Cycle Repeat from arguments. /// Ex: Cycle(1,2,3) - 1,2,3,1,2,3,1,2,3...</summary> /// <param type="T" name="Params_Contents" parameterArray="true">Array or Params Contents</param> /// <returns type="Enumerable"></returns> } Enumerable.Empty = function () { /// <summary>Returns an empty Enumerable.</summary> /// <returns type="Enumerable"></returns> } Enumerable.From = function (obj) { /// <summary> /// Make Enumerable from obj. /// 1. null = Enumerable.Empty(). /// 2. Enumerable = Enumerable. /// 3. Number/Boolean = Enumerable.Repeat(obj, 1). /// 4. String = to CharArray.(Ex:"abc" => "a","b","c"). /// 5. Object/Function = to KeyValuePair(except function) Ex:"{a:0}" => (.Key=a, .Value=0). /// 6. Array or ArrayLikeObject(has length) = to Enumerable. /// 7. JScript's IEnumerable = to Enumerable(using Enumerator). /// </summary> /// <param name="obj">object</param> /// <returns type="Enumerable"></returns> } Enumerable.Return = function (element) { /// <summary>Make one sequence. This equals Repeat(element, 1)</summary> /// <param name="element">element</param> /// <returns type="Enumerable"></returns> } Enumerable.Matches = function (input, pattern, flags) { /// <summary>Global regex match and send regexp object. /// Ex: Matches((.)z,"0z1z2z") - $[1] => 0,1,2</summary> /// <param type="String" name="input">input string</param> /// <param type="RegExp/String" name="pattern">RegExp or Pattern string</param> /// <param type="Optional:String" name="flags" optional="true">If pattern is String then can use regexp flags "i" or "m" or "im"</param> /// <returns type="Enumerable"></returns> } Enumerable.Range = function (start, count, step) { /// <summary>Generates a sequence of integral numbers within a specified range. /// Ex: Range(1,5) - 1,2,3,4,5</summary> /// <param type="Number" integer="true" name="start">The value of the first integer in the sequence.</param> /// <param type="Number" integer="true" name="count">The number of sequential integers to generate.</param> /// <param type="Optional:Number" integer="true" name="step" optional="true">Step of generate number.(Ex:Range(0,3,5) - 0,5,10)</param> /// <returns type="Enumerable"></returns> } Enumerable.RangeDown = function (start, count, step) { /// <summary>Generates a sequence of integral numbers within a specified range. /// Ex: RangeDown(5,5) - 5,4,3,2,1</summary> /// <param type="Number" integer="true" name="start">The value of the first integer in the sequence.</param> /// <param type="Number" integer="true" name="count">The number of sequential integers to generate.</param> /// <param type="Optional:Number" integer="true" name="step" optional="true">Step of generate number.(Ex:RangeDown(0,3,5) - 0,-5,-10)</param> /// <returns type="Enumerable"></returns> } Enumerable.RangeTo = function (start, to, step) { /// <summary>Generates a sequence of integral numbers. /// Ex: RangeTo(10,12) - 10,11,12 RangeTo(0,-2) - 0, -1, -2</summary> /// <param type="Number" integer="true" name="start">start integer</param> /// <param type="Number" integer="true" name="to">to integer</param> /// <param type="Optional:Number" integer="true" name="step" optional="true">Step of generate number.(Ex:RangeTo(0,7,3) - 0,3,6)</param> /// <returns type="Enumerable"></returns> } Enumerable.Repeat = function (obj, count) { /// <summary>Generates a sequence that contains one repeated value. /// If omit count then generate to infinity. /// Ex: Repeat("foo",3) - "foo","foo","foo"</summary> /// <param type="TResult" name="obj">The value to be repeated.</param> /// <param type="Optional:Number" integer="true" name="count" optional="true">The number of times to repeat the value in the generated sequence.</param> /// <returns type="Enumerable"></returns> } Enumerable.RepeatWithFinalize = function (initializer, finalizer) { /// <summary>Lazy Generates one value by initializer's result and do finalize when enumerate end</summary> /// <param type="Func&lt;T>" name="initializer">value factory.</param> /// <param type="Action&lt;T>" name="finalizer">execute when finalize.</param> /// <returns type="Enumerable"></returns> } Enumerable.Generate = function (func, count) { /// <summary>Generates a sequence that execute func value. /// If omit count then generate to infinity. /// Ex: Generate("Math.random()", 5) - 0.131341,0.95425252,...</summary> /// <param type="Func&lt;T>" name="func">The value of execute func to be repeated.</param> /// <param type="Optional:Number" integer="true" name="count" optional="true">The number of times to repeat the value in the generated sequence.</param> /// <returns type="Enumerable"></returns> } Enumerable.ToInfinity = function (start, step) { /// <summary>Generates a sequence of integral numbers to infinity. /// Ex: ToInfinity() - 0,1,2,3...</summary> /// <param type="Optional:Number" integer="true" name="start" optional="true">start integer</param> /// <param type="Optional:Number" integer="true" name="step" optional="true">Step of generate number.(Ex:ToInfinity(10,3) - 10,13,16,19,...)</param> /// <returns type="Enumerable"></returns> } Enumerable.ToNegativeInfinity = function (start, step) { /// <summary>Generates a sequence of integral numbers to negative infinity. /// Ex: ToNegativeInfinity() - 0,-1,-2,-3...</summary> /// <param type="Optional:Number" integer="true" name="start" optional="true">start integer</param> /// <param type="Optional:Number" integer="true" name="step" optional="true">Step of generate number.(Ex:ToNegativeInfinity(10,3) - 10,7,4,1,...)</param> /// <returns type="Enumerable"></returns> } Enumerable.Unfold = function (seed, func) { /// <summary>Applies function and generates a infinity sequence. /// Ex: Unfold(3,"$+10") - 3,13,23,...</summary> /// <param type="T" name="seed">The initial accumulator value.</param> /// <param type="Func&lt;T,T>" name="func">An accumulator function to be invoked on each element.</param> /// <returns type="Enumerable"></returns> } Enumerable.prototype = { /* Projection and Filtering Methods */ CascadeBreadthFirst: function (func, resultSelector) { /// <summary>Projects each element of sequence and flattens the resulting sequences into one sequence use breadth first search.</summary> /// <param name="func" type="Func&lt;T,T[]>">Select child sequence.</param> /// <param name="resultSelector" type="Optional:Func&lt;T>_or_Func&lt;T,int>" optional="true">Optional:the second parameter of the function represents the nestlevel of the source sequence.</param> /// <returns type="Enumerable"></returns> }, CascadeDepthFirst: function (func, resultSelector) { /// <summary>Projects each element of sequence and flattens the resulting sequences into one sequence use depth first search.</summary> /// <param name="func" type="Func&lt;T,T[]>">Select child sequence.</param> /// <param name="resultSelector" type="Optional:Func&lt;T>_or_Func&lt;T,int>" optional="true">Optional:the second parameter of the function represents the nestlevel of the source sequence.</param> /// <returns type="Enumerable"></returns> }, Flatten: function () { /// <summary>Flatten sequences into one sequence.</summary> /// <returns type="Enumerable"></returns> }, Pairwise: function (selector) { /// <summary>Projects current and next element of a sequence into a new form.</summary> /// <param type="Func&lt;TSource,TSource,TResult>" name="selector">A transform function to apply to current and next element.</param> /// <returns type="Enumerable"></returns> }, Scan: function (func_or_seed, func, resultSelector) { /// <summary>Applies an accumulator function over a sequence.</summary> /// <param name="func_or_seed" type="Func&lt;T,T,T>_or_TAccumulate">Func is an accumulator function to be invoked on each element. Seed is the initial accumulator value.</param> /// <param name="func" type="Optional:Func&lt;TAccumulate,T,TAccumulate>" optional="true">An accumulator function to be invoked on each element.</param> /// <param name="resultSelector" type="Optional:Func&lt;TAccumulate,TResult>" optional="true">A function to transform the final accumulator value into the result value.</param> /// <returns type="Enumerable"></returns> }, Select: function (selector) { /// <summary>Projects each element of a sequence into a new form.</summary> /// <param name="selector" type="Func&lt;T,T>_or_Func&lt;T,int,T>">A transform function to apply to each source element; Optional:the second parameter of the function represents the index of the source element.</param> /// <returns type="Enumerable"></returns> }, SelectMany: function (collectionSelector, resultSelector) { /// <summary>Projects each element of a sequence and flattens the resulting sequences into one sequence.</summary> /// <param name="collectionSelector" type="Func&lt;T,TCollection[]>_or_Func&lt;T,int,TCollection[]>">A transform function to apply to each source element; Optional:the second parameter of the function represents the index of the source element.</param> /// <param name="resultSelector" type="Optional:Func&lt;T,TCollection,TResult>" optional="true">Optional:A transform function to apply to each element of the intermediate sequence.</param> /// <returns type="Enumerable"></returns> }, Where: function (predicate) { /// <summary>Filters a sequence of values based on a predicate.</summary> /// <param name="predicate" type="Func&lt;T,bool>_or_Func&lt;T,int,bool>">A function to test each source element for a condition; Optional:the second parameter of the function represents the index of the source element.</param> /// <returns type="Enumerable"></returns> }, OfType: function (type) { /// <summary>Filters the elements based on a specified type.</summary> /// <param name="type" type="T">The type to filter the elements of the sequence on.</param> /// <returns type="Enumerable"></returns> }, Zip: function (second, selector) { /// <summary>Merges two sequences by using the specified predicate function.</summary> /// <param name="second" type="T[]">The second sequence to merge.</param> /// <param name="selector" type="Func&lt;TFirst,TSecond,TResult>_or_Func&lt;TFirst,TSecond,int,TResult>">A function that specifies how to merge the elements from the two sequences. Optional:the third parameter of the function represents the index of the source element.</param> /// <returns type="Enumerable"></returns> }, /* Join Methods */ Join: function (inner, outerKeySelector, innerKeySelector, resultSelector, compareSelector) { /// <summary>Correlates the elements of two sequences based on matching keys.</summary> /// <param name="inner" type="T[]">The sequence to join to the first sequence.</param> /// <param name="outerKeySelector" type="Func&lt;TOuter,TKey>">A function to extract the join key from each element of the first sequence.</param> /// <param name="innerKeySelector" type="Func&lt;TInner,TKey>">A function to extract the join key from each element of the second sequence.</param> /// <param name="resultSelector" type="Func&lt;TOuter,TInner,TResult>">A function to create a result element from two matching elements.</param> /// <param name="compareSelector" type="Optional:Func&lt;TKey,TCompare>" optional="true">An equality comparer to compare values.</param> /// <returns type="Enumerable"></returns> }, GroupJoin: function (inner, outerKeySelector, innerKeySelector, resultSelector, compareSelector) { /// <summary>Correlates the elements of two sequences based on equality of keys and groups the results.</summary> /// <param name="inner" type="T[]">The sequence to join to the first sequence.</param> /// <param name="outerKeySelector" type="Func&lt;TOuter>">A function to extract the join key from each element of the first sequence.</param> /// <param name="innerKeySelector" type="Func&lt;TInner>">A function to extract the join key from each element of the second sequence.</param> /// <param name="resultSelector" type="Func&lt;TOuter,Enumerable&lt;TInner>,TResult">A function to create a result element from an element from the first sequence and a collection of matching elements from the second sequence.</param> /// <param name="compareSelector" type="Optional:Func&lt;TKey,TCompare>" optional="true">An equality comparer to compare values.</param> /// <returns type="Enumerable"></returns> }, /* Set Methods */ All: function (predicate) { /// <summary>Determines whether all elements of a sequence satisfy a condition.</summary> /// <param type="Func&lt;T,bool>" name="predicate">A function to test each element for a condition.</param> /// <returns type="Boolean"></returns> }, Any: function (predicate) { /// <summary>Determines whether a sequence contains any elements or any element of a sequence satisfies a condition.</summary> /// <param name="predicate" type="Optional:Func&lt;T,bool>" optional="true">A function to test each element for a condition.</param> /// <returns type="Boolean"></returns> }, Concat: function (second) { /// <summary>Concatenates two sequences.</summary> /// <param name="second" type="T[]">The sequence to concatenate to the first sequence.</param> /// <returns type="Enumerable"></returns> }, Insert: function (index, second) { /// <summary>Merge two sequences.</summary> /// <param name="index" type="Number" integer="true">The index of insert start position.</param> /// <param name="second" type="T[]">The sequence to concatenate to the first sequence.</param> /// <returns type="Enumerable"></returns> }, Alternate: function (value) { /// <summary>Insert value to between sequence.</summary> /// <param name="value" type="T">The value of insert.</param> /// <returns type="Enumerable"></returns> }, // Overload:function(value) // Overload:function(value, compareSelector) Contains: function (value, compareSelector) { /// <summary>Determines whether a sequence contains a specified element.</summary> /// <param name="value" type="T">The value to locate in the sequence.</param> /// <param name="compareSelector" type="Optional:Func&lt;T,TKey>" optional="true">An equality comparer to compare values.</param> /// <returns type="Boolean"></returns> }, DefaultIfEmpty: function (defaultValue) { /// <summary>Returns the elements of the specified sequence or the specified value in a singleton collection if the sequence is empty.</summary> /// <param name="defaultValue" type="T">The value to return if the sequence is empty.</param> /// <returns type="Enumerable"></returns> }, Distinct: function (compareSelector) { /// <summary>Returns distinct elements from a sequence.</summary> /// <param name="compareSelector" type="Optional:Func&lt;T,TKey>" optional="true">An equality comparer to compare values.</param> /// <returns type="Enumerable"></returns> }, Except: function (second, compareSelector) { /// <summary>Produces the set difference of two sequences.</summary> /// <param name="second" type="T[]">An T[] whose Elements that also occur in the first sequence will cause those elements to be removed from the returned sequence.</param> /// <param name="compareSelector" type="Optional:Func&lt;T,TKey>" optional="true">An equality comparer to compare values.</param><|fim▁hole|> /// <returns type="Enumerable"></returns> }, Intersect: function (second, compareSelector) { /// <summary>Produces the set difference of two sequences.</summary> /// <param name="second" type="T[]">An T[] whose distinct elements that also appear in the first sequence will be returned.</param> /// <param name="compareSelector" type="Optional:Func&lt;T,TKey>" optional="true">An equality comparer to compare values.</param> /// <returns type="Enumerable"></returns> }, SequenceEqual: function (second, compareSelector) { /// <summary>Determines whether two sequences are equal by comparing the elements.</summary> /// <param name="second" type="T[]">An T[] to compare to the first sequence.</param> /// <param name="compareSelector" type="Optional:Func&lt;T,TKey>" optional="true">An equality comparer to compare values.</param> /// <returns type="Enumerable"></returns> }, Union: function (second, compareSelector) { /// <summary>Produces the union of two sequences.</summary> /// <param name="second" type="T[]">An T[] whose distinct elements form the second set for the union.</param> /// <param name="compareSelector" type="Optional:Func&lt;T,TKey>" optional="true">An equality comparer to compare values.</param> /// <returns type="Enumerable"></returns> }, /* Ordering Methods */ OrderBy: function (keySelector) { /// <summary>Sorts the elements of a sequence in ascending order according to a key.</summary> /// <param name="keySelector" type="Optional:Func&lt;T,TKey>">A function to extract a key from an element.</param> return new OrderedEnumerable(); }, OrderByDescending: function (keySelector) { /// <summary>Sorts the elements of a sequence in descending order according to a key.</summary> /// <param name="keySelector" type="Optional:Func&lt;T,TKey>">A function to extract a key from an element.</param> return new OrderedEnumerable(); }, Reverse: function () { /// <summary>Inverts the order of the elements in a sequence.</summary> /// <returns type="Enumerable"></returns> }, Shuffle: function () { /// <summary>Shuffle sequence.</summary> /// <returns type="Enumerable"></returns> }, /* Grouping Methods */ GroupBy: function (keySelector, elementSelector, resultSelector, compareSelector) { /// <summary>Groups the elements of a sequence according to a specified key selector function.</summary> /// <param name="keySelector" type="Func&lt;T,TKey>">A function to extract the key for each element.</param> /// <param name="elementSelector" type="Optional:Func&lt;T,TElement>">A function to map each source element to an element in an Grouping&lt;TKey, TElement>.</param> /// <param name="resultSelector" type="Optional:Func&lt;TKey,Enumerable&lt;TElement>,TResult>">A function to create a result value from each group.</param> /// <param name="compareSelector" type="Optional:Func&lt;TKey,TCompare>" optional="true">An equality comparer to compare values.</param> /// <returns type="Enumerable"></returns> }, PartitionBy: function (keySelector, elementSelector, resultSelector, compareSelector) { /// <summary>Create Group by continuation key.</summary> /// <param name="keySelector" type="Func&lt;T,TKey>">A function to extract the key for each element.</param> /// <param name="elementSelector" type="Optional:Func&lt;T,TElement>">A function to map each source element to an element in an Grouping&lt;TKey, TElement>.</param> /// <param name="resultSelector" type="Optional:Func&lt;TKey,Enumerable&lt;TElement>,TResult>">A function to create a result value from each group.</param> /// <param name="compareSelector" type="Optional:Func&lt;TKey,TCompare>" optional="true">An equality comparer to compare values.</param> /// <returns type="Enumerable"></returns> }, BufferWithCount: function (count) { /// <summary>Divide by count</summary> /// <param name="count" type="Number" integer="true">integer</param> /// <returns type="Enumerable"></returns> }, /* Aggregate Methods */ Aggregate: function (func_or_seed, func, resultSelector) { /// <summary>Applies an accumulator function over a sequence.</summary> /// <param name="func_or_seed" type="Func&lt;T,T,T>_or_TAccumulate">Func is an accumulator function to be invoked on each element. Seed is the initial accumulator value.</param> /// <param name="func" type="Optional:Func&lt;TAccumulate,T,TAccumulate>" optional="true">An accumulator function to be invoked on each element.</param> /// <param name="resultSelector" type="Optional:Func&lt;TAccumulate,TResult>" optional="true">A function to transform the final accumulator value into the result value.</param> /// <returns type="TResult"></returns> }, Average: function (selector) { /// <summary>Computes the average of a sequence.</summary> /// <param name="selector" type="Optional:Func&lt;T,Number>" optional="true">A transform function to apply to each element.</param> /// <returns type="Number"></returns> }, Count: function (predicate) { /// <summary>Returns the number of elements in a sequence.</summary> /// <param name="predicate" type="Optional:Func&lt;T,Boolean>" optional="true">A function to test each element for a condition.</param> /// <returns type="Number"></returns> }, Max: function (selector) { /// <summary>Returns the maximum value in a sequence</summary> /// <param name="selector" type="Optional:Func&lt;T,TKey>" optional="true">A transform function to apply to each element.</param> /// <returns type="Number"></returns> }, Min: function (selector) { /// <summary>Returns the minimum value in a sequence</summary> /// <param name="selector" type="Optional:Func&lt;T,TKey>" optional="true">A transform function to apply to each element.</param> /// <returns type="Number"></returns> }, MaxBy: function (keySelector) { /// <summary>Returns the maximum value in a sequence by keySelector</summary> /// <param name="keySelector" type="Func&lt;T,TKey>">A compare selector of element.</param> /// <returns type="T"></returns> }, MinBy: function (keySelector) { /// <summary>Returns the minimum value in a sequence by keySelector</summary> /// <param name="keySelector" type="Func&lt;T,TKey>">A compare selector of element.</param> /// <returns type="T"></returns> }, Sum: function (selector) { /// <summary>Computes the sum of a sequence of values.</summary> /// <param name="selector" type="Optional:Func&lt;T,TKey>" optional="true">A transform function to apply to each element.</param> /// <returns type="Number"></returns> }, /* Paging Methods */ ElementAt: function (index) { /// <summary>Returns the element at a specified index in a sequence.</summary> /// <param name="index" type="Number" integer="true">The zero-based index of the element to retrieve.</param> /// <returns type="T"></returns> }, ElementAtOrDefault: function (index, defaultValue) { /// <summary>Returns the element at a specified index in a sequence or a default value if the index is out of range.</summary> /// <param name="index" type="Number" integer="true">The zero-based index of the element to retrieve.</param> /// <param name="defaultValue" type="T">The value if the index is outside the bounds then send.</param> /// <returns type="T"></returns> }, First: function (predicate) { /// <summary>Returns the first element of a sequence.</summary> /// <param name="predicate" type="Optional:Func&lt;T,Boolean>">A function to test each element for a condition.</param> /// <returns type="T"></returns> }, FirstOrDefault: function (defaultValue, predicate) { /// <summary>Returns the first element of a sequence, or a default value.</summary> /// <param name="defaultValue" type="T">The value if not found then send.</param> /// <param name="predicate" type="Optional:Func&lt;T,Boolean>">A function to test each element for a condition.</param> /// <returns type="T"></returns> }, Last: function (predicate) { /// <summary>Returns the last element of a sequence.</summary> /// <param name="predicate" type="Optional:Func&lt;T,Boolean>">A function to test each element for a condition.</param> /// <returns type="T"></returns> }, LastOrDefault: function (defaultValue, predicate) { /// <summary>Returns the last element of a sequence, or a default value.</summary> /// <param name="defaultValue" type="T">The value if not found then send.</param> /// <param name="predicate" type="Optional:Func&lt;T,Boolean>">A function to test each element for a condition.</param> /// <returns type="T"></returns> }, Single: function (predicate) { /// <summary>Returns the only element of a sequence that satisfies a specified condition, and throws an exception if more than one such element exists.</summary> /// <param name="predicate" type="Optional:Func&lt;T,Boolean>">A function to test each element for a condition.</param> /// <returns type="T"></returns> }, SingleOrDefault: function (defaultValue, predicate) { /// <summary>Returns a single, specific element of a sequence of values, or a default value if no such element is found.</summary> /// <param name="defaultValue" type="T">The value if not found then send.</param> /// <param name="predicate" type="Optional:Func&lt;T,Boolean>">A function to test each element for a condition.</param> /// <returns type="T"></returns> }, Skip: function (count) { /// <summary>Bypasses a specified number of elements in a sequence and then returns the remaining elements.</summary> /// <param name="count" type="Number" integer="true">The number of elements to skip before returning the remaining elements.</param> /// <returns type="Enumerable"></returns> }, SkipWhile: function (predicate) { /// <summary>Bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements.</summary> /// <param name="predicate" type="Func&lt;T,Boolean>_or_Func&lt;T,int,Boolean>">A function to test each source element for a condition; Optional:the second parameter of the function represents the index of the source element.</param> /// <returns type="Enumerable"></returns> }, Take: function (count) { /// <summary>Returns a specified number of contiguous elements from the start of a sequence.</summary> /// <param name="count" type="Number" integer="true">The number of elements to return.</param> /// <returns type="Enumerable"></returns> }, TakeWhile: function (predicate) { /// <summary>Returns elements from a sequence as long as a specified condition is true, and then skips the remaining elements.</summary> /// <param name="predicate" type="Func&lt;T,Boolean>_or_Func&lt;T,int,Boolean>">A function to test each source element for a condition; Optional:the second parameter of the function represents the index of the source element.</param> /// <returns type="Enumerable"></returns> }, TakeExceptLast: function (count) { /// <summary>Take a sequence except last count.</summary> /// <param name="count" type="Optional:Number" integer="true">The number of skip count.</param> /// <returns type="Enumerable"></returns> }, TakeFromLast: function (count) { /// <summary>Take a sequence from last count.</summary> /// <param name="count" type="Number" integer="true">The number of take count.</param> /// <returns type="Enumerable"></returns> }, IndexOf: function (item) { /// <summary>Returns the zero-based index of the flrst occurrence of a value.</summary> /// <param name="item" type="T">The zero-based starting index of the search.</param> /// <returns type="Number" integer="true"></returns> }, LastIndexOf: function (item) { /// <summary>Returns the zero-based index of the last occurrence of a value.</summary> /// <param name="item" type="T">The zero-based starting index of the search.</param> /// <returns type="Number" integer="true"></returns> }, /* Convert Methods */ ToArray: function () { /// <summary>Creates an array from this sequence.</summary> /// <returns type="Array"></returns> }, ToLookup: function (keySelector, elementSelector, compareSelector) { /// <summary>Creates a Lookup from this sequence.</summary> /// <param name="keySelector" type="Func&lt;T,TKey>">A function to extract a key from each element.</param> /// <param name="elementSelector" type="Optional:Func&lt;T,TElement>">A transform function to produce a result element value from each element.</param> /// <param name="compareSelector" type="Optional:Func&lt;TKey,TCompare>" optional="true">An equality comparer to compare values.</param> return new Lookup(); }, ToObject: function (keySelector, elementSelector) { /// <summary>Creates a Object from this sequence.</summary> /// <param name="keySelector" type="Func&lt;T,String>">A function to extract a key from each element.</param> /// <param name="elementSelector" type="Func&lt;T,TElement>">A transform function to produce a result element value from each element.</param> /// <returns type="Object"></returns> }, ToDictionary: function (keySelector, elementSelector, compareSelector) { /// <summary>Creates a Dictionary from this sequence.</summary> /// <param name="keySelector" type="Func&lt;T,TKey>">A function to extract a key from each element.</param> /// <param name="elementSelector" type="Func&lt;T,TElement>">A transform function to produce a result element value from each element.</param> /// <param name="compareSelector" type="Optional:Func&lt;TKey,TCompare>" optional="true">An equality comparer to compare values.</param> return new Dictionary(); }, // Overload:function() // Overload:function(replacer) // Overload:function(replacer, space) ToJSON: function (replacer, space) { /// <summary>Creates a JSON String from sequence, performed only native JSON support browser or included json2.js.</summary> /// <param name="replacer" type="Optional:Func">a replacer.</param> /// <param name="space" type="Optional:Number">indent spaces.</param> /// <returns type="String"></returns> }, // Overload:function() // Overload:function(separator) // Overload:function(separator,selector) ToString: function (separator, selector) { /// <summary>Creates Joined string from this sequence.</summary> /// <param name="separator" type="Optional:String">A String.</param> /// <param name="selector" type="Optional:Func&lt;T,String>">A transform function to apply to each source element.</param> /// <returns type="String"></returns> }, /* Action Methods */ Do: function (action) { /// <summary>Performs the specified action on each element of the sequence.</summary> /// <param name="action" type="Action&lt;T>_or_Action&lt;T,int>">Optional:the second parameter of the function represents the index of the source element.</param> /// <returns type="Enumerable"></returns> }, ForEach: function (action) { /// <summary>Performs the specified action on each element of the sequence.</summary> /// <param name="action" type="Action&lt;T>_or_Action&lt;T,int>">[return true;]continue iteration.[return false;]break iteration. Optional:the second parameter of the function represents the index of the source element.</param> /// <returns type="void"></returns> }, Write: function (separator, selector) { /// <summary>Do document.write.</summary> /// <param name="separator" type="Optional:String">A String.</param> /// <param name="selector" type="Optional:Func&lt;T,String>">A transform function to apply to each source element.</param> /// <returns type="void"></returns> }, WriteLine: function (selector) { /// <summary>Do document.write + &lt;br />.</summary> /// <param name="selector" type="Optional:Func&lt;T,String>">A transform function to apply to each source element.</param> /// <returns type="void"></returns> }, Force: function () { /// <summary>Execute enumerate.</summary> /// <returns type="void"></returns> }, /* Functional Methods */ Let: function (func) { /// <summary>Bind the source to the parameter so that it can be used multiple times.</summary> /// <param name="func" type="Func&lt;Enumerable&lt;T>,Enumerable&lt;TR>>">apply function.</param> /// <returns type="Enumerable"></returns> }, Share: function () { /// <summary>Shares cursor of all enumerators to the sequence.</summary> /// <returns type="Enumerable"></returns> }, MemoizeAll: function () { /// <summary>Creates an enumerable that enumerates the original enumerable only once and caches its results.</summary> /// <returns type="Enumerable"></returns> }, /* Error Handling Methods */ Catch: function (handler) { /// <summary>catch error and do handler.</summary> /// <param name="handler" type="Action&lt;Error>">execute if error occured.</param> /// <returns type="Enumerable"></returns> }, Finally: function (finallyAction) { /// <summary>do action if enumerate end or disposed or error occured.</summary> /// <param name="handler" type="Action">finally execute.</param> /// <returns type="Enumerable"></returns> }, /* For Debug Methods */ Trace: function (message, selector) { /// <summary>Trace object use console.log.</summary> /// <param name="message" type="Optional:String">Default is 'Trace:'.</param> /// <param name="selector" type="Optional:Func&lt;T,String>">A transform function to apply to each source element.</param> /// <returns type="Enumerable"></returns> } } // vsdoc-dummy Enumerable.prototype.GetEnumerator = function () { /// <summary>Returns an enumerator that iterates through the collection.</summary> return new IEnumerator(); } var IEnumerator = function () { } IEnumerator.prototype.Current = function () { /// <summary>Gets the element in the collection at the current position of the enumerator.</summary> /// <returns type="T"></returns> } IEnumerator.prototype.MoveNext = function () { /// <summary>Advances the enumerator to the next element of the collection.</summary> /// <returns type="Boolean"></returns> } IEnumerator.prototype.Dispose = function () { /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary> /// <returns type="Void"></returns> } var Dictionary = function () { } Dictionary.prototype = { Add: function (key, value) { /// <summary>add new pair. if duplicate key then overwrite new value.</summary> /// <returns type="Void"></returns> }, Get: function (key) { /// <summary>get value. if not find key then return undefined.</summary> /// <returns type="T"></returns> }, Set: function (key, value) { /// <summary>set value. if complete set value then return true, not find key then return false.</summary> /// <returns type="Boolean"></returns> }, Contains: function (key) { /// <summary>check contains key.</summary> /// <returns type="Boolean"></returns> }, Clear: function () { /// <summary>clear dictionary.</summary> /// <returns type="Void"></returns> }, Remove: function (key) { /// <summary>remove key and value.</summary> /// <returns type="Void"></returns> }, Count: function () { /// <summary>contains value's count.</summary> /// <returns type="Number"></returns> }, ToEnumerable: function () { /// <summary>Convert to Enumerable&lt;{Key:, Value:}&gt;.</summary> /// <returns type="Enumerable"></returns> } } var Lookup = function () { } Lookup.prototype = { Count: function () { /// <summary>contains value's count.</summary> /// <returns type="Number"></returns> }, Get: function (key) { /// <summary>get grouped enumerable.</summary> /// <returns type="Enumerable"></returns> }, Contains: function (key) { /// <summary>check contains key.</summary> /// <returns type="Boolean"></returns> }, ToEnumerable: function () { /// <summary>Convert to Enumerable&lt;Grouping&gt;.</summary> /// <returns type="Enumerable"></returns> } } var Grouping = function () { } Grouping.prototype = new Enumerable(); Grouping.prototype.Key = function () { /// <summary>get grouping key.</summary> /// <returns type="T"></returns> } var OrderedEnumerable = function () { } OrderedEnumerable.prototype = new Enumerable(); OrderedEnumerable.prototype.ThenBy = function (keySelector) { /// <summary>Performs a subsequent ordering of the elements in a sequence in ascending order according to a key.</summary> /// <param name="keySelector" type="Func&lt;T,TKey>">A function to extract a key from each element.</param> return Enumerable.Empty().OrderBy(); } OrderedEnumerable.prototype.ThenByDescending = function (keySelector) { /// <summary>Performs a subsequent ordering of the elements in a sequence in descending order, according to a key.</summary> /// <param name="keySelector" type="Func&lt;T,TKey>">A function to extract a key from each element.</param> return Enumerable.Empty().OrderBy(); } return Enumerable; })()<|fim▁end|>
<|file_name|>appmonitor.py<|end_file_name|><|fim▁begin|>"""TBD """ import os import sys import time import subprocess import xmlrpc.client class ApplicationMonitor(object): """Responsible for launching, monitoring, and terminating the FLDIGI application process, using subprocess.Popen() :param hostname: The FLDIGI XML-RPC server's IP address or hostname (usually localhost / 127.0.0.1) :type hostname: str (path to folder) :param port: The port in which FLDIGI's XML-RPC server is listening on. :type port: int .. note:: Commandline arguments can be found on the following links: * `Official Documentation page <http://www.w1hkj.com/FldigiHelp-3.21/html/command_line_switches_page.html/>`_ * `Man page for FLDIGI <https://www.dragonflybsd.org/cgi/web-man?command=fldigi&section=1/>`_ """ def __init__(self, hostname='127.0.0.1', port=7362): self.platform = sys.platform self.hostname = hostname self.port = int(port) if self.platform not in ['linux', 'win32', 'darwin']: raise Exception('You\'re probably using an OS that is unsupported. Sorry about that. I take pull requests.') self.client = xmlrpc.client.ServerProxy('http://{}:{}/'.format(self.hostname, self.port)) self.process = None def start(self, headless=False, wfall_only=False): """Start fldigi in the background :param headless: if True, starts the FLDIGI application in headless mode (POSIX only! Doesn't work in Windows) :type headless: bool :param wfall_only: If True, start FLDIGI in 'waterfall-only' mode. (POSIX only! Doesn't work in Windows) :type wfall_only: bool :Example: >>> import pyfldigi >>> c = pyfldigi.Client() >>> app = pyfldigi.ApplicationMonitor(headless=True) >>> app.start() >>> # At this point, fldigi should be running in headless mode. >>> c.modem.name # Ask FLDIGI which modem it's currently using 'CW' """ args = [self._get_path()] if self.platform == 'win32': # Currently, the app crashes if I pass in any params from the windows commandline. # For now just ignore all of the params if running this under windows. pass else:<|fim▁hole|> if headless is True: if self.platform == 'win32': raise Exception('cannot run headless with win32. Headless mode is only supported on Linux.') else: # Assumes cygwin, linux, and darwin can utilize xvfb to create a fake x server args.insert(0, 'xvfb-run') # http://manpages.ubuntu.com/manpages/zesty/man1/xvfb-run.1.html args.append('-display') args.append(':99') else: if wfall_only is True: # consider this modal with 'headless' args.append('--wfall-only') # args.extend(['-title', 'fldigi']) # Set the title to something predictable. self.process = subprocess.Popen(args) start = time.time() while(1): try: if self.client.fldigi.name() == 'fldigi': break except ConnectionRefusedError: pass if time.time() - start >= 10: break time.sleep(0.5) def stop(self, save_options=True, save_log=True, save_macros=True, force=True): """Attempts to gracefully shut down fldigi. Returns the error code. :Example: >>> import pyfldigi >>> app = pyfldigi.ApplicationMonitor() >>> app.start() >>> time.sleep(10) # wait a bit >>> app.stop() """ bitmask = int('0b{}{}{}'.format(int(save_macros), int(save_log), int(save_options)), 0) self.client.fldigi.terminate(bitmask) if self.process is not None: error_code = self.process.wait(timeout=2) if force is True: if error_code is None: self.process.terminate() # attempt to terminate error_code = self.process.wait(timeout=2) if error_code is None: error_code = self.process.kill() self.process = None return error_code def kill(self): """Kills fldigi. .. warning:: Please try and use stop() before doing this to shut down fldigi gracefully. Consider kill() the last resort. :Example: >>> import pyfldigi >>> app = pyfldigi.ApplicationMonitor() >>> app.start() >>> time.sleep(10) # wait a bit >>> app.kill() # kill the process """ if self.process is not None: self.process.kill() self.process = None # TODO: Interpret error codes and raise custom exceptions def _get_path(self): if self.platform == 'win32': # Below is a clever way to return a list of fldigi versions. This would fail if the user # did not install fldigi into Program Files. fldigi_versions = [d for d in os.listdir(os.environ["ProgramFiles(x86)"]) if 'fldigi' in d.lower()] if len(fldigi_versions) == 0: raise FileNotFoundError('Cannot find the path to fldigi. Is it installed?') elif len(fldigi_versions) == 1: path = os.path.join(os.environ["ProgramFiles(x86)"], fldigi_versions[0]) # Check to see if fldigi.exe is in the folder if 'fldigi.exe' in os.listdir(path): return os.path.join(path, 'fldigi.exe') else: raise Exception('Found more than one version of fldigi. Uninstall one.') else: # Assume all other OS's are smart enough to place fldigi in PATH return 'fldigi' def is_running(self): """Uses the python subprocess module object to see if FLDIGI is still running. .. warning:: If the AppMonitor did not start FLDIGI, then this function will not return True. The method only works if FLDIGI was launched using start(). :return: Returns whether or not the FLDIGI application is running :rtype: bool """ if self.process is None: return False else: p = self.process.poll() # will return None if not yet finished. Will return the exit code if it has finished. if p is None: return False else: self.returncode = p if __name__ == '__main__': a = ApplicationMonitor() a.start() for i in range(0, 5): print(a.is_running()) time.sleep(1) errorCode = a.stop() print(errorCode)<|fim▁end|>
args.extend(['--arq-server-address', self.hostname]) args.extend(['--arq-server-port', str(self.port)])
<|file_name|>settings.js<|end_file_name|><|fim▁begin|>'use strict'; /** * app settings factory * stores the custom user settings and shares it app wide */ var app = angular.module('istart'); app.factory('appSettings', ['$q', '$rootScope',function ($q, $rootScope) { /** * migrate the old settings from istart 1.x to the * istartV2! * @type {{loaded: null, settingsDefault: {background: {imageadd: boolean, cssadd: boolean, css: string, image: string}}, config: null, save: save, loadOptions: loadOptions, background: background}} */ //if(localStorage.istartbackground) var settings = { loaded:null, backgroundSizeOptions: ['cover', 'initial'], backgroundRepeatOptions: ['no-repeat', 'repeat'], settingsDefault : { background: { imageadd:false, cssadd:false, css: '', image:'', options:null, backgroundSize: 'cover', backgroundRepeat: 'no-repeat' }, mouseWheel: { active:true }, globalsearch: { active:false }, updateCenter: { show:false, version:"2.0.1.60" }, header: { alternative:false, menuIconColor:'rgba(0, 0, 0, 0.87)', menuDimension: { w:30, h:30 } } }, config:null, save : function() { try { chrome.storage.local.set({'options': JSON.stringify(settings.config)}, function( ){ }); } catch(e) { console.error(e); } }, loadOptions : function() { var defer = $q.defer(); chrome.storage.local.get('options', function(settingsRaw) { var settingsArr=null; if(typeof settingsRaw.options == "undefined") { //first run save init config settings.config=settings.settingsDefault; settings.loaded=true; settings.save(); defer.resolve(); return; } try { settingsArr = JSON.parse(settingsRaw.options); console.log(settingsArr); settings.config=settingsArr; settings.loaded=true; defer.resolve(); } catch(e) { } }); return defer.promise; }, setBackgroundImage: function(bgImage) { settings.config.background.imageadd=true; settings.config.background.image=bgImage; settings.save(); }, setBackgroundSize: function(backgroundSize) { settings.config.background.backgroundSize = backgroundSize; settings.save(); $rootScope.$broadcast('changeBackground'); }, setBackgroundRepeat: function(backgroundRepeat) { settings.config.background.backgroundRepeat = backgroundRepeat; settings.save(); $rootScope.$broadcast('changeBackground'); }, setmouseWheelActive: function(activeState) { if(typeof settings.config.mouseWheel !== "undefined") { settings.config.mouseWheel.active=activeState; } else { settings.config.mouseWheel = { active: activeState }; } settings.save(); $rootScope.$broadcast('mouseWheelSettingsChanged', {}); }, checkSettingsLoaded: function() { var defer = $q.defer(); if(settings.loaded==null) { //console.log(localStorage.istartbackground, 'BACKGROUND SETTINGS', localStorage.istartbackground!="null", localStorage.istartbackground!==null); if(localStorage.istartbackground!="null") { settings.loadV1BackgroundSettings(); } //nothing loaded load the settings settings.loadOptions() .then(function() { defer.resolve(true); }) } else { defer.resolve(true); } return defer.promise; }, updateCenter: function() { var defer = $q.defer(); this.checkSettingsLoaded().then( function() { if(typeof settings.config.updateCenter !== "undefined") { defer.resolve(settings.config.updateCenter); } else { /** * if the settings are not present than this version didnt has the * updated settings object! So we add simply true to this object * and resolve it */ defer.resolve(settings.settingsDefault.updateCenter); } }); return defer.promise; }, setUpdateCenter: function(show, versionString) { if(typeof settings.config.updateCenter !== "undefined") { settings.config.updateCenter.show=show; settings.config.updateCenter.version=versionString; } else { settings.config.updateCenter = { show: show, version: versionString }; } settings.save(); //$rootScope.$broadcast('globalsearchSettingsChanged', {}); }, setGlobalSearch: function(activeState) { if(typeof settings.config.globalsearch !== "undefined") { settings.config.globalsearch.active=activeState; } else { settings.config.globalsearch = { active: activeState }; } settings.save(); $rootScope.$broadcast('globalsearchSettingsChanged', {}); }, globalSearch: function() { var defer = $q.defer(); this.checkSettingsLoaded().then( function() { if(typeof settings.config.globalsearch !== "undefined") { defer.resolve(settings.config.globalsearch); } else { /** * if the settings are not present than this version didnt has the * updated settings object! So we add simply true to this object * and resolve it */ defer.resolve(settings.settingsDefault.globalsearch); } }); return defer.promise; }, ensureHeaderConfigExists: function() { if(typeof settings.config.header == "undefined") { settings.config.header = settings.settingsDefault.header; } }, setHeaderAlternative: function(alternativeState) { settings.ensureHeaderConfigExists(); settings.config.header.alternative = alternativeState; settings.save(); $rootScope.$broadcast('globalHeaderChanged'); }, setMenuIconColor: function(color) { settings.ensureHeaderConfigExists(); settings.config.header.menuIconColor=color; settings.save(); $rootScope.$broadcast('globalHeaderChanged'); }, setMenuDimension: function(dimsObject) { settings.ensureHeaderConfigExists(); settings.config.header.menuDimension=dimsObject; settings.save(); $rootScope.$broadcast('globalHeaderChanged'); }, setHeader: function(headerConfigObject) { settings.config.header = headerConfigObject; settings.save(); $rootScope.$broadcast('globalHeaderChanged'); //we need an relaod, this works with an ng-if! }, header: function() { var defer = $q.defer(); this.checkSettingsLoaded().then( function() { if(typeof settings.config.header !== "undefined") { defer.resolve(settings.config.header); } else { /** * if the settings are not present than this version didnt has the * updated settings object! So we add simply true to this object * and resolve it */ defer.resolve(settings.settingsDefault.header); } }); return defer.promise; }, mouseWheel: function() { var defer = $q.defer(); this.checkSettingsLoaded().then( function() { if(typeof settings.config.mouseWheel !== "undefined") { defer.resolve(settings.config.mouseWheel); } else { /** * if the settings are not present than this version didnt has the * updated settings object! So we add simply true to this object * and resolve it */ defer.resolve(settings.settingsDefault.mouseWheel);<|fim▁hole|> background : function() { var deferr = $q.defer(); var resolveBackground = function() { if(typeof settings.config.background !== "undefined") { deferr.resolve(settings.config.background); } else { deferr.reject(settings.config.background); } }; if(settings.loaded==null) { //console.log(localStorage.istartbackground, 'BACKGROUND SETTINGS', localStorage.istartbackground!="null", localStorage.istartbackground!==null); if(localStorage.istartbackground!="null") { settings.loadV1BackgroundSettings(); } //nothing loaded load the settings settings.loadOptions() .then(function() { resolveBackground(); }) } else { resolveBackground(); } return deferr.promise; }, loadV1BackgroundSettings: function() { /** * migrate here the old Settings into the new settingsFormat. * clear the old settings directly after setting them into * the new format of V2 */ var bgsetting; var bgoptions; console.log(localStorage.istartbackground); if(localStorage.istartbackground != "null" && typeof localStorage.istartbackground != "undefined") { if(settings.config==null) { settings.config = settings.settingsDefault; } bgsetting = localStorage.istartbackground; /** * check if this is an image or color: */ if(bgsetting.indexOf('url(')!=-1) { //image ! settings.config.background.imageadd=true; settings.config.background.image = bgsetting;//the complete string? } else{ //css gradient settings.config.background.imageadd=false; settings.config.background.cssadd=true; settings.config.background.css = bgsetting; settings.save();//store the new things } } //load additional settings if(localStorage.istartbgoptions != null) { if(settings.config==null) { settings.config = settings.settingsDefault; } bgoptions = JSON.parse(localStorage.istartbgoptions); settings.config.background.options = bgoptions; settings.save();//store the new things } //todo:implement load functions to load the background from options //$('#mbg').css('backgroundImage', this.bgsetting ); localStorage.istartbackground=null; localStorage.istartbgoptions=null; /*if(this.bgoptions != null) { this.setBgOptionsFromObj(); }*/ }, setBgOptionsFromObj: function () { /** * TODO:replace this into the backGroundSettings * directive */ for(var option in this.bgoptions) { var cso = option; if(option == 'backgroundattachment') { cso = 'background-attachment'; } $('#mbg').css(cso, this.bgoptions[option] ); } } }; /** * returns the current apps list! */ return { settings:settings } }]);<|fim▁end|>
} }); return defer.promise; },
<|file_name|>TranslationTool.js<|end_file_name|><|fim▁begin|>Potree.TranslationTool = function(camera) { THREE.Object3D.call( this ); var scope = this; this.camera = camera; this.geometry = new THREE.Geometry(); this.material = new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } ); this.STATE = {<|fim▁hole|> DEFAULT: 0, TRANSLATE_X: 1, TRANSLATE_Y: 2, TRANSLATE_Z: 3 }; this.parts = { ARROW_X : {name: "arrow_x", object: undefined, color: new THREE.Color( 0xff0000 ), state: this.STATE.TRANSLATE_X}, ARROW_Y : {name: "arrow_y", object: undefined, color: new THREE.Color( 0x00ff00 ), state: this.STATE.TRANSLATE_Y}, ARROW_Z : {name: "arrow_z", object: undefined, color: new THREE.Color( 0x0000ff ), state: this.STATE.TRANSLATE_Z} } this.translateStart; this.state = this.STATE.DEFAULT; this.highlighted; this.targets; this.build = function(){ var arrowX = scope.createArrow(scope.parts.ARROW_X, scope.parts.ARROW_X.color); arrowX.rotation.z = -Math.PI/2; var arrowY = scope.createArrow(scope.parts.ARROW_Y, scope.parts.ARROW_Y.color); var arrowZ = scope.createArrow(scope.parts.ARROW_Z, scope.parts.ARROW_Z.color); arrowZ.rotation.x = -Math.PI/2; scope.add(arrowX); scope.add(arrowY); scope.add(arrowZ); var boxXY = scope.createBox(new THREE.Color( 0xffff00 )); boxXY.scale.z = 0.02; boxXY.position.set(0.5, 0.5, 0); var boxXZ = scope.createBox(new THREE.Color( 0xff00ff )); boxXZ.scale.y = 0.02; boxXZ.position.set(0.5, 0, -0.5); var boxYZ = scope.createBox(new THREE.Color( 0x00ffff )); boxYZ.scale.x = 0.02; boxYZ.position.set(0, 0.5, -0.5); scope.add(boxXY); scope.add(boxXZ); scope.add(boxYZ); scope.parts.ARROW_X.object = arrowX; scope.parts.ARROW_Y.object = arrowY; scope.parts.ARROW_Z.object = arrowZ; scope.scale.multiplyScalar(5); }; this.createBox = function(color){ var boxGeometry = new THREE.BoxGeometry(1, 1, 1); var boxMaterial = new THREE.MeshBasicMaterial({color: color, transparent: true, opacity: 0.5}); var box = new THREE.Mesh(boxGeometry, boxMaterial); return box; }; this.createArrow = function(partID, color){ var material = new THREE.MeshBasicMaterial({color: color}); var shaftGeometry = new THREE.CylinderGeometry(0.1, 0.1, 3, 10, 1, false); var shaftMatterial = material; var shaft = new THREE.Mesh(shaftGeometry, shaftMatterial); shaft.position.y = 1.5; var headGeometry = new THREE.CylinderGeometry(0, 0.3, 1, 10, 1, false); var headMaterial = material; var head = new THREE.Mesh(headGeometry, headMaterial); head.position.y = 3; var arrow = new THREE.Object3D(); arrow.add(shaft); arrow.add(head); arrow.partID = partID; arrow.material = material; return arrow; }; this.setHighlighted = function(partID){ if(partID === undefined){ if(scope.highlighted){ scope.highlighted.object.material.color = scope.highlighted.color; scope.highlighted = undefined; } return; }else if(scope.highlighted !== undefined && scope.highlighted !== partID){ scope.highlighted.object.material.color = scope.highlighted.color; } scope.highlighted = partID; partID.object.material.color = new THREE.Color(0xffff00); } this.getHoveredObject = function(mouse){ var vector = new THREE.Vector3( mouse.x, mouse.y, 0.5 ); vector.unproject(scope.camera); var raycaster = new THREE.Raycaster(); raycaster.ray.set( scope.camera.position, vector.sub( scope.camera.position ).normalize() ); var intersections = raycaster.intersectObject(scope, true); if(intersections.length === 0){ scope.setHighlighted(undefined); return undefined; } var I = intersections[0]; var partID = I.object.parent.partID; return partID; } this.onMouseMove = function(event){ var mouse = event.normalizedPosition; if(scope.state === scope.STATE.DEFAULT){ scope.setHighlighted(scope.getHoveredObject(mouse)); }else if(scope.state === scope.STATE.TRANSLATE_X || scope.state === scope.STATE.TRANSLATE_Y || scope.state === scope.STATE.TRANSLATE_Z){ var origin = scope.start.lineStart.clone(); var direction = scope.start.lineEnd.clone().sub(scope.start.lineStart); direction.normalize(); var mousePoint = new THREE.Vector3(mouse.x, mouse.y); var directionDistance = new THREE.Vector3().subVectors(mousePoint, origin).dot(direction); var pointOnLine = direction.clone().multiplyScalar(directionDistance).add(origin); pointOnLine.unproject(scope.camera); var diff = pointOnLine.clone().sub(scope.position); scope.position.copy(pointOnLine); for(var i = 0; i < scope.targets.length; i++){ var target = scope.targets[0]; target.position.add(diff); } event.signal.halt(); } }; this.onMouseDown = function(event){ if(scope.state === scope.STATE.DEFAULT){ var hoveredObject = scope.getHoveredObject(event.normalizedPosition, scope.camera); if(hoveredObject){ scope.state = hoveredObject.state; var lineStart = scope.position.clone(); var lineEnd; if(scope.state === scope.STATE.TRANSLATE_X){ lineEnd = scope.position.clone(); lineEnd.x += 2; }else if(scope.state === scope.STATE.TRANSLATE_Y){ lineEnd = scope.position.clone(); lineEnd.y += 2; }else if(scope.state === scope.STATE.TRANSLATE_Z){ lineEnd = scope.position.clone(); lineEnd.z -= 2; } lineStart.project(scope.camera); lineEnd.project(scope.camera); scope.start = { mouse: event.normalizedPosition, lineStart: lineStart, lineEnd: lineEnd }; event.signal.halt(); } } }; this.onMouseUp = function(event){ scope.setHighlighted(); scope.state = scope.STATE.DEFAULT; }; this.setTargets = function(targets){ scope.targets = targets; if(scope.targets.length === 0){ return; } //TODO calculate centroid of all targets var centroid = targets[0].position.clone(); //for(var i = 0; i < targets.length; i++){ // var target = targets[i]; //} scope.position.copy(centroid); } this.build(); }; Potree.TranslationTool.prototype = Object.create( THREE.Object3D.prototype );<|fim▁end|>
<|file_name|>sha3256_3512.rs<|end_file_name|><|fim▁begin|>macro_rules! make_sha_mod { ($modname:ident, $len:expr, $keccak_new:expr) => { pub mod $modname { use self::super::super::hash_string; use tiny_keccak::{Hasher, Sha3};<|fim▁hole|> |keccak: Sha3| { let mut output = [0u8; $len]; keccak.finalize(&mut output); hash_string(&output) }); } } } make_sha_mod!(sha3256, 32, Sha3::v256); make_sha_mod!(sha3512, 64, Sha3::v512);<|fim▁end|>
hash_func!($keccak_new(), |keccak: &mut Sha3, buffer: &[u8]| keccak.update(buffer),
<|file_name|>EnableMetricTimer.java<|end_file_name|><|fim▁begin|>/** * Copyright (c) 2015-2022, Michael Yang 杨福海 ([email protected]). * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.jboot.support.metric.annotation; import java.lang.annotation.*; @Documented @Target(ElementType.METHOD) @Inherited @Retention(RetentionPolicy.RUNTIME) public @interface EnableMetricTimer { String value() default "";<|fim▁hole|> }<|fim▁end|>
<|file_name|>ExifHandler.cpp<|end_file_name|><|fim▁begin|>///////////////////////////////////////////////////////////////////////////// // Name: ExifHandler.cpp // Purpose: ExifHandler class // Author: Alex Thuering // Created: 30.12.2007 // RCS-ID: $Id: ExifHandler.cpp,v 1.1 2007/12/30 22:45:02 ntalex Exp $ // Copyright: (c) Alex Thuering // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// #include "ExifHandler.h" #include <libexif/exif-loader.h> int ExifHandler::getOrient(wxString filename) { ExifData* exifData = exif_data_new_from_file(filename.mb_str()); if (!exifData) return -1; if (!exif_content_get_entry(exifData->ifd[EXIF_IFD_EXIF], EXIF_TAG_EXIF_VERSION)) return -1; gint orient = -1; ExifEntry* entry = exif_content_get_entry(exifData->ifd[EXIF_IFD_0], EXIF_TAG_ORIENTATION);<|fim▁hole|> exif_data_unref(exifData); return (int) orient; }<|fim▁end|>
if (entry) { ExifByteOrder byteOrder = exif_data_get_byte_order(exifData); orient = exif_get_short(entry->data, byteOrder); }
<|file_name|>google_table_repl.py<|end_file_name|><|fim▁begin|><|fim▁hole|>import time import cStringIO from PIL import Image from libmproxy.protocol.http import decoded import re def request(context, flow): try: logging.debug("request") if (flow.request.pretty_host(hostheader=True).endswith("docs.google.com")): #logging.debug("Before:") #logging.debug(flow.request.content) m = re.match(r'(?P<msg_start>[\w\W]+)(?P<msg_info>\[null,\d+,[^\]]+\])(?P<msg_end>[\w\W]+)', flow.request.content) if not m: # logging.debug("Match failed") return 0 replace = (m.group('msg_start') + '[null,2, "You have been pwned!!!"]'+m.group('msg_end')) flow.request.content = replace logging.debug("Google table request was changed!") #logging.debug(flow.request.content) except Exception as e: logging.debug("CHECK CODE, IDIOT!!!!!!!!!!!") logging.debug(type(e)) logging.debug(e) def start (context, argv): logging.basicConfig(filename="log.log",level=logging.DEBUG) logging.debug("============================================\n") logging.debug(time.time()) logging.debug("Startup:\n") context.log("start")<|fim▁end|>
import logging
<|file_name|>echidna-manifester.js<|end_file_name|><|fim▁begin|>#!/usr/bin/env node 'use strict'; // Pseudo-constants: var DEFAULT_OPTIONS = { "format": "manifest" , "compactUrls": true , "includeErrors": false , "includeTypes": false }; // “Global” variables: var Nightmare = require("nightmare") , phantomjs = require("phantomjs-prebuilt") , pth = require("path") , u = require("url") , document , baseUrl , options , callback , found , failed , pending ; var dumpResult = function() { var result , i , j ; if ("manifest" === options.format) { result = ''; for (i in found) { if (options.compactUrls) result += found[i].compactUrl + '\n'; else result += i + '\n'; } if (options.includeErrors) { for (i in failed) { if (options.compactUrls) result += failed[i].compactUrl + '\n'; else result += i + '\n'; } } if (callback) { callback(result); } else { console.log(result); } } else if ("json" === options.format) { result = {ok: []}; for (i in found) { j = {}; if (options.compactUrls) j.url = found[i].compactUrl; else j.url = i; if (options.includeTypes) j.type = found[i].type; result.ok.push(j); } if (options.includeErrors) { result.error = []; for (i in failed) { j = {}; if (options.compactUrls) j.url = failed[i].compactUrl; else j.url = i; if (options.includeTypes) j.type = failed[i].type; result.error.push(j); } } if (callback) { callback(result); } else { console.log(JSON.stringify(result, null, 2)); } } else if ("plain" === options.format) { result = ''; for (i in found) { if (options.compactUrls) result += found[i].compactUrl + ' ok'; else result += i + ' ok'; if (options.includeTypes) result += ' ' + found[i].type; result += '\n'; } if (options.includeErrors) { for (i in failed) { if (options.compactUrls) result += failed[i].compactUrl + ' error'; else result += i + ' error'; if (options.includeTypes) result += ' ' + failed[i].type; result += '\n'; } } if (callback) { callback(result); } else { console.log(result); } } }; var getMetadata = function(res) { var compactUrl = u.parse(res.url).href.replace(baseUrl, '') , type = '[unknown]' ; if (res.status && 200 === res.status) { if (/text\/html?/i .test(res.contentType)) type = 'html'; else if (/text\/css/i .test(res.contentType)) type = 'css'; else if (/image\/\w+/i .test(res.contentType)) type = 'img'; else if (/(application|text)\/(javascript|js)/i.test(res.contentType)) type = 'js'; else type = 'js'; } return {compactUrl: compactUrl, type: type}; }; var processRequest = function(res) { pending ++; }; var processResult = function(res) { if (res && res.status && res.stage && 'end' === res.stage) { if (200 === res.status) { found[res.url] = getMetadata(res); pending --; } else if (404 === res.status) { failed[res.url] = getMetadata(res); pending --; } if (0 === pending) dumpResult(); } }; exports.run = function (url, opts, cb) { document = url; baseUrl = document.replace(/[^\/]*$/, ""); options = JSON.parse(JSON.stringify(DEFAULT_OPTIONS)); if (opts) { if (opts.hasOwnProperty("format")) options.format = opts.format; if (opts.hasOwnProperty("compactUrls")) options.compactUrls = opts.compactUrls; if (opts.hasOwnProperty("includeErrors")) options.includeErrors = opts.includeErrors; if (opts.hasOwnProperty("includeTypes")) options.includeTypes = opts.includeTypes; } callback = cb; found = {}; failed = {}; pending = 0; var nm = new Nightmare({ phantomPath: pth.dirname(phantomjs.path) + "/" }); nm.on("resourceRequested", processRequest); nm.on("resourceReceived", processResult); nm.on("resourceError", processResult); nm.goto(document); nm.run(); }; <|fim▁hole|>if (!module.parent) { var source = process.argv[2] , opts ; if (process.argv.length > 3) { opts = JSON.parse(process.argv[3]); } if (!source) console.error("Usage: echidna-manifester <PATH-or-URL> [OPTIONS-as-json]"); // if path is a file, make a URL from it if (!/^\w+:/.test(source)) source = "file://" + pth.join(process.cwd(), source); exports.run(source, opts); }<|fim▁end|>
// running directly
<|file_name|>reference.rs<|end_file_name|><|fim▁begin|>// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <[email protected]> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; version // 2.1 of the License. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // use std::collections::BTreeMap; use std::path::Path; use std::path::PathBuf; use std::ops::Deref; use libimagentryutil::isa::Is; use libimagentryutil::isa::IsKindHeaderPathProvider; use libimagerror::errors::Error as EM; use toml::Value; use toml::map::Map; use toml_query::read::TomlValueReadExt; use toml_query::read::TomlValueReadTypeExt; use toml_query::read::Partial; use toml_query::delete::TomlValueDeleteExt; use toml_query::insert::TomlValueInsertExt; use anyhow::Result; use anyhow::Error; use anyhow::Context; use crate::hasher::Hasher; /// A configuration of "basepath name" -> "basepath path" mappings /// /// Should be deserializeable from the configuration file right away, because we expect a /// configuration like this in the config file: /// /// ```toml /// [ref.basepathes] /// music = "/home/alice/music" /// documents = "/home/alice/doc" /// ``` /// /// for example. #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Config(BTreeMap<String, PathBuf>); impl Config { pub fn new(map: BTreeMap<String, PathBuf>) -> Self { Config(map) } } impl Deref for Config { type Target = BTreeMap<String, PathBuf>; fn deref(&self) -> &Self::Target { &self.0 } } impl<'a> Partial<'a> for Config { const LOCATION: &'static str = "ref.basepathes"; type Output = Self; } provide_kindflag_path!(pub IsRef, "ref.is_ref"); /// Fassade module /// /// This module is necessary to build a generic fassade around the "entry with a (default) hasher to /// represent the entry as a ref". /// /// The module is for code-structuring only, all types in the module are exported publicly in the /// supermodule. pub mod fassade { use std::marker::PhantomData; use libimagstore::store::Entry; use libimagentryutil::isa::Is; use anyhow::Result; use anyhow::Context; use anyhow::Error; use crate::hasher::sha1::Sha1Hasher; use crate::hasher::Hasher; use super::IsRef; pub trait RefFassade { fn is_ref(&self) -> Result<bool>; fn as_ref_with_hasher<H: Hasher>(&self) -> RefWithHasher<H>; fn as_ref_with_hasher_mut<H: Hasher>(&mut self) -> MutRefWithHasher<H>; } impl RefFassade for Entry { /// Check whether the underlying object is actually a ref fn is_ref(&self) -> Result<bool> { self.is::<IsRef>().context("Failed to check is-ref flag").map_err(Error::from) } fn as_ref_with_hasher<H: Hasher>(&self) -> RefWithHasher<H> { RefWithHasher::new(self) } fn as_ref_with_hasher_mut<H: Hasher>(&mut self) -> MutRefWithHasher<H> { MutRefWithHasher::new(self) } } pub struct RefWithHasher<'a, H: Hasher = Sha1Hasher>(pub(crate) &'a Entry, PhantomData<H>); impl<'a, H> RefWithHasher<'a, H> where H: Hasher { fn new(entry: &'a Entry) -> Self { RefWithHasher(entry, PhantomData) } } pub struct MutRefWithHasher<'a, H: Hasher = Sha1Hasher>(pub(crate) &'a mut Entry, PhantomData<H>); impl<'a, H> MutRefWithHasher<'a, H> where H: Hasher { fn new(entry: &'a mut Entry) -> Self { MutRefWithHasher(entry, PhantomData) } } } pub use self::fassade::*; pub trait Ref { /// Check whether the underlying object is actually a ref fn is_ref(&self) -> Result<bool>; fn get_path(&self, config: &Config) -> Result<PathBuf>; fn get_path_with_basepath_setting<B>(&self, config: &Config, base: B) -> Result<PathBuf> where B: AsRef<str>; fn get_relative_path(&self) -> Result<PathBuf>; /// Get the stored hash. fn get_hash(&self) -> Result<&str>; /// Check whether the referenced file still matches its hash fn hash_valid(&self, config: &Config) -> Result<bool>; } impl<'a, H: Hasher> Ref for RefWithHasher<'a, H> { /// Check whether the underlying object is actually a ref fn is_ref(&self) -> Result<bool> { self.0.is::<IsRef>().context("Failed to check is-ref flag").map_err(Error::from) } fn get_hash(&self) -> Result<&str> { let header_path = format!("ref.hash.{}", H::NAME); self.0 .get_header() .read(&header_path) .context(anyhow!("Failed to read header at '{}'", header_path)) .map_err(Error::from)? .ok_or_else(|| { Error::from(EM::EntryHeaderFieldMissing("ref.hash.<hash>")) }) .and_then(|v| { v.as_str().ok_or_else(|| { Error::from(EM::EntryHeaderTypeError2("ref.hash.<hash>", "string")) }) }) } /// Get the path of the actual file fn get_path(&self, config: &Config) -> Result<PathBuf> { let basepath_name = self.0 .get_header() .read_string("ref.basepath")? .ok_or_else(|| Error::from(EM::EntryHeaderFieldMissing("ref.basepath")))?; self.get_path_with_basepath_setting(config, basepath_name) } fn get_path_with_basepath_setting<B>(&self, config: &Config, base: B) -> Result<PathBuf> where B: AsRef<str> { let relpath = self.0 .get_header() .read_string("ref.relpath")? .map(PathBuf::from) .ok_or_else(|| Error::from(EM::EntryHeaderFieldMissing("ref.relpath")))?; get_file_path(config, base.as_ref(), relpath) } /// Get the relative path, relative to the configured basepath fn get_relative_path(&self) -> Result<PathBuf> { self.0 .get_header() .read("ref.relpath") .context("Failed to read header at 'ref.relpath'")? .ok_or_else(|| Error::from(EM::EntryHeaderFieldMissing("ref.relpath"))) .and_then(|v| { v.as_str() .ok_or_else(|| EM::EntryHeaderTypeError2("ref.relpath", "string")) .map_err(Error::from) }) .map(PathBuf::from) } fn hash_valid(&self, config: &Config) -> Result<bool> { let ref_header = self.0 .get_header() .read("ref") .context("Failed to read header at 'ref'")? .ok_or_else(|| anyhow!("Header missing at 'ref'"))?; let basepath_name = ref_header .read("basepath") .context("Failed to read header at 'ref.basepath'")? .ok_or_else(|| anyhow!("Header missing at 'ref.basepath'"))? .as_str() .ok_or_else(|| Error::from(EM::EntryHeaderTypeError2("ref.hash.<hash>", "string")))?; let path = ref_header .read("relpath") .context("Failed to read header at 'ref.relpath'")? .ok_or_else(|| anyhow!("Header missing at 'ref.relpath'"))? .as_str() .map(PathBuf::from) .ok_or_else(|| Error::from(EM::EntryHeaderTypeError2("ref.hash.<hash>", "string")))?; let file_path = get_file_path(config, basepath_name, &path)?; ref_header .read(H::NAME) .context(anyhow!("Failed to read header at 'ref.{}'", H::NAME))? .ok_or_else(|| anyhow!("Header missing at 'ref.{}'", H::NAME)) .and_then(|v| { v.as_str().ok_or_else(|| { Error::from(EM::EntryHeaderTypeError2("ref.hash.<hash>", "string")) }) }) .and_then(|hash| H::hash(file_path).map(|h| h == hash)) } } pub trait MutRef { fn remove_ref(&mut self) -> Result<()>; /// Make a ref out of a normal (non-ref) entry. /// /// If the entry is already a ref, this fails if `force` is false fn make_ref<P, Coll>(&mut self, path: P, basepath_name: Coll, config: &Config, force: bool) -> Result<()> where P: AsRef<Path>, Coll: AsRef<str>; } impl<'a, H> MutRef for MutRefWithHasher<'a, H> where H: Hasher { fn remove_ref(&mut self) -> Result<()> { debug!("Removing 'ref' header section"); { let header = self.0.get_header_mut(); trace!("header = {:?}", header); let _ = header.delete("ref.relpath").context("Removing ref.relpath")?; if let Some(hash_tbl) = header.read_mut("ref.hash")? { if let Value::Table(ref mut tbl) = hash_tbl { *tbl = Map::new(); } } let _ = header.delete("ref.hash").context("Removing ref.hash")?; let _ = header.delete("ref.basepath").context("Removing ref.basepath")?; } debug!("Removing 'ref' header marker"); self.0.remove_isflag::<IsRef>().context("Removing ref")?; let _ = self.0 .get_header_mut() .delete("ref") .context("Removing ref")?; trace!("header = {:?}", self.0.get_header()); Ok(()) } /// Make a ref out of a normal (non-ref) entry. /// /// `path` is the path to refer to, /// /// # Warning /// /// If the entry is already a ref, this fails if `force` is false /// fn make_ref<P, Coll>(&mut self, path: P, basepath_name: Coll, config: &Config, force: bool) -> Result<()> where P: AsRef<Path>, Coll: AsRef<str> { trace!("Making ref out of {:?}", self.0); trace!("Making ref with basepath name {:?}", basepath_name.as_ref()); trace!("Making ref with config {:?}", config); trace!("Making ref forced = {}", force); if self.0.get_header().read("ref.is_ref")?.is_some() && !force { debug!("Entry is already a Ref!"); Err(anyhow!("Entry is already a reference")).context("Making ref out of entry")?; } let file_path = get_file_path(config, basepath_name.as_ref(), &path)?; if !file_path.exists() { let msg = anyhow!("File '{:?}' does not exist", file_path); Err(msg).context("Making ref out of entry")?; } debug!("Entry hashing = {}", file_path.display()); H::hash(&file_path) .and_then(|hash| { trace!("hash = {}", hash); // stripping the prefix of "path" let prefix = get_basepath(basepath_name.as_ref(), config)?; trace!("Stripping = {}", prefix.display()); let relpath = path.as_ref().strip_prefix(prefix)?; trace!("Using relpath = {} to make header section", relpath.display()); make_header_section(hash, H::NAME, relpath, basepath_name) }) .and_then(|h| self.0.get_header_mut().insert("ref", h) .context("Failed to insert 'ref' in header") .map_err(Error::from)) .and_then(|_| self.0.set_isflag::<IsRef>()) .context("Making ref out of entry")?; debug!("Setting is-ref flag"); self.0 .set_isflag::<IsRef>() .context("Setting ref-flag") .map_err(Error::from) .map(|_| ()) } } /// Create a new header section for a "ref". /// /// # Warning /// /// The `relpath` _must_ be relative to the configured path for that basepath. pub(crate) fn make_header_section<P, C, H>(hash: String, hashname: H, relpath: P, basepath: C) -> Result<Value> where P: AsRef<Path>, C: AsRef<str>, H: AsRef<str>, { let mut header_section = Value::Table(Map::new()); { let relpath = relpath .as_ref() .to_str() .map(String::from) .ok_or_else(|| { let msg = anyhow!("UTF Error in '{:?}'", relpath.as_ref()); msg })?; let _ = header_section.insert("relpath", Value::String(relpath))?; } { let mut hash_table = Value::Table(Map::new()); let _ = hash_table.insert(hashname.as_ref(), Value::String(hash))?; let _ = header_section.insert("hash", hash_table)?; } let _ = header_section.insert("basepath", Value::String(String::from(basepath.as_ref()))); Ok(header_section) } fn get_basepath<'a, Coll: AsRef<str>>(basepath_name: Coll, config: &'a Config) -> Result<&'a PathBuf> { config.get(basepath_name.as_ref()) .ok_or_else(|| anyhow!("basepath {} seems not to exist in config", basepath_name.as_ref())) .map_err(Error::from) } fn get_file_path<P>(config: &Config, basepath_name: &str, path: P) -> Result<PathBuf> where P: AsRef<Path> { config .get(basepath_name) .map(PathBuf::clone) .ok_or_else(|| { anyhow!("Configuration missing for basepath: '{}'", basepath_name) }) .context("Making ref out of entry") .map_err(Error::from) .map(|p| { let filepath = p.join(&path); trace!("Found filepath: {:?}", filepath.display()); filepath }) } #[cfg(test)] mod test { use std::path::PathBuf; use libimagstore::store::Store; use libimagstore::store::Entry;<|fim▁hole|> fn setup_logging() { let _ = ::env_logger::try_init(); } pub fn get_store() -> Store { Store::new_inmemory(PathBuf::from("/"), &None).unwrap() } struct TestHasher; impl Hasher for TestHasher { const NAME: &'static str = "Testhasher"; fn hash<P: AsRef<Path>>(path: P) -> Result<String> { path.as_ref() .to_str() .map(String::from) .ok_or_else(|| anyhow!("Failed to create test hash")) } } #[test] fn test_isref() { setup_logging(); let store = get_store(); let entry = store.retrieve(PathBuf::from("test_isref")).unwrap(); assert!(!entry.is_ref().unwrap()); } #[test] fn test_makeref() { setup_logging(); let store = get_store(); let mut entry = store.retrieve(PathBuf::from("test_makeref")).unwrap(); let file = PathBuf::from("/tmp"); // has to exist let basepath_name = "some_basepath"; let config = Config({ let mut c = BTreeMap::new(); c.insert(String::from("some_basepath"), PathBuf::from("/")); c }); let r = entry.as_ref_with_hasher_mut::<TestHasher>().make_ref(file, basepath_name, &config, false); assert!(r.is_ok()); } #[test] fn test_makeref_isref() { setup_logging(); let store = get_store(); let mut entry = store.retrieve(PathBuf::from("test_makeref_isref")).unwrap(); let file = PathBuf::from("/tmp"); // has to exists let basepath_name = "some_basepath"; let config = Config({ let mut c = BTreeMap::new(); c.insert(String::from("some_basepath"), PathBuf::from("/")); c }); let res = entry.as_ref_with_hasher_mut::<TestHasher>().make_ref(file, basepath_name, &config, false); assert!(res.is_ok(), "Expected to be ok: {:?}", res); assert!(entry.as_ref_with_hasher::<TestHasher>().is_ref().unwrap()); } #[test] fn test_makeref_is_ref_with_testhash() { setup_logging(); let store = get_store(); let mut entry = store.retrieve(PathBuf::from("test_makeref_is_ref_with_testhash")).unwrap(); let file = PathBuf::from("/tmp"); // has to exist let basepath_name = "some_basepath"; let config = Config({ let mut c = BTreeMap::new(); c.insert(String::from("some_basepath"), PathBuf::from("/")); c }); assert!(entry.as_ref_with_hasher_mut::<TestHasher>().make_ref(file, basepath_name, &config, false).is_ok()); let check_isstr = |entry: &Entry, location, shouldbe| { let var = entry.get_header().read(location); assert!(var.is_ok(), "{} is not Ok(_): {:?}", location, var); let var = var.unwrap(); assert!(var.is_some(), "{} is not Some(_): {:?}", location, var); let var = var.unwrap().as_str(); assert!(var.is_some(), "{} is not String: {:?}", location, var); assert_eq!(var.unwrap(), shouldbe, "{} is not == {}", location, shouldbe); }; check_isstr(&entry, "ref.relpath", "tmp"); check_isstr(&entry, "ref.hash.Testhasher", "/tmp"); // TestHasher hashes by returning the path itself check_isstr(&entry, "ref.basepath", "some_basepath"); } #[test] fn test_makeref_remref() { setup_logging(); let store = get_store(); let mut entry = store.retrieve(PathBuf::from("test_makeref_remref")).unwrap(); let file = PathBuf::from("/"); // has to exist let basepath_name = "some_basepath"; let config = Config({ let mut c = BTreeMap::new(); c.insert(String::from("some_basepath"), PathBuf::from("/")); c }); assert!(entry.as_ref_with_hasher_mut::<TestHasher>().make_ref(file, basepath_name, &config, false).is_ok()); assert!(entry.as_ref_with_hasher::<TestHasher>().is_ref().unwrap()); let res = entry.as_ref_with_hasher_mut::<TestHasher>().remove_ref(); assert!(res.is_ok(), "Expected to be ok: {:?}", res); assert!(!entry.as_ref_with_hasher::<TestHasher>().is_ref().unwrap()); } }<|fim▁end|>
use super::*; use crate::hasher::Hasher;
<|file_name|>createSubmit.js<|end_file_name|><|fim▁begin|>var createSubmit = function(name, primus, keyDict) { return function(event) { var message = $('#message').val(); if (message.length === 0) { event.preventDefault(); return; } $('#message').val(''); $('#message').focus(); var BigInteger = forge.jsbn.BigInteger; var data = JSON.parse(sessionStorage[name]); var pem = data.pem; var privateKey = forge.pki.privateKeyFromPem(pem); var ownPublicKey = forge.pki.setRsaPublicKey(new BigInteger(data.n), new BigInteger(data.e)); var keys = []; var iv = forge.random.getBytesSync(16); var key = forge.random.getBytesSync(16); var cipher = forge.cipher.createCipher('AES-CBC', key); cipher.start({iv: iv}); cipher.update(forge.util.createBuffer(message, 'utf8')); cipher.finish(); var encryptedMessage = cipher.output.getBytes(); var encryptedKey = ownPublicKey.encrypt(key, 'RSA-OAEP'); keys.push({ 'name': name, 'key': encryptedKey }); var md = forge.md.sha1.create(); md.update(message, 'utf8'); var signature = privateKey.sign(md); var recipients = $.map($("#recipients").tokenfield("getTokens"), function(o) {return o.value;}); var deferredRequests = []; for (var i = 0; i < recipients.length; i++) { (function (index) { var retrieveKey = function(pk) {<|fim▁hole|> if (pk === false) { return; } if (keyDict[recipients[i]] === undefined) { keyDict[recipients[i]] = pk; } var publicKey = forge.pki.setRsaPublicKey(new BigInteger(pk.n), new BigInteger(pk.e)); var encryptedKey = publicKey.encrypt(key, 'RSA-OAEP'); keys.push({ 'name': recipients[index], 'key': encryptedKey }); } if (keyDict[recipients[i]] === undefined) { deferredRequests.push($.post('/user/getpublickey', {'name' : recipients[i]}, retrieveKey)); } else { retrieveKey(keyDict[recipients[i]]); } })(i); } $.when.apply(null, deferredRequests).done(function() { primus.substream('messageStream').write({'message': encryptedMessage, 'keys': keys, 'iv': iv, 'signature': signature, 'recipients': recipients}); }); event.preventDefault(); }; };<|fim▁end|>
<|file_name|>0005_auto_20161129_1044.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2016-11-29 10:44 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0004_auto_20161129_0947'), ] operations = [ migrations.AlterField( model_name='pokemon', name='qr_code', field=models.TextField(default=''), ), migrations.AlterField( model_name='pokemon', name='qr_code_image', field=models.ImageField(blank=True, null=True, upload_to='qr'),<|fim▁hole|><|fim▁end|>
), ]
<|file_name|>conf.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at<|fim▁hole|># Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """A library for managing flags-like configuration that update dynamically. """ import logging import os import re import time try: from google.appengine.api import memcache from google.appengine.ext import db from google.appengine.api import validation from google.appengine.api import yaml_object except: from google.appengine.api import memcache from google.appengine.ext import db from google.appengine.ext import validation from google.appengine.ext import yaml_object DATASTORE_DEADLINE = 1.5 RESERVED_MARKER = 'ah__conf__' NAMESPACE = '_' + RESERVED_MARKER CONFIG_KIND = '_AppEngine_Config' ACTIVE_KEY_NAME = 'active' FILENAMES = ['conf.yaml', 'conf.yml'] PARAMETERS = 'parameters' PARAMETER_NAME_REGEX = '[a-zA-Z][a-zA-Z0-9_]*' _cached_config = None class Config(db.Expando): """The representation of a config in the datastore and memcache.""" ah__conf__version = db.IntegerProperty(default=0, required=True) @classmethod def kind(cls): """Override the kind name to prevent collisions with users.""" return CONFIG_KIND def ah__conf__load_from_yaml(self, parsed_config): """Loads all the params from a YAMLConfiguration into expando fields. We set these expando properties with a special name prefix 'p_' to keep them separate from the static attributes of Config. That way we don't have to check elsewhere to make sure the user doesn't stomp on our built in properties. Args: parse_config: A YAMLConfiguration. """ for key, value in parsed_config.parameters.iteritems(): setattr(self, key, value) class _ValidParameterName(validation.Validator): """Validator to check if a value is a valid config parameter name. We only allow valid python attribute names without leading underscores that also do not collide with reserved words in the datastore models. """ def __init__(self): self.regex = validation.Regex(PARAMETER_NAME_REGEX) def Validate(self, value, key): """Check that all parameter names are valid. This is used as a validator when parsing conf.yaml. Args: value: the value to check. key: A description of the context for which this value is being validated. Returns: The validated value. """ value = self.regex.Validate(value, key) try: db.check_reserved_word(value) except db.ReservedWordError: raise validation.ValidationError( 'The config parameter name %.100r is reserved by db.Model see: ' 'https://developers.google.com/appengine/docs/python/datastore/' 'modelclass#Disallowed_Property_Names for details.' % value) if value.startswith(RESERVED_MARKER): raise validation.ValidationError( 'The config parameter name %.100r is reserved, as are all names ' 'beginning with \'%s\', please choose a different name.' % ( value, RESERVED_MARKER)) return value class _Scalar(validation.Validator): """Validator to check if a value is a simple scalar type. We only allow scalars that are well supported by both the datastore and YAML. """ ALLOWED_PARAMETER_VALUE_TYPES = frozenset( [bool, int, long, float, str, unicode]) def Validate(self, value, key): """Check that all parameters are scalar values. This is used as a validator when parsing conf.yaml Args: value: the value to check. key: the name of parameter corresponding to this value. Returns: We just return value unchanged. """ if type(value) not in self.ALLOWED_PARAMETER_VALUE_TYPES: raise validation.ValidationError( 'Expected scalar value for parameter: %s, but found %.100r which ' 'is type %s' % (key, value, type(value).__name__)) return value class _ParameterDict(validation.ValidatedDict): """This class validates the parameters dictionary in YAMLConfiguration. Keys must look like non-private python identifiers and values must be a supported scalar. See the class comment for YAMLConfiguration. """ KEY_VALIDATOR = _ValidParameterName() VALUE_VALIDATOR = _Scalar() class YAMLConfiguration(validation.Validated): """This class describes the structure of a conf.yaml file. At the top level the file should have a params attribue which is a mapping from strings to scalars. For example: parameters: background_color: 'red' message_size: 1024 boolean_valued_param: true """ ATTRIBUTES = {PARAMETERS: _ParameterDict} def LoadSingleConf(stream): """Load a conf.yaml file or string and return a YAMLConfiguration object. Args: stream: a file object corresponding to a conf.yaml file, or its contents as a string. Returns: A YAMLConfiguration instance """ return yaml_object.BuildSingleObject(YAMLConfiguration, stream) def _find_yaml_path(): """Traverse directory trees to find conf.yaml file. Begins with the current working direcotry and then moves up the directory structure until the file is found.. Returns: the path of conf.yaml file or None if not found. """ current, last = os.getcwd(), None while current != last: for yaml_name in FILENAMES: yaml_path = os.path.join(current, yaml_name) if os.path.exists(yaml_path): return yaml_path last = current current, last = os.path.dirname(current), current return None def _fetch_from_local_file(pathfinder=_find_yaml_path, fileopener=open): """Get the configuration that was uploaded with this version. Args: pathfinder: a callable to use for finding the path of the conf.yaml file. This is only for use in testing. fileopener: a callable to use for opening a named file. This is only for use in testing. Returns: A config class instance for the options that were uploaded. If there is no config file, return None """ yaml_path = pathfinder() if yaml_path: config = Config() config.ah__conf__load_from_yaml(LoadSingleConf(fileopener(yaml_path))) logging.debug('Loaded conf parameters from conf.yaml.') return config return None def _get_active_config_key(app_version): """Generate the key for the active config record belonging to app_version. Args: app_version: the major version you want configuration data for. Returns: The key for the active Config record for the given app_version. """ return db.Key.from_path( CONFIG_KIND, '%s/%s' % (app_version, ACTIVE_KEY_NAME), namespace=NAMESPACE) def _fetch_latest_from_datastore(app_version): """Get the latest configuration data for this app-version from the datastore. Args: app_version: the major version you want configuration data for. Side Effects: We populate memcache with whatever we find in the datastore. Returns: A config class instance for most recently set options or None if the query could not complete due to a datastore exception. """ rpc = db.create_rpc(deadline=DATASTORE_DEADLINE, read_policy=db.EVENTUAL_CONSISTENCY) key = _get_active_config_key(app_version) config = None try: config = Config.get(key, rpc=rpc) logging.debug('Loaded most recent conf data from datastore.') except: logging.warning('Tried but failed to fetch latest conf data from the ' 'datastore.') if config: memcache.set(app_version, db.model_to_protobuf(config).Encode(), namespace=NAMESPACE) logging.debug('Wrote most recent conf data into memcache.') return config def _fetch_latest_from_memcache(app_version): """Get the latest configuration data for this app-version from memcache. Args: app_version: the major version you want configuration data for. Returns: A Config class instance for most recently set options or None if none could be found in memcache. """ proto_string = memcache.get(app_version, namespace=NAMESPACE) if proto_string: logging.debug('Loaded most recent conf data from memcache.') return db.model_from_protobuf(proto_string) logging.debug('Tried to load conf data from memcache, but found nothing.') return None def _inspect_environment(): """Return relevant information from the cgi environment. This is mostly split out to simplify testing. Returns: A tuple: (app_version, conf_version, development) app_version: the major version of the current application. conf_version: the current configuration version. development: a boolean, True if we're running under devappserver. """ app_version = os.environ['CURRENT_VERSION_ID'].rsplit('.', 1)[0] conf_version = int(os.environ.get('CURRENT_CONFIGURATION_VERSION', '0')) development = os.environ.get('SERVER_SOFTWARE', '').startswith('Development/') return (app_version, conf_version, development) def refresh(): """Update the local config cache from memcache/datastore. Normally configuration parameters are only refreshed at the start of a new request. If you have a very long running request, or you just need the freshest data for some reason, you can call this function to force a refresh. """ app_version, _, _ = _inspect_environment() global _cached_config new_config = _fetch_latest_from_memcache(app_version) if not new_config: new_config = _fetch_latest_from_datastore(app_version) if new_config: _cached_config = new_config def _new_request(): """Test if this is the first call to this function in the current request. This function will return True exactly once for each request Subsequent calls in the same request will return False. Returns: True if this is the first call in a given request, False otherwise. """ if RESERVED_MARKER in os.environ: return False os.environ[RESERVED_MARKER] = RESERVED_MARKER return True def _get_config(): """Check if the current cached config is stale, and if so update it.""" app_version, current_config_version, development = _inspect_environment() global _cached_config if (development and _new_request()) or not _cached_config: _cached_config = _fetch_from_local_file() or Config() if _cached_config.ah__conf__version < current_config_version: newconfig = _fetch_latest_from_memcache(app_version) if not newconfig or newconfig.ah__conf__version < current_config_version: newconfig = _fetch_latest_from_datastore(app_version) _cached_config = newconfig or _cached_config return _cached_config def get(name, default=None): """Get the value of a configuration parameter. This function is guaranteed to return the same value for every call during a single request. Args: name: The name of the configuration parameter you want a value for. default: A default value to return if the named parameter doesn't exist. Returns: The string value of the configuration parameter. """ return getattr(_get_config(), name, default) def get_all(): """Return an object with an attribute for each conf parameter. Returns: An object with an attribute for each conf parameter. """ return _get_config()<|fim▁end|>
# # http://www.apache.org/licenses/LICENSE-2.0 #
<|file_name|>bitcoin_lt.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="lt" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About UniverseCoin</source> <translation>Apie UniverseCoin</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;UniverseCoin&lt;/b&gt; version</source> <translation>&lt;b&gt;UniverseCoin&lt;/b&gt; versija</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source> <translation>Tai eksperimentinė programa. Platinama pagal MIT/X11 licenciją, kurią rasite faile COPYING arba http://www.opensource.org/licenses/mit-license.php. Šiame produkte yra OpenSSL projekto kuriamas OpenSSL Toolkit (http://www.openssl.org/), Eric Young parašyta kriptografinė programinė įranga bei Thomas Bernard sukurta UPnP programinė įranga.</translation> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The UniverseCoin developers</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Adresų knygelė</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Spragtelėkite, kad pakeistumėte adresą arba žymę</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Sukurti naują adresą</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Kopijuoti esamą adresą į mainų atmintį</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Naujas adresas</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your UniverseCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Tai yra jūsų UniverseCoin adresai mokėjimų gavimui. Galite duoti skirtingus adresus atskiriems siuntėjams, kad galėtumėte sekti, kas jums moka.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;Kopijuoti adresą</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Rodyti &amp;QR kodą</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a UniverseCoin address</source> <translation>Pasirašykite žinutę, kad įrodytume, jog esate UniverseCoin adreso savininkas</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Registruoti praneši&amp;mą</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified UniverseCoin address</source> <translation>Patikrinkite žinutę, jog įsitikintumėte, kad ją pasirašė nurodytas UniverseCoin adresas</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>&amp;Tikrinti žinutę</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Trinti</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your UniverseCoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>Kopijuoti ž&amp;ymę</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Keisti</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation type="unfinished"/> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Eksportuoti adresų knygelės duomenis</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Kableliais išskirtas failas (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Eksportavimo klaida</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Nepavyko įrašyti į failą %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Žymė</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adresas</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(nėra žymės)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Slaptafrazės dialogas</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Įvesti slaptafrazę</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Nauja slaptafrazė</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Pakartokite naują slaptafrazę</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Įveskite naują piniginės slaptafrazę.&lt;br/&gt;Prašome naudoti slaptafrazę iš &lt;b&gt; 10 ar daugiau atsitiktinių simbolių&lt;/b&gt; arba &lt;b&gt;aštuonių ar daugiau žodžių&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Užšifruoti piniginę</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Ši operacija reikalauja jūsų piniginės slaptafrazės jai atrakinti.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Atrakinti piniginę</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Ši operacija reikalauja jūsų piniginės slaptafrazės jai iššifruoti.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Iššifruoti piniginę</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Pakeisti slaptafrazę</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Įveskite seną ir naują piniginės slaptafrazes.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Patvirtinkite piniginės užšifravimą</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR LITECOINS&lt;/b&gt;!</source> <translation>Dėmesio: jei užšifruosite savo piniginę ir pamesite slaptafrazę, jūs&lt;b&gt;PRARASITE VISUS SAVO LITECOINUS&lt;/b&gt;! </translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Ar tikrai norite šifruoti savo piniginę?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Įspėjimas: įjungtas Caps Lock klavišas!</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Piniginė užšifruota</translation> </message> <message> <location line="-56"/> <source>UniverseCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your litecoins from being stolen by malware infecting your computer.</source> <translation>UniverseCoin dabar užsidarys šifravimo proceso pabaigai. Atminkite, kad piniginės šifravimas negali pilnai apsaugoti litecoinų vagysčių kai tinkle esančios kenkėjiškos programos patenka į jūsų kompiuterį.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Nepavyko užšifruoti piniginę</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Dėl vidinės klaidos nepavyko užšifruoti piniginę.Piniginė neužšifruota.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>Įvestos slaptafrazės nesutampa.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Nepavyko atrakinti piniginę</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Neteisingai įvestas slaptažodis piniginės iššifravimui.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Nepavyko iššifruoti piniginės</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Piniginės slaptažodis sėkmingai pakeistas.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>Pasirašyti ži&amp;nutę...</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Sinchronizavimas su tinklu ...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;Apžvalga</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Rodyti piniginės bendrą apžvalgą</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Sandoriai</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Apžvelgti sandorių istoriją</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Redaguoti išsaugotus adresus bei žymes</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Parodyti adresų sąraša mokėjimams gauti</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>&amp;Išeiti</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Išjungti programą</translation> </message> <message> <location line="+4"/> <source>Show information about UniverseCoin</source> <translation>Rodyti informaciją apie UniverseCoin</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Apie &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Rodyti informaciją apie Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Parinktys...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Užšifruoti piniginę...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Backup piniginę...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Keisti slaptafrazę...</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation type="unfinished"/> </message> <message> <location line="-347"/> <source>Send coins to a UniverseCoin address</source> <translation>Siųsti monetas UniverseCoin adresui</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for UniverseCoin</source> <translation>Keisti UniverseCoin konfigūracijos galimybes</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation>Daryti piniginės atsarginę kopiją</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Pakeisti slaptafrazę naudojamą piniginės užšifravimui</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>&amp;Derinimo langas</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Atverti derinimo ir diagnostikos konsolę</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>&amp;Tikrinti žinutę...</translation> </message> <message> <location line="-165"/> <location line="+530"/> <source>UniverseCoin</source> <translation>UniverseCoin</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>Piniginė</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>&amp;About UniverseCoin</source> <translation>&amp;Apie UniverseCoin</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>&amp;Rodyti / Slėpti</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign messages with your UniverseCoin addresses to prove you own them</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified UniverseCoin addresses</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Failas</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Nustatymai</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>&amp;Pagalba</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Kortelių įrankinė</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[testavimotinklas]</translation> </message> <message> <location line="+47"/> <source>UniverseCoin client</source> <translation>UniverseCoin klientas</translation> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to UniverseCoin network</source> <translation><numerusform>%n UniverseCoin tinklo aktyvus ryšys</numerusform><numerusform>%n UniverseCoin tinklo aktyvūs ryšiai</numerusform><numerusform>%n UniverseCoin tinklo aktyvūs ryšiai</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Atnaujinta</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Vejamasi...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>Patvirtinti sandorio mokestį</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Sandoris nusiųstas</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Ateinantis sandoris</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Data: %1 Suma: %2 Tipas: %3 Adresas: %4</translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation>URI apdorojimas</translation> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid UniverseCoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Piniginė &lt;b&gt;užšifruota&lt;/b&gt; ir šiuo metu &lt;b&gt;atrakinta&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Piniginė &lt;b&gt;užšifruota&lt;/b&gt; ir šiuo metu &lt;b&gt;užrakinta&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. UniverseCoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation>Tinklo įspėjimas</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Keisti adresą</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>Ž&amp;ymė</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>Žymė yra susieta su šios adresų knygelęs turiniu</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Adresas</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>Adresas yra susietas su šios adresų knygelęs turiniu. Tai gali būti keičiama tik siuntimo adresams.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Naujas gavimo adresas</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Naujas siuntimo adresas</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Keisti gavimo adresą</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Keisti siuntimo adresą</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Įvestas adresas „%1“ jau yra adresų knygelėje.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid UniverseCoin address.</source> <translation>Įvestas adresas „%1“ nėra galiojantis UniverseCoin adresas.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Nepavyko atrakinti piniginės.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Naujo rakto generavimas nepavyko.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>UniverseCoin-Qt</source> <translation>UniverseCoin-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>versija</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Naudojimas:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>komandinės eilutės parametrai</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>Naudotoji sąsajos parametrai</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Nustatyti kalbą, pavyzdžiui &quot;lt_LT&quot; (numatyta: sistemos kalba)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Paleisti sumažintą</translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Parinktys</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Pagrindinės</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>&amp;Mokėti sandorio mokestį</translation> </message> <message> <location line="+31"/> <source>Automatically start UniverseCoin after logging in to the system.</source> <translation>Automatiškai paleisti Bitkoin programą įjungus sistemą.</translation> </message> <message> <location line="+3"/> <source>&amp;Start UniverseCoin on system login</source> <translation>&amp;Paleisti UniverseCoin programą su window sistemos paleidimu</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation>&amp;Tinklas</translation> </message> <message> <location line="+6"/> <source>Automatically open the UniverseCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Automatiškai atidaryti UniverseCoin kliento prievadą maršrutizatoriuje. Tai veikia tik tada, kai jūsų maršrutizatorius palaiko UPnP ir ji įjungta.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Persiųsti prievadą naudojant &amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the UniverseCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Jungtis į Bitkoin tinklą per socks proxy (pvz. jungiantis per Tor)</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>&amp;Jungtis per SOCKS tarpinį serverį:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>Tarpinio serverio &amp;IP:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>Tarpinio serverio IP adresas (pvz. 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Prievadas:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Tarpinio serverio preivadas (pvz, 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS &amp;versija:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>Tarpinio serverio SOCKS versija (pvz., 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Langas</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Po programos lango sumažinimo rodyti tik programos ikoną.</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;M sumažinti langą bet ne užduočių juostą</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Uždarant langą neuždaryti programos. Kai ši parinktis įjungta, programa bus uždaryta tik pasirinkus meniu komandą Baigti.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>&amp;Sumažinti uždarant</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Rodymas</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>Naudotojo sąsajos &amp;kalba:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting UniverseCoin.</source> <translation>Čia gali būti nustatyta naudotojo sąsajos kalba. Šis nustatymas įsigalios iš naujo paleidus UniverseCoin.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Vienetai, kuriais rodyti sumas:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Rodomų ir siunčiamų monetų kiekio matavimo vienetai</translation> </message> <message> <location line="+9"/> <source>Whether to show UniverseCoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>&amp;Rodyti adresus sandorių sąraše</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;Gerai</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Atšaukti</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>&amp;Pritaikyti</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation>numatyta</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>Įspėjimas</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting UniverseCoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>Nurodytas tarpinio serverio adresas negalioja.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Forma</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the UniverseCoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>Balansas:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Nepatvirtinti:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Piniginė</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation>Nepribrendę:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Naujausi sandoriai&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>Jūsų einamasis balansas</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Iš viso sandorių, įskaitant tuos kurie dar turi būti patvirtinti, ir jie dar nėra įskaičiuotii į einamosios sąskaitos balansą</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start UniverseCoin: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>QR kodo dialogas</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Prašau išmokėti</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Suma:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Žymė:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Žinutė:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>Į&amp;rašyti kaip...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation>Klaida, koduojant URI į QR kodą.</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>Įvesta suma neteisinga, prašom patikrinti.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>Įrašyti QR kodą</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>PNG paveikslėliai (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Kliento pavadinimas</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation>nėra</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Kliento versija</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Informacija</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Naudojama OpenSSL versija</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Paleidimo laikas</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Tinklas</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Prisijungimų kiekis</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>Testnete</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Blokų grandinė</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Dabartinis blokų skaičius</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Paskutinio bloko laikas</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Atverti</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>Komandinės eilutės parametrai</translation> </message> <message> <location line="+7"/> <source>Show the UniverseCoin-Qt help message to get a list with possible UniverseCoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>&amp;Rodyti</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Konsolė</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Kompiliavimo data</translation> </message> <message> <location line="-104"/> <source>UniverseCoin - Debug window</source> <translation>UniverseCoin - Derinimo langas</translation> </message> <message> <location line="+25"/> <source>UniverseCoin Core</source> <translation>UniverseCoin branduolys</translation> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>Derinimo žurnalo failas</translation> </message> <message> <location line="+7"/> <source>Open the UniverseCoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Išvalyti konsolę</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the UniverseCoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Siųsti monetas</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Siųsti keliems gavėjams vienu metu</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>&amp;A Pridėti gavėją</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Pašalinti visus sandorio laukus</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Išvalyti &amp;viską</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Balansas:</translation> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Patvirtinti siuntimo veiksmą</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Siųsti</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Patvirtinti monetų siuntimą</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Ar tikrai norite siųsti %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation> ir </translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>Negaliojantis gavėjo adresas. Patikrinkite.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>Apmokėjimo suma turi būti didesnė nei 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>Suma viršija jūsų balansą.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Jei pridedame sandorio mokestį %1 bendra suma viršija jūsų balansą.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Rastas adreso dublikatas.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Klaida: sandoris buvo atmestas.Tai gali įvykti, jei kai kurios monetos iš jūsų piniginėje jau buvo panaudotos, pvz. jei naudojote wallet.dat kopiją ir monetos buvo išleistos kopijoje, bet nepažymėtos kaip skirtos išleisti čia.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Forma</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>Su&amp;ma:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>Mokėti &amp;gavėjui:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Įveskite žymę šiam adresui kad galėtumėte įtraukti ją į adresų knygelę</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>Ž&amp;ymė:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Pasirinkite adresą iš adresų knygelės</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Įvesti adresą iš mainų atminties</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>Pašalinti šį gavėją</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a UniverseCoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Įveskite bitkoinų adresą (pvz. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>&amp;Pasirašyti žinutę</translation> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Įveskite bitkoinų adresą (pvz. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>Pasirinkite adresą iš adresų knygelės</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Įvesti adresą iš mainų atminties</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Įveskite pranešimą, kurį norite pasirašyti čia</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this UniverseCoin address</source> <translation>Registruotis žinute įrodymuii, kad turite šį adresą</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Išvalyti &amp;viską</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>&amp;Patikrinti žinutę</translation> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Įveskite bitkoinų adresą (pvz. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified UniverseCoin address</source> <translation>Patikrinkite žinutę, jog įsitikintumėte, kad ją pasirašė nurodytas UniverseCoin adresas</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a UniverseCoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Įveskite bitkoinų adresą (pvz. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Spragtelėkite &quot;Registruotis žinutę&quot; tam, kad gauti parašą</translation> </message> <message> <location line="+3"/> <source>Enter UniverseCoin signature</source> <translation>Įveskite UniverseCoin parašą</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>Įvestas adresas negalioja.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Prašom patikrinti adresą ir bandyti iš naujo.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>Piniginės atrakinimas atšauktas.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Žinutės pasirašymas nepavyko.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Žinutė pasirašyta.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>Nepavyko iškoduoti parašo.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Prašom patikrinti parašą ir bandyti iš naujo.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>Parašas neatitinka žinutės.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Žinutės tikrinimas nepavyko.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Žinutė patikrinta.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The UniverseCoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[testavimotinklas]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Atidaryta iki %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1/neprisijungęs</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/nepatvirtintas</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 patvirtinimų</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Būsena</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Šaltinis</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Sugeneruotas</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Nuo</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Kam</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>savo adresas</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>žymė</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Kreditas</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>nepriimta</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Debitas</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Sandorio mokestis</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Neto suma</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Žinutė</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Komentaras</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>Sandorio ID</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Išgautos monetos turi sulaukti 120 blokų, kol jos gali būti naudojamos. Kai sukūrėte šį bloką, jis buvo transliuojamas tinkle ir turėjo būti įtrauktas į blokų grandinę. Jei nepavyksta patekti į grandinę, bus pakeista į &quot;nepriėmė&quot;, o ne &quot;vartojamas&quot;. Tai kartais gali atsitikti, jei kitas mazgas per keletą sekundžių sukuria bloką po jūsų bloko.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Derinimo informacija</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Sandoris</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Suma</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>tiesa</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>netiesa</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, transliavimas dar nebuvo sėkmingas</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>nežinomas</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Sandorio detelės</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Šis langas sandorio detalų aprašymą</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Tipas</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adresas</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Suma</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Atidaryta iki %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Atjungta (%1 patvirtinimai)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Nepatvirtintos (%1 iš %2 patvirtinimų)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Patvirtinta (%1 patvirtinimai)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Šis blokas negautas nė vienu iš mazgų ir matomai nepriimtas</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Išgauta bet nepriimta</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Gauta su</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Gauta iš</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Siųsta </translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Mokėjimas sau</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Išgauta</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>nepasiekiama</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Sandorio būklė. Užvedus pelės žymeklį ant šios srities matysite patvirtinimų skaičių.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Sandorio gavimo data ir laikas</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Sandorio tipas.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Sandorio paskirties adresas</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Suma pridėta ar išskaičiuota iš balanso</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Visi</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Šiandien</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Šią savaitę</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Šį mėnesį</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Paskutinį mėnesį</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Šiais metais</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Intervalas...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Gauta su</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Išsiųsta</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Skirta sau</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Išgauta</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Kita</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Įveskite adresą ar žymę į paiešką</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Minimali suma</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Kopijuoti adresą</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Kopijuoti žymę</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Kopijuoti sumą</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Taisyti žymę</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Rodyti sandėrio detales</translation> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Sandorio duomenų eksportavimas</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Kableliais atskirtų duomenų failas (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Patvirtintas</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Tipas</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Žymė</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Adresas</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Suma</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Eksportavimo klaida</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Neįmanoma įrašyti į failą %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Grupė:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>skirta</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Siųsti monetas</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/><|fim▁hole|> <message> <location line="+102"/> <source>Usage:</source> <translation>Naudojimas:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or litecoind</source> <translation>Siųsti komandą serveriui arba litecoind</translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Komandų sąrašas</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Suteikti pagalba komandai</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Parinktys:</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: UniverseCoin.conf)</source> <translation>Nurodyti konfigūracijos failą (pagal nutylėjimąt: UniverseCoin.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: litecoind.pid)</source> <translation>Nurodyti pid failą (pagal nutylėjimą: litecoind.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Nustatyti duomenų aplanką</translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 59333 or testnet: 19333)</source> <translation>Sujungimo klausymas prijungčiai &lt;port&gt; (pagal nutylėjimą: 59333 arba testnet: 19333)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Palaikyti ne daugiau &lt;n&gt; jungčių kolegoms (pagal nutylėjimą: 125)</translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Atjungimo dėl netinkamo kolegų elgesio riba (pagal nutylėjimą: 100)</translation> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Sekundžių kiekis eikiamas palaikyti ryšį dėl lygiarangių nestabilumo (pagal nutylėjimą: 86.400)</translation> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 9332 or testnet: 19332)</source> <translation>Klausymas JSON-RPC sujungimui prijungčiai &lt;port&gt; (pagal nutylėjimą: 9332 or testnet: 19332)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Priimti komandinę eilutę ir JSON-RPC komandas</translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Dirbti fone kaip šešėlyje ir priimti komandas</translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Naudoti testavimo tinklą</translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=litecoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;UniverseCoin Alert&quot; [email protected] </source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. UniverseCoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Įspėjimas: -paytxfee yra nustatytas per didelis. Tai sandorio mokestis, kurį turėsite mokėti, jei siųsite sandorį.</translation> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong UniverseCoin will not work properly.</source> <translation>Įspėjimas: Patikrinkite, kad kompiuterio data ir laikas yra teisingi.Jei Jūsų laikrodis neteisingai nustatytas UniverseCoin, veiks netinkamai.</translation> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>Prisijungti tik prie nurodyto mazgo</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation type="unfinished"/> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Neteisingas tor adresas: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Maksimalus buferis priėmimo sujungimui &lt;n&gt;*1000 bitų (pagal nutylėjimą: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Maksimalus buferis siuntimo sujungimui &lt;n&gt;*1000 bitų (pagal nutylėjimą: 1000)</translation> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>Išvesti papildomą derinimo informaciją. Numanomi visi kiti -debug* parametrai</translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation>Išvesti papildomą tinklo derinimo informaciją</translation> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>Prideėti laiko žymę derinimo rezultatams</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the UniverseCoin Wiki for SSL setup instructions)</source> <translation>SSL opcijos (žr.e UniverseCoin Wiki for SSL setup instructions)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Siųsti atsekimo/derinimo info į konsolę vietoj debug.log failo</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Siųsti sekimo/derinimo info derintojui</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Nustatyti sujungimo trukmę milisekundėmis (pagal nutylėjimą: 5000)</translation> </message> <message> <location line="+4"/> <source>System error: </source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Bandymas naudoti UPnP struktūra klausymosi prievadui (default: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Bandymas naudoti UPnP struktūra klausymosi prievadui (default: 1 when listening)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Vartotojo vardas JSON-RPC jungimuisi</translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>Slaptažodis JSON-RPC sujungimams</translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Leisti JSON-RPC tik iš nurodytų IP adresų</translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Siųsti komandą mazgui dirbančiam &lt;ip&gt; (pagal nutylėjimą: 127.0.0.1)</translation> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation>Atnaujinti piniginę į naujausią formatą</translation> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Nustatyti rakto apimties dydį &lt;n&gt; (pagal nutylėjimą: 100)</translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Ieškoti prarastų piniginės sandorių blokų grandinėje</translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Naudoti OpenSSL (https) jungimuisi JSON-RPC </translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation>Serverio sertifikato failas (pagal nutylėjimą: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Serverio privatus raktas (pagal nutylėjimą: server.pem)</translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Priimtini šifrai (pagal nutylėjimą: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Pagelbos žinutė</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Nepavyko susieti šiame kompiuteryje prievado %s (bind returned error %d, %s)</translation> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation>Jungtis per socks tarpinį serverį</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Leisti DNS paiešką sujungimui ir mazgo pridėjimui</translation> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>Užkraunami adresai...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation> wallet.dat pakrovimo klaida, wallet.dat sugadintas</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of UniverseCoin</source> <translation> wallet.dat pakrovimo klaida, wallet.dat reikalauja naujasnės UniverseCoin versijos</translation> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart UniverseCoin to complete</source> <translation>Piniginė turi būti prrašyta: įvykdymui perkraukite UniverseCoin</translation> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation> wallet.dat pakrovimo klaida</translation> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Neteisingas proxy adresas: &apos;%s&apos;</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Neteisinga suma -paytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Neteisinga suma</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Nepakanka lėšų</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Įkeliamas blokų indeksas...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Pridėti mazgą prie sujungti su and attempt to keep the connection open</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. UniverseCoin is probably already running.</source> <translation>Nepavyko susieti šiame kompiuteryje prievado %s. UniverseCoin tikriausiai jau veikia.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>Įtraukti mokestį už kB siunčiamiems sandoriams</translation> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Užkraunama piniginė...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Peržiūra</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Įkėlimas baigtas</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <source>Error</source> <translation>Klaida</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS><|fim▁end|>
<source>UniverseCoin version</source> <translation>UniverseCoin versija</translation> </message>
<|file_name|>downscaling_launcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python2 import os, glob os.chdir( '/workspace/Shared/Tech_Projects/ALFRESCO_Inputs/project_data/CODE/tem_ar5_inputs' ) base_dir = '/workspace/Shared/Tech_Projects/ESGF_Data_Access/project_data/data/prepped' output_base_dir = '/workspace/Shared/Tech_Projects/ALFRESCO_Inputs/project_data/TEM_Data/downscaled' cru_base_dir = '/workspace/Shared/Tech_Projects/ALFRESCO_Inputs/project_data/TEM_Data/cru_ts20/akcan' for root, dirs, files in os.walk( base_dir ): if files: path, variable = os.path.split( root ) path, model = os.path.split( path ) # this gets rid of any .xml or .txt files that may be living amongst the NetCDF's files = [ fn for fn in files if fn.endswith( '.nc' ) ] for fn in files: print 'running %s' % fn # split out the sub_dirs to have both model_name and variable folder hierarchy # from the prepped folder directory output_dir = os.path.join( output_base_dir, model, variable ) if not os.path.exists( output_dir ): os.makedirs( output_dir ) # anomalies calculation type and cru input path condition if 'tas_' in os.path.basename( fn ): anomalies_calc_type = 'absolute' downscale_operation = 'add' cru_path = os.path.join( cru_base_dir, 'tas' ) elif 'hur_' in os.path.basename( fn ): anomalies_calc_type = 'proportional' downscale_operation = 'mult' cru_path = os.path.join( cru_base_dir, 'hur' ) plev = 1000 else: NotImplementedError( "only 'hur' & 'tas' have been implemented here" ) # condition to determine if we need to read in the historical dataset with the modeled for # anomalies calculation if 'historical' in fn: # run with only the historical file dates = os.path.basename( fn ).strip( '.nc' ).split( '_' ) dates = dates[ len( dates )-2 ], dates[ len( dates )-1 ] begin_time, end_time = [ '-'.join([ i[:4], i[4:] ]) for i in dates ] if 'tas_' in fn: os.system( 'python hur_ar5_model_data_downscaling.py' + ' -hi ' + os.path.join( root, fn ) + ' -o ' + output_dir + ' -bt ' + begin_time + \ ' -et ' + end_time + ' -cbt ' + '1961-01' + ' -cet ' + '1990-12' + \ ' -cru ' + cru_path + ' -at ' + anomalies_calc_type + ' -m ' + 'mean' + ' -dso ' + downscale_operation ) elif 'hur_' in fn: # run with only the historical file os.system( 'python hur_ar5_model_data_downscaling.py' + ' -hi ' + os.path.join( root, fn ) + ' -o ' + output_dir + ' -bt ' + begin_time + \ ' -et ' + end_time + ' -cbt ' + '1961-01' + ' -cet ' + '1990-12' + \ ' -plev ' + str(plev) + ' -cru ' + cru_path + ' -at ' + anomalies_calc_type + ' -m ' + 'mean' + ' -dso ' + downscale_operation ) else: NotImplementedError( "only 'hur' & 'tas' have been implemented here" ) else: # grab the historical file from that particular folder historical_fn = glob.glob( os.path.join( root, '*historical*.nc' ) )[0] # run with both historical and modeled files for anomalies calc. if 'tas_' in fn: os.system( 'python hur_ar5_model_data_downscaling.py' + ' -mi ' + os.path.join( root, fn ) + ' -hi ' + historical_fn + ' -o ' + output_dir + \ ' -bt ' + '2006-01' + ' -et ' + '2100-12' + ' -cbt ' + '1961-01' + ' -cet ' + '1990-12' + \<|fim▁hole|> ' -cru ' + cru_path + ' -at ' + anomalies_calc_type + ' -m ' + 'mean' + ' -dso ' + downscale_operation ) else: NotImplementedError( "only 'hur' & 'tas' have been implemented here" )<|fim▁end|>
' -cru ' + cru_path + ' -at ' + anomalies_calc_type + ' -m ' + 'mean' + ' -dso ' + downscale_operation ) elif 'hur_' in fn: os.system( 'python hur_ar5_model_data_downscaling.py' + ' -mi ' + os.path.join( root, fn ) + ' -hi ' + historical_fn + ' -o ' + output_dir + \ ' -bt ' + '2006-01' + ' -et ' + '2100-12' + ' -cbt ' + '1961-01' + ' -cet ' + '1990-12' + ' -plev ' + str(plev) + \
<|file_name|>mock_store.rs<|end_file_name|><|fim▁begin|>/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashMap; use std::sync::{ atomic::{AtomicUsize, Ordering}, Arc, Mutex, }; #[derive(Debug, PartialEq)] pub struct MockStoreStats { pub sets: usize, pub gets: usize, pub hits: usize, pub misses: usize, } #[derive(Clone, Debug)] pub struct MockStore<T> { data: Arc<Mutex<HashMap<String, T>>>, pub(crate) set_count: Arc<AtomicUsize>, pub(crate) get_count: Arc<AtomicUsize>, pub(crate) hit_count: Arc<AtomicUsize>, pub(crate) miss_count: Arc<AtomicUsize>, } impl<T> MockStore<T> { pub(crate) fn new() -> Self { Self { data: Arc::new(Mutex::new(HashMap::new())), set_count: Arc::new(AtomicUsize::new(0)), get_count: Arc::new(AtomicUsize::new(0)), hit_count: Arc::new(AtomicUsize::new(0)), miss_count: Arc::new(AtomicUsize::new(0)), } } pub fn stats(&self) -> MockStoreStats { MockStoreStats { sets: self.set_count.load(Ordering::SeqCst), gets: self.get_count.load(Ordering::SeqCst), misses: self.miss_count.load(Ordering::SeqCst), hits: self.hit_count.load(Ordering::SeqCst), } } } impl<T: Clone> MockStore<T> { pub fn get(&self, key: &String) -> Option<T> { self.get_count.fetch_add(1, Ordering::SeqCst); let value = self.data.lock().expect("poisoned lock").get(key).cloned(); match &value { Some(..) => self.hit_count.fetch_add(1, Ordering::SeqCst), None => self.miss_count.fetch_add(1, Ordering::SeqCst), }; value } pub fn set(&self, key: &String, value: T) { self.set_count.fetch_add(1, Ordering::SeqCst); self.data .lock() .expect("poisoned lock") .insert(key.clone(), value); } #[cfg(test)] pub(crate) fn data(&self) -> HashMap<String, T> { self.data.lock().expect("poisoned lock").clone() } } #[cfg(test)] mod test { use super::*; #[test] fn test_counts() { let store = MockStore::new(); assert_eq!( store.stats(), MockStoreStats { sets: 0, gets: 0, misses: 0,<|fim▁hole|> hits: 0 } ); store.set(&"foo".to_string(), &()); assert_eq!( store.stats(), MockStoreStats { sets: 1, gets: 0, misses: 0, hits: 0 } ); store.get(&"foo".to_string()); assert_eq!( store.stats(), MockStoreStats { sets: 1, gets: 1, misses: 0, hits: 1 } ); store.get(&"bar".to_string()); assert_eq!( store.stats(), MockStoreStats { sets: 1, gets: 2, misses: 1, hits: 1 } ); } }<|fim▁end|>
<|file_name|>logger.js<|end_file_name|><|fim▁begin|>'use strict'; var path = require('path'), express = require('express'), errors = require('./errors'), debug = require('debug')('express-toybox:logger'), DEBUG = debug.enabled; /** * logger middleware using "morgan" or "debug". * * @param {*|String} options or log format. * @param {Number|Boolean} [options.buffer] * @param {Boolean} [options.immediate] * @param {Function} [options.skip]<|fim▁hole|> * @param {*} [options.stream] * @param {String} [options.format='combined'] log format. "combined", "common", "dev", "short", "tiny" or "default". * @param {String} [options.file] file to emit log. * @param {String} [options.debug] namespace for tj's debug namespace to emit log. * @returns {Function} connect/express middleware function */ function logger(options) { DEBUG && debug('configure http logger middleware', options); var format; if (typeof options === 'string') { format = options; options = {}; } else { format = options.format || 'combined'; delete options.format; } if (options.debug) { try { return require('morgan-debug')(options.debug, format, options); } catch (e) { console.error('**fatal** failed to configure logger with debug', e); return process.exit(2); } } if (options.file) { try { var file = path.resolve(process.cwd(), options.file); // replace stream options with stream object delete options.file; options.stream = require('fs').createWriteStream(file, {flags: 'a'}); } catch (e) { console.error('**fatal** failed to configure logger with file stream', e); return process.exit(2); } } console.warn('**fallback** use default logger middleware'); return require('morgan')(format, options); } module.exports = logger;<|fim▁end|>
<|file_name|>webhook.pb.go<|end_file_name|><|fim▁begin|>// Copyright 2022 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 // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.26.0 // protoc v3.12.2 // source: google/cloud/dialogflow/v2/webhook.proto package dialogflow import ( reflect "reflect" sync "sync" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" structpb "google.golang.org/protobuf/types/known/structpb" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) // The request message for a webhook call. type WebhookRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The unique identifier of detectIntent request session. // Can be used to identify end-user inside webhook implementation. // Format: `projects/<Project ID>/agent/sessions/<Session ID>`, or // `projects/<Project ID>/agent/environments/<Environment ID>/users/<User // ID>/sessions/<Session ID>`. Session string `protobuf:"bytes,4,opt,name=session,proto3" json:"session,omitempty"` // The unique identifier of the response. Contains the same value as // `[Streaming]DetectIntentResponse.response_id`. ResponseId string `protobuf:"bytes,1,opt,name=response_id,json=responseId,proto3" json:"response_id,omitempty"` // The result of the conversational query or event processing. Contains the // same value as `[Streaming]DetectIntentResponse.query_result`. QueryResult *QueryResult `protobuf:"bytes,2,opt,name=query_result,json=queryResult,proto3" json:"query_result,omitempty"` // Optional. The contents of the original request that was passed to // `[Streaming]DetectIntent` call. OriginalDetectIntentRequest *OriginalDetectIntentRequest `protobuf:"bytes,3,opt,name=original_detect_intent_request,json=originalDetectIntentRequest,proto3" json:"original_detect_intent_request,omitempty"` } func (x *WebhookRequest) Reset() { *x = WebhookRequest{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_dialogflow_v2_webhook_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *WebhookRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*WebhookRequest) ProtoMessage() {} func (x *WebhookRequest) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_dialogflow_v2_webhook_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use WebhookRequest.ProtoReflect.Descriptor instead. func (*WebhookRequest) Descriptor() ([]byte, []int) { return file_google_cloud_dialogflow_v2_webhook_proto_rawDescGZIP(), []int{0} } func (x *WebhookRequest) GetSession() string { if x != nil { return x.Session } return "" } func (x *WebhookRequest) GetResponseId() string { if x != nil { return x.ResponseId } return "" } func (x *WebhookRequest) GetQueryResult() *QueryResult { if x != nil { return x.QueryResult } return nil } func (x *WebhookRequest) GetOriginalDetectIntentRequest() *OriginalDetectIntentRequest { if x != nil { return x.OriginalDetectIntentRequest } return nil } // The response message for a webhook call. // // This response is validated by the Dialogflow server. If validation fails, // an error will be returned in the [QueryResult.diagnostic_info][google.cloud.dialogflow.v2.QueryResult.diagnostic_info] field. // Setting JSON fields to an empty value with the wrong type is a common error. // To avoid this error: // // - Use `""` for empty strings // - Use `{}` or `null` for empty objects // - Use `[]` or `null` for empty arrays // // For more information, see the // [Protocol Buffers Language // Guide](https://developers.google.com/protocol-buffers/docs/proto3#json). type WebhookResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Optional. The text response message intended for the end-user. // It is recommended to use `fulfillment_messages.text.text[0]` instead. // When provided, Dialogflow uses this field to populate // [QueryResult.fulfillment_text][google.cloud.dialogflow.v2.QueryResult.fulfillment_text] sent to the integration or API caller. FulfillmentText string `protobuf:"bytes,1,opt,name=fulfillment_text,json=fulfillmentText,proto3" json:"fulfillment_text,omitempty"` // Optional. The rich response messages intended for the end-user. // When provided, Dialogflow uses this field to populate // [QueryResult.fulfillment_messages][google.cloud.dialogflow.v2.QueryResult.fulfillment_messages] sent to the integration or API caller. FulfillmentMessages []*Intent_Message `protobuf:"bytes,2,rep,name=fulfillment_messages,json=fulfillmentMessages,proto3" json:"fulfillment_messages,omitempty"` // Optional. A custom field used to identify the webhook source. // Arbitrary strings are supported. // When provided, Dialogflow uses this field to populate // [QueryResult.webhook_source][google.cloud.dialogflow.v2.QueryResult.webhook_source] sent to the integration or API caller. Source string `protobuf:"bytes,3,opt,name=source,proto3" json:"source,omitempty"` // Optional. This field can be used to pass custom data from your webhook to the // integration or API caller. Arbitrary JSON objects are supported. // When provided, Dialogflow uses this field to populate // [QueryResult.webhook_payload][google.cloud.dialogflow.v2.QueryResult.webhook_payload] sent to the integration or API caller. // This field is also used by the // [Google Assistant // integration](https://cloud.google.com/dialogflow/docs/integrations/aog) // for rich response messages. // See the format definition at [Google Assistant Dialogflow webhook // format](https://developers.google.com/assistant/actions/build/json/dialogflow-webhook-json) Payload *structpb.Struct `protobuf:"bytes,4,opt,name=payload,proto3" json:"payload,omitempty"` // Optional. The collection of output contexts that will overwrite currently // active contexts for the session and reset their lifespans. // When provided, Dialogflow uses this field to populate // [QueryResult.output_contexts][google.cloud.dialogflow.v2.QueryResult.output_contexts] sent to the integration or API caller. OutputContexts []*Context `protobuf:"bytes,5,rep,name=output_contexts,json=outputContexts,proto3" json:"output_contexts,omitempty"` // Optional. Invokes the supplied events. // When this field is set, Dialogflow ignores the `fulfillment_text`, // `fulfillment_messages`, and `payload` fields. FollowupEventInput *EventInput `protobuf:"bytes,6,opt,name=followup_event_input,json=followupEventInput,proto3" json:"followup_event_input,omitempty"` // Optional. Additional session entity types to replace or extend developer // entity types with. The entity synonyms apply to all languages and persist // for the session. Setting this data from a webhook overwrites // the session entity types that have been set using `detectIntent`, // `streamingDetectIntent` or [SessionEntityType][google.cloud.dialogflow.v2.SessionEntityType] management methods. SessionEntityTypes []*SessionEntityType `protobuf:"bytes,10,rep,name=session_entity_types,json=sessionEntityTypes,proto3" json:"session_entity_types,omitempty"` } func (x *WebhookResponse) Reset() { *x = WebhookResponse{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_dialogflow_v2_webhook_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *WebhookResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*WebhookResponse) ProtoMessage() {} func (x *WebhookResponse) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_dialogflow_v2_webhook_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use WebhookResponse.ProtoReflect.Descriptor instead. func (*WebhookResponse) Descriptor() ([]byte, []int) { return file_google_cloud_dialogflow_v2_webhook_proto_rawDescGZIP(), []int{1} } func (x *WebhookResponse) GetFulfillmentText() string { if x != nil { return x.FulfillmentText } return "" } func (x *WebhookResponse) GetFulfillmentMessages() []*Intent_Message { if x != nil { return x.FulfillmentMessages } return nil } func (x *WebhookResponse) GetSource() string { if x != nil { return x.Source } return "" } func (x *WebhookResponse) GetPayload() *structpb.Struct { if x != nil { return x.Payload } return nil } func (x *WebhookResponse) GetOutputContexts() []*Context { if x != nil { return x.OutputContexts } return nil<|fim▁hole|>} func (x *WebhookResponse) GetFollowupEventInput() *EventInput { if x != nil { return x.FollowupEventInput } return nil } func (x *WebhookResponse) GetSessionEntityTypes() []*SessionEntityType { if x != nil { return x.SessionEntityTypes } return nil } // Represents the contents of the original request that was passed to // the `[Streaming]DetectIntent` call. type OriginalDetectIntentRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The source of this request, e.g., `google`, `facebook`, `slack`. It is set // by Dialogflow-owned servers. Source string `protobuf:"bytes,1,opt,name=source,proto3" json:"source,omitempty"` // Optional. The version of the protocol used for this request. // This field is AoG-specific. Version string `protobuf:"bytes,2,opt,name=version,proto3" json:"version,omitempty"` // Optional. This field is set to the value of the `QueryParameters.payload` // field passed in the request. Some integrations that query a Dialogflow // agent may provide additional information in the payload. // // In particular, for the Dialogflow Phone Gateway integration, this field has // the form: // <pre>{ // "telephony": { // "caller_id": "+18558363987" // } // }</pre> // Note: The caller ID field (`caller_id`) will be redacted for Trial // Edition agents and populated with the caller ID in [E.164 // format](https://en.wikipedia.org/wiki/E.164) for Essentials Edition agents. Payload *structpb.Struct `protobuf:"bytes,3,opt,name=payload,proto3" json:"payload,omitempty"` } func (x *OriginalDetectIntentRequest) Reset() { *x = OriginalDetectIntentRequest{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_dialogflow_v2_webhook_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *OriginalDetectIntentRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*OriginalDetectIntentRequest) ProtoMessage() {} func (x *OriginalDetectIntentRequest) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_dialogflow_v2_webhook_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use OriginalDetectIntentRequest.ProtoReflect.Descriptor instead. func (*OriginalDetectIntentRequest) Descriptor() ([]byte, []int) { return file_google_cloud_dialogflow_v2_webhook_proto_rawDescGZIP(), []int{2} } func (x *OriginalDetectIntentRequest) GetSource() string { if x != nil { return x.Source } return "" } func (x *OriginalDetectIntentRequest) GetVersion() string { if x != nil { return x.Version } return "" } func (x *OriginalDetectIntentRequest) GetPayload() *structpb.Struct { if x != nil { return x.Payload } return nil } var File_google_cloud_dialogflow_v2_webhook_proto protoreflect.FileDescriptor var file_google_cloud_dialogflow_v2_webhook_proto_rawDesc = []byte{ 0x0a, 0x28, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2f, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2f, 0x76, 0x32, 0x2f, 0x77, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x1a, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x76, 0x32, 0x1a, 0x28, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2f, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2f, 0x76, 0x32, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x27, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2f, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2f, 0x76, 0x32, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x28, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2f, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2f, 0x76, 0x32, 0x2f, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x34, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2f, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2f, 0x76, 0x32, 0x2f, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x5f, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1c, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x95, 0x02, 0x0a, 0x0e, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x18, 0x0a, 0x07, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x1f, 0x0a, 0x0b, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x49, 0x64, 0x12, 0x4a, 0x0a, 0x0c, 0x71, 0x75, 0x65, 0x72, 0x79, 0x5f, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x76, 0x32, 0x2e, 0x51, 0x75, 0x65, 0x72, 0x79, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x52, 0x0b, 0x71, 0x75, 0x65, 0x72, 0x79, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x12, 0x7c, 0x0a, 0x1e, 0x6f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x61, 0x6c, 0x5f, 0x64, 0x65, 0x74, 0x65, 0x63, 0x74, 0x5f, 0x69, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x5f, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x37, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x76, 0x32, 0x2e, 0x4f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x61, 0x6c, 0x44, 0x65, 0x74, 0x65, 0x63, 0x74, 0x49, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x52, 0x1b, 0x6f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x61, 0x6c, 0x44, 0x65, 0x74, 0x65, 0x63, 0x74, 0x49, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x22, 0xef, 0x03, 0x0a, 0x0f, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x29, 0x0a, 0x10, 0x66, 0x75, 0x6c, 0x66, 0x69, 0x6c, 0x6c, 0x6d, 0x65, 0x6e, 0x74, 0x5f, 0x74, 0x65, 0x78, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0f, 0x66, 0x75, 0x6c, 0x66, 0x69, 0x6c, 0x6c, 0x6d, 0x65, 0x6e, 0x74, 0x54, 0x65, 0x78, 0x74, 0x12, 0x5d, 0x0a, 0x14, 0x66, 0x75, 0x6c, 0x66, 0x69, 0x6c, 0x6c, 0x6d, 0x65, 0x6e, 0x74, 0x5f, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x76, 0x32, 0x2e, 0x49, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2e, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x52, 0x13, 0x66, 0x75, 0x6c, 0x66, 0x69, 0x6c, 0x6c, 0x6d, 0x65, 0x6e, 0x74, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x73, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x12, 0x31, 0x0a, 0x07, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x75, 0x63, 0x74, 0x52, 0x07, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x12, 0x4c, 0x0a, 0x0f, 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x73, 0x18, 0x05, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x23, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x76, 0x32, 0x2e, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x52, 0x0e, 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x73, 0x12, 0x58, 0x0a, 0x14, 0x66, 0x6f, 0x6c, 0x6c, 0x6f, 0x77, 0x75, 0x70, 0x5f, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x5f, 0x69, 0x6e, 0x70, 0x75, 0x74, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x26, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x76, 0x32, 0x2e, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x49, 0x6e, 0x70, 0x75, 0x74, 0x52, 0x12, 0x66, 0x6f, 0x6c, 0x6c, 0x6f, 0x77, 0x75, 0x70, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x49, 0x6e, 0x70, 0x75, 0x74, 0x12, 0x5f, 0x0a, 0x14, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x5f, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x73, 0x18, 0x0a, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x76, 0x32, 0x2e, 0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x45, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x54, 0x79, 0x70, 0x65, 0x52, 0x12, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x45, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x54, 0x79, 0x70, 0x65, 0x73, 0x22, 0x82, 0x01, 0x0a, 0x1b, 0x4f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x61, 0x6c, 0x44, 0x65, 0x74, 0x65, 0x63, 0x74, 0x49, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x31, 0x0a, 0x07, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x75, 0x63, 0x74, 0x52, 0x07, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x42, 0x9b, 0x01, 0x0a, 0x1e, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x76, 0x32, 0x42, 0x0c, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x44, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x67, 0x65, 0x6e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2f, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2f, 0x76, 0x32, 0x3b, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0xf8, 0x01, 0x01, 0xa2, 0x02, 0x02, 0x44, 0x46, 0xaa, 0x02, 0x1a, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x43, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x44, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x56, 0x32, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_google_cloud_dialogflow_v2_webhook_proto_rawDescOnce sync.Once file_google_cloud_dialogflow_v2_webhook_proto_rawDescData = file_google_cloud_dialogflow_v2_webhook_proto_rawDesc ) func file_google_cloud_dialogflow_v2_webhook_proto_rawDescGZIP() []byte { file_google_cloud_dialogflow_v2_webhook_proto_rawDescOnce.Do(func() { file_google_cloud_dialogflow_v2_webhook_proto_rawDescData = protoimpl.X.CompressGZIP(file_google_cloud_dialogflow_v2_webhook_proto_rawDescData) }) return file_google_cloud_dialogflow_v2_webhook_proto_rawDescData } var file_google_cloud_dialogflow_v2_webhook_proto_msgTypes = make([]protoimpl.MessageInfo, 3) var file_google_cloud_dialogflow_v2_webhook_proto_goTypes = []interface{}{ (*WebhookRequest)(nil), // 0: google.cloud.dialogflow.v2.WebhookRequest (*WebhookResponse)(nil), // 1: google.cloud.dialogflow.v2.WebhookResponse (*OriginalDetectIntentRequest)(nil), // 2: google.cloud.dialogflow.v2.OriginalDetectIntentRequest (*QueryResult)(nil), // 3: google.cloud.dialogflow.v2.QueryResult (*Intent_Message)(nil), // 4: google.cloud.dialogflow.v2.Intent.Message (*structpb.Struct)(nil), // 5: google.protobuf.Struct (*Context)(nil), // 6: google.cloud.dialogflow.v2.Context (*EventInput)(nil), // 7: google.cloud.dialogflow.v2.EventInput (*SessionEntityType)(nil), // 8: google.cloud.dialogflow.v2.SessionEntityType } var file_google_cloud_dialogflow_v2_webhook_proto_depIdxs = []int32{ 3, // 0: google.cloud.dialogflow.v2.WebhookRequest.query_result:type_name -> google.cloud.dialogflow.v2.QueryResult 2, // 1: google.cloud.dialogflow.v2.WebhookRequest.original_detect_intent_request:type_name -> google.cloud.dialogflow.v2.OriginalDetectIntentRequest 4, // 2: google.cloud.dialogflow.v2.WebhookResponse.fulfillment_messages:type_name -> google.cloud.dialogflow.v2.Intent.Message 5, // 3: google.cloud.dialogflow.v2.WebhookResponse.payload:type_name -> google.protobuf.Struct 6, // 4: google.cloud.dialogflow.v2.WebhookResponse.output_contexts:type_name -> google.cloud.dialogflow.v2.Context 7, // 5: google.cloud.dialogflow.v2.WebhookResponse.followup_event_input:type_name -> google.cloud.dialogflow.v2.EventInput 8, // 6: google.cloud.dialogflow.v2.WebhookResponse.session_entity_types:type_name -> google.cloud.dialogflow.v2.SessionEntityType 5, // 7: google.cloud.dialogflow.v2.OriginalDetectIntentRequest.payload:type_name -> google.protobuf.Struct 8, // [8:8] is the sub-list for method output_type 8, // [8:8] is the sub-list for method input_type 8, // [8:8] is the sub-list for extension type_name 8, // [8:8] is the sub-list for extension extendee 0, // [0:8] is the sub-list for field type_name } func init() { file_google_cloud_dialogflow_v2_webhook_proto_init() } func file_google_cloud_dialogflow_v2_webhook_proto_init() { if File_google_cloud_dialogflow_v2_webhook_proto != nil { return } file_google_cloud_dialogflow_v2_context_proto_init() file_google_cloud_dialogflow_v2_intent_proto_init() file_google_cloud_dialogflow_v2_session_proto_init() file_google_cloud_dialogflow_v2_session_entity_type_proto_init() if !protoimpl.UnsafeEnabled { file_google_cloud_dialogflow_v2_webhook_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*WebhookRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_cloud_dialogflow_v2_webhook_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*WebhookResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_cloud_dialogflow_v2_webhook_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*OriginalDetectIntentRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_google_cloud_dialogflow_v2_webhook_proto_rawDesc, NumEnums: 0, NumMessages: 3, NumExtensions: 0, NumServices: 0, }, GoTypes: file_google_cloud_dialogflow_v2_webhook_proto_goTypes, DependencyIndexes: file_google_cloud_dialogflow_v2_webhook_proto_depIdxs, MessageInfos: file_google_cloud_dialogflow_v2_webhook_proto_msgTypes, }.Build() File_google_cloud_dialogflow_v2_webhook_proto = out.File file_google_cloud_dialogflow_v2_webhook_proto_rawDesc = nil file_google_cloud_dialogflow_v2_webhook_proto_goTypes = nil file_google_cloud_dialogflow_v2_webhook_proto_depIdxs = nil }<|fim▁end|>
<|file_name|>DistributedTask.py<|end_file_name|><|fim▁begin|>''' Created on Feb 22, 2013 @author: u5682 ''' from datetime import datetime import os, sys, pickle import subprocess from time import sleep import xml.dom.minidom from xml.dom.minidom import Node class DistributedTask(object): ''' classdocs ''' def __init__(self, fileName = None): ''' Constructor ''' self.creationDate = datetime.now() if fileName == None: self.executable = "" self.arguments = [] self.outputPath = "" self.outputFile = "" self.errorPath = "" self.inputPath = "" self.inputSandbox = "" self.outputSandbox = "" self.workingDirectory = "" self.requirements = "" self.inputFiles = [] self.outputFiles = [] self.jobName = "" self.nativeSpecification = "" else: self.fromXML(fileName) def fromXML(self, fileName): #primerp rseamos el fichero doc = xml.dom.minidom.parse(fileName) self.executable = obtainText(doc, 'executable') self.arguments = obtainTextList(doc, 'arguments', 'argument') self.outputPath = obtainText(doc, 'outputPath') self.outputFile = obtainText(doc, 'outputFile') self.errorPath = obtainText(doc, 'errorPath') self.inputPath = obtainText(doc, 'inputPath') self.inputSandbox = obtainText(doc, 'inputSandbox') self.outputSandbox = obtainText(doc, 'outputSandbox') self.workingDirectory = obtainText(doc, 'workingDirectory') self.requirements = obtainText(doc, 'requirements') self.inputFiles = obtainTextList(doc, 'inputFiles', 'inputFile') self.outputFiles = obtainTextList(doc, 'outputFiles', 'outputFile') self.jobName = obtainText(doc, 'jobName') self.nativeSpecification = obtainText(doc, 'nativeSpecification') #y ahora creamos un objeto nuevo con la informacion obtenida def getArguments(self): argumentList = [] for arg in self.arguments: argumentList.append(arg.encode('ascii','ignore')) return argumentList def getInputFiles(self): inputFileList = [] for inputF in self.inputFiles: inputFileList.append(inputF.text) return inputFileList def getOutputFiles(self): outputFileList = [] for outputF in self.outputFiles: outputFileList.append(outputF.text) return outputFileList def outputFilesExist(self): for outputF in self.outputFiles: requiredFile = self.taskInfo.workingDirectory + "/" + outputF.text if not os.path.exists(requiredFile): print("OUTPUT FILE MISSING: " + requiredFile) return False return True def obtainText(node, tagName): L = node.getElementsByTagName(tagName) auxText = "" for node2 in L: for node3 in node2.childNodes: if node3.nodeType == Node.TEXT_NODE: auxText +=node3.data return auxText def obtainTextList(node, fatherTagName, sonTagName): L = node.getElementsByTagName(fatherTagName) auxTextArray = [] for node2 in L:<|fim▁hole|> L2 = node.getElementsByTagName(sonTagName) for node3 in L2: for node4 in node3.childNodes: if node4.nodeType == Node.TEXT_NODE: auxTextArray.append(node4.data) return auxTextArray<|fim▁end|>
<|file_name|>worker.py<|end_file_name|><|fim▁begin|>import os import sys import signal import argparse import requests from urllib.parse import urljoin from socket import gethostname from io import BytesIO from zipfile import ZipFile from shutil import move, rmtree from uuid import uuid4 from time import time, sleep from subprocess import Popen, check_output, STDOUT, CalledProcessError from fame.core import fame_init from fame.core.module import ModuleInfo from fame.core.internals import Internals from fame.common.config import fame_config from fame.common.constants import MODULES_ROOT from fame.common.pip import pip_install UNIX_INSTALL_SCRIPTS = { "install.sh": ["sh", "{}"], "install.py": ["python", "{}"] } WIN_INSTALL_SCRIPTS = { "install.cmd": ["{}"], "install.py": ["python", "{}"] } class Worker: def __init__(self, queues, celery_args, refresh_interval): self.queues = list(set(queues)) self.celery_args = [arg for arg in celery_args.split(' ') if arg] self.refresh_interval = refresh_interval def update_modules(self): # Module updates are only needed for remote workers if fame_config.remote: # First, backup current code backup_path = os.path.join(fame_config.temp_path, 'modules_backup_{}'.format(uuid4())) move(MODULES_ROOT, backup_path) # Replace current code with code fetched from web server url = urljoin(fame_config.remote, '/modules/download') try: response = requests.get(url, stream=True, headers={'X-API-KEY': fame_config.api_key}) response.raise_for_status() os.makedirs(MODULES_ROOT) with ZipFile(BytesIO(response.content), 'r') as zipf: zipf.extractall(MODULES_ROOT) rmtree(backup_path) print("Updated modules.") except Exception as e: print(("Could not update modules: '{}'".format(e))) print("Restoring previous version") move(backup_path, MODULES_ROOT) self.update_module_requirements() def update_module_requirements(self): for module in ModuleInfo.get_collection().find(): module = ModuleInfo(module)<|fim▁hole|> if module['type'] == "Processing": should_update = (module['queue'] in self.queues) elif module['type'] in ["Threat Intelligence", "Reporting", "Filetype"]: should_update = True else: should_update = (not fame_config.remote) if should_update: self.update_python_requirements(module) self.launch_install_scripts(module) module.save() def update_python_requirements(self, module): requirements = self._module_requirements(module) if requirements: print(("Installing requirements for '{}' ({})".format(module['name'], requirements))) rcode, output = pip_install('-r', requirements) # In case pip failed if rcode: self._module_installation_error(requirements, module, output) def launch_install_scripts(self, module): scripts = self._module_install_scripts(module) for script in scripts: try: print(("Launching installation script '{}'".format(' '.join(script)))) check_output(script, stderr=STDOUT) except CalledProcessError as e: self._module_installation_error(' '.join(script), module, e.output.decode('utf-8', errors='replace')) except Exception as e: self._module_installation_error(' '.join(script), module, e) def _module_installation_error(self, cmd, module, errors): errors = "{}: error on '{}':\n\n{}".format(cmd, gethostname(), errors) module['enabled'] = False module['error'] = errors print(errors) def _module_requirements(self, module): return module.get_file('requirements.txt') def _module_install_scripts(self, module): results = [] if sys.platform == "win32": INSTALL_SCRIPTS = WIN_INSTALL_SCRIPTS else: INSTALL_SCRIPTS = UNIX_INSTALL_SCRIPTS for filename in INSTALL_SCRIPTS: filepath = module.get_file(filename) if filepath: cmdline = [] for arg in INSTALL_SCRIPTS[filename]: cmdline.append(arg.format(filepath)) results.append(cmdline) return results # Delete files older than 7 days and empty directories def clean_temp_dir(self): current_time = time() for root, dirs, files in os.walk(fame_config.temp_path, topdown=False): for f in files: filepath = os.path.join(root, f) file_mtime = os.path.getmtime(filepath) if (current_time - file_mtime) > (7 * 24 * 3600): try: os.remove(filepath) except: pass for d in dirs: dirpath = os.path.join(root, d) try: os.rmdir(dirpath) except: pass def start(self): try: self.last_run = time() self.clean_temp_dir() self.update_modules() self.process = self._new_celery_worker() while True: updates = Internals.get(name='updates') if updates['last_update'] > self.last_run: # Stop running worker os.kill(self.process.pid, signal.SIGTERM) self.process.wait() # Update modules if needed self.update_modules() # Restart worker self.process = self._new_celery_worker() self.last_run = time() sleep(self.refresh_interval) except KeyboardInterrupt: not_finished = True while not_finished: try: self.process.wait() not_finished = False except KeyboardInterrupt: pass def _new_celery_worker(self): return Popen(['celery', '-A', 'fame.core.celeryctl', 'worker', '-Q', ','.join(self.queues)] + self.celery_args) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Launches a FAME worker.') parser.add_argument('queues', metavar='queue', type=str, nargs='*', help='The task queues that this worker will handle.') parser.add_argument('-c', '--celery_args', type=str, default='', help='Additional arguments for the celery worker.') parser.add_argument('-r', '--refresh_interval', type=int, default=30, help='Frequency at which the worker will check for updates.') args = parser.parse_args() queues = args.queues # Default queue is 'unix' if len(queues) == 0: if sys.platform == 'win32': queues = ['windows'] else: queues = ['unix'] # A local worker should also take care of updates if not fame_config.remote: queues.append('updates') fame_init() Worker(queues, args.celery_args, args.refresh_interval).start()<|fim▁end|>
if 'error' in module: del(module['error'])
<|file_name|>constant.d.ts<|end_file_name|><|fim▁begin|>import { constant } from "../fp";<|fim▁hole|><|fim▁end|>
export = constant;
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright (C) 2015 The Debsources developers <[email protected]>. # See the AUTHORS file at the top-level directory of this distribution and at # https://anonscm.debian.org/gitweb/?p=qa/debsources.git;a=blob;f=AUTHORS;hb=HEAD # # This file is part of Debsources. Debsources is free software: you can # redistribute it and/or modify it under the terms of the GNU Affero General # Public License as published by the Free Software Foundation, either version 3 # of the License, or (at your option) any later version. For more information # see the COPYING file at the top-level directory of this distribution and at # https://anonscm.debian.org/gitweb/?p=qa/debsources.git;a=blob;f=COPYING;hb=HEAD from __future__ import absolute_import <|fim▁hole|>bp_sources = Blueprint('sources', __name__, template_folder='templates', static_url_path='/static/sources', static_folder='static') from . import routes # NOQA<|fim▁end|>
from flask import Blueprint # naming rule: bp_{dirname}
<|file_name|>UserPageHandler.java<|end_file_name|><|fim▁begin|>package bdv.server; import bdv.db.UserController; import bdv.model.DataSet; import bdv.util.Render; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.ContextHandlerCollection; import org.eclipse.jetty.util.log.Log; import org.stringtemplate.v4.ST; import org.stringtemplate.v4.STGroup; import org.stringtemplate.v4.STRawGroupDir; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.net.URISyntaxException; import java.security.Principal; import java.util.List; import java.util.stream.Collectors; /** * Author: HongKee Moon ([email protected]), Scientific Computing Facility * Organization: MPI-CBG Dresden * Date: December 2016 */ public class UserPageHandler extends BaseContextHandler { private static final org.eclipse.jetty.util.log.Logger LOG = Log.getLogger( UserPageHandler.class ); UserPageHandler( final Server server, final ContextHandlerCollection publicDatasetHandlers, final ContextHandlerCollection privateDatasetHandlers, final String thumbnailsDirectoryName ) throws IOException, URISyntaxException { super( server, publicDatasetHandlers, privateDatasetHandlers, thumbnailsDirectoryName ); setContextPath( "/private/user/*" ); } @Override public void doHandle( final String target, final Request baseRequest, final HttpServletRequest request, final HttpServletResponse response ) throws IOException, ServletException { // System.out.println(target); Principal principal = request.getUserPrincipal(); // System.out.println( principal.getName() ); if ( null == request.getQueryString() ) { list( baseRequest, response, principal.getName() ); } else { // System.out.println(request.getQueryString()); updateDataSet( baseRequest, request, response, principal.getName() ); } } private void updateDataSet( Request baseRequest, HttpServletRequest request, HttpServletResponse response, String userId ) throws IOException { final String op = request.getParameter( "op" ); if ( null != op ) { if ( op.equals( "addDS" ) ) { final String dataSetName = request.getParameter( "name" ); final String tags = request.getParameter( "tags" ); final String description = request.getParameter( "description" ); final String file = request.getParameter( "file" ); final boolean isPublic = Boolean.parseBoolean( request.getParameter( "public" ) ); // System.out.println( "name: " + dataSetName ); // System.out.println( "tags: " + tags ); // System.out.println( "description: " + description ); // System.out.println( "file: " + file ); // System.out.println( "isPublic: " + isPublic ); final DataSet ds = new DataSet( dataSetName, file, tags, description, isPublic ); // Add it the database UserController.addDataSet( userId, ds ); // Add new CellHandler depending on public property addDataSet( ds, baseRequest, response ); } else if ( op.equals( "removeDS" ) ) { final long dsId = Long.parseLong( request.getParameter( "dataset" ) ); // Remove it from the database UserController.removeDataSet( userId, dsId ); // Remove the CellHandler removeDataSet( dsId, baseRequest, response ); } else if ( op.equals( "updateDS" ) ) { // UpdateDS uses x-editable // Please, refer http://vitalets.github.io/x-editable/docs.html final String field = request.getParameter( "name" ); final long dataSetId = Long.parseLong( request.getParameter( "pk" ) ); final String value = request.getParameter( "value" ); // Update the database final DataSet ds = UserController.getDataSet( userId, dataSetId ); if ( field.equals( "dataSetName" ) ) { ds.setName( value ); } else if ( field.equals( "dataSetDescription" ) ) { ds.setDescription( value ); } // Update DataBase UserController.updateDataSet( userId, ds ); // Update the CellHandler updateHandler( ds, baseRequest, response ); // System.out.println( field + ":" + value ); } else if ( op.equals( "addTag" ) || op.equals( "removeTag" ) ) { processTag( op, baseRequest, request, response ); } else if ( op.equals( "setPublic" ) ) { final long dataSetId = Long.parseLong( request.getParameter( "dataset" ) ); final boolean checked = Boolean.parseBoolean( request.getParameter( "checked" ) ); final DataSet ds = UserController.getDataSet( userId, dataSetId ); ds.setPublic( checked ); UserController.updateDataSet( userId, ds ); ds.setPublic( !checked ); updateHandlerVisibility( ds, checked, baseRequest, response ); } else if ( op.equals( "addSharedUser" ) || op.equals( "removeSharedUser" ) ) { final long dataSetId = Long.parseLong( request.getParameter( "dataset" ) ); final String sharedUserId = request.getParameter( "userId" ); if ( op.equals( "addSharedUser" ) ) { // System.out.println("Add a shared user"); UserController.addReadableSharedUser( userId, dataSetId, sharedUserId ); } else if ( op.equals( "removeSharedUser" ) ) { // System.out.println("Remove the shared user"); UserController.removeReadableSharedUser( userId, dataSetId, sharedUserId ); } response.setContentType( "text/html" ); response.setStatus( HttpServletResponse.SC_OK ); baseRequest.setHandled( true ); final PrintWriter ow = response.getWriter(); ow.write( "Success: " ); ow.close(); } } } private void updateHandlerVisibility( DataSet ds, boolean newVisibility, Request baseRequest, HttpServletResponse response ) throws IOException { String dsName = ds.getName(); boolean ret = removeCellHandler( ds.getIndex() ); if ( ret ) { ds.setPublic( newVisibility ); final boolean isPublic = newVisibility; final String context = "/" + ( isPublic ? Constants.PUBLIC_DATASET_CONTEXT_NAME : Constants.PRIVATE_DATASET_CONTEXT_NAME ) + "/id/" + ds.getIndex(); LOG.info( "Add new context: " + ds.getName() + " on " + context ); CellHandler ctx = getCellHandler( ds, isPublic, context ); ctx.setContextPath( context ); try { ctx.start(); } catch ( Exception e ) { LOG.warn( "Failed to start CellHandler", e ); e.printStackTrace(); ret = false; } } response.setContentType( "text/html" ); response.setStatus( HttpServletResponse.SC_OK ); baseRequest.setHandled( true );<|fim▁hole|> final PrintWriter ow = response.getWriter(); if ( ret ) { ow.write( "Success: " + dsName + " is removed." ); } else { ow.write( "Error: " + dsName + " cannot be removed." ); } ow.close(); } private void updateHandler( DataSet ds, Request baseRequest, HttpServletResponse response ) throws IOException { boolean ret = false; String dsName = ""; for ( final Handler handler : server.getChildHandlersByClass( CellHandler.class ) ) { final CellHandler contextHandler = ( CellHandler ) handler; if ( contextHandler.getDataSet().getIndex() == ds.getIndex() ) { final DataSet dataSet = contextHandler.getDataSet(); dataSet.setName( ds.getName() ); dataSet.setDescription( ds.getDescription() ); ret = true; dsName = ds.getName(); break; } } response.setContentType( "text/html" ); response.setStatus( HttpServletResponse.SC_OK ); baseRequest.setHandled( true ); final PrintWriter ow = response.getWriter(); if ( ret ) { ow.write( "Success: " + dsName + " is updated." ); } else { ow.write( "Error: " + dsName + " cannot be updated." ); } ow.close(); } private void removeDataSet( long dsId, Request baseRequest, HttpServletResponse response ) throws IOException { boolean ret = removeCellHandler( dsId ); response.setContentType( "text/html" ); response.setStatus( HttpServletResponse.SC_OK ); baseRequest.setHandled( true ); final PrintWriter ow = response.getWriter(); if ( ret ) { ow.write( "Success: " + dsId + " is removed." ); } else { ow.write( "Error: " + dsId + " cannot be removed." ); } ow.close(); } private void addDataSet( DataSet ds, Request baseRequest, HttpServletResponse response ) throws IOException { boolean ret = false; if ( !ds.getXmlPath().isEmpty() && !ds.getName().isEmpty() ) { final boolean isPublic = ds.isPublic(); final String context = "/" + ( isPublic ? Constants.PUBLIC_DATASET_CONTEXT_NAME : Constants.PRIVATE_DATASET_CONTEXT_NAME ) + "/id/" + ds.getIndex(); LOG.info( "Add new context: " + ds.getName() + " on " + context ); CellHandler ctx = getCellHandler( ds, isPublic, context ); ctx.setContextPath( context ); try { ctx.start(); } catch ( Exception e ) { LOG.warn( "Failed to start CellHandler", e ); e.printStackTrace(); } ret = true; } response.setContentType( "text/html" ); response.setStatus( HttpServletResponse.SC_OK ); baseRequest.setHandled( true ); final PrintWriter ow = response.getWriter(); if ( ret ) ow.write( "Success: " + ds.getName() + " is added." ); else ow.write( "Error: " + ds.getName() + " cannot be added." ); ow.close(); } private void list( final Request baseRequest, final HttpServletResponse response, final String userId ) throws IOException { response.setContentType( "text/html" ); response.setStatus( HttpServletResponse.SC_OK ); baseRequest.setHandled( true ); final PrintWriter ow = response.getWriter(); getHtmlDatasetList( ow, userId ); ow.close(); } private void getHtmlDatasetList( final PrintWriter out, final String userId ) throws IOException { final List< DataSet >[] dataSets = UserController.getDataSets( userId ); final List< DataSet > myDataSetList = dataSets[ 0 ]; final List< DataSet > sharedDataSetList = dataSets[ 1 ]; final STGroup g = new STRawGroupDir( "templates", '$', '$' ); final ST userPage = g.getInstanceOf( "userPage" ); final STGroup g2 = new STRawGroupDir( "templates", '~', '~' ); final ST userPageJS = g2.getInstanceOf( "userPageJS" ); final StringBuilder dsString = new StringBuilder(); for ( DataSet ds : myDataSetList ) { StringBuilder sharedUserString = new StringBuilder(); final ST dataSetTr = g.getInstanceOf( "privateDataSetTr" ); for ( String sharedUser : ds.getSharedUsers() ) { final ST userToBeRemoved = g.getInstanceOf( "userToBeRemoved" ); userToBeRemoved.add( "dataSetId", ds.getIndex() ); userToBeRemoved.add( "sharedUserId", sharedUser ); sharedUserString.append( userToBeRemoved.render() ); } if ( ds.getDatasetUrl() == null ) { // Setup the dataset url if ( ds.isPublic() ) { ds.setDatasetUrl( "/" + Constants.PUBLIC_DATASET_CONTEXT_NAME + "/id/" + ds.getIndex() + "/" ); } else { ds.setDatasetUrl( "/" + Constants.PRIVATE_DATASET_CONTEXT_NAME + "/id/" + ds.getIndex() + "/" ); } } dataSetTr.add( "thumbnailUrl", ds.getThumbnailUrl() ); dataSetTr.add( "dataSetId", ds.getIndex() ); dataSetTr.add( "dataSetTags", ds.getTags().stream().collect( Collectors.joining( "," ) ) ); dataSetTr.add( "dataSetName", ds.getName() ); dataSetTr.add( "dataSetDescription", ds.getDescription() ); dataSetTr.add( "dataSetLocation", ds.getXmlPath() ); String url = ds.getDatasetUrl(); if ( url.endsWith( "/" ) ) url = url.substring( 0, url.lastIndexOf( "/" ) ); dataSetTr.add( "dataSetUrl", url ); dataSetTr.add( "dataSetIsPublic", ds.isPublic() ); dataSetTr.add( "sharedUsers", sharedUserString.toString() ); dsString.append( dataSetTr.render() ); } if ( sharedDataSetList != null ) { for ( DataSet ds : sharedDataSetList ) { final ST dataSetTr = g.getInstanceOf( "sharedDataSetTr" ); if ( ds.getDatasetUrl() == null ) { // Setup the dataset url if ( ds.isPublic() ) { ds.setDatasetUrl( "/" + Constants.PUBLIC_DATASET_CONTEXT_NAME + "/id/" + ds.getIndex() + "/" ); } else { ds.setDatasetUrl( "/" + Constants.PRIVATE_DATASET_CONTEXT_NAME + "/id/" + ds.getIndex() + "/" ); } } dataSetTr.add( "thumbnailUrl", ds.getThumbnailUrl() ); dataSetTr.add( "dataSetId", ds.getIndex() ); dataSetTr.add( "dataSetTags", Render.createTagsLabel( ds ) ); dataSetTr.add( "dataSetName", ds.getName() ); dataSetTr.add( "dataSetDescription", ds.getDescription() ); dataSetTr.add( "dataSetLocation", ds.getXmlPath() ); String url = ds.getDatasetUrl(); if ( url.endsWith( "/" ) ) url = url.substring( 0, url.lastIndexOf( "/" ) ); dataSetTr.add( "dataSetUrl", url ); dataSetTr.add( "dataSetIsPublic", ds.isPublic() ); dataSetTr.add( "sharedUsers", ds.getOwner() ); dsString.append( dataSetTr.render() ); } } userPage.add( "userId", userId ); userPage.add( "dataSetTr", dsString.toString() ); userPage.add( "JS", userPageJS.render() ); out.write( userPage.render() ); out.close(); } }<|fim▁end|>
<|file_name|>instant_system_tests.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright (c) 2001-2018, Canal TP and/or its affiliates. All rights reserved. # # This file is part of Navitia, # the software to build cool stuff with public transport. # # Hope you'll enjoy and contribute to this project, # powered by Canal TP (www.canaltp.fr). # Help us simplify mobility and open public transport: # a non ending quest to the responsive locomotion way of traveling! # # LICENCE: This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Stay tuned using # twitter @navitia # channel `#navitia` on riot https://riot.im/app/#/room/#navitia:matrix.org # https://groups.google.com/d/forum/navitia # www.navitia.io from __future__ import absolute_import, print_function, unicode_literals, division from jormungandr.scenarios.ridesharing.instant_system import InstantSystem, DEFAULT_INSTANT_SYSTEM_FEED_PUBLISHER from jormungandr.scenarios.ridesharing.ridesharing_journey import Gender from jormungandr.scenarios.ridesharing.ridesharing_service import ( Ridesharing, RsFeedPublisher, RidesharingServiceError, ) import mock from jormungandr.tests import utils_test from jormungandr import utils import json fake_response = """ { "total": 2, "journeys": [ { "id": "4bcd0b9d-2c9d-42a2-8ffb-4508c952f4fb", "departureDate": "2017-12-25T08:07:59+01:00", "arrivalDate": "2017-12-25T08:25:36+01:00", "duration": 1057, "distance": 12650, "url": "https://jky8k.app.goo.gl/?efr=1&apn=com.is.android.rennes&ibi=&isi=&utm_campaign=KISIO&link=https%3A%2F%2Fwww.star.fr%2Fsearch%2F%3FfeatureName%3DsearchResultDetail%26networkId%3D33%26journeyId%3D4bcd0b9d-2c9d-42a2-8ffb-4508c952f4fb", "paths": [ { "mode": "RIDESHARINGAD", "from": { "name": "", "lat": 48.1102, "lon": -1.68623 }, "to": { "name": "", "lat": 48.02479, "lon": -1.74673 }, "departureDate": "2017-12-25T08:07:59+01:00", "arrivalDate": "2017-12-25T08:25:36+01:00", "shape": "wosdH|ihIRVDTFDzBjPNhADJ\\`C?TJt@Hj@h@tDp@bFR?bAFRBZDR@JCL@~AJl@Df@DfBNv@B~@DjAFh@HXH~@VbEfANDh@PdAl@\\RdAZnBHpADvBDf@@d@Gv@S\\OlAOl@EbAHjAVNDd@Dd@Mt@u@FGrE{EtBaBr@zCp@dDd@~BRtAHj@X`BFXlAjDLd@v@dDXlAh@TVl@hBtIB`ANpAh@nBf@xATf@Xd@JFPD@JHRLBLKDBbCbBbBbBjApA?VHPPBL`@\\^|BrBDHJ`@AP?PDRFL\\TRAJGRD`Al@jBhA~BbBx@VfALl@PHVDHPFNCVNdCnBpHzDdB|AfAjAj@h@^d@jAhBhAvA?^BNFJPHPCFGVNpBhApBt@ZL|B^dCJfDAZFLRHBNEJQZIdUa@b@JJ`@TXTFTAPKNUH]nBGtOb@vDd@`C`ArAp@zAjAnBnBJJh@h@`_@l`@fIvIfMhNl@t@dAzBnAnDx@xDh@jFfBbRdAnMdBnSjB|JbDbIhMj[rN`_@nEfJzCxDrCtDl@pBDtE^Bn@?h@?t@IdAe@XUFIvBaBvBaBf@Wl@OdAEfAJJXJHJBLCbAbAx@j@fBn@p@X`HfDdAd@NB\\CBLJDFCBI?OGILYn@gDb@uAVe@\\_@jEgDlFgARElBa@|G}AxFwA`AWv@YNI~AaArAg@bEw@pA[t@Y`B{@~BmAtAo@fAk@TYBBH?DGBKTEd@U^QlBcA^QvEcCP@Le@Cm@Eo@Ia@AI", "rideSharingAd": { "id": "24bab9de-653c-4cc4-a947-389c59cf0423", "type": "DRIVER", "from": { "name": "9 Allée Rochester, Rennes", "lat": 48.127905, "lon": -1.652393 }, "to": { "name": "2 Avenue Alphonse Legault, Bruz", "lat": 48.024714, "lon": -1.746711 }, "user": { "alias": "Jean P.", "gender": "MALE", "imageUrl": "https://dummyimage.com/128x128/C8E6C9/000.png&text=JP", "rating": { "rate": 0, "count": 0 } }, "price": { "amount": 170, "currency": "EUR" }, "vehicle": { "availableSeats": 4 } } } ] }, { "id": "05223c04-834d-4710-905f-aa3796da5837", "departureDate": "2017-12-25T08:35:42+01:00", "arrivalDate": "2017-12-25T08:53:09+01:00", "duration": 1047, "distance": 11686, "url": "https://jky8k.app.goo.gl/?efr=1&apn=com.is.android.rennes&ibi=&isi=&utm_campaign=KISIO&link=https%3A%2F%2Fwww.star.fr%2Fsearch%2F%3FfeatureName%3DsearchResultDetail%26networkId%3D33%26journeyId%3D05223c04-834d-4710-905f-aa3796da5837", "paths": [ { "mode": "RIDESHARINGAD", "from": { "name": "", "lat": 48.1102, "lon": -1.68623 }, "to": { "name": "", "lat": 48.03193, "lon": -1.74635 }, "departureDate": "2017-12-25T08:35:42+01:00", "arrivalDate": "2017-12-25T08:53:09+01:00", "shape": "wosdH|ihIRVDTFDzBjPNhADJ\\`C?TJt@Hj@h@tDp@bFR?bAFRBZDR@JCL@~AJl@Df@DfBNv@B~@DjAFh@HXH~@VbEfANDh@PdAl@\\RdAZnBHpADvBDf@@d@Gv@S\\OlAOl@EbAHjAVNDd@Dd@Mt@u@FGrE{EtBaB`CeB|AeAr@cA`@_BNgCf@RTJ`@PjBr@fBz@~@d@~Av@`Af@d@TzBfAZPVLRJf@TbAj@zIpE|J`F\\PNHpBbAp@Z~Ax@PHdA\\ANFPH@DCDMxDpBt@fABTLXJFL@JEJI\\A`Bb@fABpAY|Aq@tCsAjBy@d@StHuDxAm@t@Qf@GX@VZTDTId@Fr@\\z@\\`Dz@|PrD`FbA|HjBNBZDdB`@`QfDnGfAxJhBvBd@vF`B~CzAhGvDnD|BxBtAbBnAd@f@b@h@BRP^VNZALId@?bBbAnMhIfH~D~@`@t@NjA@`@?VFVXJZAZBXLf@HNLJLFT@RERMz@~@~@r@b@d@Rd@`@zAGj@BZL`@HJBl@BzJFh@FbAL~@Pv@dAjDl@bBlBhFvBhFdCtCrGdE`IhFt@d@HF@?DBLJNL`EnClEpCpCfBp@^bBv@hAb@hBf@xBb@rIpAVNPL@NFNFHJDBXbA|GJt@bAzGt@dFl@vDZpCLhC@pBCxBYpDC`@GAODKRALD\\JLD@G^GVw@lHSjCK|B@vCPpMCnAKf@OHEJEVF\\FHNDHLH\\BZH|KA`E@N\\x@bBtBpGpGZV", "rideSharingAd": { "id": "4eb9a4ba-fb10-4cf0-bf4c-31ada02a2c91", "type": "DRIVER", "from": { "name": "1 Boulevard Volney, Rennes", "lat": 48.1247, "lon": -1.666796 }, "to": { "name": "9012 Rue du 8 Mai 1944, Bruz", "lat": 48.031951, "lon": -1.74641 }, "user": { "alias": "Alice M.", "gender": "FEMALE", "imageUrl": "https://dummyimage.com/128x128/B2EBF2/000.png&text=AM", "rating": { "rate": 0, "count": 0 } }, "price": { "amount": 0, "currency": "EUR" }, "vehicle": { "availableSeats": 4 } } } ] } ], "url": "https://jky8k.app.goo.gl/?efr=1&apn=com.is.android.rennes&ibi=&isi=&utm_campaign=KISIO&link=https%3A%2F%2Fwww.star.fr%2Fsearch%2F%3FfeatureName%3DsearchResults%26networkId%3D33%26from%3D48.109377%252C-1.682103%26to%3D48.020335%252C-1.743929%26multimodal%3Dfalse%26departureDate%3D2017-12-25T08%253A00%253A00%252B01%253A00" } """ # https://stackoverflow.com/a/9312242/1614576 import re regex = re.compile(r'\\(?![/u"])') fixed = regex.sub(r"\\\\", fake_response) mock_get = mock.MagicMock(return_value=utils_test.MockResponse(json.loads(fixed), 200, '{}')) DUMMY_INSTANT_SYSTEM_FEED_PUBLISHER = {'id': '42', 'name': '42', 'license': 'I dunno', 'url': 'http://w.tf'} # A hack class class DummyInstance: name = '' def get_ridesharing_service_test(): configs = [ { "class": "jormungandr.scenarios.ridesharing.instant_system.InstantSystem", "args": { "service_url": "toto", "api_key": "toto key", "network": "N", "rating_scale_min": 0, "rating_scale_max": 10, "crowfly_radius": 200, "timeframe_duration": 1800, "feed_publisher": DUMMY_INSTANT_SYSTEM_FEED_PUBLISHER, }, }, { "class": "jormungandr.scenarios.ridesharing.instant_system.InstantSystem", "args": { "service_url": "tata", "api_key": "tata key", "network": "M", "rating_scale_min": 1, "rating_scale_max": 5, "crowfly_radius": 200, "timeframe_duration": 1800, }, }, ] services = Ridesharing.get_ridesharing_services(DummyInstance(), configs) assert len(services) == 2 assert services[0].service_url == 'toto' assert services[0].api_key == 'toto key' assert services[0].network == 'N' assert services[0].system_id == 'Instant System' assert services[0].rating_scale_min == 0 assert services[0].rating_scale_max == 10 assert services[0]._get_feed_publisher() == RsFeedPublisher(**DUMMY_INSTANT_SYSTEM_FEED_PUBLISHER) assert services[1].service_url == 'tata' assert services[1].api_key == 'tata key' assert services[1].network == 'M' assert services[1].system_id == 'Instant System' assert services[1].rating_scale_min == 1 assert services[1].rating_scale_max == 5 assert services[1]._get_feed_publisher() == RsFeedPublisher(**DEFAULT_INSTANT_SYSTEM_FEED_PUBLISHER) def instant_system_test(): with mock.patch('requests.get', mock_get): instant_system = InstantSystem( DummyInstance(), service_url='dummyUrl', api_key='dummyApiKey', network='dummyNetwork', feed_publisher=DUMMY_INSTANT_SYSTEM_FEED_PUBLISHER, rating_scale_min=0, rating_scale_max=10, ) from_coord = '48.109377,-1.682103' to_coord = '48.020335,-1.743929' period_extremity = utils.PeriodExtremity( datetime=utils.str_to_time_stamp("20171225T060000"), represents_start=True ) ridesharing_journeys, feed_publisher = instant_system.request_journeys_with_feed_publisher( from_coord=from_coord, to_coord=to_coord, period_extremity=period_extremity ) assert len(ridesharing_journeys) == 2 assert ridesharing_journeys[0].metadata.network == 'dummyNetwork' assert ridesharing_journeys[0].metadata.system_id == 'Instant System' assert ridesharing_journeys[0].metadata.rating_scale_min == 0 assert ridesharing_journeys[0].metadata.rating_scale_max == 10 assert ( ridesharing_journeys[0].ridesharing_ad == 'https://jky8k.app.goo.gl/?efr=1&apn=com.is.android.rennes&ibi=&isi=&utm_campaign=KISIO&link=https%3A%2F%2Fwww.star.fr%2Fsearch%2F%3FfeatureName%3DsearchResultDetail%26networkId%3D33%26journeyId%3D4bcd0b9d-2c9d-42a2-8ffb-4508c952f4fb' ) assert ridesharing_journeys[0].pickup_place.addr == "" # address is not provided in mock assert ridesharing_journeys[0].pickup_place.lat == 48.1102 assert ridesharing_journeys[0].pickup_place.lon == -1.68623 assert ridesharing_journeys[0].dropoff_place.addr == "" # address is not provided in mock assert ridesharing_journeys[0].dropoff_place.lat == 48.02479 assert ridesharing_journeys[0].dropoff_place.lon == -1.74673 assert len(ridesharing_journeys[0].shape) > 3 assert ridesharing_journeys[0].shape[0].lat == ridesharing_journeys[0].pickup_place.lat assert ridesharing_journeys[0].shape[0].lon == ridesharing_journeys[0].pickup_place.lon assert ridesharing_journeys[0].shape[1].lat == 48.1101 # test that we really load a shape assert ridesharing_journeys[0].shape[1].lon == -1.68635 assert ridesharing_journeys[0].shape[-1].lat == ridesharing_journeys[0].dropoff_place.lat assert ridesharing_journeys[0].shape[-1].lon == ridesharing_journeys[0].dropoff_place.lon assert ridesharing_journeys[0].pickup_date_time == utils.str_to_time_stamp("20171225T070759") assert ridesharing_journeys[0].dropoff_date_time == utils.str_to_time_stamp("20171225T072536") assert ridesharing_journeys[0].driver.alias == 'Jean P.' assert ridesharing_journeys[0].driver.gender == Gender.MALE assert ridesharing_journeys[0].driver.image == 'https://dummyimage.com/128x128/C8E6C9/000.png&text=JP' assert ridesharing_journeys[0].driver.rate == 0 assert ridesharing_journeys[0].driver.rate_count == 0 assert ridesharing_journeys[0].price == 170 assert ridesharing_journeys[0].currency == 'centime' assert ridesharing_journeys[0].total_seats is None assert ridesharing_journeys[0].available_seats == 4 assert ridesharing_journeys[1].metadata.network == 'dummyNetwork' assert ridesharing_journeys[1].metadata.system_id == 'Instant System' assert ridesharing_journeys[1].metadata.rating_scale_min == 0 assert ridesharing_journeys[1].metadata.rating_scale_max == 10 # the shape should not be none, but we don't test the whole string assert ridesharing_journeys[1].shape assert ( ridesharing_journeys[1].ridesharing_ad == "https://jky8k.app.goo.gl/?efr=1&apn=com.is.android.rennes&ibi=&isi=&utm_campaign=KISIO&link=https%3A%2F%2Fwww.star.fr%2Fsearch%2F%3FfeatureName%3DsearchResultDetail%26networkId%3D33%26journeyId%3D05223c04-834d-4710-905f-aa3796da5837" ) assert ridesharing_journeys[1].pickup_place.addr == "" assert ridesharing_journeys[1].pickup_place.lat == 48.1102 assert ridesharing_journeys[1].pickup_place.lon == -1.68623 assert ridesharing_journeys[1].dropoff_place.addr == "" assert ridesharing_journeys[1].dropoff_place.lat == 48.03193 assert ridesharing_journeys[1].dropoff_place.lon == -1.74635 assert ridesharing_journeys[1].pickup_date_time == utils.str_to_time_stamp("20171225T073542") assert ridesharing_journeys[1].dropoff_date_time == utils.str_to_time_stamp("20171225T075309") assert ridesharing_journeys[1].driver.alias == 'Alice M.' assert ridesharing_journeys[1].driver.gender == Gender.FEMALE assert ridesharing_journeys[1].driver.image == 'https://dummyimage.com/128x128/B2EBF2/000.png&text=AM' assert ridesharing_journeys[1].driver.rate == 0 assert ridesharing_journeys[1].driver.rate_count == 0 assert ridesharing_journeys[1].price == 0 assert ridesharing_journeys[1].currency == 'centime' assert ridesharing_journeys[1].total_seats is None assert ridesharing_journeys[1].available_seats == 4 assert feed_publisher == RsFeedPublisher(**DUMMY_INSTANT_SYSTEM_FEED_PUBLISHER) import requests_mock import pytest def test_request_journeys_should_raise_on_non_200(): with requests_mock.Mocker() as mock: instant_system = InstantSystem( DummyInstance(), service_url='http://instant.sys', api_key='ApiKey', network='Network' ) mock.get('http://instant.sys', status_code=401, text='{this is the http response}') with pytest.raises(RidesharingServiceError) as e: instant_system._request_journeys( '1.2,3.4', '5.6,7.8', utils.PeriodExtremity(<|fim▁hole|> datetime=utils.str_to_time_stamp("20171225T060000"), represents_start=True ), ) exception_params = e.value.get_params().values() assert 401 in exception_params assert '{this is the http response}' in exception_params<|fim▁end|>
<|file_name|>client.go<|end_file_name|><|fim▁begin|>package ec2 import ( "encoding/base64" "encoding/xml" "fmt" "net/url" "strconv" "strings" "github.com/dynport/gocloud/aws" ) func NewFromEnv() *Client { return &Client{ aws.NewFromEnv(), } } type Client struct { *aws.Client } func (client *Client) Endpoint() string { prefix := "https://" if client.Client.Region != "" { prefix += client.Client.Region + "." } return prefix + "ec2.amazonaws.com" } const ( API_VERSIONS_EC2 = "2013-08-15" CANONICAL_OWNER_ID = "099720109477" SELF_OWNER_ID = "self" UBUNTU_ALL = "ubuntu/images/*" UBUNTU_PREFIX = "ubuntu-*" UBUNTU_RARING_PREFIX = "ubuntu-raring*" UBUNTU_TRUSTY_PREFIX = "ubuntu-trusty*" UBUNTU_SAUCY_PREFIX = "ubuntu-saucy*" ImagePrefixRaringAmd64 = "ubuntu-raring-13.04-amd64*" ) type ImageFilter struct { Owner string Name string ImageIds []string } type ImageList []*Image type InstanceList []*Instance func (list ImageList) Len() int { return len(list) } func (list ImageList) Swap(a, b int) { list[a], list[b] = list[b], list[a] } func (list ImageList) Less(a, b int) bool { return list[a].Name > list[b].Name } type RunInstancesConfig struct { ImageId string `json:",omitempty"` MinCount int `json:",omitempty"` MaxCount int `json:",omitempty"` InstanceType string `json:",omitempty"` AvailabilityZone string `json:",omitempty"` KeyName string `json:",omitempty"` SecurityGroups []string `json:",omitempty"` SubnetId string `json:",omitempty"` NetworkInterfaces []*CreateNetworkInterface `json:",omitempty"` BlockDeviceMappings []*BlockDeviceMapping `json:",omitempty"` UserData string `json:",omitempty"` IamInstanceProfileName string `json:",omitempty"` EbsOptimized bool `json:",omitempty"` } func (config *RunInstancesConfig) Values() (url.Values, error) { values := url.Values{} if config.MinCount == 0 { config.MinCount = 1 } if config.MaxCount == 0 { config.MaxCount = 1 } if config.ImageId == "" { return nil, fmt.Errorf("ImageId must be provided") } values.Add("MinCount", strconv.Itoa(config.MinCount)) values.Add("MaxCount", strconv.Itoa(config.MaxCount)) values.Add("ImageId", config.ImageId) if config.EbsOptimized { values.Add("EbsOptimized", "true") } if config.UserData != "" { values.Add("UserData", b64.EncodeToString([]byte(config.UserData))) } if config.IamInstanceProfileName != "" { values.Add("IamInstanceProfile.Name", config.IamInstanceProfileName) } if config.InstanceType != "" { values.Add("InstanceType", config.InstanceType) } if config.KeyName != "" { values.Add("KeyName", config.KeyName) } if config.AvailabilityZone != "" { values.Add("Placement.AvailabilityZone", config.AvailabilityZone) } if len(config.NetworkInterfaces) > 0 { for i, nic := range config.NetworkInterfaces { idx := strconv.Itoa(i) values.Add("NetworkInterface."+idx+".DeviceIndex", idx) values.Add("NetworkInterface."+idx+".AssociatePublicIpAddress", "true") values.Add("NetworkInterface."+idx+".SubnetId", nic.SubnetId) for i, sg := range nic.SecurityGroupIds { values.Add("NetworkInterface."+idx+".SecurityGroupId."+strconv.Itoa(i), sg) } } } else { for i, sg := range config.SecurityGroups { values.Add("SecurityGroupId."+strconv.Itoa(i+1), sg) } values.Add("SubnetId", config.SubnetId) } for i, bdm := range config.BlockDeviceMappings { prefix := fmt.Sprintf("BlockDeviceMapping.%d", i) if bdm.DeviceName == "" { return nil, fmt.Errorf("DeviceName must be set for all BlockDeviceMappings") } values.Add(prefix+".DeviceName", bdm.DeviceName) if ebs := bdm.Ebs; ebs != nil { prefix := prefix + ".Ebs" if ebs.VolumeSize > 0 { values.Add(prefix+".VolumeSize", strconv.Itoa(ebs.VolumeSize)) } if ebs.Iops > 0 { values.Add(prefix+".Iops", strconv.Itoa(ebs.Iops)) } if ebs.DeleteOnTermination { values.Add(prefix+".DeleteOnTermination", "true") } if ebs.Encrypted { values.Add(prefix+".Encrypted", "true") } if ebs.SnapshotId != "" { values.Add(prefix+".SnapshotId", ebs.SnapshotId) }<|fim▁hole|> } return values, nil } func (config *RunInstancesConfig) AddPublicIp() error { if config.SubnetId == "" { return fmt.Errorf("SubnetId must be set") } nic := &CreateNetworkInterface{ DeviceIndex: len(config.NetworkInterfaces), AssociatePublicIpAddress: true, SubnetId: config.SubnetId, SecurityGroupIds: config.SecurityGroups, } config.NetworkInterfaces = []*CreateNetworkInterface{nic} return nil } func queryForAction(action string) string { values := &url.Values{} values.Add("Version", API_VERSIONS_EC2) values.Add("Action", action) return values.Encode() } func (client *Client) DescribeTags() (tags TagList, e error) { query := queryForAction("DescribeTags") raw, e := client.DoSignedRequest("GET", client.Endpoint(), query, nil) if e != nil { return tags, e } rsp := &DescribeTagsResponse{} e = xml.Unmarshal(raw.Content, rsp) if e != nil { return tags, e } return rsp.Tags, e } func (client *Client) CreateTags(resourceIds []string, tags map[string]string) error { values := &url.Values{} for i, id := range resourceIds { values.Add("ResourceId."+strconv.Itoa(i), id) } tagsCount := 1 for k, v := range tags { prefix := fmt.Sprintf("Tag.%d.", tagsCount) values.Add(prefix+"Key", k) values.Add(prefix+"Value", v) tagsCount++ } query := queryForAction("CreateTags") + "&" + values.Encode() _, e := client.DoSignedRequest("POST", client.Endpoint(), query, nil) if e != nil { return e } return nil } func (client *Client) TerminateInstances(ids []string) (*aws.Response, error) { query := queryForAction("TerminateInstances") for i, id := range ids { query += fmt.Sprintf("&InstanceId.%d=%s", i, id) } return client.DoSignedRequest("DELETE", client.Endpoint(), query, nil) } type Error struct { Code string `xml:"Code"` Message string `xml:"Message"` } type ErrorResponse struct { XMLName xml.Name `xml:"Response"` RequestID string `xml:"RequestID"` Errors []*Error `xml:"Errors>Error"` } func (er *ErrorResponse) ErrorStrings() string { out := []string{} for _, e := range er.Errors { out = append(out, fmt.Sprintf("%s: %s", e.Code, e.Message)) } return strings.Join(out, ", ") } type RunInstancesResponse struct { XMLName xml.Name `xml:"RunInstancesResponse"` RequestId string `xml:"requestId"` ReservationId string `xml:"reservationId"` OwnerId string `xml:"ownerId"` Instances []*Instance `xml:"instancesSet>item"` } var b64 = base64.StdEncoding func (client *Client) RunInstances(config *RunInstancesConfig) (list InstanceList, e error) { values, e := config.Values() if e != nil { return nil, e } query := queryForAction("RunInstances") + "&" + values.Encode() raw, e := client.DoSignedRequest("POST", client.Endpoint(), query, nil) if e != nil { return list, e } er := &ErrorResponse{} if e := xml.Unmarshal(raw.Content, er); e == nil { return nil, fmt.Errorf(er.ErrorStrings()) } rsp := &RunInstancesResponse{} e = xml.Unmarshal(raw.Content, rsp) if e != nil { return list, e } return InstanceList(rsp.Instances), nil } type DescribeInstancesOptions struct { InstanceIds []string Filters []*Filter } func (client *Client) DescribeInstancesWithOptions(options *DescribeInstancesOptions) (instances []*Instance, e error) { if options == nil { options = &DescribeInstancesOptions{} } values := url.Values{"Version": {API_VERSIONS_EC2}, "Action": {"DescribeInstances"}} if len(options.InstanceIds) > 0 { for i, id := range options.InstanceIds { values.Add("InstanceId."+strconv.Itoa(i+1), id) } } applyFilters(values, options.Filters) raw, e := client.DoSignedRequest("GET", client.Endpoint(), values.Encode(), nil) if e != nil { return instances, e } rsp := &DescribeInstancesResponse{} e = xml.Unmarshal(raw.Content, rsp) if e != nil { e = fmt.Errorf("%s: %s", e.Error(), string(raw.Content)) return instances, e } return rsp.Instances(), nil } func (client *Client) DescribeInstances() (instances []*Instance, e error) { return client.DescribeInstancesWithOptions(nil) }<|fim▁end|>
if ebs.VolumeType != "" { values.Add(prefix+".VolumeType", ebs.VolumeType) } }
<|file_name|>test_cli.py<|end_file_name|><|fim▁begin|># Copyright The Cloud Custodian Authors. # SPDX-License-Identifier: Apache-2.0 import json import os import sys from argparse import ArgumentTypeError from datetime import datetime, timedelta from c7n import cli, version, commands from c7n.resolver import ValuesFrom from c7n.resources import aws from c7n.schema import ElementSchema, generate from c7n.utils import yaml_dump, yaml_load from .common import BaseTest, TextTestIO class CliTest(BaseTest): """ A subclass of BaseTest with some handy functions for CLI related tests. """ def patch_account_id(self): def test_account_id(options): options.account_id = self.account_id self.patch(aws, "_default_account_id", test_account_id) def get_output(self, argv): """ Run cli.main with the supplied argv and return the output. """ out, err = self.run_and_expect_success(argv) return out def capture_output(self): out = TextTestIO() err = TextTestIO() self.patch(sys, "stdout", out) self.patch(sys, "stderr", err) return out, err def run_and_expect_success(self, argv): """ Run cli.main() with supplied argv and expect normal execution. """ self.patch_account_id() self.patch(sys, "argv", argv) out, err = self.capture_output() try: cli.main() except SystemExit as e: self.fail( "Expected sys.exit would not be called. Exit code was ({})".format( e.code ) ) return out.getvalue(), err.getvalue() def run_and_expect_failure(self, argv, exit_code): """ Run cli.main() with supplied argv and expect exit_code. """ self.patch_account_id() self.patch(sys, "argv", argv) out, err = self.capture_output() # clear_resources() with self.assertRaises(SystemExit) as cm: cli.main() self.assertEqual(cm.exception.code, exit_code) return out.getvalue(), err.getvalue() def run_and_expect_exception(self, argv, exception): """ Run cli.main() with supplied argv and expect supplied exception. """ self.patch_account_id() self.patch(sys, "argv", argv) # clear_resources() try: cli.main() except exception: return self.fail("Error: did not raise {}.".format(exception)) class UtilsTest(BaseTest): def test_key_val_pair(self): self.assertRaises(ArgumentTypeError, cli._key_val_pair, "invalid option") param = "day=today" self.assertIs(cli._key_val_pair(param), param) class VersionTest(CliTest): def test_version(self): output = self.get_output(["custodian", "version"]) self.assertEqual(output.strip(), version.version) def test_debug_version(self): output = self.get_output(["custodian", "version", "--debug"]) self.assertIn(version.version, output) self.assertIn('botocore==', output) self.assertIn('python-dateutil==', output) class ValidateTest(CliTest): def test_invalidate_structure_exit(self): invalid_policies = {"policies": [{"name": "foo"}]} yaml_file = self.write_policy_file(invalid_policies) self.run_and_expect_failure(["custodian", "validate", yaml_file], 1) def test_validate(self): invalid_policies = { "policies": [ { "name": "foo", "resource": "s3", "filters": [{"tag:custodian_tagging": "not-null"}], "actions": [ {"type": "untag", "tags": {"custodian_cleanup": "yes"}} ], } ] } yaml_file = self.write_policy_file(invalid_policies) json_file = self.write_policy_file(invalid_policies, format="json") # YAML validation self.run_and_expect_exception(["custodian", "validate", yaml_file], SystemExit) # JSON validation self.run_and_expect_failure(["custodian", "validate", json_file], 1) # no config files given self.run_and_expect_failure(["custodian", "validate"], 1) # nonexistent file given self.run_and_expect_exception( ["custodian", "validate", "fake.yaml"], ValueError ) valid_policies = { "policies": [ { "name": "foo", "resource": "s3", "filters": [{"tag:custodian_tagging": "not-null"}], "actions": [{"type": "tag", "tags": {"custodian_cleanup": "yes"}}], } ] } yaml_file = self.write_policy_file(valid_policies) self.run_and_expect_success(["custodian", "validate", yaml_file]) # legacy -c option self.run_and_expect_success(["custodian", "validate", "-c", yaml_file]) # duplicate policy names self.run_and_expect_failure(["custodian", "validate", yaml_file, yaml_file], 1) class SchemaTest(CliTest): def test_schema_outline(self): stdout, stderr = self.run_and_expect_success([ "custodian", "schema", "--outline", "--json", "aws"]) data = json.loads(stdout) self.assertEqual(list(data.keys()), ["aws"]) self.assertTrue(len(data['aws']) > 100) self.assertEqual( sorted(data['aws']['aws.ec2'].keys()), ['actions', 'filters']) self.assertTrue(len(data['aws']['aws.ec2']['actions']) > 10) def test_schema_alias(self): stdout, stderr = self.run_and_expect_success([ "custodian", "schema", "aws.network-addr"]) self.assertIn("aws.elastic-ip:", stdout) def test_schema_alias_unqualified(self): stdout, stderr = self.run_and_expect_success([ "custodian", "schema", "network-addr"]) self.assertIn("aws.elastic-ip:", stdout) def test_schema(self): # no options stdout, stderr = self.run_and_expect_success(["custodian", "schema"]) data = yaml_load(stdout) assert data['resources'] # summary option self.run_and_expect_success(["custodian", "schema", "--summary"]) # json option self.run_and_expect_success(["custodian", "schema", "--json"]) # with just a cloud self.run_and_expect_success(["custodian", "schema", "aws"]) # with just a resource self.run_and_expect_success(["custodian", "schema", "ec2"]) # with just a mode self.run_and_expect_success(["custodian", "schema", "mode"]) # mode.type self.run_and_expect_success(["custodian", "schema", "mode.phd"]) # resource.actions self.run_and_expect_success(["custodian", "schema", "ec2.actions"]) # resource.filters self.run_and_expect_success(["custodian", "schema", "ec2.filters"]) # specific item self.run_and_expect_success(["custodian", "schema", "ec2.filters.tag-count"]) def test_invalid_options(self): # invalid resource self.run_and_expect_failure(["custodian", "schema", "fakeresource"], 1) # invalid category self.run_and_expect_failure(["custodian", "schema", "ec2.arglbargle"], 1) # invalid item self.run_and_expect_failure( ["custodian", "schema", "ec2.filters.nonexistent"], 1 ) # invalid number of selectors self.run_and_expect_failure(["custodian", "schema", "ec2.filters.and.foo"], 1) def test_schema_output(self): output = self.get_output(["custodian", "schema"]) self.assertIn("aws.ec2", output) # self.assertIn("azure.vm", output) # self.assertIn("gcp.instance", output) output = self.get_output(["custodian", "schema", "aws"]) self.assertIn("aws.ec2", output) self.assertNotIn("azure.vm", output) self.assertNotIn("gcp.instance", output) output = self.get_output(["custodian", "schema", "aws.ec2"]) self.assertIn("actions:", output) self.assertIn("filters:", output) output = self.get_output(["custodian", "schema", "ec2"]) self.assertIn("actions:", output) self.assertIn("filters:", output) output = self.get_output(["custodian", "schema", "ec2.filters"]) self.assertNotIn("actions:", output) self.assertIn("filters:", output) output = self.get_output(["custodian", "schema", "ec2.filters.image"]) self.assertIn("Help", output) def test_schema_expand(self): # refs should only ever exist in a dictionary by itself test_schema = { '$ref': '#/definitions/filters_common/value_from' } result = ElementSchema.schema(generate()['definitions'], test_schema) self.assertEqual(result, ValuesFrom.schema) def test_schema_multi_expand(self): test_schema = { 'schema1': { '$ref': '#/definitions/filters_common/value_from' }, 'schema2': { '$ref': '#/definitions/filters_common/value_from' } } expected = yaml_dump({ 'schema1': { 'type': 'object', 'additionalProperties': 'False', 'required': ['url'], 'properties': { 'url': {'type': 'string'}, 'format': {'enum': ['csv', 'json', 'txt', 'csv2dict']}, 'expr': {'oneOf': [ {'type': 'integer'}, {'type': 'string'}]} } }, 'schema2': { 'type': 'object', 'additionalProperties': 'False', 'required': ['url'], 'properties': { 'url': {'type': 'string'}, 'format': {'enum': ['csv', 'json', 'txt', 'csv2dict']}, 'expr': {'oneOf': [ {'type': 'integer'}, {'type': 'string'}]} } } }) result = yaml_dump(ElementSchema.schema(generate()['definitions'], test_schema)) self.assertEqual(result, expected) def test_schema_expand_not_found(self): test_schema = { '$ref': '#/definitions/filters_common/invalid_schema' } result = ElementSchema.schema(generate()['definitions'], test_schema) self.assertEqual(result, None) class ReportTest(CliTest): def test_report(self): policy_name = "ec2-running-instances" valid_policies = { "policies": [ { "name": policy_name, "resource": "ec2", "query": [{"instance-state-name": "running"}], } ] } yaml_file = self.write_policy_file(valid_policies) output = self.get_output( ["custodian", "report", "-s", self.output_dir, yaml_file] ) self.assertIn("InstanceId", output) self.assertIn("i-014296505597bf519", output) # ASCII formatted test output = self.get_output( [ "custodian", "report", "--format", "grid", "-s", self.output_dir, yaml_file, ] ) self.assertIn("InstanceId", output) self.assertIn("i-014296505597bf519", output) # json format output = self.get_output( ["custodian", "report", "--format", "json", "-s", self.output_dir, yaml_file] ) self.assertTrue("i-014296505597bf519", json.loads(output)[0]['InstanceId']) # empty file temp_dir = self.get_temp_dir() empty_policies = {"policies": []} yaml_file = self.write_policy_file(empty_policies) self.run_and_expect_failure( ["custodian", "report", "-s", temp_dir, yaml_file], 1 ) # more than 1 policy policies = { "policies": [ {"name": "foo", "resource": "s3"}, {"name": "bar", "resource": "ec2"} ] } yaml_file = self.write_policy_file(policies) self.run_and_expect_failure( ["custodian", "report", "-s", temp_dir, yaml_file], 1 ) def test_warning_on_empty_policy_filter(self): # This test is to examine the warning output supplied when -p is used and # the resulting policy set is empty. It is not specific to the `report` # subcommand - it is also used by `run` and a few other subcommands.<|fim▁hole|> policy_name = "test-policy" valid_policies = { "policies": [ { "name": policy_name, "resource": "s3", "filters": [{"tag:custodian_tagging": "not-null"}], } ] } yaml_file = self.write_policy_file(valid_policies) temp_dir = self.get_temp_dir() bad_policy_name = policy_name + "-nonexistent" log_output = self.capture_logging("custodian.commands") self.run_and_expect_failure( ["custodian", "report", "-s", temp_dir, "-p", bad_policy_name, yaml_file], 1 ) self.assertIn(policy_name, log_output.getvalue()) bad_resource_name = "foo" self.run_and_expect_failure( ["custodian", "report", "-s", temp_dir, "-t", bad_resource_name, yaml_file], 1, ) class LogsTest(CliTest): def test_logs(self): temp_dir = self.get_temp_dir() # Test 1 - empty file empty_policies = {"policies": []} yaml_file = self.write_policy_file(empty_policies) self.run_and_expect_failure(["custodian", "logs", "-s", temp_dir, yaml_file], 1) # Test 2 - more than one policy policies = { "policies": [ {"name": "foo", "resource": "s3"}, {"name": "bar", "resource": "ec2"} ] } yaml_file = self.write_policy_file(policies) self.run_and_expect_failure(["custodian", "logs", "-s", temp_dir, yaml_file], 1) # Test 3 - successful test p_data = { "name": "test-policy", "resource": "rds", "filters": [ {"key": "GroupName", "type": "security-group", "value": "default"} ], "actions": [{"days": 10, "type": "retention"}], } yaml_file = self.write_policy_file({"policies": [p_data]}) output_dir = os.path.join(os.path.dirname(__file__), "data", "logs") self.run_and_expect_failure(["custodian", "logs", "-s", output_dir, yaml_file], 1) class RunTest(CliTest): def test_ec2(self): session_factory = self.replay_flight_data( "test_ec2_state_transition_age_filter" ) from c7n.policy import PolicyCollection self.patch( PolicyCollection, "session_factory", staticmethod(lambda x=None: session_factory), ) temp_dir = self.get_temp_dir() yaml_file = self.write_policy_file( { "policies": [ { "name": "ec2-state-transition-age", "resource": "ec2", "filters": [ {"State.Name": "running"}, {"type": "state-age", "days": 30} ], } ] } ) # TODO - capture logging and ensure the following # self.assertIn('Running policy ec2-state-transition-age', logs) # self.assertIn('metric:ResourceCount Count:1 policy:ec2-state-transition-age', logs) self.run_and_expect_success( [ "custodian", "run", "--cache", temp_dir + "/cache", "-s", temp_dir, yaml_file, ] ) def test_error(self): from c7n.policy import Policy self.patch( Policy, "__call__", lambda x: (_ for _ in ()).throw(Exception("foobar")) ) # # Make sure that if the policy causes an exception we error out # temp_dir = self.get_temp_dir() yaml_file = self.write_policy_file( { "policies": [ { "name": "error", "resource": "ec2", "filters": [ {"State.Name": "running"}, {"type": "state-age", "days": 30} ], } ] } ) self.run_and_expect_failure( [ "custodian", "run", "--cache", temp_dir + "/cache", "-s", temp_dir, yaml_file, ], 2, ) # # Test --debug # class CustomError(Exception): pass import pdb self.patch(pdb, "post_mortem", lambda x: (_ for _ in ()).throw(CustomError)) self.run_and_expect_exception( ["custodian", "run", "-s", temp_dir, "--debug", yaml_file], CustomError ) class MetricsTest(CliTest): def test_metrics(self): session_factory = self.replay_flight_data("test_lambda_policy_metrics") from c7n.policy import PolicyCollection self.patch( PolicyCollection, "session_factory", staticmethod(lambda x=None: session_factory), ) yaml_file = self.write_policy_file( { "policies": [ { "name": "ec2-tag-compliance-v6", "resource": "ec2", "mode": {"type": "ec2-instance-state", "events": ["running"]}, "filters": [ {"tag:custodian_status": "absent"}, { "or": [ {"tag:App": "absent"}, {"tag:Env": "absent"}, {"tag:Owner": "absent"}, ] }, ], } ] } ) end = datetime.utcnow() start = end - timedelta(14) period = 24 * 60 * 60 * 14 self.run_and_expect_failure( [ "custodian", "metrics", "--start", str(start), "--end", str(end), "--period", str(period), yaml_file, ], 1 ) def test_metrics_get_endpoints(self): # # Test for defaults when --start is not supplied # class FakeOptions: start = end = None days = 5 options = FakeOptions() start, end = commands._metrics_get_endpoints(options) self.assertEqual((end - start).days, options.days) # # Test that --start and --end have to be passed together # policy = { "policies": [ { "name": "metrics-test", "resource": "ec2", "query": [{"instance-state-name": "running"}], } ] } yaml_file = self.write_policy_file(policy) self.run_and_expect_failure( ["custodian", "metrics", "--start", "1", yaml_file], 1 ) class MiscTest(CliTest): def test_no_args(self): stdout, stderr = self.run_and_expect_failure(["custodian"], 2) self.assertIn("metrics", stderr) self.assertIn("logs", stderr) def test_empty_policy_file(self): # Doesn't do anything, but should exit 0 temp_dir = self.get_temp_dir() yaml_file = self.write_policy_file({}) self.run_and_expect_failure( ["custodian", "run", "-s", temp_dir, yaml_file], 1) def test_nonexistent_policy_file(self): temp_dir = self.get_temp_dir() yaml_file = self.write_policy_file({}) nonexistent = yaml_file + ".bad" self.run_and_expect_failure( ["custodian", "run", "-s", temp_dir, yaml_file, nonexistent], 1 ) def test_duplicate_policy(self): policy = { "policies": [ { "name": "metrics-test", "resource": "ec2", "query": [{"instance-state-name": "running"}], } ] } temp_dir = self.get_temp_dir() yaml_file = self.write_policy_file(policy) self.run_and_expect_failure( ["custodian", "run", "-s", temp_dir, yaml_file, yaml_file], 1 ) def test_failure_with_no_default_region(self): policy = {"policies": [{"name": "will-never-run", "resource": "ec2"}]} temp_dir = self.get_temp_dir() yaml_file = self.write_policy_file(policy) self.patch(aws, "get_profile_session", lambda x: None) self.run_and_expect_failure(["custodian", "run", "-s", temp_dir, yaml_file], 1)<|fim▁end|>
<|file_name|>performance_lun_metric.go<|end_file_name|><|fim▁begin|>// Code generated by go-swagger; DO NOT EDIT. package models // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "context" "encoding/json" "github.com/go-openapi/errors" "github.com/go-openapi/strfmt" "github.com/go-openapi/swag" "github.com/go-openapi/validate" ) // PerformanceLunMetric Performance numbers, such as IOPS latency and throughput. // // swagger:model performance_lun_metric type PerformanceLunMetric struct { // links Links *PerformanceLunMetricLinks `json:"_links,omitempty"` // The duration over which this sample is calculated. The time durations are represented in the ISO-8601 standard format. Samples can be calculated over the following durations: // // Example: PT15S // Read Only: true // Enum: [PT15S PT4M PT30M PT2H P1D PT5M] Duration string `json:"duration,omitempty"` // iops Iops *PerformanceLunMetricIops `json:"iops,omitempty"` // latency Latency *PerformanceLunMetricLatency `json:"latency,omitempty"` // Errors associated with the sample. For example, if the aggregation of data over multiple nodes fails, then any partial errors might return "ok" on success or "error" on an internal uncategorized failure. Whenever a sample collection is missed but done at a later time, it is back filled to the previous 15 second timestamp and tagged with "backfilled_data". "Inconsistent_ delta_time" is encountered when the time between two collections is not the same for all nodes. Therefore, the aggregated value might be over or under inflated. "Negative_delta" is returned when an expected monotonically increasing value has decreased in value. "Inconsistent_old_data" is returned when one or more nodes do not have the latest data. // Example: ok // Read Only: true // Enum: [ok error partial_no_data partial_no_response partial_other_error negative_delta not_found backfilled_data inconsistent_delta_time inconsistent_old_data partial_no_uuid] Status string `json:"status,omitempty"` // throughput Throughput *PerformanceLunMetricThroughput `json:"throughput,omitempty"` // The timestamp of the performance data. // Example: 2017-01-25T11:20:13Z // Read Only: true // Format: date-time Timestamp *strfmt.DateTime `json:"timestamp,omitempty"` // The unique identifier of the LUN. // // Example: 1cd8a442-86d1-11e0-ae1c-123478563412 // Read Only: true UUID string `json:"uuid,omitempty"` } // Validate validates this performance lun metric func (m *PerformanceLunMetric) Validate(formats strfmt.Registry) error { var res []error if err := m.validateLinks(formats); err != nil { res = append(res, err) } if err := m.validateDuration(formats); err != nil { res = append(res, err) } if err := m.validateIops(formats); err != nil { res = append(res, err) }<|fim▁hole|> if err := m.validateLatency(formats); err != nil { res = append(res, err) } if err := m.validateStatus(formats); err != nil { res = append(res, err) } if err := m.validateThroughput(formats); err != nil { res = append(res, err) } if err := m.validateTimestamp(formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *PerformanceLunMetric) validateLinks(formats strfmt.Registry) error { if swag.IsZero(m.Links) { // not required return nil } if m.Links != nil { if err := m.Links.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("_links") } return err } } return nil } var performanceLunMetricTypeDurationPropEnum []interface{} func init() { var res []string if err := json.Unmarshal([]byte(`["PT15S","PT4M","PT30M","PT2H","P1D","PT5M"]`), &res); err != nil { panic(err) } for _, v := range res { performanceLunMetricTypeDurationPropEnum = append(performanceLunMetricTypeDurationPropEnum, v) } } const ( // BEGIN DEBUGGING // performance_lun_metric // PerformanceLunMetric // duration // Duration // PT15S // END DEBUGGING // PerformanceLunMetricDurationPT15S captures enum value "PT15S" PerformanceLunMetricDurationPT15S string = "PT15S" // BEGIN DEBUGGING // performance_lun_metric // PerformanceLunMetric // duration // Duration // PT4M // END DEBUGGING // PerformanceLunMetricDurationPT4M captures enum value "PT4M" PerformanceLunMetricDurationPT4M string = "PT4M" // BEGIN DEBUGGING // performance_lun_metric // PerformanceLunMetric // duration // Duration // PT30M // END DEBUGGING // PerformanceLunMetricDurationPT30M captures enum value "PT30M" PerformanceLunMetricDurationPT30M string = "PT30M" // BEGIN DEBUGGING // performance_lun_metric // PerformanceLunMetric // duration // Duration // PT2H // END DEBUGGING // PerformanceLunMetricDurationPT2H captures enum value "PT2H" PerformanceLunMetricDurationPT2H string = "PT2H" // BEGIN DEBUGGING // performance_lun_metric // PerformanceLunMetric // duration // Duration // P1D // END DEBUGGING // PerformanceLunMetricDurationP1D captures enum value "P1D" PerformanceLunMetricDurationP1D string = "P1D" // BEGIN DEBUGGING // performance_lun_metric // PerformanceLunMetric // duration // Duration // PT5M // END DEBUGGING // PerformanceLunMetricDurationPT5M captures enum value "PT5M" PerformanceLunMetricDurationPT5M string = "PT5M" ) // prop value enum func (m *PerformanceLunMetric) validateDurationEnum(path, location string, value string) error { if err := validate.EnumCase(path, location, value, performanceLunMetricTypeDurationPropEnum, true); err != nil { return err } return nil } func (m *PerformanceLunMetric) validateDuration(formats strfmt.Registry) error { if swag.IsZero(m.Duration) { // not required return nil } // value enum if err := m.validateDurationEnum("duration", "body", m.Duration); err != nil { return err } return nil } func (m *PerformanceLunMetric) validateIops(formats strfmt.Registry) error { if swag.IsZero(m.Iops) { // not required return nil } if m.Iops != nil { if err := m.Iops.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("iops") } return err } } return nil } func (m *PerformanceLunMetric) validateLatency(formats strfmt.Registry) error { if swag.IsZero(m.Latency) { // not required return nil } if m.Latency != nil { if err := m.Latency.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("latency") } return err } } return nil } var performanceLunMetricTypeStatusPropEnum []interface{} func init() { var res []string if err := json.Unmarshal([]byte(`["ok","error","partial_no_data","partial_no_response","partial_other_error","negative_delta","not_found","backfilled_data","inconsistent_delta_time","inconsistent_old_data","partial_no_uuid"]`), &res); err != nil { panic(err) } for _, v := range res { performanceLunMetricTypeStatusPropEnum = append(performanceLunMetricTypeStatusPropEnum, v) } } const ( // BEGIN DEBUGGING // performance_lun_metric // PerformanceLunMetric // status // Status // ok // END DEBUGGING // PerformanceLunMetricStatusOk captures enum value "ok" PerformanceLunMetricStatusOk string = "ok" // BEGIN DEBUGGING // performance_lun_metric // PerformanceLunMetric // status // Status // error // END DEBUGGING // PerformanceLunMetricStatusError captures enum value "error" PerformanceLunMetricStatusError string = "error" // BEGIN DEBUGGING // performance_lun_metric // PerformanceLunMetric // status // Status // partial_no_data // END DEBUGGING // PerformanceLunMetricStatusPartialNoData captures enum value "partial_no_data" PerformanceLunMetricStatusPartialNoData string = "partial_no_data" // BEGIN DEBUGGING // performance_lun_metric // PerformanceLunMetric // status // Status // partial_no_response // END DEBUGGING // PerformanceLunMetricStatusPartialNoResponse captures enum value "partial_no_response" PerformanceLunMetricStatusPartialNoResponse string = "partial_no_response" // BEGIN DEBUGGING // performance_lun_metric // PerformanceLunMetric // status // Status // partial_other_error // END DEBUGGING // PerformanceLunMetricStatusPartialOtherError captures enum value "partial_other_error" PerformanceLunMetricStatusPartialOtherError string = "partial_other_error" // BEGIN DEBUGGING // performance_lun_metric // PerformanceLunMetric // status // Status // negative_delta // END DEBUGGING // PerformanceLunMetricStatusNegativeDelta captures enum value "negative_delta" PerformanceLunMetricStatusNegativeDelta string = "negative_delta" // BEGIN DEBUGGING // performance_lun_metric // PerformanceLunMetric // status // Status // not_found // END DEBUGGING // PerformanceLunMetricStatusNotFound captures enum value "not_found" PerformanceLunMetricStatusNotFound string = "not_found" // BEGIN DEBUGGING // performance_lun_metric // PerformanceLunMetric // status // Status // backfilled_data // END DEBUGGING // PerformanceLunMetricStatusBackfilledData captures enum value "backfilled_data" PerformanceLunMetricStatusBackfilledData string = "backfilled_data" // BEGIN DEBUGGING // performance_lun_metric // PerformanceLunMetric // status // Status // inconsistent_delta_time // END DEBUGGING // PerformanceLunMetricStatusInconsistentDeltaTime captures enum value "inconsistent_delta_time" PerformanceLunMetricStatusInconsistentDeltaTime string = "inconsistent_delta_time" // BEGIN DEBUGGING // performance_lun_metric // PerformanceLunMetric // status // Status // inconsistent_old_data // END DEBUGGING // PerformanceLunMetricStatusInconsistentOldData captures enum value "inconsistent_old_data" PerformanceLunMetricStatusInconsistentOldData string = "inconsistent_old_data" // BEGIN DEBUGGING // performance_lun_metric // PerformanceLunMetric // status // Status // partial_no_uuid // END DEBUGGING // PerformanceLunMetricStatusPartialNoUUID captures enum value "partial_no_uuid" PerformanceLunMetricStatusPartialNoUUID string = "partial_no_uuid" ) // prop value enum func (m *PerformanceLunMetric) validateStatusEnum(path, location string, value string) error { if err := validate.EnumCase(path, location, value, performanceLunMetricTypeStatusPropEnum, true); err != nil { return err } return nil } func (m *PerformanceLunMetric) validateStatus(formats strfmt.Registry) error { if swag.IsZero(m.Status) { // not required return nil } // value enum if err := m.validateStatusEnum("status", "body", m.Status); err != nil { return err } return nil } func (m *PerformanceLunMetric) validateThroughput(formats strfmt.Registry) error { if swag.IsZero(m.Throughput) { // not required return nil } if m.Throughput != nil { if err := m.Throughput.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("throughput") } return err } } return nil } func (m *PerformanceLunMetric) validateTimestamp(formats strfmt.Registry) error { if swag.IsZero(m.Timestamp) { // not required return nil } if err := validate.FormatOf("timestamp", "body", "date-time", m.Timestamp.String(), formats); err != nil { return err } return nil } // ContextValidate validate this performance lun metric based on the context it is used func (m *PerformanceLunMetric) ContextValidate(ctx context.Context, formats strfmt.Registry) error { var res []error if err := m.contextValidateLinks(ctx, formats); err != nil { res = append(res, err) } if err := m.contextValidateDuration(ctx, formats); err != nil { res = append(res, err) } if err := m.contextValidateIops(ctx, formats); err != nil { res = append(res, err) } if err := m.contextValidateLatency(ctx, formats); err != nil { res = append(res, err) } if err := m.contextValidateStatus(ctx, formats); err != nil { res = append(res, err) } if err := m.contextValidateThroughput(ctx, formats); err != nil { res = append(res, err) } if err := m.contextValidateTimestamp(ctx, formats); err != nil { res = append(res, err) } if err := m.contextValidateUUID(ctx, formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *PerformanceLunMetric) contextValidateLinks(ctx context.Context, formats strfmt.Registry) error { if m.Links != nil { if err := m.Links.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("_links") } return err } } return nil } func (m *PerformanceLunMetric) contextValidateDuration(ctx context.Context, formats strfmt.Registry) error { if err := validate.ReadOnly(ctx, "duration", "body", string(m.Duration)); err != nil { return err } return nil } func (m *PerformanceLunMetric) contextValidateIops(ctx context.Context, formats strfmt.Registry) error { if m.Iops != nil { if err := m.Iops.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("iops") } return err } } return nil } func (m *PerformanceLunMetric) contextValidateLatency(ctx context.Context, formats strfmt.Registry) error { if m.Latency != nil { if err := m.Latency.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("latency") } return err } } return nil } func (m *PerformanceLunMetric) contextValidateStatus(ctx context.Context, formats strfmt.Registry) error { if err := validate.ReadOnly(ctx, "status", "body", string(m.Status)); err != nil { return err } return nil } func (m *PerformanceLunMetric) contextValidateThroughput(ctx context.Context, formats strfmt.Registry) error { if m.Throughput != nil { if err := m.Throughput.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("throughput") } return err } } return nil } func (m *PerformanceLunMetric) contextValidateTimestamp(ctx context.Context, formats strfmt.Registry) error { if err := validate.ReadOnly(ctx, "timestamp", "body", m.Timestamp); err != nil { return err } return nil } func (m *PerformanceLunMetric) contextValidateUUID(ctx context.Context, formats strfmt.Registry) error { if err := validate.ReadOnly(ctx, "uuid", "body", string(m.UUID)); err != nil { return err } return nil } // MarshalBinary interface implementation func (m *PerformanceLunMetric) MarshalBinary() ([]byte, error) { if m == nil { return nil, nil } return swag.WriteJSON(m) } // UnmarshalBinary interface implementation func (m *PerformanceLunMetric) UnmarshalBinary(b []byte) error { var res PerformanceLunMetric if err := swag.ReadJSON(b, &res); err != nil { return err } *m = res return nil } // PerformanceLunMetricIops The rate of I/O operations observed at the storage object. // // swagger:model PerformanceLunMetricIops type PerformanceLunMetricIops struct { // Performance metric for other I/O operations. Other I/O operations can be metadata operations, such as directory lookups and so on. Other int64 `json:"other,omitempty"` // Performance metric for read I/O operations. // Example: 200 Read int64 `json:"read,omitempty"` // Performance metric aggregated over all types of I/O operations. // Example: 1000 Total int64 `json:"total,omitempty"` // Peformance metric for write I/O operations. // Example: 100 Write int64 `json:"write,omitempty"` } // Validate validates this performance lun metric iops func (m *PerformanceLunMetricIops) Validate(formats strfmt.Registry) error { return nil } // ContextValidate validate this performance lun metric iops based on the context it is used func (m *PerformanceLunMetricIops) ContextValidate(ctx context.Context, formats strfmt.Registry) error { var res []error if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } // MarshalBinary interface implementation func (m *PerformanceLunMetricIops) MarshalBinary() ([]byte, error) { if m == nil { return nil, nil } return swag.WriteJSON(m) } // UnmarshalBinary interface implementation func (m *PerformanceLunMetricIops) UnmarshalBinary(b []byte) error { var res PerformanceLunMetricIops if err := swag.ReadJSON(b, &res); err != nil { return err } *m = res return nil } // PerformanceLunMetricLatency The round trip latency in microseconds observed at the storage object. // // swagger:model PerformanceLunMetricLatency type PerformanceLunMetricLatency struct { // Performance metric for other I/O operations. Other I/O operations can be metadata operations, such as directory lookups and so on. Other int64 `json:"other,omitempty"` // Performance metric for read I/O operations. // Example: 200 Read int64 `json:"read,omitempty"` // Performance metric aggregated over all types of I/O operations. // Example: 1000 Total int64 `json:"total,omitempty"` // Peformance metric for write I/O operations. // Example: 100 Write int64 `json:"write,omitempty"` } // Validate validates this performance lun metric latency func (m *PerformanceLunMetricLatency) Validate(formats strfmt.Registry) error { return nil } // ContextValidate validate this performance lun metric latency based on the context it is used func (m *PerformanceLunMetricLatency) ContextValidate(ctx context.Context, formats strfmt.Registry) error { var res []error if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } // MarshalBinary interface implementation func (m *PerformanceLunMetricLatency) MarshalBinary() ([]byte, error) { if m == nil { return nil, nil } return swag.WriteJSON(m) } // UnmarshalBinary interface implementation func (m *PerformanceLunMetricLatency) UnmarshalBinary(b []byte) error { var res PerformanceLunMetricLatency if err := swag.ReadJSON(b, &res); err != nil { return err } *m = res return nil } // PerformanceLunMetricLinks performance lun metric links // // swagger:model PerformanceLunMetricLinks type PerformanceLunMetricLinks struct { // self Self *Href `json:"self,omitempty"` } // Validate validates this performance lun metric links func (m *PerformanceLunMetricLinks) Validate(formats strfmt.Registry) error { var res []error if err := m.validateSelf(formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *PerformanceLunMetricLinks) validateSelf(formats strfmt.Registry) error { if swag.IsZero(m.Self) { // not required return nil } if m.Self != nil { if err := m.Self.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("_links" + "." + "self") } return err } } return nil } // ContextValidate validate this performance lun metric links based on the context it is used func (m *PerformanceLunMetricLinks) ContextValidate(ctx context.Context, formats strfmt.Registry) error { var res []error if err := m.contextValidateSelf(ctx, formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *PerformanceLunMetricLinks) contextValidateSelf(ctx context.Context, formats strfmt.Registry) error { if m.Self != nil { if err := m.Self.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("_links" + "." + "self") } return err } } return nil } // MarshalBinary interface implementation func (m *PerformanceLunMetricLinks) MarshalBinary() ([]byte, error) { if m == nil { return nil, nil } return swag.WriteJSON(m) } // UnmarshalBinary interface implementation func (m *PerformanceLunMetricLinks) UnmarshalBinary(b []byte) error { var res PerformanceLunMetricLinks if err := swag.ReadJSON(b, &res); err != nil { return err } *m = res return nil } // PerformanceLunMetricThroughput The rate of throughput bytes per second observed at the storage object. // // swagger:model PerformanceLunMetricThroughput type PerformanceLunMetricThroughput struct { // Performance metric for other I/O operations. Other I/O operations can be metadata operations, such as directory lookups and so on. Other int64 `json:"other,omitempty"` // Performance metric for read I/O operations. // Example: 200 Read int64 `json:"read,omitempty"` // Performance metric aggregated over all types of I/O operations. // Example: 1000 Total int64 `json:"total,omitempty"` // Peformance metric for write I/O operations. // Example: 100 Write int64 `json:"write,omitempty"` } // Validate validates this performance lun metric throughput func (m *PerformanceLunMetricThroughput) Validate(formats strfmt.Registry) error { return nil } // ContextValidate validate this performance lun metric throughput based on the context it is used func (m *PerformanceLunMetricThroughput) ContextValidate(ctx context.Context, formats strfmt.Registry) error { var res []error if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } // MarshalBinary interface implementation func (m *PerformanceLunMetricThroughput) MarshalBinary() ([]byte, error) { if m == nil { return nil, nil } return swag.WriteJSON(m) } // UnmarshalBinary interface implementation func (m *PerformanceLunMetricThroughput) UnmarshalBinary(b []byte) error { var res PerformanceLunMetricThroughput if err := swag.ReadJSON(b, &res); err != nil { return err } *m = res return nil }<|fim▁end|>
<|file_name|>benchmark_bundle.js<|end_file_name|><|fim▁begin|>// modules are defined as an array // [ module function, map of requireuires ] // // map of requireuires is short require name -> numeric require // // anything defined in a previous bundle is accessed via the // orig method which is the requireuire for previous bundles (function outer (modules, cache, entry) { // Save the require from previous bundle to this closure if any var previousRequire = typeof require == "function" && require; function findProxyquireifyName() { var deps = Object.keys(modules) .map(function (k) { return modules[k][1]; }); for (var i = 0; i < deps.length; i++) { var pq = deps[i]['proxyquireify']; if (pq) return pq; } } var proxyquireifyName = findProxyquireifyName(); function newRequire(name, jumped){ // Find the proxyquireify module, if present var pqify = (proxyquireifyName != null) && cache[proxyquireifyName]; // Proxyquireify provides a separate cache that is used when inside // a proxyquire call, and is set to null outside a proxyquire call. // This allows the regular caching semantics to work correctly both // inside and outside proxyquire calls while keeping the cached // modules isolated. // When switching from one proxyquire call to another, it clears // the cache to prevent contamination between different sets // of stubs. var currentCache = (pqify && pqify.exports._cache) || cache; if(!currentCache[name]) { if(!modules[name]) { // if we cannot find the the module within our internal map or // cache jump to the current global require ie. the last bundle // that was added to the page. var currentRequire = typeof require == "function" && require; if (!jumped && currentRequire) return currentRequire(name, true); // If there are other bundles on this page the require from the // previous one is saved to 'previousRequire'. Repeat this as // many times as there are bundles until the module is found or // we exhaust the require chain. if (previousRequire) return previousRequire(name, true); var err = new Error('Cannot find module \'' + name + '\''); err.code = 'MODULE_NOT_FOUND'; throw err; } var m = currentCache[name] = {exports:{}}; // The normal browserify require function var req = function(x){ var id = modules[name][1][x]; return newRequire(id ? id : x); }; // The require function substituted for proxyquireify var moduleRequire = function(x){ var pqify = (proxyquireifyName != null) && cache[proxyquireifyName]; // Only try to use the proxyquireify version if it has been `require`d if (pqify && pqify.exports._proxy) { return pqify.exports._proxy(req, x); } else { return req(x); } }; modules[name][0].call(m.exports,moduleRequire,m,m.exports,outer,modules,currentCache,entry); } return currentCache[name].exports; } for(var i=0;i<entry.length;i++) newRequire(entry[i]); // Override the current require with this new one return newRequire; }) ({1:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MAIN // var ctor = ( typeof Float32Array === 'function' ) ? Float32Array : void 0; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = ctor; },{}],2:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * Typed array constructor which returns a typed array representing an array of single-precision floating-point numbers in the platform byte order. * * @module @stdlib/array/float32 * * @example * var ctor = require( '@stdlib/array/float32' ); * * var arr = new ctor( 10 ); * // returns <Float32Array> */ // MODULES // var hasFloat32ArraySupport = require( '@stdlib/assert/has-float32array-support' ); var builtin = require( './float32array.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var ctor; if ( hasFloat32ArraySupport() ) { ctor = builtin; } else { ctor = polyfill; } // EXPORTS // module.exports = ctor; },{"./float32array.js":1,"./polyfill.js":3,"@stdlib/assert/has-float32array-support":33}],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":36}],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":41}],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":44}],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":47}],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'; // 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' ); // MAIN // var CTORS = [ [ Float64Array, 'Float64Array' ], [ Float32Array, 'Float32Array' ], [ Int32Array, 'Int32Array' ], [ Uint32Array, 'Uint32Array' ], [ Int16Array, 'Int16Array' ], [ Uint16Array, 'Uint16Array' ], [ Int8Array, 'Int8Array' ], [ Uint8Array, 'Uint8Array' ], [ Uint8ClampedArray, 'Uint8ClampedArray' ] ]; // EXPORTS // module.exports = CTORS; },{"@stdlib/array/float32":2,"@stdlib/array/float64":5,"@stdlib/array/int16":7,"@stdlib/array/int32":10,"@stdlib/array/int8":13,"@stdlib/array/uint16":20,"@stdlib/array/uint32":23,"@stdlib/array/uint8":26,"@stdlib/array/uint8c":29}],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'; /** * Return a JSON representation of a typed array. * * @module @stdlib/array/to-json * * @example * var Float64Array = require( '@stdlib/array/float64' ); * var toJSON = require( '@stdlib/array/to-json' ); * * var arr = new Float64Array( [ 5.0, 3.0 ] ); * var json = toJSON( arr ); * // returns { 'type': 'Float64Array', 'data': [ 5.0, 3.0 ] } */ // MODULES // var toJSON = require( './to_json.js' ); // EXPORTS // module.exports = toJSON; },{"./to_json.js":18}],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'; // MODULES // var isTypedArray = require( '@stdlib/assert/is-typed-array' ); var typeName = require( './type.js' ); // MAIN // /** * Returns a JSON representation of a typed array. * * ## Notes * * - We build a JSON object representing a typed array similar to how Node.js `Buffer` objects are represented. See [Buffer][1]. * * [1]: https://nodejs.org/api/buffer.html#buffer_buf_tojson * * @param {TypedArray} arr - typed array to serialize * @throws {TypeError} first argument must be a typed array * @returns {Object} JSON representation * * @example * var Float64Array = require( '@stdlib/array/float64' ); * * var arr = new Float64Array( [ 5.0, 3.0 ] ); * var json = toJSON( arr ); * // returns { 'type': 'Float64Array', 'data': [ 5.0, 3.0 ] } */ function toJSON( arr ) { var out; var i; if ( !isTypedArray( arr ) ) { throw new TypeError( 'invalid argument. Must provide a typed array. Value: `' + arr + '`.' ); } out = {}; out.type = typeName( arr ); out.data = []; for ( i = 0; i < arr.length; i++ ) { out.data.push( arr[ i ] ); } return out; } // EXPORTS // module.exports = toJSON; },{"./type.js":19,"@stdlib/assert/is-typed-array":165}],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'; // MODULES // var instanceOf = require( '@stdlib/assert/instance-of' ); var ctorName = require( '@stdlib/utils/constructor-name' ); var getPrototypeOf = require( '@stdlib/utils/get-prototype-of' ); var CTORS = require( './ctors.js' ); // MAIN // /** * Returns the typed array type. * * @private * @param {TypedArray} arr - typed array * @returns {(string|void)} typed array type * * @example * var Float64Array = require( '@stdlib/array/float64' ); * * var arr = new Float64Array( 5 ); * var str = typeName( arr ); * // returns 'Float64Array' */ function typeName( arr ) { var v; var i; // Check for typed array objects from the same realm (same Node.js `vm` or same `Window` object)... for ( i = 0; i < CTORS.length; i++ ) { if ( instanceOf( arr, CTORS[ i ][ 0 ] ) ) { return CTORS[ i ][ 1 ]; } } // Walk the prototype tree until we find an object having a desired native class... while ( arr ) { v = ctorName( arr ); for ( i = 0; i < CTORS.length; i++ ) { if ( v === CTORS[ i ][ 1 ] ) { return CTORS[ i ][ 1 ]; } } arr = getPrototypeOf( arr ); } } // EXPORTS // module.exports = typeName; },{"./ctors.js":16,"@stdlib/assert/instance-of":71,"@stdlib/utils/constructor-name":366,"@stdlib/utils/get-prototype-of":389}],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'; /** * 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":21,"./uint16array.js":22,"@stdlib/assert/has-uint16array-support":59}],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'; // 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; },{}],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'; // MAIN // var ctor = ( typeof Uint16Array === 'function' ) ? Uint16Array : void 0; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = ctor; },{}],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'; /** * 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":24,"./uint32array.js":25,"@stdlib/assert/has-uint32array-support":62}],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'; // 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; },{}],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'; // MAIN // var ctor = ( typeof Uint32Array === 'function' ) ? Uint32Array : void 0; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = ctor; },{}],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'; /** * 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":27,"./uint8array.js":28,"@stdlib/assert/has-uint8array-support":65}],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'; // 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; },{}],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 ctor = ( typeof Uint8Array === 'function' ) ? Uint8Array : void 0; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = ctor; },{}],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'; /** * 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":30,"./uint8clampedarray.js":31,"@stdlib/assert/has-uint8clampedarray-support":68}],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'; // 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; },{}],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 ctor = ( typeof Uint8ClampedArray === 'function' ) ? Uint8ClampedArray : void 0; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = ctor; },{}],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'; // MAIN // var main = ( typeof Float32Array === 'function' ) ? Float32Array : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],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'; /** * 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":34}],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'; // 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":32,"@stdlib/assert/is-float32array":98,"@stdlib/constants/float64/pinf":246}],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 Float64Array === 'function' ) ? Float64Array : 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'; /** * 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":37}],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'; // 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":35,"@stdlib/assert/is-float64array":100}],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'; /** * Dummy function. * * @private */ function foo() { // No-op... } // EXPORTS // module.exports = foo; },{}],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'; /** * Test for native function `name` support. * * @module @stdlib/assert/has-function-name-support * * @example * var hasFunctionNameSupport = require( '@stdlib/assert/has-function-name-support' ); * * var bool = hasFunctionNameSupport(); * // returns <boolean> */ // MODULES // var hasFunctionNameSupport = require( './main.js' ); // EXPORTS // module.exports = hasFunctionNameSupport; },{"./main.js":40}],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'; // MODULES // var foo = require( './foo.js' ); // MAIN // /** * Tests for native function `name` support. * * @returns {boolean} boolean indicating if an environment has function `name` support * * @example * var bool = hasFunctionNameSupport(); * // returns <boolean> */ function hasFunctionNameSupport() { return ( foo.name === 'foo' ); } // EXPORTS // module.exports = hasFunctionNameSupport; },{"./foo.js":38}],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'; /** * 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":43}],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'; // MAIN // var main = ( typeof Int16Array === 'function' ) ? Int16Array : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],43:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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":42,"@stdlib/assert/is-int16array":104,"@stdlib/constants/int16/max":248,"@stdlib/constants/int16/min":249}],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 `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":46}],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'; // MAIN // var main = ( typeof Int32Array === 'function' ) ? Int32Array : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],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'; // 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":45,"@stdlib/assert/is-int32array":106,"@stdlib/constants/int32/max":250,"@stdlib/constants/int32/min":251}],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'; /** * 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":49}],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'; // MAIN // var main = ( typeof Int8Array === 'function' ) ? Int8Array : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],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'; // 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":48,"@stdlib/assert/is-int8array":108,"@stdlib/constants/int8/max":252,"@stdlib/constants/int8/min":253}],50:[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":456}],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'; /** * 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":52}],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'; // 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":50,"@stdlib/assert/is-buffer":88}],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'; /** * 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":54}],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'; // 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; },{}],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 `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":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'; // MAIN // /** * Tests for native `Symbol` support. * * @returns {boolean} boolean indicating if an environment has `Symbol` support * * @example * var bool = hasSymbolSupport(); * // returns <boolean> */ function hasSymbolSupport() { return ( typeof Symbol === 'function' && typeof Symbol( 'foo' ) === 'symbol' ); } // EXPORTS // module.exports = hasSymbolSupport; },{}],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'; /** * 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":58}],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'; // 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":55}],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'; /** * 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":60}],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'; // 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":61,"@stdlib/assert/is-uint16array":168,"@stdlib/constants/uint16/max":254}],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'; // MAIN // var main = ( typeof Uint16Array === 'function' ) ? Uint16Array : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],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'; /** * 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":63}],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'; // 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":64,"@stdlib/assert/is-uint32array":170,"@stdlib/constants/uint32/max":255}],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'; // MAIN // var main = ( typeof Uint32Array === 'function' ) ? Uint32Array : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],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 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":66}],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 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":67,"@stdlib/assert/is-uint8array":172,"@stdlib/constants/uint8/max":256}],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'; // MAIN // var main = ( typeof Uint8Array === 'function' ) ? Uint8Array : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],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 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":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 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":70,"@stdlib/assert/is-uint8clampedarray":174}],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'; // MAIN // var main = ( typeof Uint8ClampedArray === 'function' ) ? Uint8ClampedArray : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],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'; /** * Test whether a value has in its prototype chain a specified constructor as a prototype property. * * @module @stdlib/assert/instance-of * * @example * var instanceOf = require( '@stdlib/assert/instance-of' ); * * var bool = instanceOf( [], Array ); * // returns true * * bool = instanceOf( {}, Object ); // exception * // returns true * * bool = instanceOf( 'beep', String ); * // returns false * * bool = instanceOf( null, Object ); * // returns false * * bool = instanceOf( 5, Object ); * // returns false */ // MODULES // var instanceOf = require( './main.js' ); // EXPORTS // module.exports = instanceOf; },{"./main.js":72}],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'; // MAIN // /** * Tests whether a value has in its prototype chain a specified constructor as a prototype property. * * @param {*} value - value to test * @param {Function} constructor - constructor to test against * @throws {TypeError} constructor must be callable * @returns {boolean} boolean indicating whether a value is an instance of a provided constructor * * @example * var bool = instanceOf( [], Array ); * // returns true * * @example * var bool = instanceOf( {}, Object ); // exception * // returns true * * @example * var bool = instanceOf( 'beep', String ); * // returns false * * @example * var bool = instanceOf( null, Object ); * // returns false * * @example * var bool = instanceOf( 5, Object ); * // returns false */ function instanceOf( value, constructor ) { // TODO: replace with `isCallable` check if ( typeof constructor !== 'function' ) { throw new TypeError( 'invalid argument. `constructor` argument must be callable. Value: `'+constructor+'`.' ); } return ( value instanceof constructor ); } // EXPORTS // module.exports = instanceOf; },{}],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 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":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'; /** * 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":73,"./main.js":75,"./polyfill.js":76}],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'; // 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":423}],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'; // 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":53,"@stdlib/assert/is-array":79,"@stdlib/assert/is-enumerable-property":93,"@stdlib/constants/uint32/max":255,"@stdlib/math/base/assert/is-integer":261}],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'; /** * 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":78}],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'; // 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":235,"@stdlib/math/base/assert/is-integer":261}],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 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":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 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":423}],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 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":82,"./object.js":83,"./primitive.js":84,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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 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":83,"./primitive.js":84}],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 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":86,"@stdlib/assert/has-tostringtag-support":57,"@stdlib/utils/native-class":423}],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'; /** * 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; },{}],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'; // eslint-disable-next-line stdlib/no-redeclare var toString = Boolean.prototype.toString; // non-generic // EXPORTS // module.exports = toString; },{}],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'; // 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":85}],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'; // EXPORTS // module.exports = true; },{}],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'; /** * 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":89}],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'; // 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":143}],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'; /** * 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":91}],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'; // 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":236,"@stdlib/math/base/assert/is-integer":261}],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 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":95}],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 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":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 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":92,"./native.js":95,"@stdlib/assert/is-integer":110,"@stdlib/assert/is-nan":118,"@stdlib/assert/is-string":158}],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'; // 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; },{}],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'; /** * 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":97}],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'; // 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":389,"@stdlib/utils/native-class":423}],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'; /** * 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":99}],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'; // 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":423}],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'; /** * 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":101}],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'; // 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":423}],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'; /** * 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":103}],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 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":450}],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'; /** * 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":105}],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 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":423}],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'; /** * 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":107}],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'; // 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":423}],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'; /** * 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":109}],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'; // 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":423}],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'; /** * 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":112,"./object.js":113,"./primitive.js":114,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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 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":245,"@stdlib/constants/float64/pinf":246,"@stdlib/math/base/assert/is-integer":261}],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 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":113,"./primitive.js":114}],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'; // 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":111,"@stdlib/assert/is-number":137}],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'; // 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":111,"@stdlib/assert/is-number":137}],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'; // 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":20,"@stdlib/array/uint8":26}],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. */ '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":117}],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'; // 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":115}],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 `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":119,"./object.js":120,"./primitive.js":121,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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 `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":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 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":137,"@stdlib/math/base/assert/is-nan":263}],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 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":137,"@stdlib/math/base/assert/is-nan":263}],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 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":123}],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'; // 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; },{}],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'; /** * 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":125}],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. */ /* 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":122}],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 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":127,"@stdlib/assert/tools/array-like-function":179,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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'; /** * 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":128,"./object.js":129,"./primitive.js":130,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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'; // 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":129,"./primitive.js":130}],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 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":110}],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 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":110}],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'; /** * 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":132,"./object.js":133,"./primitive.js":134,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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 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":133,"./primitive.js":134}],133:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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":137}],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'; // 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":137}],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'; /** * 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":136}],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'; /** * 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; },{}],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'; /** * 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":138,"./object.js":139,"./primitive.js":140,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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'; // 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":139,"./primitive.js":140}],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 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":142,"@stdlib/assert/has-tostringtag-support":57,"@stdlib/number/ctor":292,"@stdlib/utils/native-class":423}],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'; /** * 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; },{}],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 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":292}],142:[function(require,module,exports){ arguments[4][86][0].apply(exports,arguments) },{"./tostring.js":141,"dup":86}],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'; /** * 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":144,"@stdlib/assert/tools/array-function":177,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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'; /** * 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; },{}],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 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":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 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":79}],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'; /** * 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":148}],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'; // 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":53,"@stdlib/assert/is-function":102,"@stdlib/assert/is-object":145,"@stdlib/utils/get-prototype-of":389,"@stdlib/utils/native-class":423}],149:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * Test if a value is a 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":150,"./object.js":151,"./primitive.js":152,"@stdlib/utils/define-nonenumerable-read-only-property":374}],150:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // MAIN // /** * Tests if a value is a 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":151,"./primitive.js":152}],151:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":110}],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 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":110}],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'; var exec = RegExp.prototype.exec; // non-generic // EXPORTS // module.exports = exec; },{}],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'; /** * 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":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'; // 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":156,"@stdlib/assert/has-tostringtag-support":57,"@stdlib/utils/native-class":423}],156:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":153}],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 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":158,"@stdlib/assert/tools/array-function":177,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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'; /** * 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":159,"./object.js":160,"./primitive.js":161,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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'; // 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":160,"./primitive.js":161}],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 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":162,"@stdlib/assert/has-tostringtag-support":57,"@stdlib/utils/native-class":423}],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'; /** * 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; },{}],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 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":163}],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'; // eslint-disable-next-line stdlib/no-redeclare var valueOf = String.prototype.valueOf; // non-generic // EXPORTS // module.exports = valueOf; },{}],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 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' ); // MAIN // var CTORS = [ Float64Array, Float32Array, Int32Array, Uint32Array, Int16Array, Uint16Array, Int8Array, Uint8Array, Uint8ClampedArray ]; // EXPORTS // module.exports = CTORS; },{"@stdlib/array/float32":2,"@stdlib/array/float64":5,"@stdlib/array/int16":7,"@stdlib/array/int32":10,"@stdlib/array/int8":13,"@stdlib/array/uint16":20,"@stdlib/array/uint32":23,"@stdlib/array/uint8":26,"@stdlib/array/uint8c":29}],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'; /** * Test if a value is a typed array. * * @module @stdlib/assert/is-typed-array * * @example * var Int8Array = require( '@stdlib/array/int8' ); * var isTypedArray = require( '@stdlib/assert/is-typed-array' ); * * var bool = isTypedArray( new Int8Array( 10 ) ); * // returns true */ // MODULES // var isTypedArray = require( './main.js' ); // EXPORTS // module.exports = isTypedArray; },{"./main.js":166}],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'; // MODULES // var ctorName = require( '@stdlib/utils/constructor-name' ); var fcnName = require( '@stdlib/utils/function-name' ); var getPrototypeOf = require( '@stdlib/utils/get-prototype-of' ); var hasFloat64ArraySupport = require( '@stdlib/assert/has-float64array-support' ); var Float64Array = require( '@stdlib/array/float64' ); var CTORS = require( './ctors.js' ); var NAMES = require( './names.json' ); // VARIABLES // // Abstract `TypedArray` class: var TypedArray = ( hasFloat64ArraySupport() ) ? getPrototypeOf( Float64Array ) : Dummy; // eslint-disable-line max-len // Ensure abstract typed array class has expected name: TypedArray = ( fcnName( TypedArray ) === 'TypedArray' ) ? TypedArray : Dummy; // FUNCTIONS // /** * Dummy constructor. * * @private */ function Dummy() {} // eslint-disable-line no-empty-function // MAIN // /** * Tests if a value is a typed array. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is a typed array * * @example * var Int8Array = require( '@stdlib/array/int8' ); * * var bool = isTypedArray( new Int8Array( 10 ) ); * // returns true */ function isTypedArray( value ) { var v; var i; if ( typeof value !== 'object' || value === null ) { return false; } // Check for the abstract class... if ( value instanceof TypedArray ) { return true; } // Check for typed array objects from the same realm (same Node.js `vm` or same `Window` object)... for ( i = 0; i < CTORS.length; i++ ) { if ( value instanceof CTORS[ i ] ) { return true; } } // Walk the prototype tree until we find an object having a desired class... while ( value ) { v = ctorName( value ); for ( i = 0; i < NAMES.length; i++ ) { if ( NAMES[ i ] === v ) { return true; } } value = getPrototypeOf( value ); } return false; } // EXPORTS // module.exports = isTypedArray; },{"./ctors.js":164,"./names.json":167,"@stdlib/array/float64":5,"@stdlib/assert/has-float64array-support":36,"@stdlib/utils/constructor-name":366,"@stdlib/utils/function-name":386,"@stdlib/utils/get-prototype-of":389}],167:[function(require,module,exports){ module.exports=[ "Int8Array", "Uint8Array", "Uint8ClampedArray", "Int16Array", "Uint16Array", "Int32Array", "Uint32Array", "Float32Array", "Float64Array" ] },{}],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'; /** * 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":169}],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 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":423}],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'; /** * 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":171}],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'; // 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":423}],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'; /** * 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":173}],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'; // 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":423}],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'; /** * 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":175}],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'; // 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":423}],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'; // MODULES // var isArray = require( '@stdlib/assert/is-array' ); // MAIN // /** * Returns a function which tests if every element in an array passes a test condition. * * @param {Function} predicate - function to apply * @throws {TypeError} must provide a function * @returns {Function} an array function * * @example * var isOdd = require( '@stdlib/assert/is-odd' ); * * var arr1 = [ 1, 3, 5, 7 ]; * var arr2 = [ 3, 5, 8 ]; * * var validate = arrayfcn( isOdd ); * * var bool = validate( arr1 ); * // returns true * * bool = validate( arr2 ); * // returns false */ function arrayfcn( predicate ) { if ( typeof predicate !== 'function' ) { throw new TypeError( 'invalid argument. Must provide a function. Value: `' + predicate + '`.' ); } return every; /** * Tests if every element in an array passes a test condition. * * @private * @param {*} value - value to test * @returns {boolean} boolean indicating whether a value is an array for which all elements pass a test condition */ function every( value ) { var len; var i; if ( !isArray( value ) ) { return false; } len = value.length; if ( len === 0 ) { return false; } for ( i = 0; i < len; i++ ) { if ( predicate( value[ i ] ) === false ) { return false; } } return true; } } // EXPORTS // module.exports = arrayfcn; },{"@stdlib/assert/is-array":79}],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'; /** * 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":176}],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'; // MODULES // var isArrayLike = require( '@stdlib/assert/is-array-like' ); // MAIN // /** * Returns a function which tests if every element in an array-like object passes a test condition. * * @param {Function} predicate - function to apply * @throws {TypeError} must provide a function * @returns {Function} an array-like object function * * @example * var isOdd = require( '@stdlib/assert/is-odd' ); * * var arr1 = [ 1, 3, 5, 7 ]; * var arr2 = [ 3, 5, 8 ]; * * var validate = arraylikefcn( isOdd ); * * var bool = validate( arr1 ); * // returns true * * bool = validate( arr2 ); * // returns false */ function arraylikefcn( predicate ) { if ( typeof predicate !== 'function' ) { throw new TypeError( 'invalid argument. Must provide a function. Value: `' + predicate + '`.' ); } return every; /** * Tests if every element in an array-like object passes a test condition. * * @private * @param {*} value - value to test * @returns {boolean} boolean indicating whether a value is an array-like object for which all elements pass a test condition */ function every( value ) { var len; var i; if ( !isArrayLike( value ) ) { return false; } len = value.length; if ( len === 0 ) { return false; } for ( i = 0; i < len; i++ ) { if ( predicate( value[ i ] ) === false ) { return false; } } return true; } } // EXPORTS // module.exports = arraylikefcn; },{"@stdlib/assert/is-array-like":77}],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'; /** * 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":178}],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'; // MODULES // var TransformStream = require( '@stdlib/streams/node/transform' ); var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var isFunction = require( '@stdlib/assert/is-function' ); var createHarness = require( './harness' ); var harness = require( './get_harness.js' ); // VARIABLES // var listeners = []; // FUNCTIONS // /** * Callback invoked when a harness finishes running all benchmarks. * * @private */ function done() { var len; var f; var i; len = listeners.length; // Inform all the listeners that the harness has finished... for ( i = 0; i < len; i++ ) { f = listeners.shift(); f(); } } /** * Creates a results stream. * * @private * @param {Options} [options] - stream options * @throws {Error} must provide valid stream options * @returns {TransformStream} results stream */ function createStream( options ) { var stream; var bench; var opts; if ( arguments.length ) { opts = options; } else { opts = {}; } // If we have already created a harness, calling this function simply creates another results stream... if ( harness.cached ) { bench = harness(); return bench.createStream( opts ); } stream = new TransformStream( opts ); opts.stream = stream; // Create a harness which uses the created output stream: harness( opts, done ); return stream; } /** * Adds a listener for when a harness finishes running all benchmarks. * * @private * @param {Callback} clbk - listener * @throws {TypeError} must provide a function * @throws {Error} must provide a listener only once * @returns {void} */ function onFinish( clbk ) { var i; if ( !isFunction( clbk ) ) { throw new TypeError( 'invalid argument. Must provide a function. Value: `'+clbk+'`.' ); } // Allow adding a listener only once... for ( i = 0; i < listeners.length; i++ ) { if ( clbk === listeners[ i ] ) { throw new Error( 'invalid argument. Attempted to add duplicate listener.' ); } } listeners.push( clbk ); } // MAIN // /** * Runs a benchmark. * * @param {string} name - benchmark name * @param {Options} [options] - benchmark options * @param {boolean} [options.skip=false] - boolean indicating whether to skip a benchmark * @param {(PositiveInteger|null)} [options.iterations=null] - number of iterations * @param {PositiveInteger} [options.repeats=3] - number of repeats * @param {PositiveInteger} [options.timeout=300000] - number of milliseconds before a benchmark automatically fails * @param {Function} [benchmark] - function containing benchmark code * @throws {TypeError} first argument must be a string * @throws {TypeError} options argument must be an object * @throws {TypeError} must provide valid options * @throws {TypeError} benchmark argument must a function * @returns {Benchmark} benchmark harness * * @example * bench( 'beep', function benchmark( b ) { * var x; * var i; * b.tic(); * for ( i = 0; i < b.iterations; i++ ) { * x = Math.sin( Math.random() ); * if ( x !== x ) { * b.ok( false, 'should not return NaN' ); * } * } * b.toc(); * if ( x !== x ) { * b.ok( false, 'should not return NaN' ); * } * b.end(); * }); */ function bench( name, options, benchmark ) { var h = harness( done ); if ( arguments.length < 2 ) { h( name ); } else if ( arguments.length === 2 ) { h( name, options ); } else { h( name, options, benchmark ); } return bench; } /** * Creates a benchmark harness. * * @name createHarness * @memberof bench * @type {Function} * @param {Options} [options] - harness options * @param {Callback} [clbk] - callback to invoke when a harness finishes running all benchmarks * @throws {TypeError} options argument must be an object * @throws {TypeError} must provide valid options * @throws {TypeError} callback argument must be a function * @returns {Function} benchmark harness */ setReadOnly( bench, 'createHarness', createHarness ); /** * Creates a results stream. * * @name createStream * @memberof bench * @type {Function} * @param {Options} [options] - stream options * @throws {Error} must provide valid stream options * @returns {TransformStream} results stream */ setReadOnly( bench, 'createStream', createStream ); /** * Adds a listener for when a harness finishes running all benchmarks. * * @name onFinish * @memberof bench * @type {Function} * @param {Callback} clbk - listener * @throws {TypeError} must provide a function * @throws {Error} must provide a listener only once * @returns {void} */ setReadOnly( bench, 'onFinish', onFinish ); // EXPORTS // module.exports = bench; },{"./get_harness.js":202,"./harness":203,"@stdlib/assert/is-function":102,"@stdlib/streams/node/transform":348,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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'; // 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":53}],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'; // EXPORTS // module.exports = clearTimeout; },{}],183:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":327,"@stdlib/string/replace":354,"@stdlib/string/trim":356}],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 // /** * 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; },{}],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 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":222}],186:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MAIN // /** * 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; },{}],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 // /** * 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; },{}],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 // /** * 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; },{}],189:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // 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; },{}],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 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 }); <|fim▁hole|> '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":181,"./comment.js":183,"./deep_equal.js":184,"./end.js":185,"./ended.js":186,"./equal.js":187,"./exit.js":188,"./fail.js":189,"./not_deep_equal.js":191,"./not_equal.js":192,"./not_ok.js":193,"./ok.js":194,"./pass.js":195,"./run.js":196,"./skip.js":198,"./todo.js":199,"@stdlib/time/tic":358,"@stdlib/time/toc":362,"@stdlib/utils/define-nonenumerable-read-only-property":374,"@stdlib/utils/define-property":381,"@stdlib/utils/inherit":402,"events":455}],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'; // 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; },{}],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'; // 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; },{}],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'; // 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; },{}],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'; // 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; },{}],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'; // 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; },{}],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 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":182,"./set_timeout.js":197}],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'; // EXPORTS // module.exports = setTimeout; },{}],198:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MAIN // /** * 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; },{}],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 // /** * 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; },{}],200:[function(require,module,exports){ module.exports={ "skip": false, "iterations": null, "repeats": 3, "timeout": 300000 } },{}],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'; // MODULES // var isFunction = require( '@stdlib/assert/is-function' ); var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; var isObject = require( '@stdlib/assert/is-plain-object' ); var isNodeWritableStreamLike = require( '@stdlib/assert/is-node-writable-stream-like' ); var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var pick = require( '@stdlib/utils/pick' ); var omit = require( '@stdlib/utils/omit' ); var noop = require( '@stdlib/utils/noop' ); var createHarness = require( './harness' ); var logStream = require( './log' ); var canEmitExit = require( './utils/can_emit_exit.js' ); var proc = require( './utils/process.js' ); // MAIN // /** * Creates a benchmark harness which supports closing when a process exits. * * @private * @param {Options} [options] - function options * @param {boolean} [options.autoclose] - boolean indicating whether to automatically close a harness after a harness finishes running all benchmarks * @param {Stream} [options.stream] - output writable stream * @param {Callback} [clbk] - callback to invoke when a harness finishes running all benchmarks * @throws {TypeError} options argument must be an object * @throws {TypeError} must provide valid options * @throws {TypeError} callback argument must be a function * @returns {Function} benchmark harness * * @example * var proc = require( 'process' ); * var bench = createExitHarness( onFinish ); * * function onFinish() { * bench.close(); * } * * bench( 'beep', function benchmark( b ) { * var x; * var i; * b.tic(); * for ( i = 0; i < b.iterations; i++ ) { * x = Math.sin( Math.random() ); * if ( x !== x ) { * b.ok( false, 'should not return NaN' ); * } * } * b.toc(); * if ( x !== x ) { * b.ok( false, 'should not return NaN' ); * } * b.end(); * }); * * @example * var stdout = require( '@stdlib/streams/node/stdout' ); * * var stream = createExitHarness().createStream(); * stream.pipe( stdout ); */ function createExitHarness() { var exitCode; var pipeline; var harness; var options; var stream; var topts; var opts; var clbk; if ( arguments.length === 0 ) { options = {}; clbk = noop; } else if ( arguments.length === 1 ) { if ( isFunction( arguments[ 0 ] ) ) { options = {}; clbk = arguments[ 0 ]; } else if ( isObject( arguments[ 0 ] ) ) { options = arguments[ 0 ]; clbk = noop; } else { throw new TypeError( 'invalid argument. Must provide either an options object or a callback function. Value: `'+arguments[ 0 ]+'`.' ); } } else { options = arguments[ 0 ]; if ( !isObject( options ) ) { throw new TypeError( 'invalid argument. First argument must be an object. Value: `'+options+'`.' ); } clbk = arguments[ 1 ]; if ( !isFunction( clbk ) ) { throw new TypeError( 'invalid argument. Second argument must be a function. Value: `'+clbk+'`.' ); } } opts = {}; if ( hasOwnProp( options, 'autoclose' ) ) { opts.autoclose = options.autoclose; if ( !isBoolean( opts.autoclose ) ) { throw new TypeError( 'invalid option. `autoclose` option must be a boolean primitive. Option: `'+opts.autoclose+'`.' ); } } if ( hasOwnProp( options, 'stream' ) ) { opts.stream = options.stream; if ( !isNodeWritableStreamLike( opts.stream ) ) { throw new TypeError( 'invalid option. `stream` option must be a writable stream. Option: `'+opts.stream+'`.' ); } } exitCode = 0; // Create a new harness: topts = pick( opts, [ 'autoclose' ] ); harness = createHarness( topts, done ); // Create a results stream: topts = omit( options, [ 'autoclose', 'stream' ] ); stream = harness.createStream( topts ); // Pipe results to an output stream: pipeline = stream.pipe( opts.stream || logStream() ); // If a process can emit an 'exit' event, capture errors in order to set the exit code... if ( canEmitExit ) { pipeline.on( 'error', onError ); proc.on( 'exit', onExit ); } return harness; /** * Callback invoked when a harness finishes. * * @private * @returns {void} */ function done() { return clbk(); } /** * Callback invoked upon a stream `error` event. * * @private * @param {Error} error - error object */ function onError() { exitCode = 1; } /** * Callback invoked upon an `exit` event. * * @private * @param {integer} code - exit code */ function onExit( code ) { if ( code !== 0 ) { // Allow the process to exit... return; } harness.close(); proc.exit( exitCode || harness.exitCode ); } } // EXPORTS // module.exports = createExitHarness; },{"./harness":203,"./log":209,"./utils/can_emit_exit.js":220,"./utils/process.js":223,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-function":102,"@stdlib/assert/is-node-writable-stream-like":124,"@stdlib/assert/is-plain-object":147,"@stdlib/utils/noop":430,"@stdlib/utils/omit":432,"@stdlib/utils/pick":434}],202:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // 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":201,"./utils/can_emit_exit.js":220}],203:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var setReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' ); var isString = require( '@stdlib/assert/is-string' ).isPrimitive; var isFunction = require( '@stdlib/assert/is-function' ); var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; var isObject = require( '@stdlib/assert/is-plain-object' ); var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var copy = require( '@stdlib/utils/copy' ); var Benchmark = require( './../benchmark-class' ); var Runner = require( './../runner' ); var nextTick = require( './../utils/next_tick.js' ); var DEFAULTS = require( './../defaults.json' ); var validate = require( './validate.js' ); var init = require( './init.js' ); // MAIN // /** * Creates a benchmark harness. * * @param {Options} [options] - function options * @param {boolean} [options.autoclose] - boolean indicating whether to automatically close a harness after a harness finishes running all benchmarks * @param {Callback} [clbk] - callback to invoke when a harness finishes running all benchmarks * @throws {TypeError} options argument must be an object * @throws {TypeError} must provide valid options * @throws {TypeError} callback argument must be a function * @returns {Function} benchmark harness * * @example * var bench = createHarness( onFinish ); * * function onFinish() { * bench.close(); * console.log( 'Exit code: %d', bench.exitCode ); * } * * bench( 'beep', function benchmark( b ) { * var x; * var i; * b.tic(); * for ( i = 0; i < b.iterations; i++ ) { * x = Math.sin( Math.random() ); * if ( x !== x ) { * b.ok( false, 'should not return NaN' ); * } * } * b.toc(); * if ( x !== x ) { * b.ok( false, 'should not return NaN' ); * } * b.end(); * }); * * @example * var stdout = require( '@stdlib/streams/node/stdout' ); * * var stream = createHarness().createStream(); * stream.pipe( stdout ); */ function createHarness( options, clbk ) { var exitCode; var runner; var queue; var opts; var cb; opts = {}; if ( arguments.length === 1 ) { if ( isFunction( options ) ) { cb = options; } else if ( isObject( options ) ) { opts = options; } else { throw new TypeError( 'invalid argument. Must provide either an options object or a callback function. Value: `'+options+'`.' ); } } else if ( arguments.length > 1 ) { if ( !isObject( options ) ) { throw new TypeError( 'invalid argument. First argument must be an object. Value: `'+options+'`.' ); } if ( hasOwnProp( options, 'autoclose' ) ) { opts.autoclose = options.autoclose; if ( !isBoolean( opts.autoclose ) ) { throw new TypeError( 'invalid option. `autoclose` option must be a boolean primitive. Option: `'+opts.autoclose+'`.' ); } } cb = clbk; if ( !isFunction( cb ) ) { throw new TypeError( 'invalid argument. Second argument must be a function. Value: `'+cb+'`.' ); } } runner = new Runner(); if ( opts.autoclose ) { runner.once( 'done', close ); } if ( cb ) { runner.once( 'done', cb ); } exitCode = 0; queue = []; /** * Benchmark harness. * * @private * @param {string} name - benchmark name * @param {Options} [options] - benchmark options * @param {boolean} [options.skip=false] - boolean indicating whether to skip a benchmark * @param {(PositiveInteger|null)} [options.iterations=null] - number of iterations * @param {PositiveInteger} [options.repeats=3] - number of repeats * @param {PositiveInteger} [options.timeout=300000] - number of milliseconds before a benchmark automatically fails * @param {Function} [benchmark] - function containing benchmark code * @throws {TypeError} first argument must be a string * @throws {TypeError} options argument must be an object * @throws {TypeError} must provide valid options * @throws {TypeError} benchmark argument must a function * @throws {Error} benchmark error * @returns {Function} benchmark harness */ function harness( name, options, benchmark ) { var opts; var err; var b; if ( !isString( name ) ) { throw new TypeError( 'invalid argument. First argument must be a string. Value: `'+name+'`.' ); } opts = copy( DEFAULTS ); if ( arguments.length === 2 ) { if ( isFunction( options ) ) { b = options; } else { err = validate( opts, options ); if ( err ) { throw err; } } } else if ( arguments.length > 2 ) { err = validate( opts, options ); if ( err ) { throw err; } b = benchmark; if ( !isFunction( b ) ) { throw new TypeError( 'invalid argument. Third argument must be a function. Value: `'+b+'`.' ); } } // Add the benchmark to the initialization queue: queue.push( [ name, opts, b ] ); // Perform initialization on the next turn of the event loop (note: this allows all benchmarks to be "registered" within the same turn of the loop; otherwise, we run the risk of registration-execution race conditions (i.e., a benchmark registers and executes before other benchmarks can register, depleting the benchmark queue and leading the harness to close)): if ( queue.length === 1 ) { nextTick( initialize ); } return harness; } /** * Initializes each benchmark. * * @private * @returns {void} */ function initialize() { var idx = -1; return next(); /** * Initialize the next benchmark. * * @private * @returns {void} */ function next() { var args; idx += 1; // If all benchmarks have been initialized, begin running the benchmarks: if ( idx === queue.length ) { queue.length = 0; return runner.run(); } // Initialize the next benchmark: args = queue[ idx ]; init( args[ 0 ], args[ 1 ], args[ 2 ], onInit ); } /** * Callback invoked after performing initialization tasks. * * @private * @param {string} name - benchmark name * @param {Options} opts - benchmark options * @param {(Function|undefined)} benchmark - function containing benchmark code * @returns {void} */ function onInit( name, opts, benchmark ) { var b; var i; // Create a `Benchmark` instance for each repeat to ensure each benchmark has its own state... for ( i = 0; i < opts.repeats; i++ ) { b = new Benchmark( name, opts, benchmark ); b.on( 'result', onResult ); runner.push( b ); } return next(); } } /** * Callback invoked upon a `result` event. * * @private * @param {(string|Object)} result - result */ function onResult( result ) { if ( !isString( result ) && !result.ok && !result.todo ) { exitCode = 1; } } /** * Returns a results stream. * * @private * @param {Object} [options] - options * @returns {TransformStream} transform stream */ function createStream( options ) { if ( arguments.length ) { return runner.createStream( options ); } return runner.createStream(); } /** * Closes a benchmark harness. * * @private */ function close() { runner.close(); } /** * Forcefully exits a benchmark harness. * * @private */ function exit() { runner.exit(); } /** * Returns the harness exit code. * * @private * @returns {NonNegativeInteger} exit code */ function getExitCode() { return exitCode; } setReadOnly( harness, 'createStream', createStream ); setReadOnly( harness, 'close', close ); setReadOnly( harness, 'exit', exit ); setReadOnlyAccessor( harness, 'exitCode', getExitCode ); return harness; } // EXPORTS // module.exports = createHarness; },{"./../benchmark-class":190,"./../defaults.json":200,"./../runner":217,"./../utils/next_tick.js":222,"./init.js":204,"./validate.js":207,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-function":102,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-string":158,"@stdlib/utils/copy":370,"@stdlib/utils/define-nonenumerable-read-only-accessor":372,"@stdlib/utils/define-nonenumerable-read-only-property":374}],204:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":205,"./pretest.js":206}],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'; // 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":190,"@stdlib/assert/is-string":158,"@stdlib/utils/copy":370}],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 isString = require( '@stdlib/assert/is-string' ).isPrimitive; var copy = require( '@stdlib/utils/copy' ); var Benchmark = require( './../benchmark-class' ); // MAIN // /** * Runs pretests to sanity check and/or catch failures. * * @private * @param {string} name - benchmark name * @param {Options} options - benchmark options * @param {(Function|undefined)} benchmark - function containing benchmark code * @param {Callback} clbk - callback to invoke after completing pretests */ function pretest( name, options, benchmark, clbk ) { var fail; var opts; var tic; var toc; var b; // Counters to determine the number of `tic` and `toc` events: tic = 0; toc = 0; // Local copy: opts = copy( options ); opts.iterations = 1; // Pretest to check for minimum requirements and/or errors... b = new Benchmark( name, opts, benchmark ); b.on( 'result', onResult ); b.on( 'tic', onTic ); b.on( 'toc', onToc ); b.once( 'end', onEnd ); b.run(); /** * Callback invoked upon a `result` event. * * @private * @param {(string|Object)} result - result */ function onResult( result ) { if ( !isString( result ) && !result.ok && !result.todo ) { fail = true; } } /** * Callback invoked upon a `tic` event. * * @private */ function onTic() { tic += 1; } /** * Callback invoked upon a `toc` event. * * @private */ function onToc() { toc += 1; } /** * Callback invoked upon an `end` event. * * @private * @returns {void} */ function onEnd() { var err; if ( fail ) { // Possibility that failure is intermittent, but we will assume that the usual case is that the failure would persist across all repeats and no sense failing multiple times when once suffices. err = new Error( 'benchmark failed' ); } else if ( tic !== 1 || toc !== 1 ) { // Unable to do anything definitive with timing information (e.g., a tic with no toc or vice versa, or benchmark function calls neither tic nor toc). err = new Error( 'invalid benchmark' ); } if ( err ) { return clbk( err ); } return clbk(); } } // EXPORTS // module.exports = pretest; },{"./../benchmark-class":190,"@stdlib/assert/is-string":158,"@stdlib/utils/copy":370}],207:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var isObject = require( '@stdlib/assert/is-plain-object' ); var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; var isNull = require( '@stdlib/assert/is-null' ); var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive; // MAIN // /** * Validates function options. * * @private * @param {Object} opts - destination object * @param {Options} options - function options * @param {boolean} [options.skip] - boolean indicating whether to skip a benchmark * @param {(PositiveInteger|null)} [options.iterations] - number of iterations * @param {PositiveInteger} [options.repeats] - number of repeats * @param {PositiveInteger} [options.timeout] - number of milliseconds before a benchmark automatically fails * @returns {(Error|null)} error object or null * * @example * var opts = {}; * var options = { * 'skip': false, * 'iterations': 1e6, * 'repeats': 3, * 'timeout': 10000 * }; * * var err = validate( opts, options ); * if ( err ) { * throw err; * } */ function validate( opts, options ) { if ( !isObject( options ) ) { return new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' ); } if ( hasOwnProp( options, 'skip' ) ) { opts.skip = options.skip; if ( !isBoolean( opts.skip ) ) { return new TypeError( 'invalid option. `skip` option must be a boolean primitive. Option: `' + opts.skip + '`.' ); } } if ( hasOwnProp( options, 'iterations' ) ) { opts.iterations = options.iterations; if ( !isPositiveInteger( opts.iterations ) && !isNull( opts.iterations ) ) { return new TypeError( 'invalid option. `iterations` option must be either a positive integer or `null`. Option: `' + opts.iterations + '`.' ); } } if ( hasOwnProp( options, 'repeats' ) ) { opts.repeats = options.repeats; if ( !isPositiveInteger( opts.repeats ) ) { return new TypeError( 'invalid option. `repeats` option must be a positive integer. Option: `' + opts.repeats + '`.' ); } } if ( hasOwnProp( options, 'timeout' ) ) { opts.timeout = options.timeout; if ( !isPositiveInteger( opts.timeout ) ) { return new TypeError( 'invalid option. `timeout` option must be a positive integer. Option: `' + opts.timeout + '`.' ); } } return null; } // EXPORTS // module.exports = validate; },{"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-null":135,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-positive-integer":149}],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'; /** * 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":180}],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 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":210,"@stdlib/streams/node/transform":348,"@stdlib/string/from-code-point":352}],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'; // 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; },{}],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 // /** * Removes any pending benchmarks. * * @private */ function clear() { /* eslint-disable no-invalid-this */ this._benchmarks.length = 0; } // EXPORTS // module.exports = clear; },{}],212:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MAIN // /** * 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; },{}],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. */ /* 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":222,"@stdlib/assert/is-string":158,"@stdlib/streams/node/transform":348}],214:[function(require,module,exports){ /* eslint-disable stdlib/jsdoc-require-throws-tags */ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var replace = require( '@stdlib/string/replace' ); var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var reEOL = require( '@stdlib/regexp/eol' ); // VARIABLES // var RE_WHITESPACE = /\s+/g; // MAIN // /** * Encodes an assertion. * * @private * @param {Object} result - result * @param {PositiveInteger} count - result count * @returns {string} encoded assertion */ function encodeAssertion( result, count ) { var actualStack; var errorStack; var expected; var actual; var indent; var stack; var lines; var out; var i; out = ''; if ( !result.ok ) { out += 'not '; } // Add result count: out += 'ok ' + count; // Add description: if ( result.name ) { out += ' ' + replace( result.name.toString(), RE_WHITESPACE, ' ' ); } // Append directives: if ( result.skip ) { out += ' # SKIP'; } else if ( result.todo ) { out += ' # TODO'; } out += '\n'; if ( result.ok ) { return out; } // Format diagnostics as YAML... indent = ' '; out += indent + '---\n'; out += indent + 'operator: ' + result.operator + '\n'; if ( hasOwnProp( result, 'actual' ) || hasOwnProp( result, 'expected' ) ) { // TODO: inspect object logic (https://github.com/substack/tape/blob/master/lib/results.js#L145) expected = result.expected; actual = result.actual; if ( actual !== actual && expected !== expected ) { throw new Error( 'TODO: remove me' ); } } if ( result.at ) { out += indent + 'at: ' + result.at + '\n'; } if ( result.actual ) { actualStack = result.actual.stack; } if ( result.error ) { errorStack = result.error.stack; } if ( actualStack ) { stack = actualStack; } else { stack = errorStack; } if ( stack ) { lines = stack.toString().split( reEOL.REGEXP ); out += indent + 'stack: |-\n'; for ( i = 0; i < lines.length; i++ ) { out += indent + ' ' + lines[ i ] + '\n'; } } out += indent + '...\n'; return out; } // EXPORTS // module.exports = encodeAssertion; },{"@stdlib/assert/has-own-property":53,"@stdlib/regexp/eol":327,"@stdlib/string/replace":354}],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'; // 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; },{}],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'; // 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; },{}],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 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":211,"./close.js":212,"./create_stream.js":213,"./exit.js":216,"./push.js":218,"./run.js":219,"@stdlib/streams/node/transform":348,"@stdlib/utils/define-property":381,"@stdlib/utils/inherit":402,"events":455}],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. */ /* 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":214,"./encode_result.js":215,"@stdlib/assert/is-string":158}],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'; // MAIN // /** * Runs pending benchmarks. * * @private */ function run() { /* eslint-disable no-invalid-this */ this.emit( '_run' ); } // EXPORTS // module.exports = run; },{}],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 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":221,"@stdlib/assert/is-browser":87}],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'; // MODULES // var proc = require( './process.js' ); // MAIN // var bool = ( proc && typeof proc.exit === 'function' ); // EXPORTS // module.exports = bool; },{"./process.js":223}],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'; // 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; },{}],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'; // MODULES // var proc = require( 'process' ); // EXPORTS // module.exports = proc; },{"process":466}],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'; /** * 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":208}],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'; /** * BLAS level 1 routine to copy values from `x` into `y`. * * @module @stdlib/blas/base/gcopy * * @example * var gcopy = require( '@stdlib/blas/base/gcopy' ); * * var x = [ 1.0, 2.0, 3.0, 4.0, 5.0 ]; * var y = [ 6.0, 7.0, 8.0, 9.0, 10.0 ]; * * gcopy( x.length, x, 1, y, 1 ); * // y => [ 1.0, 2.0, 3.0, 4.0, 5.0 ] * * @example * var gcopy = require( '@stdlib/blas/base/gcopy' ); * * var x = [ 1.0, 2.0, 3.0, 4.0, 5.0 ]; * var y = [ 6.0, 7.0, 8.0, 9.0, 10.0 ]; * * gcopy.ndarray( x.length, x, 1, 0, y, 1, 0 ); * // y => [ 1.0, 2.0, 3.0, 4.0, 5.0 ] */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var gcopy = require( './main.js' ); var ndarray = require( './ndarray.js' ); // MAIN // setReadOnly( gcopy, 'ndarray', ndarray ); // EXPORTS // module.exports = gcopy; },{"./main.js":226,"./ndarray.js":227,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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'; // VARIABLES // var M = 8; // MAIN // /** * Copies values from `x` into `y`. * * @param {PositiveInteger} N - number of values to copy * @param {NumericArray} x - input array * @param {integer} strideX - `x` stride length * @param {NumericArray} y - destination array * @param {integer} strideY - `y` stride length * @returns {NumericArray} `y` * * @example * var x = [ 1.0, 2.0, 3.0, 4.0, 5.0 ]; * var y = [ 6.0, 7.0, 8.0, 9.0, 10.0 ]; * * gcopy( x.length, x, 1, y, 1 ); * // y => [ 1.0, 2.0, 3.0, 4.0, 5.0 ] */ function gcopy( N, x, strideX, y, strideY ) { var ix; var iy; var m; var i; if ( N <= 0 ) { return y; } // Use unrolled loops if both strides are equal to `1`... if ( strideX === 1 && strideY === 1 ) { m = N % M; // If we have a remainder, run a clean-up loop... if ( m > 0 ) { for ( i = 0; i < m; i++ ) { y[ i ] = x[ i ]; } } if ( N < M ) { return y; } for ( i = m; i < N; i += M ) { y[ i ] = x[ i ]; y[ i+1 ] = x[ i+1 ]; y[ i+2 ] = x[ i+2 ]; y[ i+3 ] = x[ i+3 ]; y[ i+4 ] = x[ i+4 ]; y[ i+5 ] = x[ i+5 ]; y[ i+6 ] = x[ i+6 ]; y[ i+7 ] = x[ i+7 ]; } return y; } if ( strideX < 0 ) { ix = (1-N) * strideX; } else { ix = 0; } if ( strideY < 0 ) { iy = (1-N) * strideY; } else { iy = 0; } for ( i = 0; i < N; i++ ) { y[ iy ] = x[ ix ]; ix += strideX; iy += strideY; } return y; } // EXPORTS // module.exports = gcopy; },{}],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'; // VARIABLES // var M = 8; // MAIN // /** * Copies values from `x` into `y`. * * @param {PositiveInteger} N - number of values to copy * @param {NumericArray} x - input array * @param {integer} strideX - `x` stride length * @param {NonNegativeInteger} offsetX - starting `x` index * @param {NumericArray} y - destination array * @param {integer} strideY - `y` stride length * @param {NonNegativeInteger} offsetY - starting `y` index * @returns {NumericArray} `y` * * @example * var x = [ 1.0, 2.0, 3.0, 4.0, 5.0 ]; * var y = [ 6.0, 7.0, 8.0, 9.0, 10.0 ]; * * gcopy( x.length, x, 1, 0, y, 1, 0 ); * // y => [ 1.0, 2.0, 3.0, 4.0, 5.0 ] */ function gcopy( N, x, strideX, offsetX, y, strideY, offsetY ) { var ix; var iy; var m; var i; if ( N <= 0 ) { return y; } ix = offsetX; iy = offsetY; // Use unrolled loops if both strides are equal to `1`... if ( strideX === 1 && strideY === 1 ) { m = N % M; // If we have a remainder, run a clean-up loop... if ( m > 0 ) { for ( i = 0; i < m; i++ ) { y[ iy ] = x[ ix ]; ix += strideX; iy += strideY; } } if ( N < M ) { return y; } for ( i = m; i < N; i += M ) { y[ iy ] = x[ ix ]; y[ iy+1 ] = x[ ix+1 ]; y[ iy+2 ] = x[ ix+2 ]; y[ iy+3 ] = x[ ix+3 ]; y[ iy+4 ] = x[ ix+4 ]; y[ iy+5 ] = x[ ix+5 ]; y[ iy+6 ] = x[ ix+6 ]; y[ iy+7 ] = x[ ix+7 ]; ix += M; iy += M; } return y; } for ( i = 0; i < N; i++ ) { y[ iy ] = x[ ix ]; ix += strideX; iy += strideY; } return y; } // EXPORTS // module.exports = gcopy; },{}],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'; // MAIN // var ctor = require( 'buffer' ).Buffer; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = ctor; },{"buffer":456}],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'; /** * 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":228,"./polyfill.js":230,"@stdlib/assert/has-node-buffer-support":51}],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'; // TODO: write (browser) polyfill // MAIN // /** * Buffer constructor. * * @throws {Error} not implemented */ function polyfill() { throw new Error( 'not implemented' ); } // EXPORTS // module.exports = polyfill; },{}],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'; // 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":102,"@stdlib/buffer/ctor":229}],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'; /** * 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":231,"./main.js":233,"./polyfill.js":234}],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'; // MODULES // var isBuffer = require( '@stdlib/assert/is-buffer' ); var Buffer = require( '@stdlib/buffer/ctor' ); // MAIN // /** * Copies buffer data to a new `Buffer` instance. * * @param {Buffer} buffer - buffer from which to copy * @throws {TypeError} must provide a `Buffer` instance * @returns {Buffer} new `Buffer` instance * * @example * var fromArray = require( '@stdlib/buffer/from-array' ); * * var b1 = fromArray( [ 1, 2, 3, 4 ] ); * // returns <Buffer> * * var b2 = fromBuffer( b1 ); * // returns <Buffer> */ function fromBuffer( buffer ) { if ( !isBuffer( buffer ) ) { throw new TypeError( 'invalid argument. Must provide a Buffer. Value: `' + buffer + '`' ); } return Buffer.from( buffer ); } // EXPORTS // module.exports = fromBuffer; },{"@stdlib/assert/is-buffer":88,"@stdlib/buffer/ctor":229}],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'; // MODULES // var isBuffer = require( '@stdlib/assert/is-buffer' ); var Buffer = require( '@stdlib/buffer/ctor' ); // MAIN // /** * Copies buffer data to a new `Buffer` instance. * * @param {Buffer} buffer - buffer from which to copy * @throws {TypeError} must provide a `Buffer` instance * @returns {Buffer} new `Buffer` instance * * @example * var fromArray = require( '@stdlib/buffer/from-array' ); * * var b1 = fromArray( [ 1, 2, 3, 4 ] ); * // returns <Buffer> * * var b2 = fromBuffer( b1 ); * // returns <Buffer> */ function fromBuffer( buffer ) { if ( !isBuffer( buffer ) ) { throw new TypeError( 'invalid argument. Must provide a Buffer. Value: `' + buffer + '`' ); } return new Buffer( buffer ); // eslint-disable-line no-buffer-constructor } // EXPORTS // module.exports = fromBuffer; },{"@stdlib/assert/is-buffer":88,"@stdlib/buffer/ctor":229}],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 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; },{}],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 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; },{}],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'; /** * Difference between one and the smallest value greater than one that can be represented as a double-precision floating-point number. * * @module @stdlib/constants/float64/eps * @type {number} * * @example * var FLOAT64_EPSILON = require( '@stdlib/constants/float64/eps' ); * // returns 2.220446049250313e-16 */ // MAIN // /** * Difference between one and the smallest value greater than one that can be represented as a double-precision floating-point number. * * ## Notes * * The difference is * * ```tex * \frac{1}{2^{52}} * ``` * * @constant * @type {number} * @default 2.220446049250313e-16 * @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985} * @see [Machine Epsilon]{@link https://en.wikipedia.org/wiki/Machine_epsilon} */ var FLOAT64_EPSILON = 2.2204460492503130808472633361816E-16; // EXPORTS // module.exports = FLOAT64_EPSILON; },{}],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'; /** * 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; },{}],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'; /** * 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; },{}],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'; /** * 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; },{}],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'; /** * The maximum biased base 2 exponent for a subnormal double-precision floating-point number. * * @module @stdlib/constants/float64/max-base2-exponent-subnormal * @type {integer32} * * @example * var FLOAT64_MAX_BASE2_EXPONENT_SUBNORMAL = require( '@stdlib/constants/float64/max-base2-exponent-subnormal' ); * // returns -1023 */ // MAIN // /** * The maximum biased base 2 exponent for a subnormal double-precision floating-point number. * * ```text * 00000000000 => 0 - BIAS = -1023 * ``` * * where `BIAS = 1023`. * * @constant * @type {integer32} * @default -1023 * @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985} */ var FLOAT64_MAX_BASE2_EXPONENT_SUBNORMAL = -1023|0; // asm type annotation // EXPORTS // module.exports = FLOAT64_MAX_BASE2_EXPONENT_SUBNORMAL; },{}],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'; /** * The maximum biased base 2 exponent for a double-precision floating-point number. * * @module @stdlib/constants/float64/max-base2-exponent * @type {integer32} * * @example * var FLOAT64_MAX_BASE2_EXPONENT = require( '@stdlib/constants/float64/max-base2-exponent' ); * // returns 1023 */ // MAIN // /** * The maximum biased base 2 exponent for a double-precision floating-point number. * * ```text * 11111111110 => 2046 - BIAS = 1023 * ``` * * where `BIAS = 1023`. * * @constant * @type {integer32} * @default 1023 * @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985} */ var FLOAT64_MAX_BASE2_EXPONENT = 1023|0; // asm type annotation // EXPORTS // module.exports = FLOAT64_MAX_BASE2_EXPONENT; },{}],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'; /** * Maximum safe double-precision floating-point integer. * * @module @stdlib/constants/float64/max-safe-integer * @type {number} * * @example * var FLOAT64_MAX_SAFE_INTEGER = require( '@stdlib/constants/float64/max-safe-integer' ); * // returns 9007199254740991 */ // MAIN // /** * Maximum safe double-precision floating-point integer. * * ## Notes * * The integer has the value * * ```tex * 2^{53} - 1 * ``` * * @constant * @type {number} * @default 9007199254740991 * @see [Safe Integers]{@link http://www.2ality.com/2013/10/safe-integers.html} * @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985} */ var FLOAT64_MAX_SAFE_INTEGER = 9007199254740991; // EXPORTS // module.exports = FLOAT64_MAX_SAFE_INTEGER; },{}],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'; /** * The minimum biased base 2 exponent for a subnormal double-precision floating-point number. * * @module @stdlib/constants/float64/min-base2-exponent-subnormal * @type {integer32} * * @example * var FLOAT64_MIN_BASE2_EXPONENT_SUBNORMAL = require( '@stdlib/constants/float64/min-base2-exponent-subnormal' ); * // returns -1074 */ // MAIN // /** * The minimum biased base 2 exponent for a subnormal double-precision floating-point number. * * ```text * -(BIAS+(52-1)) = -(1023+51) = -1074 * ``` * * where `BIAS = 1023` and `52` is the number of digits in the significand. * * @constant * @type {integer32} * @default -1074 * @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985} */ var FLOAT64_MIN_BASE2_EXPONENT_SUBNORMAL = -1074|0; // asm type annotation // EXPORTS // module.exports = FLOAT64_MIN_BASE2_EXPONENT_SUBNORMAL; },{}],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'; /** * 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":292}],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'; /** * 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; },{}],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'; /** * Smallest positive double-precision floating-point normal number. * * @module @stdlib/constants/float64/smallest-normal * @type {number} * * @example * var FLOAT64_SMALLEST_NORMAL = require( '@stdlib/constants/float64/smallest-normal' ); * // returns 2.2250738585072014e-308 */ // MAIN // /** * The smallest positive double-precision floating-point normal number. * * ## Notes * * The number has the value * * ```tex * \frac{1}{2^{1023-1}} * ``` * * which corresponds to the bit sequence * * ```binarystring * 0 00000000001 00000000000000000000 00000000000000000000000000000000 * ``` * * @constant * @type {number} * @default 2.2250738585072014e-308 * @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985} */ var FLOAT64_SMALLEST_NORMAL = 2.2250738585072014e-308; // EXPORTS // module.exports = FLOAT64_SMALLEST_NORMAL; },{}],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'; /** * 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; },{}],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'; /** * 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; },{}],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'; /** * 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; },{}],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'; /** * 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; },{}],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'; /** * 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; },{}],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'; /** * 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; },{}],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'; /** * 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; },{}],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'; /** * 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; },{}],256:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * 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; },{}],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'; /** * 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; },{}],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'; /** * 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; },{}],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'; /** * Test if a double-precision floating-point numeric value is infinite. * * @module @stdlib/math/base/assert/is-infinite * * @example * var isInfinite = require( '@stdlib/math/base/assert/is-infinite' ); * * var bool = isInfinite( Infinity ); * // returns true * * bool = isInfinite( -Infinity ); * // returns true * * bool = isInfinite( 5.0 ); * // returns false * * bool = isInfinite( NaN ); * // returns false */ // MODULES // var isInfinite = require( './main.js' ); // EXPORTS // module.exports = isInfinite; },{"./main.js":260}],260:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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' ); // MAIN // /** * Tests if a double-precision floating-point numeric value is infinite. * * @param {number} x - value to test * @returns {boolean} boolean indicating whether the value is infinite * * @example * var bool = isInfinite( Infinity ); * // returns true * * @example * var bool = isInfinite( -Infinity ); * // returns true * * @example * var bool = isInfinite( 5.0 ); * // returns false * * @example * var bool = isInfinite( NaN ); * // returns false */ function isInfinite( x ) { return (x === PINF || x === NINF); } // EXPORTS // module.exports = isInfinite; },{"@stdlib/constants/float64/ninf":245,"@stdlib/constants/float64/pinf":246}],261:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":262}],262:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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":277}],263:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":264}],264:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // 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; },{}],265:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * Test if a double-precision floating-point numeric value is positive zero. * * @module @stdlib/math/base/assert/is-positive-zero * * @example * var isPositiveZero = require( '@stdlib/math/base/assert/is-positive-zero' ); * * var bool = isPositiveZero( 0.0 ); * // returns true * * bool = isPositiveZero( -0.0 ); * // returns false */ // MODULES // var isPositiveZero = require( './main.js' ); // EXPORTS // module.exports = isPositiveZero; },{"./main.js":266}],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 PINF = require( '@stdlib/constants/float64/pinf' ); // MAIN // /** * Tests if a double-precision floating-point numeric value is positive zero. * * @param {number} x - value to test * @returns {boolean} boolean indicating whether the value is positive zero * * @example * var bool = isPositiveZero( 0.0 ); * // returns true * * @example * var bool = isPositiveZero( -0.0 ); * // returns false */ function isPositiveZero( x ) { return (x === 0.0 && 1.0/x === PINF); } // EXPORTS // module.exports = isPositiveZero; },{"@stdlib/constants/float64/pinf":246}],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'; /** * Compute an absolute value of a double-precision floating-point number. * * @module @stdlib/math/base/special/abs * * @example * var abs = require( '@stdlib/math/base/special/abs' ); * * var v = abs( -1.0 ); * // returns 1.0 * * v = abs( 2.0 ); * // returns 2.0 * * v = abs( 0.0 ); * // returns 0.0 * * v = abs( -0.0 ); * // returns 0.0 * * v = abs( NaN ); * // returns NaN */ // MODULES // var abs = require( './main.js' ); // EXPORTS // module.exports = abs; },{"./main.js":268}],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 // /** * Computes the absolute value of a double-precision floating-point number `x`. * * @param {number} x - input value * @returns {number} absolute value * * @example * var v = abs( -1.0 ); * // returns 1.0 * * @example * var v = abs( 2.0 ); * // returns 2.0 * * @example * var v = abs( 0.0 ); * // returns 0.0 * * @example * var v = abs( -0.0 ); * // returns 0.0 * * @example * var v = abs( NaN ); * // returns NaN */ function abs( x ) { return Math.abs( x ); // eslint-disable-line stdlib/no-builtin-math } // EXPORTS // module.exports = abs; },{}],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'; /** * Round a double-precision floating-point number toward positive infinity. * * @module @stdlib/math/base/special/ceil * * @example * var ceil = require( '@stdlib/math/base/special/ceil' ); * * var v = ceil( -4.2 ); * // returns -4.0 * * v = ceil( 9.99999 ); * // returns 10.0 * * v = ceil( 0.0 ); * // returns 0.0 * * v = ceil( NaN ); * // returns NaN */ // MODULES // var ceil = require( './main.js' ); // EXPORTS // module.exports = ceil; },{"./main.js":270}],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'; // TODO: implementation (?) /** * Rounds a double-precision floating-point number toward positive infinity. * * @param {number} x - input value * @returns {number} rounded value * * @example * var v = ceil( -4.2 ); * // returns -4.0 * * @example * var v = ceil( 9.99999 ); * // returns 10.0 * * @example * var v = ceil( 0.0 ); * // returns 0.0 * * @example * var v = ceil( NaN ); * // returns NaN */ var ceil = Math.ceil; // eslint-disable-line stdlib/no-builtin-math // EXPORTS // module.exports = ceil; },{}],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 toWords = require( '@stdlib/number/float64/base/to-words' ); var getHighWord = require( '@stdlib/number/float64/base/get-high-word' ); var fromWords = require( '@stdlib/number/float64/base/from-words' ); // VARIABLES // // 10000000000000000000000000000000 => 2147483648 => 0x80000000 var SIGN_MASK = 0x80000000>>>0; // asm type annotation // 01111111111111111111111111111111 => 2147483647 => 0x7fffffff var MAGNITUDE_MASK = 0x7fffffff|0; // asm type annotation // High/low words workspace: var WORDS = [ 0, 0 ]; // WARNING: not thread safe // MAIN // /** * Returns a double-precision floating-point number with the magnitude of `x` and the sign of `y`. * * @param {number} x - number from which to derive a magnitude * @param {number} y - number from which to derive a sign * @returns {number} a double-precision floating-point number * * @example * var z = copysign( -3.14, 10.0 ); * // returns 3.14 * * @example * var z = copysign( 3.14, -1.0 ); * // returns -3.14 * * @example * var z = copysign( 1.0, -0.0 ); * // returns -1.0 * * @example * var z = copysign( -3.14, -0.0 ); * // returns -3.14 * * @example * var z = copysign( -0.0, 1.0 ); * // returns 0.0 */ function copysign( x, y ) { var hx; var hy; // Split `x` into higher and lower order words: toWords( WORDS, x ); hx = WORDS[ 0 ]; // Turn off the sign bit of `x`: hx &= MAGNITUDE_MASK; // Extract the higher order word from `y`: hy = getHighWord( y ); // Leave only the sign bit of `y` turned on: hy &= SIGN_MASK; // Copy the sign bit of `y` to `x`: hx |= hy; // Return a new value having the same magnitude as `x`, but with the sign of `y`: return fromWords( hx, WORDS[ 1 ] ); } // EXPORTS // module.exports = copysign; },{"@stdlib/number/float64/base/from-words":296,"@stdlib/number/float64/base/get-high-word":300,"@stdlib/number/float64/base/to-words":305}],272:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * Return a double-precision floating-point number with the magnitude of `x` and the sign of `y`. * * @module @stdlib/math/base/special/copysign * * @example * var copysign = require( '@stdlib/math/base/special/copysign' ); * * var z = copysign( -3.14, 10.0 ); * // returns 3.14 * * z = copysign( 3.14, -1.0 ); * // returns -3.14 * * z = copysign( 1.0, -0.0 ); * // returns -1.0 * * z = copysign( -3.14, -0.0 ); * // returns -3.14 * * z = copysign( -0.0, 1.0 ); * // returns 0.0 */ // MODULES // var copysign = require( './copysign.js' ); // EXPORTS // module.exports = copysign; },{"./copysign.js":271}],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. * * * ## Notice * * The following copyright, license, and long comment were part of the original implementation available as part of [FreeBSD]{@link https://svnweb.freebsd.org/base/release/9.3.0/lib/msun/src/e_exp.c}. The implementation follows the original, but has been modified for JavaScript. * * ```text * Copyright (C) 2004 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ``` */ 'use strict'; // MODULES // var isnan = require( '@stdlib/math/base/assert/is-nan' ); var trunc = require( '@stdlib/math/base/special/trunc' ); var NINF = require( '@stdlib/constants/float64/ninf' ); var PINF = require( '@stdlib/constants/float64/pinf' ); var expmulti = require( './expmulti.js' ); // VARIABLES // var LN2_HI = 6.93147180369123816490e-01; var LN2_LO = 1.90821492927058770002e-10; var LOG2_E = 1.44269504088896338700e+00; var OVERFLOW = 7.09782712893383973096e+02; var UNDERFLOW = -7.45133219101941108420e+02; var NEARZERO = 1.0 / (1 << 28); // 2^-28; var NEG_NEARZERO = -NEARZERO; // MAIN // /** * Evaluates the natural exponential function. * * ## Method * * 1. We reduce \\( x \\) to an \\( r \\) so that \\( |r| \leq 0.5 \cdot \ln(2) \approx 0.34658 \\). Given \\( x \\), we find an \\( r \\) and integer \\( k \\) such that * * ```tex * \begin{align*} * x &= k \cdot \ln(2) + r \\ * |r| &\leq 0.5 \cdot \ln(2) * \end{align*} * ``` * * <!-- <note> --> * * \\( r \\) can be represented as \\( r = \mathrm{hi} - \mathrm{lo} \\) for better accuracy. * * <!-- </note> --> * * 2. We approximate of \\( e^{r} \\) by a special rational function on the interval \\(\[0,0.34658]\\): * * ```tex * \begin{align*} * R\left(r^2\right) &= r \cdot \frac{ e^{r}+1 }{ e^{r}-1 } \\ * &= 2 + \frac{r^2}{6} - \frac{r^4}{360} + \ldots * \end{align*} * ``` * * We use a special Remes algorithm on \\(\[0,0.34658]\\) to generate a polynomial of degree \\(5\\) to approximate \\(R\\). The maximum error of this polynomial approximation is bounded by \\(2^{-59}\\). In other words, * * ```tex * R(z) \sim 2 + P_1 z + P_2 z^2 + P_3 z^3 + P_4 z^4 + P_5 z^5 * ``` * * where \\( z = r^2 \\) and * * ```tex * \left| 2 + P_1 z + \ldots + P_5 z^5 - R(z) \right| \leq 2^{-59} * ``` * * <!-- <note> --> * * The values of \\( P_1 \\) to \\( P_5 \\) are listed in the source code. * * <!-- </note> --> * * The computation of \\( e^{r} \\) thus becomes * * ```tex * \begin{align*} * e^{r} &= 1 + \frac{2r}{R-r} \\ * &= 1 + r + \frac{r \cdot R_1(r)}{2 - R_1(r)}\ \text{for better accuracy} * \end{align*} * ``` * * where * * ```tex * R_1(r) = r - P_1\ r^2 + P_2\ r^4 + \ldots + P_5\ r^{10} * ``` * * 3. We scale back to obtain \\( e^{x} \\). From step 1, we have * * ```tex * e^{x} = 2^k e^{r} * ``` * * * ## Special Cases * * ```tex * \begin{align*} * e^\infty &= \infty \\ * e^{-\infty} &= 0 \\ * e^{\mathrm{NaN}} &= \mathrm{NaN} \\ * e^0 &= 1\ \mathrm{is\ exact\ for\ finite\ argument\ only} * \end{align*} * ``` * * ## Notes * * - According to an error analysis, the error is always less than \\(1\\) ulp (unit in the last place). * * - For an IEEE double, * * - if \\(x > 7.09782712893383973096\mbox{e+}02\\), then \\(e^{x}\\) overflows * - if \\(x < -7.45133219101941108420\mbox{e+}02\\), then \\(e^{x}\\) underflows * * - The hexadecimal values included in the source code are the intended ones for the used constants. Decimal values may be used, provided that the compiler will convert from decimal to binary accurately enough to produce the intended hexadecimal values. * * * @param {number} x - input value * @returns {number} function value * * @example * var v = exp( 4.0 ); * // returns ~54.5982 * * @example * var v = exp( -9.0 ); * // returns ~1.234e-4 * * @example * var v = exp( 0.0 ); * // returns 1.0 * * @example * var v = exp( NaN ); * // returns NaN */ function exp( x ) { var hi; var lo; var k; if ( isnan( x ) || x === PINF ) { return x; } if ( x === NINF ) { return 0.0; } if ( x > OVERFLOW ) { return PINF; } if ( x < UNDERFLOW ) { return 0.0; } if ( x > NEG_NEARZERO && x < NEARZERO ) { return 1.0 + x; } // Reduce and compute `r = hi - lo` for extra precision. if ( x < 0.0 ) { k = trunc( (LOG2_E*x) - 0.5 ); } else { k = trunc( (LOG2_E*x) + 0.5 ); } hi = x - (k*LN2_HI); lo = k * LN2_LO; return expmulti( hi, lo, k ); } // EXPORTS // module.exports = exp; },{"./expmulti.js":274,"@stdlib/constants/float64/ninf":245,"@stdlib/constants/float64/pinf":246,"@stdlib/math/base/assert/is-nan":263,"@stdlib/math/base/special/trunc":288}],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. * * * ## Notice * * The following copyright, license, and long comment were part of the original implementation available as part of [FreeBSD]{@link https://svnweb.freebsd.org/base/release/9.3.0/lib/msun/src/e_exp.c}. The implementation follows the original, but has been modified for JavaScript. * * ```text * Copyright (C) 2004 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ``` */ 'use strict'; // MODULES // var ldexp = require( '@stdlib/math/base/special/ldexp' ); var polyvalP = require( './polyval_p.js' ); // MAIN // /** * Computes \\(e^{r} 2^k\\) where \\(r = \mathrm{hi} - \mathrm{lo}\\) and \\(|r| \leq \ln(2)/2\\). * * @private * @param {number} hi - upper bound * @param {number} lo - lower bound * @param {integer} k - power of 2 * @returns {number} function value */ function expmulti( hi, lo, k ) { var r; var t; var c; var y; r = hi - lo; t = r * r; c = r - ( t*polyvalP( t ) ); y = 1.0 - ( lo - ( (r*c)/(2.0-c) ) - hi); return ldexp( y, k ); } // EXPORTS // module.exports = expmulti; },{"./polyval_p.js":276,"@stdlib/math/base/special/ldexp":279}],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'; /** * Evaluate the natural exponential function. * * @module @stdlib/math/base/special/exp * * @example * var exp = require( '@stdlib/math/base/special/exp' ); * * var v = exp( 4.0 ); * // returns ~54.5982 * * v = exp( -9.0 ); * // returns ~1.234e-4 * * v = exp( 0.0 ); * // returns 1.0 * * v = exp( NaN ); * // returns NaN */ // MODULES // var exp = require( './exp.js' ); // EXPORTS // module.exports = exp; },{"./exp.js":273}],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. */ /* This is a generated file. Do not edit directly. */ 'use strict'; // MAIN // /** * Evaluates a polynomial. * * ## Notes * * - The implementation uses [Horner's rule][horners-method] for efficient computation. * * [horners-method]: https://en.wikipedia.org/wiki/Horner%27s_method * * * @private * @param {number} x - value at which to evaluate the polynomial * @returns {number} evaluated polynomial */ function evalpoly( x ) { if ( x === 0.0 ) { return 0.16666666666666602; } return 0.16666666666666602 + (x * (-0.0027777777777015593 + (x * (0.00006613756321437934 + (x * (-0.0000016533902205465252 + (x * 4.1381367970572385e-8))))))); // eslint-disable-line max-len } // EXPORTS // module.exports = evalpoly; },{}],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'; /** * 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":278}],278:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // 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; },{}],279:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * Multiply a double-precision floating-point number by an integer power of two. * * @module @stdlib/math/base/special/ldexp * * @example * var ldexp = require( '@stdlib/math/base/special/ldexp' ); * * var x = ldexp( 0.5, 3 ); // => 0.5 * 2^3 = 0.5 * 8 * // returns 4.0 * * x = ldexp( 4.0, -2 ); // => 4 * 2^(-2) = 4 * (1/4) * // returns 1.0 * * x = ldexp( 0.0, 20 ); * // returns 0.0 * * x = ldexp( -0.0, 39 ); * // returns -0.0 * * x = ldexp( NaN, -101 ); * // returns NaN * * x = ldexp( Infinity, 11 ); * // returns Infinity * * x = ldexp( -Infinity, -118 ); * // returns -Infinity */ // MODULES // var ldexp = require( './ldexp.js' ); // EXPORTS // module.exports = ldexp; },{"./ldexp.js":280}],280:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // NOTES // /* * => ldexp: load exponent (see [The Open Group]{@link http://pubs.opengroup.org/onlinepubs/9699919799/functions/ldexp.html} and [cppreference]{@link http://en.cppreference.com/w/c/numeric/math/ldexp}). */ // MODULES // var PINF = require( '@stdlib/constants/float64/pinf' ); var NINF = require( '@stdlib/constants/float64/ninf' ); var BIAS = require( '@stdlib/constants/float64/exponent-bias' ); var MAX_EXPONENT = require( '@stdlib/constants/float64/max-base2-exponent' ); var MAX_SUBNORMAL_EXPONENT = require( '@stdlib/constants/float64/max-base2-exponent-subnormal' ); var MIN_SUBNORMAL_EXPONENT = require( '@stdlib/constants/float64/min-base2-exponent-subnormal' ); var isnan = require( '@stdlib/math/base/assert/is-nan' ); var isInfinite = require( '@stdlib/math/base/assert/is-infinite' ); var copysign = require( '@stdlib/math/base/special/copysign' ); var normalize = require( '@stdlib/number/float64/base/normalize' ); var floatExp = require( '@stdlib/number/float64/base/exponent' ); var toWords = require( '@stdlib/number/float64/base/to-words' ); var fromWords = require( '@stdlib/number/float64/base/from-words' ); // VARIABLES // // 1/(1<<52) = 1/(2**52) = 1/4503599627370496 var TWO52_INV = 2.220446049250313e-16; // Exponent all 0s: 1 00000000000 11111111111111111111 => 2148532223 var CLEAR_EXP_MASK = 0x800fffff>>>0; // asm type annotation // Normalization workspace: var FRAC = [ 0.0, 0.0 ]; // WARNING: not thread safe // High/low words workspace: var WORDS = [ 0, 0 ]; // WARNING: not thread safe // MAIN // /** * Multiplies a double-precision floating-point number by an integer power of two. * * @param {number} frac - fraction * @param {integer} exp - exponent * @returns {number} double-precision floating-point number * * @example * var x = ldexp( 0.5, 3 ); // => 0.5 * 2^3 = 0.5 * 8 * // returns 4.0 * * @example * var x = ldexp( 4.0, -2 ); // => 4 * 2^(-2) = 4 * (1/4) * // returns 1.0 * * @example * var x = ldexp( 0.0, 20 ); * // returns 0.0 * * @example * var x = ldexp( -0.0, 39 ); * // returns -0.0 * * @example * var x = ldexp( NaN, -101 ); * // returns NaN * * @example * var x = ldexp( Infinity, 11 ); * // returns Infinity * * @example * var x = ldexp( -Infinity, -118 ); * // returns -Infinity */ function ldexp( frac, exp ) { var high; var m; if ( frac === 0.0 || // handles +-0 isnan( frac ) || isInfinite( frac ) ) { return frac; } // Normalize the input fraction: normalize( FRAC, frac ); frac = FRAC[ 0 ]; exp += FRAC[ 1 ]; // Extract the exponent from `frac` and add it to `exp`: exp += floatExp( frac ); // Check for underflow/overflow... if ( exp < MIN_SUBNORMAL_EXPONENT ) { return copysign( 0.0, frac ); } if ( exp > MAX_EXPONENT ) { if ( frac < 0.0 ) { return NINF; } return PINF; } // Check for a subnormal and scale accordingly to retain precision... if ( exp <= MAX_SUBNORMAL_EXPONENT ) { exp += 52; m = TWO52_INV; } else { m = 1.0; } // Split the fraction into higher and lower order words: toWords( WORDS, frac ); high = WORDS[ 0 ]; // Clear the exponent bits within the higher order word: high &= CLEAR_EXP_MASK; // Set the exponent bits to the new exponent: high |= ((exp+BIAS) << 20); // Create a new floating-point number: return m * fromWords( high, WORDS[ 1 ] ); } // EXPORTS // module.exports = ldexp; },{"@stdlib/constants/float64/exponent-bias":238,"@stdlib/constants/float64/max-base2-exponent":242,"@stdlib/constants/float64/max-base2-exponent-subnormal":241,"@stdlib/constants/float64/min-base2-exponent-subnormal":244,"@stdlib/constants/float64/ninf":245,"@stdlib/constants/float64/pinf":246,"@stdlib/math/base/assert/is-infinite":259,"@stdlib/math/base/assert/is-nan":263,"@stdlib/math/base/special/copysign":272,"@stdlib/number/float64/base/exponent":294,"@stdlib/number/float64/base/from-words":296,"@stdlib/number/float64/base/normalize":302,"@stdlib/number/float64/base/to-words":305}],281:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * Return the maximum value. * * @module @stdlib/math/base/special/max * * @example * var max = require( '@stdlib/math/base/special/max' ); * * var v = max( 3.14, 4.2 ); * // returns 4.2 * * v = max( 5.9, 3.14, 4.2 ); * // returns 5.9 * * v = max( 3.14, NaN ); * // returns NaN * * v = max( +0.0, -0.0 ); * // returns +0.0 */ // MODULES // var max = require( './max.js' ); // EXPORTS // module.exports = max; },{"./max.js":282}],282:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var isPositiveZero = require( '@stdlib/math/base/assert/is-positive-zero' ); var isnan = require( '@stdlib/math/base/assert/is-nan' ); var NINF = require( '@stdlib/constants/float64/ninf' ); var PINF = require( '@stdlib/constants/float64/pinf' ); // MAIN // /** * Returns the maximum value. * * @param {number} [x] - first number * @param {number} [y] - second number * @param {...number} [args] - numbers * @returns {number} maximum value * * @example * var v = max( 3.14, 4.2 ); * // returns 4.2 * * @example * var v = max( 5.9, 3.14, 4.2 ); * // returns 5.9 * * @example * var v = max( 3.14, NaN ); * // returns NaN * * @example * var v = max( +0.0, -0.0 ); * // returns +0.0 */ function max( x, y ) { var len; var m; var v; var i; len = arguments.length; if ( len === 2 ) { if ( isnan( x ) || isnan( y ) ) { return NaN; } if ( x === PINF || y === PINF ) { return PINF; } if ( x === y && x === 0.0 ) { if ( isPositiveZero( x ) ) { return x; } return y; } if ( x > y ) { return x; } return y; } m = NINF; for ( i = 0; i < len; i++ ) { v = arguments[ i ]; if ( isnan( v ) || v === PINF ) { return v; } if ( v > m ) { m = v; } else if ( v === m && v === 0.0 && isPositiveZero( v ) ) { m = v; } } return m; } // EXPORTS // module.exports = max; },{"@stdlib/constants/float64/ninf":245,"@stdlib/constants/float64/pinf":246,"@stdlib/math/base/assert/is-nan":263,"@stdlib/math/base/assert/is-positive-zero":265}],283:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * 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":284}],284:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":285}],285:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":238,"@stdlib/constants/float64/high-word-exponent-mask":239,"@stdlib/constants/float64/high-word-significand-mask":240,"@stdlib/constants/float64/pinf":246,"@stdlib/math/base/assert/is-nan":263,"@stdlib/number/float64/base/from-words":296,"@stdlib/number/float64/base/to-words":305}],286:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // 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":287}],287:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // 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; },{}],288:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * Round a double-precision floating-point number toward zero. * * @module @stdlib/math/base/special/trunc * * @example * var trunc = require( '@stdlib/math/base/special/trunc' ); * * var v = trunc( -4.2 ); * // returns -4.0 * * v = trunc( 9.99999 ); * // returns 9.0 * * v = trunc( 0.0 ); * // returns 0.0 * * v = trunc( -0.0 ); * // returns -0.0 * * v = trunc( NaN ); * // returns NaN * * v = trunc( Infinity ); * // returns Infinity * * v = trunc( -Infinity ); * // returns -Infinity */ // MODULES // var trunc = require( './main.js' ); // EXPORTS // module.exports = trunc; },{"./main.js":289}],289:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var floor = require( '@stdlib/math/base/special/floor' ); var ceil = require( '@stdlib/math/base/special/ceil' ); // MAIN // /** * Rounds a double-precision floating-point number toward zero. * * @param {number} x - input value * @returns {number} rounded value * * @example * var v = trunc( -4.2 ); * // returns -4.0 * * @example * var v = trunc( 9.99999 ); * // returns 9.0 * * @example * var v = trunc( 0.0 ); * // returns 0.0 * * @example * var v = trunc( -0.0 ); * // returns -0.0 * * @example * var v = trunc( NaN ); * // returns NaN * * @example * var v = trunc( Infinity ); * // returns Infinity * * @example * var v = trunc( -Infinity ); * // returns -Infinity */ function trunc( x ) { if ( x < 0.0 ) { return ceil( x ); } return floor( x ); } // EXPORTS // module.exports = trunc; },{"@stdlib/math/base/special/ceil":269,"@stdlib/math/base/special/floor":277}],290:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * Perform C-like multiplication of two unsigned 32-bit integers. * * @module @stdlib/math/base/special/uimul * * @example * var uimul = require( '@stdlib/math/base/special/uimul' ); * * var v = uimul( 10>>>0, 4>>>0 ); * // returns 40 */ // MODULES // var uimul = require( './main.js' ); // EXPORTS // module.exports = uimul; },{"./main.js":291}],291:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // VARIABLES // // Define a mask for the least significant 16 bits (low word): 65535 => 0x0000ffff => 00000000000000001111111111111111 var LOW_WORD_MASK = 0x0000ffff>>>0; // asm type annotation // MAIN // /** * Performs C-like multiplication of two unsigned 32-bit integers. * * ## Method * * - To emulate C-like multiplication without the aid of 64-bit integers, we recognize that a 32-bit integer can be split into two 16-bit words * * ```tex * a = w_h*2^{16} + w_l * ``` * * where \\( w_h \\) is the most significant 16 bits and \\( w_l \\) is the least significant 16 bits. For example, consider the maximum unsigned 32-bit integer \\( 2^{32}-1 \\) * * ```binarystring * 11111111111111111111111111111111 * ``` * * The 16-bit high word is then * * ```binarystring * 1111111111111111 * ``` * * and the 16-bit low word * * ```binarystring * 1111111111111111 * ``` * * If we cast the high word to 32-bit precision and multiply by \\( 2^{16} \\) (equivalent to a 16-bit left shift), then the bit sequence is * * ```binarystring * 11111111111111110000000000000000 * ``` * * Similarly, upon casting the low word to 32-bit precision, the bit sequence is * * ```binarystring * 00000000000000001111111111111111 * ``` * * From the rules of binary addition, we recognize that adding the two 32-bit values for the high and low words will return our original value \\( 2^{32}-1 \\). * * - Accordingly, the multiplication of two 32-bit integers can be expressed * * ```tex * \begin{align*} * a \cdot b &= ( a_h \cdot 2^{16} + a_l) \cdot ( b_h \cdot 2^{16} + b_l) \\ * &= a_l \cdot b_l + a_h \cdot b_l \cdot 2^{16} + a_l \cdot b_h \cdot 2^{16} + (a_h \cdot b_h) \cdot 2^{32} \\ * &= a_l \cdot b_l + (a_h \cdot b_l + a_l \cdot b_h) \cdot 2^{16} + (a_h \cdot b_h) \cdot 2^{32} * \end{align*} * ``` * * - We note that multiplying (dividing) an integer by \\( 2^n \\) is equivalent to performing a left (right) shift of \\( n \\) bits. * * - Further, as we want to return an integer of the same precision, for a 32-bit integer, the return value will be modulo \\( 2^{32} \\). Stated another way, we only care about the low word of a 64-bit result. * * - Accordingly, the last term, being evenly divisible by \\( 2^{32} \\), drops from the equation leaving the remaining two terms as the remainder. * * ```tex * a \cdot b = a_l \cdot b_l + (a_h \cdot b_l + a_l \cdot b_h) << 16 * ``` * * - Lastly, the second term in the above equation contributes to the middle bits and may cause the product to "overflow". However, we can disregard (`>>>0`) overflow bits due modulo arithmetic, as discussed earlier with regard to the term involving the partial product of high words. * * * @param {uinteger32} a - integer * @param {uinteger32} b - integer * @returns {uinteger32} product * * @example * var v = uimul( 10>>>0, 4>>>0 ); * // returns 40 */ function uimul( a, b ) { var lbits; var mbits; var ha; var hb; var la; var lb; a >>>= 0; // asm type annotation b >>>= 0; // asm type annotation // Isolate the most significant 16-bits: ha = ( a>>>16 )>>>0; // asm type annotation hb = ( b>>>16 )>>>0; // asm type annotation // Isolate the least significant 16-bits: la = ( a&LOW_WORD_MASK )>>>0; // asm type annotation lb = ( b&LOW_WORD_MASK )>>>0; // asm type annotation // Compute partial sums: lbits = ( la*lb )>>>0; // asm type annotation; no integer overflow possible mbits = ( ((ha*lb) + (la*hb))<<16 )>>>0; // asm type annotation; possible integer overflow // The final `>>>0` converts the intermediate sum to an unsigned integer (possible integer overflow during sum): return ( lbits + mbits )>>>0; // asm type annotation } // EXPORTS // module.exports = uimul; },{}],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'; /** * 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":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'; // EXPORTS // module.exports = Number; // eslint-disable-line stdlib/require-globals },{}],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'; /** * Return an integer corresponding to the unbiased exponent of a double-precision floating-point number. * * @module @stdlib/number/float64/base/exponent * * @example * var exponent = require( '@stdlib/number/float64/base/exponent' ); * * var exp = exponent( 3.14e-307 ); // => 2**-1019 ~ 1e-307 * // returns -1019 * * exp = exponent( -3.14 ); * // returns 1 * * exp = exponent( 0.0 ); * // returns -1023 * * exp = exponent( NaN ); * // returns 1024 */ // MODULES // var exponent = require( './main.js' ); // EXPORTS // module.exports = exponent; },{"./main.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 getHighWord = require( '@stdlib/number/float64/base/get-high-word' ); var EXP_MASK = require( '@stdlib/constants/float64/high-word-exponent-mask' ); var BIAS = require( '@stdlib/constants/float64/exponent-bias' ); // MAIN // /** * Returns an integer corresponding to the unbiased exponent of a double-precision floating-point number. * * @param {number} x - input value * @returns {integer32} unbiased exponent * * @example * var exp = exponent( 3.14e-307 ); // => 2**-1019 ~ 1e-307 * // returns -1019 * * @example * var exp = exponent( -3.14 ); * // returns 1 * * @example * var exp = exponent( 0.0 ); * // returns -1023 * * @example * var exp = exponent( NaN ); * // returns 1024 */ function exponent( x ) { // Extract from the input value a higher order word (unsigned 32-bit integer) which contains the exponent: var high = getHighWord( x ); // Apply a mask to isolate only the exponent bits and then shift off all bits which are part of the fraction: high = ( high & EXP_MASK ) >>> 20; // Remove the bias and return: return (high - BIAS)|0; // asm type annotation } // EXPORTS // module.exports = exponent; },{"@stdlib/constants/float64/exponent-bias":238,"@stdlib/constants/float64/high-word-exponent-mask":239,"@stdlib/number/float64/base/get-high-word":300}],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'; /** * 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":298}],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 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":116}],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 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":297,"@stdlib/array/float64":5,"@stdlib/array/uint32":23}],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 isLittleEndian = require( '@stdlib/assert/is-little-endian' ); // MAIN // var HIGH; if ( isLittleEndian === true ) { HIGH = 1; // second index } else { HIGH = 0; // first index } // EXPORTS // module.exports = HIGH; },{"@stdlib/assert/is-little-endian":116}],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'; /** * Return an unsigned 32-bit integer corresponding to the more significant 32 bits of a double-precision floating-point number. * * @module @stdlib/number/float64/base/get-high-word * * @example * var getHighWord = require( '@stdlib/number/float64/base/get-high-word' ); * * var w = getHighWord( 3.14e201 ); // => 01101001110001001000001011000011 * // returns 1774486211 */ // MODULES // var getHighWord = require( './main.js' ); // EXPORTS // module.exports = getHighWord; },{"./main.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'; // MODULES // var Uint32Array = require( '@stdlib/array/uint32' ); var Float64Array = require( '@stdlib/array/float64' ); var HIGH = require( './high.js' ); // VARIABLES // var FLOAT64_VIEW = new Float64Array( 1 ); var UINT32_VIEW = new Uint32Array( FLOAT64_VIEW.buffer ); // MAIN // /** * Returns an unsigned 32-bit integer corresponding to the more significant 32 bits of a double-precision floating-point number. * * ## 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 * * @param {number} x - input value * @returns {uinteger32} higher order word * * @example * var w = getHighWord( 3.14e201 ); // => 01101001110001001000001011000011 * // returns 1774486211 */ function getHighWord( x ) { FLOAT64_VIEW[ 0 ] = x; return UINT32_VIEW[ HIGH ]; } // EXPORTS // module.exports = getHighWord; },{"./high.js":299,"@stdlib/array/float64":5,"@stdlib/array/uint32":23}],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 normal number `y` and exponent `exp` satisfying \\(x = y \cdot 2^\mathrm{exp}\\). * * @module @stdlib/number/float64/base/normalize * * @example * var normalize = require( '@stdlib/number/float64/base/normalize' ); * var pow = require( '@stdlib/math/base/special/pow' ); * * var out = normalize( 3.14e-319 ); * // returns [ 1.4141234400356668e-303, -52 ] * * var y = out[ 0 ]; * var exp = out[ 1 ]; * * var bool = ( y*pow(2.0,exp) === 3.14e-319 ); * // returns true * * @example * var Float64Array = require( '@stdlib/array/float64' ); * var normalize = require( '@stdlib/number/float64/base/normalize' ); * * var out = new Float64Array( 2 ); * * var v = normalize( out, 3.14e-319 ); * // returns <Float64Array>[ 1.4141234400356668e-303, -52 ] * * var bool = ( v === out ); * // returns true */ // MODULES // var normalize = require( './main.js' ); // EXPORTS // module.exports = normalize; },{"./main.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 fcn = require( './normalize.js' ); // MAIN // /** * Returns a normal number `y` and exponent `exp` satisfying \\(x = y \cdot 2^\mathrm{exp}\\). * * @param {(Array|TypedArray|Object)} [out] - output array * @param {number} x - input value * @returns {(Array|TypedArray|Object)} output array * * @example * var pow = require( '@stdlib/math/base/special/pow' ); * * var out = normalize( [ 0.0, 0 ], 3.14e-319 ); * // returns [ 1.4141234400356668e-303, -52 ] * * var y = out[ 0 ]; * var exp = out[ 1 ]; * * var bool = ( y*pow(2.0,exp) === 3.14e-319 ); * // returns true * * @example * var Float64Array = require( '@stdlib/array/float64' ); * var pow = require( '@stdlib/math/base/special/pow' ); * * var out = new Float64Array( 2 ); * * var v = normalize( out, 3.14e-319 ); * // returns <Float64Array>[ 1.4141234400356668e-303, -52 ] * * var bool = ( v === out ); * // returns true * * @example * var out = normalize( [ 0.0, 0 ], 0.0 ); * // returns [ 0.0, 0 ] * * @example * var out = normalize( [ 0.0, 0 ], Infinity ); * // returns [ Infinity, 0 ] * * @example * var out = normalize( [ 0.0, 0 ], -Infinity ); * // returns [ -Infinity, 0 ] * * @example * var out = normalize( [ 0.0, 0 ], NaN ); * // returns [ NaN, 0 ] */ function normalize( out, x ) { if ( arguments.length === 1 ) { return fcn( [ 0.0, 0 ], out ); } return fcn( out, x ); } // EXPORTS // module.exports = normalize; },{"./normalize.js":304}],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'; // MODULES // var FLOAT64_SMALLEST_NORMAL = require( '@stdlib/constants/float64/smallest-normal' ); var isInfinite = require( '@stdlib/math/base/assert/is-infinite' ); var isnan = require( '@stdlib/math/base/assert/is-nan' ); var abs = require( '@stdlib/math/base/special/abs' ); // VARIABLES // // (1<<52) var SCALAR = 4503599627370496; // MAIN // /** * Returns a normal number `y` and exponent `exp` satisfying \\(x = y \cdot 2^\mathrm{exp}\\). * * @private * @param {(Array|TypedArray|Object)} out - output array * @param {number} x - input value * @returns {(Array|TypedArray|Object)} output array * * @example * var pow = require( '@stdlib/math/base/special/pow' ); * * var out = normalize( [ 0.0, 0 ], 3.14e-319 ); * // returns [ 1.4141234400356668e-303, -52 ] * * var y = out[ 0 ]; * var exp = out[ 1 ]; * * var bool = ( y*pow(2.0,exp) === 3.14e-319 ); * // returns true * * @example * var out = normalize( [ 0.0, 0 ], 0.0 ); * // returns [ 0.0, 0 ]; * * @example * var out = normalize( [ 0.0, 0 ], Infinity ); * // returns [ Infinity, 0 ] * * @example * var out = normalize( [ 0.0, 0 ], -Infinity ); * // returns [ -Infinity, 0 ] * * @example * var out = normalize( [ 0.0, 0 ], NaN ); * // returns [ NaN, 0 ] */ function normalize( out, x ) { if ( isnan( x ) || isInfinite( x ) ) { out[ 0 ] = x; out[ 1 ] = 0; return out; } if ( x !== 0.0 && abs( x ) < FLOAT64_SMALLEST_NORMAL ) { out[ 0 ] = x * SCALAR; out[ 1 ] = -52; return out; } out[ 0 ] = x; out[ 1 ] = 0; return out; } // EXPORTS // module.exports = normalize; },{"@stdlib/constants/float64/smallest-normal":247,"@stdlib/math/base/assert/is-infinite":259,"@stdlib/math/base/assert/is-nan":263,"@stdlib/math/base/special/abs":267}],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'; /** * 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":307}],306:[function(require,module,exports){ arguments[4][297][0].apply(exports,arguments) },{"@stdlib/assert/is-little-endian":116,"dup":297}],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 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":308}],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'; // 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":306,"@stdlib/array/float64":5,"@stdlib/array/uint32":23}],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 isnan = require( '@stdlib/math/base/assert/is-nan' ); // VARIABLES // var NUM_WARMUPS = 8; // MAIN // /** * Initializes a shuffle table. * * @private * @param {PRNG} rand - pseudorandom number generator * @param {Int32Array} table - table * @param {PositiveInteger} N - table size * @throws {Error} PRNG returned `NaN` * @returns {NumberArray} shuffle table */ function createTable( rand, table, N ) { var v; var i; // "warm-up" the PRNG... for ( i = 0; i < NUM_WARMUPS; i++ ) { v = rand(); // Prevent the above loop from being discarded by the compiler... if ( isnan( v ) ) { throw new Error( 'unexpected error. PRNG returned `NaN`.' ); } } // Initialize the shuffle table... for ( i = N-1; i >= 0; i-- ) { table[ i ] = rand(); } return table; } // EXPORTS // module.exports = createTable; },{"@stdlib/math/base/assert/is-nan":263}],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. */ /* eslint-disable max-len */ 'use strict'; // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var setReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' ); var setReadWriteAccessor = require( '@stdlib/utils/define-nonenumerable-read-write-accessor' ); var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var isObject = require( '@stdlib/assert/is-plain-object' ); var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; var isCollection = require( '@stdlib/assert/is-collection' ); var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive; var isInt32Array = require( '@stdlib/assert/is-int32array' ); var gcopy = require( '@stdlib/blas/base/gcopy' ); var floor = require( '@stdlib/math/base/special/floor' ); var Int32Array = require( '@stdlib/array/int32' ); var INT32_MAX = require( '@stdlib/constants/int32/max' ); var typedarray2json = require( '@stdlib/array/to-json' ); var createTable = require( './create_table.js' ); var randint32 = require( './rand_int32.js' ); // VARIABLES // var NORMALIZATION_CONSTANT = (INT32_MAX - 1)|0; // asm type annotation var MAX_SEED = (INT32_MAX - 1)|0; // asm type annotation var A = 16807|0; // asm type annotation // Define the number of elements in the shuffle table: var TABLE_LENGTH = 32; // Define the state array schema version: var STATE_ARRAY_VERSION = 1; // NOTE: anytime the state array schema changes, this value should be incremented!!! // Define the number of sections in the state array: var NUM_STATE_SECTIONS = 3; // table, other, seed // Define the index offset of the "table" section in the state array: var TABLE_SECTION_OFFSET = 2; // | version | num_sections | table_length | ...table | other_length | shuffle_state | prng_state | seed_length | ...seed | // Define the index offset of the "state" section in the state array: var STATE_SECTION_OFFSET = TABLE_LENGTH + 3; // | version | num_sections | table_length | ...table | state_length | shuffle_state | prng_state | seed_length | ...seed | // Define the index offset of the seed section in the state array: var SEED_SECTION_OFFSET = TABLE_LENGTH + 6; // | version | num_sections | table_length | ...table | state_length | shuffle_state | prng_state | seed_length | ...seed | // Define the length of the "fixed" length portion of the state array: var STATE_FIXED_LENGTH = TABLE_LENGTH + 7; // 1 (version) + 1 (num_sections) + 1 (table_length) + TABLE_LENGTH (table) + 1 (state_length) + 1 (shuffle_state) + 1 (prng_state) + 1 (seed_length) // Define the indices for the shuffle table and PRNG states: var SHUFFLE_STATE = STATE_SECTION_OFFSET + 1; var PRNG_STATE = STATE_SECTION_OFFSET + 2; // FUNCTIONS // /** * Verifies state array integrity. * * @private * @param {Int32Array} state - state array * @param {boolean} FLG - flag indicating whether the state array was provided as an option (true) or an argument (false) * @returns {(Error|null)} an error or `null` */ function verifyState( state, FLG ) { var s1; if ( FLG ) { s1 = 'option'; } else { s1 = 'argument'; } // The state array must have a minimum length... if ( state.length < STATE_FIXED_LENGTH+1 ) { return new RangeError( 'invalid '+s1+'. `state` array has insufficient length.' ); } // The first element of the state array must equal the supported state array schema version... if ( state[ 0 ] !== STATE_ARRAY_VERSION ) { return new RangeError( 'invalid '+s1+'. `state` array has an incompatible schema version. Expected: '+STATE_ARRAY_VERSION+'. Actual: '+state[ 0 ]+'.' ); } // The second element of the state array must contain the number of sections... if ( state[ 1 ] !== NUM_STATE_SECTIONS ) { return new RangeError( 'invalid '+s1+'. `state` array has an incompatible number of sections. Expected: '+NUM_STATE_SECTIONS+'. Actual: '+state[ 1 ]+'.' ); } // The length of the "table" section must equal `TABLE_LENGTH`... if ( state[ TABLE_SECTION_OFFSET ] !== TABLE_LENGTH ) { return new RangeError( 'invalid '+s1+'. `state` array has an incompatible table length. Expected: '+TABLE_LENGTH+'. Actual: '+state[ TABLE_SECTION_OFFSET ]+'.' ); } // The length of the "state" section must equal `2`... if ( state[ STATE_SECTION_OFFSET ] !== 2 ) { return new RangeError( 'invalid '+s1+'. `state` array has an incompatible state length. Expected: '+(2).toString()+'. Actual: '+state[ STATE_SECTION_OFFSET ]+'.' ); } // The length of the "seed" section much match the empirical length... if ( state[ SEED_SECTION_OFFSET ] !== state.length-STATE_FIXED_LENGTH ) { return new RangeError( 'invalid '+s1+'. `state` array length is incompatible with seed section length. Expected: '+(state.length-STATE_FIXED_LENGTH)+'. Actual: '+state[ SEED_SECTION_OFFSET ]+'.' ); } return null; } // MAIN // /** * Returns a linear congruential pseudorandom number generator (LCG) whose output is shuffled. * * @param {Options} [options] - options * @param {PRNGSeedMINSTD} [options.seed] - pseudorandom number generator seed * @param {PRNGStateMINSTD} [options.state] - pseudorandom number generator state * @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state * @throws {TypeError} options argument must be an object * @throws {TypeError} a seed must be either a positive integer less than the maximum signed 32-bit integer or an array-like object containing integers less than the maximum signed 32-bit integer * @throws {RangeError} a numeric seed must be a positive integer less than the maximum signed 32-bit integer * @throws {TypeError} state must be an `Int32Array` * @throws {Error} must provide a valid state * @throws {TypeError} `copy` option must be a boolean * @returns {PRNG} shuffled LCG PRNG * * @example * var minstd = factory(); * * var v = minstd(); * // returns <number> * * @example * // Return a seeded LCG: * var minstd = factory({ * 'seed': 1234 * }); * * var v = minstd(); * // returns 1421600654 */ function factory( options ) { var STATE; var state; var opts; var seed; var slen; var err; opts = {}; if ( arguments.length ) { if ( !isObject( options ) ) { throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' ); } if ( hasOwnProp( options, 'copy' ) ) { opts.copy = options.copy; if ( !isBoolean( options.copy ) ) { throw new TypeError( 'invalid option. `copy` option must be a boolean. Option: `' + options.copy + '`.' ); } } if ( hasOwnProp( options, 'state' ) ) { state = options.state; opts.state = true; if ( !isInt32Array( state ) ) { throw new TypeError( 'invalid option. `state` option must be an Int32Array. Option: `' + state + '`.' ); } err = verifyState( state, true ); if ( err ) { throw err; } if ( opts.copy === false ) { STATE = state; } else { STATE = new Int32Array( state.length ); gcopy( state.length, state, 1, STATE, 1 ); } // Create a state (table) "view": state = new Int32Array( STATE.buffer, STATE.byteOffset+((TABLE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), TABLE_LENGTH ); // Create a seed "view": seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), state[ SEED_SECTION_OFFSET ] ); } // If provided a PRNG state, we ignore the `seed` option... if ( seed === void 0 ) { if ( hasOwnProp( options, 'seed' ) ) { seed = options.seed; opts.seed = true; if ( isPositiveInteger( seed ) ) { if ( seed > MAX_SEED ) { throw new RangeError( 'invalid option. `seed` option must be a positive integer less than the maximum signed 32-bit integer. Option: `' + seed + '`.' ); } seed |= 0; // asm type annotation } else if ( isCollection( seed ) && seed.length > 0 ) { slen = seed.length; STATE = new Int32Array( STATE_FIXED_LENGTH+slen ); // Initialize sections: STATE[ 0 ] = STATE_ARRAY_VERSION; STATE[ 1 ] = NUM_STATE_SECTIONS; STATE[ TABLE_SECTION_OFFSET ] = TABLE_LENGTH; STATE[ STATE_SECTION_OFFSET ] = 2; STATE[ PRNG_STATE ] = seed[ 0 ]; STATE[ SEED_SECTION_OFFSET ] = slen; // Copy the provided seed array to prevent external mutation, as mutation would lead to an inability to reproduce PRNG values according to the PRNG's stated seed: gcopy.ndarray( slen, seed, 1, 0, STATE, 1, SEED_SECTION_OFFSET+1 ); // Create a state (table) "view": state = new Int32Array( STATE.buffer, STATE.byteOffset+((TABLE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), TABLE_LENGTH ); // Create a seed "view": seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), slen ); // Initialize the internal PRNG state: state = createTable( minstd, state, TABLE_LENGTH ); STATE[ SHUFFLE_STATE ] = state[ 0 ]; } else { throw new TypeError( 'invalid option. `seed` option must be either a positive integer less than the maximum signed 32-bit integer or an array-like object containing integer values less than the maximum signed 32-bit integer. Option: `' + seed + '`.' ); } } else { seed = randint32()|0; // asm type annotation } } } else { seed = randint32()|0; // asm type annotation } if ( state === void 0 ) { STATE = new Int32Array( STATE_FIXED_LENGTH+1 ); // Initialize sections: STATE[ 0 ] = STATE_ARRAY_VERSION; STATE[ 1 ] = NUM_STATE_SECTIONS; STATE[ TABLE_SECTION_OFFSET ] = TABLE_LENGTH; STATE[ STATE_SECTION_OFFSET ] = 2; STATE[ PRNG_STATE ] = seed; STATE[ SEED_SECTION_OFFSET ] = 1; STATE[ SEED_SECTION_OFFSET+1 ] = seed; // Create a state (table) "view": state = new Int32Array( STATE.buffer, STATE.byteOffset+((TABLE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), TABLE_LENGTH ); // Create a seed "view": seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 ); // Initialize the internal PRNG state: state = createTable( minstd, state, TABLE_LENGTH ); STATE[ SHUFFLE_STATE ] = state[ 0 ]; } setReadOnly( minstdShuffle, 'NAME', 'minstd-shuffle' ); setReadOnlyAccessor( minstdShuffle, 'seed', getSeed ); setReadOnlyAccessor( minstdShuffle, 'seedLength', getSeedLength ); setReadWriteAccessor( minstdShuffle, 'state', getState, setState ); setReadOnlyAccessor( minstdShuffle, 'stateLength', getStateLength ); setReadOnlyAccessor( minstdShuffle, 'byteLength', getStateSize ); setReadOnly( minstdShuffle, 'toJSON', toJSON ); setReadOnly( minstdShuffle, 'MIN', 1 ); setReadOnly( minstdShuffle, 'MAX', INT32_MAX-1 ); setReadOnly( minstdShuffle, 'normalized', normalized ); setReadOnly( normalized, 'NAME', minstdShuffle.NAME ); setReadOnlyAccessor( normalized, 'seed', getSeed ); setReadOnlyAccessor( normalized, 'seedLength', getSeedLength ); setReadWriteAccessor( normalized, 'state', getState, setState ); setReadOnlyAccessor( normalized, 'stateLength', getStateLength ); setReadOnlyAccessor( normalized, 'byteLength', getStateSize ); setReadOnly( normalized, 'toJSON', toJSON ); setReadOnly( normalized, 'MIN', (minstdShuffle.MIN-1.0) / NORMALIZATION_CONSTANT ); setReadOnly( normalized, 'MAX', (minstdShuffle.MAX-1.0) / NORMALIZATION_CONSTANT ); return minstdShuffle; /** * Returns the PRNG seed. * * @private * @returns {PRNGSeedMINSTD} seed */ function getSeed() { var len = STATE[ SEED_SECTION_OFFSET ]; return gcopy( len, seed, 1, new Int32Array( len ), 1 ); } /** * Returns the PRNG seed length. * * @private * @returns {PositiveInteger} seed length */ function getSeedLength() { return STATE[ SEED_SECTION_OFFSET ]; } /** * Returns the PRNG state length. * * @private * @returns {PositiveInteger} state length */ function getStateLength() { return STATE.length; } /** * Returns the PRNG state size (in bytes). * * @private * @returns {PositiveInteger} state size (in bytes) */ function getStateSize() { return STATE.byteLength; } /** * Returns the current PRNG state. * * ## Notes * * - The PRNG state array is comprised of a preamble followed by `3` sections: * * 0. preamble (version + number of sections) * 1. shuffle table * 2. internal PRNG state * 3. PRNG seed * * - The first element of the PRNG state array preamble is the state array schema version. * * - The second element of the PRNG state array preamble is the number of state array sections (i.e., `3`). * * - The first element of each section following the preamble specifies the section length. The remaining section elements comprise the section contents. * * @private * @returns {PRNGStateMINSTD} current state */ function getState() { var len = STATE.length; return gcopy( len, STATE, 1, new Int32Array( len ), 1 ); } /** * Sets the PRNG state. * * ## Notes * * - If PRNG state is "shared" (meaning a state array was provided during PRNG creation and **not** copied) and one sets the generator state to a state array having a different length, the PRNG does **not** update the existing shared state and, instead, points to the newly provided state array. In order to synchronize PRNG output according to the new shared state array, the state array for **each** relevant PRNG must be **explicitly** set. * - If PRNG state is "shared" and one sets the generator state to a state array of the same length, the PRNG state is updated (along with the state of all other PRNGs sharing the PRNG's state array). * * @private * @param {PRNGStateMINSTD} s - generator state * @throws {TypeError} must provide an `Int32Array` * @throws {Error} must provide a valid state */ function setState( s ) { var err; if ( !isInt32Array( s ) ) { throw new TypeError( 'invalid argument. Must provide an Int32Array. Value: `' + s + '`.' ); } err = verifyState( s, false ); if ( err ) { throw err; } if ( opts.copy === false ) { if ( opts.state && s.length === STATE.length ) { gcopy( s.length, s, 1, STATE, 1 ); // update current shared state } else { STATE = s; // point to new shared state opts.state = true; // setting this flag allows updating a shared state even if a state array was not provided at PRNG creation } } else { // Check if we can reuse allocated memory... if ( s.length !== STATE.length ) { STATE = new Int32Array( s.length ); // reallocate } gcopy( s.length, s, 1, STATE, 1 ); } // Create a new state (table) "view": state = new Int32Array( STATE.buffer, STATE.byteOffset+((TABLE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), TABLE_LENGTH ); // Create a new seed "view": seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), STATE[ SEED_SECTION_OFFSET ] ); } /** * Serializes the pseudorandom number generator as a JSON object. * * ## Notes * * - `JSON.stringify()` implicitly calls this method when stringifying a PRNG. * * @private * @returns {Object} JSON representation */ function toJSON() { var out = {}; out.type = 'PRNG'; out.name = minstdShuffle.NAME; out.state = typedarray2json( STATE ); out.params = []; return out; } /** * Generates a pseudorandom integer on the interval \\( [1,2^{31}-1) \\). * * @private * @returns {integer32} pseudorandom integer */ function minstd() { var s = STATE[ PRNG_STATE ]|0; // asm type annotation s = ( (A*s)%INT32_MAX )|0; // asm type annotation STATE[ PRNG_STATE ] = s; return s|0; // asm type annotation } /** * Generates a pseudorandom integer on the interval \\( [1,2^{31}-1) \\). * * @private * @returns {integer32} pseudorandom integer * * @example * var v = minstd(); * // returns <number> */ function minstdShuffle() { var s; var i; s = STATE[ SHUFFLE_STATE ]; i = floor( TABLE_LENGTH * (s/INT32_MAX) ); // Pull a state from the table: s = state[ i ]; // Update the PRNG state: STATE[ SHUFFLE_STATE ] = s; // Replace the pulled state: state[ i ] = minstd(); return s; } /** * Generates a pseudorandom number on the interval \\( [0,1) \\). * * @private * @returns {number} pseudorandom number * * @example * var v = normalized(); * // returns <number> */ function normalized() { return (minstdShuffle()-1) / NORMALIZATION_CONSTANT; } } // EXPORTS // module.exports = factory; },{"./create_table.js":309,"./rand_int32.js":313,"@stdlib/array/int32":10,"@stdlib/array/to-json":17,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-collection":90,"@stdlib/assert/is-int32array":106,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-positive-integer":149,"@stdlib/blas/base/gcopy":225,"@stdlib/constants/int32/max":250,"@stdlib/math/base/special/floor":277,"@stdlib/utils/define-nonenumerable-read-only-accessor":372,"@stdlib/utils/define-nonenumerable-read-only-property":374,"@stdlib/utils/define-nonenumerable-read-write-accessor":376}],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'; /** * A linear congruential pseudorandom number generator (LCG) whose output is shuffled. * * @module @stdlib/random/base/minstd-shuffle * * @example * var minstd = require( '@stdlib/random/base/minstd-shuffle' ); * * var v = minstd(); * // returns <number> * * @example * var factory = require( '@stdlib/random/base/minstd-shuffle' ).factory; * * var minstd = factory({ * 'seed': 1234 * }); * * var v = minstd(); * // returns 1421600654 */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var minstd = require( './main.js' ); var factory = require( './factory.js' ); // MAIN // setReadOnly( minstd, 'factory', factory ); // EXPORTS // module.exports = minstd; },{"./factory.js":310,"./main.js":312,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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'; // MODULES // var factory = require( './factory.js' ); var randint32 = require( './rand_int32.js' ); // MAIN // /** * Generates a pseudorandom integer on the interval \\( [1,2^{31}-1) \\). * * ## Method * * Linear congruential generators (LCGs) use the recurrence relation * * ```tex * X_{n+1} = ( a \cdot X_n + c ) \operatorname{mod}(m) * ``` * * where the modulus \\( m \\) is a prime number or power of a prime number and \\( a \\) is a primitive root modulo \\( m \\). * * <!-- <note> --> * * For an LCG to be a Lehmer RNG, the seed \\( X_0 \\) must be coprime to \\( m \\). * * <!-- </note> --> * * In this implementation, the constants \\( a \\), \\( c \\), and \\( m \\) have the values * * ```tex * \begin{align*} * a &= 7^5 = 16807 \\ * c &= 0 \\ * m &= 2^{31} - 1 = 2147483647 * \end{align*} * ``` * * <!-- <note> --> * * The constant \\( m \\) is a Mersenne prime (modulo \\(31\\)). * * <!-- </note> --> * * <!-- <note> --> * * The constant \\( a \\) is a primitive root (modulo \\(31\\)). * * <!-- </note> --> * * Accordingly, the maximum possible product is * * ```tex * 16807 \cdot (m - 1) \approx 2^{46} * ``` * * The values for \\( a \\), \\( c \\), and \\( m \\) are taken from Park and Miller, "Random Number Generators: Good Ones Are Hard To Find". Park's and Miller's article is also the basis for a recipe in the second edition of _Numerical Recipes in C_. * * This implementation subsequently shuffles the output of a linear congruential pseudorandom number generator (LCG) using a shuffle table in accordance with the Bays-Durham algorithm. * * * ## Notes * * - The generator has a period of approximately \\(2.1\mbox{e}9\\) (see [Numerical Recipes in C, 2nd Edition](#references), p. 279). * * * ## References * * - Bays, Carter, and S. D. Durham. 1976. "Improving a Poor Random Number Generator." _ACM Transactions on Mathematical Software_ 2 (1). New York, NY, USA: ACM: 59–64. doi:[10.1145/355666.355670](http://dx.doi.org/10.1145/355666.355670). * - Herzog, T.N., and G. Lord. 2002. _Applications of Monte Carlo Methods to Finance and Insurance_. ACTEX Publications. [https://books.google.com/books?id=vC7I\\\_gdX-A0C](https://books.google.com/books?id=vC7I\_gdX-A0C). * - Press, William H., Brian P. Flannery, Saul A. Teukolsky, and William T. Vetterling. 1992. _Numerical Recipes in C: The Art of Scientific Computing, Second Edition_. Cambridge University Press. * * * @function minstd * @type {PRNG} * @returns {PositiveInteger} pseudorandom integer * * @example * var v = minstd(); * // returns <number> */ var minstd = factory({ 'seed': randint32() }); // EXPORTS // module.exports = minstd; },{"./factory.js":310,"./rand_int32.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 INT32_MAX = require( '@stdlib/constants/int32/max' ); var floor = require( '@stdlib/math/base/special/floor' ); // VARIABLES // var MAX = INT32_MAX - 1; // MAIN // /** * Returns a pseudorandom integer on the interval \\([1, 2^{31}-1)\\). * * @private * @returns {PositiveInteger} pseudorandom integer * * @example * var v = randint32(); * // returns <number> */ function randint32() { var v = floor( 1.0 + (MAX*Math.random()) ); // eslint-disable-line stdlib/no-builtin-math return v|0; // asm type annotation } // EXPORTS // module.exports = randint32; },{"@stdlib/constants/int32/max":250,"@stdlib/math/base/special/floor":277}],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. */ /* eslint-disable max-len */ 'use strict'; // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var setReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' ); var setReadWriteAccessor = require( '@stdlib/utils/define-nonenumerable-read-write-accessor' ); var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var isObject = require( '@stdlib/assert/is-plain-object' ); var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; var isCollection = require( '@stdlib/assert/is-collection' ); var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive; var isInt32Array = require( '@stdlib/assert/is-int32array' ); var INT32_MAX = require( '@stdlib/constants/int32/max' ); var Int32Array = require( '@stdlib/array/int32' ); var gcopy = require( '@stdlib/blas/base/gcopy' ); var typedarray2json = require( '@stdlib/array/to-json' ); var randint32 = require( './rand_int32.js' ); // VARIABLES // var NORMALIZATION_CONSTANT = (INT32_MAX - 1)|0; // asm type annotation var MAX_SEED = (INT32_MAX - 1)|0; // asm type annotation var A = 16807|0; // asm type annotation // Define the state array schema version: var STATE_ARRAY_VERSION = 1; // NOTE: anytime the state array schema changes, this value should be incremented!!! // Define the number of sections in the state array: var NUM_STATE_SECTIONS = 2; // state, seed // Define the index offset of the "state" section in the state array: var STATE_SECTION_OFFSET = 2; // | version | num_sections | state_length | ...state | seed_length | ...seed | // Define the index offset of the seed section in the state array: var SEED_SECTION_OFFSET = 4; // | version | num_sections | state_length | ...state | seed_length | ...seed | // Define the length of the "fixed" length portion of the state array: var STATE_FIXED_LENGTH = 5; // 1 (version) + 1 (num_sections) + 1 (state_length) + 1 (state) + 1 (seed_length) // FUNCTIONS // /** * Verifies state array integrity. * * @private * @param {Int32Array} state - state array * @param {boolean} FLG - flag indicating whether the state array was provided as an option (true) or an argument (false) * @returns {(Error|null)} an error or `null` */ function verifyState( state, FLG ) { var s1; if ( FLG ) { s1 = 'option'; } else { s1 = 'argument'; } // The state array must have a minimum length... if ( state.length < STATE_FIXED_LENGTH+1 ) { return new RangeError( 'invalid '+s1+'. `state` array has insufficient length.' ); } // The first element of the state array must equal the supported state array schema version... if ( state[ 0 ] !== STATE_ARRAY_VERSION ) { return new RangeError( 'invalid '+s1+'. `state` array has an incompatible schema version. Expected: '+STATE_ARRAY_VERSION+'. Actual: '+state[ 0 ]+'.' ); } // The second element of the state array must contain the number of sections... if ( state[ 1 ] !== NUM_STATE_SECTIONS ) { return new RangeError( 'invalid '+s1+'. `state` array has an incompatible number of sections. Expected: '+NUM_STATE_SECTIONS+'. Actual: '+state[ 1 ]+'.' ); } // The length of the "state" section must equal `1`... if ( state[ STATE_SECTION_OFFSET ] !== 1 ) { return new RangeError( 'invalid '+s1+'. `state` array has an incompatible state length. Expected: '+(1).toString()+'. Actual: '+state[ STATE_SECTION_OFFSET ]+'.' ); } // The length of the "seed" section much match the empirical length... if ( state[ SEED_SECTION_OFFSET ] !== state.length-STATE_FIXED_LENGTH ) { return new RangeError( 'invalid '+s1+'. `state` array length is incompatible with seed section length. Expected: '+(state.length-STATE_FIXED_LENGTH)+'. Actual: '+state[ SEED_SECTION_OFFSET ]+'.' ); } return null; } // MAIN // /** * Returns a linear congruential pseudorandom number generator (LCG) based on Park and Miller. * * @param {Options} [options] - options * @param {PRNGSeedMINSTD} [options.seed] - pseudorandom number generator seed * @param {PRNGStateMINSTD} [options.state] - pseudorandom number generator state * @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state * @throws {TypeError} options argument must be an object * @throws {TypeError} a seed must be either a positive integer less than the maximum signed 32-bit integer or an array-like object containing integers less than the maximum signed 32-bit integer * @throws {RangeError} a numeric seed must be a positive integer less than the maximum signed 32-bit integer * @throws {TypeError} state must be an `Int32Array` * @throws {Error} must provide a valid state * @throws {TypeError} `copy` option must be a boolean * @returns {PRNG} LCG PRNG * * @example * var minstd = factory(); * * var v = minstd(); * // returns <number> * * @example * // Return a seeded LCG: * var minstd = factory({ * 'seed': 1234 * }); * * var v = minstd(); * // returns 20739838 */ function factory( options ) { var STATE; var state; var opts; var seed; var slen; var err; opts = {}; if ( arguments.length ) { if ( !isObject( options ) ) { throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' ); } if ( hasOwnProp( options, 'copy' ) ) { opts.copy = options.copy; if ( !isBoolean( options.copy ) ) { throw new TypeError( 'invalid option. `copy` option must be a boolean. Option: `' + options.copy + '`.' ); } } if ( hasOwnProp( options, 'state' ) ) { state = options.state; opts.state = true; if ( !isInt32Array( state ) ) { throw new TypeError( 'invalid option. `state` option must be an Int32Array. Option: `' + state + '`.' ); } err = verifyState( state, true ); if ( err ) { throw err; } if ( opts.copy === false ) { STATE = state; } else { STATE = new Int32Array( state.length ); gcopy( state.length, state, 1, STATE, 1 ); } // Create a state "view": state = new Int32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 ); // Create a seed "view": seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), state[ SEED_SECTION_OFFSET ] ); } // If provided a PRNG state, we ignore the `seed` option... if ( seed === void 0 ) { if ( hasOwnProp( options, 'seed' ) ) { seed = options.seed; opts.seed = true; if ( isPositiveInteger( seed ) ) { if ( seed > MAX_SEED ) { throw new RangeError( 'invalid option. `seed` option must be a positive integer less than the maximum signed 32-bit integer. Option: `' + seed + '`.' ); } seed |= 0; // asm type annotation } else if ( isCollection( seed ) && seed.length > 0 ) { slen = seed.length; STATE = new Int32Array( STATE_FIXED_LENGTH+slen ); // Initialize sections: STATE[ 0 ] = STATE_ARRAY_VERSION; STATE[ 1 ] = NUM_STATE_SECTIONS; STATE[ STATE_SECTION_OFFSET ] = 1; STATE[ SEED_SECTION_OFFSET ] = slen; // Copy the provided seed array to prevent external mutation, as mutation would lead to an inability to reproduce PRNG values according to the PRNG's stated seed: gcopy.ndarray( slen, seed, 1, 0, STATE, 1, SEED_SECTION_OFFSET+1 ); // Create a state "view": state = new Int32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 ); // Create a seed "view": seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), slen ); // Initialize the internal PRNG state: state[ 0 ] = seed[ 0 ]; } else { throw new TypeError( 'invalid option. `seed` option must be either a positive integer less than the maximum signed 32-bit integer or an array-like object containing integer values less than the maximum signed 32-bit integer. Option: `' + seed + '`.' ); } } else { seed = randint32()|0; // asm type annotation } } } else { seed = randint32()|0; // asm type annotation } if ( state === void 0 ) { STATE = new Int32Array( STATE_FIXED_LENGTH+1 ); // Initialize sections: STATE[ 0 ] = STATE_ARRAY_VERSION; STATE[ 1 ] = NUM_STATE_SECTIONS; STATE[ STATE_SECTION_OFFSET ] = 1; STATE[ SEED_SECTION_OFFSET ] = 1; STATE[ SEED_SECTION_OFFSET+1 ] = seed; // Create a state "view": state = new Int32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 ); // Create a seed "view": seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 ); // Initialize the internal PRNG state: state[ 0 ] = seed[ 0 ]; } setReadOnly( minstd, 'NAME', 'minstd' ); setReadOnlyAccessor( minstd, 'seed', getSeed ); setReadOnlyAccessor( minstd, 'seedLength', getSeedLength ); setReadWriteAccessor( minstd, 'state', getState, setState ); setReadOnlyAccessor( minstd, 'stateLength', getStateLength ); setReadOnlyAccessor( minstd, 'byteLength', getStateSize ); setReadOnly( minstd, 'toJSON', toJSON ); setReadOnly( minstd, 'MIN', 1 ); setReadOnly( minstd, 'MAX', INT32_MAX-1 ); setReadOnly( minstd, 'normalized', normalized ); setReadOnly( normalized, 'NAME', minstd.NAME ); setReadOnlyAccessor( normalized, 'seed', getSeed ); setReadOnlyAccessor( normalized, 'seedLength', getSeedLength ); setReadWriteAccessor( normalized, 'state', getState, setState ); setReadOnlyAccessor( normalized, 'stateLength', getStateLength ); setReadOnlyAccessor( normalized, 'byteLength', getStateSize ); setReadOnly( normalized, 'toJSON', toJSON ); setReadOnly( normalized, 'MIN', (minstd.MIN-1.0) / NORMALIZATION_CONSTANT ); setReadOnly( normalized, 'MAX', (minstd.MAX-1.0) / NORMALIZATION_CONSTANT ); return minstd; /** * Returns the PRNG seed. * * @private * @returns {PRNGSeedMINSTD} seed */ function getSeed() { var len = STATE[ SEED_SECTION_OFFSET ]; return gcopy( len, seed, 1, new Int32Array( len ), 1 ); } /** * Returns the PRNG seed length. * * @private * @returns {PositiveInteger} seed length */ function getSeedLength() { return STATE[ SEED_SECTION_OFFSET ]; } /** * Returns the PRNG state length. * * @private * @returns {PositiveInteger} state length */ function getStateLength() { return STATE.length; } /** * Returns the PRNG state size (in bytes). * * @private * @returns {PositiveInteger} state size (in bytes) */ function getStateSize() { return STATE.byteLength; } /** * Returns the current PRNG state. * * ## Notes * * - The PRNG state array is comprised of a preamble followed by `2` sections: * * 0. preamble (version + number of sections) * 1. internal PRNG state * 2. PRNG seed * * - The first element of the PRNG state array preamble is the state array schema version. * * - The second element of the PRNG state array preamble is the number of state array sections (i.e., `2`). * * - The first element of each section following the preamble specifies the section length. The remaining section elements comprise the section contents. * * @private * @returns {PRNGStateMINSTD} current state */ function getState() { var len = STATE.length; return gcopy( len, STATE, 1, new Int32Array( len ), 1 ); } /** * Sets the PRNG state. * * ## Notes * * - If PRNG state is "shared" (meaning a state array was provided during PRNG creation and **not** copied) and one sets the generator state to a state array having a different length, the PRNG does **not** update the existing shared state and, instead, points to the newly provided state array. In order to synchronize PRNG output according to the new shared state array, the state array for **each** relevant PRNG must be **explicitly** set. * - If PRNG state is "shared" and one sets the generator state to a state array of the same length, the PRNG state is updated (along with the state of all other PRNGs sharing the PRNG's state array). * * @private * @param {PRNGStateMINSTD} s - generator state * @throws {TypeError} must provide an `Int32Array` * @throws {Error} must provide a valid state */ function setState( s ) { var err; if ( !isInt32Array( s ) ) { throw new TypeError( 'invalid argument. Must provide an Int32Array. Value: `' + s + '`.' ); } err = verifyState( s, false ); if ( err ) { throw err; } if ( opts.copy === false ) { if ( opts.state && s.length === STATE.length ) { gcopy( s.length, s, 1, STATE, 1 ); // update current shared state } else { STATE = s; // point to new shared state opts.state = true; // setting this flag allows updating a shared state even if a state array was not provided at PRNG creation } } else { // Check if we can reuse allocated memory... if ( s.length !== STATE.length ) { STATE = new Int32Array( s.length ); // reallocate } gcopy( s.length, s, 1, STATE, 1 ); } // Create a new state "view": state = new Int32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 ); // Create a new seed "view": seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), STATE[ SEED_SECTION_OFFSET ] ); } /** * Serializes the pseudorandom number generator as a JSON object. * * ## Notes * * - `JSON.stringify()` implicitly calls this method when stringifying a PRNG. * * @private * @returns {Object} JSON representation */ function toJSON() { var out = {}; out.type = 'PRNG'; out.name = minstd.NAME; out.state = typedarray2json( STATE ); out.params = []; return out; } /** * Generates a pseudorandom integer on the interval \\( [1,2^{31}-1) \\). * * @private * @returns {integer32} pseudorandom integer */ function minstd() { var s = state[ 0 ]|0; // asm type annotation s = ( (A*s)%INT32_MAX )|0; // asm type annotation state[ 0 ] = s; return s|0; // asm type annotation } /** * Generates a pseudorandom number on the interval \\( [0,1) \\). * * @private * @returns {number} pseudorandom number */ function normalized() { return (minstd()-1) / NORMALIZATION_CONSTANT; } } // EXPORTS // module.exports = factory; },{"./rand_int32.js":317,"@stdlib/array/int32":10,"@stdlib/array/to-json":17,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-collection":90,"@stdlib/assert/is-int32array":106,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-positive-integer":149,"@stdlib/blas/base/gcopy":225,"@stdlib/constants/int32/max":250,"@stdlib/utils/define-nonenumerable-read-only-accessor":372,"@stdlib/utils/define-nonenumerable-read-only-property":374,"@stdlib/utils/define-nonenumerable-read-write-accessor":376}],315:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * A linear congruential pseudorandom number generator (LCG) based on Park and Miller. * * @module @stdlib/random/base/minstd * * @example * var minstd = require( '@stdlib/random/base/minstd' ); * * var v = minstd(); * // returns <number> * * @example * var factory = require( '@stdlib/random/base/minstd' ).factory; * * var minstd = factory({ * 'seed': 1234 * }); * * var v = minstd(); * // returns 20739838 */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var minstd = require( './main.js' ); var factory = require( './factory.js' ); // MAIN // setReadOnly( minstd, 'factory', factory ); // EXPORTS // module.exports = minstd; },{"./factory.js":314,"./main.js":316,"@stdlib/utils/define-nonenumerable-read-only-property":374}],316:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var factory = require( './factory.js' ); var randint32 = require( './rand_int32.js' ); // MAIN // /** * Generates a pseudorandom integer on the interval \\( [1,2^{31}-1) \\). * * ## Method * * Linear congruential generators (LCGs) use the recurrence relation * * ```tex * X_{n+1} = ( a \cdot X_n + c ) \operatorname{mod}(m) * ``` * * where the modulus \\( m \\) is a prime number or power of a prime number and \\( a \\) is a primitive root modulo \\( m \\). * * <!-- <note> --> * * For an LCG to be a Lehmer RNG, the seed \\( X_0 \\) must be coprime to \\( m \\). * * <!-- </note> --> * * In this implementation, the constants \\( a \\), \\( c \\), and \\( m \\) have the values * * ```tex * \begin{align*} * a &= 7^5 = 16807 \\ * c &= 0 \\ * m &= 2^{31} - 1 = 2147483647 * \end{align*} * ``` * * <!-- <note> --> * * The constant \\( m \\) is a Mersenne prime (modulo \\(31\\)). * * <!-- </note> --> * * <!-- <note> --> * * The constant \\( a \\) is a primitive root (modulo \\(31\\)). * * <!-- </note> --> * * Accordingly, the maximum possible product is * * ```tex * 16807 \cdot (m - 1) \approx 2^{46} * ``` * * The values for \\( a \\), \\( c \\), and \\( m \\) are taken from Park and Miller, "Random Number Generators: Good Ones Are Hard To Find". Park's and Miller's article is also the basis for a recipe in the second edition of _Numerical Recipes in C_. * * * ## Notes * * - The generator has a period of approximately \\(2.1\mbox{e}9\\) (see [Numerical Recipes in C, 2nd Edition](#references), p. 279). * * * ## References * * - Park, S. K., and K. W. Miller. 1988. "Random Number Generators: Good Ones Are Hard to Find." _Communications of the ACM_ 31 (10). New York, NY, USA: ACM: 1192–1201. doi:[10.1145/63039.63042](http://dx.doi.org/10.1145/63039.63042). * - Press, William H., Brian P. Flannery, Saul A. Teukolsky, and William T. Vetterling. 1992. _Numerical Recipes in C: The Art of Scientific Computing, Second Edition_. Cambridge University Press. * * * @function minstd * @type {PRNG} * @returns {PositiveInteger} pseudorandom integer * * @example * var v = minstd(); * // returns <number> */ var minstd = factory({ 'seed': randint32() }); // EXPORTS // module.exports = minstd; },{"./factory.js":314,"./rand_int32.js":317}],317:[function(require,module,exports){ arguments[4][313][0].apply(exports,arguments) },{"@stdlib/constants/int32/max":250,"@stdlib/math/base/special/floor":277,"dup":313}],318:[function(require,module,exports){ /* eslint-disable max-lines, max-len */ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * ## Notice * * The original C code and copyright notice are from the [source implementation]{@link http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/mt19937ar.c}. The implementation has been modified for JavaScript. * * ```text * Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. The names of its contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ``` */ 'use strict'; // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var setReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' ); var setReadWriteAccessor = require( '@stdlib/utils/define-nonenumerable-read-write-accessor' ); var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var isObject = require( '@stdlib/assert/is-plain-object' ); var isCollection = require( '@stdlib/assert/is-collection' ); var isUint32Array = require( '@stdlib/assert/is-uint32array' ); var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive; var FLOAT64_MAX_SAFE_INTEGER = require( '@stdlib/constants/float64/max-safe-integer' ); var UINT32_MAX = require( '@stdlib/constants/uint32/max' ); var Uint32Array = require( '@stdlib/array/uint32' ); var max = require( '@stdlib/math/base/special/max' ); var uimul = require( '@stdlib/math/base/special/uimul' ); var gcopy = require( '@stdlib/blas/base/gcopy' ); var typedarray2json = require( '@stdlib/array/to-json' ); var randuint32 = require( './rand_uint32.js' ); // VARIABLES // // Define the size of the state array (see refs): var N = 624; // Define a (magic) constant used for indexing into the state array: var M = 397; // Define the maximum seed: 11111111111111111111111111111111 var MAX_SEED = UINT32_MAX >>> 0; // asm type annotation // For seed arrays, define an initial state (magic) constant: 19650218 => 00000001001010111101011010101010 var SEED_ARRAY_INIT_STATE = 19650218 >>> 0; // asm type annotation // Define a mask for the most significant `w-r` bits, where `w` is the word size (32 bits) and `r` is the separation point of one word (see refs): 2147483648 => 0x80000000 => 10000000000000000000000000000000 var UPPER_MASK = 0x80000000 >>> 0; // asm type annotation // Define a mask for the least significant `r` bits (see refs): 2147483647 => 0x7fffffff => 01111111111111111111111111111111 var LOWER_MASK = 0x7fffffff >>> 0; // asm type annotation // Define a multiplier (see Knuth TAOCP Vol2. 3rd Ed. P.106): 1812433253 => 01101100000001111000100101100101 var KNUTH_MULTIPLIER = 1812433253 >>> 0; // asm type annotation // Define a (magic) multiplier: 1664525 => 00000000000110010110011000001101 var MAGIC_MULTIPLIER_1 = 1664525 >>> 0; // asm type annotation // Define a (magic) multiplier: 1566083941 => 01011101010110001000101101100101 var MAGIC_MULTIPLIER_2 = 1566083941 >>> 0; // asm type annotation // Define a tempering coefficient: 2636928640 => 0x9d2c5680 => 10011101001011000101011010000000 var TEMPERING_COEFFICIENT_1 = 0x9d2c5680 >>> 0; // asm type annotation // Define a tempering coefficient: 4022730752 => 0xefc60000 => 11101111110001100000000000000000 var TEMPERING_COEFFICIENT_2 = 0xefc60000 >>> 0; // asm type annotation // Define a constant vector `a` (see refs): 2567483615 => 0x9908b0df => 10011001000010001011000011011111 var MATRIX_A = 0x9908b0df >>> 0; // asm type annotation // MAG01[x] = x * MATRIX_A; for x = {0,1} var MAG01 = [ 0x0 >>> 0, MATRIX_A >>> 0 ]; // asm type annotation // Define a normalization constant when generating double-precision floating-point numbers: 2^53 => 9007199254740992 var FLOAT64_NORMALIZATION_CONSTANT = 1.0 / ( FLOAT64_MAX_SAFE_INTEGER+1.0 ); // eslint-disable-line id-length // 2^26: 67108864 var TWO_26 = 67108864 >>> 0; // asm type annotation // 2^32: 2147483648 => 0x80000000 => 10000000000000000000000000000000 var TWO_32 = 0x80000000 >>> 0; // asm type annotation // 1 (as a 32-bit unsigned integer): 1 => 0x1 => 00000000000000000000000000000001 var ONE = 0x1 >>> 0; // asm type annotation // Define the maximum normalized pseudorandom double-precision floating-point number: ( (((2^32-1)>>>5)*2^26)+( (2^32-1)>>>6) ) / 2^53 var MAX_NORMALIZED = FLOAT64_MAX_SAFE_INTEGER * FLOAT64_NORMALIZATION_CONSTANT; // Define the state array schema version: var STATE_ARRAY_VERSION = 1; // NOTE: anytime the state array schema changes, this value should be incremented!!! // Define the number of sections in the state array: var NUM_STATE_SECTIONS = 3; // state, other, seed // Define the index offset of the "state" section in the state array: var STATE_SECTION_OFFSET = 2; // | version | num_sections | state_length | ...state | other_length | state_index | seed_length | ...seed | // Define the index offset of the "other" section in the state array: var OTHER_SECTION_OFFSET = N + 3; // | version | num_sections | state_length | ...state | other_length | state_index | seed_length | ...seed | // Define the index offset of the seed section in the state array: var SEED_SECTION_OFFSET = N + 5; // | version | num_sections | state_length | ...state | other_length | state_index | seed_length | ...seed | // Define the length of the "fixed" length portion of the state array: var STATE_FIXED_LENGTH = N + 6; // 1 (version) + 1 (num_sections) + 1 (state_length) + N (state) + 1 (other_length) + 1 (state_index) + 1 (seed_length) // FUNCTIONS // /** * Verifies state array integrity. * * @private * @param {Uint32Array} state - state array * @param {boolean} FLG - flag indicating whether the state array was provided as an option (true) or an argument (false) * @returns {(Error|null)} an error or `null` */ function verifyState( state, FLG ) { var s1; if ( FLG ) { s1 = 'option'; } else { s1 = 'argument'; } // The state array must have a minimum length... if ( state.length < STATE_FIXED_LENGTH+1 ) { return new RangeError( 'invalid '+s1+'. `state` array has insufficient length.' ); } // The first element of the state array must equal the supported state array schema version... if ( state[ 0 ] !== STATE_ARRAY_VERSION ) { return new RangeError( 'invalid '+s1+'. `state` array has an incompatible schema version. Expected: '+STATE_ARRAY_VERSION+'. Actual: '+state[ 0 ]+'.' ); } // The second element of the state array must contain the number of sections... if ( state[ 1 ] !== NUM_STATE_SECTIONS ) { return new RangeError( 'invalid '+s1+'. `state` array has an incompatible number of sections. Expected: '+NUM_STATE_SECTIONS+'. Actual: '+state[ 1 ]+'.' ); } // The length of the "state" section must equal `N`... if ( state[ STATE_SECTION_OFFSET ] !== N ) { return new RangeError( 'invalid '+s1+'. `state` array has an incompatible state length. Expected: '+N+'. Actual: '+state[ STATE_SECTION_OFFSET ]+'.' ); } // The length of the "other" section must equal `1`... if ( state[ OTHER_SECTION_OFFSET ] !== 1 ) { return new RangeError( 'invalid '+s1+'. `state` array has an incompatible section length. Expected: '+(1).toString()+'. Actual: '+state[ OTHER_SECTION_OFFSET ]+'.' ); } // The length of the "seed" section much match the empirical length... if ( state[ SEED_SECTION_OFFSET ] !== state.length-STATE_FIXED_LENGTH ) { return new RangeError( 'invalid '+s1+'. `state` array length is incompatible with seed section length. Expected: '+(state.length-STATE_FIXED_LENGTH)+'. Actual: '+state[ SEED_SECTION_OFFSET ]+'.' ); } return null; } /** * Returns an initial PRNG state. * * @private * @param {Uint32Array} state - state array * @param {PositiveInteger} N - state size * @param {uinteger32} s - seed * @returns {Uint32Array} state array */ function createState( state, N, s ) { var i; // Set the first element of the state array to the provided seed: state[ 0 ] = s >>> 0; // equivalent to `s & 0xffffffffUL` in original C implementation // Initialize the remaining state array elements: for ( i = 1; i < N; i++ ) { /* * In the original C implementation (see `init_genrand()`), * * ```c * mt[i] = (KNUTH_MULTIPLIER * (mt[i-1] ^ (mt[i-1] >> 30)) + i) * ``` * * In order to replicate this in JavaScript, we must emulate C-like multiplication of unsigned 32-bit integers. */ s = state[ i-1 ]>>>0; // asm type annotation s = ( s^(s>>>30) )>>>0; // asm type annotation state[ i ] = ( uimul( s, KNUTH_MULTIPLIER ) + i )>>>0; // asm type annotation } return state; } /** * Initializes a PRNG state array according to a seed array. * * @private * @param {Uint32Array} state - state array * @param {NonNegativeInteger} N - state array length * @param {Collection} seed - seed array * @param {NonNegativeInteger} M - seed array length * @returns {Uint32Array} state array */ function initState( state, N, seed, M ) { var s; var i; var j; var k; i = 1; j = 0; for ( k = max( N, M ); k > 0; k-- ) { /* * In the original C implementation (see `init_by_array()`), * * ```c * mt[i] = (mt[i]^((mt[i-1]^(mt[i-1]>>30))*1664525UL)) + seed[j] + j; * ``` * * In order to replicate this in JavaScript, we must emulate C-like multiplication of unsigned 32-bit integers. */ s = state[ i-1 ]>>>0; // asm type annotation s = ( s^(s>>>30) )>>>0; // asm type annotation s = ( uimul( s, MAGIC_MULTIPLIER_1 ) )>>>0; // asm type annotation state[ i ] = ( ((state[i]>>>0)^s) + seed[j] + j )>>>0; /* non-linear */ // asm type annotation i += 1; j += 1; if ( i >= N ) { state[ 0 ] = state[ N-1 ]; i = 1; } if ( j >= M ) { j = 0; } } for ( k = N-1; k > 0; k-- ) { /* * In the original C implementation (see `init_by_array()`), * * ```c * mt[i] = (mt[i]^((mt[i-1]^(mt[i-1]>>30))*1566083941UL)) - i; * ``` * * In order to replicate this in JavaScript, we must emulate C-like multiplication of unsigned 32-bit integers. */ s = state[ i-1 ]>>>0; // asm type annotation s = ( s^(s>>>30) )>>>0; // asm type annotation s = ( uimul( s, MAGIC_MULTIPLIER_2 ) )>>>0; // asm type annotation state[ i ] = ( ((state[i]>>>0)^s) - i )>>>0; /* non-linear */ // asm type annotation i += 1; if ( i >= N ) { state[ 0 ] = state[ N-1 ]; i = 1; } } // Ensure a non-zero initial state array: state[ 0 ] = TWO_32; // MSB (most significant bit) is 1 return state; } /** * Updates a PRNG's internal state by generating the next `N` words. * * @private * @param {Uint32Array} state - state array * @returns {Uint32Array} state array */ function twist( state ) { var w; var i; var j; var k; k = N - M; for ( i = 0; i < k; i++ ) { w = ( state[i]&UPPER_MASK ) | ( state[i+1]&LOWER_MASK ); state[ i ] = state[ i+M ] ^ ( w>>>1 ) ^ MAG01[ w&ONE ]; } j = N - 1; for ( ; i < j; i++ ) { w = ( state[i]&UPPER_MASK ) | ( state[i+1]&LOWER_MASK ); state[ i ] = state[ i-k ] ^ ( w>>>1 ) ^ MAG01[ w&ONE ]; } w = ( state[j]&UPPER_MASK ) | ( state[0]&LOWER_MASK ); state[ j ] = state[ M-1 ] ^ ( w>>>1 ) ^ MAG01[ w&ONE ]; return state; } // MAIN // /** * Returns a 32-bit Mersenne Twister pseudorandom number generator. * * ## Notes * * - In contrast to the original C implementation, array seeds of length `1` are considered integer seeds. This ensures that the seed `[ 1234 ]` generates the same output as the seed `1234`. In the original C implementation, the two seeds would yield different output, which is **not** obvious from a user perspective. * * @param {Options} [options] - options * @param {PRNGSeedMT19937} [options.seed] - pseudorandom number generator seed * @param {PRNGStateMT19937} [options.state] - pseudorandom number generator state * @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state * @throws {TypeError} options argument must be an object * @throws {TypeError} a seed must be either a positive integer less than or equal to the maximum unsigned 32-bit integer or an array-like object containing integers less than or equal to the maximum unsigned 32-bit integer * @throws {RangeError} a numeric seed must be a positive integer less than or equal to the maximum unsigned 32-bit integer * @throws {TypeError} state must be a `Uint32Array` * @throws {Error} must provide a valid state * @throws {TypeError} `copy` option must be a boolean * @returns {PRNG} Mersenne Twister PRNG * * @example * var mt19937 = factory(); * * var v = mt19937(); * // returns <number> * * @example * // Return a seeded Mersenne Twister PRNG: * var mt19937 = factory({ * 'seed': 1234 * }); * * var v = mt19937(); * // returns 822569775 */ function factory( options ) { var STATE; var state; var opts; var seed; var slen; var err; opts = {}; if ( arguments.length ) { if ( !isObject( options ) ) { throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' ); } if ( hasOwnProp( options, 'copy' ) ) { opts.copy = options.copy; if ( !isBoolean( options.copy ) ) { throw new TypeError( 'invalid option. `copy` option must be a boolean. Option: `' + options.copy + '`.' ); } } if ( hasOwnProp( options, 'state' ) ) { state = options.state; opts.state = true; if ( !isUint32Array( state ) ) { throw new TypeError( 'invalid option. `state` option must be a Uint32Array. Option: `' + state + '`.' ); } err = verifyState( state, true ); if ( err ) { throw err; } if ( opts.copy === false ) { STATE = state; } else { STATE = new Uint32Array( state.length ); gcopy( state.length, state, 1, STATE, 1 ); } // Create a state "view": state = new Uint32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), N ); // Create a seed "view": seed = new Uint32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), state[ SEED_SECTION_OFFSET ] ); } // If provided a PRNG state, we ignore the `seed` option... if ( seed === void 0 ) { if ( hasOwnProp( options, 'seed' ) ) { seed = options.seed; opts.seed = true; if ( isPositiveInteger( seed ) ) { if ( seed > MAX_SEED ) { throw new RangeError( 'invalid option. `seed` option must be a positive integer less than or equal to the maximum unsigned 32-bit integer. Option: `' + seed + '`.' ); } seed >>>= 0; // asm type annotation } else if ( isCollection( seed ) === false || seed.length < 1 ) { throw new TypeError( 'invalid option. `seed` option must be either a positive integer less than or equal to the maximum unsigned 32-bit integer or an array-like object containing integer values less than or equal to the maximum unsigned 32-bit integer. Option: `' + seed + '`.' ); } else if ( seed.length === 1 ) { seed = seed[ 0 ]; if ( !isPositiveInteger( seed ) ) { throw new TypeError( 'invalid option. `seed` option must be either a positive integer less than or equal to the maximum unsigned 32-bit integer or an array-like object containing integer values less than or equal to the maximum unsigned 32-bit integer. Option: `' + seed + '`.' ); } if ( seed > MAX_SEED ) { throw new RangeError( 'invalid option. `seed` option must be either a positive integer less than or equal to the maximum unsigned 32-bit integer or an array-like object containing integer values less than or equal to the maximum unsigned 32-bit integer. Option: `' + seed + '`.' ); } seed >>>= 0; // asm type annotation } else { slen = seed.length; STATE = new Uint32Array( STATE_FIXED_LENGTH+slen ); // Initialize sections: STATE[ 0 ] = STATE_ARRAY_VERSION; STATE[ 1 ] = NUM_STATE_SECTIONS; STATE[ STATE_SECTION_OFFSET ] = N; STATE[ OTHER_SECTION_OFFSET ] = 1; STATE[ OTHER_SECTION_OFFSET+1 ] = N; // state index STATE[ SEED_SECTION_OFFSET ] = slen; // Copy the provided seed array to prevent external mutation, as mutation would lead to an inability to reproduce PRNG values according to the PRNG's stated seed: gcopy.ndarray( slen, seed, 1, 0, STATE, 1, SEED_SECTION_OFFSET+1 ); // Create a state "view": state = new Uint32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), N ); // Create a seed "view": seed = new Uint32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), slen ); // Initialize the internal PRNG state: state = createState( state, N, SEED_ARRAY_INIT_STATE ); state = initState( state, N, seed, slen ); } } else { seed = randuint32() >>> 0; // asm type annotation } } } else { seed = randuint32() >>> 0; // asm type annotation } if ( state === void 0 ) { STATE = new Uint32Array( STATE_FIXED_LENGTH+1 ); // Initialize sections: STATE[ 0 ] = STATE_ARRAY_VERSION; STATE[ 1 ] = NUM_STATE_SECTIONS; STATE[ STATE_SECTION_OFFSET ] = N; STATE[ OTHER_SECTION_OFFSET ] = 1; STATE[ OTHER_SECTION_OFFSET+1 ] = N; // state index STATE[ SEED_SECTION_OFFSET ] = 1; STATE[ SEED_SECTION_OFFSET+1 ] = seed; // Create a state "view": state = new Uint32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), N ); // Create a seed "view": seed = new Uint32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 ); // Initialize the internal PRNG state: state = createState( state, N, seed ); } // Note: property order matters in order to maintain consistency of PRNG "shape" (hidden classes). setReadOnly( mt19937, 'NAME', 'mt19937' ); setReadOnlyAccessor( mt19937, 'seed', getSeed ); setReadOnlyAccessor( mt19937, 'seedLength', getSeedLength ); setReadWriteAccessor( mt19937, 'state', getState, setState ); setReadOnlyAccessor( mt19937, 'stateLength', getStateLength ); setReadOnlyAccessor( mt19937, 'byteLength', getStateSize ); setReadOnly( mt19937, 'toJSON', toJSON ); setReadOnly( mt19937, 'MIN', 1 ); setReadOnly( mt19937, 'MAX', UINT32_MAX ); setReadOnly( mt19937, 'normalized', normalized ); setReadOnly( normalized, 'NAME', mt19937.NAME ); setReadOnlyAccessor( normalized, 'seed', getSeed ); setReadOnlyAccessor( normalized, 'seedLength', getSeedLength ); setReadWriteAccessor( normalized, 'state', getState, setState ); setReadOnlyAccessor( normalized, 'stateLength', getStateLength ); setReadOnlyAccessor( normalized, 'byteLength', getStateSize ); setReadOnly( normalized, 'toJSON', toJSON ); setReadOnly( normalized, 'MIN', 0.0 ); setReadOnly( normalized, 'MAX', MAX_NORMALIZED ); return mt19937; /** * Returns the PRNG seed. * * @private * @returns {PRNGSeedMT19937} seed */ function getSeed() { var len = STATE[ SEED_SECTION_OFFSET ]; return gcopy( len, seed, 1, new Uint32Array( len ), 1 ); } /** * Returns the PRNG seed length. * * @private * @returns {PositiveInteger} seed length */ function getSeedLength() { return STATE[ SEED_SECTION_OFFSET ]; } /** * Returns the PRNG state length. * * @private * @returns {PositiveInteger} state length */ function getStateLength() { return STATE.length; } /** * Returns the PRNG state size (in bytes). * * @private * @returns {PositiveInteger} state size (in bytes) */ function getStateSize() { return STATE.byteLength; } /** * Returns the current PRNG state. * * ## Notes * * - The PRNG state array is comprised of a preamble followed by `3` sections: * * 0. preamble (version + number of sections) * 1. internal PRNG state * 2. auxiliary state information * 3. PRNG seed * * - The first element of the PRNG state array preamble is the state array schema version. * * - The second element of the PRNG state array preamble is the number of state array sections (i.e., `3`). * * - The first element of each section following the preamble specifies the section length. The remaining section elements comprise the section contents. * * @private * @returns {PRNGStateMT19937} current state */ function getState() { var len = STATE.length; return gcopy( len, STATE, 1, new Uint32Array( len ), 1 ); } /** * Sets the PRNG state. * * ## Notes * * - If PRNG state is "shared" (meaning a state array was provided during PRNG creation and **not** copied) and one sets the generator state to a state array having a different length, the PRNG does **not** update the existing shared state and, instead, points to the newly provided state array. In order to synchronize PRNG output according to the new shared state array, the state array for **each** relevant PRNG must be **explicitly** set. * - If PRNG state is "shared" and one sets the generator state to a state array of the same length, the PRNG state is updated (along with the state of all other PRNGs sharing the PRNG's state array). * * @private * @param {PRNGStateMT19937} s - generator state * @throws {TypeError} must provide a `Uint32Array` * @throws {Error} must provide a valid state */ function setState( s ) { var err; if ( !isUint32Array( s ) ) { throw new TypeError( 'invalid argument. Must provide a Uint32Array. Value: `' + s + '`.' ); } err = verifyState( s, false ); if ( err ) { throw err; } if ( opts.copy === false ) { if ( opts.state && s.length === STATE.length ) { gcopy( s.length, s, 1, STATE, 1 ); // update current shared state } else { STATE = s; // point to new shared state opts.state = true; // setting this flag allows updating a shared state even if a state array was not provided at PRNG creation } } else { // Check if we can reuse allocated memory... if ( s.length !== STATE.length ) { STATE = new Uint32Array( s.length ); // reallocate } gcopy( s.length, s, 1, STATE, 1 ); } // Create a new state "view": state = new Uint32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), N ); // Create a new seed "view": seed = new Uint32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), STATE[ SEED_SECTION_OFFSET ] ); } /** * Serializes the pseudorandom number generator as a JSON object. * * ## Notes * * - `JSON.stringify()` implicitly calls this method when stringifying a PRNG. * * @private * @returns {Object} JSON representation */ function toJSON() { var out = {}; out.type = 'PRNG'; out.name = mt19937.NAME; out.state = typedarray2json( STATE ); out.params = []; return out; } /** * Generates a pseudorandom integer on the interval \\( [1,2^{32}-1) \\). * * @private * @returns {uinteger32} pseudorandom integer * * @example * var r = mt19937(); * // returns <number> */ function mt19937() { var r; var i; // Retrieve the current state index: i = STATE[ OTHER_SECTION_OFFSET+1 ]; // Determine whether we need to update the PRNG state: if ( i >= N ) { state = twist( state ); i = 0; } // Get the next word of "raw"/untempered state: r = state[ i ]; // Update the state index: STATE[ OTHER_SECTION_OFFSET+1 ] = i + 1; // Tempering transform to compensate for the reduced dimensionality of equidistribution: r ^= r >>> 11; r ^= ( r << 7 ) & TEMPERING_COEFFICIENT_1; r ^= ( r << 15 ) & TEMPERING_COEFFICIENT_2; r ^= r >>> 18; return r >>> 0; } /** * Generates a pseudorandom number on the interval \\( [0,1) \\). * * ## Notes * * - The original C implementation credits Isaku Wada for this algorithm (2002/01/09). * * @private * @returns {number} pseudorandom number * * @example * var r = normalized(); * // returns <number> */ function normalized() { var x = mt19937() >>> 5; var y = mt19937() >>> 6; return ( (x*TWO_26)+y ) * FLOAT64_NORMALIZATION_CONSTANT; } } // EXPORTS // module.exports = factory; },{"./rand_uint32.js":321,"@stdlib/array/to-json":17,"@stdlib/array/uint32":23,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-collection":90,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-positive-integer":149,"@stdlib/assert/is-uint32array":170,"@stdlib/blas/base/gcopy":225,"@stdlib/constants/float64/max-safe-integer":243,"@stdlib/constants/uint32/max":255,"@stdlib/math/base/special/max":281,"@stdlib/math/base/special/uimul":290,"@stdlib/utils/define-nonenumerable-read-only-accessor":372,"@stdlib/utils/define-nonenumerable-read-only-property":374,"@stdlib/utils/define-nonenumerable-read-write-accessor":376}],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'; /** * A 32-bit Mersenne Twister pseudorandom number generator. * * @module @stdlib/random/base/mt19937 * * @example * var mt19937 = require( '@stdlib/random/base/mt19937' ); * * var v = mt19937(); * // returns <number> * * @example * var factory = require( '@stdlib/random/base/mt19937' ).factory; * * var mt19937 = factory({ * 'seed': 1234 * }); * * var v = mt19937(); * // returns 822569775 */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var mt19937 = require( './main.js' ); var factory = require( './factory.js' ); // MAIN // setReadOnly( mt19937, 'factory', factory ); // EXPORTS // module.exports = mt19937; },{"./factory.js":318,"./main.js":320,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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 factory = require( './factory.js' ); var randuint32 = require( './rand_uint32.js' ); // MAIN // /** * Generates a pseudorandom integer on the interval \\( [1,2^{32}-1) \\). * * ## Method * * - When generating normalized double-precision floating-point numbers, we first generate two pseudorandom integers \\( x \\) and \\( y \\) on the interval \\( [1,2^{32}-1) \\) for a combined \\( 64 \\) random bits. * * - We would like \\( 53 \\) random bits to generate a 53-bit precision integer and, thus, want to discard \\( 11 \\) of the generated bits. * * - We do so by discarding \\( 5 \\) bits from \\( x \\) and \\( 6 \\) bits from \\( y \\). * * - Accordingly, \\( x \\) contains \\( 27 \\) random bits, which are subsequently shifted left \\( 26 \\) bits (multiplied by \\( 2^{26} \\), and \\( y \\) contains \\( 26 \\) random bits to fill in the lower \\( 26 \\) bits. When summed, they combine to comprise \\( 53 \\) random bits of a double-precision floating-point integer. * * - As an example, suppose, for the sake of argument, the 32-bit PRNG generates the maximum unsigned 32-bit integer \\( 2^{32}-1 \\) twice in a row. Then, * * ```javascript * x = 4294967295 >>> 5; // 00000111111111111111111111111111 * y = 4294967295 >>> 6; // 00000011111111111111111111111111 * ``` * * Multiplying \\( x \\) by \\( 2^{26} \\) returns \\( 9007199187632128 \\), which, in binary, is * * ```binarystring * 0 10000110011 11111111111111111111 11111100000000000000000000000000 * ``` * * Adding \\( y \\) yields \\( 9007199254740991 \\) (the maximum "safe" double-precision floating-point integer value), which, in binary, is * * ```binarystring * 0 10000110011 11111111111111111111 11111111111111111111111111111111 * ``` * * - Similarly, suppose the 32-bit PRNG generates the following values * * ```javascript * x = 1 >>> 5; // 0 => 00000000000000000000000000000000 * y = 64 >>> 6; // 1 => 00000000000000000000000000000001 * ``` * * Multiplying \\( x \\) by \\( 2^{26} \\) returns \\( 0 \\), which, in binary, is * * ```binarystring * 0 00000000000 00000000000000000000 00000000000000000000000000000000 * ``` * * Adding \\( y \\) yields \\( 1 \\), which, in binary, is * * ```binarystring * 0 01111111111 00000000000000000000 00000000000000000000000000000000 * ``` * * - As different combinations of \\( x \\) and \\( y \\) are generated, different combinations of double-precision floating-point exponent and significand bits will be toggled, thus generating pseudorandom double-precision floating-point numbers. * * * ## References * * - Matsumoto, Makoto, and Takuji Nishimura. 1998. "Mersenne Twister: A 623-dimensionally Equidistributed Uniform Pseudo-random Number Generator." _ACM Transactions on Modeling and Computer Simulation_ 8 (1). New York, NY, USA: ACM: 3–30. doi:[10.1145/272991.272995][@matsumoto:1998a]. * - Harase, Shin. 2017. "Conversion of Mersenne Twister to double-precision floating-point numbers." _ArXiv_ abs/1708.06018 (September). <https://arxiv.org/abs/1708.06018>. * * [@matsumoto:1998a]: https://doi.org/10.1145/272991.272995 * * * @function mt19937 * @type {PRNG} * @returns {PositiveInteger} pseudorandom integer * * @example * var v = mt19937(); * // returns <number> */ var mt19937 = factory({ 'seed': randuint32() }); // EXPORTS // module.exports = mt19937; },{"./factory.js":318,"./rand_uint32.js":321}],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 UINT32_MAX = require( '@stdlib/constants/uint32/max' ); var floor = require( '@stdlib/math/base/special/floor' ); // VARIABLES // var MAX = UINT32_MAX - 1; // MAIN // /** * Returns a pseudorandom integer on the interval \\([1, 2^{32}-1)\\). * * @private * @returns {PositiveInteger} pseudorandom integer * * @example * var v = randuint32(); * // returns <number> */ function randuint32() { var v = floor( 1.0 + (MAX*Math.random()) ); // eslint-disable-line stdlib/no-builtin-math return v >>> 0; // asm type annotation } // EXPORTS // module.exports = randuint32; },{"@stdlib/constants/uint32/max":255,"@stdlib/math/base/special/floor":277}],322:[function(require,module,exports){ module.exports={ "name": "mt19937", "copy": true } },{}],323:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var setReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' ); var setReadWriteAccessor = require( '@stdlib/utils/define-nonenumerable-read-write-accessor' ); var isObject = require( '@stdlib/assert/is-plain-object' ); var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var typedarray2json = require( '@stdlib/array/to-json' ); var defaults = require( './defaults.json' ); var PRNGS = require( './prngs.js' ); // MAIN // /** * Returns a pseudorandom number generator for generating uniformly distributed random numbers on the interval \\( [0,1) \\). * * @param {Options} [options] - function options * @param {string} [options.name='mt19937'] - name of pseudorandom number generator * @param {*} [options.seed] - pseudorandom number generator seed * @param {*} [options.state] - pseudorandom number generator state * @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state * @throws {TypeError} must provide an object * @throws {TypeError} must provide valid options * @throws {Error} must provide the name of a supported pseudorandom number generator * @returns {PRNG} pseudorandom number generator * * @example * var uniform = factory(); * var v = uniform(); * // returns <number> * * @example * var uniform = factory({ * 'name': 'minstd' * }); * var v = uniform(); * // returns <number> * * @example * var uniform = factory({ * 'seed': 12345 * }); * var v = uniform(); * // returns <number> * * @example * var uniform = factory({ * 'name': 'minstd', * 'seed': 12345 * }); * var v = uniform(); * // returns <number> */ function factory( options ) { var opts; var rand; var prng; opts = { 'name': defaults.name, 'copy': defaults.copy }; if ( arguments.length ) { if ( !isObject( options ) ) { throw new TypeError( 'invalid argument. Must provide an object. Value: `' + options + '`.' ); } if ( hasOwnProp( options, 'name' ) ) { opts.name = options.name; } if ( hasOwnProp( options, 'state' ) ) { opts.state = options.state; if ( opts.state === void 0 ) { throw new TypeError( 'invalid option. `state` option cannot be undefined. Option: `' + opts.state + '`.' ); } } else if ( hasOwnProp( options, 'seed' ) ) { opts.seed = options.seed; if ( opts.seed === void 0 ) { throw new TypeError( 'invalid option. `seed` option cannot be undefined. Option: `' + opts.seed + '`.' ); } } if ( hasOwnProp( options, 'copy' ) ) { opts.copy = options.copy; if ( !isBoolean( opts.copy ) ) { throw new TypeError( 'invalid option. `copy` option must be a boolean. Option: `' + opts.copy + '`.' ); } } } prng = PRNGS[ opts.name ]; if ( prng === void 0 ) { throw new Error( 'invalid option. Unrecognized/unsupported PRNG. Option: `' + opts.name + '`.' ); } if ( opts.state === void 0 ) { if ( opts.seed === void 0 ) { rand = prng.factory(); } else { rand = prng.factory({ 'seed': opts.seed }); } } else { rand = prng.factory({ 'state': opts.state, 'copy': opts.copy }); } setReadOnly( uniform, 'NAME', 'randu' ); setReadOnlyAccessor( uniform, 'seed', getSeed ); setReadOnlyAccessor( uniform, 'seedLength', getSeedLength ); setReadWriteAccessor( uniform, 'state', getState, setState ); setReadOnlyAccessor( uniform, 'stateLength', getStateLength ); setReadOnlyAccessor( uniform, 'byteLength', getStateSize ); setReadOnly( uniform, 'toJSON', toJSON ); setReadOnly( uniform, 'PRNG', rand ); setReadOnly( uniform, 'MIN', rand.normalized.MIN ); setReadOnly( uniform, 'MAX', rand.normalized.MAX ); return uniform; /** * Returns the PRNG seed. * * @private * @returns {*} seed */ function getSeed() { return rand.seed; } /** * Returns the PRNG seed length. * * @private * @returns {PositiveInteger} seed length */ function getSeedLength() { return rand.seedLength; } /** * Returns the PRNG state length. * * @private * @returns {PositiveInteger} state length */ function getStateLength() { return rand.stateLength; } /** * Returns the PRNG state size (in bytes). * * @private * @returns {PositiveInteger} state size (in bytes) */ function getStateSize() { return rand.byteLength; } /** * Returns the current pseudorandom number generator state. * * @private * @returns {*} current state */ function getState() { return rand.state; } /** * Sets the pseudorandom number generator state. * * @private * @param {*} s - generator state * @throws {Error} must provide a valid state */ function setState( s ) { rand.state = s; } /** * Serializes the pseudorandom number generator as a JSON object. * * ## Notes * * - `JSON.stringify()` implicitly calls this method when stringifying a PRNG. * * @private * @returns {Object} JSON representation */ function toJSON() { var out = {}; out.type = 'PRNG'; out.name = uniform.NAME + '-' + rand.NAME; out.state = typedarray2json( rand.state ); out.params = []; return out; } /** * Returns a uniformly distributed pseudorandom number on the interval \\( [0,1) \\). * * @private * @returns {number} pseudorandom number * * @example * var v = uniform(); * // returns <number> */ function uniform() { return rand.normalized(); } } // EXPORTS // module.exports = factory; },{"./defaults.json":322,"./prngs.js":326,"@stdlib/array/to-json":17,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-plain-object":147,"@stdlib/utils/define-nonenumerable-read-only-accessor":372,"@stdlib/utils/define-nonenumerable-read-only-property":374,"@stdlib/utils/define-nonenumerable-read-write-accessor":376}],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'; /** * Uniformly distributed pseudorandom numbers on the interval \\( [0,1) \\). * * @module @stdlib/random/base/randu * * @example * var randu = require( '@stdlib/random/base/randu' ); * * var v = randu(); * // returns <number> * * @example * var factory = require( '@stdlib/random/base/randu' ).factory; * * var randu = factory({ * 'name': 'minstd', * 'seed': 12345 * }); * * var v = randu(); * // returns <number> */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var randu = require( './main.js' ); var factory = require( './factory.js' ); // MAIN // setReadOnly( randu, 'factory', factory ); // EXPORTS // module.exports = randu; },{"./factory.js":323,"./main.js":325,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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 factory = require( './factory.js' ); // MAIN // /** * Returns a uniformly distributed random number on the interval \\( [0,1) \\). * * @name randu * @type {PRNG} * @returns {number} pseudorandom number * * @example * var v = randu(); * // returns <number> */ var randu = factory(); // EXPORTS // module.exports = randu; },{"./factory.js":323}],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'; // MAIN // var prngs = {}; prngs[ 'minstd' ] = require( '@stdlib/random/base/minstd' ); prngs[ 'minstd-shuffle' ] = require( '@stdlib/random/base/minstd-shuffle' ); prngs[ 'mt19937' ] = require( '@stdlib/random/base/mt19937' ); // EXPORTS // module.exports = prngs; },{"@stdlib/random/base/minstd":315,"@stdlib/random/base/minstd-shuffle":311,"@stdlib/random/base/mt19937":319}],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'; /** * 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":328,"./regexp.js":329,"./regexp_capture.js":330,"@stdlib/utils/define-nonenumerable-read-only-property":374}],328:[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":331}],329:[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":328}],330:[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":328}],331:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var isObject = require( '@stdlib/assert/is-plain-object' ); var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; var isString = require( '@stdlib/assert/is-string' ).isPrimitive; // MAIN // /** * Validates function options. * * @private * @param {Object} opts - destination object * @param {Options} options - function options * @param {string} [options.flags] - regular expression flags * @param {boolean} [options.capture] - boolean indicating whether to wrap a regular expression matching a decimal number with a capture group * @returns {(Error|null)} null or an error object * * @example * var opts = {}; * var options = { * 'flags': 'gm' * }; * var err = validate( opts, options ); * if ( err ) { * throw err; * } */ function validate( opts, options ) { if ( !isObject( options ) ) { return new TypeError( 'invalid argument. Options must be an object. Value: `' + options + '`.' ); } if ( hasOwnProp( options, 'flags' ) ) { opts.flags = options.flags; if ( !isString( opts.flags ) ) { return new TypeError( 'invalid option. `flags` option must be a string primitive. Option: `' + opts.flags + '`.' ); } } if ( hasOwnProp( options, 'capture' ) ) { opts.capture = options.capture; if ( !isBoolean( opts.capture ) ) { return new TypeError( 'invalid option. `capture` option must be a boolean primitive. Option: `' + opts.capture + '`.' ); } } return null; } // EXPORTS // module.exports = validate; },{"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-string":158}],332:[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":333,"./regexp.js":334,"@stdlib/utils/define-nonenumerable-read-only-property":374}],333:[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; },{}],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 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":333}],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'; /** * 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":336,"./regexp.js":337,"@stdlib/utils/define-nonenumerable-read-only-property":374}],336:[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; },{}],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 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":336}],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'; // MODULES // var bench = require( '@stdlib/bench' ); var randu = require( '@stdlib/random/base/randu' ); var isnan = require( '@stdlib/math/base/assert/is-nan' ); var EPS = require( '@stdlib/constants/float64/eps' ); var pkg = require( './../package.json' ).name; var pdf = require( './../lib' ); // MAIN // bench( pkg, function benchmark( b ) { var lambda; var x; var y; var i; b.tic(); for ( i = 0; i < b.iterations; i++ ) { x = ( randu()*100.0 ); lambda = ( randu()*100.0 ) + EPS; y = pdf( x, lambda ); if ( isnan( y ) ) { b.fail( 'should not return NaN' ); } } b.toc(); if ( isnan( y ) ) { b.fail( 'should not return NaN' ); } b.pass( 'benchmark finished' ); b.end(); }); bench( pkg+':factory', function benchmark( b ) { var lambda; var mypdf; var x; var y; var i; lambda = 10.0; mypdf = pdf.factory( lambda ); b.tic(); for ( i = 0; i < b.iterations; i++ ) { x = ( randu()*100.0 ) + EPS; y = mypdf( x ); if ( isnan( y ) ) { b.fail( 'should not return NaN' ); } } b.toc(); if ( isnan( y ) ) { b.fail( 'should not return NaN' ); } b.pass( 'benchmark finished' ); b.end(); }); },{"./../lib":340,"./../package.json":342,"@stdlib/bench":224,"@stdlib/constants/float64/eps":237,"@stdlib/math/base/assert/is-nan":263,"@stdlib/random/base/randu":324}],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'; // MODULES // var constantFunction = require( '@stdlib/utils/constant-function' ); var isnan = require( '@stdlib/math/base/assert/is-nan' ); var exp = require( '@stdlib/math/base/special/exp' ); var PINF = require( '@stdlib/constants/float64/pinf' ); // MAIN // /** * Returns a function for evaluating the probability density function (PDF) for an exponential distribution with parameter `lambda`. * * @param {PositiveNumber} lambda - rate parameter * @returns {Function} probability density function (PDF) * * @example * var pdf = factory( 0.5 ); * var y = pdf( 3.0 ); * // returns ~0.112 * * y = pdf( 1.0 ); * // returns ~0.303 */ function factory( lambda ) { var scale; if ( isnan( lambda ) || lambda < 0.0 || lambda === PINF ) { return constantFunction( NaN ); } scale = 1.0 / lambda; return pdf; /** * Evaluates the probability density function (PDF) for an exponential distribution. * * @private * @param {number} x - input value * @returns {number} evaluated PDF * * @example * var y = pdf( 2.3 ); * // returns <number> */ function pdf( x ) { if ( isnan( x ) ) { return NaN; } if ( x < 0.0 ) { return 0.0; } return exp( -x / scale ) / scale; } } // EXPORTS // module.exports = factory; },{"@stdlib/constants/float64/pinf":246,"@stdlib/math/base/assert/is-nan":263,"@stdlib/math/base/special/exp":275,"@stdlib/utils/constant-function":365}],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'; /** * Exponential distribution probability density function (PDF). * * @module @stdlib/stats/base/dists/exponential/pdf * * @example * var pdf = require( '@stdlib/stats/base/dists/exponential/pdf' ); * * var y = pdf( 0.3, 4.0 ); * // returns ~1.205 * * var myPDF = pdf.factory( 0.5 ); * * y = myPDF( 3.0 ); * // returns ~0.112 * * y = myPDF( 1.0 ); * // returns ~0.303 */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var pdf = require( './pdf.js' ); var factory = require( './factory.js' ); // MAIN // setReadOnly( pdf, 'factory', factory ); // EXPORTS // module.exports = pdf; },{"./factory.js":339,"./pdf.js":341,"@stdlib/utils/define-nonenumerable-read-only-property":374}],341:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var isnan = require( '@stdlib/math/base/assert/is-nan' ); var exp = require( '@stdlib/math/base/special/exp' ); var PINF = require( '@stdlib/constants/float64/pinf' ); // MAIN // /** * Evaluates the probability density function (PDF) for an exponential distribution with rate parameter `lambda` at a value `x`. * * @param {number} x - input value * @param {PositiveNumber} lambda - rate parameter * @returns {number} evaluated PDF * * @example * var y = pdf( 0.3, 4.0 ); * // returns ~1.205 * * @example * var y = pdf( 2.0, 0.7 ); * // returns ~0.173 * * @example * var y = pdf( -1.0, 0.5 ); * // returns 0.0 * * @example * var y = pdf( 0, NaN ); * // returns NaN * * @example * var y = pdf( NaN, 2.0 ); * // returns NaN * * @example * // Negative rate: * var y = pdf( 2.0, -1.0 ); * // returns NaN */ function pdf( x, lambda ) { var scale; if ( isnan( x ) || isnan( lambda ) || lambda < 0.0 || lambda === PINF ) { return NaN; } if ( x < 0.0 ) { return 0.0; } scale = 1.0 / lambda; return exp( -x / scale ) / scale; } // EXPORTS // module.exports = pdf; },{"@stdlib/constants/float64/pinf":246,"@stdlib/math/base/assert/is-nan":263,"@stdlib/math/base/special/exp":275}],342:[function(require,module,exports){ module.exports={ "name": "@stdlib/stats/base/dists/exponential/pdf", "version": "0.0.0", "description": "Exponential distribution probability density function (PDF).", "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", "stdmath", "statistics", "stats", "distribution", "dist", "probability", "continuous", "pdf", "life-time", "memoryless property", "arrival time", "exponential", "univariate" ] } },{}],343:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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":458}],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 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":343,"./defaults.json":345,"./destroy.js":346,"./validate.js":351,"@stdlib/utils/copy":370,"@stdlib/utils/inherit":402,"debug":458,"readable-stream":475}],345:[function(require,module,exports){ module.exports={ "objectMode": false, "encoding": null, "allowHalfOpen": false, "decodeStrings": true } },{}],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'; // 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":428,"debug":458}],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 isObject = require( '@stdlib/assert/is-plain-object' ); var copy = require( '@stdlib/utils/copy' ); var Stream = require( './main.js' ); // MAIN // /** * Creates a reusable transform stream factory. * * @param {Options} [options] - stream options * @param {boolean} [options.objectMode=false] - specifies whether a stream should operate in object mode * @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings` * @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false` * @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends * @param {boolean} [options.decodeStrings=true] - specifies whether to decode `strings` into `Buffer` objects when writing * @throws {TypeError} options argument must be an object * @returns {Function} transform stream factory * * @example * function transform( chunk, enc, clbk ) { * clbk( null, chunk.toString()+'\n' ); * } * * var opts = { * 'objectMode': true, * 'encoding': 'utf8', * 'highWaterMark': 64, * 'decodeStrings': false * }; * * var factory = streamFactory( opts ); * * // Create 10 identically configured streams... * var streams = []; * var i; * for ( i = 0; i < 10; i++ ) { * streams.push( factory( transform ) ); * } */ function streamFactory( options ) { var opts; if ( arguments.length ) { if ( !isObject( options ) ) { throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' ); } opts = copy( options ); } else { opts = {}; } return createStream; /** * Creates a transform stream. * * @private * @param {Function} transform - callback to invoke upon receiving a new chunk * @param {Function} [flush] - callback to invoke after receiving all chunks and prior to the stream closing * @throws {TypeError} must provide valid options * @throws {TypeError} transform callback must be a function * @throws {TypeError} flush callback must be a function * @returns {TransformStream} transform stream */ function createStream( transform, flush ) { opts.transform = transform; if ( arguments.length > 1 ) { opts.flush = flush; } else { delete opts.flush; // clear any previous `flush` } return new Stream( opts ); } } // EXPORTS // module.exports = streamFactory; },{"./main.js":349,"@stdlib/assert/is-plain-object":147,"@stdlib/utils/copy":370}],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'; /** * 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":344,"./factory.js":347,"./main.js":349,"./object_mode.js":350,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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'; // 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":343,"./defaults.json":345,"./destroy.js":346,"./validate.js":351,"@stdlib/utils/copy":370,"@stdlib/utils/inherit":402,"debug":458,"readable-stream":475}],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'; // MODULES // var isObject = require( '@stdlib/assert/is-plain-object' ); var copy = require( '@stdlib/utils/copy' ); var Stream = require( './main.js' ); // MAIN // /** * Returns a transform stream with `objectMode` set to `true`. * * @param {Options} [options] - stream options * @param {Function} [options.transform] - callback to invoke upon receiving a new chunk * @param {Function} [options.flush] - callback to invoke after receiving all chunks and prior to the stream closing * @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings` * @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false` * @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends * @param {boolean} [options.decodeStrings=true] - specifies whether to decode `strings` into `Buffer` objects when writing * @throws {TypeError} options argument must be an object * @throws {TypeError} must provide valid options * @returns {TransformStream} transform stream * * @example * var stdout = require( '@stdlib/streams/node/stdout' ); * * function stringify( chunk, enc, clbk ) { * clbk( null, JSON.stringify( chunk ) ); * } * * function newline( chunk, enc, clbk ) { * clbk( null, chunk+'\n' ); * } * * var s1 = objectMode({ * 'transform': stringify * }); * * var s2 = objectMode({ * 'transform': newline * }); * * s1.pipe( s2 ).pipe( stdout ); * * s1.write( {'value': 'a'} ); * s1.write( {'value': 'b'} ); * s1.write( {'value': 'c'} ); * * s1.end(); * * // prints: '{"value":"a"}\n{"value":"b"}\n{"value":"c"}\n' */ function objectMode( options ) { var opts; if ( arguments.length ) { if ( !isObject( options ) ) { throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' ); } opts = copy( options ); } else { opts = {}; } opts.objectMode = true; return new Stream( opts ); } // EXPORTS // module.exports = objectMode; },{"./main.js":349,"@stdlib/assert/is-plain-object":147,"@stdlib/utils/copy":370}],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'; // MODULES // var isObject = require( '@stdlib/assert/is-plain-object' ); var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var isFunction = require( '@stdlib/assert/is-function' ); var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; var isNonNegative = require( '@stdlib/assert/is-nonnegative-number' ).isPrimitive; var isString = require( '@stdlib/assert/is-string' ).isPrimitive; // MAIN // /** * Validates function options. * * @private * @param {Object} opts - destination object * @param {Options} options - function options * @param {Function} [options.transform] - callback to invoke upon receiving a new chunk * @param {Function} [options.flush] - callback to invoke after receiving all chunks and prior to the stream closing * @param {boolean} [options.objectMode] - specifies whether a stream should operate in object mode * @param {(string|null)} [options.encoding] - specifies how `Buffer` objects should be decoded to `strings` * @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false` * @param {boolean} [options.allowHalfOpen] - specifies whether the stream should remain open even if one side ends * @param {boolean} [options.decodeStrings] - specifies whether to decode `strings` into `Buffer` objects when writing * @returns {(Error|null)} null or an error object */ function validate( opts, options ) { if ( !isObject( options ) ) { return new TypeError( 'invalid argument. Options must be an object. Value: `' + options + '`.' ); } if ( hasOwnProp( options, 'transform' ) ) { opts.transform = options.transform; if ( !isFunction( opts.transform ) ) { return new TypeError( 'invalid option. `transform` option must be a function. Option: `' + opts.transform + '`.' ); } } if ( hasOwnProp( options, 'flush' ) ) { opts.flush = options.flush; if ( !isFunction( opts.flush ) ) { return new TypeError( 'invalid option. `flush` option must be a function. Option: `' + opts.flush + '`.' ); } } if ( hasOwnProp( options, 'objectMode' ) ) { opts.objectMode = options.objectMode; if ( !isBoolean( opts.objectMode ) ) { return new TypeError( 'invalid option. `objectMode` option must be a primitive boolean. Option: `' + opts.objectMode + '`.' ); } } if ( hasOwnProp( options, 'encoding' ) ) { opts.encoding = options.encoding; if ( !isString( opts.encoding ) ) { return new TypeError( 'invalid option. `encoding` option must be a primitive string. Option: `' + opts.encoding + '`.' ); } } if ( hasOwnProp( options, 'allowHalfOpen' ) ) { opts.allowHalfOpen = options.allowHalfOpen; if ( !isBoolean( opts.allowHalfOpen ) ) { return new TypeError( 'invalid option. `allowHalfOpen` option must be a primitive boolean. Option: `' + opts.allowHalfOpen + '`.' ); } } if ( hasOwnProp( options, 'highWaterMark' ) ) { opts.highWaterMark = options.highWaterMark; if ( !isNonNegative( opts.highWaterMark ) ) { return new TypeError( 'invalid option. `highWaterMark` option must be a nonnegative number. Option: `' + opts.highWaterMark + '`.' ); } } if ( hasOwnProp( options, 'decodeStrings' ) ) { opts.decodeStrings = options.decodeStrings; if ( !isBoolean( opts.decodeStrings ) ) { return new TypeError( 'invalid option. `decodeStrings` option must be a primitive boolean. Option: `' + opts.decodeStrings + '`.' ); } } return null; } // EXPORTS // module.exports = validate; },{"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-function":102,"@stdlib/assert/is-nonnegative-number":131,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-string":158}],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'; /** * 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":353}],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 isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive; var isCollection = require( '@stdlib/assert/is-collection' ); var UNICODE_MAX = require( '@stdlib/constants/unicode/max' ); var UNICODE_MAX_BMP = require( '@stdlib/constants/unicode/max-bmp' ); // VARIABLES // var fromCharCode = String.fromCharCode; // Factor to rescale a code point from a supplementary plane: var Ox10000 = 0x10000|0; // 65536 // Factor added to obtain a high surrogate: var OxD800 = 0xD800|0; // 55296 // Factor added to obtain a low surrogate: var OxDC00 = 0xDC00|0; // 56320 // 10-bit mask: 2^10-1 = 1023 => 0x3ff => 00000000 00000000 00000011 11111111 var Ox3FF = 1023|0; // MAIN // /** * Creates a string from a sequence of Unicode code points. * * ## Notes * * - UTF-16 encoding uses one 16-bit unit for non-surrogates (U+0000 to U+D7FF and U+E000 to U+FFFF). * - UTF-16 encoding uses two 16-bit units (surrogate pairs) for U+10000 to U+10FFFF and encodes U+10000-U+10FFFF by subtracting 0x10000 from the code point, expressing the result as a 20-bit binary, and splitting the 20 bits of 0x0-0xFFFFF as upper and lower 10-bits. The respective 10-bits are stored in two 16-bit words: a high and a low surrogate. * * * @param {...NonNegativeInteger} args - sequence of code points * @throws {Error} must provide either an array-like object of code points or one or more code points as separate arguments * @throws {TypeError} a code point must be a nonnegative integer * @throws {RangeError} must provide a valid Unicode code point * @returns {string} created string * * @example * var str = fromCodePoint( 9731 ); * // returns '☃' */ function fromCodePoint( args ) { var len; var str; var arr; var low; var hi; var pt; var i; len = arguments.length; if ( len === 1 && isCollection( args ) ) { arr = arguments[ 0 ]; len = arr.length; } else { arr = []; for ( i = 0; i < len; i++ ) { arr.push( arguments[ i ] ); } } if ( len === 0 ) { throw new Error( 'insufficient input arguments. Must provide either an array of code points or one or more code points as separate arguments.' ); } str = ''; for ( i = 0; i < len; i++ ) { pt = arr[ i ]; if ( !isNonNegativeInteger( pt ) ) { throw new TypeError( 'invalid argument. Must provide valid code points (nonnegative integers). Value: `'+pt+'`.' ); } if ( pt > UNICODE_MAX ) { throw new RangeError( 'invalid argument. Must provide a valid code point (cannot exceed max). Value: `'+pt+'`.' ); } if ( pt <= UNICODE_MAX_BMP ) { str += fromCharCode( pt ); } else { // Code point from a supplementary plane. Split into two 16-bit code units (surrogate pair). pt -= Ox10000; hi = (pt >> 10) + OxD800; low = (pt & Ox3FF) + OxDC00; str += fromCharCode( hi, low ); } } return str; } // EXPORTS // module.exports = fromCodePoint; },{"@stdlib/assert/is-collection":90,"@stdlib/assert/is-nonnegative-integer":127,"@stdlib/constants/unicode/max":258,"@stdlib/constants/unicode/max-bmp":257}],354:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * 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":355}],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 rescape = require( '@stdlib/utils/escape-regexp-string' ); var isFunction = require( '@stdlib/assert/is-function' ); var isString = require( '@stdlib/assert/is-string' ).isPrimitive; var isRegExp = require( '@stdlib/assert/is-regexp' ); // MAIN // /** * Replace search occurrences with a replacement string. * * @param {string} str - input string * @param {(string|RegExp)} search - search expression * @param {(string|Function)} newval - replacement value or function * @throws {TypeError} first argument must be a string primitive * @throws {TypeError} second argument argument must be a string primitive or regular expression * @throws {TypeError} third argument must be a string primitive or function * @returns {string} new string containing replacement(s) * * @example * var str = 'beep'; * var out = replace( str, 'e', 'o' ); * // returns 'boop' * * @example * var str = 'Hello World'; * var out = replace( str, /world/i, 'Mr. President' ); * // returns 'Hello Mr. President' * * @example * var capitalize = require( '@stdlib/string/capitalize' ); * * var str = 'Oranges and lemons say the bells of St. Clement\'s'; * * function replacer( match, p1 ) { * return capitalize( p1 ); * } * * var out = replace( str, /([^\s]*)/gi, replacer); * // returns 'Oranges And Lemons Say The Bells Of St. Clement\'s' */ function replace( str, search, newval ) { if ( !isString( str ) ) { throw new TypeError( 'invalid argument. First argument must be a string primitive. Value: `' + str + '`.' ); } if ( isString( search ) ) { search = rescape( search ); search = new RegExp( search, 'g' ); } else if ( !isRegExp( search ) ) { throw new TypeError( 'invalid argument. Second argument must be a string primitive or regular expression. Value: `' + search + '`.' ); } if ( !isString( newval ) && !isFunction( newval ) ) { throw new TypeError( 'invalid argument. Third argument must be a string primitive or replacement function. Value: `' + newval + '`.' ); } return str.replace( search, newval ); } // EXPORTS // module.exports = replace; },{"@stdlib/assert/is-function":102,"@stdlib/assert/is-regexp":154,"@stdlib/assert/is-string":158,"@stdlib/utils/escape-regexp-string":383}],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'; /** * 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":357}],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'; // MODULES // var isString = require( '@stdlib/assert/is-string' ).isPrimitive; var replace = require( '@stdlib/string/replace' ); // VARIABLES // // The following regular expression should suffice to polyfill (most?) all environments. var RE = /^[\u0020\f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]*([\S\s]*?)[\u0020\f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]*$/; // MAIN // /** * Trim whitespace characters from beginning and end of a string. * * @param {string} str - input string * @throws {TypeError} must provide a string primitive * @returns {string} trimmed string * * @example * var out = trim( ' Whitespace ' ); * // returns 'Whitespace' * * @example * var out = trim( '\t\t\tTabs\t\t\t' ); * // returns 'Tabs' * * @example * var out = trim( '\n\n\nNew Lines\n\n\n' ); * // returns 'New Lines' */ function trim( str ) { if ( !isString( str ) ) { throw new TypeError( 'invalid argument. Must provide a string primitive. Value: `' + str + '`.' ); } return replace( str, RE, '$1' ); } // EXPORTS // module.exports = trim; },{"@stdlib/assert/is-string":158,"@stdlib/string/replace":354}],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 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":360,"@stdlib/assert/is-object":145,"@stdlib/math/base/special/modf":283,"@stdlib/math/base/special/round":286,"@stdlib/utils/global":395}],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 isFunction = require( '@stdlib/assert/is-function' ); // MAIN // var bool = isFunction( Date.now ); // EXPORTS // module.exports = bool; },{"@stdlib/assert/is-function":102}],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'; // 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":359,"./polyfill.js":361}],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 // /** * 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; },{}],362:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * 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":363}],363:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var isNonNegativeIntegerArray = require( '@stdlib/assert/is-nonnegative-integer-array' ).primitives; var tic = require( '@stdlib/time/tic' ); // MAIN // /** * Returns a high-resolution time difference. * * ## Notes * * - Output format: `[seconds, nanoseconds]`. * * * @param {NonNegativeIntegerArray} time - high-resolution time * @throws {TypeError} must provide a nonnegative integer array * @throws {RangeError} input array must have length `2` * @returns {NumberArray} high resolution time difference * * @example * var tic = require( '@stdlib/time/tic' ); * * var start = tic(); * var delta = toc( start ); * // returns [<number>,<number>] */ function toc( time ) { var now = tic(); var sec; var ns; if ( !isNonNegativeIntegerArray( time ) ) { throw new TypeError( 'invalid argument. Must provide an array of nonnegative integers. Value: `' + time + '`.' ); } if ( time.length !== 2 ) { throw new RangeError( 'invalid argument. Input array must have length `2`.' ); } sec = now[ 0 ] - time[ 0 ]; ns = now[ 1 ] - time[ 1 ]; if ( sec > 0 && ns < 0 ) { sec -= 1; ns += 1e9; } else if ( sec < 0 && ns > 0 ) { sec += 1; ns -= 1e9; } return [ sec, ns ]; } // EXPORTS // module.exports = toc; },{"@stdlib/assert/is-nonnegative-integer-array":126,"@stdlib/time/tic":358}],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'; /** * Creates a function which always returns the same value. * * @param {*} [value] - value to always return * @returns {Function} constant function * * @example * var fcn = wrap( 3.14 ); * * var v = fcn(); * // returns 3.14 * * v = fcn(); * // returns 3.14 * * v = fcn(); * // returns 3.14 */ function wrap( value ) { return constantFunction; /** * Constant function. * * @private * @returns {*} constant value */ function constantFunction() { return value; } } // EXPORTS // module.exports = wrap; },{}],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'; /** * Create a constant function. * * @module @stdlib/utils/constant-function * * @example * var constantFunction = require( '@stdlib/utils/constant-function' ); * * var fcn = constantFunction( 3.14 ); * * var v = fcn(); * // returns 3.14 * * v = fcn(); * // returns 3.14 * * v = fcn(); * // returns 3.14 */ // MODULES // var constantFunction = require( './constant_function.js' ); // EXPORTS // module.exports = constantFunction; },{"./constant_function.js":364}],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'; /** * 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":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 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":88,"@stdlib/regexp/function-name":332,"@stdlib/utils/native-class":423}],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'; // MODULES // var isArray = require( '@stdlib/assert/is-array' ); var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive; var PINF = require( '@stdlib/constants/float64/pinf' ); var deepCopy = require( './deep_copy.js' ); // MAIN // /** * Copies or deep clones a value to an arbitrary depth. * * @param {*} value - value to copy * @param {NonNegativeInteger} [level=+infinity] - copy depth * @throws {TypeError} `level` must be a nonnegative integer * @returns {*} value copy * * @example * var out = copy( 'beep' ); * // returns 'beep' * * @example * var value = [ * { * 'a': 1, * 'b': true, * 'c': [ 1, 2, 3 ] * } * ]; * var out = copy( value ); * // returns [ { 'a': 1, 'b': true, 'c': [ 1, 2, 3 ] } ] * * var bool = ( value[0].c === out[0].c ); * // returns false */ function copy( value, level ) { var out; if ( arguments.length > 1 ) { if ( !isNonNegativeInteger( level ) ) { throw new TypeError( 'invalid argument. `level` must be a nonnegative integer. Value: `' + level + '`.' ); } if ( level === 0 ) { return value; } } else { level = PINF; } out = ( isArray( value ) ) ? new Array( value.length ) : {}; return deepCopy( value, out, [value], [out], level ); } // EXPORTS // module.exports = copy; },{"./deep_copy.js":369,"@stdlib/assert/is-array":79,"@stdlib/assert/is-nonnegative-integer":127,"@stdlib/constants/float64/pinf":246}],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 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":371,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-array":79,"@stdlib/assert/is-buffer":88,"@stdlib/assert/is-error":96,"@stdlib/buffer/from-buffer":232,"@stdlib/utils/define-property":381,"@stdlib/utils/get-prototype-of":389,"@stdlib/utils/index-of":399,"@stdlib/utils/keys":416,"@stdlib/utils/property-descriptor":438,"@stdlib/utils/property-names":442,"@stdlib/utils/regexp-from-string":445,"@stdlib/utils/type-of":450}],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'; /** * 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":368}],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'; // 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":20,"@stdlib/array/uint32":23,"@stdlib/array/uint8":26,"@stdlib/array/uint8c":29}],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'; /** * 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":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 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":381}],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'; /** * 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":375}],375:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":381}],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'; /** * Define a non-enumerable read-write accessor. * * @module @stdlib/utils/define-nonenumerable-read-write-accessor * * @example * var setNonEnumerableReadWriteAccessor = require( '@stdlib/utils/define-nonenumerable-read-write-accessor' ); * * function getter() { * return name + ' foo'; * } * * function setter( v ) { * name = v; * } * * var name = 'bar'; * var obj = {}; * * setNonEnumerableReadWriteAccessor( obj, 'foo', getter, setter ); * * var v = obj.foo; * // returns 'bar foo' * * obj.foo = 'beep'; * * v = obj.foo; * // returns 'beep foo' */ // MODULES // var setNonEnumerableReadWriteAccessor = require( './main.js' ); // EXPORTS // module.exports = setNonEnumerableReadWriteAccessor; },{"./main.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 defineProperty = require( '@stdlib/utils/define-property' ); // MAIN // /** * Defines a non-enumerable read-write accessor. * * @param {Object} obj - object on which to define the property * @param {(string|symbol)} prop - property name * @param {Function} getter - get accessor * @param {Function} setter - set accessor * * @example * function getter() { * return name + ' foo'; * } * * function setter( v ) { * name = v; * } * * var name = 'bar'; * var obj = {}; * * setNonEnumerableReadWriteAccessor( obj, 'foo', getter, setter ); * * var v = obj.foo; * // returns 'bar foo' * * obj.foo = 'beep'; * * v = obj.foo; * // returns 'beep foo' */ function setNonEnumerableReadWriteAccessor( obj, prop, getter, setter ) { // eslint-disable-line id-length defineProperty( obj, prop, { 'configurable': false, 'enumerable': false, 'get': getter, 'set': setter }); } // EXPORTS // module.exports = setNonEnumerableReadWriteAccessor; },{"@stdlib/utils/define-property":381}],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'; // 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; },{}],379:[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; },{}],380:[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":379}],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'; /** * 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":378,"./has_define_property_support.js":380,"./polyfill.js":382}],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. */ /* eslint-disable no-underscore-dangle, no-proto */ 'use strict'; // VARIABLES // var objectProtoype = Object.prototype; var toStr = objectProtoype.toString; var defineGetter = objectProtoype.__defineGetter__; var defineSetter = objectProtoype.__defineSetter__; var lookupGetter = objectProtoype.__lookupGetter__; var lookupSetter = objectProtoype.__lookupSetter__; // MAIN // /** * Defines (or modifies) an object property. * * ## Notes * * - Property descriptors come in two flavors: **data descriptors** and **accessor descriptors**. A data descriptor is a property that has a value, which may or may not be writable. An accessor descriptor is a property described by a getter-setter function pair. A descriptor must be one of these two flavors and cannot be both. * * @param {Object} obj - object on which to define the property * @param {string} prop - property name * @param {Object} descriptor - property descriptor * @param {boolean} [descriptor.configurable=false] - boolean indicating if property descriptor can be changed and if the property can be deleted from the provided object * @param {boolean} [descriptor.enumerable=false] - boolean indicating if the property shows up when enumerating object properties * @param {boolean} [descriptor.writable=false] - boolean indicating if the value associated with the property can be changed with an assignment operator * @param {*} [descriptor.value] - property value * @param {(Function|void)} [descriptor.get=undefined] - function which serves as a getter for the property, or, if no getter, undefined. When the property is accessed, a getter function is called without arguments and with the `this` context set to the object through which the property is accessed (which may not be the object on which the property is defined due to inheritance). The return value will be used as the property value. * @param {(Function|void)} [descriptor.set=undefined] - function which serves as a setter for the property, or, if no setter, undefined. When assigning a property value, a setter function is called with one argument (the value being assigned to the property) and with the `this` context set to the object through which the property is assigned. * @throws {TypeError} first argument must be an object * @throws {TypeError} third argument must be an object * @throws {Error} property descriptor cannot have both a value and a setter and/or getter * @returns {Object} object with added property * * @example * var obj = {}; * * defineProperty( obj, 'foo', { * 'value': 'bar' * }); * * var str = obj.foo; * // returns 'bar' */ function defineProperty( obj, prop, descriptor ) { var prototype; var hasValue; var hasGet; var hasSet; if ( typeof obj !== 'object' || obj === null || toStr.call( obj ) === '[object Array]' ) { throw new TypeError( 'invalid argument. First argument must be an object. Value: `' + obj + '`.' ); } if ( typeof descriptor !== 'object' || descriptor === null || toStr.call( descriptor ) === '[object Array]' ) { throw new TypeError( 'invalid argument. Property descriptor must be an object. Value: `' + descriptor + '`.' ); } hasValue = ( 'value' in descriptor ); if ( hasValue ) { if ( lookupGetter.call( obj, prop ) || lookupSetter.call( obj, prop ) ) { // Override `__proto__` to avoid touching inherited accessors: prototype = obj.__proto__; obj.__proto__ = objectProtoype; // Delete property as existing getters/setters prevent assigning value to specified property: delete obj[ prop ]; obj[ prop ] = descriptor.value; // Restore original prototype: obj.__proto__ = prototype; } else { obj[ prop ] = descriptor.value; } } hasGet = ( 'get' in descriptor ); hasSet = ( 'set' in descriptor ); if ( hasValue && ( hasGet || hasSet ) ) { throw new Error( 'invalid argument. Cannot specify one or more accessors and a value or writable attribute in the property descriptor.' ); } if ( hasGet && defineGetter ) { defineGetter.call( obj, prop, descriptor.get ); } if ( hasSet && defineSetter ) { defineSetter.call( obj, prop, descriptor.set ); } return obj; } // EXPORTS // module.exports = defineProperty; },{}],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'; /** * 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":384}],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'; // MODULES // var isString = require( '@stdlib/assert/is-string' ).isPrimitive; // VARIABLES // var RE_CHARS = /[-\/\\^$*+?.()|[\]{}]/g; // eslint-disable-line no-useless-escape // MAIN // /** * Escapes a regular expression string. * * @param {string} str - regular expression string * @throws {TypeError} first argument must be a string primitive * @returns {string} escaped string * * @example * var str = rescape( '[A-Z]*' ); * // returns '\\[A\\-Z\\]\\*' */ function rescape( str ) { var len; var s; var i; if ( !isString( str ) ) { throw new TypeError( 'invalid argument. Must provide a regular expression string. Value: `' + str + '`.' ); } // Check if the string starts with a forward slash... if ( str[ 0 ] === '/' ) { // Find the last forward slash... len = str.length; for ( i = len-1; i >= 0; i-- ) { if ( str[ i ] === '/' ) { break; } } } // If we searched the string to no avail or if the first letter is not `/`, assume that the string is not of the form `/[...]/[guimy]`: if ( i === void 0 || i <= 0 ) { return str.replace( RE_CHARS, '\\$&' ); } // We need to de-construct the string... s = str.substring( 1, i ); // Only escape the characters between the `/`: s = s.replace( RE_CHARS, '\\$&' ); // Reassemble: str = str[ 0 ] + s + str.substring( i ); return str; } // EXPORTS // module.exports = rescape; },{"@stdlib/assert/is-string":158}],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 isFunction = require( '@stdlib/assert/is-function' ); var hasFunctionNameSupport = require( '@stdlib/assert/has-function-name-support' ); var RE = require( '@stdlib/regexp/function-name' ).REGEXP; // VARIABLES // var isFunctionNameSupported = hasFunctionNameSupport(); // MAIN // /** * Returns the name of a function. * * @param {Function} fcn - input function * @throws {TypeError} must provide a function * @returns {string} function name * * @example * var v = functionName( Math.sqrt ); * // returns 'sqrt' * * @example * var v = functionName( function foo(){} ); * // returns 'foo' * * @example * var v = functionName( function(){} ); * // returns '' || 'anonymous' * * @example * var v = functionName( String ); * // returns 'String' */ function functionName( fcn ) { // TODO: add support for generator functions? if ( isFunction( fcn ) === false ) { throw new TypeError( 'invalid argument. Must provide a function. Value: `' + fcn + '`.' ); } if ( isFunctionNameSupported ) { return fcn.name; } return RE.exec( fcn.toString() )[ 1 ]; } // EXPORTS // module.exports = functionName; },{"@stdlib/assert/has-function-name-support":39,"@stdlib/assert/is-function":102,"@stdlib/regexp/function-name":332}],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'; /** * Return the name of a function. * * @module @stdlib/utils/function-name * * @example * var functionName = require( '@stdlib/utils/function-name' ); * * var v = functionName( String ); * // returns 'String' * * v = functionName( function foo(){} ); * // returns 'foo' * * v = functionName( function(){} ); * // returns '' || 'anonymous' */ // MODULES // var functionName = require( './function_name.js' ); // EXPORTS // module.exports = functionName; },{"./function_name.js":385}],387:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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":390,"./polyfill.js":391,"@stdlib/assert/is-function":102}],388:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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":387}],389:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":388}],390:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],391:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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":392,"@stdlib/utils/native-class":423}],392:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],393:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],394:[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 : {}) },{}],395:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":396}],396:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; var getThis = require( './codegen.js' ); var Self = require( './self.js' ); var Win = require( './window.js' ); var Global = require( './global.js' ); // MAIN // /** * Returns the global object. * * ## Notes * * - Using code generation is the **most** reliable way to resolve the global object; however, doing so is likely to violate content security policies (CSPs) in, e.g., Chrome Apps and elsewhere. * * @param {boolean} [codegen=false] - boolean indicating whether to use code generation to resolve the global object * @throws {TypeError} must provide a boolean * @throws {Error} unable to resolve global object * @returns {Object} global object * * @example * var g = getGlobal(); * // returns {...} */ function getGlobal( codegen ) { if ( arguments.length ) { if ( !isBoolean( codegen ) ) { throw new TypeError( 'invalid argument. Must provide a boolean primitive. Value: `'+codegen+'`.' ); } if ( codegen ) { return getThis(); } // Fall through... } // Case: browsers and web workers if ( Self ) { return Self; } // Case: browsers if ( Win ) { return Win; } // Case: Node.js if ( Global ) { return Global; } // Case: unknown throw new Error( 'unexpected error. Unable to resolve global object.' ); } // EXPORTS // module.exports = getGlobal; },{"./codegen.js":393,"./global.js":394,"./self.js":397,"./window.js":398,"@stdlib/assert/is-boolean":81}],397:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],398:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],399:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":400}],400:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var isnan = require( '@stdlib/assert/is-nan' ); var isCollection = require( '@stdlib/assert/is-collection' ); var isString = require( '@stdlib/assert/is-string' ).isPrimitive; var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive; // MAIN // /** * Returns the first index at which a given element can be found. * * @param {ArrayLike} arr - array-like object * @param {*} searchElement - element to find * @param {integer} [fromIndex] - starting index (if negative, the start index is determined relative to last element) * @throws {TypeError} must provide an array-like object * @throws {TypeError} `fromIndex` must be an integer * @returns {integer} index or -1 * * @example * var arr = [ 4, 3, 2, 1 ]; * var idx = indexOf( arr, 3 ); * // returns 1 * * @example * var arr = [ 4, 3, 2, 1 ]; * var idx = indexOf( arr, 5 ); * // returns -1 * * @example * // Using a `fromIndex`: * var arr = [ 1, 2, 3, 4, 5, 2, 6 ]; * var idx = indexOf( arr, 2, 3 ); * // returns 5 * * @example * // `fromIndex` which exceeds `array` length: * var arr = [ 1, 2, 3, 4, 2, 5 ]; * var idx = indexOf( arr, 2, 10 ); * // returns -1 * * @example * // Negative `fromIndex`: * var arr = [ 1, 2, 3, 4, 5, 2, 6, 2 ]; * var idx = indexOf( arr, 2, -4 ); * // returns 5 * * idx = indexOf( arr, 2, -1 ); * // returns 7 * * @example * // Negative `fromIndex` exceeding input `array` length: * var arr = [ 1, 2, 3, 4, 5, 2, 6 ]; * var idx = indexOf( arr, 2, -10 ); * // returns 1 * * @example * // Array-like objects: * var str = 'bebop'; * var idx = indexOf( str, 'o' ); * // returns 3 */ function indexOf( arr, searchElement, fromIndex ) { var len; var i; if ( !isCollection( arr ) && !isString( arr ) ) { throw new TypeError( 'invalid argument. First argument must be an array-like object. Value: `' + arr + '`.' ); } len = arr.length; if ( len === 0 ) { return -1; } if ( arguments.length === 3 ) { if ( !isInteger( fromIndex ) ) { throw new TypeError( 'invalid argument. `fromIndex` must be an integer. Value: `' + fromIndex + '`.' ); } if ( fromIndex >= 0 ) { if ( fromIndex >= len ) { return -1; } i = fromIndex; } else { i = len + fromIndex; if ( i < 0 ) { i = 0; } } } else { i = 0; } // Check for `NaN`... if ( isnan( searchElement ) ) { for ( ; i < len; i++ ) { if ( isnan( arr[i] ) ) { return i; } } } else { for ( ; i < len; i++ ) { if ( arr[ i ] === searchElement ) { return i; } } } return -1; } // EXPORTS // module.exports = indexOf; },{"@stdlib/assert/is-collection":90,"@stdlib/assert/is-integer":110,"@stdlib/assert/is-nan":118,"@stdlib/assert/is-string":158}],401:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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":404,"./polyfill.js":405}],402:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":403}],403:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var defineProperty = require( '@stdlib/utils/define-property' ); var validate = require( './validate.js' ); var createObject = require( './detect.js' ); // MAIN // /** * Implements prototypical inheritance by replacing the prototype of one constructor with the prototype of another constructor. * * ## Notes * * - This implementation is not designed to work with ES2015/ES6 classes. For ES2015/ES6 classes, use `class` with `extends`. * - For reference, see [node#3455](https://github.com/nodejs/node/pull/3455), [node#4179](https://github.com/nodejs/node/issues/4179), [node#3452](https://github.com/nodejs/node/issues/3452), and [node commit](https://github.com/nodejs/node/commit/29da8cf8d7ab8f66b9091ab22664067d4468461e#diff-3deb3f32958bb937ae05c6f3e4abbdf5). * * * @param {(Object|Function)} ctor - constructor which will inherit * @param {(Object|Function)} superCtor - super (parent) constructor * @throws {TypeError} first argument must be either an object or a function which can inherit * @throws {TypeError} second argument must be either an object or a function from which a constructor can inherit * @throws {TypeError} second argument must have an inheritable prototype * @returns {(Object|Function)} child constructor * * @example * function Foo() { * return this; * } * Foo.prototype.beep = function beep() { * return 'boop'; * }; * * function Bar() { * Foo.call( this ); * return this; * } * inherit( Bar, Foo ); * * var bar = new Bar(); * var v = bar.beep(); * // returns 'boop' */ function inherit( ctor, superCtor ) { var err = validate( ctor ); if ( err ) { throw err; } err = validate( superCtor ); if ( err ) { throw err; } if ( typeof superCtor.prototype === 'undefined' ) { throw new TypeError( 'invalid argument. Second argument must have a prototype from which another object can inherit. Value: `'+superCtor.prototype+'`.' ); } // Create a prototype which inherits from the parent prototype: ctor.prototype = createObject( superCtor.prototype ); // Set the constructor to refer to the child constructor: defineProperty( ctor.prototype, 'constructor', { 'configurable': true, 'enumerable': false, 'writable': true, 'value': ctor }); return ctor; } // EXPORTS // module.exports = inherit; },{"./detect.js":401,"./validate.js":406,"@stdlib/utils/define-property":381}],404:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],405:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],406:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * Tests that a value is a valid constructor. * * @private * @param {*} value - value to test * @returns {(Error|null)} error object or null * * @example * var ctor = function ctor() {}; * * var err = validate( ctor ); * // returns null * * err = validate( null ); * // returns <TypeError> */ function validate( value ) { var type = typeof value; if ( value === null || (type !== 'object' && type !== 'function') ) { return new TypeError( 'invalid argument. A provided constructor must be either an object (except null) or a function. Value: `'+value+'`.' ); } return null; } // EXPORTS // module.exports = validate; },{}],407:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],408:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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":407,"@stdlib/assert/is-arguments":74}],409:[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" ] },{}],410:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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":407}],411:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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":409,"./is_constructor_prototype.js":417,"./window.js":422,"@stdlib/assert/has-own-property":53,"@stdlib/utils/index-of":399,"@stdlib/utils/type-of":450}],412:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],413:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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":93,"@stdlib/utils/noop":430}],414:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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":93}],415:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],416:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":419}],417:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],418:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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":411,"./has_window.js":415,"./is_constructor_prototype.js":417}],419:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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":407,"./builtin_wrapper.js":408,"./has_arguments_bug.js":410,"./has_builtin.js":412,"./polyfill.js":421}],420:[function(require,module,exports){ module.exports=[ "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "constructor" ] },{}],421:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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":413,"./has_non_enumerable_properties_bug.js":414,"./is_constructor_prototype_wrapper.js":418,"./non_enumerable.json":420,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-arguments":74,"@stdlib/assert/is-object-like":143}],422:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],423:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":424,"./polyfill.js":425,"@stdlib/assert/has-tostringtag-support":57}],424:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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":426}],425:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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":426,"./tostringtag.js":427,"@stdlib/assert/has-own-property":53}],426:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],427:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],428:[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":429}],429:[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":466}],430:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":431}],431:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],432:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":433}],433:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var objectKeys = require( '@stdlib/utils/keys' ); var isString = require( '@stdlib/assert/is-string' ).isPrimitive; var isStringArray = require( '@stdlib/assert/is-string-array' ).primitives; var indexOf = require( '@stdlib/utils/index-of' ); // MAIN // /** * Returns a partial object copy excluding specified keys. * * @param {Object} obj - source object * @param {(string|StringArray)} keys - keys to exclude * @throws {TypeError} first argument must be an object * @throws {TypeError} second argument must be either a string or an array of strings * @returns {Object} new object * * @example * var obj1 = { * 'a': 1, * 'b': 2 * }; * * var obj2 = omit( obj1, 'b' ); * // returns { 'a': 1 } */ function omit( obj, keys ) { var ownKeys; var out; var key; var i; if ( typeof obj !== 'object' || obj === null ) { throw new TypeError( 'invalid argument. First argument must be an object. Value: `'+obj+'`.' ); } ownKeys = objectKeys( obj ); out = {}; if ( isString( keys ) ) { for ( i = 0; i < ownKeys.length; i++ ) { key = ownKeys[ i ]; if ( key !== keys ) { out[ key ] = obj[ key ]; } } return out; } if ( isStringArray( keys ) ) { for ( i = 0; i < ownKeys.length; i++ ) { key = ownKeys[ i ]; if ( indexOf( keys, key ) === -1 ) { out[ key ] = obj[ key ]; } } return out; } throw new TypeError( 'invalid argument. Second argument must be either a string primitive or an array of string primitives. Value: `'+keys+'`.' ); } // EXPORTS // module.exports = omit; },{"@stdlib/assert/is-string":158,"@stdlib/assert/is-string-array":157,"@stdlib/utils/index-of":399,"@stdlib/utils/keys":416}],434:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":435}],435:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var isString = require( '@stdlib/assert/is-string' ).isPrimitive; var isStringArray = require( '@stdlib/assert/is-string-array' ).primitives; var hasOwnProp = require( '@stdlib/assert/has-own-property' ); // MAIN // /** * Returns a partial object copy containing only specified keys. If a key does not exist as an own property in a source object, the key is ignored. * * @param {Object} obj - source object * @param {(string|StringArray)} keys - keys to copy * @throws {TypeError} first argument must be an object * @throws {TypeError} second argument must be either a string or an array of strings * @returns {Object} new object * * @example * var obj1 = { * 'a': 1, * 'b': 2 * }; * * var obj2 = pick( obj1, 'b' ); * // returns { 'b': 2 } */ function pick( obj, keys ) { var out; var key; var i; if ( typeof obj !== 'object' || obj === null ) { throw new TypeError( 'invalid argument. First argument must be an object. Value: `'+obj+'`.' ); } out = {}; if ( isString( keys ) ) { if ( hasOwnProp( obj, keys ) ) { out[ keys ] = obj[ keys ]; } return out; } if ( isStringArray( keys ) ) { for ( i = 0; i < keys.length; i++ ) { key = keys[ i ]; if ( hasOwnProp( obj, key ) ) { out[ key ] = obj[ key ]; } } return out; } throw new TypeError( 'invalid argument. Second argument must be either a string primitive or an array of string primitives. Value: `'+keys+'`.' ); } // EXPORTS // module.exports = pick; },{"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-string":158,"@stdlib/assert/is-string-array":157}],436:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],437:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],438:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":436,"./has_builtin.js":437,"./polyfill.js":439}],439:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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":53}],440:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],441:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],442:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":440,"./has_builtin.js":441,"./polyfill.js":443}],443:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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":416}],444:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var isString = require( '@stdlib/assert/is-string' ).isPrimitive; var reRegExp = require( '@stdlib/regexp/regexp' ); // MAIN // /** * Parses a regular expression string and returns a new regular expression. * * @param {string} str - regular expression string * @throws {TypeError} must provide a regular expression string * @returns {(RegExp|null)} regular expression or null * * @example * var re = reFromString( '/beep/' ); * // returns /beep/ */ function reFromString( str ) { if ( !isString( str ) ) { throw new TypeError( 'invalid argument. Must provide a regular expression string. Value: `' + str + '`.' ); } // Capture the regular expression pattern and any flags: str = reRegExp().exec( str ); // Create a new regular expression: return ( str ) ? new RegExp( str[1], str[2] ) : null; } // EXPORTS // module.exports = reFromString; },{"@stdlib/assert/is-string":158,"@stdlib/regexp/regexp":335}],445:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":444}],446:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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":447,"./fixtures/re.js":448,"./fixtures/typedarray.js":449}],447:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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":395}],448:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],449:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],450:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":446,"./polyfill.js":451,"./typeof.js":452}],451:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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":366}],452:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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":366}],453:[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('') } },{}],454:[function(require,module,exports){ },{}],455:[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); } } },{}],456:[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":453,"buffer":456,"ieee754":460}],457:[function(require,module,exports){ (function (Buffer){(function (){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(arg) { if (Array.isArray) { return Array.isArray(arg); } return objectToString(arg) === '[object Array]'; } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = Buffer.isBuffer; function objectToString(o) { return Object.prototype.toString.call(o); } }).call(this)}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) },{"../../is-buffer/index.js":462}],458:[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":459,"_process":466}],459:[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":464}],460:[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 } },{}],461:[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 } } } },{}],462:[function(require,module,exports){ /*! * Determine if an object is a Buffer * * @author Feross Aboukhadijeh <https://feross.org> * @license MIT */ // The _isBuffer check is for Safari 5-7 support, because it's missing // Object.prototype.constructor. Remove this eventually module.exports = function (obj) { return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) } function isBuffer (obj) { return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) } // For Node v0.10 support. Remove this eventually. function isSlowBuffer (obj) { return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) } },{}],463:[function(require,module,exports){ var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; },{}],464:[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'; } },{}],465:[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":466}],466:[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; }; },{}],467:[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":469,"./_stream_writable":471,"core-util-is":457,"inherits":461,"process-nextick-args":465}],468:[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":470,"core-util-is":457,"inherits":461}],469:[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":467,"./internal/streams/BufferList":472,"./internal/streams/destroy":473,"./internal/streams/stream":474,"_process":466,"core-util-is":457,"events":455,"inherits":461,"isarray":463,"process-nextick-args":465,"safe-buffer":476,"string_decoder/":477,"util":454}],470:[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":467,"core-util-is":457,"inherits":461}],471:[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":467,"./internal/streams/destroy":473,"./internal/streams/stream":474,"_process":466,"core-util-is":457,"inherits":461,"process-nextick-args":465,"safe-buffer":476,"timers":478,"util-deprecate":479}],472:[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":476,"util":454}],473:[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":465}],474:[function(require,module,exports){ module.exports = require('events').EventEmitter; },{"events":455}],475:[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":467,"./lib/_stream_passthrough.js":468,"./lib/_stream_readable.js":469,"./lib/_stream_transform.js":470,"./lib/_stream_writable.js":471}],476:[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":456}],477:[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":476}],478:[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":466,"timers":478}],479:[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 : {}) },{}]},{},[338]);<|fim▁end|>
defineProperty( this, '_count', { 'configurable': false, 'enumerable': false, 'writable': true,
<|file_name|>uicrosslines.cpp<|end_file_name|><|fim▁begin|>// This file is part of VSTGUI. It is subject to the license terms // in the LICENSE file found in the top-level directory of this // distribution and at http://github.com/steinbergmedia/vstgui/LICENSE #include "uicrosslines.h" #if VSTGUI_LIVE_EDITING #include "../../lib/cviewcontainer.h" #include "../../lib/cdrawcontext.h" #include "uiselection.h" namespace VSTGUI { //---------------------------------------------------------------------------------------------------- UICrossLines::UICrossLines (CViewContainer* editView, int32_t style, const CColor& background, const CColor& foreground) : CView (CRect (0, 0, 0, 0)) , editView (editView) , style (style) , background (background) , foreground (foreground) { setMouseEnabled (false); viewSizeChanged (editView, CRect (0, 0, 0, 0)); editView->registerViewListener (this); } //---------------------------------------------------------------------------------------------------- UICrossLines::~UICrossLines () { editView->unregisterViewListener (this); } //---------------------------------------------------------------------------------------------------- void UICrossLines::viewSizeChanged (CView* view, const CRect& oldSize) { CRect r = editView->getVisibleViewSize (); r.originize (); CPoint p; editView->getParentView ()->localToFrame (p); r.offset (p.x, p.y); if (getViewSize () != r) { invalidRect (getViewSize ()); setViewSize (r); } } //---------------------------------------------------------------------------------------------------- void UICrossLines::update (UISelection* selection) { invalid (); CPoint p; currentRect = selection->getBounds (); localToFrame (p); currentRect.offset (-p.x, -p.y); invalid (); } //---------------------------------------------------------------------------------------------------- void UICrossLines::update (const CPoint& point) { invalid (); currentRect.left = point.x-1; currentRect.top = point.y-1; currentRect.setWidth (1); currentRect.setHeight (1); editView->getTransform ().transform (currentRect); CPoint p; getParentView ()->frameToLocal (p); currentRect.offset (p.x, p.y); editView->localToFrame (p); currentRect.offset (p.x, p.y); invalid (); } //---------------------------------------------------------------------------------------------------- void UICrossLines::invalid () { CRect frameRect = getViewSize (); invalidRect (CRect (currentRect.left-3, frameRect.top, currentRect.left+3, frameRect.bottom)); invalidRect (CRect (frameRect.left, currentRect.top-3, frameRect.right, currentRect.top+3)); if (style == kSelectionStyle) { invalidRect (CRect (currentRect.right-3, frameRect.top, currentRect.right+3, frameRect.bottom)); invalidRect (CRect (frameRect.left, currentRect.bottom-3, frameRect.right, currentRect.bottom+3)); } } //---------------------------------------------------------------------------------------------------- void UICrossLines::drawLines (CDrawContext* pContext, const CRect& size, const CRect& selectionSize) { pContext->drawLine (CPoint (size.left, selectionSize.top), CPoint (size.right, selectionSize.top)); pContext->drawLine (CPoint (selectionSize.left, size.top), CPoint (selectionSize.left, size.bottom)); if (style == kSelectionStyle) { pContext->drawLine (CPoint (size.left, selectionSize.bottom - 1), CPoint (size.right, selectionSize.bottom - 1)); pContext->drawLine (CPoint (selectionSize.right-1, size.top), CPoint (selectionSize.right-1, size.bottom)); } } //---------------------------------------------------------------------------------------------------- void UICrossLines::draw (CDrawContext* pContext) { CRect size = getViewSize (); CRect selectionSize (currentRect); pContext->setDrawMode (kAliasing); pContext->setLineStyle (kLineSolid); pContext->setFrameColor (background); pContext->setLineWidth (1); drawLines (pContext, size, selectionSize); static const CCoord dashLength [] = {3,3}; static const CLineStyle lineStyle (CLineStyle::kLineCapButt, CLineStyle::kLineJoinMiter, 0, 2, dashLength); pContext->setLineStyle (lineStyle); pContext->setFrameColor (foreground); drawLines (pContext, size, selectionSize); } } <|fim▁hole|><|fim▁end|>
#endif // VSTGUI_LIVE_EDITING
<|file_name|>DaemonManager.java<|end_file_name|><|fim▁begin|>package com.mhfs.controller.hotplug; import java.io.File; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.net.SocketException; import com.mhfs.controller.config.Config; import com.mhfs.controller.daemon.DaemonMain; import com.mhfs.ipc.InvocationManager; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioDatagramChannel; public class DaemonManager { private static Process process; private static Channel channel; public static InvocationManager startDaemon() throws Exception { int port = findFreePort(); String javaHome = System.getProperty("java.home"); String javaBin = javaHome + File.separator + "bin" + File.separator + "java"; String classpath = System.getProperty("java.class.path"); String libPath = "-Djava.library.path=" + System.getProperty("java.library.path"); String className = DaemonMain.class.getCanonicalName(); String args = Config.INSTANCE.shouldDebugInput() ? "debugControllerInput" : ""; ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, libPath, className, String.valueOf(port), args); builder.inheritIO(); process = builder.start(); Thread.sleep(2000);//Waiting for Daemon to start. ClientNetworkHandler cnw = new ClientNetworkHandler(); InetSocketAddress adr = new InetSocketAddress("localhost", port); Bootstrap b = new Bootstrap(); b.group(new NioEventLoopGroup()); b.channel(NioDatagramChannel.class); b.handler(cnw); ChannelFuture future = b.connect(adr).syncUninterruptibly(); cnw.init(future.channel(), adr); InvocationManager manager = new InvocationManager(cnw); cnw.setInvocationManager(manager); manager.init(); Thread t = new Thread(() -> { future.channel().closeFuture().syncUninterruptibly(); b.group().shutdownGracefully(); }); t.setDaemon(true); t.setName("Netty-IPC Shutdown Waiter"); Runtime.getRuntime().addShutdownHook(new Thread(() -> stopDaemon())); return manager; } private static int findFreePort() throws SocketException { DatagramSocket socket = new DatagramSocket(); int port = socket.getLocalPort(); socket.close(); <|fim▁hole|> public static void stopDaemon() { if(process != null) { process.destroy(); } if(channel != null) { channel.close(); } } }<|fim▁end|>
return port; }
<|file_name|>vec.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! A growable list type with heap-allocated contents, written `Vec<T>` but //! pronounced 'vector.' //! //! Vectors have `O(1)` indexing, amortized `O(1)` push (to the end) and //! `O(1)` pop (from the end). //! //! # Examples //! //! You can explicitly create a `Vec<T>` with `new()`: //! //! ``` //! let v: Vec<i32> = Vec::new(); //! ``` //! //! ...or by using the `vec!` macro: //! //! ``` //! let v: Vec<i32> = vec![]; //! //! let v = vec![1, 2, 3, 4, 5]; //! //! let v = vec![0; 10]; // ten zeroes //! ``` //! //! You can `push` values onto the end of a vector (which will grow the vector as needed): //! //! ``` //! let mut v = vec![1, 2]; //! //! v.push(3); //! ``` //! //! Popping values works in much the same way: //! //! ``` //! let mut v = vec![1, 2]; //! //! let two = v.pop(); //! ``` //! //! Vectors also support indexing (through the `Index` and `IndexMut` traits): //! //! ``` //! let mut v = vec![1, 2, 3]; //! let three = v[2]; //! v[1] = v[1] + 5; //! ``` #![stable(feature = "rust1", since = "1.0.0")] use core::prelude::*; use alloc::boxed::Box; use alloc::heap::{EMPTY, allocate, reallocate, deallocate}; use core::cmp::max; use core::cmp::Ordering; use core::fmt; use core::hash::{self, Hash}; use core::intrinsics::{arith_offset, assume}; use core::iter::{repeat, FromIterator}; use core::marker::PhantomData; use core::mem; use core::ops::{Index, IndexMut, Deref}; use core::ops; use core::ptr; use core::ptr::Unique; use core::slice; use core::isize; use core::usize; use borrow::{Cow, IntoCow}; use super::range::RangeArgument; // FIXME- fix places which assume the max vector allowed has memory usize::MAX. const MAX_MEMORY_SIZE: usize = isize::MAX as usize; /// A growable list type, written `Vec<T>` but pronounced 'vector.' /// /// # Examples /// /// ``` /// let mut vec = Vec::new(); /// vec.push(1); /// vec.push(2); /// /// assert_eq!(vec.len(), 2); /// assert_eq!(vec[0], 1); /// /// assert_eq!(vec.pop(), Some(2)); /// assert_eq!(vec.len(), 1); /// /// vec[0] = 7; /// assert_eq!(vec[0], 7); /// /// vec.extend([1, 2, 3].iter().cloned()); /// /// for x in &vec { /// println!("{}", x); /// } /// assert_eq!(vec, [7, 1, 2, 3]); /// ``` /// /// The `vec!` macro is provided to make initialization more convenient: /// /// ``` /// let mut vec = vec![1, 2, 3]; /// vec.push(4); /// assert_eq!(vec, [1, 2, 3, 4]); /// ``` /// /// Use a `Vec<T>` as an efficient stack: /// /// ``` /// let mut stack = Vec::new(); /// /// stack.push(1); /// stack.push(2); /// stack.push(3); /// /// while let Some(top) = stack.pop() { /// // Prints 3, 2, 1 /// println!("{}", top); /// } /// ``` /// /// # Capacity and reallocation /// /// The capacity of a vector is the amount of space allocated for any future /// elements that will be added onto the vector. This is not to be confused with /// the *length* of a vector, which specifies the number of actual elements /// within the vector. If a vector's length exceeds its capacity, its capacity /// will automatically be increased, but its elements will have to be /// reallocated. /// /// For example, a vector with capacity 10 and length 0 would be an empty vector /// with space for 10 more elements. Pushing 10 or fewer elements onto the /// vector will not change its capacity or cause reallocation to occur. However, /// if the vector's length is increased to 11, it will have to reallocate, which /// can be slow. For this reason, it is recommended to use `Vec::with_capacity` /// whenever possible to specify how big the vector is expected to get. #[unsafe_no_drop_flag] #[stable(feature = "rust1", since = "1.0.0")] pub struct Vec<T> { ptr: Unique<T>, len: usize, cap: usize, } unsafe impl<T: Send> Send for Vec<T> { } unsafe impl<T: Sync> Sync for Vec<T> { } //////////////////////////////////////////////////////////////////////////////// // Inherent methods //////////////////////////////////////////////////////////////////////////////// impl<T> Vec<T> { /// Constructs a new, empty `Vec<T>`. /// /// The vector will not allocate until elements are pushed onto it. /// /// # Examples /// /// ``` /// let mut vec: Vec<i32> = Vec::new(); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn new() -> Vec<T> { // We want ptr to never be NULL so instead we set it to some arbitrary // non-null value which is fine since we never call deallocate on the ptr // if cap is 0. The reason for this is because the pointer of a slice // being NULL would break the null pointer optimization for enums. unsafe { Vec::from_raw_parts(EMPTY as *mut T, 0, 0) } } /// Constructs a new, empty `Vec<T>` with the specified capacity. /// /// The vector will be able to hold exactly `capacity` elements without reallocating. If /// `capacity` is 0, the vector will not allocate. /// /// It is important to note that this function does not specify the *length* of the returned /// vector, but only the *capacity*. (For an explanation of the difference between length and /// capacity, see the main `Vec<T>` docs above, 'Capacity and reallocation'.) /// /// # Examples /// /// ``` /// let mut vec = Vec::with_capacity(10); /// /// // The vector contains no items, even though it has capacity for more /// assert_eq!(vec.len(), 0); /// /// // These are all done without reallocating... /// for i in 0..10 { /// vec.push(i); /// } /// /// // ...but this may make the vector reallocate /// vec.push(11); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn with_capacity(capacity: usize) -> Vec<T> { if mem::size_of::<T>() == 0 { unsafe { Vec::from_raw_parts(EMPTY as *mut T, 0, usize::MAX) } } else if capacity == 0 { Vec::new() } else { let size = capacity.checked_mul(mem::size_of::<T>()) .expect("capacity overflow"); let ptr = unsafe { allocate(size, mem::min_align_of::<T>()) }; if ptr.is_null() { ::alloc::oom() } unsafe { Vec::from_raw_parts(ptr as *mut T, 0, capacity) } } } /// Creates a `Vec<T>` directly from the raw components of another vector. /// /// This is highly unsafe, due to the number of invariants that aren't checked. /// /// # Examples /// /// ``` /// use std::ptr; /// use std::mem; /// /// fn main() { /// let mut v = vec![1, 2, 3]; /// /// // Pull out the various important pieces of information about `v` /// let p = v.as_mut_ptr(); /// let len = v.len(); /// let cap = v.capacity(); /// /// unsafe { /// // Cast `v` into the void: no destructor run, so we are in /// // complete control of the allocation to which `p` points. /// mem::forget(v); /// /// // Overwrite memory with 4, 5, 6 /// for i in 0..len as isize { /// ptr::write(p.offset(i), 4 + i); /// } /// /// // Put everything back together into a Vec /// let rebuilt = Vec::from_raw_parts(p, len, cap); /// assert_eq!(rebuilt, [4, 5, 6]); /// } /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec<T> { Vec { ptr: Unique::new(ptr), len: length, cap: capacity, } } /// Creates a vector by copying the elements from a raw pointer. /// /// This function will copy `elts` contiguous elements starting at `ptr` /// into a new allocation owned by the returned `Vec<T>`. The elements of /// the buffer are copied into the vector without cloning, as if /// `ptr::read()` were called on them. #[inline] #[unstable(feature = "vec_from_raw_buf", reason = "may be better expressed via composition")] #[deprecated(since = "1.2.0", reason = "use slice::from_raw_parts + .to_vec() instead")] pub unsafe fn from_raw_buf(ptr: *const T, elts: usize) -> Vec<T> { let mut dst = Vec::with_capacity(elts); dst.set_len(elts); ptr::copy_nonoverlapping(ptr, dst.as_mut_ptr(), elts); dst } /// Returns the number of elements the vector can hold without /// reallocating. /// /// # Examples /// /// ``` /// let vec: Vec<i32> = Vec::with_capacity(10); /// assert_eq!(vec.capacity(), 10); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn capacity(&self) -> usize { self.cap } /// Reserves capacity for at least `additional` more elements to be inserted /// in the given `Vec<T>`. The collection may reserve more space to avoid /// frequent reallocations. /// /// # Panics /// /// Panics if the new capacity overflows `usize`. /// /// # Examples /// /// ``` /// let mut vec = vec![1]; /// vec.reserve(10); /// assert!(vec.capacity() >= 11); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn reserve(&mut self, additional: usize) { if self.cap - self.len < additional { const ERR_MSG: &'static str = "Vec::reserve: `isize` overflow"; let new_min_cap = self.len.checked_add(additional).expect(ERR_MSG); if new_min_cap > MAX_MEMORY_SIZE { panic!(ERR_MSG) } self.grow_capacity(match new_min_cap.checked_next_power_of_two() { Some(x) if x > MAX_MEMORY_SIZE => MAX_MEMORY_SIZE, None => MAX_MEMORY_SIZE, Some(x) => x, }); } } /// Reserves the minimum capacity for exactly `additional` more elements to /// be inserted in the given `Vec<T>`. Does nothing if the capacity is already /// sufficient. /// /// Note that the allocator may give the collection more space than it /// requests. Therefore capacity can not be relied upon to be precisely /// minimal. Prefer `reserve` if future insertions are expected. /// /// # Panics /// /// Panics if the new capacity overflows `usize`. /// /// # Examples /// /// ``` /// let mut vec = vec![1]; /// vec.reserve_exact(10); /// assert!(vec.capacity() >= 11); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn reserve_exact(&mut self, additional: usize) { if self.cap - self.len < additional { match self.len.checked_add(additional) { None => panic!("Vec::reserve: `usize` overflow"), Some(new_cap) => self.grow_capacity(new_cap) } } } /// Shrinks the capacity of the vector as much as possible. /// /// It will drop down as close as possible to the length but the allocator /// may still inform the vector that there is space for a few more elements. /// /// # Examples /// /// ``` /// let mut vec = Vec::with_capacity(10); /// vec.extend([1, 2, 3].iter().cloned()); /// assert_eq!(vec.capacity(), 10); /// vec.shrink_to_fit(); /// assert!(vec.capacity() >= 3); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn shrink_to_fit(&mut self) { if mem::size_of::<T>() == 0 { return } if self.len == 0 { if self.cap != 0 { unsafe { dealloc(*self.ptr, self.cap) } self.cap = 0; } } else if self.cap != self.len { unsafe { // Overflow check is unnecessary as the vector is already at // least this large. let ptr = reallocate(*self.ptr as *mut u8, self.cap * mem::size_of::<T>(), self.len * mem::size_of::<T>(), mem::min_align_of::<T>()) as *mut T; if ptr.is_null() { ::alloc::oom() } self.ptr = Unique::new(ptr); } self.cap = self.len; } } /// Converts the vector into Box<[T]>. /// /// Note that this will drop any excess capacity. Calling this and /// converting back to a vector with `into_vec()` is equivalent to calling /// `shrink_to_fit()`. #[stable(feature = "rust1", since = "1.0.0")] pub fn into_boxed_slice(mut self) -> Box<[T]> { self.shrink_to_fit(); unsafe { let xs: Box<[T]> = Box::from_raw(&mut *self); mem::forget(self); xs } } /// Shorten a vector, dropping excess elements. /// /// If `len` is greater than the vector's current length, this has no /// effect. /// /// # Examples /// /// ``` /// let mut vec = vec![1, 2, 3, 4]; /// vec.truncate(2); /// assert_eq!(vec, [1, 2]); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn truncate(&mut self, len: usize) { unsafe { // drop any extra elements while len < self.len { // decrement len before the read(), so a panic on Drop doesn't // re-drop the just-failed value. self.len -= 1; ptr::read(self.get_unchecked(self.len)); } } } /// Extracts a slice containing the entire vector. /// /// Equivalent to `&s[..]`. #[inline] #[unstable(feature = "convert", reason = "waiting on RFC revision")] pub fn as_slice(&self) -> &[T] { self } /// Extracts a mutable slice of the entire vector. /// /// Equivalent to `&mut s[..]`. #[inline] #[unstable(feature = "convert", reason = "waiting on RFC revision")] pub fn as_mut_slice(&mut self) -> &mut [T] { &mut self[..] } /// Sets the length of a vector. /// /// This will explicitly set the size of the vector, without actually /// modifying its buffers, so it is up to the caller to ensure that the /// vector is actually the specified size. /// /// # Examples /// /// ``` /// let mut v = vec![1, 2, 3, 4]; /// unsafe { /// v.set_len(1); /// } /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub unsafe fn set_len(&mut self, len: usize) { self.len = len; } /// Removes an element from anywhere in the vector and return it, replacing /// it with the last element. /// /// This does not preserve ordering, but is O(1). /// /// # Panics /// /// Panics if `index` is out of bounds. /// /// # Examples /// /// ``` /// let mut v = vec!["foo", "bar", "baz", "qux"]; /// /// assert_eq!(v.swap_remove(1), "bar"); /// assert_eq!(v, ["foo", "qux", "baz"]); /// /// assert_eq!(v.swap_remove(0), "foo"); /// assert_eq!(v, ["baz", "qux"]); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn swap_remove(&mut self, index: usize) -> T { let length = self.len(); self.swap(index, length - 1); self.pop().unwrap() } /// Inserts an element at position `index` within the vector, shifting all /// elements after position `i` one position to the right. /// /// # Panics /// /// Panics if `index` is greater than the vector's length. /// /// # Examples /// /// ``` /// let mut vec = vec![1, 2, 3]; /// vec.insert(1, 4); /// assert_eq!(vec, [1, 4, 2, 3]); /// vec.insert(4, 5); /// assert_eq!(vec, [1, 4, 2, 3, 5]); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn insert(&mut self, index: usize, element: T) { let len = self.len(); assert!(index <= len); // space for the new element self.reserve(1); unsafe { // infallible // The spot to put the new value { let p = self.as_mut_ptr().offset(index as isize); // Shift everything over to make space. (Duplicating the // `index`th element into two consecutive places.) ptr::copy(&*p, p.offset(1), len - index); // Write it in, overwriting the first copy of the `index`th // element. ptr::write(&mut *p, element); } self.set_len(len + 1); } } /// Removes and returns the element at position `index` within the vector, /// shifting all elements after position `index` one position to the left. /// /// # Panics /// /// Panics if `index` is out of bounds. /// /// # Examples /// /// ``` /// let mut v = vec![1, 2, 3]; /// assert_eq!(v.remove(1), 2); /// assert_eq!(v, [1, 3]); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn remove(&mut self, index: usize) -> T { let len = self.len(); assert!(index < len); unsafe { // infallible let ret; { // the place we are taking from. let ptr = self.as_mut_ptr().offset(index as isize); // copy it out, unsafely having a copy of the value on // the stack and in the vector at the same time. ret = ptr::read(ptr); // Shift everything down to fill in that spot. ptr::copy(&*ptr.offset(1), ptr, len - index - 1); } self.set_len(len - 1); ret } } /// Retains only the elements specified by the predicate. /// /// In other words, remove all elements `e` such that `f(&e)` returns false. /// This method operates in place and preserves the order of the retained /// elements. /// /// # Examples /// /// ``` /// let mut vec = vec![1, 2, 3, 4]; /// vec.retain(|&x| x%2 == 0); /// assert_eq!(vec, [2, 4]); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn retain<F>(&mut self, mut f: F) where F: FnMut(&T) -> bool { let len = self.len(); let mut del = 0; { let v = &mut **self; for i in 0..len { if !f(&v[i]) { del += 1; } else if del > 0 { v.swap(i-del, i); } } } if del > 0 { self.truncate(len - del); } } /// Appends an element to the back of a collection. /// /// # Panics /// /// Panics if the number of elements in the vector overflows a `usize`. /// /// # Examples /// /// ``` /// let mut vec = vec!(1, 2); /// vec.push(3); /// assert_eq!(vec, [1, 2, 3]); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn push(&mut self, value: T) { #[cold] #[inline(never)] fn resize<T>(vec: &mut Vec<T>) { let old_size = vec.cap * mem::size_of::<T>(); if old_size >= MAX_MEMORY_SIZE { panic!("capacity overflow") } let mut size = max(old_size, 2 * mem::size_of::<T>()) * 2; if old_size > size || size > MAX_MEMORY_SIZE { size = MAX_MEMORY_SIZE; } unsafe { let ptr = alloc_or_realloc(*vec.ptr, old_size, size); if ptr.is_null() { ::alloc::oom() } vec.ptr = Unique::new(ptr); } vec.cap = max(vec.cap, 2) * 2; } if mem::size_of::<T>() == 0 { // zero-size types consume no memory, so we can't rely on the // address space running out self.len = self.len.checked_add(1).expect("length overflow"); mem::forget(value); return } if self.len == self.cap { resize(self); } unsafe { let end = (*self.ptr).offset(self.len as isize); ptr::write(&mut *end, value); self.len += 1; } } /// Removes the last element from a vector and returns it, or `None` if it is empty. /// /// # Examples /// /// ``` /// let mut vec = vec![1, 2, 3]; /// assert_eq!(vec.pop(), Some(3)); /// assert_eq!(vec, [1, 2]); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn pop(&mut self) -> Option<T> { if self.len == 0 { None } else { unsafe { self.len -= 1; Some(ptr::read(self.get_unchecked(self.len()))) } } } /// Moves all the elements of `other` into `Self`, leaving `other` empty. /// /// # Panics /// /// Panics if the number of elements in the vector overflows a `usize`. /// /// # Examples /// /// ``` /// # #![feature(append)] /// let mut vec = vec![1, 2, 3]; /// let mut vec2 = vec![4, 5, 6]; /// vec.append(&mut vec2); /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]); /// assert_eq!(vec2, []); /// ``` #[inline] #[unstable(feature = "append", reason = "new API, waiting for dust to settle")] pub fn append(&mut self, other: &mut Self) { if mem::size_of::<T>() == 0 { // zero-size types consume no memory, so we can't rely on the // address space running out self.len = self.len.checked_add(other.len()).expect("length overflow"); unsafe { other.set_len(0) } return; } self.reserve(other.len()); let len = self.len(); unsafe { ptr::copy_nonoverlapping( other.as_ptr(), self.get_unchecked_mut(len), other.len()); } self.len += other.len(); unsafe { other.set_len(0); } } /// Create a draining iterator that removes the specified range in the vector /// and yields the removed items from start to end. The element range is /// removed even if the iterator is not consumed until the end. /// /// Note: It is unspecified how many elements are removed from the vector, /// if the `Drain` value is leaked. /// /// # Panics /// /// Panics if the starting point is greater than the end point or if /// the end point is greater than the length of the vector. /// /// # Examples /// /// ``` /// # #![feature(drain)] /// /// // Draining using `..` clears the whole vector. /// let mut v = vec![1, 2, 3]; /// let u: Vec<_> = v.drain(..).collect(); /// assert_eq!(v, &[]); /// assert_eq!(u, &[1, 2, 3]); /// ``` #[unstable(feature = "drain", reason = "recently added, matches RFC")] pub fn drain<R>(&mut self, range: R) -> Drain<T> where R: RangeArgument<usize> { // Memory safety // // When the Drain is first created, it shortens the length of // the source vector to make sure no uninitalized or moved-from elements // are accessible at all if the Drain's destructor never gets to run. // // Drain will ptr::read out the values to remove. // When finished, remaining tail of the vec is copied back to cover // the hole, and the vector length is restored to the new length. // let len = self.len(); let start = *range.start().unwrap_or(&0); let end = *range.end().unwrap_or(&len); assert!(start <= end); assert!(end <= len); unsafe { // set self.vec length's to start, to be safe in case Drain is leaked self.set_len(start); // Use the borrow in the IterMut to indicate borrowing behavior of the // whole Drain iterator (like &mut T). let range_slice = slice::from_raw_parts_mut( self.as_mut_ptr().offset(start as isize), end - start); Drain { tail_start: end, tail_len: len - end, iter: range_slice.iter_mut(), vec: self as *mut _, } } } /// Clears the vector, removing all values. /// /// # Examples /// /// ``` /// let mut v = vec![1, 2, 3]; /// /// v.clear(); /// /// assert!(v.is_empty()); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn clear(&mut self) { self.truncate(0) } /// Returns the number of elements in the vector. /// /// # Examples /// /// ``` /// let a = vec![1, 2, 3]; /// assert_eq!(a.len(), 3); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn len(&self) -> usize { self.len } /// Returns `true` if the vector contains no elements. /// /// # Examples /// /// ``` /// let mut v = Vec::new(); /// assert!(v.is_empty()); /// /// v.push(1); /// assert!(!v.is_empty()); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn is_empty(&self) -> bool { self.len() == 0 } /// Converts a `Vec<T>` to a `Vec<U>` where `T` and `U` have the same /// size and in case they are not zero-sized the same minimal alignment. /// /// # Panics /// /// Panics if `T` and `U` have differing sizes or are not zero-sized and /// have differing minimal alignments. /// /// # Examples /// /// ``` /// # #![feature(map_in_place)] /// let v = vec![0, 1, 2]; /// let w = v.map_in_place(|i| i + 3); /// assert_eq!(&w[..], &[3, 4, 5]); /// /// #[derive(PartialEq, Debug)] /// struct Newtype(u8); /// let bytes = vec![0x11, 0x22]; /// let newtyped_bytes = bytes.map_in_place(|x| Newtype(x)); /// assert_eq!(&newtyped_bytes[..], &[Newtype(0x11), Newtype(0x22)]); /// ``` #[unstable(feature = "map_in_place", reason = "API may change to provide stronger guarantees")] pub fn map_in_place<U, F>(self, mut f: F) -> Vec<U> where F: FnMut(T) -> U { // FIXME: Assert statically that the types `T` and `U` have the same // size. assert!(mem::size_of::<T>() == mem::size_of::<U>()); let mut vec = self; if mem::size_of::<T>() != 0 { // FIXME: Assert statically that the types `T` and `U` have the // same minimal alignment in case they are not zero-sized. // These asserts are necessary because the `min_align_of` of the // types are passed to the allocator by `Vec`. assert!(mem::min_align_of::<T>() == mem::min_align_of::<U>()); // This `as isize` cast is safe, because the size of the elements of the // vector is not 0, and: // // 1) If the size of the elements in the vector is 1, the `isize` may // overflow, but it has the correct bit pattern so that the // `.offset()` function will work. // // Example: // Address space 0x0-0xF. // `u8` array at: 0x1. // Size of `u8` array: 0x8. // Calculated `offset`: -0x8. // After `array.offset(offset)`: 0x9. // (0x1 + 0x8 = 0x1 - 0x8) // // 2) If the size of the elements in the vector is >1, the `usize` -> // `isize` conversion can't overflow. let offset = vec.len() as isize; let start = vec.as_mut_ptr(); let mut pv = PartialVecNonZeroSized { vec: vec, start_t: start, // This points inside the vector, as the vector has length // `offset`. end_t: unsafe { start.offset(offset) }, start_u: start as *mut U, end_u: start as *mut U, _marker: PhantomData, }; // start_t // start_u // | // +-+-+-+-+-+-+ // |T|T|T|...|T| // +-+-+-+-+-+-+ // | | // end_u end_t while pv.end_u as *mut T != pv.end_t { unsafe { // start_u start_t // | | // +-+-+-+-+-+-+-+-+-+ // |U|...|U|T|T|...|T| // +-+-+-+-+-+-+-+-+-+ // | | // end_u end_t let t = ptr::read(pv.start_t); // start_u start_t // | | // +-+-+-+-+-+-+-+-+-+ // |U|...|U|X|T|...|T| // +-+-+-+-+-+-+-+-+-+ // | | // end_u end_t // We must not panic here, one cell is marked as `T` // although it is not `T`. pv.start_t = pv.start_t.offset(1); // start_u start_t // | | // +-+-+-+-+-+-+-+-+-+ // |U|...|U|X|T|...|T| // +-+-+-+-+-+-+-+-+-+ // | | // end_u end_t // We may panic again. // The function given by the user might panic. let u = f(t); ptr::write(pv.end_u, u); // start_u start_t // | | // +-+-+-+-+-+-+-+-+-+ // |U|...|U|U|T|...|T| // +-+-+-+-+-+-+-+-+-+ // | | // end_u end_t // We should not panic here, because that would leak the `U` // pointed to by `end_u`. pv.end_u = pv.end_u.offset(1); // start_u start_t // | | // +-+-+-+-+-+-+-+-+-+ // |U|...|U|U|T|...|T| // +-+-+-+-+-+-+-+-+-+ // | | // end_u end_t // We may panic again. } } // start_u start_t // | | // +-+-+-+-+-+-+ // |U|...|U|U|U| // +-+-+-+-+-+-+ // | // end_t // end_u // Extract `vec` and prevent the destructor of // `PartialVecNonZeroSized` from running. Note that none of the // function calls can panic, thus no resources can be leaked (as the // `vec` member of `PartialVec` is the only one which holds // allocations -- and it is returned from this function. None of // this can panic. unsafe { let vec_len = pv.vec.len(); let vec_cap = pv.vec.capacity(); let vec_ptr = pv.vec.as_mut_ptr() as *mut U; mem::forget(pv); Vec::from_raw_parts(vec_ptr, vec_len, vec_cap) } } else { // Put the `Vec` into the `PartialVecZeroSized` structure and // prevent the destructor of the `Vec` from running. Since the // `Vec` contained zero-sized objects, it did not allocate, so we // are not leaking memory here. let mut pv = PartialVecZeroSized::<T,U> { num_t: vec.len(), num_u: 0, marker: PhantomData, }; mem::forget(vec); while pv.num_t != 0 { unsafe { // Create a `T` out of thin air and decrement `num_t`. This // must not panic between these steps, as otherwise a // destructor of `T` which doesn't exist runs. let t = mem::uninitialized(); pv.num_t -= 1; // The function given by the user might panic. let u = f(t); // Forget the `U` and increment `num_u`. This increment // cannot overflow the `usize` as we only do this for a // number of times that fits into a `usize` (and start with // `0`). Again, we should not panic between these steps. mem::forget(u); pv.num_u += 1; } } // Create a `Vec` from our `PartialVecZeroSized` and make sure the // destructor of the latter will not run. None of this can panic. let mut result = Vec::new(); unsafe { result.set_len(pv.num_u); mem::forget(pv); } result } } /// Splits the collection into two at the given index. /// /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`, /// and the returned `Self` contains elements `[at, len)`. /// /// Note that the capacity of `self` does not change. /// /// # Panics /// /// Panics if `at > len`. /// /// # Examples /// /// ``` /// # #![feature(split_off)] /// let mut vec = vec![1,2,3]; /// let vec2 = vec.split_off(1); /// assert_eq!(vec, [1]); /// assert_eq!(vec2, [2, 3]); /// ``` #[inline] #[unstable(feature = "split_off", reason = "new API, waiting for dust to settle")] pub fn split_off(&mut self, at: usize) -> Self { assert!(at <= self.len(), "`at` out of bounds"); let other_len = self.len - at; let mut other = Vec::with_capacity(other_len); // Unsafely `set_len` and copy items to `other`. unsafe { self.set_len(at); other.set_len(other_len); ptr::copy_nonoverlapping( self.as_ptr().offset(at as isize), other.as_mut_ptr(), other.len()); } other } } impl<T: Clone> Vec<T> { /// Resizes the `Vec` in-place so that `len()` is equal to `new_len`. /// /// Calls either `extend()` or `truncate()` depending on whether `new_len` /// is larger than the current value of `len()` or not. /// /// # Examples /// /// ``` /// # #![feature(vec_resize)] /// let mut vec = vec!["hello"]; /// vec.resize(3, "world"); /// assert_eq!(vec, ["hello", "world", "world"]); /// /// let mut vec = vec![1, 2, 3, 4]; /// vec.resize(2, 0); /// assert_eq!(vec, [1, 2]); /// ``` #[unstable(feature = "vec_resize", reason = "matches collection reform specification; waiting for dust to settle")] pub fn resize(&mut self, new_len: usize, value: T) { let len = self.len(); if new_len > len { self.extend(repeat(value).take(new_len - len)); } else { self.truncate(new_len); } } /// Appends all elements in a slice to the `Vec`. /// /// Iterates over the slice `other`, clones each element, and then appends /// it to this `Vec`. The `other` vector is traversed in-order. /// /// # Examples /// /// ``` /// # #![feature(vec_push_all)] /// let mut vec = vec![1]; /// vec.push_all(&[2, 3, 4]); /// assert_eq!(vec, [1, 2, 3, 4]); /// ``` #[inline] #[unstable(feature = "vec_push_all", reason = "likely to be replaced by a more optimized extend")] pub fn push_all(&mut self, other: &[T]) { self.reserve(other.len()); for i in 0..other.len() { let len = self.len(); // Unsafe code so this can be optimised to a memcpy (or something similarly // fast) when T is Copy. LLVM is easily confused, so any extra operations // during the loop can prevent this optimisation. unsafe { ptr::write( self.get_unchecked_mut(len), other.get_unchecked(i).clone()); self.set_len(len + 1); } } } } impl<T: PartialEq> Vec<T> { /// Removes consecutive repeated elements in the vector. /// /// If the vector is sorted, this removes all duplicates. /// /// # Examples /// /// ``` /// let mut vec = vec![1, 2, 2, 3, 2]; /// /// vec.dedup(); /// /// assert_eq!(vec, [1, 2, 3, 2]); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn dedup(&mut self) { unsafe { // Although we have a mutable reference to `self`, we cannot make // *arbitrary* changes. The `PartialEq` comparisons could panic, so we // must ensure that the vector is in a valid state at all time. // // The way that we handle this is by using swaps; we iterate // over all the elements, swapping as we go so that at the end // the elements we wish to keep are in the front, and those we // wish to reject are at the back. We can then truncate the // vector. This operation is still O(n). // // Example: We start in this state, where `r` represents "next // read" and `w` represents "next_write`. // // r // +---+---+---+---+---+---+ // | 0 | 1 | 1 | 2 | 3 | 3 | // +---+---+---+---+---+---+ // w // // Comparing self[r] against self[w-1], this is not a duplicate, so // we swap self[r] and self[w] (no effect as r==w) and then increment both // r and w, leaving us with: // // r // +---+---+---+---+---+---+ // | 0 | 1 | 1 | 2 | 3 | 3 | // +---+---+---+---+---+---+ // w // // Comparing self[r] against self[w-1], this value is a duplicate, // so we increment `r` but leave everything else unchanged: // // r // +---+---+---+---+---+---+ // | 0 | 1 | 1 | 2 | 3 | 3 | // +---+---+---+---+---+---+ // w // // Comparing self[r] against self[w-1], this is not a duplicate, // so swap self[r] and self[w] and advance r and w: // // r // +---+---+---+---+---+---+ // | 0 | 1 | 2 | 1 | 3 | 3 | // +---+---+---+---+---+---+ // w // // Not a duplicate, repeat: // // r // +---+---+---+---+---+---+ // | 0 | 1 | 2 | 3 | 1 | 3 | // +---+---+---+---+---+---+ // w // // Duplicate, advance r. End of vec. Truncate to w. let ln = self.len(); if ln <= 1 { return; } // Avoid bounds checks by using raw pointers. let p = self.as_mut_ptr(); let mut r: usize = 1; let mut w: usize = 1; while r < ln { let p_r = p.offset(r as isize); let p_wm1 = p.offset((w - 1) as isize); if *p_r != *p_wm1 { if r != w { let p_w = p_wm1.offset(1); mem::swap(&mut *p_r, &mut *p_w); } w += 1; } r += 1; } self.truncate(w); } } } //////////////////////////////////////////////////////////////////////////////// // Internal methods and functions //////////////////////////////////////////////////////////////////////////////// impl<T> Vec<T> { /// Reserves capacity for exactly `capacity` elements in the given vector. /// /// If the capacity for `self` is already equal to or greater than the /// requested capacity, then no action is taken. fn grow_capacity(&mut self, capacity: usize) { if mem::size_of::<T>() == 0 { return } if capacity > self.cap { let size = capacity.checked_mul(mem::size_of::<T>()) .expect("capacity overflow"); unsafe { let ptr = alloc_or_realloc(*self.ptr, self.cap * mem::size_of::<T>(), size); if ptr.is_null() { ::alloc::oom() } self.ptr = Unique::new(ptr); } self.cap = capacity; } } } // FIXME: #13996: need a way to mark the return value as `noalias` #[inline(never)] unsafe fn alloc_or_realloc<T>(ptr: *mut T, old_size: usize, size: usize) -> *mut T { if old_size == 0 { allocate(size, mem::min_align_of::<T>()) as *mut T } else { reallocate(ptr as *mut u8, old_size, size, mem::min_align_of::<T>()) as *mut T } } #[inline] unsafe fn dealloc<T>(ptr: *mut T, len: usize) { if mem::size_of::<T>() != 0 { deallocate(ptr as *mut u8, len * mem::size_of::<T>(), mem::min_align_of::<T>()) } } #[doc(hidden)] #[stable(feature = "rust1", since = "1.0.0")] pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> { unsafe { let mut v = Vec::with_capacity(n); let mut ptr = v.as_mut_ptr(); // Write all elements except the last one for i in 1..n { ptr::write(ptr, Clone::clone(&elem)); ptr = ptr.offset(1); v.set_len(i); // Increment the length in every step in case Clone::clone() panics } if n > 0 { // We can write the last element directly without cloning needlessly ptr::write(ptr, elem); v.set_len(n); } v } } //////////////////////////////////////////////////////////////////////////////// // Common trait implementations for Vec //////////////////////////////////////////////////////////////////////////////// #[stable(feature = "rust1", since = "1.0.0")] impl<T:Clone> Clone for Vec<T> { #[cfg(not(test))] fn clone(&self) -> Vec<T> { <[T]>::to_vec(&**self) } // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is // required for this method definition, is not available. Instead use the // `slice::to_vec` function which is only available with cfg(test) // NB see the slice::hack module in slice.rs for more information #[cfg(test)] fn clone(&self) -> Vec<T> { ::slice::to_vec(&**self) } fn clone_from(&mut self, other: &Vec<T>) { // drop anything in self that will not be overwritten if self.len() > other.len() { self.truncate(other.len()) } // reuse the contained values' allocations/resources. for (place, thing) in self.iter_mut().zip(other) { place.clone_from(thing) } // self.len <= other.len due to the truncate above, so the // slice here is always in-bounds. let slice = &other[self.len()..]; self.push_all(slice); } } #[stable(feature = "rust1", since = "1.0.0")] impl<T: Hash> Hash for Vec<T> { #[inline] fn hash<H: hash::Hasher>(&self, state: &mut H) { Hash::hash(&**self, state) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T> Index<usize> for Vec<T> { type Output = T; #[inline] fn index(&self, index: usize) -> &T { // NB built-in indexing via `&[T]` &(**self)[index] } } #[stable(feature = "rust1", since = "1.0.0")] impl<T> IndexMut<usize> for Vec<T> { #[inline] fn index_mut(&mut self, index: usize) -> &mut T { // NB built-in indexing via `&mut [T]` &mut (**self)[index] } } #[stable(feature = "rust1", since = "1.0.0")] impl<T> ops::Index<ops::Range<usize>> for Vec<T> { type Output = [T]; #[inline] fn index(&self, index: ops::Range<usize>) -> &[T] { Index::index(&**self, index) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T> ops::Index<ops::RangeTo<usize>> for Vec<T> { type Output = [T]; #[inline] fn index(&self, index: ops::RangeTo<usize>) -> &[T] { Index::index(&**self, index) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T> ops::Index<ops::RangeFrom<usize>> for Vec<T> { type Output = [T]; #[inline] fn index(&self, index: ops::RangeFrom<usize>) -> &[T] { Index::index(&**self, index) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T> ops::Index<ops::RangeFull> for Vec<T> { type Output = [T]; #[inline] fn index(&self, _index: ops::RangeFull) -> &[T] { self } } #[stable(feature = "rust1", since = "1.0.0")] impl<T> ops::IndexMut<ops::Range<usize>> for Vec<T> { #[inline] fn index_mut(&mut self, index: ops::Range<usize>) -> &mut [T] { IndexMut::index_mut(&mut **self, index) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T> ops::IndexMut<ops::RangeTo<usize>> for Vec<T> { #[inline] fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut [T] { IndexMut::index_mut(&mut **self, index) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T> ops::IndexMut<ops::RangeFrom<usize>> for Vec<T> { #[inline] fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut [T] { IndexMut::index_mut(&mut **self, index) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T> ops::IndexMut<ops::RangeFull> for Vec<T> { #[inline] fn index_mut(&mut self, _index: ops::RangeFull) -> &mut [T] { self } } #[stable(feature = "rust1", since = "1.0.0")] impl<T> ops::Deref for Vec<T> { type Target = [T]; fn deref(&self) -> &[T] { unsafe { let p = *self.ptr; assume(p != 0 as *mut T); slice::from_raw_parts(p, self.len) } } } #[stable(feature = "rust1", since = "1.0.0")] impl<T> ops::DerefMut for Vec<T> { fn deref_mut(&mut self) -> &mut [T] { unsafe { let ptr = *self.ptr; assume(!ptr.is_null()); slice::from_raw_parts_mut(ptr, self.len) } } } #[stable(feature = "rust1", since = "1.0.0")] impl<T> FromIterator<T> for Vec<T> { #[inline] fn from_iter<I: IntoIterator<Item=T>>(iterable: I) -> Vec<T> { // Unroll the first iteration, as the vector is going to be // expanded on this iteration in every case when the iterable is not // empty, but the loop in extend_desugared() is not going to see the // vector being full in the few subsequent loop iterations. // So we get better branch prediction and the possibility to // construct the vector with initial estimated capacity. let mut iterator = iterable.into_iter(); let mut vector = match iterator.next() { None => return Vec::new(), Some(element) => { let (lower, _) = iterator.size_hint(); let mut vector = Vec::with_capacity(lower.saturating_add(1)); unsafe { ptr::write(vector.get_unchecked_mut(0), element); vector.set_len(1); } vector } }; vector.extend_desugared(iterator); vector } } #[stable(feature = "rust1", since = "1.0.0")] impl<T> IntoIterator for Vec<T> { type Item = T; type IntoIter = IntoIter<T>; /// Creates a consuming iterator, that is, one that moves each value out of /// the vector (from start to end). The vector cannot be used after calling /// this. /// /// # Examples /// /// ``` /// let v = vec!["a".to_string(), "b".to_string()]; /// for s in v.into_iter() { /// // s has type String, not &String /// println!("{}", s); /// } /// ``` #[inline] fn into_iter(self) -> IntoIter<T> { unsafe { let ptr = *self.ptr; assume(!ptr.is_null()); let cap = self.cap; let begin = ptr as *const T; let end = if mem::size_of::<T>() == 0 { arith_offset(ptr as *const i8, self.len() as isize) as *const T } else { ptr.offset(self.len() as isize) as *const T }; mem::forget(self); IntoIter { allocation: ptr, cap: cap, ptr: begin, end: end } } } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, T> IntoIterator for &'a Vec<T> { type Item = &'a T; type IntoIter = slice::Iter<'a, T>; fn into_iter(self) -> slice::Iter<'a, T> { self.iter() } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, T> IntoIterator for &'a mut Vec<T> { type Item = &'a mut T; type IntoIter = slice::IterMut<'a, T>; fn into_iter(mut self) -> slice::IterMut<'a, T> { self.iter_mut() } } #[stable(feature = "rust1", since = "1.0.0")] impl<T> Extend<T> for Vec<T> { #[inline] fn extend<I: IntoIterator<Item=T>>(&mut self, iterable: I) { self.extend_desugared(iterable.into_iter()) } } impl<T> Vec<T> { fn extend_desugared<I: Iterator<Item=T>>(&mut self, mut iterator: I) { // This function should be the moral equivalent of: // // for item in iterator { // self.push(item); // } while let Some(element) = iterator.next() { let len = self.len(); if len == self.capacity() { let (lower, _) = iterator.size_hint(); self.reserve(lower.saturating_add(1)); } unsafe { ptr::write(self.get_unchecked_mut(len), element); // NB can't overflow since we would have had to alloc the address space self.set_len(len + 1); } } } } #[stable(feature = "extend_ref", since = "1.2.0")] impl<'a, T: 'a + Copy> Extend<&'a T> for Vec<T> { fn extend<I: IntoIterator<Item=&'a T>>(&mut self, iter: I) { self.extend(iter.into_iter().cloned()); } } __impl_slice_eq1! { Vec<A>, Vec<B> } __impl_slice_eq1! { Vec<A>, &'b [B] } __impl_slice_eq1! { Vec<A>, &'b mut [B] } __impl_slice_eq1! { Cow<'a, [A]>, &'b [B], Clone } __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B], Clone } __impl_slice_eq1! { Cow<'a, [A]>, Vec<B>, Clone } macro_rules! array_impls { ($($N: expr)+) => { $( // NOTE: some less important impls are omitted to reduce code bloat __impl_slice_eq1! { Vec<A>, [B; $N] } __impl_slice_eq1! { Vec<A>, &'b [B; $N] } // __impl_slice_eq1! { Vec<A>, &'b mut [B; $N] } // __impl_slice_eq1! { Cow<'a, [A]>, [B; $N], Clone } // __impl_slice_eq1! { Cow<'a, [A]>, &'b [B; $N], Clone } // __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B; $N], Clone } )+ } } array_impls! { 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 } #[stable(feature = "rust1", since = "1.0.0")] impl<T: PartialOrd> PartialOrd for Vec<T> { #[inline] fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> { PartialOrd::partial_cmp(&**self, &**other) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T: Eq> Eq for Vec<T> {} #[stable(feature = "rust1", since = "1.0.0")] impl<T: Ord> Ord for Vec<T> { #[inline] fn cmp(&self, other: &Vec<T>) -> Ordering { Ord::cmp(&**self, &**other) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T> Drop for Vec<T> { fn drop(&mut self) { // This is (and should always remain) a no-op if the fields are // zeroed (when moving out, because of #[unsafe_no_drop_flag]). if self.cap != 0 && self.cap != mem::POST_DROP_USIZE { unsafe { for x in self.iter() { ptr::read(x); } dealloc(*self.ptr, self.cap) } } } } #[stable(feature = "rust1", since = "1.0.0")] impl<T> Default for Vec<T> { #[stable(feature = "rust1", since = "1.0.0")] fn default() -> Vec<T> { Vec::new() } } #[stable(feature = "rust1", since = "1.0.0")] impl<T: fmt::Debug> fmt::Debug for Vec<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&**self, f) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T> AsRef<Vec<T>> for Vec<T> { fn as_ref(&self) -> &Vec<T> { self } } #[stable(feature = "rust1", since = "1.0.0")] impl<T> AsRef<[T]> for Vec<T> { fn as_ref(&self) -> &[T] { self } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, T: Clone> From<&'a [T]> for Vec<T> { #[cfg(not(test))] fn from(s: &'a [T]) -> Vec<T> { s.to_vec() } #[cfg(test)] fn from(s: &'a [T]) -> Vec<T> { ::slice::to_vec(s) } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a> From<&'a str> for Vec<u8> { fn from(s: &'a str) -> Vec<u8> { From::from(s.as_bytes()) } } //////////////////////////////////////////////////////////////////////////////// // Clone-on-write //////////////////////////////////////////////////////////////////////////////// #[stable(feature = "rust1", since = "1.0.0")] impl<'a, T> FromIterator<T> for Cow<'a, [T]> where T: Clone { fn from_iter<I: IntoIterator<Item=T>>(it: I) -> Cow<'a, [T]> { Cow::Owned(FromIterator::from_iter(it)) } } #[allow(deprecated)] impl<'a, T: 'a> IntoCow<'a, [T]> for Vec<T> where T: Clone { fn into_cow(self) -> Cow<'a, [T]> { Cow::Owned(self) } } #[allow(deprecated)] impl<'a, T> IntoCow<'a, [T]> for &'a [T] where T: Clone { fn into_cow(self) -> Cow<'a, [T]> { Cow::Borrowed(self) } } //////////////////////////////////////////////////////////////////////////////// // Iterators //////////////////////////////////////////////////////////////////////////////// /// An iterator that moves out of a vector. #[stable(feature = "rust1", since = "1.0.0")] pub struct IntoIter<T> { allocation: *mut T, // the block of memory allocated for the vector cap: usize, // the capacity of the vector ptr: *const T, end: *const T } unsafe impl<T: Send> Send for IntoIter<T> { } unsafe impl<T: Sync> Sync for IntoIter<T> { } impl<T> IntoIter<T> { #[inline] /// Drops all items that have not yet been moved and returns the empty vector. #[unstable(feature = "iter_to_vec")] pub fn into_inner(mut self) -> Vec<T> { unsafe { for _x in self.by_ref() { } let IntoIter { allocation, cap, ptr: _ptr, end: _end } = self; mem::forget(self); Vec::from_raw_parts(allocation, 0, cap) } } } #[stable(feature = "rust1", since = "1.0.0")] impl<T> Iterator for IntoIter<T> { type Item = T; #[inline] fn next(&mut self) -> Option<T> { unsafe { if self.ptr == self.end { None } else { if mem::size_of::<T>() == 0 { // purposefully don't use 'ptr.offset' because for // vectors with 0-size elements this would return the // same pointer. self.ptr = arith_offset(self.ptr as *const i8, 1) as *const T; // Use a non-null pointer value Some(ptr::read(EMPTY as *mut T)) } else { let old = self.ptr; self.ptr = self.ptr.offset(1); Some(ptr::read(old)) } } } } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { let diff = (self.end as usize) - (self.ptr as usize); let size = mem::size_of::<T>(); let exact = diff / (if size == 0 {1} else {size}); (exact, Some(exact)) } #[inline] fn count(self) -> usize { self.size_hint().0 } } #[stable(feature = "rust1", since = "1.0.0")] impl<T> DoubleEndedIterator for IntoIter<T> { #[inline] fn next_back(&mut self) -> Option<T> { unsafe { if self.end == self.ptr { None } else { if mem::size_of::<T>() == 0 {<|fim▁hole|> // Use a non-null pointer value Some(ptr::read(EMPTY as *mut T)) } else { self.end = self.end.offset(-1); Some(ptr::read(mem::transmute(self.end))) } } } } } #[stable(feature = "rust1", since = "1.0.0")] impl<T> ExactSizeIterator for IntoIter<T> {} #[stable(feature = "rust1", since = "1.0.0")] impl<T> Drop for IntoIter<T> { fn drop(&mut self) { // destroy the remaining elements if self.cap != 0 { for _x in self.by_ref() {} unsafe { dealloc(self.allocation, self.cap); } } } } /// A draining iterator for `Vec<T>`. #[unstable(feature = "drain", reason = "recently added")] pub struct Drain<'a, T: 'a> { /// Index of tail to preserve tail_start: usize, /// Length of tail tail_len: usize, /// Current remaining range to remove iter: slice::IterMut<'a, T>, vec: *mut Vec<T>, } unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {} unsafe impl<'a, T: Send> Send for Drain<'a, T> {} #[stable(feature = "rust1", since = "1.0.0")] impl<'a, T> Iterator for Drain<'a, T> { type Item = T; #[inline] fn next(&mut self) -> Option<T> { self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) } ) } fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, T> DoubleEndedIterator for Drain<'a, T> { #[inline] fn next_back(&mut self) -> Option<T> { self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) } ) } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, T> Drop for Drain<'a, T> { fn drop(&mut self) { // exhaust self first while let Some(_) = self.next() { } if self.tail_len > 0 { unsafe { let source_vec = &mut *self.vec; // memmove back untouched tail, update to new length let start = source_vec.len(); let tail = self.tail_start; let src = source_vec.as_ptr().offset(tail as isize); let dst = source_vec.as_mut_ptr().offset(start as isize); ptr::copy(src, dst, self.tail_len); source_vec.set_len(start + self.tail_len); } } } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, T> ExactSizeIterator for Drain<'a, T> {} //////////////////////////////////////////////////////////////////////////////// // Conversion from &[T] to &Vec<T> //////////////////////////////////////////////////////////////////////////////// /// Wrapper type providing a `&Vec<T>` reference via `Deref`. #[unstable(feature = "collections")] #[deprecated(since = "1.2.0", reason = "replaced with deref coercions or Borrow")] pub struct DerefVec<'a, T:'a> { x: Vec<T>, l: PhantomData<&'a T>, } #[unstable(feature = "collections")] #[deprecated(since = "1.2.0", reason = "replaced with deref coercions or Borrow")] #[allow(deprecated)] impl<'a, T> Deref for DerefVec<'a, T> { type Target = Vec<T>; fn deref<'b>(&'b self) -> &'b Vec<T> { &self.x } } // Prevent the inner `Vec<T>` from attempting to deallocate memory. #[stable(feature = "rust1", since = "1.0.0")] #[deprecated(since = "1.2.0", reason = "replaced with deref coercions or Borrow")] #[allow(deprecated)] impl<'a, T> Drop for DerefVec<'a, T> { fn drop(&mut self) { self.x.len = 0; self.x.cap = 0; } } /// Converts a slice to a wrapper type providing a `&Vec<T>` reference. /// /// # Examples /// /// ``` /// # #![feature(collections)] /// use std::vec::as_vec; /// /// // Let's pretend we have a function that requires `&Vec<i32>` /// fn vec_consumer(s: &Vec<i32>) { /// assert_eq!(s, &[1, 2, 3]); /// } /// /// // Provide a `&Vec<i32>` from a `&[i32]` without allocating /// let values = [1, 2, 3]; /// vec_consumer(&as_vec(&values)); /// ``` #[unstable(feature = "collections")] #[deprecated(since = "1.2.0", reason = "replaced with deref coercions or Borrow")] #[allow(deprecated)] pub fn as_vec<'a, T>(x: &'a [T]) -> DerefVec<'a, T> { unsafe { DerefVec { x: Vec::from_raw_parts(x.as_ptr() as *mut T, x.len(), x.len()), l: PhantomData, } } } //////////////////////////////////////////////////////////////////////////////// // Partial vec, used for map_in_place //////////////////////////////////////////////////////////////////////////////// /// An owned, partially type-converted vector of elements with non-zero size. /// /// `T` and `U` must have the same, non-zero size. They must also have the same /// alignment. /// /// When the destructor of this struct runs, all `U`s from `start_u` (incl.) to /// `end_u` (excl.) and all `T`s from `start_t` (incl.) to `end_t` (excl.) are /// destructed. Additionally the underlying storage of `vec` will be freed. struct PartialVecNonZeroSized<T,U> { vec: Vec<T>, start_u: *mut U, end_u: *mut U, start_t: *mut T, end_t: *mut T, _marker: PhantomData<U>, } /// An owned, partially type-converted vector of zero-sized elements. /// /// When the destructor of this struct runs, all `num_t` `T`s and `num_u` `U`s /// are destructed. struct PartialVecZeroSized<T,U> { num_t: usize, num_u: usize, marker: PhantomData<::core::cell::Cell<(T,U)>>, } impl<T,U> Drop for PartialVecNonZeroSized<T,U> { fn drop(&mut self) { unsafe { // `vec` hasn't been modified until now. As it has a length // currently, this would run destructors of `T`s which might not be // there. So at first, set `vec`s length to `0`. This must be done // at first to remain memory-safe as the destructors of `U` or `T` // might cause unwinding where `vec`s destructor would be executed. self.vec.set_len(0); // We have instances of `U`s and `T`s in `vec`. Destruct them. while self.start_u != self.end_u { let _ = ptr::read(self.start_u); // Run a `U` destructor. self.start_u = self.start_u.offset(1); } while self.start_t != self.end_t { let _ = ptr::read(self.start_t); // Run a `T` destructor. self.start_t = self.start_t.offset(1); } // After this destructor ran, the destructor of `vec` will run, // deallocating the underlying memory. } } } impl<T,U> Drop for PartialVecZeroSized<T,U> { fn drop(&mut self) { unsafe { // Destruct the instances of `T` and `U` this struct owns. while self.num_t != 0 { let _: T = mem::uninitialized(); // Run a `T` destructor. self.num_t -= 1; } while self.num_u != 0 { let _: U = mem::uninitialized(); // Run a `U` destructor. self.num_u -= 1; } } } }<|fim▁end|>
// See above for why 'ptr.offset' isn't used self.end = arith_offset(self.end as *const i8, -1) as *const T;
<|file_name|>ToStringUtil.java<|end_file_name|><|fim▁begin|>package com.ashokgelal.samaya; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; /** Implements the <tt>toString</tt> method for some common cases. <P>This class is intended only for cases where <tt>toString</tt> is used in an informal manner (usually for logging and stack traces). It is especially suited for <tt>public</tt> classes which model domain objects. Here is an example of a return value of the {@link #getText} method : <PRE> hirondelle.web4j.model.MyUser { LoginName: Bob LoginPassword: **** EmailAddress: [email protected] StarRating: 1 FavoriteTheory: Quantum Chromodynamics SendCard: true Age: 42 DesiredSalary: 42000 BirthDate: Sat Feb 26 13:45:43 EST 2005 } </PRE> (Previous versions of this classes used indentation within the braces. That has been removed, since it displays poorly when nesting occurs.) <P>Here are two more examples, using classes taken from the JDK : <PRE> java.util.StringTokenizer { nextElement: This hasMoreElements: true countTokens: 3 nextToken: is hasMoreTokens: true } java.util.ArrayList { size: 3 toArray: [blah, blah, blah] isEmpty: false } </PRE> <|fim▁hole|> <PRE> public String toString() { return ToStringUtil.getText(this); } </PRE> <span class="highlight">However, there is a case where this typical style can fail catastrophically</span> : when two objects reference each other, and each has <tt>toString</tt> implemented as above, then the program will loop indefinitely! <P>As a remedy for this problem, the following variation is provided : <PRE> public String toString() { return ToStringUtil.getTextAvoidCyclicRefs(this, Product.class, "getId"); } </PRE> Here, the usual behavior is overridden for any method which returns a <tt>Product</tt> : instead of calling <tt>Product.toString</tt>, the return value of <tt>Product.getId()</tt> is used to textually represent the object. */ final class ToStringUtil { /** Return an informal textual description of an object. <P>It is highly recommened that the caller <em>not</em> rely on details of the returned <tt>String</tt>. See class description for examples of return values. <P><span class="highlight">WARNING</span>: If two classes have cyclic references (that is, each has a reference to the other), then infinite looping will result if <em>both</em> call this method! To avoid this problem, use <tt>getText</tt> for one of the classes, and {@link #getTextAvoidCyclicRefs} for the other class. <P>The only items which contribute to the result are the class name, and all no-argument <tt>public</tt> methods which return a value. As well, methods defined by the <tt>Object</tt> class, and factory methods which return an <tt>Object</tt> of the native class ("<tt>getInstance</tt>" methods) do not contribute. <P>Items are converted to a <tt>String</tt> simply by calling their <tt>toString method</tt>, with these exceptions : <ul> <li>{@link Util#getArrayAsString(Object)} is used for arrays <li>a method whose name contain the text <tt>"password"</tt> (not case-sensitive) have their return values hard-coded to <tt>"****"</tt>. </ul> <P>If the method name follows the pattern <tt>getXXX</tt>, then the word 'get' is removed from the presented result. @param aObject the object for which a <tt>toString</tt> result is required. */ static String getText(Object aObject) { return getTextAvoidCyclicRefs(aObject, null, null); } /** As in {@link #getText}, but, for return values which are instances of <tt>aSpecialClass</tt>, then call <tt>aMethodName</tt> instead of <tt>toString</tt>. <P> If <tt>aSpecialClass</tt> and <tt>aMethodName</tt> are <tt>null</tt>, then the behavior is exactly the same as calling {@link #getText}. */ static String getTextAvoidCyclicRefs(Object aObject, Class aSpecialClass, String aMethodName) { StringBuilder result = new StringBuilder(); addStartLine(aObject, result); Method[] methods = aObject.getClass().getDeclaredMethods(); for(Method method: methods){ if ( isContributingMethod(method, aObject.getClass()) ){ addLineForGetXXXMethod(aObject, method, result, aSpecialClass, aMethodName); } } addEndLine(result); return result.toString(); } // PRIVATE // /* Names of methods in the <tt>Object</tt> class which are ignored. */ private static final String fGET_CLASS = "getClass"; private static final String fCLONE = "clone"; private static final String fHASH_CODE = "hashCode"; private static final String fTO_STRING = "toString"; private static final String fGET = "get"; private static final Object[] fNO_ARGS = new Object[0]; private static final Class[] fNO_PARAMS = new Class[0]; /* Previous versions of this class indented the data within a block. That style breaks when one object references another. The indentation has been removed, but this variable has been retained, since others might prefer the indentation anyway. */ private static final String fINDENT = ""; private static final String fAVOID_CIRCULAR_REFERENCES = "[circular reference]"; private static final Logger fLogger = Util.getLogger(ToStringUtil.class); private static final String NEW_LINE = System.getProperty("line.separator"); private static Pattern PASSWORD_PATTERN = Pattern.compile("password", Pattern.CASE_INSENSITIVE); private static String HIDDEN_PASSWORD_VALUE = "****"; //prevent construction by the caller private ToStringUtil() { //empty } private static void addStartLine(Object aObject, StringBuilder aResult){ aResult.append( aObject.getClass().getName() ); aResult.append(" {"); aResult.append(NEW_LINE); } private static void addEndLine(StringBuilder aResult){ aResult.append("}"); aResult.append(NEW_LINE); } /** Return <tt>true</tt> only if <tt>aMethod</tt> is public, takes no args, returns a value whose class is not the native class, is not a method of <tt>Object</tt>. */ private static boolean isContributingMethod(Method aMethod, Class aNativeClass){ boolean isPublic = Modifier.isPublic( aMethod.getModifiers() ); boolean hasNoArguments = aMethod.getParameterTypes().length == 0; boolean hasReturnValue = aMethod.getReturnType() != Void.TYPE; boolean returnsNativeObject = aMethod.getReturnType() == aNativeClass; boolean isMethodOfObjectClass = aMethod.getName().equals(fCLONE) || aMethod.getName().equals(fGET_CLASS) || aMethod.getName().equals(fHASH_CODE) || aMethod.getName().equals(fTO_STRING) ; return isPublic && hasNoArguments && hasReturnValue && ! isMethodOfObjectClass && ! returnsNativeObject; } private static void addLineForGetXXXMethod( Object aObject, Method aMethod, StringBuilder aResult, Class aCircularRefClass, String aCircularRefMethodName ){ aResult.append(fINDENT); aResult.append( getMethodNameMinusGet(aMethod) ); aResult.append(": "); Object returnValue = getMethodReturnValue(aObject, aMethod); if ( returnValue != null && returnValue.getClass().isArray() ) { aResult.append( Util.getArrayAsString(returnValue) ); } else { if (aCircularRefClass == null) { aResult.append( returnValue ); } else { if (aCircularRefClass == returnValue.getClass()) { Method method = getMethodFromName(aCircularRefClass, aCircularRefMethodName); if ( isContributingMethod(method, aCircularRefClass)){ returnValue = getMethodReturnValue(returnValue, method); aResult.append( returnValue ); } else { aResult.append(fAVOID_CIRCULAR_REFERENCES); } } } } aResult.append( NEW_LINE ); } private static String getMethodNameMinusGet(Method aMethod){ String result = aMethod.getName(); if (result.startsWith(fGET) ) { result = result.substring(fGET.length()); } return result; } /** Return value is possibly-null. */ private static Object getMethodReturnValue(Object aObject, Method aMethod){ Object result = null; try { result = aMethod.invoke(aObject, fNO_ARGS); } catch (IllegalAccessException ex){ vomit(aObject, aMethod); } catch (InvocationTargetException ex){ vomit(aObject, aMethod); } result = dontShowPasswords(result, aMethod); return result; } private static Method getMethodFromName(Class aSpecialClass, String aMethodName){ Method result = null; try { result = aSpecialClass.getMethod(aMethodName, fNO_PARAMS); } catch ( NoSuchMethodException ex){ vomit(aSpecialClass, aMethodName); } return result; } private static void vomit(Object aObject, Method aMethod){ fLogger.severe( "Cannot get return value using reflection. Class: " + aObject.getClass().getName() + " Method: " + aMethod.getName() ); } private static void vomit(Class aSpecialClass, String aMethodName){ fLogger.severe( "Reflection fails to get no-arg method named: " + Util.quote(aMethodName) + " for class: " + aSpecialClass.getName() ); } private static Object dontShowPasswords(Object aReturnValue, Method aMethod){ Object result = aReturnValue; Matcher matcher = PASSWORD_PATTERN.matcher(aMethod.getName()); if ( matcher.find()) { result = HIDDEN_PASSWORD_VALUE; } return result; } /* Two informal classes with cyclic references, used for testing. */ private static final class Ping { public void setPong(Pong aPong){fPong = aPong; } public Pong getPong(){ return fPong; } public Integer getId() { return new Integer(123); } public String getUserPassword(){ return "blah"; } public String toString() { return getText(this); } private Pong fPong; } private static final class Pong { public void setPing(Ping aPing){ fPing = aPing; } public Ping getPing() { return fPing; } public String toString() { return getTextAvoidCyclicRefs(this, Ping.class, "getId"); //to see the infinite looping, use this instead : //return getText(this); } private Ping fPing; } /** Informal test harness. */ public static void main (String... args) { List<String> list = new ArrayList<String>(); list.add("blah"); list.add("blah"); list.add("blah"); System.out.println( ToStringUtil.getText(list) ); StringTokenizer parser = new StringTokenizer("This is the end."); System.out.println( ToStringUtil.getText(parser) ); Ping ping = new Ping(); Pong pong = new Pong(); ping.setPong(pong); pong.setPing(ping); System.out.println( ping ); System.out.println( pong ); } }<|fim▁end|>
There are two use cases for this class. The typical use case is :
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>from setuptools import setup, find_packages setup( name='zeit.content.gallery', version='2.9.2.dev0', author='gocept, Zeit Online', author_email='[email protected]', url='http://www.zeit.de/', description="vivi Content-Type Portraitbox", packages=find_packages('src'), package_dir={'': 'src'}, include_package_data=True, zip_safe=False, license='BSD', namespace_packages=['zeit', 'zeit.content'], install_requires=[<|fim▁hole|> 'setuptools', 'zeit.cms >= 3.0.dev0', 'zeit.connector>=2.4.0.dev0', 'zeit.imp>=0.15.0.dev0', 'zeit.content.image', 'zeit.push>=1.21.0.dev0', 'zeit.wysiwyg', 'zope.app.appsetup', 'zope.app.testing', 'zope.component', 'zope.formlib', 'zope.interface', 'zope.publisher', 'zope.security', 'zope.testing', ], entry_points={ 'fanstatic.libraries': [ 'zeit_content_gallery=zeit.content.gallery.browser.resources:lib', ], }, )<|fim▁end|>
'cssselect', 'Pillow', 'gocept.form',
<|file_name|>account.rs<|end_file_name|><|fim▁begin|>// droplet_limit number The total number of droplets the user may have // email string The email the user has registered for Digital // Ocean with // uuid string The universal identifier for this user // email_verified boolean If true, the user has verified their account // via email. False otherwise. use std::fmt; use std::borrow::Cow; use response::NamedResponse; use response::NotArray; #[derive(Deserialize, Debug)] pub struct Account { /// droplet_limit is a "number" in json, which could be a float, even thought that's not a /// reasonable value for a droplet limit, neither is a negative number pub droplet_limit: f64, pub email: String, pub uuid: String, pub email_verified: bool, } impl NotArray for Account {} impl fmt::Display for Account { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Email: {}\n\ Droplet Limit: {:.0}\n\ UUID: {}\n\ E-Mail Verified: {}", self.email, self.droplet_limit, self.uuid, self.email_verified) } } impl NamedResponse for Account { fn name<'a>() -> Cow<'a, str> { "account".into() }<|fim▁hole|>// TODO: Implement response headers: // content-type: application/json; charset=utf-8 // status: 200 OK // ratelimit-limit: 1200 // ratelimit-remaining: 1137 // ratelimit-reset: 1415984218<|fim▁end|>
}
<|file_name|>InputFactory.hpp<|end_file_name|><|fim▁begin|>// InputFactory.hpp // KlayGE ÊäÈëÒýÇæ³éÏ󹤳§ Í·Îļþ // Ver 3.1.0 // °æÈ¨ËùÓÐ(C) ¹¨ÃôÃô, 2003-2005 // Homepage: http://www.klayge.org // // 3.1.0 // Ôö¼ÓÁËNullObject (2005.10.29) // // 2.0.0 // ³õ´Î½¨Á¢ (2003.8.30) // // Ð޸ļǼ ///////////////////////////////////////////////////////////////////////////////// #ifndef _INPUTFACTORY_HPP #define _INPUTFACTORY_HPP #pragma once #include <KlayGE/PreDeclare.hpp> #include <string> #include <boost/noncopyable.hpp> namespace KlayGE { class KLAYGE_CORE_API InputFactory { public: virtual ~InputFactory() { } static InputFactoryPtr NullObject(); virtual std::wstring const & Name() const = 0; InputEngine& InputEngineInstance(); void Suspend(); void Resume(); private: virtual InputEnginePtr DoMakeInputEngine() = 0; virtual void DoSuspend() = 0; virtual void DoResume() = 0; protected: InputEnginePtr ie_; }; template <typename InputEngineType> class ConcreteInputFactory : boost::noncopyable, public InputFactory { public: ConcreteInputFactory(std::wstring const & name) : name_(name) { } std::wstring const & Name() const { return name_; } private: InputEnginePtr DoMakeInputEngine() { return MakeSharedPtr<InputEngineType>(); } virtual void DoSuspend() KLAYGE_OVERRIDE { } virtual void DoResume() KLAYGE_OVERRIDE { } <|fim▁hole|> private: std::wstring const name_; }; } #endif // _INPUTFACTORY_HPP<|fim▁end|>
<|file_name|>portal.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.account.controllers.portal import PortalAccount from odoo.http import request class PortalAccount(PortalAccount):<|fim▁hole|> def _invoice_get_page_view_values(self, invoice, access_token, **kwargs): values = super(PortalAccount, self)._invoice_get_page_view_values(invoice, access_token, **kwargs) payment_inputs = request.env['payment.acquirer']._get_available_payment_input(partner=invoice.partner_id, company=invoice.company_id) # if not connected (using public user), the method _get_available_payment_input will return public user tokens is_public_user = request.env.user._is_public() if is_public_user: # we should not display payment tokens owned by the public user payment_inputs.pop('pms', None) token_count = request.env['payment.token'].sudo().search_count([('acquirer_id.company_id', '=', invoice.company_id.id), ('partner_id', '=', invoice.partner_id.id), ]) values['existing_token'] = token_count > 0 values.update(payment_inputs) # if the current user is connected we set partner_id to his partner otherwise we set it as the invoice partner # we do this to force the creation of payment tokens to the correct partner and avoid token linked to the public user values['partner_id'] = invoice.partner_id if is_public_user else request.env.user.partner_id, return values<|fim▁end|>