code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
<?php if($IDproducto!=null){ //obtener los datos de la bd $conObtenerDatosProducto = include $_SERVER['DOCUMENT_ROOT']."/admin/crearConexion.php"; $sqlObtenerDatosProducto="SELECT * FROM productos WHERE ID='$IDproducto'"; $resultObtenerDatosProducto = mysqli_query($conObtenerDatosProducto,$sqlObtenerDatosProducto); if($resultObtenerDatosProducto===false || $resultObtenerDatosProducto->num_rows===0) { exit; } for ($z = 0; $z <$resultObtenerDatosProducto->num_rows; $z++) { $resultObtenerDatosProducto->data_seek($z); $estaFila = $resultObtenerDatosProducto->fetch_assoc(); $Producto = $estaFila["nombre"]; } mysqli_close($conObtenerDatosProducto); } ?>
puntodesarrollo/taxislibertador
admin/obtenerDatosProducto.php
PHP
apache-2.0
704
package org.mokolo.meet; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.TimeZone; import lombok.Getter; import lombok.Setter; /** * Single sample from meter * */ public class Sample { @Getter @Setter private Long timestamp; @Getter private Map<Pricing, Float> electricityTotalKWHInMap; @Getter private Map<Pricing, Float> electricityTotalKWHOutMap; @Getter Float electricityCurrentKWIn; @Getter Float electricityCurrentKWOut; @Getter Float gasTotalM3In; private static SimpleDateFormat isoDateHourGMTFormat = new SimpleDateFormat("yyyy-MM-dd:HHZ"); static { isoDateHourGMTFormat.setTimeZone(TimeZone.getTimeZone("GMT")); } public Sample() { this.electricityTotalKWHInMap = new HashMap<>(); this.electricityTotalKWHOutMap = new HashMap<>(); } public void put(String key, Float value) { if (key.equals("EIT1") || key.equals("ElAfnCum1")) this.electricityTotalKWHInMap.put(Pricing.LOW, value); else if (key.equals("EIT2") || key.equals("ElAfnCum2")) this.electricityTotalKWHInMap.put(Pricing.HIGH, value); else if (key.equals("EOT1") || key.equals("ElLevCum1")) this.electricityTotalKWHOutMap.put(Pricing.LOW, value); else if (key.equals("EOT2") || key.equals("ElLevCum2")) this.electricityTotalKWHOutMap.put(Pricing.HIGH, value); else if (key.equals("EIC") || key.equals("ElAfnCur")) this.electricityCurrentKWIn = value; else if (key.equals("EOC") || key.equals("ElLevCur")) this.electricityCurrentKWOut = value; else if (key.equals("GIT") || key.equals("GasAfnCum")) this.gasTotalM3In = value; } public Float getElectricityTotalKWHIn() { return sum(this.electricityTotalKWHInMap.values()); } public Float getElectricityTotalKWHOut() { return sum(this.electricityTotalKWHOutMap.values()); } public static Float sum(Collection<Float> values) { if (values == null || values.isEmpty()) return null; else { Float f = new Float(0.0); for (Float entry : values) f += entry; return f; } } public SampleStatistics getSampleStatistics() { return new SampleStatistics(this.timestamp, this.electricityCurrentKWIn, this.electricityCurrentKWOut); } }
fredvos/meet
src/main/java/org/mokolo/meet/Sample.java
Java
apache-2.0
2,296
/** * @license Copyright 2017 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ 'use strict'; /** * @fileoverview Ensures the contrast between foreground and background colors meets * WCAG 2 AA contrast ratio thresholds. * See base class in axe-audit.js for audit() implementation. */ const AxeAudit = require('./axe-audit'); class ColorContrast extends AxeAudit { /** * @return {LH.Audit.Meta} */ static get meta() { return { id: 'color-contrast', title: 'Background and foreground colors have a sufficient contrast ratio', failureTitle: 'Background and foreground colors do not have a ' + 'sufficient contrast ratio.', description: 'Low-contrast text is difficult or impossible for many users to read. ' + '[Learn more](https://dequeuniversity.com/rules/axe/2.2/color-contrast?application=lighthouse).', requiredArtifacts: ['Accessibility'], }; } } module.exports = ColorContrast;
mixed/lighthouse
lighthouse-core/audits/accessibility/color-contrast.js
JavaScript
apache-2.0
1,473
/* * Copyright 2013 Monoscape * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * History: * 2011/11/10 Imesh Gunaratne <imesh@monoscape.org> Created. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Monoscape.Common.Sockets.FileServer; using System.Net; namespace Monoscape.NodeController.Sockets { /// <summary> /// Node Controller file receive socket. /// File should be sent using NcFileTransferSocket. /// </summary> internal class NcApFileReceiveSocket : AbstractFileReceiveSocket { protected override string SocketName { get { return "NcApFileReceiveSocket"; } } public NcApFileReceiveSocket(string fileStorePath, IPAddress ipAddress, int port) : base(fileStorePath, ipAddress, port) { } } }
monoscape/monoscape
Monoscape.NodeController/Sockets/NcApFileReceiveSocket.cs
C#
apache-2.0
1,416
/* * Progress.java file written and maintained by Calin Cocan * Created on: Oct 16, 2015 * * This work is free: you can redistribute it and/or modify it under the terms of Apache License Version 2.0 * * 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 License for more details. * You should have received a copy of the License along with this program. If not, see <http://choosealicense.com/licenses/apache-2.0/>. ********************************************************************************************************************* */ package org.cgc.wfx; public interface Progress { boolean notifyProgress(int progressVal); }
calinrc/hdfs_wfx
java/wfx_launcher/src/main/java/org/cgc/wfx/Progress.java
Java
apache-2.0
790
/* * Copyright (C) 2013 salesforce.com, 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. */ ({ testVerifyIfTestLoaded : { test:function(cmp){ var children = (cmp.getElements()[0]).childNodes; $A.test.assertEquals(4, children.length); $A.test.assertEquals("It is not true.It is literally not false.", $A.test.getText(children[0])); $A.test.assertEquals("It wishes it was true.It is not true.", $A.test.getText(children[1])); $A.test.assertEquals("It wishes it was true.It is not true.", $A.test.getText(children[2])); $A.test.assertEquals("It is not true.It is literally not false.", $A.test.getText(children[3])); } } })
lhong375/aura
aura-impl/src/test/components/iterationTest/iterationWJSProviderOnlyList/iterationWJSProviderOnlyListTest.js
JavaScript
apache-2.0
1,218
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.baksoy.sunshine.data; import android.annotation.TargetApi; import android.content.ContentProvider; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; public class WeatherProvider extends ContentProvider { // The URI Matcher used by this content provider. private static final UriMatcher sUriMatcher = buildUriMatcher(); private WeatherDbHelper mOpenHelper; static final int WEATHER = 100; static final int WEATHER_WITH_LOCATION = 101; static final int WEATHER_WITH_LOCATION_AND_DATE = 102; static final int LOCATION = 300; private static final SQLiteQueryBuilder sWeatherByLocationSettingQueryBuilder; static{ sWeatherByLocationSettingQueryBuilder = new SQLiteQueryBuilder(); //This is an inner join which looks like //weather INNER JOIN location ON weather.location_id = location._id sWeatherByLocationSettingQueryBuilder.setTables( WeatherContract.WeatherEntry.TABLE_NAME + " INNER JOIN " + WeatherContract.LocationEntry.TABLE_NAME + " ON " + WeatherContract.WeatherEntry.TABLE_NAME + "." + WeatherContract.WeatherEntry.COLUMN_LOC_KEY + " = " + WeatherContract.LocationEntry.TABLE_NAME + "." + WeatherContract.LocationEntry._ID); } //location.location_setting = ? private static final String sLocationSettingSelection = WeatherContract.LocationEntry.TABLE_NAME+ "." + WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ? "; //location.location_setting = ? AND date >= ? private static final String sLocationSettingWithStartDateSelection = WeatherContract.LocationEntry.TABLE_NAME+ "." + WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ? AND " + WeatherContract.WeatherEntry.COLUMN_DATE + " >= ? "; //location.location_setting = ? AND date = ? private static final String sLocationSettingAndDaySelection = WeatherContract.LocationEntry.TABLE_NAME + "." + WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ? AND " + WeatherContract.WeatherEntry.COLUMN_DATE + " = ? "; private Cursor getWeatherByLocationSetting(Uri uri, String[] projection, String sortOrder) { String locationSetting = WeatherContract.WeatherEntry.getLocationSettingFromUri(uri); long startDate = WeatherContract.WeatherEntry.getStartDateFromUri(uri); String[] selectionArgs; String selection; if (startDate == 0) { selection = sLocationSettingSelection; selectionArgs = new String[]{locationSetting}; } else { selectionArgs = new String[]{locationSetting, Long.toString(startDate)}; selection = sLocationSettingWithStartDateSelection; } return sWeatherByLocationSettingQueryBuilder.query(mOpenHelper.getReadableDatabase(), projection, selection, selectionArgs, null, null, sortOrder ); } private Cursor getWeatherByLocationSettingAndDate( Uri uri, String[] projection, String sortOrder) { String locationSetting = WeatherContract.WeatherEntry.getLocationSettingFromUri(uri); long date = WeatherContract.WeatherEntry.getDateFromUri(uri); return sWeatherByLocationSettingQueryBuilder.query(mOpenHelper.getReadableDatabase(), projection, sLocationSettingAndDaySelection, new String[]{locationSetting, Long.toString(date)}, null, null, sortOrder ); } /* Students: Here is where you need to create the UriMatcher. This UriMatcher will match each URI to the WEATHER, WEATHER_WITH_LOCATION, WEATHER_WITH_LOCATION_AND_DATE, and LOCATION integer constants defined above. You can test this by uncommenting the testUriMatcher test within TestUriMatcher. */ static UriMatcher buildUriMatcher() { // I know what you're thinking. Why create a UriMatcher when you can use regular // expressions instead? Because you're not crazy, that's why. // All paths added to the UriMatcher have a corresponding code to return when a match is // found. The code passed into the constructor represents the code to return for the root // URI. It's common to use NO_MATCH as the code for this case. final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH); final String authority = WeatherContract.CONTENT_AUTHORITY; // For each type of URI you want to add, create a corresponding code. matcher.addURI(authority, WeatherContract.PATH_WEATHER, WEATHER); matcher.addURI(authority, WeatherContract.PATH_WEATHER + "/*", WEATHER_WITH_LOCATION); matcher.addURI(authority, WeatherContract.PATH_WEATHER + "/*/#", WEATHER_WITH_LOCATION_AND_DATE); matcher.addURI(authority, WeatherContract.PATH_LOCATION, LOCATION); return matcher; } /* Students: We've coded this for you. We just create a new WeatherDbHelper for later use here. */ @Override public boolean onCreate() { mOpenHelper = new WeatherDbHelper(getContext()); return true; } /* Students: Here's where you'll code the getType function that uses the UriMatcher. You can test this by uncommenting testGetType in TestProvider. */ @Override public String getType(Uri uri) { // Use the Uri Matcher to determine what kind of URI this is. final int match = sUriMatcher.match(uri); switch (match) { // Student: Uncomment and fill out these two cases case WEATHER_WITH_LOCATION_AND_DATE: return WeatherContract.WeatherEntry.CONTENT_ITEM_TYPE; case WEATHER_WITH_LOCATION: return WeatherContract.WeatherEntry.CONTENT_TYPE; case WEATHER: return WeatherContract.WeatherEntry.CONTENT_TYPE; case LOCATION: return WeatherContract.LocationEntry.CONTENT_TYPE; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { // Here's the switch statement that, given a URI, will determine what kind of request it is, // and query the database accordingly. Cursor retCursor; switch (sUriMatcher.match(uri)) { // "weather/*/*" case WEATHER_WITH_LOCATION_AND_DATE: { retCursor = getWeatherByLocationSettingAndDate(uri, projection, sortOrder); break; } // "weather/*" case WEATHER_WITH_LOCATION: { retCursor = getWeatherByLocationSetting(uri, projection, sortOrder); break; } // "weather" case WEATHER: { retCursor = mOpenHelper.getReadableDatabase().query( WeatherContract.WeatherEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder ); break; } // "location" case LOCATION: { retCursor = mOpenHelper.getReadableDatabase().query( WeatherContract.LocationEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder ); break; } default: throw new UnsupportedOperationException("Unknown uri: " + uri); } retCursor.setNotificationUri(getContext().getContentResolver(), uri); return retCursor; } /* Student: Add the ability to insert Locations to the implementation of this function. */ @Override public Uri insert(Uri uri, ContentValues values) { final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final int match = sUriMatcher.match(uri); Uri returnUri; switch (match) { case WEATHER: { normalizeDate(values); long _id = db.insert(WeatherContract.WeatherEntry.TABLE_NAME, null, values); if ( _id > 0 ) returnUri = WeatherContract.WeatherEntry.buildWeatherUri(_id); else throw new android.database.SQLException("Failed to insert row into " + uri); break; } case LOCATION: { long _id = db.insert(WeatherContract.LocationEntry.TABLE_NAME, null, values); if ( _id > 0 ) returnUri = WeatherContract.LocationEntry.buildLocationUri(_id); else throw new android.database.SQLException("Failed to insert row into " + uri); break; } default: throw new UnsupportedOperationException("Unknown uri: " + uri); } getContext().getContentResolver().notifyChange(uri, null); return returnUri; } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final int match = sUriMatcher.match(uri); int rowsDeleted; // this makes delete all rows return the number of rows deleted if ( null == selection ) selection = "1"; switch (match) { case WEATHER: rowsDeleted = db.delete( WeatherContract.WeatherEntry.TABLE_NAME, selection, selectionArgs); break; case LOCATION: rowsDeleted = db.delete( WeatherContract.LocationEntry.TABLE_NAME, selection, selectionArgs); break; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } // Because a null deletes all rows if (rowsDeleted != 0) { getContext().getContentResolver().notifyChange(uri, null); } return rowsDeleted; } private void normalizeDate(ContentValues values) { // normalize the date value if (values.containsKey(WeatherContract.WeatherEntry.COLUMN_DATE)) { long dateValue = values.getAsLong(WeatherContract.WeatherEntry.COLUMN_DATE); values.put(WeatherContract.WeatherEntry.COLUMN_DATE, WeatherContract.normalizeDate(dateValue)); } } @Override public int update( Uri uri, ContentValues values, String selection, String[] selectionArgs) { final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final int match = sUriMatcher.match(uri); int rowsUpdated; switch (match) { case WEATHER: normalizeDate(values); rowsUpdated = db.update(WeatherContract.WeatherEntry.TABLE_NAME, values, selection, selectionArgs); break; case LOCATION: rowsUpdated = db.update(WeatherContract.LocationEntry.TABLE_NAME, values, selection, selectionArgs); break; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } if (rowsUpdated != 0) { getContext().getContentResolver().notifyChange(uri, null); } return rowsUpdated; } @Override public int bulkInsert(Uri uri, ContentValues[] values) { final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final int match = sUriMatcher.match(uri); switch (match) { case WEATHER: db.beginTransaction(); int returnCount = 0; try { for (ContentValues value : values) { normalizeDate(value); long _id = db.insert(WeatherContract.WeatherEntry.TABLE_NAME, null, value); if (_id != -1) { returnCount++; } } db.setTransactionSuccessful(); } finally { db.endTransaction(); } getContext().getContentResolver().notifyChange(uri, null); return returnCount; default: return super.bulkInsert(uri, values); } } // You do not need to call this method. This is a method specifically to assist the testing // framework in running smoothly. You can read more at: // http://developer.android.com/reference/android/content/ContentProvider.html#shutdown() @Override @TargetApi(11) public void shutdown() { mOpenHelper.close(); super.shutdown(); } }
baksoy/Sunshine2
app/src/main/java/com/baksoy/sunshine/data/WeatherProvider.java
Java
apache-2.0
14,334
/* * Copyright 2018 Systemic Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Sif.Framework.Model.Parameters { /// <summary> /// Message parameter conveyance type. /// </summary> public enum ConveyanceType { HttpHeader, MatrixParameter, QueryParameter, UrlPath } }
nsip/Sif3Framework-dotNet
Code/Sif3Framework/Sif.Framework/Model/Parameters/ConveyanceType.cs
C#
apache-2.0
856
package pro.taskana.rest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.IOException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; import org.springframework.hateoas.Link; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; import pro.taskana.RestHelper; import pro.taskana.TaskanaSpringBootTest; import pro.taskana.rest.resource.ClassificationResource; import pro.taskana.rest.resource.ClassificationSummaryListResource; import pro.taskana.rest.resource.ClassificationSummaryResource; /** * Test ClassificationController. * * @author bbr */ @TaskanaSpringBootTest class ClassificationControllerIntTest { static RestTemplate template = RestHelper.getRestTemplate(); @Autowired RestHelper restHelper; @Test void testGetAllClassifications() { ResponseEntity<ClassificationSummaryListResource> response = template.exchange( restHelper.toUrl(Mapping.URL_CLASSIFICATIONS), HttpMethod.GET, restHelper.defaultRequest(), ParameterizedTypeReference.forType(ClassificationSummaryListResource.class)); assertNotNull(response.getBody().getLink(Link.REL_SELF)); } @Test void testGetAllClassificationsFilterByCustomAttribute() { ResponseEntity<ClassificationSummaryListResource> response = template.exchange( restHelper.toUrl(Mapping.URL_CLASSIFICATIONS) + "?domain=DOMAIN_A&custom-1-like=RVNR", HttpMethod.GET, restHelper.defaultRequest(), ParameterizedTypeReference.forType(ClassificationSummaryListResource.class)); assertNotNull(response.getBody().getLink(Link.REL_SELF)); assertEquals(13, response.getBody().getContent().size()); } @Test void testGetAllClassificationsKeepingFilters() { ResponseEntity<ClassificationSummaryListResource> response = template.exchange( restHelper.toUrl(Mapping.URL_CLASSIFICATIONS) + "?domain=DOMAIN_A&sort-by=key&order=asc", HttpMethod.GET, restHelper.defaultRequest(), ParameterizedTypeReference.forType(ClassificationSummaryListResource.class)); assertNotNull(response.getBody().getLink(Link.REL_SELF)); assertTrue( response .getBody() .getLink(Link.REL_SELF) .getHref() .endsWith("/api/v1/classifications?domain=DOMAIN_A&sort-by=key&order=asc")); assertEquals(17, response.getBody().getContent().size()); assertEquals("A12", response.getBody().getContent().iterator().next().key); } @Test void testGetSecondPageSortedByKey() { ResponseEntity<ClassificationSummaryListResource> response = template.exchange( restHelper.toUrl(Mapping.URL_CLASSIFICATIONS) + "?domain=DOMAIN_A&sort-by=key&order=asc&page=2&page-size=5", HttpMethod.GET, restHelper.defaultRequest(), ParameterizedTypeReference.forType(ClassificationSummaryListResource.class)); assertEquals(5, response.getBody().getContent().size()); assertEquals("L1050", response.getBody().getContent().iterator().next().key); assertNotNull(response.getBody().getLink(Link.REL_SELF)); assertTrue( response .getBody() .getLink(Link.REL_SELF) .getHref() .endsWith( "/api/v1/classifications?" + "domain=DOMAIN_A&sort-by=key&order=asc&page=2&page-size=5")); assertNotNull(response.getBody().getLink(Link.REL_FIRST)); assertNotNull(response.getBody().getLink(Link.REL_LAST)); assertNotNull(response.getBody().getLink(Link.REL_NEXT)); assertNotNull(response.getBody().getLink(Link.REL_PREVIOUS)); } @Test @DirtiesContext void testCreateClassification() { String newClassification = "{\"classificationId\":\"\",\"category\":\"MANUAL\"," + "\"domain\":\"DOMAIN_A\",\"key\":\"NEW_CLASS\"," + "\"name\":\"new classification\",\"type\":\"TASK\"}"; ResponseEntity<ClassificationResource> responseEntity = template.exchange( restHelper.toUrl(Mapping.URL_CLASSIFICATIONS), HttpMethod.POST, new HttpEntity<>(newClassification, restHelper.getHeaders()), ParameterizedTypeReference.forType(ClassificationResource.class)); assertNotNull(responseEntity); assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode()); newClassification = "{\"classificationId\":\"\",\"category\":\"MANUAL\"," + "\"domain\":\"DOMAIN_A\",\"key\":\"NEW_CLASS_2\"," + "\"name\":\"new classification\",\"type\":\"TASK\"}"; responseEntity = template.exchange( restHelper.toUrl(Mapping.URL_CLASSIFICATIONS), HttpMethod.POST, new HttpEntity<>(newClassification, restHelper.getHeaders()), ParameterizedTypeReference.forType(ClassificationResource.class)); assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode()); } @Test @DirtiesContext void testCreateClassificationWithParentId() { String newClassification = "{\"classificationId\":\"\",\"category\":\"MANUAL\"," + "\"domain\":\"DOMAIN_B\",\"key\":\"NEW_CLASS_P1\"," + "\"name\":\"new classification\",\"type\":\"TASK\"," + "\"parentId\":\"CLI:200000000000000000000000000000000015\"}"; ResponseEntity<ClassificationResource> responseEntity = template.exchange( restHelper.toUrl(Mapping.URL_CLASSIFICATIONS), HttpMethod.POST, new HttpEntity<>(newClassification, restHelper.getHeaders()), ParameterizedTypeReference.forType(ClassificationResource.class)); assertNotNull(responseEntity); assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode()); } @Test @DirtiesContext @SuppressWarnings("checkstyle:LineLength") void testCreateClassificationWithParentKey() { String newClassification = "{\"classificationId\":\"\",\"category\":\"MANUAL\",\"domain\":\"DOMAIN_B\"," + "\"key\":\"NEW_CLASS_P2\",\"name\":\"new classification\"," + "\"type\":\"TASK\",\"parentKey\":\"T2100\"}"; ResponseEntity<ClassificationResource> responseEntity = template.exchange( restHelper.toUrl(Mapping.URL_CLASSIFICATIONS), HttpMethod.POST, new HttpEntity<>(newClassification, restHelper.getHeaders()), ParameterizedTypeReference.forType(ClassificationResource.class)); assertNotNull(responseEntity); assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode()); } @Test @DirtiesContext void testCreateClassificationWithParentKeyInDomain_aShouldCreateAClassificationInRootDomain() throws IOException { String newClassification = "{\"classificationId\":\"\",\"category\":\"MANUAL\",\"domain\":\"DOMAIN_A\"," + "\"key\":\"NEW_CLASS_P2\",\"name\":\"new classification\"," + "\"type\":\"TASK\",\"parentKey\":\"T2100\"}"; ResponseEntity<ClassificationResource> responseEntity = template.exchange( restHelper.toUrl(Mapping.URL_CLASSIFICATIONS), HttpMethod.POST, new HttpEntity<>(newClassification, restHelper.getHeaders()), ParameterizedTypeReference.forType(ClassificationResource.class)); assertNotNull(responseEntity); assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode()); ResponseEntity<ClassificationSummaryListResource> response = template.exchange( restHelper.toUrl(Mapping.URL_CLASSIFICATIONS), HttpMethod.GET, restHelper.defaultRequest(), ParameterizedTypeReference.forType(ClassificationSummaryListResource.class)); assertNotNull(response.getBody().getLink(Link.REL_SELF)); boolean foundClassificationCreated = false; for (ClassificationSummaryResource classification : response.getBody().getContent()) { if ("NEW_CLASS_P2".equals(classification.getKey()) && "".equals(classification.getDomain()) && "T2100".equals(classification.getParentKey())) { foundClassificationCreated = true; } } assertEquals(true, foundClassificationCreated); } @Test @DirtiesContext void testReturn400IfCreateClassificationWithIncompatibleParentIdAndKey() throws IOException { String newClassification = "{\"classificationId\":\"\",\"category\":\"MANUAL\",\"domain\":\"DOMAIN_B\"," + "\"key\":\"NEW_CLASS_P3\",\"name\":\"new classification\"," + "\"type\":\"TASK\",\"parentId\":\"CLI:200000000000000000000000000000000015\"," + "\"parentKey\":\"T2000\"}"; HttpClientErrorException e = Assertions.assertThrows( HttpClientErrorException.class, () -> template.exchange( restHelper.toUrl(Mapping.URL_CLASSIFICATIONS), HttpMethod.POST, new HttpEntity<>(newClassification, restHelper.getHeaders()), ParameterizedTypeReference.forType(ClassificationResource.class))); assertNotNull(e); assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode()); } @Test @DirtiesContext void testCreateClassificationWithClassificationIdReturnsError400() throws IOException { String newClassification = "{\"classificationId\":\"someId\",\"category\":\"MANUAL\"," + "\"domain\":\"DOMAIN_A\",\"key\":\"NEW_CLASS\"," + "\"name\":\"new classification\",\"type\":\"TASK\"}"; HttpClientErrorException e = Assertions.assertThrows( HttpClientErrorException.class, () -> template.exchange( restHelper.toUrl(Mapping.URL_CLASSIFICATIONS), HttpMethod.POST, new HttpEntity<>(newClassification, restHelper.getHeaders()), ParameterizedTypeReference.forType(ClassificationResource.class))); assertNotNull(e); assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode()); } @Test void testGetClassificationWithSpecialCharacter() { HttpEntity<String> request = new HttpEntity<String>(restHelper.getHeadersAdmin()); ResponseEntity<ClassificationSummaryResource> response = template.exchange( restHelper.toUrl( Mapping.URL_CLASSIFICATIONS_ID, "CLI:100000000000000000000000000000000009"), HttpMethod.GET, request, ParameterizedTypeReference.forType(ClassificationSummaryResource.class)); assertEquals("Zustimmungserklärung", response.getBody().name); } @Test @DirtiesContext void testDeleteClassification() { HttpEntity<String> request = new HttpEntity<String>(restHelper.getHeaders()); ResponseEntity<ClassificationSummaryResource> response = template.exchange( restHelper.toUrl( Mapping.URL_CLASSIFICATIONS_ID, "CLI:200000000000000000000000000000000004"), HttpMethod.DELETE, request, ParameterizedTypeReference.forType(ClassificationSummaryResource.class)); assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); assertThrows( HttpClientErrorException.class, () -> { template.exchange( restHelper.toUrl( Mapping.URL_CLASSIFICATIONS_ID, "CLI:200000000000000000000000000000000004"), HttpMethod.GET, request, ParameterizedTypeReference.forType(ClassificationSummaryResource.class)); }); } }
BVier/Taskana
rest/taskana-rest-spring/src/test/java/pro/taskana/rest/ClassificationControllerIntTest.java
Java
apache-2.0
12,241
// Copyright 2007-2017 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.AzureServiceBusTransport.Contexts { using Context; using Topology; public interface ServiceBusReceiveEndpointContext : ReceiveEndpointContext { BrokerTopology BrokerTopology { get; } } }
SanSYS/MassTransit
src/MassTransit.AzureServiceBusTransport/Contexts/ServiceBusReceiveEndpointContext.cs
C#
apache-2.0
888
package net.happybrackets.develop; import net.beadsproject.beads.data.Sample; import net.beadsproject.beads.data.SampleManager; import net.beadsproject.beads.ugens.*; import net.happybrackets.core.HBAction; import net.happybrackets.device.HB; import net.happybrackets.device.sensors.*; import net.happybrackets.device.sensors.sensor_types.AccelerometerSensor; import net.happybrackets.device.sensors.sensor_types.GyroscopeSensor; import java.lang.invoke.MethodHandles; import java.util.LinkedList; public class CassetteTapeMachine implements HBAction { // final static int FFSPEED = 8; final static float FFSPEED = 0.08f; final static float FFATTEN = 0.5f; enum State { PLAY, STOP, FREE, REV, FF, RW; } long timeOfLastStopToPlay = 0, timeOfLastPlayToStop = 0; float newLoopStart = 0; State currentState = State.STOP, previousState = State.STOP; Glide rateEnv, rateMod, gainEnv, loopStart, loopEnd; SamplePlayer sp; LinkedList<double[]> sensorHistory; int count = 0; @Override public void action(HB hb) { hb.reset(); //audio stuff gainEnv = new Glide(hb.ac, 1f, 500); Gain g = new Gain(hb.ac, 1, gainEnv); rateEnv = new Glide(hb.ac, 0, 200); rateMod = new Glide(hb.ac, 0, 200); Function rate = new Function(rateEnv, rateMod) { @Override public float calculate() { return x[0] + x[1]; } }; SampleManager.setVerbose(true); String sample_name = "data/audio/Nylon_Guitar/Clean_A_harm.wav"; //sample_name = "data/audio/hiphop.wav"; Sample sample = SampleManager.sample(sample_name); System.out.println("Is sample loaded or null? " + sample_name); if (sample == null) { hb.setStatus("Unable to load sample " ); } else { sp = new SamplePlayer(hb.ac, sample); sp.setRate(rate); sp.setLoopType(SamplePlayer.LoopType.LOOP_FORWARDS); loopStart = new Glide(hb.ac, 0, 500); loopEnd = new Glide(hb.ac, (float) sp.getSample().getLength(), 500); sp.setLoopStart(loopStart); sp.setLoopEnd(loopEnd); g.addInput(sp); BiquadFilter bf = new BiquadFilter(hb.ac, 1, BiquadFilter.HP); bf.setFrequency(100); bf.addInput(g); hb.sound(bf); //sensor averaging sensorHistory = new LinkedList<double[]>(); for (int i = 0; i < 10; i++) { sensorHistory.add(new double[]{0, 0, 0}); } } //set up sensor // AccelerometerListener sensor = (MiniMU)hb.getSensor(MiniMU.class); Accelerometer accel_sensor = (Accelerometer)hb.getSensor(Accelerometer.class); if (accel_sensor != null) { accel_sensor.addListener(new SensorUpdateListener() { @Override public void sensorUpdated() { count++; //state stuff, with averaging double[] accel = accel_sensor.getAccelerometerData(); sensorHistory.removeFirst(); sensorHistory.add(accel); double xsmooth = 0, ysmooth = 0, zsmooth = 0; for (double[] histValue : sensorHistory) { xsmooth += histValue[0] / sensorHistory.size(); ysmooth += histValue[1] / sensorHistory.size(); zsmooth += histValue[2] / sensorHistory.size(); } if (count % 1 == 0) { // System.out.println(xsmooth + " " + ysmooth + " " + zsmooth); } if ((Math.abs(xsmooth) > Math.abs(ysmooth)) && (Math.abs(xsmooth) > Math.abs(zsmooth))) { if (xsmooth > 0) currentState = State.FF; else currentState = State.RW; } else if (Math.abs(ysmooth) > Math.abs(zsmooth)) { if (ysmooth > 0) currentState = State.PLAY; else currentState = State.FREE; } else { if (zsmooth > 0) currentState = State.STOP; else currentState = State.REV; } if (currentState != previousState) { changeState(); } } }); } Gyroscope gyroscope = (Gyroscope)hb.getSensor(Gyroscope.class); if (gyroscope != null){ gyroscope.addListener(new SensorUpdateListener() { @Override public void sensorUpdated() { double[] gyr = gyroscope.getGyroscopeData(); //magnitude double mag = Math.sqrt(gyr[0] * gyr[0] + gyr[1] * gyr[1] + gyr[2] * gyr[2]); double thresh = 2; System.out.println(mag); if (mag > thresh) rateMod.setValue((float) (mag - thresh) / 2f); else rateMod.setValue(0); } }); } } public void changeState() { System.out.println("State changed to " + currentState); switch(currentState) { case RW: rateEnv.setValue(-FFSPEED); gainEnv.setValue(FFATTEN); break; case FF: rateEnv.setValue(FFSPEED); gainEnv.setValue(FFATTEN); break; case PLAY: rateEnv.setValue(1); gainEnv.setValue(1f); break; case STOP: rateEnv.setValue(0); gainEnv.setValue(1); break; case REV: rateEnv.setValue(-1); gainEnv.setValue(1f); break; } if(previousState == State.STOP && currentState == State.PLAY) { System.out.println("STOP TO PLAY TRANSITION"); if(timeOfLastPlayToStop != 0 && timeOfLastStopToPlay != 0) { float duration = timeOfLastPlayToStop - timeOfLastStopToPlay; loopStart.setValue(newLoopStart); loopEnd.setValue(newLoopStart + duration); System.out.println("Setting loop start " + newLoopStart + ", loop end " + (newLoopStart + duration)); newLoopStart = (float)sp.getPosition(); } timeOfLastStopToPlay = System.currentTimeMillis(); } else if(previousState == State.PLAY && currentState == State.STOP) { System.out.println("PLAY TO STOP TRANSITION"); timeOfLastPlayToStop = System.currentTimeMillis(); } previousState = currentState; } public static void main(String[] args) { try { HB.runDebug(MethodHandles.lookup().lookupClass()); } catch (Exception e) { e.printStackTrace(); } } }
orsjb/HappyBrackets
HappyBrackets/src/test/java/net/happybrackets/develop/CassetteTapeMachine.java
Java
apache-2.0
7,101
# File permute.py def permute1(seq): if not seq: # Shuffle any sequence: list return [seq] # Empty sequence else: res = [] for i in range(len(seq)): rest = seq[:i] + seq[i+1:] # Delete current node for x in permute1(rest): # Permute the others res.append(seq[i:i+1] + x) # Add node at front return res def permute2(seq): if not seq: # Shuffle any sequence: generator yield seq # Empty sequence else: for i in range(len(seq)): rest = seq[:i] + seq[i+1:] # Delete current node for x in permute2(rest): # Permute the others yield seq[i:i+1] + x # Add node at front
dreadrel/UWF_2014_spring_COP3990C-2507
notebooks/scripts/book_code/code/permute.py
Python
apache-2.0
865
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.harmony.security.provider.crypto; import java.math.BigInteger; import java.security.InvalidKeyException; import java.security.Key; import java.security.KeyFactorySpi; import java.security.PrivateKey; import java.security.PublicKey; import java.security.interfaces.DSAParams; import java.security.interfaces.DSAPrivateKey; import java.security.interfaces.DSAPublicKey; import java.security.spec.DSAPrivateKeySpec; import java.security.spec.DSAPublicKeySpec; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; public class DSAKeyFactoryImpl extends KeyFactorySpi { /** * This method generates a DSAPrivateKey object from the provided key * specification. * * @param keySpec * - the specification (key material) for the DSAPrivateKey. * * @return a DSAPrivateKey object * * @throws InvalidKeySpecException * if "keySpec" is neither DSAPrivateKeySpec nor * PKCS8EncodedKeySpec */ protected PrivateKey engineGeneratePrivate(KeySpec keySpec) throws InvalidKeySpecException { if (keySpec != null) { if (keySpec instanceof DSAPrivateKeySpec) { return new DSAPrivateKeyImpl((DSAPrivateKeySpec) keySpec); } if (keySpec instanceof PKCS8EncodedKeySpec) { return new DSAPrivateKeyImpl((PKCS8EncodedKeySpec) keySpec); } } throw new InvalidKeySpecException( "'keySpec' is neither DSAPrivateKeySpec nor PKCS8EncodedKeySpec"); } /** * This method generates a DSAPublicKey object from the provided key * specification. * * @param keySpec * - the specification (key material) for the DSAPublicKey. * * @return a DSAPublicKey object * * @throws InvalidKeySpecException * if "keySpec" is neither DSAPublicKeySpec nor * X509EncodedKeySpec */ protected PublicKey engineGeneratePublic(KeySpec keySpec) throws InvalidKeySpecException { if (keySpec != null) { if (keySpec instanceof DSAPublicKeySpec) { return new DSAPublicKeyImpl((DSAPublicKeySpec) keySpec); } if (keySpec instanceof X509EncodedKeySpec) { return new DSAPublicKeyImpl((X509EncodedKeySpec) keySpec); } } throw new InvalidKeySpecException( "'keySpec' is neither DSAPublicKeySpec nor X509EncodedKeySpec"); } /** * This method returns a specification for the supplied key. * * The specification will be returned in the form of an object of the type * specified by keySpec. * * @param key * - either DSAPrivateKey or DSAPublicKey * @param keySpec * - either DSAPrivateKeySpec.class or DSAPublicKeySpec.class * * @return either a DSAPrivateKeySpec or a DSAPublicKeySpec * * @throws InvalidKeySpecException * if "keySpec" is not a specification for DSAPublicKey or * DSAPrivateKey */ protected <T extends KeySpec> T engineGetKeySpec(Key key, Class<T> keySpec) throws InvalidKeySpecException { BigInteger p, q, g, x, y; if (key != null) { if (keySpec == null) { throw new NullPointerException("keySpec == null"); } if (key instanceof DSAPrivateKey) { DSAPrivateKey privateKey = (DSAPrivateKey) key; if (keySpec.equals(DSAPrivateKeySpec.class)) { x = privateKey.getX(); DSAParams params = privateKey.getParams(); p = params.getP(); q = params.getQ(); g = params.getG(); return (T) (new DSAPrivateKeySpec(x, p, q, g)); } if (keySpec.equals(PKCS8EncodedKeySpec.class)) { return (T) (new PKCS8EncodedKeySpec(key.getEncoded())); } throw new InvalidKeySpecException( "'keySpec' is neither DSAPrivateKeySpec nor PKCS8EncodedKeySpec"); } if (key instanceof DSAPublicKey) { DSAPublicKey publicKey = (DSAPublicKey) key; if (keySpec.equals(DSAPublicKeySpec.class)) { y = publicKey.getY(); DSAParams params = publicKey.getParams(); p = params.getP(); q = params.getQ(); g = params.getG(); return (T) (new DSAPublicKeySpec(y, p, q, g)); } if (keySpec.equals(X509EncodedKeySpec.class)) { return (T) (new X509EncodedKeySpec(key.getEncoded())); } throw new InvalidKeySpecException( "'keySpec' is neither DSAPublicKeySpec nor X509EncodedKeySpec"); } } throw new InvalidKeySpecException( "'key' is neither DSAPublicKey nor DSAPrivateKey"); } /** * The method generates a DSAPublicKey object from the provided key. * * @param key * - a DSAPublicKey object or DSAPrivateKey object. * * @return object of the same type as the "key" argument * * @throws InvalidKeyException * if "key" is neither DSAPublicKey nor DSAPrivateKey */ protected Key engineTranslateKey(Key key) throws InvalidKeyException { if (key != null) { if (key instanceof DSAPrivateKey) { DSAPrivateKey privateKey = (DSAPrivateKey) key; DSAParams params = privateKey.getParams(); try { return engineGeneratePrivate(new DSAPrivateKeySpec( privateKey.getX(), params.getP(), params.getQ(), params.getG())); } catch (InvalidKeySpecException e) { // Actually this exception shouldn't be thrown throw new InvalidKeyException( "ATTENTION: InvalidKeySpecException: " + e); } } if (key instanceof DSAPublicKey) { DSAPublicKey publicKey = (DSAPublicKey) key; DSAParams params = publicKey.getParams(); try { return engineGeneratePublic(new DSAPublicKeySpec( publicKey.getY(), params.getP(), params.getQ(), params.getG())); } catch (InvalidKeySpecException e) { // Actually this exception shouldn't be thrown throw new InvalidKeyException( "ATTENTION: InvalidKeySpecException: " + e); } } } throw new InvalidKeyException( "'key' is neither DSAPublicKey nor DSAPrivateKey"); } }
webos21/xi
java/jcl/src/java/org/apache/harmony/security/provider/crypto/DSAKeyFactoryImpl.java
Java
apache-2.0
6,772
package com.googlecode.blaisemath.primitive; /*- * #%L * blaise-common * -- * Copyright (C) 2014 - 2021 Elisha Peterson * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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% */ import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import java.awt.*; import java.awt.geom.AffineTransform; import java.awt.geom.Arc2D; import java.awt.geom.Area; import java.awt.geom.Ellipse2D; import java.awt.geom.GeneralPath; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.Collections; import java.util.List; import java.util.ServiceLoader; /** * Provides several custom shapes that can be used to draw points. * * @author Elisha Peterson */ public final class Markers { /** Caches markers loaded from resources file. */ private static final List<Marker> MARKER_CACHE = Lists.newArrayList(); /** Singleton for empty path. */ private static final GeneralPath EMPTY_PATH = new GeneralPath(); //region STATIC INSTANCES public static final BlankMarker BLANK = new BlankMarker(); public static final CircleMarker CIRCLE = new CircleMarker(); public static final SquareMarker SQUARE = new SquareMarker(); public static final DiamondMarker DIAMOND = new DiamondMarker(); public static final TriangleMarker TRIANGLE = new TriangleMarker(); public static final StarMarker5 STAR = new StarMarker5(); public static final StarMarker7 STAR7 = new StarMarker7(); public static final StarMarker11 STAR11 = new StarMarker11(); public static final PlusMarker PLUS = new PlusMarker(); public static final CrossMarker CROSS = new CrossMarker(); public static final TargetMarker TARGET = new TargetMarker(); public static final ArrowMarker ARROW = new ArrowMarker(); public static final GapArrowMarker GAP_ARROW = new GapArrowMarker(); public static final ThickArrowMarker THICK_ARROW = new ThickArrowMarker(); public static final ChevronMarker CHEVRON_MARKER = new ChevronMarker(); public static final TriangleMarkerForward TRIANGLE_ARROW = new TriangleMarkerForward(); public static final ArrowheadMarker ARROWHEAD = new ArrowheadMarker(); public static final TeardropMarker TEARDROP = new TeardropMarker(); public static final HappyFaceMarker HAPPYFACE = new HappyFaceMarker(); public static final HouseMarker HOUSE = new HouseMarker(); //endregion /** * Utility class */ private Markers() { } /** * Retrieve list of available shapes. * @return list of marker constants */ public static List<Marker> getAvailableMarkers() { if (MARKER_CACHE.isEmpty()) { ServiceLoader<Marker> loader = ServiceLoader.load(Marker.class); Iterables.addAll(MARKER_CACHE, loader); } return Collections.unmodifiableList(MARKER_CACHE); } /** * Blank marker. */ public static class BlankMarker implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { return EMPTY_PATH; } } /** * Circle marker. */ public static class CircleMarker implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { return new Ellipse2D.Double(p.getX() - radius, p.getY() - radius, 2 * radius, 2 * radius); } } /** * Square marker. */ public static class SquareMarker implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { return new Rectangle2D.Double( p.getX() - radius / Math.sqrt(2), p.getY() - radius / Math.sqrt(2), 2 * radius / Math.sqrt(2), 2 * radius / Math.sqrt(2)); } } /** * Diamond marker. */ public static class DiamondMarker implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { double x = p.getX(); double y = p.getY(); GeneralPath path = new GeneralPath(); path.moveTo((float) x, (float) (y - radius)); path.lineTo((float) (x - radius), (float) y); path.lineTo((float) x, (float) (y + radius)); path.lineTo((float) (x + radius), (float) y); path.closePath(); return path; } } /** * Triangle marker, pointing up. */ public static class TriangleMarker implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { double x = p.getX(); double y = p.getY(); GeneralPath path = new GeneralPath(); path.moveTo((float) x, (float) (y - radius)); path.lineTo((float) (x + radius * Math.cos(Math.PI * 1.16667)), (float) (y - radius * Math.sin(Math.PI * 1.16667))); path.lineTo((float) (x + radius * Math.cos(Math.PI * 1.83333)), (float) (y - radius * Math.sin(Math.PI * 1.83333))); path.closePath(); return path; } } /** * Five point star marker. */ public static class StarMarker5 implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { double x = p.getX(); double y = p.getY(); GeneralPath path = new GeneralPath(); path.moveTo((float) x, (float) (y - radius)); for (int i = 0; i < 5; i++) { double theta = Math.PI / 2 + 2 * Math.PI * i / 5; path.lineTo((float) (x + radius * Math.cos(theta)), (float) (y - radius * Math.sin(theta))); theta += Math.PI / 5; path.lineTo((float) (x + radius / Math.sqrt(8) * Math.cos(theta)), (float) (y - radius / Math.sqrt(8) * Math.sin(theta))); } path.closePath(); return path; } } /** * Seven point star marker. */ public static class StarMarker7 implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { double x = p.getX(); double y = p.getY(); GeneralPath path = new GeneralPath(); path.moveTo((float) x, (float) (y - radius)); for (int i = 0; i < 7; i++) { double theta = Math.PI / 2 + 2 * Math.PI * i / 7; path.lineTo((float) (x + radius * Math.cos(theta)), (float) (y - radius * Math.sin(theta))); theta += Math.PI / 7; path.lineTo((float) (x + radius / 2 * Math.cos(theta)), (float) (y - radius / 2 * Math.sin(theta))); } path.closePath(); return path; } } /** * Eleven point star marker. */ public static class StarMarker11 implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { double x = p.getX(); double y = p.getY(); GeneralPath path = new GeneralPath(); path.moveTo((float) x, (float) (y - radius)); for (int i = 0; i < 11; i++) { double theta = Math.PI / 2 + 2 * Math.PI * i / 11; path.lineTo((float) (x + radius * Math.cos(theta)), (float) (y - radius * Math.sin(theta))); theta += Math.PI / 11; path.lineTo((float) (x + radius / 1.5 * Math.cos(theta)), (float) (y - radius / 1.5 * Math.sin(theta))); } path.closePath(); return path; } } /** * Plus marker. */ public static class PlusMarker implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { double x = p.getX(); double y = p.getY(); GeneralPath path = new GeneralPath(); path.moveTo((float) x, (float) (y - radius)); path.lineTo((float) x, (float) (y + radius)); path.moveTo((float) (x - radius), (float) y); path.lineTo((float) (x + radius), (float) y); return new Area(new BasicStroke(radius/3).createStrokedShape(path)); } } /** * Cross marker. */ public static class CrossMarker implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { double x = p.getX(); double y = p.getY(); GeneralPath path = new GeneralPath(); double r2 = 0.7 * radius; path.moveTo((float) (x - r2), (float) (y - r2)); path.lineTo((float) (x + r2), (float) (y + r2)); path.moveTo((float) (x - r2), (float) (y + r2)); path.lineTo((float) (x + r2), (float) (y - r2)); return new Area(new BasicStroke(radius/3).createStrokedShape(path)); } } /** * Target marker (with circle and crosshairs). */ public static class TargetMarker implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { double x = p.getX(); double y = p.getY(); GeneralPath path = new GeneralPath(); path.moveTo((float) x, (float) (y - radius)); path.lineTo((float) x, (float) (y + radius)); path.moveTo((float) (x - radius), (float) y); path.lineTo((float) (x + radius), (float) y); path.append(new Ellipse2D.Double(x - .6 * radius, y - .6 * radius, 1.2 * radius, 1.2 * radius), false); return new Area(new BasicStroke(radius/6).createStrokedShape(path)); } } /** * Arrow marker, pointing forward. */ public static class GapArrowMarker implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { double x = p.getX(); double y = p.getY(); GeneralPath path = new GeneralPath(); path.moveTo((float) (x + .5 * radius), (float) (y - .5 * radius)); path.lineTo((float) (x + radius), (float) y); path.lineTo((float) (x + .5*radius), (float) (y + .5*radius)); path.moveTo((float) (x + .4*radius), (float) y); path.lineTo((float) (x - radius), (float) y); Shape wideShape = new Area(new BasicStroke(radius/4).createStrokedShape(path)); return AffineTransform.getRotateInstance(angle, x, y).createTransformedShape(wideShape); } } /** * Arrow marker, pointing forward. */ public static class ArrowMarker implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { double x = p.getX(); double y = p.getY(); GeneralPath path = new GeneralPath(); path.moveTo((float) (x + .5 * radius), (float) (y - .5 * radius)); path.lineTo((float) (x + radius), (float) y); path.lineTo((float) (x + .5*radius), (float) (y + .5*radius)); path.moveTo((float) (x + .8*radius), (float) y); path.lineTo((float) (x - radius), (float) y); Shape wideShape = new Area(new BasicStroke(radius/4).createStrokedShape(path)); return AffineTransform.getRotateInstance(angle, x, y).createTransformedShape(wideShape); } } /** * Thicker arrow marker, pointing forward. */ public static class ThickArrowMarker implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { double x = p.getX(); double y = p.getY(); GeneralPath path = new GeneralPath(); path.moveTo((float) (x + .5 * radius), (float) (y - .5 * radius)); path.lineTo((float) (x + radius), (float) y); path.lineTo((float) (x + .5*radius), (float) (y + .5*radius)); path.moveTo((float) (x + .6*radius), (float) y); path.lineTo((float) (x - radius), (float) y); Shape wideShape = new Area(new BasicStroke(radius/2).createStrokedShape(path)); return AffineTransform.getRotateInstance(angle, x, y).createTransformedShape(wideShape); } } /** * Chevron marker, pointing forward. */ public static class ChevronMarker implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { double x = p.getX(), y = p.getY(); GeneralPath path = new GeneralPath(); path.moveTo((float) (x + .3 * radius), (float) (y - .5 * radius)); path.lineTo((float) (x + .8 * radius), (float) y); path.lineTo((float) (x + .3 * radius), (float) (y + .5 * radius)); path.moveTo((float) (x - .7 * radius), (float) (y - .5 * radius)); path.lineTo((float) (x - .2 * radius), (float) y); path.lineTo((float) (x - .7 * radius), (float) (y + .5 * radius)); Shape wideShape = new Area(new BasicStroke(radius/4).createStrokedShape(path)); return AffineTransform.getRotateInstance(angle, x, y).createTransformedShape(wideShape); } } /** * Triangle marker, pointing forward. */ public static class TriangleMarkerForward implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { double x = p.getX(), y = p.getY(); GeneralPath path = new GeneralPath(); path.moveTo((float) (x + radius), (float) y); path.lineTo((float) (x + radius * Math.cos(Math.PI * 0.6667)), (float) (y - radius * Math.sin(Math.PI * 0.6667))); path.lineTo((float) (x + radius * Math.cos(Math.PI * 1.3333)), (float) (y - radius * Math.sin(Math.PI * 1.3333))); path.closePath(); return AffineTransform.getRotateInstance(angle, x, y).createTransformedShape(path); } } /** * Arrowhead marker, pointing forward. */ public static class ArrowheadMarker implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { double x = p.getX(), y = p.getY(); GeneralPath gp10 = new GeneralPath(); gp10.moveTo((float) (x + radius), (float) y); gp10.lineTo((float) (x - radius), (float) (y + radius)); gp10.lineTo((float) (x - .5 * radius), (float) y); gp10.lineTo((float) (x - radius), (float) (y - radius)); gp10.closePath(); return AffineTransform.getRotateInstance(angle, x, y).createTransformedShape(gp10); } } /** * Teardrop marker, pointing forward. */ public static class TeardropMarker implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { double x = p.getX(), y = p.getY(); GeneralPath gp11 = new GeneralPath(); gp11.moveTo(-.25f, -.5f); gp11.curveTo(-1f, -.5f, -1f, .5f, -.25f, .5f); gp11.curveTo(.5f, .5f, .5f, 0, 1f, 0); gp11.curveTo(.5f, 0, .5f, -.5f, -.2f, -.5f); gp11.closePath(); gp11.transform(new AffineTransform(radius, 0, 0, radius, x, y)); return AffineTransform.getRotateInstance(angle, x, y).createTransformedShape(gp11); } } /** * Happy face marker. */ public static class HappyFaceMarker implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { double x = p.getX(), y = p.getY(); Area a = new Area(new Ellipse2D.Double(x - radius, y - radius, 2 * radius, 2 * radius)); a.subtract(new Area(new Ellipse2D.Double(x - radius / 3 - radius / 6, y - radius / 2, radius / 3, radius / 3))); a.subtract(new Area(new Ellipse2D.Double(x + radius / 3 - radius / 6, y - radius / 2, radius / 3, radius / 3))); a.subtract(new Area(new Arc2D.Double(x - radius / 2, y - radius / 2, radius, radius, 200, 140, Arc2D.CHORD))); return a; } } /** * House-shaped marker. */ public static class HouseMarker implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { double x = p.getX(), y = p.getY(); GeneralPath gp13 = new GeneralPath(); gp13.moveTo(-.9f, -.9f); gp13.lineTo(.9f, -.9f); gp13.lineTo(.9f, .4f); gp13.lineTo(1f, .4f); gp13.lineTo(.75f, .625f); gp13.lineTo(.75f, 1f); gp13.lineTo(.5f, 1f); gp13.lineTo(.5f, .75f); gp13.lineTo(0f, 1f); gp13.lineTo(-1f, .4f); gp13.lineTo(-.9f, .4f); gp13.lineTo(-.9f, -.9f); gp13.closePath(); gp13.transform(new AffineTransform(radius, 0, 0, -radius, x, y)); return gp13; } } }
triathematician/blaisemath
blaise-common/src/main/java/com/googlecode/blaisemath/primitive/Markers.java
Java
apache-2.0
17,804
/* * Copyright (C) 2013-2015 RoboVM AB * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Portions of this code is based on Apple Inc's PhotoPicker sample (v2.0) * which is copyright (C) 2010-2013 Apple Inc. */ package org.robovm.samples.tabster.viewcontrollers; import org.robovm.apple.uikit.UIImage; import org.robovm.apple.uikit.UILabel; import org.robovm.apple.uikit.UINavigationController; import org.robovm.apple.uikit.UITabBarItem; import org.robovm.apple.uikit.UIViewController; import org.robovm.objc.annotation.CustomClass; import org.robovm.objc.annotation.IBOutlet; @CustomClass("FourViewController") public class FourViewController extends UIViewController { private UILabel titleLabel; /** * this is called when the UITabBarController loads it's views at launch * time */ @Override public void awakeFromNib() { // make our tabbar icon a custom one; // we could do it in Interface Builder, but this is just to illustrate a // point about using awakeFromNib vs. viewDidLoad. UITabBarItem customTab = new UITabBarItem("Four", UIImage.create("tab4.png"), 0); setTabBarItem(customTab); } @Override public void viewWillAppear(boolean animated) { super.viewWillAppear(animated); // if we were navigated to through the More screen table, then we have a // navigation bar which also means we have a title. So hide the title // label in this case, otherwise, we need it if (getParentViewController() instanceof UINavigationController) { titleLabel.setHidden(true); } else { titleLabel.setHidden(false); } } @IBOutlet private void setTitleLabel(UILabel titleLabel) { this.titleLabel = titleLabel; } }
samskivert/robovm-samples
Tabster/src/main/java/org/robovm/samples/tabster/viewcontrollers/FourViewController.java
Java
apache-2.0
2,319
import React from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import { Headline } from '@folio/stripes/components'; import css from './ProxyViewList.css'; const ProxyViewList = ({ records, name, label, itemComponent, stripes }) => { const ComponentToRender = itemComponent; const items = records.map((record, index) => ( <ComponentToRender key={`item-${index}`} record={record} stripes={stripes} /> )); const noSponsorsFound = <FormattedMessage id="ui-users.permissions.noSponsorsFound" />; const noProxiesFound = <FormattedMessage id="ui-users.permissions.noProxiesFound" />; const noneFoundMsg = name === 'sponsors' ? noSponsorsFound : noProxiesFound; return ( <div className={css.list} data-test={name}> <Headline tag="h4" size="small" margin="small">{label}</Headline> {items.length ? items : <p className={css.isEmptyMessage}>{noneFoundMsg}</p>} </div> ); }; ProxyViewList.propTypes = { records: PropTypes.arrayOf(PropTypes.object), itemComponent: PropTypes.func.isRequired, name: PropTypes.string.isRequired, label: PropTypes.node.isRequired, stripes: PropTypes.object.isRequired, }; export default ProxyViewList;
folio-org/ui-users
src/components/ProxyGroup/ProxyViewList/ProxyViewList.js
JavaScript
apache-2.0
1,222
package com.splunk.sharedmc.loggable_events; /** * Categories of loggable events. */ public enum LoggableEventType { PLAYER("PlayerEvent"), BLOCK("BlockEvent"), DEATH("DeathEvent"); private final String eventName; LoggableEventType(String eventName) { this.eventName = eventName; } public String getEventName() { return eventName; } }
splunk/minecraft-app
shared-mc/src/main/java/com/splunk/sharedmc/loggable_events/LoggableEventType.java
Java
apache-2.0
389
import { useEffect, useState, useMemo } from "react" import useCommons from "../../../lib/hooks/useCommons" import { Link } from "react-router-dom" import StaticTags from "../StaticTags" import useL7Policy from "../../../lib/hooks/useL7Policy" import CopyPastePopover from "../shared/CopyPastePopover" import useListener from "../../../lib/hooks/useListener" import { addNotice, addError } from "lib/flashes" import { ErrorsList } from "lib/elektra-form/components/errors_list" import CachedInfoPopover from "../shared/CachedInforPopover" import CachedInfoPopoverContent from "./CachedInfoPopoverContent" import { policy } from "policy" import { scope } from "ajax_helper" import SmartLink from "../shared/SmartLink" import Log from "../shared/logger" import DropDownMenu from "../shared/DropdownMenu" import useStatus from "../../../lib/hooks/useStatus" import usePolling from "../../../lib/hooks/usePolling" const L7PolicyListItem = ({ props, l7Policy, searchTerm, listenerID, disabled, shouldPoll, }) => { const { MyHighlighter, matchParams, errorMessage, searchParamsToString } = useCommons() const { actionRedirect, deleteL7Policy, persistL7Policy, onSelectL7Policy, reset, } = useL7Policy() const [loadbalancerID, setLoadbalancerID] = useState(null) const { persistListener } = useListener() const { entityStatus } = useStatus( l7Policy.operating_status, l7Policy.provisioning_status ) useEffect(() => { const params = matchParams(props) setLoadbalancerID(params.loadbalancerID) }, []) const pollingCallback = () => { return persistL7Policy(loadbalancerID, listenerID, l7Policy.id) } usePolling({ delay: l7Policy.provisioning_status.includes("PENDING") ? 20000 : 60000, callback: pollingCallback, active: shouldPoll || l7Policy?.provisioning_status?.includes("PENDING"), }) const onL7PolicyClick = (e) => { if (e) { e.stopPropagation() e.preventDefault() } onSelectL7Policy(props, l7Policy.id) } const canEdit = useMemo( () => policy.isAllowed("lbaas2:l7policy_update", { target: { scoped_domain_name: scope.domain }, }), [scope.domain] ) const canDelete = useMemo( () => policy.isAllowed("lbaas2:l7policy_delete", { target: { scoped_domain_name: scope.domain }, }), [scope.domain] ) const canShowJSON = useMemo( () => policy.isAllowed("lbaas2:l7policy_get", { target: { scoped_domain_name: scope.domain }, }), [scope.domain] ) const handleDelete = (e) => { if (e) { e.stopPropagation() e.preventDefault() } const l7policyID = l7Policy.id const l7policyName = l7Policy.name return deleteL7Policy(loadbalancerID, listenerID, l7policyID, l7policyName) .then((response) => { addNotice( <React.Fragment> L7 Policy <b>{l7policyName}</b> ({l7policyID}) is being deleted. </React.Fragment> ) // fetch the listener again containing the new policy so it gets updated fast persistListener(loadbalancerID, listenerID) .then(() => {}) .catch((error) => {}) }) .catch((error) => { addError( React.createElement(ErrorsList, { errors: errorMessage(error.response), }) ) }) } const displayName = () => { const name = l7Policy.name || l7Policy.id if (disabled) { return ( <span className="info-text"> <CopyPastePopover text={name} size={20} sliceType="MIDDLE" shouldPopover={false} shouldCopy={false} bsClass="cp copy-paste-ids" /> </span> ) } else { return ( <Link to="#" onClick={onL7PolicyClick}> <CopyPastePopover text={name} size={20} sliceType="MIDDLE" shouldPopover={false} shouldCopy={false} searchTerm={searchTerm} /> </Link> ) } } const displayID = () => { if (l7Policy.name) { if (disabled) { return ( <div className="info-text"> <CopyPastePopover text={l7Policy.id} size={12} sliceType="MIDDLE" bsClass="cp copy-paste-ids" shouldPopover={false} /> </div> ) } else { return ( <CopyPastePopover text={l7Policy.id} size={12} sliceType="MIDDLE" bsClass="cp copy-paste-ids" searchTerm={searchTerm} /> ) } } } const l7RuleIDs = l7Policy.rules.map((l7rule) => l7rule.id) Log.debug("RENDER L7 Policy Item") return ( <tr> <td className="snug-nowrap"> {displayName()} {displayID()} <CopyPastePopover text={l7Policy.description} size={20} shouldCopy={false} shouldPopover={true} searchTerm={searchTerm} /> </td> <td>{entityStatus}</td> <td> <StaticTags tags={l7Policy.tags} /> </td> <td>{l7Policy.position}</td> <td> <MyHighlighter search={searchTerm}>{l7Policy.action}</MyHighlighter> {actionRedirect(l7Policy.action).map((redirect, index) => ( <span className="display-flex" key={index}> <br /> <b>{redirect.label}: </b> {redirect.value === "redirect_prefix" || redirect.value === "redirect_url" ? ( <CopyPastePopover text={l7Policy[redirect.value]} size={20} bsClass="cp label-right" /> ) : ( <span className="label-right">{l7Policy[redirect.value]}</span> )} </span> ))} </td> <td> {disabled ? ( <span className="info-text">{l7Policy.rules.length}</span> ) : ( <CachedInfoPopover popoverId={"l7rules-popover-" + l7Policy.id} buttonName={l7RuleIDs.length} title={ <React.Fragment> L7 Rules <Link to="#" onClick={onL7PolicyClick} style={{ float: "right" }} > Show all </Link> </React.Fragment> } content={ <CachedInfoPopoverContent props={props} lbID={loadbalancerID} listenerID={listenerID} l7PolicyID={l7Policy.id} l7RuleIDs={l7RuleIDs} cachedl7RuleIDs={l7Policy.cached_rules} /> } /> )} </td> <td> <DropDownMenu buttonIcon={<span className="fa fa-cog" />}> <li> <SmartLink to={`/loadbalancers/${loadbalancerID}/listeners/${listenerID}/l7policies/${ l7Policy.id }/edit?${searchParamsToString(props)}`} isAllowed={canEdit} notAllowedText="Not allowed to edit. Please check with your administrator." > Edit </SmartLink> </li> <li> <SmartLink onClick={handleDelete} isAllowed={canDelete} notAllowedText="Not allowed to delete. Please check with your administrator." > Delete </SmartLink> </li> <li> <SmartLink to={`/loadbalancers/${loadbalancerID}/listeners/${listenerID}/l7policies/${ l7Policy.id }/json?${searchParamsToString(props)}`} isAllowed={canShowJSON} notAllowedText="Not allowed to get JSOn. Please check with your administrator." > JSON </SmartLink> </li> </DropDownMenu> </td> </tr> ) } export default L7PolicyListItem
sapcc/elektra
plugins/lbaas2/app/javascript/app/components/l7policies/L7PolicyListItem.js
JavaScript
apache-2.0
8,173
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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.gravitee.am.management.handlers.management.api.authentication.handler; import io.gravitee.am.identityprovider.api.User; import io.gravitee.am.management.handlers.management.api.authentication.provider.generator.JWTGenerator; import io.gravitee.am.management.handlers.management.api.authentication.service.AuthenticationService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import static io.gravitee.am.management.handlers.management.api.authentication.provider.generator.RedirectCookieGenerator.DEFAULT_REDIRECT_COOKIE_NAME; /** * @author Titouan COMPIEGNE (titouan.compiegne at graviteesource.com) * @author GraviteeSource Team */ public class CustomAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { protected final Logger logger = LoggerFactory.getLogger(CustomAuthenticationSuccessHandler.class); @Autowired private JWTGenerator jwtGenerator; @Autowired private AuthenticationService authenticationService; @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException { String redirectUri = (String) request.getAttribute(DEFAULT_REDIRECT_COOKIE_NAME); // finish authentication and get an enhanced principal with user information. User principal = authenticationService.onAuthenticationSuccess(authentication); // store jwt authentication cookie to secure management restricted operations Cookie jwtAuthenticationCookie = jwtGenerator.generateCookie(principal); response.addCookie(jwtAuthenticationCookie); // Replay the original request. logger.debug("Redirecting to Url: " + redirectUri); getRedirectStrategy().sendRedirect(request, response, redirectUri); } }
gravitee-io/graviteeio-access-management
gravitee-am-management-api/gravitee-am-management-api-rest/src/main/java/io/gravitee/am/management/handlers/management/api/authentication/handler/CustomAuthenticationSuccessHandler.java
Java
apache-2.0
2,923
/* @internal */ namespace ts.codefix { const fixId = "inferFromUsage"; const errorCodes = [ // Variable declarations Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, // Variable uses Diagnostics.Variable_0_implicitly_has_an_1_type.code, // Parameter declarations Diagnostics.Parameter_0_implicitly_has_an_1_type.code, Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, // Get Accessor declarations Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, // Set Accessor declarations Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, // Property declarations Diagnostics.Member_0_implicitly_has_an_1_type.code, //// Suggestions // Variable declarations Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code, // Variable uses Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, // Parameter declarations Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code, // Get Accessor declarations Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code, Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code, // Set Accessor declarations Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code, // Property declarations Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, // Function expressions and declarations Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code, ]; registerCodeFix({ errorCodes, getCodeActions(context) { const { sourceFile, program, span: { start }, errorCode, cancellationToken, host, preferences } = context; const token = getTokenAtPosition(sourceFile, start); let declaration: Declaration | undefined; const changes = textChanges.ChangeTracker.with(context, changes => { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ returnTrue, host, preferences); }); const name = declaration && getNameOfDeclaration(declaration); return !name || changes.length === 0 ? undefined : [createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId], getAllCodeActions(context) { const { sourceFile, program, cancellationToken, host, preferences } = context; const markSeen = nodeSeenTracker(); return codeFixAll(context, errorCodes, (changes, err) => { doChange(changes, sourceFile, getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host, preferences); }); }, }); function getDiagnostic(errorCode: number, token: Node): DiagnosticMessage { switch (errorCode) { case Diagnostics.Parameter_0_implicitly_has_an_1_type.code: case Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: return isSetAccessorDeclaration(getContainingFunction(token)!) ? Diagnostics.Infer_type_of_0_from_usage : Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code: return Diagnostics.Infer_parameter_types_from_usage; case Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code: return Diagnostics.Infer_this_type_of_0_from_usage; default: return Diagnostics.Infer_type_of_0_from_usage; } } /** Map suggestion code to error code */ function mapSuggestionDiagnostic(errorCode: number) { switch (errorCode) { case Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code: return Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code; case Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: return Diagnostics.Variable_0_implicitly_has_an_1_type.code; case Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: return Diagnostics.Parameter_0_implicitly_has_an_1_type.code; case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code: return Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code; case Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code: return Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code; case Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code: return Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code; case Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code: return Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code; case Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: return Diagnostics.Member_0_implicitly_has_an_1_type.code; } return errorCode; } function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, token: Node, errorCode: number, program: Program, cancellationToken: CancellationToken, markSeen: NodeSeenTracker, host: LanguageServiceHost, preferences: UserPreferences): Declaration | undefined { if (!isParameterPropertyModifier(token.kind) && token.kind !== SyntaxKind.Identifier && token.kind !== SyntaxKind.DotDotDotToken && token.kind !== SyntaxKind.ThisKeyword) { return undefined; } const { parent } = token; const importAdder = createImportAdder(sourceFile, program, preferences, host); errorCode = mapSuggestionDiagnostic(errorCode); switch (errorCode) { // Variable and Property declarations case Diagnostics.Member_0_implicitly_has_an_1_type.code: case Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: if ((isVariableDeclaration(parent) && markSeen(parent)) || isPropertyDeclaration(parent) || isPropertySignature(parent)) { // handle bad location annotateVariableDeclaration(changes, importAdder, sourceFile, parent, program, host, cancellationToken); importAdder.writeFixes(changes); return parent; } if (isPropertyAccessExpression(parent)) { const type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken); const typeNode = getTypeNodeIfAccessible(type, parent, program, host); if (typeNode) { // Note that the codefix will never fire with an existing `@type` tag, so there is no need to merge tags const typeTag = factory.createJSDocTypeTag(/*tagName*/ undefined, factory.createJSDocTypeExpression(typeNode), /*comment*/ undefined); addJSDocTags(changes, sourceFile, cast(parent.parent.parent, isExpressionStatement), [typeTag]); } importAdder.writeFixes(changes); return parent; } return undefined; case Diagnostics.Variable_0_implicitly_has_an_1_type.code: { const symbol = program.getTypeChecker().getSymbolAtLocation(token); if (symbol && symbol.valueDeclaration && isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { annotateVariableDeclaration(changes, importAdder, sourceFile, symbol.valueDeclaration, program, host, cancellationToken); importAdder.writeFixes(changes); return symbol.valueDeclaration; } return undefined; } } const containingFunction = getContainingFunction(token); if (containingFunction === undefined) { return undefined; } let declaration: Declaration | undefined; switch (errorCode) { // Parameter declarations case Diagnostics.Parameter_0_implicitly_has_an_1_type.code: if (isSetAccessorDeclaration(containingFunction)) { annotateSetAccessor(changes, importAdder, sourceFile, containingFunction, program, host, cancellationToken); declaration = containingFunction; break; } // falls through case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: if (markSeen(containingFunction)) { const param = cast(parent, isParameter); annotateParameters(changes, importAdder, sourceFile, param, containingFunction, program, host, cancellationToken); declaration = param; } break; // Get Accessor declarations case Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: case Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: if (isGetAccessorDeclaration(containingFunction) && isIdentifier(containingFunction.name)) { annotate(changes, importAdder, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host); declaration = containingFunction; } break; // Set Accessor declarations case Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: if (isSetAccessorDeclaration(containingFunction)) { annotateSetAccessor(changes, importAdder, sourceFile, containingFunction, program, host, cancellationToken); declaration = containingFunction; } break; // Function 'this' case Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code: if (textChanges.isThisTypeAnnotatable(containingFunction) && markSeen(containingFunction)) { annotateThis(changes, sourceFile, containingFunction, program, host, cancellationToken); declaration = containingFunction; } break; default: return Debug.fail(String(errorCode)); } importAdder.writeFixes(changes); return declaration; } function annotateVariableDeclaration( changes: textChanges.ChangeTracker, importAdder: ImportAdder, sourceFile: SourceFile, declaration: VariableDeclaration | PropertyDeclaration | PropertySignature, program: Program, host: LanguageServiceHost, cancellationToken: CancellationToken, ): void { if (isIdentifier(declaration.name)) { annotate(changes, importAdder, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); } } function annotateParameters( changes: textChanges.ChangeTracker, importAdder: ImportAdder, sourceFile: SourceFile, parameterDeclaration: ParameterDeclaration, containingFunction: SignatureDeclaration, program: Program, host: LanguageServiceHost, cancellationToken: CancellationToken, ): void { if (!isIdentifier(parameterDeclaration.name)) { return; } const parameterInferences = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken); Debug.assert(containingFunction.parameters.length === parameterInferences.length, "Parameter count and inference count should match"); if (isInJSFile(containingFunction)) { annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host); } else { const needParens = isArrowFunction(containingFunction) && !findChildOfKind(containingFunction, SyntaxKind.OpenParenToken, sourceFile); if (needParens) changes.insertNodeBefore(sourceFile, first(containingFunction.parameters), factory.createToken(SyntaxKind.OpenParenToken)); for (const { declaration, type } of parameterInferences) { if (declaration && !declaration.type && !declaration.initializer) { annotate(changes, importAdder, sourceFile, declaration, type, program, host); } } if (needParens) changes.insertNodeAfter(sourceFile, last(containingFunction.parameters), factory.createToken(SyntaxKind.CloseParenToken)); } } function annotateThis(changes: textChanges.ChangeTracker, sourceFile: SourceFile, containingFunction: textChanges.ThisTypeAnnotatable, program: Program, host: LanguageServiceHost, cancellationToken: CancellationToken) { const references = getFunctionReferences(containingFunction, sourceFile, program, cancellationToken); if (!references || !references.length) { return; } const thisInference = inferTypeFromReferences(program, references, cancellationToken).thisParameter(); const typeNode = getTypeNodeIfAccessible(thisInference, containingFunction, program, host); if (!typeNode) { return; } if (isInJSFile(containingFunction)) { annotateJSDocThis(changes, sourceFile, containingFunction, typeNode); } else { changes.tryInsertThisTypeAnnotation(sourceFile, containingFunction, typeNode); } } function annotateJSDocThis(changes: textChanges.ChangeTracker, sourceFile: SourceFile, containingFunction: SignatureDeclaration, typeNode: TypeNode) { addJSDocTags(changes, sourceFile, containingFunction, [ factory.createJSDocThisTag(/*tagName*/ undefined, factory.createJSDocTypeExpression(typeNode)), ]); } function annotateSetAccessor( changes: textChanges.ChangeTracker, importAdder: ImportAdder, sourceFile: SourceFile, setAccessorDeclaration: SetAccessorDeclaration, program: Program, host: LanguageServiceHost, cancellationToken: CancellationToken, ): void { const param = firstOrUndefined(setAccessorDeclaration.parameters); if (param && isIdentifier(setAccessorDeclaration.name) && isIdentifier(param.name)) { let type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken); if (type === program.getTypeChecker().getAnyType()) { type = inferTypeForVariableFromUsage(param.name, program, cancellationToken); } if (isInJSFile(setAccessorDeclaration)) { annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type }], program, host); } else { annotate(changes, importAdder, sourceFile, param, type, program, host); } } } function annotate(changes: textChanges.ChangeTracker, importAdder: ImportAdder, sourceFile: SourceFile, declaration: textChanges.TypeAnnotatable, type: Type, program: Program, host: LanguageServiceHost): void { const typeNode = getTypeNodeIfAccessible(type, declaration, program, host); if (typeNode) { if (isInJSFile(sourceFile) && declaration.kind !== SyntaxKind.PropertySignature) { const parent = isVariableDeclaration(declaration) ? tryCast(declaration.parent.parent, isVariableStatement) : declaration; if (!parent) { return; } const typeExpression = factory.createJSDocTypeExpression(typeNode); const typeTag = isGetAccessorDeclaration(declaration) ? factory.createJSDocReturnTag(/*tagName*/ undefined, typeExpression, /*comment*/ undefined) : factory.createJSDocTypeTag(/*tagName*/ undefined, typeExpression, /*comment*/ undefined); addJSDocTags(changes, sourceFile, parent, [typeTag]); } else if (!tryReplaceImportTypeNodeWithAutoImport(typeNode, declaration, sourceFile, changes, importAdder, getEmitScriptTarget(program.getCompilerOptions()))) { changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); } } } function tryReplaceImportTypeNodeWithAutoImport( typeNode: TypeNode, declaration: textChanges.TypeAnnotatable, sourceFile: SourceFile, changes: textChanges.ChangeTracker, importAdder: ImportAdder, scriptTarget: ScriptTarget ): boolean { const importableReference = tryGetAutoImportableReferenceFromTypeNode(typeNode, scriptTarget); if (importableReference && changes.tryInsertTypeAnnotation(sourceFile, declaration, importableReference.typeNode)) { forEach(importableReference.symbols, s => importAdder.addImportFromExportedSymbol(s, /*usageIsTypeOnly*/ true)); return true; } return false; } function annotateJSDocParameters(changes: textChanges.ChangeTracker, sourceFile: SourceFile, parameterInferences: readonly ParameterInference[], program: Program, host: LanguageServiceHost): void { const signature = parameterInferences.length && parameterInferences[0].declaration.parent; if (!signature) { return; } const inferences = mapDefined(parameterInferences, inference => { const param = inference.declaration; // only infer parameters that have (1) no type and (2) an accessible inferred type if (param.initializer || getJSDocType(param) || !isIdentifier(param.name)) { return; } const typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host); if (typeNode) { const name = factory.cloneNode(param.name); setEmitFlags(name, EmitFlags.NoComments | EmitFlags.NoNestedComments); return { name: factory.cloneNode(param.name), param, isOptional: !!inference.isOptional, typeNode }; } }); if (!inferences.length) { return; } if (isArrowFunction(signature) || isFunctionExpression(signature)) { const needParens = isArrowFunction(signature) && !findChildOfKind(signature, SyntaxKind.OpenParenToken, sourceFile); if (needParens) { changes.insertNodeBefore(sourceFile, first(signature.parameters), factory.createToken(SyntaxKind.OpenParenToken)); } forEach(inferences, ({ typeNode, param }) => { const typeTag = factory.createJSDocTypeTag(/*tagName*/ undefined, factory.createJSDocTypeExpression(typeNode)); const jsDoc = factory.createJSDocComment(/*comment*/ undefined, [typeTag]); changes.insertNodeAt(sourceFile, param.getStart(sourceFile), jsDoc, { suffix: " " }); }); if (needParens) { changes.insertNodeAfter(sourceFile, last(signature.parameters), factory.createToken(SyntaxKind.CloseParenToken)); } } else { const paramTags = map(inferences, ({ name, typeNode, isOptional }) => factory.createJSDocParameterTag(/*tagName*/ undefined, name, /*isBracketed*/ !!isOptional, factory.createJSDocTypeExpression(typeNode), /* isNameFirst */ false, /*comment*/ undefined)); addJSDocTags(changes, sourceFile, signature, paramTags); } } export function addJSDocTags(changes: textChanges.ChangeTracker, sourceFile: SourceFile, parent: HasJSDoc, newTags: readonly JSDocTag[]): void { const comments = flatMap(parent.jsDoc, j => typeof j.comment === "string" ? factory.createJSDocText(j.comment) : j.comment) as JSDocComment[]; const oldTags = flatMapToMutable(parent.jsDoc, j => j.tags); const unmergedNewTags = newTags.filter(newTag => !oldTags || !oldTags.some((tag, i) => { const merged = tryMergeJsdocTags(tag, newTag); if (merged) oldTags[i] = merged; return !!merged; })); const tag = factory.createJSDocComment(factory.createNodeArray(intersperse(comments, factory.createJSDocText("\n"))), factory.createNodeArray([...(oldTags || emptyArray), ...unmergedNewTags])); const jsDocNode = parent.kind === SyntaxKind.ArrowFunction ? getJsDocNodeForArrowFunction(parent) : parent; jsDocNode.jsDoc = parent.jsDoc; jsDocNode.jsDocCache = parent.jsDocCache; changes.insertJsdocCommentBefore(sourceFile, jsDocNode, tag); } function getJsDocNodeForArrowFunction(signature: ArrowFunction): HasJSDoc { if (signature.parent.kind === SyntaxKind.PropertyDeclaration) { return signature.parent as HasJSDoc; } return signature.parent.parent as HasJSDoc; } function tryMergeJsdocTags(oldTag: JSDocTag, newTag: JSDocTag): JSDocTag | undefined { if (oldTag.kind !== newTag.kind) { return undefined; } switch (oldTag.kind) { case SyntaxKind.JSDocParameterTag: { const oldParam = oldTag as JSDocParameterTag; const newParam = newTag as JSDocParameterTag; return isIdentifier(oldParam.name) && isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText ? factory.createJSDocParameterTag(/*tagName*/ undefined, newParam.name, /*isBracketed*/ false, newParam.typeExpression, newParam.isNameFirst, oldParam.comment) : undefined; } case SyntaxKind.JSDocReturnTag: return factory.createJSDocReturnTag(/*tagName*/ undefined, (newTag as JSDocReturnTag).typeExpression, oldTag.comment); } } function getReferences(token: PropertyName | Token<SyntaxKind.ConstructorKeyword>, program: Program, cancellationToken: CancellationToken): readonly Identifier[] { // Position shouldn't matter since token is not a SourceFile. return mapDefined(FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), entry => entry.kind !== FindAllReferences.EntryKind.Span ? tryCast(entry.node, isIdentifier) : undefined); } function inferTypeForVariableFromUsage(token: Identifier | PrivateIdentifier, program: Program, cancellationToken: CancellationToken): Type { const references = getReferences(token, program, cancellationToken); return inferTypeFromReferences(program, references, cancellationToken).single(); } function inferTypeForParametersFromUsage(func: SignatureDeclaration, sourceFile: SourceFile, program: Program, cancellationToken: CancellationToken) { const references = getFunctionReferences(func, sourceFile, program, cancellationToken); return references && inferTypeFromReferences(program, references, cancellationToken).parameters(func) || func.parameters.map<ParameterInference>(p => ({ declaration: p, type: isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : program.getTypeChecker().getAnyType() })); } function getFunctionReferences(containingFunction: SignatureDeclaration, sourceFile: SourceFile, program: Program, cancellationToken: CancellationToken): readonly Identifier[] | undefined { let searchToken; switch (containingFunction.kind) { case SyntaxKind.Constructor: searchToken = findChildOfKind<Token<SyntaxKind.ConstructorKeyword>>(containingFunction, SyntaxKind.ConstructorKeyword, sourceFile); break; case SyntaxKind.ArrowFunction: case SyntaxKind.FunctionExpression: const parent = containingFunction.parent; searchToken = (isVariableDeclaration(parent) || isPropertyDeclaration(parent)) && isIdentifier(parent.name) ? parent.name : containingFunction.name; break; case SyntaxKind.FunctionDeclaration: case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: searchToken = containingFunction.name; break; } if (!searchToken) { return undefined; } return getReferences(searchToken, program, cancellationToken); } interface ParameterInference { readonly declaration: ParameterDeclaration; readonly type: Type; readonly isOptional?: boolean; } function inferTypeFromReferences(program: Program, references: readonly Identifier[], cancellationToken: CancellationToken) { const checker = program.getTypeChecker(); const builtinConstructors: { [s: string]: (t: Type) => Type } = { string: () => checker.getStringType(), number: () => checker.getNumberType(), Array: t => checker.createArrayType(t), Promise: t => checker.createPromiseType(t), }; const builtins = [ checker.getStringType(), checker.getNumberType(), checker.createArrayType(checker.getAnyType()), checker.createPromiseType(checker.getAnyType()), ]; return { single, parameters, thisParameter, }; interface CallUsage { argumentTypes: Type[]; return_: Usage; } interface Usage { isNumber: boolean | undefined; isString: boolean | undefined; /** Used ambiguously, eg x + ___ or object[___]; results in string | number if no other evidence exists */ isNumberOrString: boolean | undefined; candidateTypes: Type[] | undefined; properties: UnderscoreEscapedMap<Usage> | undefined; calls: CallUsage[] | undefined; constructs: CallUsage[] | undefined; numberIndex: Usage | undefined; stringIndex: Usage | undefined; candidateThisTypes: Type[] | undefined; inferredTypes: Type[] | undefined; } function createEmptyUsage(): Usage { return { isNumber: undefined, isString: undefined, isNumberOrString: undefined, candidateTypes: undefined, properties: undefined, calls: undefined, constructs: undefined, numberIndex: undefined, stringIndex: undefined, candidateThisTypes: undefined, inferredTypes: undefined, }; } function combineUsages(usages: Usage[]): Usage { const combinedProperties = new Map<__String, Usage[]>(); for (const u of usages) { if (u.properties) { u.properties.forEach((p, name) => { if (!combinedProperties.has(name)) { combinedProperties.set(name, []); } combinedProperties.get(name)!.push(p); }); } } const properties = new Map<__String, Usage>(); combinedProperties.forEach((ps, name) => { properties.set(name, combineUsages(ps)); }); return { isNumber: usages.some(u => u.isNumber), isString: usages.some(u => u.isString), isNumberOrString: usages.some(u => u.isNumberOrString), candidateTypes: flatMap(usages, u => u.candidateTypes) as Type[], properties, calls: flatMap(usages, u => u.calls) as CallUsage[], constructs: flatMap(usages, u => u.constructs) as CallUsage[], numberIndex: forEach(usages, u => u.numberIndex), stringIndex: forEach(usages, u => u.stringIndex), candidateThisTypes: flatMap(usages, u => u.candidateThisTypes) as Type[], inferredTypes: undefined, // clear type cache }; } function single(): Type { return combineTypes(inferTypesFromReferencesSingle(references)); } function parameters(declaration: SignatureDeclaration): ParameterInference[] | undefined { if (references.length === 0 || !declaration.parameters) { return undefined; } const usage = createEmptyUsage(); for (const reference of references) { cancellationToken.throwIfCancellationRequested(); calculateUsageOfNode(reference, usage); } const calls = [...usage.constructs || [], ...usage.calls || []]; return declaration.parameters.map((parameter, parameterIndex): ParameterInference => { const types = []; const isRest = isRestParameter(parameter); let isOptional = false; for (const call of calls) { if (call.argumentTypes.length <= parameterIndex) { isOptional = isInJSFile(declaration); types.push(checker.getUndefinedType()); } else if (isRest) { for (let i = parameterIndex; i < call.argumentTypes.length; i++) { types.push(checker.getBaseTypeOfLiteralType(call.argumentTypes[i])); } } else { types.push(checker.getBaseTypeOfLiteralType(call.argumentTypes[parameterIndex])); } } if (isIdentifier(parameter.name)) { const inferred = inferTypesFromReferencesSingle(getReferences(parameter.name, program, cancellationToken)); types.push(...(isRest ? mapDefined(inferred, checker.getElementTypeOfArrayType) : inferred)); } const type = combineTypes(types); return { type: isRest ? checker.createArrayType(type) : type, isOptional: isOptional && !isRest, declaration: parameter }; }); } function thisParameter() { const usage = createEmptyUsage(); for (const reference of references) { cancellationToken.throwIfCancellationRequested(); calculateUsageOfNode(reference, usage); } return combineTypes(usage.candidateThisTypes || emptyArray); } function inferTypesFromReferencesSingle(references: readonly Identifier[]): Type[] { const usage: Usage = createEmptyUsage(); for (const reference of references) { cancellationToken.throwIfCancellationRequested(); calculateUsageOfNode(reference, usage); } return inferTypes(usage); } function calculateUsageOfNode(node: Expression, usage: Usage): void { while (isRightSideOfQualifiedNameOrPropertyAccess(node)) { node = node.parent as Expression; } switch (node.parent.kind) { case SyntaxKind.ExpressionStatement: inferTypeFromExpressionStatement(node, usage); break; case SyntaxKind.PostfixUnaryExpression: usage.isNumber = true; break; case SyntaxKind.PrefixUnaryExpression: inferTypeFromPrefixUnaryExpression(node.parent as PrefixUnaryExpression, usage); break; case SyntaxKind.BinaryExpression: inferTypeFromBinaryExpression(node, node.parent as BinaryExpression, usage); break; case SyntaxKind.CaseClause: case SyntaxKind.DefaultClause: inferTypeFromSwitchStatementLabel(node.parent as CaseOrDefaultClause, usage); break; case SyntaxKind.CallExpression: case SyntaxKind.NewExpression: if ((node.parent as CallExpression | NewExpression).expression === node) { inferTypeFromCallExpression(node.parent as CallExpression | NewExpression, usage); } else { inferTypeFromContextualType(node, usage); } break; case SyntaxKind.PropertyAccessExpression: inferTypeFromPropertyAccessExpression(node.parent as PropertyAccessExpression, usage); break; case SyntaxKind.ElementAccessExpression: inferTypeFromPropertyElementExpression(node.parent as ElementAccessExpression, node, usage); break; case SyntaxKind.PropertyAssignment: case SyntaxKind.ShorthandPropertyAssignment: inferTypeFromPropertyAssignment(node.parent as PropertyAssignment | ShorthandPropertyAssignment, usage); break; case SyntaxKind.PropertyDeclaration: inferTypeFromPropertyDeclaration(node.parent as PropertyDeclaration, usage); break; case SyntaxKind.VariableDeclaration: { const { name, initializer } = node.parent as VariableDeclaration; if (node === name) { if (initializer) { // This can happen for `let x = null;` which still has an implicit-any error. addCandidateType(usage, checker.getTypeAtLocation(initializer)); } break; } } // falls through default: return inferTypeFromContextualType(node, usage); } } function inferTypeFromContextualType(node: Expression, usage: Usage): void { if (isExpressionNode(node)) { addCandidateType(usage, checker.getContextualType(node)); } } function inferTypeFromExpressionStatement(node: Expression, usage: Usage): void { addCandidateType(usage, isCallExpression(node) ? checker.getVoidType() : checker.getAnyType()); } function inferTypeFromPrefixUnaryExpression(node: PrefixUnaryExpression, usage: Usage): void { switch (node.operator) { case SyntaxKind.PlusPlusToken: case SyntaxKind.MinusMinusToken: case SyntaxKind.MinusToken: case SyntaxKind.TildeToken: usage.isNumber = true; break; case SyntaxKind.PlusToken: usage.isNumberOrString = true; break; // case SyntaxKind.ExclamationToken: // no inferences here; } } function inferTypeFromBinaryExpression(node: Expression, parent: BinaryExpression, usage: Usage): void { switch (parent.operatorToken.kind) { // ExponentiationOperator case SyntaxKind.AsteriskAsteriskToken: // MultiplicativeOperator // falls through case SyntaxKind.AsteriskToken: case SyntaxKind.SlashToken: case SyntaxKind.PercentToken: // ShiftOperator // falls through case SyntaxKind.LessThanLessThanToken: case SyntaxKind.GreaterThanGreaterThanToken: case SyntaxKind.GreaterThanGreaterThanGreaterThanToken: // BitwiseOperator // falls through case SyntaxKind.AmpersandToken: case SyntaxKind.BarToken: case SyntaxKind.CaretToken: // CompoundAssignmentOperator // falls through case SyntaxKind.MinusEqualsToken: case SyntaxKind.AsteriskAsteriskEqualsToken: case SyntaxKind.AsteriskEqualsToken: case SyntaxKind.SlashEqualsToken: case SyntaxKind.PercentEqualsToken: case SyntaxKind.AmpersandEqualsToken: case SyntaxKind.BarEqualsToken: case SyntaxKind.CaretEqualsToken: case SyntaxKind.LessThanLessThanEqualsToken: case SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken: case SyntaxKind.GreaterThanGreaterThanEqualsToken: // AdditiveOperator // falls through case SyntaxKind.MinusToken: // RelationalOperator // falls through case SyntaxKind.LessThanToken: case SyntaxKind.LessThanEqualsToken: case SyntaxKind.GreaterThanToken: case SyntaxKind.GreaterThanEqualsToken: const operandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); if (operandType.flags & TypeFlags.EnumLike) { addCandidateType(usage, operandType); } else { usage.isNumber = true; } break; case SyntaxKind.PlusEqualsToken: case SyntaxKind.PlusToken: const otherOperandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); if (otherOperandType.flags & TypeFlags.EnumLike) { addCandidateType(usage, otherOperandType); } else if (otherOperandType.flags & TypeFlags.NumberLike) { usage.isNumber = true; } else if (otherOperandType.flags & TypeFlags.StringLike) { usage.isString = true; } else if (otherOperandType.flags & TypeFlags.Any) { // do nothing, maybe we'll learn something elsewhere } else { usage.isNumberOrString = true; } break; // AssignmentOperators case SyntaxKind.EqualsToken: case SyntaxKind.EqualsEqualsToken: case SyntaxKind.EqualsEqualsEqualsToken: case SyntaxKind.ExclamationEqualsEqualsToken: case SyntaxKind.ExclamationEqualsToken: addCandidateType(usage, checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left)); break; case SyntaxKind.InKeyword: if (node === parent.left) { usage.isString = true; } break; // LogicalOperator Or NullishCoalescing case SyntaxKind.BarBarToken: case SyntaxKind.QuestionQuestionToken: if (node === parent.left && (node.parent.parent.kind === SyntaxKind.VariableDeclaration || isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { // var x = x || {}; // TODO: use getFalsyflagsOfType addCandidateType(usage, checker.getTypeAtLocation(parent.right)); } break; case SyntaxKind.AmpersandAmpersandToken: case SyntaxKind.CommaToken: case SyntaxKind.InstanceOfKeyword: // nothing to infer here break; } } function inferTypeFromSwitchStatementLabel(parent: CaseOrDefaultClause, usage: Usage): void { addCandidateType(usage, checker.getTypeAtLocation(parent.parent.parent.expression)); } function inferTypeFromCallExpression(parent: CallExpression | NewExpression, usage: Usage): void { const call: CallUsage = { argumentTypes: [], return_: createEmptyUsage() }; if (parent.arguments) { for (const argument of parent.arguments) { call.argumentTypes.push(checker.getTypeAtLocation(argument)); } } calculateUsageOfNode(parent, call.return_); if (parent.kind === SyntaxKind.CallExpression) { (usage.calls || (usage.calls = [])).push(call); } else { (usage.constructs || (usage.constructs = [])).push(call); } } function inferTypeFromPropertyAccessExpression(parent: PropertyAccessExpression, usage: Usage): void { const name = escapeLeadingUnderscores(parent.name.text); if (!usage.properties) { usage.properties = new Map(); } const propertyUsage = usage.properties.get(name) || createEmptyUsage(); calculateUsageOfNode(parent, propertyUsage); usage.properties.set(name, propertyUsage); } function inferTypeFromPropertyElementExpression(parent: ElementAccessExpression, node: Expression, usage: Usage): void { if (node === parent.argumentExpression) { usage.isNumberOrString = true; return; } else { const indexType = checker.getTypeAtLocation(parent.argumentExpression); const indexUsage = createEmptyUsage(); calculateUsageOfNode(parent, indexUsage); if (indexType.flags & TypeFlags.NumberLike) { usage.numberIndex = indexUsage; } else { usage.stringIndex = indexUsage; } } } function inferTypeFromPropertyAssignment(assignment: PropertyAssignment | ShorthandPropertyAssignment, usage: Usage) { const nodeWithRealType = isVariableDeclaration(assignment.parent.parent) ? assignment.parent.parent : assignment.parent; addCandidateThisType(usage, checker.getTypeAtLocation(nodeWithRealType)); } function inferTypeFromPropertyDeclaration(declaration: PropertyDeclaration, usage: Usage) { addCandidateThisType(usage, checker.getTypeAtLocation(declaration.parent)); } interface Priority { high: (t: Type) => boolean; low: (t: Type) => boolean; } function removeLowPriorityInferences(inferences: readonly Type[], priorities: Priority[]): Type[] { const toRemove: ((t: Type) => boolean)[] = []; for (const i of inferences) { for (const { high, low } of priorities) { if (high(i)) { Debug.assert(!low(i), "Priority can't have both low and high"); toRemove.push(low); } } } return inferences.filter(i => toRemove.every(f => !f(i))); } function combineFromUsage(usage: Usage) { return combineTypes(inferTypes(usage)); } function combineTypes(inferences: readonly Type[]): Type { if (!inferences.length) return checker.getAnyType(); // 1. string or number individually override string | number // 2. non-any, non-void overrides any or void // 3. non-nullable, non-any, non-void, non-anonymous overrides anonymous types const stringNumber = checker.getUnionType([checker.getStringType(), checker.getNumberType()]); const priorities: Priority[] = [ { high: t => t === checker.getStringType() || t === checker.getNumberType(), low: t => t === stringNumber }, { high: t => !(t.flags & (TypeFlags.Any | TypeFlags.Void)), low: t => !!(t.flags & (TypeFlags.Any | TypeFlags.Void)) }, { high: t => !(t.flags & (TypeFlags.Nullable | TypeFlags.Any | TypeFlags.Void)) && !(getObjectFlags(t) & ObjectFlags.Anonymous), low: t => !!(getObjectFlags(t) & ObjectFlags.Anonymous) }]; let good = removeLowPriorityInferences(inferences, priorities); const anons = good.filter(i => getObjectFlags(i) & ObjectFlags.Anonymous) as AnonymousType[]; if (anons.length) { good = good.filter(i => !(getObjectFlags(i) & ObjectFlags.Anonymous)); good.push(combineAnonymousTypes(anons)); } return checker.getWidenedType(checker.getUnionType(good.map(checker.getBaseTypeOfLiteralType), UnionReduction.Subtype)); } function combineAnonymousTypes(anons: AnonymousType[]) { if (anons.length === 1) { return anons[0]; } const calls = []; const constructs = []; const stringIndices = []; const numberIndices = []; let stringIndexReadonly = false; let numberIndexReadonly = false; const props = createMultiMap<Type>(); for (const anon of anons) { for (const p of checker.getPropertiesOfType(anon)) { props.add(p.name, p.valueDeclaration ? checker.getTypeOfSymbolAtLocation(p, p.valueDeclaration) : checker.getAnyType()); } calls.push(...checker.getSignaturesOfType(anon, SignatureKind.Call)); constructs.push(...checker.getSignaturesOfType(anon, SignatureKind.Construct)); const stringIndexInfo = checker.getIndexInfoOfType(anon, IndexKind.String); if (stringIndexInfo) { stringIndices.push(stringIndexInfo.type); stringIndexReadonly = stringIndexReadonly || stringIndexInfo.isReadonly; } const numberIndexInfo = checker.getIndexInfoOfType(anon, IndexKind.Number); if (numberIndexInfo) { numberIndices.push(numberIndexInfo.type); numberIndexReadonly = numberIndexReadonly || numberIndexInfo.isReadonly; } } const members = mapEntries(props, (name, types) => { const isOptional = types.length < anons.length ? SymbolFlags.Optional : 0; const s = checker.createSymbol(SymbolFlags.Property | isOptional, name as __String); s.type = checker.getUnionType(types); return [name, s]; }); const indexInfos = []; if (stringIndices.length) indexInfos.push(checker.createIndexInfo(checker.getStringType(), checker.getUnionType(stringIndices), stringIndexReadonly)); if (numberIndices.length) indexInfos.push(checker.createIndexInfo(checker.getNumberType(), checker.getUnionType(numberIndices), numberIndexReadonly)); return checker.createAnonymousType( anons[0].symbol, members as UnderscoreEscapedMap<TransientSymbol>, calls, constructs, indexInfos); } function inferTypes(usage: Usage): Type[] { const types = []; if (usage.isNumber) { types.push(checker.getNumberType()); } if (usage.isString) { types.push(checker.getStringType()); } if (usage.isNumberOrString) { types.push(checker.getUnionType([checker.getStringType(), checker.getNumberType()])); } if (usage.numberIndex) { types.push(checker.createArrayType(combineFromUsage(usage.numberIndex))); } if (usage.properties?.size || usage.calls?.length || usage.constructs?.length || usage.stringIndex) { types.push(inferStructuralType(usage)); } types.push(...(usage.candidateTypes || []).map(t => checker.getBaseTypeOfLiteralType(t))); types.push(...inferNamedTypesFromProperties(usage)); return types; } function inferStructuralType(usage: Usage) { const members = new Map<__String, Symbol>(); if (usage.properties) { usage.properties.forEach((u, name) => { const symbol = checker.createSymbol(SymbolFlags.Property, name); symbol.type = combineFromUsage(u); members.set(name, symbol); }); } const callSignatures: Signature[] = usage.calls ? [getSignatureFromCalls(usage.calls)] : []; const constructSignatures: Signature[] = usage.constructs ? [getSignatureFromCalls(usage.constructs)] : []; const indexInfos = usage.stringIndex ? [checker.createIndexInfo(checker.getStringType(), combineFromUsage(usage.stringIndex), /*isReadonly*/ false)] : []; return checker.createAnonymousType(/*symbol*/ undefined, members, callSignatures, constructSignatures, indexInfos); } function inferNamedTypesFromProperties(usage: Usage): Type[] { if (!usage.properties || !usage.properties.size) return []; const types = builtins.filter(t => allPropertiesAreAssignableToUsage(t, usage)); if (0 < types.length && types.length < 3) { return types.map(t => inferInstantiationFromUsage(t, usage)); } return []; } function allPropertiesAreAssignableToUsage(type: Type, usage: Usage) { if (!usage.properties) return false; return !forEachEntry(usage.properties, (propUsage, name) => { const source = checker.getTypeOfPropertyOfType(type, name as string); if (!source) { return true; } if (propUsage.calls) { const sigs = checker.getSignaturesOfType(source, SignatureKind.Call); return !sigs.length || !checker.isTypeAssignableTo(source, getFunctionFromCalls(propUsage.calls)); } else { return !checker.isTypeAssignableTo(source, combineFromUsage(propUsage)); } }); } /** * inference is limited to * 1. generic types with a single parameter * 2. inference to/from calls with a single signature */ function inferInstantiationFromUsage(type: Type, usage: Usage) { if (!(getObjectFlags(type) & ObjectFlags.Reference) || !usage.properties) { return type; } const generic = (type as TypeReference).target; const singleTypeParameter = singleOrUndefined(generic.typeParameters); if (!singleTypeParameter) return type; const types: Type[] = []; usage.properties.forEach((propUsage, name) => { const genericPropertyType = checker.getTypeOfPropertyOfType(generic, name as string); Debug.assert(!!genericPropertyType, "generic should have all the properties of its reference."); types.push(...inferTypeParameters(genericPropertyType, combineFromUsage(propUsage), singleTypeParameter)); }); return builtinConstructors[type.symbol.escapedName as string](combineTypes(types)); } function inferTypeParameters(genericType: Type, usageType: Type, typeParameter: Type): readonly Type[] { if (genericType === typeParameter) { return [usageType]; } else if (genericType.flags & TypeFlags.UnionOrIntersection) { return flatMap((genericType as UnionOrIntersectionType).types, t => inferTypeParameters(t, usageType, typeParameter)); } else if (getObjectFlags(genericType) & ObjectFlags.Reference && getObjectFlags(usageType) & ObjectFlags.Reference) { // this is wrong because we need a reference to the targetType to, so we can check that it's also a reference const genericArgs = checker.getTypeArguments(genericType as TypeReference); const usageArgs = checker.getTypeArguments(usageType as TypeReference); const types = []; if (genericArgs && usageArgs) { for (let i = 0; i < genericArgs.length; i++) { if (usageArgs[i]) { types.push(...inferTypeParameters(genericArgs[i], usageArgs[i], typeParameter)); } } } return types; } const genericSigs = checker.getSignaturesOfType(genericType, SignatureKind.Call); const usageSigs = checker.getSignaturesOfType(usageType, SignatureKind.Call); if (genericSigs.length === 1 && usageSigs.length === 1) { return inferFromSignatures(genericSigs[0], usageSigs[0], typeParameter); } return []; } function inferFromSignatures(genericSig: Signature, usageSig: Signature, typeParameter: Type) { const types = []; for (let i = 0; i < genericSig.parameters.length; i++) { const genericParam = genericSig.parameters[i]; const usageParam = usageSig.parameters[i]; const isRest = genericSig.declaration && isRestParameter(genericSig.declaration.parameters[i]); if (!usageParam) { break; } let genericParamType = genericParam.valueDeclaration ? checker.getTypeOfSymbolAtLocation(genericParam, genericParam.valueDeclaration) : checker.getAnyType(); const elementType = isRest && checker.getElementTypeOfArrayType(genericParamType); if (elementType) { genericParamType = elementType; } const targetType = (usageParam as SymbolLinks).type || (usageParam.valueDeclaration ? checker.getTypeOfSymbolAtLocation(usageParam, usageParam.valueDeclaration) : checker.getAnyType()); types.push(...inferTypeParameters(genericParamType, targetType, typeParameter)); } const genericReturn = checker.getReturnTypeOfSignature(genericSig); const usageReturn = checker.getReturnTypeOfSignature(usageSig); types.push(...inferTypeParameters(genericReturn, usageReturn, typeParameter)); return types; } function getFunctionFromCalls(calls: CallUsage[]) { return checker.createAnonymousType(/*symbol*/ undefined, createSymbolTable(), [getSignatureFromCalls(calls)], emptyArray, emptyArray); } function getSignatureFromCalls(calls: CallUsage[]): Signature { const parameters: Symbol[] = []; const length = Math.max(...calls.map(c => c.argumentTypes.length)); for (let i = 0; i < length; i++) { const symbol = checker.createSymbol(SymbolFlags.FunctionScopedVariable, escapeLeadingUnderscores(`arg${i}`)); symbol.type = combineTypes(calls.map(call => call.argumentTypes[i] || checker.getUndefinedType())); if (calls.some(call => call.argumentTypes[i] === undefined)) { symbol.flags |= SymbolFlags.Optional; } parameters.push(symbol); } const returnType = combineFromUsage(combineUsages(calls.map(call => call.return_))); return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, SignatureFlags.None); } function addCandidateType(usage: Usage, type: Type | undefined) { if (type && !(type.flags & TypeFlags.Any) && !(type.flags & TypeFlags.Never)) { (usage.candidateTypes || (usage.candidateTypes = [])).push(type); } } function addCandidateThisType(usage: Usage, type: Type | undefined) { if (type && !(type.flags & TypeFlags.Any) && !(type.flags & TypeFlags.Never)) { (usage.candidateThisTypes || (usage.candidateThisTypes = [])).push(type); } } } }
kpreisser/TypeScript
src/services/codefixes/inferFromUsage.ts
TypeScript
apache-2.0
60,313
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.elasticmapreduce.model; import java.io.Serializable; import javax.annotation.Generated; /** * <p> * This output indicates the result of removing tags from a resource. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/elasticmapreduce-2009-03-31/RemoveTags" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class RemoveTagsResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof RemoveTagsResult == false) return false; RemoveTagsResult other = (RemoveTagsResult) obj; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; return hashCode; } @Override public RemoveTagsResult clone() { try { return (RemoveTagsResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
jentfoo/aws-sdk-java
aws-java-sdk-emr/src/main/java/com/amazonaws/services/elasticmapreduce/model/RemoveTagsResult.java
Java
apache-2.0
2,404
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * Copyright 2012-2021 the original author or authors. */ package org.assertj.core.api.classes; import static org.mockito.Mockito.verify; import org.assertj.core.api.ClassAssert; import org.assertj.core.api.ClassAssertBaseTest; /** * Tests for <code>{@link org.assertj.core.api.ClassAssert#hasDeclaredFields(String...)}</code>. * * @author William Delanoue */ class ClassAssert_hasDeclaredFields_Test extends ClassAssertBaseTest { @Override protected ClassAssert invoke_api_method() { return assertions.hasDeclaredFields("field"); } @Override protected void verify_internal_effects() { verify(classes).assertHasDeclaredFields(getInfo(assertions), getActual(assertions), "field"); } }
hazendaz/assertj-core
src/test/java/org/assertj/core/api/classes/ClassAssert_hasDeclaredFields_Test.java
Java
apache-2.0
1,264
package cn.wh.bean; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="person") public class Person implements Serializable { private static final long serialVersionUID = 8648652046877078029L; private Integer id; private String name; public Person() {} public Person(String name) { this.name = name; } @Id @Column(name="id") @GeneratedValue(strategy=GenerationType.AUTO) public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Column(name="name",length=20,nullable=false) public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Person other = (Person) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
bingoogolapple/J2EENote
EJB/EntityBean/src/cn/wh/bean/Person.java
Java
apache-2.0
1,405
package com.microexample.geolocation; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.*; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.EnvironmentVariableCredentialsProvider; import com.amazonaws.services.dynamodbv2.*; import com.microexample.geolocation.contracts.*; import com.microexample.geolocation.factories.*; import com.microexample.geolocation.repositories.*; import com.microexample.geolocation.services.*; @SpringBootApplication @Configuration public class GeolocationApplication { public static void main(String[] args) { SpringApplication.run(GeolocationApplication.class, args); } // usealy api use "request" Scope /** * Coordinates service resolver */ @Bean(destroyMethod = "dispose") @Scope("singleton") public ICoordinatesService coordinatesService() { ICoordinatesRepository coordinatesRepository = coordinatesRepository(); return new CoordinatesService(coordinatesRepository); } /** * Coordinates repository resolver */ @Bean @Scope("singleton") public ICoordinatesRepository coordinatesRepository() { AmazonDynamoDB dbContext = amazonDynamoDB(); return new CoordinatesRepository(dbContext); } /** * Amazon db context resolver */ @Bean(destroyMethod = "shutdown") @Scope("singleton") public AmazonDynamoDB amazonDynamoDB() { IFactory<AmazonDynamoDB> dbContextFactory = dynamoDbFactory(); AmazonDynamoDB dbContext = dbContextFactory.create(); return dbContext; } /** * Amazon dynamo db factory resolver */ @Bean @Scope("singleton") public IFactory<AmazonDynamoDB> dynamoDbFactory() { AWSCredentialsProvider awsCredentialsProvider = AWSCredentialsProvider(); IFactory<AmazonDynamoDB> dbContextFactory = new AmazonDynamoDbFactory(awsCredentialsProvider); return dbContextFactory; } /** * Amazon credentials provider resolver */ @Bean @Scope("singleton") public AWSCredentialsProvider AWSCredentialsProvider() { EnvironmentVariableCredentialsProvider awsCredentialsProvider = new EnvironmentVariableCredentialsProvider(); return awsCredentialsProvider; } }
vahpetr/microapp
geolocation/src/main/java/com/microexample/geolocation/GeolocationApplication.java
Java
apache-2.0
2,396
/** * Package for utils in "Sql-xml-xslt-jdbc" task. * * @author Viacheslav Piliugin (mailto:ephemeralin@gmail.com) * @version $Id$ * @since 0.1 */ package ru.job4j.sqlxmlxsltjdbc.util;
ephemeralin/java-training
chapter_006/src/main/java/ru/job4j/sqlxmlxsltjdbc/util/package-info.java
Java
apache-2.0
192
from __future__ import absolute_import, unicode_literals import django from django.db import models from django.utils.translation import ugettext_lazy as _ from .managers import QueueManager, MessageManager class Queue(models.Model): name = models.CharField(_('name'), max_length=200, unique=True) objects = QueueManager() class Meta: if django.VERSION >= (1, 7): app_label = 'karellen_kombu_transport_django' db_table = 'djkombu_queue' verbose_name = _('queue') verbose_name_plural = _('queues') class Message(models.Model): visible = models.BooleanField(default=True, db_index=True) sent_at = models.DateTimeField(null=True, blank=True, db_index=True, auto_now_add=True) payload = models.TextField(_('payload'), null=False) queue = models.ForeignKey(Queue, related_name='messages') objects = MessageManager() class Meta: if django.VERSION >= (1, 7): app_label = 'karellen_kombu_transport_django' db_table = 'djkombu_message' verbose_name = _('message') verbose_name_plural = _('messages')
arcivanov/karellen-kombu-ext
src/main/python/karellen/kombu/transport/django/models.py
Python
apache-2.0
1,161
// @Bind #menu1.#menuItem2.onClick !function() { dorado.MessageBox.alert("Dorado7.0 快速入门"); }; // @Bind #tree1.onDataRowClick !function(self) { // 定义Tab变量 var tab = {}; // self 代表事件所属的控件,此处指 Tree对象 // self.get("currentNode")表示获取当前被点击的节点。 with (self.get("currentNode")) { // 制定当前的tab为IFrameTab tab.$type = "IFrame"; // 定义新Tab的标签 tab.caption = get("label"); // 定义Tab的Path // get("userData")表示获取当前节点的UserData属性, // 也就是刚才设定的 sample.chapter01.HelloWorld.d tab.path = get("userData"); tab.name = get("label"); tab.closeable = true; } // 如果当前节点有指定的Path则打开新的tab if (tab.path) { with (view.get("#tabControl")) { // 根据name查找是否已经打开过当前的Tab。 // 如果没有打开过,则需要添加一个新的Tab var currentTab = getTab(tab.name); if (currentTab) { tab = currentTab; } else { // 获取ID为tabControl的对象,并添加一个新的Tab // 设定ID为tabControl的对象的当前Tab为新创建的Tab tab = addTab(tab); } // 设定当前的Tab为制定的tab set("currentTab", tab); } } };
leifchen/hello-dorado
src/demo/chapter02/Main.js
JavaScript
apache-2.0
1,297
var GPSClient = {}; GPSClient.send = function(exeurl, latitude,longitude,actionname,username) { var client = Titanium.Network.createHTTPClient({timeout : 100000}); var paramater = '&intaliouser=' + username + '&parameter=latitude:' + longitude + ','; //var paramater = '&username=' + username + '&parameter=latitude:' + longitude + ','; var paramater1 = 'longitude:' + latitude + ','; var paramater2 = 'timestamp:timestamp,'; var paramater3 = 'actionname:' + actionname + ','; var paramater4 = 'name:' + username + ','; var url = exeurl + paramater + paramater1 + paramater2 + paramater3 + paramater4; client.open(GET_REC, url); client.onload = function() { try { var resData = eval("("+this.responseText+")"); if (resData[0].error == 'Yes') { var dialog = Titanium.UI.createAlertDialog({}); dialog.title = Titanium.Locale.getString("gps_yes_title"); dialog.message = resData[0].contents; dialog.show(); return; } else { return; } } catch (e) { Titanium.API.error(e); var dialog = Titanium.UI.createAlertDialog({}); dialog.title = Titanium.Locale.getString("gps_catch_title"); dialog.message = Titanium.Locale.getString("gps_catch_message"); dialog.show(); return; } }; client.onerror = function() { if (client.status == 401) { var dialog = Titanium.UI.createAlertDialog({}); dialog.title = Titanium.Locale.getString("gps_connect_title"); dialog.message = Titanium.Locale.getString("gps_connect_message"); dialog.show(); return; } var dialog = Titanium.UI.createAlertDialog({}); dialog.title = Titanium.Locale.getString("gps_network_title"); dialog.message = Titanium.Locale.getString("gps_network_message"); dialog.show(); return; }; client.send(); };
DaisukeSugai/salesreport
Resources/gps.js
JavaScript
apache-2.0
1,761
/** */ package org.afplib.afplib.impl; import java.util.Collection; import org.afplib.afplib.AfplibPackage; import org.afplib.afplib.BRG; import org.afplib.base.Triplet; import org.afplib.base.impl.SFImpl; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.util.EObjectContainmentEList; import org.eclipse.emf.ecore.util.InternalEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>BRG</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link org.afplib.afplib.impl.BRGImpl#getRGrpName <em>RGrp Name</em>}</li> * <li>{@link org.afplib.afplib.impl.BRGImpl#getTriplets <em>Triplets</em>}</li> * </ul> * * @generated */ public class BRGImpl extends SFImpl implements BRG { /** * The default value of the '{@link #getRGrpName() <em>RGrp Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getRGrpName() * @generated * @ordered */ protected static final String RGRP_NAME_EDEFAULT = null; /** * The cached value of the '{@link #getRGrpName() <em>RGrp Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getRGrpName() * @generated * @ordered */ protected String rGrpName = RGRP_NAME_EDEFAULT; /** * The cached value of the '{@link #getTriplets() <em>Triplets</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTriplets() * @generated * @ordered */ protected EList<Triplet> triplets; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected BRGImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return AfplibPackage.eINSTANCE.getBRG(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getRGrpName() { return rGrpName; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setRGrpName(String newRGrpName) { String oldRGrpName = rGrpName; rGrpName = newRGrpName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.BRG__RGRP_NAME, oldRGrpName, rGrpName)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<Triplet> getTriplets() { if (triplets == null) { triplets = new EObjectContainmentEList.Resolving<Triplet>(Triplet.class, this, AfplibPackage.BRG__TRIPLETS); } return triplets; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case AfplibPackage.BRG__TRIPLETS: return ((InternalEList<?>)getTriplets()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case AfplibPackage.BRG__RGRP_NAME: return getRGrpName(); case AfplibPackage.BRG__TRIPLETS: return getTriplets(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case AfplibPackage.BRG__RGRP_NAME: setRGrpName((String)newValue); return; case AfplibPackage.BRG__TRIPLETS: getTriplets().clear(); getTriplets().addAll((Collection<? extends Triplet>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case AfplibPackage.BRG__RGRP_NAME: setRGrpName(RGRP_NAME_EDEFAULT); return; case AfplibPackage.BRG__TRIPLETS: getTriplets().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case AfplibPackage.BRG__RGRP_NAME: return RGRP_NAME_EDEFAULT == null ? rGrpName != null : !RGRP_NAME_EDEFAULT.equals(rGrpName); case AfplibPackage.BRG__TRIPLETS: return triplets != null && !triplets.isEmpty(); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (RGrpName: "); result.append(rGrpName); result.append(')'); return result.toString(); } } //BRGImpl
yan74/afplib
org.afplib/src/main/java/org/afplib/afplib/impl/BRGImpl.java
Java
apache-2.0
5,195
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; /** * <p>DynaClass which implements the <code>MutableDynaClass</code> interface.</p> * * <p>A <code>MutableDynaClass</code> is a specialized extension to <code>DynaClass</code> * that allows properties to be added or removed dynamically.</p> * * <p>This implementation has one slightly unusual default behaviour - calling * the <code>getDynaProperty(name)</code> method for a property which doesn't * exist returns a <code>DynaProperty</code> rather than <code>null</code>. The * reason for this is that <code>BeanUtils</code> calls this method to check if * a property exists before trying to set the value. This would defeat the object * of the <code>LazyDynaBean</code> which automatically adds missing properties * when any of its <code>set()</code> methods are called. For this reason the * <code>isDynaProperty(name)</code> method has been added to this implementation * in order to determine if a property actually exists. If the more <i>normal</i> * behaviour of returning <code>null</code> is required, then this can be achieved * by calling the <code>setReturnNull(true)</code>.</p> * * <p>The <code>add(name, type, readable, writable)</code> method is not implemented * and always throws an <code>UnsupportedOperationException</code>. I believe * this attributes need to be added to the <code>DynaProperty</code> class * in order to control read/write facilities.</p> * * @version $Id: LazyDynaClass.java 1747095 2016-06-07 00:27:52Z ggregory $ * @see LazyDynaBean */ public class LazyDynaClass extends BasicDynaClass implements MutableDynaClass { /** * Controls whether changes to this DynaClass's properties are allowed. */ protected boolean restricted; /** * <p>Controls whether the <code>getDynaProperty()</code> method returns * null if a property doesn't exist - or creates a new one.</p> * * <p>Default is <code>false</code>. */ protected boolean returnNull = false; /** * Construct a new LazyDynaClass with default parameters. */ public LazyDynaClass() { this(null, (DynaProperty[])null); } /** * Construct a new LazyDynaClass with the specified name. * * @param name Name of this DynaBean class */ public LazyDynaClass(final String name) { this(name, (DynaProperty[])null); } /** * Construct a new LazyDynaClass with the specified name and DynaBean class. * * @param name Name of this DynaBean class * @param dynaBeanClass The implementation class for new instances */ public LazyDynaClass(final String name, final Class<?> dynaBeanClass) { this(name, dynaBeanClass, null); } /** * Construct a new LazyDynaClass with the specified name and properties. * * @param name Name of this DynaBean class * @param properties Property descriptors for the supported properties */ public LazyDynaClass(final String name, final DynaProperty[] properties) { this(name, LazyDynaBean.class, properties); } /** * Construct a new LazyDynaClass with the specified name, DynaBean class and properties. * * @param name Name of this DynaBean class * @param dynaBeanClass The implementation class for new instances * @param properties Property descriptors for the supported properties */ public LazyDynaClass(final String name, final Class<?> dynaBeanClass, final DynaProperty properties[]) { super(name, dynaBeanClass, properties); } /** * <p>Is this DynaClass currently restricted.</p> * <p>If restricted, no changes to the existing registration of * property names, data types, readability, or writeability are allowed.</p> * @return <code>true</code> if this {@link MutableDynaClass} cannot be changed * otherwise <code>false</code> */ public boolean isRestricted() { return restricted; } /** * <p>Set whether this DynaClass is currently restricted.</p> * <p>If restricted, no changes to the existing registration of * property names, data types, readability, or writeability are allowed.</p> * @param restricted <code>true</code> if this {@link MutableDynaClass} cannot * be changed otherwise <code>false</code> */ public void setRestricted(final boolean restricted) { this.restricted = restricted; } /** * Should this DynaClass return a <code>null</code> from * the <code>getDynaProperty(name)</code> method if the property * doesn't exist. * * @return <code>true</code> if a <code>null</code> {@link DynaProperty} * should be returned if the property doesn't exist, otherwise * <code>false</code> if a new {@link DynaProperty} should be created. */ public boolean isReturnNull() { return returnNull; } /** * Set whether this DynaClass should return a <code>null</code> from * the <code>getDynaProperty(name)</code> method if the property * doesn't exist. * @param returnNull <code>true</code> if a <code>null</code> {@link DynaProperty} * should be returned if the property doesn't exist, otherwise * <code>false</code> if a new {@link DynaProperty} should be created. */ public void setReturnNull(final boolean returnNull) { this.returnNull = returnNull; } /** * Add a new dynamic property with no restrictions on data type, * readability, or writeability. * * @param name Name of the new dynamic property * * @throws IllegalArgumentException if name is null * @throws IllegalStateException if this DynaClass is currently * restricted, so no new properties can be added */ public void add(final String name) { add(new DynaProperty(name)); } /** * Add a new dynamic property with the specified data type, but with * no restrictions on readability or writeability. * * @param name Name of the new dynamic property * @param type Data type of the new dynamic property (null for no * restrictions) * * @throws IllegalArgumentException if name is null * @throws IllegalStateException if this DynaClass is currently * restricted, so no new properties can be added */ public void add(final String name, final Class<?> type) { if (type == null) { add(name); } else { add(new DynaProperty(name, type)); } } /** * <p>Add a new dynamic property with the specified data type, readability, * and writeability.</p> * * <p><strong>N.B.</strong>Support for readable/writeable properties has not been implemented * and this method always throws a <code>UnsupportedOperationException</code>.</p> * * <p>I'm not sure the intention of the original authors for this method, but it seems to * me that readable/writable should be attributes of the <code>DynaProperty</code> class * (which they are not) and is the reason this method has not been implemented.</p> * * @param name Name of the new dynamic property * @param type Data type of the new dynamic property (null for no * restrictions) * @param readable Set to <code>true</code> if this property value * should be readable * @param writeable Set to <code>true</code> if this property value * should be writeable * * @throws UnsupportedOperationException anytime this method is called */ public void add(final String name, final Class<?> type, final boolean readable, final boolean writeable) { throw new java.lang.UnsupportedOperationException("readable/writable properties not supported"); } /** * Add a new dynamic property. * * @param property Property the new dynamic property to add. * * @throws IllegalArgumentException if name is null * @throws IllegalStateException if this DynaClass is currently * restricted, so no new properties can be added */ protected void add(final DynaProperty property) { if (property.getName() == null) { throw new IllegalArgumentException("Property name is missing."); } if (isRestricted()) { throw new IllegalStateException("DynaClass is currently restricted. No new properties can be added."); } // Check if property already exists if (propertiesMap.get(property.getName()) != null) { return; } // Create a new property array with the specified property final DynaProperty[] oldProperties = getDynaProperties(); final DynaProperty[] newProperties = new DynaProperty[oldProperties.length+1]; System.arraycopy(oldProperties, 0, newProperties, 0, oldProperties.length); newProperties[oldProperties.length] = property; // Update the properties setProperties(newProperties); } /** * Remove the specified dynamic property, and any associated data type, * readability, and writeability, from this dynamic class. * <strong>NOTE</strong> - This does <strong>NOT</strong> cause any * corresponding property values to be removed from DynaBean instances * associated with this DynaClass. * * @param name Name of the dynamic property to remove * * @throws IllegalArgumentException if name is null * @throws IllegalStateException if this DynaClass is currently * restricted, so no properties can be removed */ public void remove(final String name) { if (name == null) { throw new IllegalArgumentException("Property name is missing."); } if (isRestricted()) { throw new IllegalStateException("DynaClass is currently restricted. No properties can be removed."); } // Ignore if property doesn't exist if (propertiesMap.get(name) == null) { return; } // Create a new property array of without the specified property final DynaProperty[] oldProperties = getDynaProperties(); final DynaProperty[] newProperties = new DynaProperty[oldProperties.length-1]; int j = 0; for (int i = 0; i < oldProperties.length; i++) { if (!(name.equals(oldProperties[i].getName()))) { newProperties[j] = oldProperties[i]; j++; } } // Update the properties setProperties(newProperties); } /** * <p>Return a property descriptor for the specified property.</p> * * <p>If the property is not found and the <code>returnNull</code> indicator is * <code>true</code>, this method always returns <code>null</code>.</p> * * <p>If the property is not found and the <code>returnNull</code> indicator is * <code>false</code> a new property descriptor is created and returned (although * its not actually added to the DynaClass's properties). This is the default * beahviour.</p> * * <p>The reason for not returning a <code>null</code> property descriptor is that * <code>BeanUtils</code> uses this method to check if a property exists * before trying to set it - since these <i>Lazy</i> implementations automatically * add any new properties when they are set, returning <code>null</code> from * this method would defeat their purpose.</p> * * @param name Name of the dynamic property for which a descriptor * is requested * @return The dyna property for the specified name * * @throws IllegalArgumentException if no property name is specified */ @Override public DynaProperty getDynaProperty(final String name) { if (name == null) { throw new IllegalArgumentException("Property name is missing."); } DynaProperty dynaProperty = propertiesMap.get(name); // If it doesn't exist and returnNull is false // create a new DynaProperty if (dynaProperty == null && !isReturnNull() && !isRestricted()) { dynaProperty = new DynaProperty(name); } return dynaProperty; } /** * <p>Indicate whether a property actually exists.</p> * * <p><strong>N.B.</strong> Using <code>getDynaProperty(name) == null</code> * doesn't work in this implementation because that method might * return a DynaProperty if it doesn't exist (depending on the * <code>returnNull</code> indicator).</p> * * @param name The name of the property to check * @return <code>true</code> if there is a property of the * specified name, otherwise <code>false</code> * @throws IllegalArgumentException if no property name is specified */ public boolean isDynaProperty(final String name) { if (name == null) { throw new IllegalArgumentException("Property name is missing."); } return propertiesMap.get(name) == null ? false : true; } }
yippeesoft/NotifyTools
beanutils/src/main/java/org/apache/commons/beanutils/LazyDynaClass.java
Java
apache-2.0
13,983
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Net; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Elasticsearch.Net; using Nest; using Tests.Framework; namespace Tests.Framework.Integration { public class ElasticsearchNode : IDisposable { private static readonly object _lock = new object(); // <installpath> <> <plugin folder prefix> private readonly Dictionary<string, string> SupportedPlugins = new Dictionary<string, string> { { "delete-by-query", "delete-by-query" }, { "cloud-azure", "cloud-azure" } }; private readonly bool _doNotSpawnIfAlreadyRunning; private ObservableProcess _process; private IDisposable _processListener; public string Version { get; } public string Binary { get; } private string RoamingFolder { get; } private string RoamingClusterFolder { get; } public bool Started { get; private set; } public bool RunningIntegrations { get; private set; } public string Prefix { get; set; } public string ClusterName { get; } public string NodeName { get; } public string RepositoryPath { get; private set; } public ElasticsearchNodeInfo Info { get; private set; } public int Port { get; private set; } #if DOTNETCORE // Investigate problem with ManualResetEvent on CoreClr // Maybe due to .WaitOne() not taking exitContext? public class Signal { private readonly object _lock = new object(); private bool _notified; public Signal(bool initialState) { _notified = initialState; } public void Set() { lock (_lock) { if (!_notified) { _notified = true; Monitor.Pulse(_lock); } } } public bool WaitOne(TimeSpan timeout, bool exitContext) { lock (_lock) { bool exit = true; if (!_notified) exit = Monitor.Wait(_lock, timeout); return exit; } } } private readonly Subject<Signal> _blockingSubject = new Subject<Signal>(); public IObservable<Signal> BootstrapWork { get; } #else private readonly Subject<ManualResetEvent> _blockingSubject = new Subject<ManualResetEvent>(); public IObservable<ManualResetEvent> BootstrapWork { get; } #endif public ElasticsearchNode( string elasticsearchVersion, bool runningIntegrations, bool doNotSpawnIfAlreadyRunning, string prefix ) { _doNotSpawnIfAlreadyRunning = doNotSpawnIfAlreadyRunning; this.Version = elasticsearchVersion; this.RunningIntegrations = runningIntegrations; this.Prefix = prefix.ToLowerInvariant(); var suffix = Guid.NewGuid().ToString("N").Substring(0, 6); this.ClusterName = $"{this.Prefix}-cluster-{suffix}"; this.NodeName = $"{this.Prefix}-node-{suffix}"; this.BootstrapWork = _blockingSubject; if (!runningIntegrations) { this.Port = 9200; return; } var appData = GetApplicationDataDirectory(); this.RoamingFolder = Path.Combine(appData, "NEST", this.Version); this.RoamingClusterFolder = Path.Combine(this.RoamingFolder, "elasticsearch-" + elasticsearchVersion); this.RepositoryPath = Path.Combine(RoamingFolder, "repositories"); this.Binary = Path.Combine(this.RoamingClusterFolder, "bin", "elasticsearch") + ".bat"; Console.WriteLine("========> {0}", this.RoamingFolder); this.DownloadAndExtractElasticsearch(); } private string GetApplicationDataDirectory() { #if DOTNETCORE return Environment.GetEnvironmentVariable("APPDATA"); #else return Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); #endif } public IObservable<ElasticsearchMessage> Start(string[] additionalSettings = null) { if (!this.RunningIntegrations) return Observable.Empty<ElasticsearchMessage>(); this.Stop(); var timeout = TimeSpan.FromMinutes(1); #if DOTNETCORE var handle = new Signal(false); #else var handle = new ManualResetEvent(false); #endif if (_doNotSpawnIfAlreadyRunning) { var client = TestClient.GetClient(); var alreadyUp = client.RootNodeInfo(); if (alreadyUp.IsValid) { var checkPlugins = client.CatPlugins(); if (checkPlugins.IsValid) { foreach (var supportedPlugin in SupportedPlugins) { if (!checkPlugins.Records.Any(r => r.Component.Equals(supportedPlugin.Key))) throw new Exception($"Already running elasticsearch does not have supported plugin {supportedPlugin.Key} installed."); } this.Started = true; this.Port = 9200; this.Info = new ElasticsearchNodeInfo(alreadyUp.Version.Number, null, alreadyUp.Version.LuceneVersion); this._blockingSubject.OnNext(handle); if (!handle.WaitOne(timeout, true)) throw new Exception($"Could not launch tests on already running elasticsearch within {timeout}"); return Observable.Empty<ElasticsearchMessage>(); } } } var settings = new string[] { $"-Des.cluster.name={this.ClusterName}", $"-Des.node.name={this.NodeName}", $"-Des.path.repo={this.RepositoryPath}", $"-Des.script.inline=on", $"-Des.script.indexed=on" }.Concat(additionalSettings ?? Enumerable.Empty<string>()); this._process = new ObservableProcess(this.Binary, settings.ToArray()); var observable = Observable.Using(() => this._process, process => process.Start()) .Select(consoleLine => new ElasticsearchMessage(consoleLine)); this._processListener = observable.Subscribe(onNext: s => HandleConsoleMessage(s, handle)); if (!handle.WaitOne(timeout, true)) { this.Stop(); throw new Exception($"Could not start elasticsearch within {timeout}"); } return observable; } #if DOTNETCORE private void HandleConsoleMessage(ElasticsearchMessage s, Signal handle) #else private void HandleConsoleMessage(ElasticsearchMessage s, ManualResetEvent handle) #endif { //no need to snoop for metadata if we already started if (!this.RunningIntegrations || this.Started) return; ElasticsearchNodeInfo info; int port; if (s.TryParseNodeInfo(out info)) { this.Info = info; } else if (s.TryGetStartedConfirmation()) { var healthyCluster = this.Client().ClusterHealth(g => g.WaitForStatus(WaitForStatus.Yellow).Timeout(TimeSpan.FromSeconds(30))); if (healthyCluster.IsValid) { this._blockingSubject.OnNext(handle); this.Started = true; } else { this._blockingSubject.OnError(new Exception("Did not see a healthy cluster after the node started for 30 seconds")); handle.Set(); this.Stop(); } } else if (s.TryGetPortNumber(out port)) { this.Port = port; } } private void DownloadAndExtractElasticsearch() { lock (_lock) { var zip = $"elasticsearch-{this.Version}.zip"; var downloadUrl = $"https://download.elasticsearch.org/elasticsearch/release/org/elasticsearch/distribution/zip/elasticsearch/{this.Version}/{zip}"; var localZip = Path.Combine(this.RoamingFolder, zip); Directory.CreateDirectory(this.RoamingFolder); if (!File.Exists(localZip)) { Console.WriteLine($"Download elasticsearch: {this.Version} from {downloadUrl}"); new WebClient().DownloadFile(downloadUrl, localZip); Console.WriteLine($"Downloaded elasticsearch: {this.Version}"); } if (!Directory.Exists(this.RoamingClusterFolder)) { Console.WriteLine($"Unziping elasticsearch: {this.Version} ..."); ZipFile.ExtractToDirectory(localZip, this.RoamingFolder); } InstallPlugins(); //hunspell config var hunspellFolder = Path.Combine(this.RoamingClusterFolder, "config", "hunspell", "en_US"); var hunspellPrefix = Path.Combine(hunspellFolder, "en_US"); if (!File.Exists(hunspellPrefix + ".dic")) { Directory.CreateDirectory(hunspellFolder); //File.Create(hunspellPrefix + ".dic"); File.WriteAllText(hunspellPrefix + ".dic", "1\r\nabcdegf"); //File.Create(hunspellPrefix + ".aff"); File.WriteAllText(hunspellPrefix + ".aff", "SET UTF8\r\nSFX P Y 1\r\nSFX P 0 s"); } var analysFolder = Path.Combine(this.RoamingClusterFolder, "config", "analysis"); if (!Directory.Exists(analysFolder)) Directory.CreateDirectory(analysFolder); var fopXml = Path.Combine(analysFolder, "fop") + ".xml"; if (!File.Exists(fopXml)) File.WriteAllText(fopXml, "<languages-info />"); var customStems = Path.Combine(analysFolder, "custom_stems") + ".txt"; if (!File.Exists(customStems)) File.WriteAllText(customStems, ""); var stopwords = Path.Combine(analysFolder, "stopwords") + ".txt"; if (!File.Exists(stopwords)) File.WriteAllText(stopwords, ""); } } private void InstallPlugins() { var pluginBat = Path.Combine(this.RoamingClusterFolder, "bin", "plugin") + ".bat"; foreach (var plugin in SupportedPlugins) { var installPath = plugin.Key; var localPath = plugin.Value; var pluginFolder = Path.Combine(this.RoamingClusterFolder, "plugins", localPath); if (!Directory.Exists(this.RoamingClusterFolder)) continue; // assume plugin already installed if (Directory.Exists(pluginFolder)) continue; Console.WriteLine($"Installing elasticsearch plugin: {localPath} ..."); var timeout = TimeSpan.FromSeconds(60); var handle = new ManualResetEvent(false); Task.Run(() => { using (var p = new ObservableProcess(pluginBat, "install", installPath)) { var o = p.Start(); Console.WriteLine($"Calling: {pluginBat} install {installPath}"); o.Subscribe(e=>Console.WriteLine(e), (e) => { Console.WriteLine($"Failed installing elasticsearch plugin: {localPath} "); handle.Set(); throw e; }, () => { Console.WriteLine($"Finished installing elasticsearch plugin: {localPath} exit code: {p.ExitCode}"); handle.Set(); }); if (!handle.WaitOne(timeout, true)) throw new Exception($"Could not install ${installPath} within {timeout}"); } }); if (!handle.WaitOne(timeout, true)) throw new Exception($"Could not install ${installPath} within {timeout}"); } } public IElasticClient Client(Func<Uri, IConnectionPool> createPool, Func<ConnectionSettings, ConnectionSettings> settings) { var port = this.Started ? this.Port : 9200; settings = settings ?? (s => s); var client = TestClient.GetClient(s => AppendClusterNameToHttpHeaders(settings(s)), port, createPool); return client; } public IElasticClient Client(Func<ConnectionSettings, ConnectionSettings> settings = null) { var port = this.Started ? this.Port : 9200; settings = settings ?? (s => s); var client = TestClient.GetClient(s => AppendClusterNameToHttpHeaders(settings(s)), port); return client; } private ConnectionSettings AppendClusterNameToHttpHeaders(ConnectionSettings settings) { IConnectionConfigurationValues values = settings; var headers = values.Headers ?? new NameValueCollection(); headers.Add("ClusterName", this.ClusterName); return settings; } public void Stop() { if (!this.RunningIntegrations || !this.Started) return; this.Started = false; Console.WriteLine($"Stopping... ran integrations: {this.RunningIntegrations}"); Console.WriteLine($"Node started: {this.Started} on port: {this.Port} using PID: {this.Info?.Pid}"); this._process?.Dispose(); this._processListener?.Dispose(); if (this.Info != null && this.Info.Pid.HasValue) { var esProcess = Process.GetProcessById(this.Info.Pid.Value); Console.WriteLine($"Killing elasticsearch PID {this.Info.Pid}"); esProcess.Kill(); esProcess.WaitForExit(5000); esProcess.Close(); } if (this._doNotSpawnIfAlreadyRunning) return; var dataFolder = Path.Combine(this.RoamingClusterFolder, "data", this.ClusterName); if (Directory.Exists(dataFolder)) { Console.WriteLine($"attempting to delete cluster data: {dataFolder}"); Directory.Delete(dataFolder, true); } //var logPath = Path.Combine(this.RoamingClusterFolder, "logs"); //var files = Directory.GetFiles(logPath, this.ClusterName + "*.log"); //foreach (var f in files) //{ // Console.WriteLine($"attempting to delete log file: {f}"); // File.Delete(f); //} if (Directory.Exists(this.RepositoryPath)) { Console.WriteLine("attempting to delete repositories"); Directory.Delete(this.RepositoryPath, true); } } public void Dispose() { this.Stop(); } } public class ElasticsearchMessage { /* [2015-05-26 20:05:07,681][INFO ][node ] [Nick Fury] version[1.5.2], pid[7704], build[62ff986/2015-04-27T09:21:06Z] [2015-05-26 20:05:07,681][INFO ][node ] [Nick Fury] initializing ... [2015-05-26 20:05:07,681][INFO ][plugins ] [Nick Fury] loaded [], sites [] [2015-05-26 20:05:10,790][INFO ][node ] [Nick Fury] initialized [2015-05-26 20:05:10,821][INFO ][node ] [Nick Fury] starting ... [2015-05-26 20:05:11,041][INFO ][transport ] [Nick Fury] bound_address {inet[/0:0:0:0:0:0:0:0:9300]}, publish_address {inet[/192.168.194.146:9300]} [2015-05-26 20:05:11,056][INFO ][discovery ] [Nick Fury] elasticsearch-martijnl/yuiyXva3Si6sQE5tY_9CHg [2015-05-26 20:05:14,103][INFO ][cluster.service ] [Nick Fury] new_master [Nick Fury][yuiyXva3Si6sQE5tY_9CHg][WIN-DK60SLEMH8C][inet[/192.168.194.146:9300]], reason: zen-disco-join (elected_as_master) [2015-05-26 20:05:14,134][INFO ][gateway ] [Nick Fury] recovered [0] indices into cluster_state [2015-05-26 20:05:14,150][INFO ][http ] [Nick Fury] bound_address {inet[/0:0:0:0:0:0:0:0:9200]}, publish_address {inet[/192.168.194.146:9200]} [2015-05-26 20:05:14,150][INFO ][node ] [Nick Fury] started */ public DateTime Date { get; } public string Level { get; } public string Section { get; } public string Node { get; } public string Message { get; } private static readonly Regex ConsoleLineParser = new Regex(@"\[(?<date>.*?)\]\[(?<level>.*?)\]\[(?<section>.*?)\] \[(?<node>.*?)\] (?<message>.+)"); public ElasticsearchMessage(string consoleLine) { Console.WriteLine(consoleLine); if (string.IsNullOrEmpty(consoleLine)) return; var match = ConsoleLineParser.Match(consoleLine); if (!match.Success) return; var dateString = match.Groups["date"].Value.Trim(); Date = DateTime.ParseExact(dateString, "yyyy-MM-dd HH:mm:ss,fff", CultureInfo.CurrentCulture); Level = match.Groups["level"].Value.Trim(); Section = match.Groups["section"].Value.Trim().Replace("org.elasticsearch.", ""); Node = match.Groups["node"].Value.Trim(); Message = match.Groups["message"].Value.Trim(); } private static readonly Regex InfoParser = new Regex(@"version\[(?<version>.*)\], pid\[(?<pid>.*)\], build\[(?<build>.+)\]"); public bool TryParseNodeInfo(out ElasticsearchNodeInfo nodeInfo) { nodeInfo = null; if (this.Section != "node") return false; var match = InfoParser.Match(this.Message); if (!match.Success) return false; var version = match.Groups["version"].Value.Trim(); var pid = match.Groups["pid"].Value.Trim(); var build = match.Groups["build"].Value.Trim(); nodeInfo = new ElasticsearchNodeInfo(version, pid, build); return true; } public bool TryGetStartedConfirmation() { if (this.Section != "node") return false; return this.Message == "started"; } private static readonly Regex PortParser = new Regex(@"bound_address(es)? {.+\:(?<port>\d+)}"); public bool TryGetPortNumber(out int port) { port = 0; if (this.Section != "http") return false; var match = PortParser.Match(this.Message); if (!match.Success) return false; var portString = match.Groups["port"].Value.Trim(); port = int.Parse(portString); return true; } } public class ElasticsearchNodeInfo { public string Version { get; } public int? Pid { get; } public string Build { get; } public ElasticsearchNodeInfo(string version, string pid, string build) { this.Version = version; if (!string.IsNullOrEmpty(pid)) Pid = int.Parse(pid); Build = build; } } }
cstlaurent/elasticsearch-net
src/Tests/Framework/Integration/Process/ElasticsearchNode.cs
C#
apache-2.0
16,547
/* * Copyright (c) 2011-2015 Spotify AB * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.spotify.google.cloud.pubsub.client.integration; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import static com.google.common.util.concurrent.MoreExecutors.getExitingScheduledExecutorService; class ProgressMeter implements Runnable { private static final double NANOS_PER_MS = TimeUnit.MILLISECONDS.toNanos(1); private static final long NANOS_PER_S = TimeUnit.SECONDS.toNanos(1); private final AtomicLong totalLatency = new AtomicLong(); private final AtomicLong totalOperations = new AtomicLong(); private final String unit; private final boolean reportLatency; private long startTime; private long lastRows; private long lastTime; private long lastLatency; private static final ScheduledExecutorService EXECUTOR = getExitingScheduledExecutorService( new ScheduledThreadPoolExecutor(1)); public ProgressMeter(final String unit) { this(unit, false); } public ProgressMeter(final String unit, final boolean reportLatency) { this.unit = unit; this.reportLatency = reportLatency; this.startTime = System.nanoTime(); this.lastTime = startTime; EXECUTOR.scheduleAtFixedRate(this, 1, 1, TimeUnit.SECONDS); } public void inc() { this.totalOperations.incrementAndGet(); } public void inc(final long ops) { this.totalOperations.addAndGet(ops); } public void inc(final long ops, final long latency) { this.totalOperations.addAndGet(ops); this.totalLatency.addAndGet(latency); } @Override public void run() { final long now = System.nanoTime(); final long totalOperations = this.totalOperations.get(); final long totalLatency = this.totalLatency.get(); final long deltaOps = totalOperations - lastRows; final long deltaTime = now - lastTime; final long deltaLatency = totalLatency - lastLatency; lastRows = totalOperations; lastTime = now; lastLatency = totalLatency; final long operations = (deltaTime == 0) ? 0 : (NANOS_PER_S * deltaOps) / deltaTime; final double avgLatency = (deltaOps == 0) ? 0 : deltaLatency / (NANOS_PER_MS * deltaOps); final long seconds = TimeUnit.NANOSECONDS.toSeconds(now - startTime); System.out.printf("%,4ds: %,12d %s/s.", seconds, operations, unit); if (reportLatency) { System.out.printf(" %,10.3f ms avg latency.", avgLatency); } System.out.printf(" (total: %,12d)\n", totalOperations); System.out.flush(); } }
skinzer/async-google-pubsub-client
src/test/java/com/spotify/google/cloud/pubsub/client/integration/ProgressMeter.java
Java
apache-2.0
3,190
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License a * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.llap.metrics; import avro.shaded.com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import java.io.Serializable; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.metrics2.MetricsCollector; import org.apache.hadoop.metrics2.MetricsInfo; import org.apache.hadoop.metrics2.MetricsSource; import org.apache.hadoop.metrics2.annotation.Metric; import org.apache.hadoop.metrics2.annotation.Metrics; import org.apache.hadoop.metrics2.lib.MutableCounterLong; /** * Wrapper around a read/write lock to collect the lock wait times. * Instances of this wrapper class can be used to collect/accumulate the wai * times around R/W locks. This is helpful if the source of a performance issue * might be related to lock contention and you need to identify the actual * locks. Instances of this class can be wrapped around any <code>ReadWriteLock * </code> implementation. */ public class ReadWriteLockMetrics implements ReadWriteLock { private LockWrapper readLock; ///< wrapper around original read lock private LockWrapper writeLock; ///< wrapper around original write lock /** * Helper class to compare two <code>LockMetricSource</code> instances. * This <code>Comparator</code> class can be used to sort a list of <code> * LockMetricSource</code> instances in descending order by their total lock * wait time. */ public static class MetricsComparator implements Comparator<MetricsSource>, Serializable { private static final long serialVersionUID = -1; @Override public int compare(MetricsSource o1, MetricsSource o2) { if (o1 != null && o2 != null && o1 instanceof LockMetricSource && o2 instanceof LockMetricSource) { LockMetricSource lms1 = (LockMetricSource)o1; LockMetricSource lms2 = (LockMetricSource)o2; long totalMs1 = (lms1.readLockWaitTimeTotal.value() / 1000000L) + (lms1.writeLockWaitTimeTotal.value() / 1000000L); long totalMs2 = (lms2.readLockWaitTimeTotal.value() / 1000000L) + (lms2.writeLockWaitTimeTotal.value() / 1000000L); // sort descending by total lock time if (totalMs1 < totalMs2) { return 1; } if (totalMs1 > totalMs2) { return -1; } // sort by label (ascending) if lock time is the same return lms1.lockLabel.compareTo(lms2.lockLabel); } return 0; } } /** * Wraps a <code>ReadWriteLock</code> into a monitored lock if required by * configuration. This helper is checking the <code> * hive.llap.lockmetrics.collect</code> configuration option and wraps the * passed in <code>ReadWriteLock</code> into a monitoring container if the * option is set to <code>true</code>. Otherwise, the original (passed in) * lock instance is returned unmodified. * * @param conf Configuration instance to check for LLAP conf options * @param lock The <code>ReadWriteLock</code> to wrap for monitoring * @param metrics The target container for locking metrics * @see #createLockMetricsSource */ public static ReadWriteLock wrap(Configuration conf, ReadWriteLock lock, MetricsSource metrics) { Preconditions.checkNotNull(lock, "Caller has to provide valid input lock"); boolean needsWrap = false; if (null != conf) { needsWrap = HiveConf.getBoolVar(conf, HiveConf.ConfVars.LLAP_COLLECT_LOCK_METRICS); } if (false == needsWrap) { return lock; } Preconditions.checkNotNull(metrics, "Caller has to procide group specific metrics source"); return new ReadWriteLockMetrics(lock, metrics); } /** * Factory method for new metric collections. * You can create and use a single <code>MetricsSource</code> collection for * multiple R/W locks. This makes sense if several locks belong to a single * group and you're then interested in the accumulated values for the whole * group, rather than the single lock instance. The passed in label is * supposed to identify the group uniquely. * * @param label The group identifier for lock statistics */ public static MetricsSource createLockMetricsSource(String label) { Preconditions.checkNotNull(label); Preconditions.checkArgument(!label.contains("\""), "Label can't contain quote (\")"); return new LockMetricSource(label); } /** * Returns a list with all created <code>MetricsSource</code> instances for * the R/W lock metrics. The returned list contains the instances that were * previously created via the <code>createLockMetricsSource</code> function. * * @return A list of all R/W lock based metrics sources */ public static List<MetricsSource> getAllMetricsSources() { ArrayList<MetricsSource> ret = null; synchronized (LockMetricSource.allInstances) { ret = new ArrayList<>(LockMetricSource.allInstances); } return ret; } /// Enumeration of metric info names and descriptions @VisibleForTesting public enum LockMetricInfo implements MetricsInfo { ReadLockWaitTimeTotal("The total wait time for read locks in nanoseconds"), ReadLockWaitTimeMax("The maximum wait time for a read lock in nanoseconds"), ReadLockCount("Total amount of read lock requests"), WriteLockWaitTimeTotal( "The total wait time for write locks in nanoseconds"), WriteLockWaitTimeMax( "The maximum wait time for a write lock in nanoseconds"), WriteLockCount("Total amount of write lock requests"); private final String description; ///< metric description /** * Creates a new <code>MetricsInfo</code> with the given description. * * @param desc The description of the info */ private LockMetricInfo(String desc) { description = desc; } @Override public String description() { return this.description; } } /** * Source of the accumulated lock times and counts. * Instances of this <code>MetricSource</code> can be created via the static * factory method <code>createLockMetricsSource</code> and shared across * multiple instances of the outer <code>ReadWriteLockMetric</code> class. */ @Metrics(about = "Lock Metrics", context = "locking") private static class LockMetricSource implements MetricsSource { private static final ArrayList<MetricsSource> allInstances = new ArrayList<>(); private final String lockLabel; ///< identifier for the group of locks /// accumulated wait time for read locks @Metric MutableCounterLong readLockWaitTimeTotal; /// highest wait time for read locks @Metric MutableCounterLong readLockWaitTimeMax; /// total number of read lock calls @Metric MutableCounterLong readLockCounts; /// accumulated wait time for write locks @Metric MutableCounterLong writeLockWaitTimeTotal; /// highest wait time for write locks @Metric MutableCounterLong writeLockWaitTimeMax; /// total number of write lock calls @Metric MutableCounterLong writeLockCounts; /** * Creates a new metrics collection instance. * Several locks can share a single <code>MetricsSource</code> instances * where all of them increment the metrics counts together. This can be * interesting to have a single instance for a group of related locks. The * group should then be identified by the label. * * @param label The identifier of the metrics collection */ private LockMetricSource(String label) { lockLabel = label; readLockWaitTimeTotal = new MutableCounterLong(LockMetricInfo.ReadLockWaitTimeTotal, 0); readLockWaitTimeMax = new MutableCounterLong(LockMetricInfo.ReadLockWaitTimeMax, 0); readLockCounts = new MutableCounterLong(LockMetricInfo.ReadLockCount, 0); writeLockWaitTimeTotal = new MutableCounterLong(LockMetricInfo.WriteLockWaitTimeTotal, 0); writeLockWaitTimeMax = new MutableCounterLong(LockMetricInfo.WriteLockWaitTimeMax, 0); writeLockCounts = new MutableCounterLong(LockMetricInfo.WriteLockCount, 0); synchronized (allInstances) { allInstances.add(this); } } @Override public void getMetrics(MetricsCollector collector, boolean all) { collector.addRecord(this.lockLabel) .setContext("Locking") .addCounter(LockMetricInfo.ReadLockWaitTimeTotal, readLockWaitTimeTotal.value()) .addCounter(LockMetricInfo.ReadLockWaitTimeMax, readLockWaitTimeMax.value()) .addCounter(LockMetricInfo.ReadLockCount, readLockCounts.value()) .addCounter(LockMetricInfo.WriteLockWaitTimeTotal, writeLockWaitTimeTotal.value()) .addCounter(LockMetricInfo.WriteLockWaitTimeMax, writeLockWaitTimeMax.value()) .addCounter(LockMetricInfo.WriteLockCount, writeLockCounts.value()); } @Override public String toString() { long avgRead = 0L; long avgWrite = 0L; long totalMillis = 0L; if (0 < readLockCounts.value()) { avgRead = readLockWaitTimeTotal.value() / readLockCounts.value(); } if (0 < writeLockCounts.value()) { avgWrite = writeLockWaitTimeTotal.value() / writeLockCounts.value(); } totalMillis = (readLockWaitTimeTotal.value() / 1000000L) + (writeLockWaitTimeTotal.value() / 1000000L); StringBuffer sb = new StringBuffer(); sb.append("{ \"type\" : \"R/W Lock Stats\", \"label\" : \""); sb.append(lockLabel); sb.append("\", \"totalLockWaitTimeMillis\" : "); sb.append(totalMillis); sb.append(", \"readLock\" : { \"count\" : "); sb.append(readLockCounts.value()); sb.append(", \"avgWaitTimeNanos\" : "); sb.append(avgRead); sb.append(", \"maxWaitTimeNanos\" : "); sb.append(readLockWaitTimeMax.value()); sb.append(" }, \"writeLock\" : { \"count\" : "); sb.append(writeLockCounts.value()); sb.append(", \"avgWaitTimeNanos\" : "); sb.append(avgWrite); sb.append(", \"maxWaitTimeNanos\" : "); sb.append(writeLockWaitTimeMax.value()); sb.append(" } }"); return sb.toString(); } } /** * Inner helper class to wrap the original lock with a monitored one. * This inner class is delegating all actual locking operations to the wrapped * lock, while itself is only responsible to measure the time that it took to * acquire a specific lock. */ private static class LockWrapper implements Lock { /// the lock to delegate the work to private final Lock wrappedLock; /// total lock wait time in nanos private final MutableCounterLong lockWaitTotal; /// highest lock wait time (max) private final MutableCounterLong lockWaitMax; /// number of lock counts private final MutableCounterLong lockWaitCount; /** * Creates a new wrapper around an existing lock. * * @param original The original lock to wrap by this monitoring lock * @param total The (atomic) counter to increment for total lock wait time * @param max The (atomic) counter to adjust to the maximum wait time * @param cnt The (atomic) counter to increment with each lock call */ LockWrapper(Lock original, MutableCounterLong total, MutableCounterLong max, MutableCounterLong cnt) { wrappedLock = original; this.lockWaitTotal = total; this.lockWaitMax = max; this.lockWaitCount = cnt; } @Override public void lock() { long start = System.nanoTime(); wrappedLock.lock(); incrementBy(System.nanoTime() - start); } @Override public void lockInterruptibly() throws InterruptedException { long start = System.nanoTime(); wrappedLock.lockInterruptibly(); incrementBy(System.nanoTime() - start); } @Override public boolean tryLock() { return wrappedLock.tryLock(); } @Override public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { long start = System.nanoTime(); boolean ret = wrappedLock.tryLock(time, unit); incrementBy(System.nanoTime() - start); return ret; } @Override public void unlock() { wrappedLock.unlock(); } @Override public Condition newCondition() { return wrappedLock.newCondition(); } /** * Helper to increment the monitoring counters. * Called from the lock implementations to increment the total/max/coun * values of the monitoring counters. * * @param waitTime The actual wait time (in nanos) for the lock operation */ private void incrementBy(long waitTime) { this.lockWaitTotal.incr(waitTime); this.lockWaitCount.incr(); if (waitTime > this.lockWaitMax.value()) { this.lockWaitMax.incr(waitTime - this.lockWaitMax.value()); } } } /** * Creates a new monitoring wrapper around a R/W lock. * The so created wrapper instance can be used instead of the original R/W * lock, which then automatically updates the monitoring values in the <code> * MetricsSource</code>. This allows easy "slide in" of lock monitoring where * originally only a standard R/W lock was used. * * @param lock The original R/W lock to wrap for monitoring * @param metrics The target for lock monitoring */ private ReadWriteLockMetrics(ReadWriteLock lock, MetricsSource metrics) { Preconditions.checkNotNull(lock); Preconditions.checkArgument(metrics instanceof LockMetricSource, "Invalid MetricsSource"); LockMetricSource lms = (LockMetricSource)metrics; readLock = new LockWrapper(lock.readLock(), lms.readLockWaitTimeTotal, lms.readLockWaitTimeMax, lms.readLockCounts); writeLock = new LockWrapper(lock.writeLock(), lms.writeLockWaitTimeTotal, lms.writeLockWaitTimeMax, lms.writeLockCounts); } @Override public Lock readLock() { return readLock; } @Override public Lock writeLock() { return writeLock; } }
alanfgates/hive
llap-common/src/java/org/apache/hadoop/hive/llap/metrics/ReadWriteLockMetrics.java
Java
apache-2.0
15,607
package leetcode; /** * Given a non negative integer number num. For every numbers i in the range 0 ≤ * i ≤ num calculate the number of 1's in their binary representation and return * them as an array. * Example: * For num = 5 you should return [0,1,1,2,1,2]. * Follow up: * It is very easy to come up with a solution with run time * O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a * single pass? * Space complexity should be O(n). * Can you do it like a boss? Do it without using any builtin function like * __builtin_popcount in c++ or in any other language. * Show Hint */ public class Counting_Bits { public static void main(String[] args) { // 110 010 // System.err.println(3 & 2); System.err.println(countBits(100000000).toString()); } public static int[] countBits(int num) { int[] rt = new int[num]; for (int i = 0; i < num; i++) { int count = 0; int j = i; while(j != 0) { j = j & (j-1); count ++; } rt[i] = count; } return rt; } }
pistolove/Lettcode
lettcode/src/leetcode/Counting_Bits.java
Java
apache-2.0
1,193
package org.directcode.ide.core; import lombok.Getter; import org.directcode.ide.api.*; import org.directcode.ide.api.MenuBar; import org.directcode.ide.plugins.PluginManager; import org.directcode.ide.util.Logger; import org.directcode.ide.window.EditorWindow; import org.directcode.ide.window.laf.LookAndFeelManager; import javax.swing.*; import javax.swing.plaf.nimbus.NimbusLookAndFeel; import java.awt.*; import java.io.File; /** * Main Entrypoint for the IDE * @since 0.0.1 */ public class Aluminum { /** * Primary Instance of our IDE. */ @Getter private static Aluminum IDE; /** * Tab size for the IDE. */ public static int tabSize = 4; /** * Location of the plugins directory. */ public static File pluginsDir; /** * The primary window for our application. */ @Getter private EditorWindow editor; /** * Logger for the application. */ private static Logger logger; /** * PluginManager for our IDE. */ private PluginManager pluginManager; /** * Start the application. */ private void start() { // Initialize the look and feel initializeLookAndFeel(); // Start the GUI createGui(); logger = new Logger("Aluminum"); logger.info("Starting"); // Initialize the Plugin Manager pluginManager = new PluginManager(); pluginManager.start(); } /** * Create the GUI. */ private void createGui() { editor = new EditorWindow(); } /** * Initialize the Look and Feel for our application. */ private void initializeLookAndFeel() { LookAndFeelManager lookAndFeelManager = new LookAndFeelManager(new NimbusLookAndFeel()); lookAndFeelManager.setLAF(); } /** * Initiate a shutdown of Aluminum. */ public void stop() { logger.info("Stopping"); pluginManager.stop(); System.exit(0); } /** * Main entrypoint. * * @param args Arguments for application in a String array */ public static void main(String[] args) { long startTime = System.currentTimeMillis(); // Ensure the IDE isn't running on a headless system. if (GraphicsEnvironment.isHeadless()) { throw new HeadlessException("Unable to detect display"); } // Initialize the plugins directory if it does not exist pluginsDir = new File("plugins/"); pluginsDir.mkdir(); // Initialize the class, and start IDE = new Aluminum(); IDE.start(); long endStartTime = System.currentTimeMillis(); logger.debug("Startup time: " + ((endStartTime - startTime))); MenuBar.addMenuItem(0, new JMenu("Test")); } }
logangorence/Aluminum
src/main/java/org/directcode/ide/core/Aluminum.java
Java
apache-2.0
2,738
using De.Osthus.Ambeth.Merge; namespace De.Osthus.Ambeth.Bytecode { /** * Base class for entities that have access to the {@link IEntityFactory} */ public abstract class AbstractEntity { protected IEntityFactory entityFactory; protected AbstractEntity(IEntityFactory entityFactory) { this.entityFactory = entityFactory; } } }
Dennis-Koch/ambeth
ambeth/Ambeth.Test/ambeth/bytecode/AbstractEntity.cs
C#
apache-2.0
398
package org.lantern.monitoring; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.util.HashMap; import java.util.Map; import org.apache.commons.io.IOUtils; import org.lantern.HttpURLClient; import org.lantern.JsonUtils; import org.lantern.LanternConstants; /** * API for posting and querying stats to/from statshub. */ public class StatshubAPI extends HttpURLClient { public StatshubAPI() { this(null); } public StatshubAPI(InetSocketAddress proxyAddress) { super(proxyAddress); } /** * Submit stats for an instance to statshub. * * @param instanceId * @param userGuid * @param countryCode * @param isFallback * @param stats * @throws Exception */ public void postInstanceStats( String instanceId, String userGuid, String countryCode, boolean isFallback, Stats stats) throws Exception { postStats("instance_" + instanceId, userGuid, countryCode, isFallback, stats, null); } /** * Submit stats for a user to statshub. * * @param userGuid * @param countryCode * @param stats * @throws Exception */ public void postUserStats( String userGuid, String countryCode, Stats stats) throws Exception { postStats("user_" + userGuid, userGuid, countryCode, false, stats, null); } /** * Submits stats to statshub. * * @param id * the stat id (instanceId or userId) * @param userGuid * the userId (if applicable) * @param countryCode * the countryCode * @param addFallbackDim * if true, the id will be added to the dims as "fallback" * @param stats * the stats * @param dims * additional dimensions to post with the stats */ public void postStats( String id, String userGuid, String countryCode, boolean addFallbackDim, Stats stats, Map<String, String> additionalDims) throws Exception { Map<String, Object> request = new HashMap<String, Object>(); Map<String, String> dims = new HashMap<String, String>(); if (additionalDims != null) { dims.putAll(additionalDims); } dims.put("user", userGuid); dims.put("country", countryCode); if (addFallbackDim) { dims.put("fallback", id); } request.put("dims", dims); request.put("counters", stats.getCounters()); request.put("increments", stats.getIncrements()); request.put("gauges", stats.getGauges()); request.put("members", stats.getMembers()); HttpURLConnection conn = null; OutputStream out = null; try { String url = urlFor(id); conn = newConn(url); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/json"); out = conn.getOutputStream(); JsonUtils.OBJECT_MAPPER.writeValue(out, request); int code = conn.getResponseCode(); if (code != 200) { // will be logged below throw new Exception("Got " + code + " response for " + url + ":\n" + conn.getResponseMessage()); } } finally { IOUtils.closeQuietly(out); if (conn != null) { conn.disconnect(); } } } public StatsResponse getStats(final String dimension) throws IOException { HttpURLConnection conn = null; InputStream in = null; try { String url = urlFor(dimension + "/"); conn = newConn(url); conn.setRequestMethod("GET"); conn.setRequestProperty("Content-Type", "application/json"); in = conn.getInputStream(); int code = conn.getResponseCode(); if (code != 200) { // will be logged below throw new IOException("Got " + code + " response for " + url + ":\n" + conn.getResponseMessage()); } return JsonUtils.decode(in, StatsResponse.class); } finally { IOUtils.closeQuietly(in); if (conn != null) { conn.disconnect(); } } } private String urlFor(String instanceId) { return LanternConstants.statshubBaseAddress + instanceId; } }
getlantern/lantern-common
src/main/java/org/lantern/monitoring/StatshubAPI.java
Java
apache-2.0
4,868
package fi.oulu.tol.sqat; public class ConjuredItem extends Item{ public ConjuredItem(String name, int sellIn, int quality){ super(name, sellIn, quality); } }
Domuska/GildedRose
src/fi/oulu/tol/sqat/ConjuredItem.java
Java
apache-2.0
174
/* * Copyright (c) 2020 VMware Inc. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hillview.table.filters; import org.hillview.table.api.ITable; import org.hillview.table.api.ITableFilter; import org.hillview.table.api.ITableFilterDescription; import org.hillview.utils.Linq; /** * Describes an array of RangeFilters and an optional complement. */ @SuppressWarnings("CanBeFinal") public class RangeFilterArrayDescription implements ITableFilterDescription { public RangeFilterDescription[] filters = new RangeFilterDescription[0]; public boolean complement; @Override public ITableFilter getFilter(ITable table) { String[] cols = Linq.map(this.filters, f -> f.cd.name, String.class); table.getLoadedColumns(cols); ITableFilter[] filters = Linq.map(this.filters, f -> f.getFilter(table), ITableFilter.class); ITableFilter result = new AndFilter(filters); if (this.complement) result = new NotFilter(result); return result; } }
mbudiu-vmw/hiero
platform/src/main/java/org/hillview/table/filters/RangeFilterArrayDescription.java
Java
apache-2.0
1,601
package explorviz.shared.usertracking.records.application; import explorviz.shared.usertracking.UsertrackingRecord; public class BackToLandscapeRecord extends UsertrackingRecord { @Override public String csvSerialize() { return ""; } }
ExplorViz/ExplorViz
src/explorviz/shared/usertracking/records/application/BackToLandscapeRecord.java
Java
apache-2.0
243
/* Cameronism.Csv * Copyright © 2016 Cameronism.com. All Rights Reserved. * * Apache License 2.0 - http://www.apache.org/licenses/LICENSE-2.0 */ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace Cameronism.Csv { public interface IFlattener { Type Type { get; } IList<IMemberInfo> Members { get; } IList<object> Flatten(object item); } }
cameronism/Cameronism.Csv
Cameronism.CSV/IFlattener.cs
C#
apache-2.0
455
/* * Copyright 2009 Kjetil Valstadsve * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 vanadis.launcher; import org.osgi.framework.*; import org.osgi.service.packageadmin.PackageAdmin; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import vanadis.blueprints.BundleResolver; import vanadis.blueprints.BundleSpecification; import vanadis.blueprints.SystemSpecification; import vanadis.core.collections.Generic; import vanadis.common.io.Location; import vanadis.core.lang.EntryPoint; import vanadis.core.lang.Not; import vanadis.core.lang.VarArgs; import vanadis.common.time.TimeSpan; import java.io.PrintStream; import java.net.URI; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; @EntryPoint("Subclasses discovered at runtime") public abstract class AbstractOSGiLauncher implements OSGiLauncher { private final AtomicBoolean launched = new AtomicBoolean(false); private final AtomicBoolean failedLaunch = new AtomicBoolean(false); private final AtomicBoolean closed = new AtomicBoolean(false); private URI home; private Location location; private List<BundleResolver> bundleResolvers; private SystemSpecification systemSpecification; private final List<ServiceRegistration> bundleRegistrations = Generic.list(); private final List<ServiceRegistration> moduleRegistrations = Generic.list(); private LaunchResult launchResult; private BundleContext bundleContext; private long bootstrapId; private Dictionary<?, ?> bundleHeaders; @Override public final LaunchResult getLaunchResult() { requireLaunched(); return launchResult; } @Override public final void close(PrintStream stream) { if (!closed.getAndSet(true)) { unregisterAll(stream); stopFramework(); } } @Override public final String getProviderInfo() { requireLaunched(); return bundleHeaders.get(Constants.BUNDLE_SYMBOLICNAME) + " " + bundleHeaders.get(Constants.BUNDLE_VERSION); } @SuppressWarnings({"ThrowCaughtLocally"}) @Override public final LaunchResult launch(URI home, Location location, List<BundleResolver> bundleResolvers, SystemSpecification systemSpecification) { setLaunchState(home, location, bundleResolvers, systemSpecification); try { assertPrelaunchState(this.bundleContext == null); BundleContext bundleContext = launchedBundleContext(); if (bundleContext == null) { throw new IllegalStateException(this + " produced null bundle context!"); } List<Bundle> bundles = startAutoBundles(bundleContext); setLaunchResultState(bundleContext, bundles); registerBundles(); registerModules(); return launchResult; } catch (RuntimeException e) { failedLaunch.set(true); throw e; } } private void setLaunchResultState(BundleContext bundleContext, List<Bundle> bundles) { this.launchResult = new LaunchResult(bundleContext, bundles); this.bundleContext = launchResult.getBundleContext(); Bundle bundle = this.bundleContext.getBundle(); this.bootstrapId = bundle.getBundleId(); this.bundleHeaders = bundle.getHeaders(); } @Override public final boolean isLaunched() { return launched.get() && !failedLaunch.get(); } @Override public final URI getHome() { requireLaunched(); return home; } @Override public final URI getRepo() { return systemSpecification.getRepo(); } @Override public final Location getLocation() { requireLaunched(); return location; } private void assertPrelaunchState(boolean check) { assert check : this + " was launched twice!"; } private void requireLaunched() { if (!launched.get()) { throw new IllegalStateException(this + " not launched"); } if (failedLaunch.get()) { throw new IllegalStateException(this + " failed launch, should be discarded"); } } private List<Bundle> startAutoBundles(BundleContext bundleContext) { List<Bundle> bundles = Generic.list(); for (BundleSpecification specification : getSystemSpecification().getAutoBundles(bundleResolvers)) { bundles.add(install(bundleContext, specification)); } for (Bundle bundle : bundles) { startBundle(bundleContext, bundle, bundles); } resolve(bundleContext); return bundles; } private static void resolve(BundleContext bundleContext) { ServiceReference ref = bundleContext.getServiceReference(PackageAdmin.class.getName()); try { if (ref != null) { PackageAdmin admin = (PackageAdmin) bundleContext.getService(ref); admin.resolveBundles(null); } } finally { bundleContext.ungetService(ref); } } private static void startBundle(BundleContext bundleContext, Bundle bundle, List<Bundle> bundles) { if (isNonFragment(bundle)) { try { bundle.start(); } catch (BundleException e) { throw new StartupException (bundleContext + " failed to start bundle " + bundle + ", " + bundles.size() + " was started: " + bundles, e); } } } protected abstract BundleContext launchedBundleContext(); protected abstract void stopFramework(); protected abstract String osgiExports(); protected final SystemSpecification getSystemSpecification() { return systemSpecification; } protected Map<String, Object> getStandardPackagesConfiguration() { Map<String, Object> configuration = Generic.map(); configuration.put(Constants.FRAMEWORK_SYSTEMPACKAGES, systemPackages()); configuration.put(Constants.FRAMEWORK_BOOTDELEGATION, bootDelegationPackages()); return configuration; } private String systemPackages() { return new StringBuilder (SystemPackages.JDK).append(",").append (osgiExports()).append(",").append (SystemPackages.UTIL).toString(); } private static String bootDelegationPackages() { String[] bootDelegationPackages = new String[]{SystemPackages.PROFILING, SystemPackages.COVERAGE}; if (VarArgs.present(bootDelegationPackages)) { StringBuilder sb = new StringBuilder(bootDelegationPackages[0]); for (int i = 1; i < bootDelegationPackages.length; i++) { sb.append(",").append(bootDelegationPackages[i]); } return sb.toString(); } return null; } protected final void setLaunchState(URI home, Location location, List<BundleResolver> bundleResolvers, SystemSpecification systemSpecification) { if (launched.getAndSet(true)) { throw new IllegalArgumentException(this + " already launched"); } this.home = setOnceTo(this.home, home, "home"); this.location = setOnceTo(this.location, location, "location"); this.bundleResolvers = setOnceTo(this.bundleResolvers, bundleResolvers, "bundle resolvers"); this.systemSpecification = setOnceTo(this.systemSpecification, systemSpecification, "system specification"); } private <T> T setOnceTo(T current, T value, String desc) { assert current == null : this + " was launched twice, " + desc + " was set to " + current; return Not.nil(value, desc); } private void registerBundles() { registerAll(bundleRegistrations, systemSpecification.getDynaBundles()); } private void registerModules() { registerAll(moduleRegistrations, systemSpecification.moduleSpecifications()); } private void registerAll(List<ServiceRegistration> registrationList, Collection<?> objects) { requireLaunched(); for (Object object : objects) { registrationList.add(registrationOf(object)); } } private void unregisterAll(PrintStream stream) { if (launchResult == null) { return; } print(stream, "["); unregister(moduleRegistrations); defaultWait(new ReferenceVanishWaiter("vanadis.ext.ObjectManager", null, 5, stream, launchResult), "ObjectManagers still present, continuing..."); unregister(bundleRegistrations); defaultWait(new ReferenceVanishWaiter("vanadis.ext.ObjectManagerFactory", null, 5, stream, launchResult), "ObjectManagers still present, continuing..."); print(stream, "|"); uninstallAll(launchResult.getNonCoreBundles(), stream); print(stream, "|"); uninstallAll(launchResult.getAutoBundles(true), stream); print(stream, "]"); } private ServiceRegistration registrationOf(Object object) { return bundleContext.registerService(object.getClass().getName(), object, null); } private void uninstallAll(List<Bundle> bundles, PrintStream stream) { for (Bundle bundle : bundles) { long bundleId = bundle.getBundleId(); if (bundleId > 0 && bundleId != bootstrapId) { try { shutdown(bundle); print(stream, "."); } catch (Throwable e) { if (log.isDebugEnabled()) { log.debug("Bundle " + bundleId + " failed to stop: " + bundle, e); } print(stream, "x"); } } } } private static final Logger log = LoggerFactory.getLogger(AbstractOSGiLauncher.class); private static void shutdown(Bundle bundle) throws BundleException { String bundleString = null; try { bundleString = bundle.toString() + " (" + bundle.getSymbolicName() + ")"; } catch (Exception e) { log.warn("Failed to get bundle data", e); } try { int state = bundle.getState(); if (state == Bundle.ACTIVE || state == Bundle.STARTING || state == Bundle.STOPPING) { bundle.stop(); } } finally { try { bundle.uninstall(); } catch (Throwable e) { log.warn("Bundle " + bundleString + " failed to uninstall", e); } } log.info("Shutdown: " + bundleString); } private static boolean isNonFragment(Bundle bundle) { return bundle.getHeaders().get(Constants.FRAGMENT_HOST) == null; } private static Bundle install(BundleContext bundleContext, BundleSpecification specification) { try { return bundleContext.installBundle(specification.getUrlString()); } catch (BundleException e) { throw new StartupException("Failed to install start bundle at " + specification, e); } } private static void print(PrintStream stream, Object object) { if (stream != null) { stream.print(object); } } private static void defaultWait(Waiter waiter, String warning) { if (!wait(waiter, TimeSpan.MINUTE, TimeSpan.millis(250))) { log.warn(warning); } } private static void unregister(List<ServiceRegistration> regs) { List<ServiceRegistration> reversed = Generic.list(regs); Collections.reverse(reversed); for (ServiceRegistration registration : reversed) { try { registration.unregister(); } catch (Exception e) { log.warn("Failed to unregister " + registration, e); } } } private static Boolean wait(Waiter waiter, TimeSpan timeout, TimeSpan retry) { return timeout.newDeadline().tryEvery(retry, waiter); } }
kjetilv/vanadis
launcher/src/main/java/vanadis/launcher/AbstractOSGiLauncher.java
Java
apache-2.0
12,772
package se.chalmers.pd.sensors; import org.json.JSONException; import org.json.JSONObject; /** * This controller class creates messages and asks a mqtt worker to publish * them. The worker is instantiated when the object is created and the thread is * started. There is no guarantee however that the thread will start and connect * immediately. */ public class Controller { private static final String TOPIC = "/sensor/infotainment"; private MqttWorker mqttWorker; /** * Creates a an mqtt client and tells it to connect */ public Controller() { mqttWorker = new MqttWorker(); mqttWorker.start(); } /** * Tells the mqtt client to publish a message on this specific sensor topic with * the action message. */ public void performAction(Action action) { mqttWorker.publish(TOPIC, getJsonMessage(action)); } /** * Helper method to create a json object that can be stringified and sent to * the receiver. * * @param action * the action that the message will contain * @return a stringified json object containing the action that is passed * in. */ private String getJsonMessage(Action action) { JSONObject message = new JSONObject(); try { message.put(Action.action.toString(), action.toString()); } catch (JSONException e) { e.printStackTrace(); } return message.toString(); } }
Snadde/infotainment
apps/sensors/src/se/chalmers/pd/sensors/Controller.java
Java
apache-2.0
1,389
package com.fsck.k9.mail.store.imap; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.fsck.k9.mail.K9MailLib; import com.fsck.k9.mail.filter.FixedLengthInputStream; import com.fsck.k9.mail.filter.PeekableInputStream; import timber.log.Timber; import static com.fsck.k9.mail.K9MailLib.DEBUG_PROTOCOL_IMAP; class ImapResponseParser { private PeekableInputStream inputStream; private ImapResponse response; private Exception exception; public ImapResponseParser(PeekableInputStream in) { this.inputStream = in; } public ImapResponse readResponse() throws IOException { return readResponse(null); } /** * Reads the next response available on the stream and returns an {@code ImapResponse} object that represents it. */ public ImapResponse readResponse(ImapResponseCallback callback) throws IOException { try { int peek = inputStream.peek(); if (peek == '+') { readContinuationRequest(callback); } else if (peek == '*') { readUntaggedResponse(callback); } else { readTaggedResponse(callback); } if (exception != null) { throw new ImapResponseParserException("readResponse(): Exception in callback method", exception); } return response; } finally { response = null; exception = null; } } private void readContinuationRequest(ImapResponseCallback callback) throws IOException { parseCommandContinuationRequest(); response = ImapResponse.newContinuationRequest(callback); skipIfSpace(); String rest = readStringUntilEndOfLine(); response.add(rest); } private void readUntaggedResponse(ImapResponseCallback callback) throws IOException { parseUntaggedResponse(); response = ImapResponse.newUntaggedResponse(callback); readTokens(response); } private void readTaggedResponse(ImapResponseCallback callback) throws IOException { String tag = parseTaggedResponse(); response = ImapResponse.newTaggedResponse(callback, tag); readTokens(response); } List<ImapResponse> readStatusResponse(String tag, String commandToLog, String logId, UntaggedHandler untaggedHandler) throws IOException, NegativeImapResponseException { List<ImapResponse> responses = new ArrayList<ImapResponse>(); ImapResponse response; do { response = readResponse(); if (K9MailLib.isDebug() && DEBUG_PROTOCOL_IMAP) { Timber.v("%s<<<%s", logId, response); } if (response.getTag() != null && !response.getTag().equalsIgnoreCase(tag)) { Timber.w("After sending tag %s, got tag response from previous command %s for %s", tag, response, logId); Iterator<ImapResponse> responseIterator = responses.iterator(); while (responseIterator.hasNext()) { ImapResponse delResponse = responseIterator.next(); if (delResponse.getTag() != null || delResponse.size() < 2 || ( !equalsIgnoreCase(delResponse.get(1), Responses.EXISTS) && !equalsIgnoreCase(delResponse.get(1), Responses.EXPUNGE))) { responseIterator.remove(); } } response = null; continue; } if (response.getTag() == null && untaggedHandler != null) { untaggedHandler.handleAsyncUntaggedResponse(response); } responses.add(response); } while (response == null || response.getTag() == null); if (response.size() < 1 || !equalsIgnoreCase(response.get(0), Responses.OK)) { String message = "Command: " + commandToLog + "; response: " + response.toString(); throw new NegativeImapResponseException(message, responses); } return responses; } private void readTokens(ImapResponse response) throws IOException { response.clear(); Object firstToken = readToken(response); checkTokenIsString(firstToken); String symbol = (String) firstToken; response.add(symbol); if (isStatusResponse(symbol)) { parseResponseText(response); } else if (equalsIgnoreCase(symbol, Responses.LIST) || equalsIgnoreCase(symbol, Responses.LSUB)) { parseListResponse(response); } else { Object token; while ((token = readToken(response)) != null) { if (!(token instanceof ImapList)) { response.add(token); } } } } /** * Parse {@code resp-text} tokens * <p> * Responses "OK", "PREAUTH", "BYE", "NO", "BAD", and continuation request responses can * contain {@code resp-text} tokens. We parse the {@code resp-text-code} part as tokens and * read the rest as sequence of characters to avoid the parser interpreting things like * "{123}" as start of a literal. * </p> * <p>Example:</p> * <p> * {@code * OK [UIDVALIDITY 3857529045] UIDs valid} * </p> * <p> * See RFC 3501, Section 9 Formal Syntax (resp-text) * </p> * * @param parent * The {@link ImapResponse} instance that holds the parsed tokens of the response. * * @throws IOException * If there's a network error. * * @see #isStatusResponse(String) */ private void parseResponseText(ImapResponse parent) throws IOException { skipIfSpace(); int next = inputStream.peek(); if (next == '[') { parseList(parent, '[', ']'); skipIfSpace(); } String rest = readStringUntilEndOfLine(); if (rest != null && !rest.isEmpty()) { // The rest is free-form text. parent.add(rest); } } private void parseListResponse(ImapResponse response) throws IOException { expect(' '); parseList(response, '(', ')'); expect(' '); String delimiter = parseQuotedOrNil(); response.add(delimiter); expect(' '); String name = parseString(); response.add(name); expect('\r'); expect('\n'); } private void skipIfSpace() throws IOException { if (inputStream.peek() == ' ') { expect(' '); } } /** * Reads the next token of the response. The token can be one of: String - * for NIL, QUOTED, NUMBER, ATOM. Object - for LITERAL. * ImapList - for PARENTHESIZED LIST. Can contain any of the above * elements including List. * * @return The next token in the response or null if there are no more * tokens. */ private Object readToken(ImapResponse response) throws IOException { while (true) { Object token = parseToken(response); if (token == null || !(token.equals(")") || token.equals("]"))) { return token; } } } private Object parseToken(ImapList parent) throws IOException { while (true) { int ch = inputStream.peek(); if (ch == '(') { return parseList(parent, '(', ')'); } else if (ch == '[') { return parseList(parent, '[', ']'); } else if (ch == ')') { expect(')'); return ")"; } else if (ch == ']') { expect(']'); return "]"; } else if (ch == '"') { return parseQuoted(); } else if (ch == '{') { return parseLiteral(); } else if (ch == ' ') { expect(' '); } else if (ch == '\r') { expect('\r'); expect('\n'); return null; } else if (ch == '\n') { expect('\n'); return null; } else if (ch == '\t') { expect('\t'); } else { return parseBareString(true); } } } private String parseString() throws IOException { int ch = inputStream.peek(); if (ch == '"') { return parseQuoted(); } else if (ch == '{') { return (String) parseLiteral(); } else { return parseBareString(false); } } private boolean parseCommandContinuationRequest() throws IOException { expect('+'); return true; } private void parseUntaggedResponse() throws IOException { expect('*'); expect(' '); } private String parseTaggedResponse() throws IOException { return readStringUntil(' '); } private ImapList parseList(ImapList parent, char start, char end) throws IOException { expect(start); ImapList list = new ImapList(); parent.add(list); String endString = String.valueOf(end); Object token; while (true) { token = parseToken(list); if (token == null) { return null; } else if (token.equals(endString)) { break; } else if (!(token instanceof ImapList)) { list.add(token); } } return list; } private String parseBareString(boolean allowBrackets) throws IOException { StringBuilder sb = new StringBuilder(); int ch; while (true) { ch = inputStream.peek(); if (ch == -1) { throw new IOException("parseBareString(): end of stream reached"); } if (ch == '(' || ch == ')' || (allowBrackets && (ch == '[' || ch == ']')) || ch == '{' || ch == ' ' || ch == '"' || (ch >= 0x00 && ch <= 0x1f) || ch == 0x7f) { if (sb.length() == 0) { throw new IOException(String.format("parseBareString(): (%04x %c)", ch, ch)); } return sb.toString(); } else { sb.append((char) inputStream.read()); } } } /** * A "{" has been read. Read the rest of the size string, the space and then notify the callback with an * {@code InputStream}. */ private Object parseLiteral() throws IOException { expect('{'); int size = Integer.parseInt(readStringUntil('}')); expect('\r'); expect('\n'); if (size == 0) { return ""; } if (response.getCallback() != null) { FixedLengthInputStream fixed = new FixedLengthInputStream(inputStream, size); Exception callbackException = null; Object result = null; try { result = response.getCallback().foundLiteral(response, fixed); } catch (IOException e) { throw e; } catch (Exception e) { callbackException = e; } boolean someDataWasRead = fixed.available() != size; if (someDataWasRead) { if (result == null && callbackException == null) { throw new AssertionError("Callback consumed some data but returned no result"); } fixed.skipRemaining(); } if (callbackException != null) { if (exception == null) { exception = callbackException; } return "EXCEPTION"; } if (result != null) { return result; } } byte[] data = new byte[size]; int read = 0; while (read != size) { int count = inputStream.read(data, read, size - read); if (count == -1) { throw new IOException("parseLiteral(): end of stream reached"); } read += count; } return new String(data, "US-ASCII"); } private String parseQuoted() throws IOException { expect('"'); StringBuilder sb = new StringBuilder(); int ch; boolean escape = false; while ((ch = inputStream.read()) != -1) { if (!escape && ch == '\\') { // Found the escape character escape = true; } else if (!escape && ch == '"') { return sb.toString(); } else { sb.append((char) ch); escape = false; } } throw new IOException("parseQuoted(): end of stream reached"); } private String parseQuotedOrNil() throws IOException { int peek = inputStream.peek(); if (peek == '"') { return parseQuoted(); } else { parseNil(); return null; } } private void parseNil() throws IOException { expect('N'); expect('I'); expect('L'); } private String readStringUntil(char end) throws IOException { StringBuilder sb = new StringBuilder(); int ch; while ((ch = inputStream.read()) != -1) { if (ch == end) { return sb.toString(); } else { sb.append((char) ch); } } throw new IOException("readStringUntil(): end of stream reached. " + "Read: \"" + sb.toString() + "\" while waiting for " + formatChar(end)); } private String formatChar(char value) { return value < 32 ? "[" + Integer.toString(value) + "]" : "'" + value + "'"; } private String readStringUntilEndOfLine() throws IOException { String rest = readStringUntil('\r'); expect('\n'); return rest; } private void expect(char expected) throws IOException { int readByte = inputStream.read(); if (readByte != expected) { throw new IOException(String.format("Expected %04x (%c) but got %04x (%c)", (int) expected, expected, readByte, (char) readByte)); } } private boolean isStatusResponse(String symbol) { return symbol.equalsIgnoreCase(Responses.OK) || symbol.equalsIgnoreCase(Responses.NO) || symbol.equalsIgnoreCase(Responses.BAD) || symbol.equalsIgnoreCase(Responses.PREAUTH) || symbol.equalsIgnoreCase(Responses.BYE); } static boolean equalsIgnoreCase(Object token, String symbol) { if (token == null || !(token instanceof String)) { return false; } return symbol.equalsIgnoreCase((String) token); } private void checkTokenIsString(Object token) throws IOException { if (!(token instanceof String)) { throw new IOException("Unexpected non-string token: " + token.getClass().getSimpleName() + " - " + token); } } }
philipwhiuk/q-mail
qmail-library/src/main/java/com/fsck/k9/mail/store/imap/ImapResponseParser.java
Java
apache-2.0
15,316
'use strict'; /** * 블럭 모델 * * @class Block * * @exception {Error} Messages.CONSTRUCT_ERROR * 아래 문서의 1.3 Models Folder의 항목 참조 * @link https://github.com/Gaia3D/F4DConverter/blob/master/doc/F4D_SpecificationV1.pdf */ var Block = function() { if (!(this instanceof Block)) { throw new Error(Messages.CONSTRUCT_ERROR); } /** * This class is the container which holds the VBO Cache Keys. * @type {VBOVertexIdxCacheKeysContainer} */ this.vBOVertexIdxCacheKeysContainer = new VBOVertexIdxCacheKeysContainer(); /** * @deprecated * @type {number} * @default -1 */ this.mIFCEntityType = -1; /** * small object flag. * if bbox.getMaxLength() < 0.5, isSmallObj = true * * @type {Boolean} * @default false */ this.isSmallObj = false; /** * block radius * 일반적으로 bbox.getMaxLength() / 2.0 로 선언됨. * * @type {Boolean} * @default 10 */ this.radius = 10; /** * only for test.delete this. * @deprecated */ this.vertexCount = 0; /** * 각각의 사물중 복잡한 모델이 있을 경우 Lego로 처리 * 현재는 사용하지 않으나 추후에 필요할 수 있어서 그대로 둠. * legoBlock. * @type {Lego} */ this.lego; }; /** * block 초기화. gl에서 해당 block 및 lego 삭제 * * @param {WebGLRenderingContext} gl * @param {VboManager} vboMemManager */ Block.prototype.deleteObjects = function(gl, vboMemManager) { this.vBOVertexIdxCacheKeysContainer.deleteGlObjects(gl, vboMemManager); this.vBOVertexIdxCacheKeysContainer = undefined; this.mIFCEntityType = undefined; this.isSmallObj = undefined; this.radius = undefined; // only for test. delete this. this.vertexCount = undefined; if (this.lego) { this.lego.deleteGlObjects(gl); } this.lego = undefined; }; /** * render할 준비가 됬는지 체크 * * @param {NeoReference} neoReference magoManager의 objectSelected와 비교 하기 위한 neoReference 객체 * @param {MagoManager} magoManager * @param {Number} maxSizeToRender block의 radius와 비교하기 위한 ref number. * @returns {Boolean} block의 radius가 maxSizeToRender보다 크고, block의 radius가 magoManager의 보다 크고, 카메라가 움직이고 있지 않고, magoManager의 objectSelected와 neoReference가 같을 경우 true 반환 */ Block.prototype.isReadyToRender = function(neoReference, magoManager, maxSizeToRender) { if (maxSizeToRender && (this.radius < maxSizeToRender)) { return false; } if (magoManager.isCameraMoving && this.radius < magoManager.smallObjectSize && magoManager.objectSelected !== neoReference) { return false; } return true; };
Gaia3D/mago3djs
src/mago3d/f4d/Block.js
JavaScript
apache-2.0
2,674
<?php class Link_model extends CI_Model { public function __construct() { $this->load->database(); $this->load->helper('security'); $this->load->helper('human_timing'); $this->load->helper('markdown'); $this->load->helper('telveflavor'); $this->load->library('hashids'); $this->hashids = new Hashids($this->config->item('hashids_salt'), 6); $this->load->helper('tr_lang'); $this->load->helper('link_submission'); $this->load->library('image_lib'); } public function retrieve_link($id = false, $rows = null, $offset = null, $sort = null, $topic = null, $domain = null, $search_query = null) //By default, all states are returned { if ($id === false) { /* $sql = "SELECT score,link.id,title,url,link.created,username,topic,comments FROM link, user WHERE link.uid = user.id LIMIT ".$rows.",".$rows; $query = $this->db->query($sql); $query = $this->db->get('link',$rows,$offset); */ if (!empty($this->session->userdata['username']) && $this->session->userdata['username']) { $this->db->where('username', $this->session->userdata('username')); $this->db->select('id'); $this->db->limit(1); $query_for_uid = $this->db->get('user'); $user = $query_for_uid->row_array(); $this->db->select('score,link.id,title,url,text,embed,picurl,domain,link.created,username,topic,comments,up_down'); $this->db->from('link'); $this->db->join('user', 'link.uid = user.id'); $this->db->join('vote_link', $user['id'].' = vote_link.uid AND link.id = vote_link.link_id', 'left'); } else { $this->db->select('score,link.id,title,url,text,embed,picurl,domain,link.created,username,topic,comments'); $this->db->from('link'); $this->db->join('user', 'link.uid = user.id'); } $this->db->limit($rows, $offset); if ($sort == 'new') { $this->db->order_by("created", "desc"); } elseif ($sort == 'rising') { $this->db->order_by("(200 * score) + (.1 * link.created) + (60 * comments) DESC"); } elseif ($sort == 'controversial') { $this->db->order_by("comments", "desc"); } elseif ($sort == 'top') { $this->db->order_by("score", "desc"); } elseif ($sort == 'hot') { $this->db->order_by("(100 * score) + (.001 * link.created) + (1000 * comments) DESC"); } if ($topic) { $this->db->where('topic', $topic); } if ($domain) { $this->db->where('domain', $domain); } if ($search_query) { $this->db->where('MATCH (link.title) AGAINST ("'.$search_query.'")', null, false); $this->db->or_where('MATCH (link.text) AGAINST ("'.$search_query.'")', null, false); $this->db->or_where('MATCH (link.domain) AGAINST ("'.$search_query.'")', null, false); $this->db->or_where('MATCH (link.url) AGAINST ("'.$search_query.'")', null, false); $this->db->or_where('MATCH (link.topic) AGAINST ("'.$search_query.'")', null, false); } $query = $this->db->get(); return $this->hash_multirow($query->result_array()); } $id = $this->hashids->decode($id)[0]; if (!empty($this->session->userdata['username']) && $this->session->userdata['username']) { $this->db->where('username', $this->session->userdata('username')); $this->db->select('id'); $this->db->limit(1); $query_for_uid = $this->db->get('user'); $user = $query_for_uid->row_array(); $this->db->select('score,link.id,title,url,text,embed,picurl,domain,link.created,username,topic,comments,up_down,favourite_link.uid as is_favorited'); $this->db->from('link'); $this->db->join('user', 'link.uid = user.id'); $this->db->join('vote_link', $user['id'].' = vote_link.uid AND link.id = vote_link.link_id', 'left'); $this->db->join('favourite_link', $user['id'].' = favourite_link.uid AND link.id = favourite_link.link_id', 'left'); } else { $this->db->select('score,link.id,title,url,text,embed,picurl,domain,link.created,username,topic,comments'); $this->db->from('link'); $this->db->join('user', 'link.uid = user.id'); } $this->db->where('link.id', $id); $query = $this->db->get(); return $this->hash_row($query->row_array()); } public function get_link_count($id = false, $rows = null, $offset = null, $topic = null, $domain = null, $search_query = null) { if ($id === false) { if ($topic) { $this->db->where('topic', $topic); } if ($domain) { $this->db->where('domain', $domain); } if ($search_query) { $this->db->where('MATCH (link.title) AGAINST ("'.$search_query.'")', null, false); $this->db->or_where('MATCH (link.text) AGAINST ("'.$search_query.'")', null, false); $this->db->or_where('MATCH (link.domain) AGAINST ("'.$search_query.'")', null, false); $this->db->or_where('MATCH (link.url) AGAINST ("'.$search_query.'")', null, false); $this->db->or_where('MATCH (link.topic) AGAINST ("'.$search_query.'")', null, false); } $query = $this->db->get('link', $rows, $offset); return count($query->result_array()); } $id = $this->hashids->decode($id)[0]; $query = $this->db->get_where('link', array('id' => $id )); //返回某一条状态 return $this->hash_row($query->row_array()); } public function get_total_reply_count() { $query = $this->db->get('reply'); return count($query->result_array()); } public function get_total_topic_count() { $query = $this->db->get('topic'); return count($query->result_array()); } public function retrieve_reply_by_id($id) { //SELECT score,reply.id,content,reply.created,username FROM reply, user WHERE reply.uid = user.id $id = $this->hashids->decode($id)[0]; $this->db->select('score,comments,reply.id,content,reply.created,username'); $this->db->from('reply'); $this->db->where('pid', $id); $this->db->join('user', 'reply.uid = user.id'); //$this->db->limit($rows,$offset); $query = $this->db->get(); //$query = $this->db->get_where('reply',array('pid' => $id )); return $this->hash_multirow($query->result_array()); } public function retrieve_reply_tree_by_id($id) { $level = 0; //depth $res = ""; return $this->display_children($id, $level, $res); } private function display_children($pid, $level, &$res) { $Parsedown = new Parsedown(); $pid = $this->hashids->decode($pid)[0]; if (!empty($this->session->userdata['username']) && $this->session->userdata['username']) { $this->db->where('username', $this->session->userdata('username')); $this->db->select('id'); $this->db->limit(1); $query_for_uid = $this->db->get('user'); $user = $query_for_uid->row_array(); $this->db->select('reply.id,comments,content,reply.uid,score,reply.created,up_down,favourite_reply.uid as is_favorited'); $this->db->from('reply'); $this->db->where('pid', $pid); $this->db->join('vote_reply', $user['id'].' = vote_reply.uid AND reply.id = vote_reply.reply_id', 'left'); $this->db->join('favourite_reply', 'favourite_reply.uid = '.$user['id'].' AND reply.id = favourite_reply.reply_id', 'left'); } else { $this->db->select('id,comments,content,uid,score,created'); $this->db->from('reply'); $this->db->where('pid', $pid); } if (!$level) { $this->db->where('is_parent_link', 1); } else { $this->db->where('is_parent_link', 0); } if (!$this->input->get('nolimit')) { $this->db->limit(20); } if ($this->input->get('sirala') == 'zirve') { $this->db->order_by("score", "desc"); } elseif ($this->input->get('sirala') == 'yeni') { $this->db->order_by("reply.created", "desc"); } elseif ($this->input->get('sirala') == 'tartismali') { $this->db->order_by("comments", "desc"); } elseif ($this->input->get('sirala') == 'eski') { $this->db->order_by("reply.created", "asc"); } else { //$this->db->where('reply.created >= DATE_SUB(NOW(),INTERVAL 1 HOUR)'); //https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html $this->db->order_by("(8 * score) + (.1 * reply.created) + (6 * comments) DESC"); //echo $this->db->last_query(); } $query = $this->db->get(); if ($query->num_rows() == 0) { return; } if (!$level) { $res.='<ul style="list-style-type:none;">'; } else { $res.='<ul style="list-style-type:none; margin-left:14px; padding-left:.8em; border-left:solid 1px rgba(0, 0, 0, .2);">'; } foreach ($this->hash_multirow($query->result_array()) as $row) { $this->db->select('username'); $this->db->where('id', $row['uid']); $query = $this->db->get('user'); $username = $query->row_array()['username']; $ago = human_timing($row['created']); if (!empty($this->session->userdata['username']) && $this->session->userdata['username']) { $up_style = ($row['up_down'] == 1 ? 'color:green;' : 'color:black;'); $down_style = ((!($row['up_down'] == '') && ($row['up_down'] == 0)) ? 'color:red;' : 'color:black;'); } else { $up_style = 'color:black;'; $down_style = 'color:black;'; } $favourite_onclick = (isset($row['is_favorited']) ? 'unfavourite_reply(this)' : 'favourite_reply(this)'); $favourite_html = (isset($row['is_favorited']) ? 'favori<span class="glyphicon glyphicon-star"></span>' : 'favori<span class="glyphicon glyphicon-star-empty"></span>'); $res.='<li>'; $res.="<!--One reply from the reply tree of this post--> <div id='yorum-".$row['id']."' class='row-fluid reply-wrapper'> <div class='span8'> <div class='reply-header'> <a class='reply-up login-required' title='evet' href='javascript:void(0)' id='".$row['id']."' onclick='rply_up(this)'><i class='glyphicon glyphicon-arrow-up' style='".$up_style."'></i></a> <a class='color-gray' title='küçült' href='javascript:void(0)' onclick='switch_state(this)'>[–]</a>&nbsp;<small> <a class='reply-user-link' href='".base_url('kullanici/').$username.'/'."'>".$username."</a>&nbsp;&nbsp;<span id='reply-score-".$row['id']."'>".$row['score']."</span> puan&nbsp;&nbsp;".$ago." gönderildi &nbsp;<span class='color-gray'>(<a class='color-gray' title='yanıt sayısı'> ".$row['comments']." <span class='glyphicon glyphicon-comment' style='font-size:10px;'></span> </a>)</small></span> </div> <a class='reply-down login-required' title='hayır' href='javascript:void(0)' id='".$row['id']."' onclick='rply_down(this)'><i class='glyphicon glyphicon-arrow-down' style='".$down_style."'></i></a> <div class='reply-content'> <span>".telveflavor($Parsedown->text($row['content']))."</span> </div> <div class='reply-functions hide_function'> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<small><a class='color-gray' id='".$row['id']."' href='javascript:void(0)' onclick='".$favourite_onclick."' class='login-required'>".$favourite_html."</a> &nbsp;&nbsp;&nbsp;&nbsp;<a class='color-gray' href='javascript:void(0)' onclick='report_reply(\"".$row['id']."\")' class='login-required'>şikayet<span class='glyphicon glyphicon-flag'></span></a> &nbsp;&nbsp;&nbsp;&nbsp;</small><a class='color-gray' href='javascript:void(0)' onclick='set_reply(this)' id='".$row['id']."'><small>yanıt<span class='glyphicon glyphicon-share-alt special-reply-icon'></span></small></a> &nbsp;&nbsp;&nbsp;&nbsp;</small><a class='color-gray' href='javascript:void(0)' onclick='share_reply(this)' id='".$row['id']."'><small>paylaş<span class='glyphicon glyphicon-share'></span></small></a> </div> </div> </div> <!--One reply from the reply tree of this post-->"; $this->display_children($row['id'], $level+1, $res); $res.='</li>'; } return $res.='</ul>'; } public function insert_link() { $this->db->where('username', $this->session->userdata('username')); $this->db->select('id'); $this->db->limit(1); $query = $this->db->get('user'); $row = $query->row_array(); $url = $this->input->post('url'); $parsed = parse_url($url); $topic = str_replace(' ', '', $this->input->post('topic')); $topic = str_replace(['Â','â'], ['A','a'], $topic); $topic = preg_replace('/[^a-zA-Z0-9ÇŞĞÜÖİçşğüöı]+/', '', $topic); list($picurl, $text, $embed) = analyze_url($url); if (!empty($this->input->post('text'))) { $text = $this->input->post('text'); } $data = array( 'title' => $this->input->post('title'), 'url' => $url, 'text' => $text, 'embed' => $embed, 'picurl' => $picurl, 'domain' => $parsed['host'], 'topic' => tr_strtoupper($topic), 'uid' => $row['id'], //User's ID 'score' => 0, 'comments' => 0 ); $this->db->insert('link', $data); $id = $this->hashids->encode($this->db->insert_id()); $ext = pathinfo(parse_url($picurl, PHP_URL_PATH), PATHINFO_EXTENSION); $target_path = 'assets/img/link_thumbnails/'.$id.'.'.$ext; copy($picurl, $target_path); $config['image_library'] = 'gd2'; $config['source_image'] = $target_path; $config['create_thumb'] = true; $config['maintain_ratio'] = true; $config['width'] = 248; $this->image_lib->initialize($config); $this->image_lib->resize(); $this->image_lib->clear(); return $id; } public function insert_link_cli($title, $url, $topic) { $this->db->where('username', 'moderator'); $this->db->select('id'); $this->db->limit(1); $query = $this->db->get('user'); $row = $query->row_array(); $parsed = parse_url($url); $topic = str_replace(' ', '', $topic); $topic = str_replace(['Â','â'], ['A','a'], $topic); $topic = preg_replace('/[^a-zA-Z0-9ÇŞĞÜÖİçşğüöı]+/', '', $topic); list($picurl, $text, $embed) = analyze_url($url); $data = array( 'title' => $title, 'url' => $url, 'text' => null, 'embed' => $embed, 'picurl' => $picurl, 'domain' => $parsed['host'], 'topic' => tr_strtoupper($topic), 'uid' => $row['id'], //User's ID 'score' => 0, 'comments' => 0 ); $this->db->insert('link', $data); $id = $this->hashids->encode($this->db->insert_id()); $ext = pathinfo(parse_url($picurl, PHP_URL_PATH), PATHINFO_EXTENSION); $target_path = 'assets/img/link_thumbnails/'.$id.'.'.$ext; copy($picurl, $target_path); $config['image_library'] = 'gd2'; $config['source_image'] = $target_path; $config['create_thumb'] = true; $config['maintain_ratio'] = true; $config['width'] = 248; $this->image_lib->initialize($config); $this->image_lib->resize(); $this->image_lib->clear(); return $id; } public function insert_reply() { $this->db->where('username', $this->session->userdata('username')); $this->db->select('id'); $this->db->limit(1); $query = $this->db->get('user'); $row = $query->row_array(); $content = xss_clean($this->input->post('content')); $content = trim($content); $data = array( 'content' => $content, 'pid' => $this->hashids->decode($this->input->post('pid'))[0], 'uid' => $row['id'], 'score' => 0, 'comments' => 0, 'is_parent_link' => $this->input->post('is_parent_link'), 'link_id' => $this->hashids->decode($this->input->post('link_id'))[0] ); $this->db->insert('reply', $data); return $this->hashids->encode($this->db->insert_id()); } public function up_score() { $id = $this->input->post('id'); $id = $this->hashids->decode($id)[0]; $this->db->where('id', $id); $this->db->set('score', 'score+1', false); $this->db->update('link'); } public function down_score() { $id = $this->input->post('id'); $id = $this->hashids->decode($id)[0]; $this->db->where('id', $id); $this->db->set('score', 'score-1', false); $this->db->update('link'); } public function rply_up_score() { $id = $this->input->post('id'); $id = $this->hashids->decode($id)[0]; $this->db->where('id', $id); $this->db->set('score', 'score+1', false); $this->db->update('reply'); } public function rply_down_score() { $id = $this->input->post('id'); $id = $this->hashids->decode($id)[0]; $this->db->where('id', $id); $this->db->set('score', 'score-1', false); $this->db->update('reply'); } public function increase_comments() { $id = $this->input->post('pid'); $id = $this->hashids->decode($id)[0]; $this->db->where('id', $id); $this->db->set('comments', 'comments+1', false); $this->db->update('link'); } public function increase_rply_comments() { $id = $this->input->post('pid'); $id = $this->hashids->decode($id)[0]; $this->db->where('id', $id); $this->db->set('comments', 'comments+1', false); $this->db->update('reply'); } public function retrieve_topics_for_header() { $this->db->select('topic, COUNT(*) as topic_occurrence'); $this->db->from('link'); $this->db->group_by('topic'); $this->db->order_by('topic_occurrence', 'desc'); $query = $this->db->get(); return $query->result_array(); } public function random_topic() { $this->db->select('topic'); $this->db->from('link'); $this->db->group_by('topic'); $this->db->order_by('rand()'); $this->db->limit(1); $query = $this->db->get(); return $query->row_array(); } public function retrieve_topics($rows, $offset) { $this->db->select('topic, COUNT(topic) as topic_occurrence, MIN(link.created) as created, MIN(topic.description) as description, MIN(topic.subscribers) as subscribers'); $this->db->from('link'); $this->db->group_by('topic'); $this->db->order_by('topic_occurrence', 'desc'); $this->db->limit($rows, $offset); $this->db->join('topic', 'link.topic = topic.name', 'left'); $query = $this->db->get(); return $query->result_array(); } public function retrieve_all_topics() { $this->db->select('link.topic as topic,topic.header_image as header_image'); $this->db->from('link'); $this->db->group_by('link.topic'); $this->db->join('topic', 'link.topic = topic.name'); $query = $this->db->get(); return $query->result_array(); } public function retrieve_all_links() { $this->db->select('id,uid,title,url,text,embed,picurl,domain,topic,created,score,comments,reported,favorited,is_link_for_union'); $this->db->from('link'); $query = $this->db->get(); return $query->result_array(); } public function increase_topic_reported() { $this->db->where('name', $this->input->post('name')); $this->db->set('reported', 'reported+1', false); $this->db->update('topic'); } public function increase_link_reported() { $id = $this->input->post('id'); $id = $this->hashids->decode($id)[0]; $this->db->where('id', $id); $this->db->set('reported', 'reported+1', false); $this->db->update('link'); } public function increase_reply_reported() { $id = $this->input->post('id'); $id = $this->hashids->decode($id)[0]; $this->db->where('id', $id); $this->db->set('reported', 'reported+1', false); $this->db->update('reply'); } private function hash_multirow($multirow) { foreach ($multirow as &$row) { $row['id'] = $this->hashids->encode($row['id']); } unset($row); return $multirow; } private function hash_row($row) { $row['id'] = $this->hashids->encode($row['id']); return $row; } public function fix_domain_with_empty_topics($domain, $topic) { $this->db->where('domain', $domain); $this->db->where('topic', ''); $this->db->set('topic', $topic); $this->db->update('link'); } }
DragonComputer/telve.net
application/models/Link_model.php
PHP
apache-2.0
24,205
package moe.dangoreader.activity; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageButton; import android.widget.TextView; import io.paperdb.Paper; import moe.dangoreader.R; import moe.dangoreader.UserLibraryHelper; import moe.dangoreader.adapter.MangaItemPageAdapter; import moe.dangoreader.database.Manga; import moe.dangoreader.model.MangaEdenMangaDetailItem; import moe.dangoreader.parse.MangaEden; import retrofit.Callback; import retrofit.Response; import retrofit.Retrofit; /** * Activity that displays a single manga, and shows manga info and chapters */ public class MangaItemActivity extends AppCompatActivity { private Manga manga; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_manga_item); Paper.init(this); findViewById(R.id.manga_item_pager).setVisibility(View.GONE); initToolBar(); String mangaId = getIntent().getStringExtra("mangaId"); manga = Paper.book(UserLibraryHelper.USER_LIBRARY_DB).read(mangaId); // if (manga != null && manga.chaptersList != null) { // initViewPager(); // initMarqueeTitle(); // } fetchMangaDetailFromMangaEden(mangaId); } private void initToolBar() { Toolbar toolbar = (Toolbar) findViewById(R.id.manga_item_toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowTitleEnabled(false); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); } private void initViewPager() { ViewPager viewPager = (ViewPager) findViewById(R.id.manga_item_pager); MangaItemPageAdapter mangaItemPageAdapter = new MangaItemPageAdapter(this, getSupportFragmentManager(), manga.id); viewPager.setAdapter(mangaItemPageAdapter); TabLayout tabLayout = (TabLayout) findViewById(R.id.manga_item_tabs); tabLayout.setupWithViewPager(viewPager); findViewById(R.id.manga_item_placeholder).setVisibility(View.GONE); findViewById(R.id.manga_item_pager).setVisibility(View.VISIBLE); } private void initMarqueeTitle() { TextView mangaTitleView = (TextView) findViewById(R.id.manga_item_chapter_title); mangaTitleView.setText(manga.title); mangaTitleView.setSelected(true); // for marquee to scroll } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_manga_item, menu); MenuItem bookmarkItem = menu.findItem(R.id.manga_item_bookmark_button); final MangaItemActivity activity = this; final ImageButton bookmarkToggle = new ImageButton(this); bookmarkToggle.setImageResource(R.drawable.bookmark_toggle); bookmarkToggle.setSelected(manga != null && manga.favorite); bookmarkToggle.setBackgroundResource(R.color.transparent); bookmarkToggle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (bookmarkToggle.isSelected()) { UserLibraryHelper.removeFromLibrary(manga, bookmarkToggle, activity, true, null, -1); } else { UserLibraryHelper.addToLibrary(manga, bookmarkToggle, activity, true, null, -1); } } }); bookmarkItem.setActionView(bookmarkToggle); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { return super.onOptionsItemSelected(item); } private void fetchMangaDetailFromMangaEden(final String mangaId) { Log.d("MangaItemActivity", "Fetching manga details"); MangaEden.getMangaEdenService(this) .getMangaDetails(mangaId) .enqueue(new Callback<MangaEdenMangaDetailItem>() { @Override public void onResponse(Response<MangaEdenMangaDetailItem> response, Retrofit retrofit) { MangaEdenMangaDetailItem mangaDetailItem = response.body(); manga = UserLibraryHelper.updateManga(mangaId, mangaDetailItem); initViewPager(); initMarqueeTitle(); } @Override public void onFailure(Throwable t) { Log.e("MangaItemActivity", "Could not fetch details from MangaEden"); } }); } }
williamxu/DangoReader
app/src/main/java/moe/dangoreader/activity/MangaItemActivity.java
Java
apache-2.0
5,092
/* Copyright 2019 The Ceph-CSI Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 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 util import ( "bufio" "errors" "fmt" "io" "os" "strconv" "strings" ) const ( procCgroup = "/proc/self/cgroup" sysPidsMaxFmt = "/sys/fs/cgroup/pids%s/pids.max" ) // return the cgouprs "pids.max" file of the current process // // find the line containing the pids group from the /proc/self/cgroup file // $ grep 'pids' /proc/self/cgroup // 7:pids:/kubepods.slice/kubepods-besteffort.slice/....scope // $ cat /sys/fs/cgroup/pids + *.scope + /pids.max. func getCgroupPidsFile() (string, error) { cgroup, err := os.Open(procCgroup) if err != nil { return "", err } defer cgroup.Close() // #nosec: error on close is not critical here scanner := bufio.NewScanner(cgroup) var slice string for scanner.Scan() { parts := strings.SplitN(scanner.Text(), ":", 3) if parts == nil || len(parts) < 3 { continue } if parts[1] == "pids" { slice = parts[2] break } } if slice == "" { return "", fmt.Errorf("could not find a cgroup for 'pids'") } pidsMax := fmt.Sprintf(sysPidsMaxFmt, slice) return pidsMax, nil } // GetPIDLimit returns the current PID limit, or an error. A value of -1 // translates to "max". func GetPIDLimit() (int, error) { pidsMax, err := getCgroupPidsFile() if err != nil { return 0, err } f, err := os.Open(pidsMax) // #nosec - intended reading from /sys/... if err != nil { return 0, err } defer f.Close() // #nosec: error on close is not critical here maxPidsStr, err := bufio.NewReader(f).ReadString('\n') if err != nil && !errors.Is(err, io.EOF) { return 0, err } maxPidsStr = strings.TrimRight(maxPidsStr, "\n") maxPids := -1 if maxPidsStr != "max" { maxPids, err = strconv.Atoi(maxPidsStr) if err != nil { return 0, err } } return maxPids, nil } // SetPIDLimit configures the given PID limit for the current process. A value // of -1 translates to "max". func SetPIDLimit(limit int) error { limitStr := "max" if limit != -1 { limitStr = fmt.Sprintf("%d", limit) } pidsMax, err := getCgroupPidsFile() if err != nil { return err } f, err := os.Create(pidsMax) if err != nil { return err } _, err = f.WriteString(limitStr) if err != nil { f.Close() // #nosec: a write error will be more useful to return return err } return f.Close() }
ceph/ceph-csi
internal/util/pidlimit.go
GO
apache-2.0
2,838
// 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 }); defineProperty( this, '_count', { 'configurable': false, 'enumerable': false, 'writable': true, 'value': 0 }); // Read-only: setReadOnly( this, 'name', name ); setReadOnly( this, 'tic', start ); setReadOnly( this, 'toc', stop ); setReadOnly( this, 'iterations', opts.iterations ); setReadOnly( this, 'timeout', opts.timeout ); return this; /** * Starts a benchmark timer. * * ## Notes * * - Using a scoped variable prevents nefarious mutation by bad actors hoping to manipulate benchmark results. * - The one attack vector which remains is manipulation of the `require` cache for `tic` and `toc`. * - One way to combat cache manipulation is by comparing the checksum of `Function#toString()` against known values. * * @private */ function start() { if ( hasTicked ) { self.fail( '.tic() called more than once' ); } else { self.emit( 'tic' ); hasTicked = true; time = tic(); } } /** * Stops a benchmark timer. * * @private * @returns {void} */ function stop() { var elapsed; var secs; var rate; var out; if ( hasTicked === false ) { return self.fail( '.toc() called before .tic()' ); } elapsed = toc( time ); if ( hasTocked ) { return self.fail( '.toc() called more than once' ); } hasTocked = true; self.emit( 'toc' ); secs = elapsed[ 0 ] + ( elapsed[ 1 ]/1e9 ); rate = self.iterations / secs; out = { 'ok': true, 'operator': 'result', 'iterations': self.iterations, 'elapsed': secs, 'rate': rate }; self.emit( 'result', out ); } } /* * Inherit from the `EventEmitter` prototype. */ inherit( Benchmark, EventEmitter ); /** * Runs a benchmark. * * @private * @name run * @memberof Benchmark.prototype * @type {Function} */ setReadOnly( Benchmark.prototype, 'run', run ); /** * Forcefully ends a benchmark. * * @private * @name exit * @memberof Benchmark.prototype * @type {Function} */ setReadOnly( Benchmark.prototype, 'exit', exit ); /** * Returns a `boolean` indicating if a benchmark has ended. * * @private * @name ended * @memberof Benchmark.prototype * @type {Function} * @returns {boolean} boolean indicating if a benchmark has ended */ setReadOnly( Benchmark.prototype, 'ended', ended ); /** * Generates an assertion. * * @private * @name _assert * @memberof Benchmark.prototype * @type {Function} * @param {boolean} ok - assertion outcome * @param {Options} opts - options */ setReadOnly( Benchmark.prototype, '_assert', assert ); /** * Writes a comment. * * @name comment * @memberof Benchmark.prototype * @type {Function} * @param {string} msg - comment message */ setReadOnly( Benchmark.prototype, 'comment', comment ); /** * Generates an assertion which will be skipped. * * @name skip * @memberof Benchmark.prototype * @type {Function} * @param {*} value - value * @param {string} msg - message */ setReadOnly( Benchmark.prototype, 'skip', skip ); /** * Generates an assertion which should be implemented. * * @name todo * @memberof Benchmark.prototype * @type {Function} * @param {*} value - value * @param {string} msg - message */ setReadOnly( Benchmark.prototype, 'todo', todo ); /** * Generates a failing assertion. * * @name fail * @memberof Benchmark.prototype * @type {Function} * @param {string} msg - message */ setReadOnly( Benchmark.prototype, 'fail', fail ); /** * Generates a passing assertion. * * @name pass * @memberof Benchmark.prototype * @type {Function} * @param {string} msg - message */ setReadOnly( Benchmark.prototype, 'pass', pass ); /** * Asserts that a `value` is truthy. * * @name ok * @memberof Benchmark.prototype * @type {Function} * @param {*} value - value * @param {string} [msg] - message */ setReadOnly( Benchmark.prototype, 'ok', ok ); /** * Asserts that a `value` is falsy. * * @name notOk * @memberof Benchmark.prototype * @type {Function} * @param {*} value - value * @param {string} [msg] - message */ setReadOnly( Benchmark.prototype, 'notOk', notOk ); /** * Asserts that `actual` is strictly equal to `expected`. * * @name equal * @memberof Benchmark.prototype * @type {Function} * @param {*} actual - actual value * @param {*} expected - expected value * @param {string} [msg] - message */ setReadOnly( Benchmark.prototype, 'equal', equal ); /** * Asserts that `actual` is not strictly equal to `expected`. * * @name notEqual * @memberof Benchmark.prototype * @type {Function} * @param {*} actual - actual value * @param {*} expected - expected value * @param {string} [msg] - message */ setReadOnly( Benchmark.prototype, 'notEqual', notEqual ); /** * Asserts that `actual` is deeply equal to `expected`. * * @name deepEqual * @memberof Benchmark.prototype * @type {Function} * @param {*} actual - actual value * @param {*} expected - expected value * @param {string} [msg] message */ setReadOnly( Benchmark.prototype, 'deepEqual', deepEqual ); /** * Asserts that `actual` is not deeply equal to `expected`. * * @name notDeepEqual * @memberof Benchmark.prototype * @type {Function} * @param {*} actual - actual value * @param {*} expected - expected value * @param {string} [msg] message */ setReadOnly( Benchmark.prototype, 'notDeepEqual', notDeepEqual ); /** * Ends a benchmark. * * @name end * @memberof Benchmark.prototype * @type {Function} */ setReadOnly( Benchmark.prototype, 'end', end ); // EXPORTS // module.exports = Benchmark; },{"./assert.js":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]);
stdlib-js/www
public/docs/api/latest/@stdlib/stats/base/dists/exponential/pdf/benchmark_bundle.js
JavaScript
apache-2.0
938,262
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BesyProject.Models { public class Servico { public long ServicoId { get; set; } public string Descricao { get; set; } public virtual ICollection<Empresa> Empresas { get; set; } } }
GabrielMathias17/Interdisciplinar.Net
BesyProject/BesyProject/Models/Servico.cs
C#
apache-2.0
334
#pragma once #include <data_types/fourierseries.hpp> #include <kernels/kernels.h> #include <kernels/defaults.h> #include <iostream> #include <utils/nvtx.hpp> class HarmonicFolder { private: unsigned int max_blocks; unsigned int max_threads; float** h_data_ptrs; float** d_data_ptrs; HarmonicSums<float>& sums; public: HarmonicFolder(HarmonicSums<float>& sums, unsigned int max_blocks=MAX_BLOCKS, unsigned int max_threads=MAX_THREADS) :sums(sums),max_blocks(max_blocks),max_threads(max_threads) { Utils::device_malloc<float*>(&d_data_ptrs,sums.size()); Utils::host_malloc<float*>(&h_data_ptrs,sums.size()); } void fold(DevicePowerSpectrum<float>& fold0) { PUSH_NVTX_RANGE("Harmonic summing",2) for (int ii=0;ii<sums.size();ii++) { h_data_ptrs[ii] = sums[ii]->get_data(); } Utils::h2dcpy<float*>(d_data_ptrs,h_data_ptrs,sums.size()); device_harmonic_sum(fold0.get_data(),d_data_ptrs, fold0.get_nbins(),sums.size(), max_blocks,max_threads); POP_NVTX_RANGE } ~HarmonicFolder() { Utils::device_free(d_data_ptrs); Utils::host_free(h_data_ptrs); } };
ewanbarr/peasoup
include/transforms/harmonicfolder.hpp
C++
apache-2.0
1,149
package com.github.j1stiot.mqtt.api.internal; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.handler.codec.mqtt.*; import org.apache.commons.lang3.StringUtils; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * Represent MQTT Message passed in Communicator */ @SuppressWarnings("unused") public class InternalMessage<T> implements Serializable { // fixed header private MqttMessageType messageType; private boolean dup; private MqttQoS qos; private boolean retain; // some info in CONNECT message, but useful for stateless transfer private MqttVersion version; private String clientId; private String userName; // broker id, only meaningful when the message is sent by broker private String brokerId; // variable header and payload private T payload; protected InternalMessage() { } public InternalMessage(MqttMessageType messageType, boolean dup, MqttQoS qos, boolean retain, MqttVersion version, String clientId, String userName, String brokerId) { this(messageType, dup, qos, retain, version, clientId, userName, brokerId, null); } public InternalMessage(MqttMessageType messageType, boolean dup, MqttQoS qos, boolean retain, MqttVersion version, String clientId, String userName, String brokerId, T payload) { this.messageType = messageType; this.dup = dup; this.qos = qos; this.retain = retain; this.version = version; this.clientId = clientId; this.userName = userName; this.brokerId = brokerId; this.payload = payload; } protected static <T> InternalMessage<T> fromMqttMessage(MqttVersion version, String clientId, String userName, String brokerId, MqttFixedHeader fixedHeader) { return new InternalMessage<>(fixedHeader.messageType(), fixedHeader.dup(), fixedHeader.qos(), fixedHeader.retain(), version, clientId, userName, brokerId); } public static InternalMessage<Connect> fromMqttMessage(MqttVersion version, String clientId, String userName, String brokerId, MqttConnectMessage mqtt) { InternalMessage<Connect> msg = fromMqttMessage(version, clientId, userName, brokerId, mqtt.fixedHeader()); msg.payload = mqtt.variableHeader().willFlag() ? new Connect(mqtt.variableHeader().cleanSession(), mqtt.variableHeader().willRetain(), mqtt.variableHeader().willQos(), mqtt.payload().willTopic(), mqtt.payload().willMessage().getBytes()) : new Connect(mqtt.variableHeader().cleanSession(), false, MqttQoS.AT_MOST_ONCE, null, null); return msg; } public static InternalMessage<ConnAck> fromMqttMessage(MqttVersion version, String clientId, String userName, String brokerId, MqttConnAckMessage mqtt) { InternalMessage<ConnAck> msg = fromMqttMessage(version, clientId, userName, brokerId, mqtt.fixedHeader()); msg.payload = new ConnAck(mqtt.variableHeader().returnCode(), mqtt.variableHeader().sessionPresent()); return msg; } public static InternalMessage<Subscribe> fromMqttMessage(MqttVersion version, String clientId, String userName, String brokerId, MqttSubscribeMessage mqtt, List<MqttGrantedQoS> returnCodes) { InternalMessage<Subscribe> msg = fromMqttMessage(version, clientId, userName, brokerId, mqtt.fixedHeader()); // forge topic subscriptions if (mqtt.payload().subscriptions().size() != returnCodes.size()) { throw new IllegalArgumentException("MQTT SUBSCRIBE message's subscriptions count not equal to granted QoS count"); } List<TopicSubscription> topicSubscriptions = new ArrayList<>(); for (int i = 0; i < mqtt.payload().subscriptions().size(); i++) { TopicSubscription subscription = new TopicSubscription(mqtt.payload().subscriptions().get(i).topic(), returnCodes.get(i)); topicSubscriptions.add(subscription); } msg.payload = new Subscribe(mqtt.variableHeader().packetId(), topicSubscriptions); return msg; } public static InternalMessage<SubAck> fromMqttMessage(MqttVersion version, String clientId, String userName, String brokerId, MqttSubAckMessage mqtt) { InternalMessage<SubAck> msg = fromMqttMessage(version, clientId, userName, brokerId, mqtt.fixedHeader()); msg.payload = new SubAck(mqtt.variableHeader().packetId(), mqtt.payload().grantedQoSLevels()); return msg; } public static InternalMessage<Unsubscribe> fromMqttMessage(MqttVersion version, String clientId, String userName, String brokerId, MqttUnsubscribeMessage mqtt) { InternalMessage<Unsubscribe> msg = fromMqttMessage(version, clientId, userName, brokerId, mqtt.fixedHeader()); msg.payload = new Unsubscribe(mqtt.variableHeader().packetId(), mqtt.payload().topics()); return msg; } public static InternalMessage<Publish> fromMqttMessage(MqttVersion version, String clientId, String userName, String brokerId, MqttPublishMessage mqtt) { InternalMessage<Publish> msg = fromMqttMessage(version, clientId, userName, brokerId, mqtt.fixedHeader()); // forge bytes payload ByteBuf buf = mqtt.payload().duplicate(); byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); msg.payload = new Publish(mqtt.variableHeader().topicName(), mqtt.variableHeader().packetId(), bytes); return msg; } public static InternalMessage<Publish> fromMqttMessage(String topic, MqttVersion version, String clientId, String userName, String brokerId, MqttPublishMessage mqtt) { InternalMessage<Publish> msg = fromMqttMessage(version, clientId, userName, brokerId, mqtt.fixedHeader()); // forge bytes payload ByteBuf buf = mqtt.payload().duplicate(); byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); msg.payload = new Publish(topic, mqtt.variableHeader().packetId(), bytes); return msg; } public static InternalMessage<Disconnect> fromMqttMessage(MqttVersion version, String clientId, String userName, String brokerId, boolean cleanSession, boolean cleanExit) { return new InternalMessage<>(MqttMessageType.DISCONNECT, false, MqttQoS.AT_MOST_ONCE, false, version, clientId, userName, brokerId, new Disconnect(cleanSession, cleanExit)); } public static InternalMessage fromMqttMessage(MqttVersion version, String clientId, String userName, String brokerId, MqttMessage mqtt) { if (mqtt.variableHeader() != null && mqtt.variableHeader() instanceof MqttPacketIdVariableHeader) { InternalMessage<PacketId> msg = fromMqttMessage(version, clientId, userName, brokerId, mqtt.fixedHeader()); msg.payload = new PacketId(((MqttPacketIdVariableHeader) mqtt.variableHeader()).packetId()); return msg; } else { return fromMqttMessage(version, clientId, userName, brokerId, mqtt.fixedHeader()); } } public MqttMessageType getMessageType() { return messageType; } public void setMessageType(MqttMessageType messageType) { this.messageType = messageType; } public boolean isDup() { return dup; } public void setDup(boolean dup) { this.dup = dup; } public MqttQoS getQos() { return qos; } public void setQos(MqttQoS qos) { this.qos = qos; } public boolean isRetain() { return retain; } public void setRetain(boolean retain) { this.retain = retain; } public MqttVersion getVersion() { return version; } public void setVersion(MqttVersion version) { this.version = version; } public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getBrokerId() { return brokerId; } public void setBrokerId(String brokerId) { this.brokerId = brokerId; } public T getPayload() { return payload; } public void setPayload(T payload) { this.payload = payload; } public MqttMessage toMqttMessage() { MqttFixedHeader fixedHeader = new MqttFixedHeader(messageType, dup, qos, retain, 0); switch (messageType) { case CONNECT: Connect connect = (Connect) payload; boolean userNameFlag = StringUtils.isNotBlank(userName); boolean willFlag = connect.getWillMessage() != null && connect.getWillMessage().length > 0; return MqttMessageFactory.newMessage(fixedHeader, new MqttConnectVariableHeader(version.protocolName(), version.protocolLevel(), userNameFlag, false, connect.isWillRetain(), connect.getWillQos(), willFlag, connect.isCleanSession(), 0), new MqttConnectPayload(clientId, connect.getWillTopic(), new String(connect.getWillMessage()), userName, null)); case CONNACK: ConnAck connAck = (ConnAck) payload; return MqttMessageFactory.newMessage(fixedHeader, new MqttConnAckVariableHeader(connAck.getReturnCode(), connAck.isSessionPresent()), null); case SUBSCRIBE: Subscribe subscribe = (Subscribe) payload; List<MqttTopicSubscription> subscriptions = new ArrayList<>(); subscribe.getSubscriptions().forEach(s -> subscriptions.add(new MqttTopicSubscription(s.getTopic(), MqttQoS.valueOf(s.getGrantedQos().value()))) ); return MqttMessageFactory.newMessage(fixedHeader, MqttPacketIdVariableHeader.from(subscribe.getPacketId()), new MqttSubscribePayload(subscriptions)); case SUBACK: SubAck subAck = (SubAck) payload; return MqttMessageFactory.newMessage(fixedHeader, MqttPacketIdVariableHeader.from(subAck.getPacketId()), new MqttSubAckPayload(subAck.getGrantedQoSLevels())); case UNSUBSCRIBE: Unsubscribe unsubscribe = (Unsubscribe) payload; return MqttMessageFactory.newMessage(fixedHeader, MqttPacketIdVariableHeader.from(unsubscribe.getPacketId()), new MqttUnsubscribePayload(unsubscribe.getTopics())); case PUBLISH: Publish publish = (Publish) payload; return MqttMessageFactory.newMessage(fixedHeader, (qos == MqttQoS.AT_MOST_ONCE) ? MqttPublishVariableHeader.from(publish.getTopicName()) : MqttPublishVariableHeader.from(publish.getTopicName(), publish.getPacketId()), (publish.getPayload() != null && publish.getPayload().length > 0) ? Unpooled.wrappedBuffer(publish.getPayload()) : Unpooled.EMPTY_BUFFER); case UNSUBACK: case PUBACK: case PUBREC: case PUBREL: case PUBCOMP: PacketId packetId = (PacketId) payload; return MqttMessageFactory.newMessage(fixedHeader, MqttPacketIdVariableHeader.from(packetId.getPacketId()), null); case PINGREQ: case PINGRESP: case DISCONNECT: return MqttMessageFactory.newMessage(fixedHeader, null, null); default: throw new IllegalStateException("unknown message type " + messageType); } } }
12315jack/j1st-mqtt
j1st-mqtt-api/src/main/java/com/github/j1stiot/mqtt/api/internal/InternalMessage.java
Java
apache-2.0
13,361
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package ec2 import ( "context" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/internal/awsutil" ) type ImportKeyPairInput struct { _ struct{} `type:"structure"` // Checks whether you have the required permissions for the action, without // actually making the request, and provides an error response. If you have // the required permissions, the error response is DryRunOperation. Otherwise, // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` // A unique name for the key pair. // // KeyName is a required field KeyName *string `locationName:"keyName" type:"string" required:"true"` // The public key. For API calls, the text must be base64-encoded. For command // line tools, base64 encoding is performed for you. // // PublicKeyMaterial is automatically base64 encoded/decoded by the SDK. // // PublicKeyMaterial is a required field PublicKeyMaterial []byte `locationName:"publicKeyMaterial" type:"blob" required:"true"` // The tags to apply to the imported key pair. TagSpecifications []TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` } // String returns the string representation func (s ImportKeyPairInput) String() string { return awsutil.Prettify(s) } // Validate inspects the fields of the type to determine if they are valid. func (s *ImportKeyPairInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "ImportKeyPairInput"} if s.KeyName == nil { invalidParams.Add(aws.NewErrParamRequired("KeyName")) } if s.PublicKeyMaterial == nil { invalidParams.Add(aws.NewErrParamRequired("PublicKeyMaterial")) } if invalidParams.Len() > 0 { return invalidParams } return nil } type ImportKeyPairOutput struct { _ struct{} `type:"structure"` // The MD5 public key fingerprint as specified in section 4 of RFC 4716. KeyFingerprint *string `locationName:"keyFingerprint" type:"string"` // The key pair name you provided. KeyName *string `locationName:"keyName" type:"string"` // The ID of the resulting key pair. KeyPairId *string `locationName:"keyPairId" type:"string"` // The tags applied to the imported key pair. Tags []Tag `locationName:"tagSet" locationNameList:"item" type:"list"` } // String returns the string representation func (s ImportKeyPairOutput) String() string { return awsutil.Prettify(s) } const opImportKeyPair = "ImportKeyPair" // ImportKeyPairRequest returns a request value for making API operation for // Amazon Elastic Compute Cloud. // // Imports the public key from an RSA key pair that you created with a third-party // tool. Compare this with CreateKeyPair, in which AWS creates the key pair // and gives the keys to you (AWS keeps a copy of the public key). With ImportKeyPair, // you create the key pair and give AWS just the public key. The private key // is never transferred between you and AWS. // // For more information about key pairs, see Key Pairs (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html) // in the Amazon Elastic Compute Cloud User Guide. // // // Example sending a request using ImportKeyPairRequest. // req := client.ImportKeyPairRequest(params) // resp, err := req.Send(context.TODO()) // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ImportKeyPair func (c *Client) ImportKeyPairRequest(input *ImportKeyPairInput) ImportKeyPairRequest { op := &aws.Operation{ Name: opImportKeyPair, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { input = &ImportKeyPairInput{} } req := c.newRequest(op, input, &ImportKeyPairOutput{}) return ImportKeyPairRequest{Request: req, Input: input, Copy: c.ImportKeyPairRequest} } // ImportKeyPairRequest is the request type for the // ImportKeyPair API operation. type ImportKeyPairRequest struct { *aws.Request Input *ImportKeyPairInput Copy func(*ImportKeyPairInput) ImportKeyPairRequest } // Send marshals and sends the ImportKeyPair API request. func (r ImportKeyPairRequest) Send(ctx context.Context) (*ImportKeyPairResponse, error) { r.Request.SetContext(ctx) err := r.Request.Send() if err != nil { return nil, err } resp := &ImportKeyPairResponse{ ImportKeyPairOutput: r.Request.Data.(*ImportKeyPairOutput), response: &aws.Response{Request: r.Request}, } return resp, nil } // ImportKeyPairResponse is the response type for the // ImportKeyPair API operation. type ImportKeyPairResponse struct { *ImportKeyPairOutput response *aws.Response } // SDKResponseMetdata returns the response metadata for the // ImportKeyPair request. func (r *ImportKeyPairResponse) SDKResponseMetdata() *aws.Response { return r.response }
cilium-team/cilium
vendor/github.com/aws/aws-sdk-go-v2/service/ec2/api_op_ImportKeyPair.go
GO
apache-2.0
4,833
using System.Collections.Generic; namespace N3P.MVVM { public interface IExportedState { IEnumerable<string> Keys { get; } object this[string key] { get; } int Count { get; } object Apply(); } }
mlorbetske/n3p-mvvm
N3P.Take2.MVVM/IExportedState.cs
C#
apache-2.0
261
from givabit.backend.charity import Charity from givabit.backend.errors import MissingValueException, MultipleValueException from givabit.test_common import test_data from givabit.test_common import test_utils class CharityRepositoryTest(test_utils.TestCase): def setUp(self): super(CharityRepositoryTest, self).setUp() self.all_charities = [test_data.c1, test_data.c2, test_data.c3, test_data.c4] for charity in self.all_charities: self.charity_repo.add_or_update_charity(charity) def test_lists_charities(self): self.assertSequenceEqual(self.charity_repo.list_charities(), self.all_charities) def test_gets_single_charity(self): self.assertEqual(self.charity_repo.get_charity('Shelter'), test_data.c1) self.assertEqual(self.charity_repo.get_charity('Oxfam'), test_data.c2) with self.assertRaises(MissingValueException): self.charity_repo.get_charity('Does not exist') try: self.charity_repo.get_charity('BHF') except MultipleValueException, e: self.assertSequenceEqual(e.values, [test_data.c3, test_data.c4]) def test_gets_charity_by_id(self): self.assertEquals(self.charity_repo.get_charity(id=test_data.c1.key().id()), test_data.c1) def test_getting_missing_charity_by_id_throws(self): missing_id = 0 while missing_id in map(lambda charity: charity.key().id(), self.all_charities): missing_id += 1 with self.assertRaises(MissingValueException): self.charity_repo.get_charity(id=missing_id)
illicitonion/givabit
src/givabit/backend/charity_repository_test.py
Python
apache-2.0
1,597
package config var ()
phenax/diary-pwa
config/db.go
GO
apache-2.0
23
package weibo4j.http; import org.apache.commons.httpclient.*; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.methods.DeleteMethod; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.multipart.*; import org.apache.commons.httpclient.params.HttpClientParams; import org.apache.commons.httpclient.params.HttpConnectionManagerParams; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.log4j.Logger; import weibo4j.model.*; import weibo4j.org.json.JSONException; import javax.activation.MimetypesFileTypeMap; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; /** * @author sinaWeibo */ public class HttpClient implements java.io.Serializable { private static final long serialVersionUID = -176092625883595547L; private static final int OK = 200;// OK: Success! private static final int NOT_MODIFIED = 304;// Not Modified: There was no new data to return. private static final int BAD_REQUEST = 400;// Bad Request: The request was invalid. An accompanying error message will explain why. This is the status code will be returned during rate limiting. private static final int NOT_AUTHORIZED = 401;// Not Authorized: Authentication credentials were missing or incorrect. private static final int FORBIDDEN = 403;// Forbidden: The request is understood, but it has been refused. An accompanying error message will explain why. private static final int NOT_FOUND = 404;// Not Found: The URI requested is invalid or the resource requested, such as a user, does not exists. private static final int NOT_ACCEPTABLE = 406;// Not Acceptable: Returned by the Search API when an invalid format is specified in the request. private static final int INTERNAL_SERVER_ERROR = 500;// Internal Server Error: Something is broken. Please post to the group so the Weibo team can investigate. private static final int BAD_GATEWAY = 502;// Bad Gateway: Weibo is down or being upgraded. private static final int SERVICE_UNAVAILABLE = 503;// Service Unavailable: The Weibo servers are up, but overloaded with requests. Try again later. The search and trend methods use this to indicate when you are being rate limited. private String proxyHost = Configuration.getProxyHost(); private int proxyPort = Configuration.getProxyPort(); private String proxyAuthUser = Configuration.getProxyUser(); private String proxyAuthPassword = Configuration.getProxyPassword(); public String getProxyHost() { return proxyHost; } /** * Sets proxy host. System property -Dsinat4j.http.proxyHost or * http.proxyHost overrides this attribute. * * @param proxyHost */ public void setProxyHost(String proxyHost) { this.proxyHost = Configuration.getProxyHost(proxyHost); } public int getProxyPort() { return proxyPort; } /** * Sets proxy port. System property -Dsinat4j.http.proxyPort or * -Dhttp.proxyPort overrides this attribute. * * @param proxyPort */ public void setProxyPort(int proxyPort) { this.proxyPort = Configuration.getProxyPort(proxyPort); } public String getProxyAuthUser() { return proxyAuthUser; } /** * Sets proxy authentication user. System property -Dsinat4j.http.proxyUser * overrides this attribute. * * @param proxyAuthUser */ public void setProxyAuthUser(String proxyAuthUser) { this.proxyAuthUser = Configuration.getProxyUser(proxyAuthUser); } public String getProxyAuthPassword() { return proxyAuthPassword; } /** * Sets proxy authentication password. System property * -Dsinat4j.http.proxyPassword overrides this attribute. * * @param proxyAuthPassword */ public void setProxyAuthPassword(String proxyAuthPassword) { this.proxyAuthPassword = Configuration.getProxyPassword(proxyAuthPassword); } private final static boolean DEBUG = Configuration.getDebug(); static Logger log = Logger.getLogger(HttpClient.class.getName()); org.apache.commons.httpclient.HttpClient client = null; private MultiThreadedHttpConnectionManager connectionManager; private int maxSize; public HttpClient() { this(150, 30000, 30000, 1024 * 1024); } public HttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize) { connectionManager = new MultiThreadedHttpConnectionManager(); HttpConnectionManagerParams params = connectionManager.getParams(); params.setDefaultMaxConnectionsPerHost(maxConPerHost); params.setConnectionTimeout(conTimeOutMs); params.setSoTimeout(soTimeOutMs); HttpClientParams clientParams = new HttpClientParams(); // 忽略cookie 避免 Cookie rejected 警告 clientParams.setCookiePolicy(CookiePolicy.IGNORE_COOKIES); client = new org.apache.commons.httpclient.HttpClient(clientParams, connectionManager); Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443); Protocol.registerProtocol("https", myhttps); this.maxSize = maxSize; // 支持proxy if (proxyHost != null && !proxyHost.equals("")) { client.getHostConfiguration().setProxy(proxyHost, proxyPort); client.getParams().setAuthenticationPreemptive(true); if (proxyAuthUser != null && !proxyAuthUser.equals("")) { client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxyAuthUser, proxyAuthPassword)); log("Proxy AuthUser: " + proxyAuthUser); log("Proxy AuthPassword: " + proxyAuthPassword); } } } /** * log调试 */ private static void log(String message) { if (DEBUG) { log.debug(message); } } /** * 处理http getmethod 请求 */ public Response get(String url, String token) throws WeiboException { return get(url, new PostParameter[0], token); } public Response get(String url, PostParameter[] params, String token) throws WeiboException { log("Request:"); log("GET:" + url); if (null != params && params.length > 0) { String encodedParams = HttpClient.encodeParameters(params); if (-1 == url.indexOf("?")) { url += "?" + encodedParams; } else { url += "&" + encodedParams; } } GetMethod getmethod = new GetMethod(url); return httpRequest(getmethod, token); } public Response get(String url, PostParameter[] params, Paging paging, String token) throws WeiboException { if (null != paging) { List<PostParameter> pagingParams = new ArrayList<PostParameter>(4); if (-1 != paging.getMaxId()) { pagingParams.add(new PostParameter("max_id", String.valueOf(paging.getMaxId()))); } if (-1 != paging.getSinceId()) { pagingParams.add(new PostParameter("since_id", String.valueOf(paging.getSinceId()))); } if (-1 != paging.getPage()) { pagingParams.add(new PostParameter("page", String.valueOf(paging.getPage()))); } if (-1 != paging.getCount()) { if (-1 != url.indexOf("search")) { // search api takes "rpp" pagingParams.add(new PostParameter("rpp", String.valueOf(paging.getCount()))); } else { pagingParams.add(new PostParameter("count", String.valueOf(paging.getCount()))); } } PostParameter[] newparams = null; PostParameter[] arrayPagingParams = pagingParams.toArray(new PostParameter[pagingParams.size()]); if (null != params) { newparams = new PostParameter[params.length + pagingParams.size()]; System.arraycopy(params, 0, newparams, 0, params.length); System.arraycopy(arrayPagingParams, 0, newparams, params.length, pagingParams.size()); } else { if (0 != arrayPagingParams.length) { String encodedParams = HttpClient.encodeParameters(arrayPagingParams); if (-1 != url.indexOf("?")) { url += "&" + encodedParams; } else { url += "?" + encodedParams; } } } return get(url, newparams, token); } else { return get(url, params, token); } } /** * 处理http deletemethod请求 */ public Response delete(String url, PostParameter[] params, String token) throws WeiboException { if (0 != params.length) { String encodedParams = HttpClient.encodeParameters(params); if (-1 == url.indexOf("?")) { url += "?" + encodedParams; } else { url += "&" + encodedParams; } } DeleteMethod deleteMethod = new DeleteMethod(url); return httpRequest(deleteMethod, token); } /** * 处理http post请求 */ public Response post(String url, PostParameter[] params, String token) throws WeiboException { return post(url, params, true, token); } public Response post(String url, PostParameter[] params, Boolean WithTokenHeader, String token) throws WeiboException { log("Request:"); log("POST" + url); PostMethod postMethod = new PostMethod(url); for (int i = 0; i < params.length; i++) { postMethod.addParameter(params[i].getName(), params[i].getValue()); } HttpMethodParams param = postMethod.getParams(); param.setContentCharset("UTF-8"); return httpRequest(postMethod, WithTokenHeader, token); } /** * 支持multipart方式上传图片 */ public Response multPartURL(String url, PostParameter[] params, ImageItem item, String token) throws WeiboException { PostMethod postMethod = new PostMethod(url); try { Part[] parts = null; if (params == null) { parts = new Part[1]; } else { parts = new Part[params.length + 1]; } if (params != null) { int i = 0; for (PostParameter entry : params) { parts[i++] = new StringPart(entry.getName(), (String) entry.getValue()); } parts[parts.length - 1] = new ByteArrayPart(item.getContent(), item.getName(), item.getContentType()); } postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams())); return httpRequest(postMethod, token); } catch (Exception ex) { throw new WeiboException(ex.getMessage(), ex, -1); } } public Response multPartURL(String fileParamName, String url, PostParameter[] params, File file, boolean authenticated, String token) throws WeiboException { PostMethod postMethod = new PostMethod(url); try { Part[] parts = null; if (params == null) { parts = new Part[1]; } else { parts = new Part[params.length + 1]; } if (params != null) { int i = 0; for (PostParameter entry : params) { parts[i++] = new StringPart(entry.getName(), (String) entry.getValue()); } } FilePart filePart = new FilePart(fileParamName, file.getName(), file, new MimetypesFileTypeMap().getContentType(file), "UTF-8"); filePart.setTransferEncoding("binary"); parts[parts.length - 1] = filePart; postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams())); return httpRequest(postMethod, token); } catch (Exception ex) { throw new WeiboException(ex.getMessage(), ex, -1); } } public Response httpRequest(HttpMethod method, String token) throws WeiboException { return httpRequest(method, true, token); } public Response httpRequest(HttpMethod method, Boolean WithTokenHeader, String token) throws WeiboException { InetAddress ipaddr; int responseCode = -1; try { ipaddr = InetAddress.getLocalHost(); List<Header> headers = new ArrayList<Header>(); if (WithTokenHeader) { if (token == null) { throw new IllegalStateException("Oauth2 token is not set!"); } headers.add(new Header("Authorization", "OAuth2 " + token)); headers.add(new Header("API-RemoteIP", ipaddr.getHostAddress())); client.getHostConfiguration().getParams().setParameter("http.default-headers", headers); for (Header hd : headers) { log(hd.getName() + ": " + hd.getValue()); } } method.getParams() .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); client.executeMethod(method); Header[] resHeader = method.getResponseHeaders(); responseCode = method.getStatusCode(); log("Response:"); log("https StatusCode:" + String.valueOf(responseCode)); for (Header header : resHeader) { log(header.getName() + ":" + header.getValue()); } Response response = new Response(); response.setResponseAsString(method.getResponseBodyAsString()); log(response.toString() + "\n"); if (responseCode != OK) { try { throw new WeiboException(getCause(responseCode), response.asJSONObject(), method.getStatusCode()); } catch (JSONException e) { e.printStackTrace(); } } return response; } catch (IOException ioe) { throw new WeiboException(ioe.getMessage(), ioe, responseCode); } finally { method.releaseConnection(); } } /* * 对parameters进行encode处理 */ public static String encodeParameters(PostParameter[] postParams) { StringBuffer buf = new StringBuffer(); for (int j = 0; j < postParams.length; j++) { if (j != 0) { buf.append("&"); } try { buf.append(URLEncoder.encode(postParams[j].getName(), "UTF-8")).append("=") .append(URLEncoder.encode(postParams[j].getValue(), "UTF-8")); } catch (java.io.UnsupportedEncodingException neverHappen) { } } return buf.toString(); } private static class ByteArrayPart extends PartBase { private byte[] mData; private String mName; public ByteArrayPart(byte[] data, String name, String type) throws IOException { super(name, type, "UTF-8", "binary"); mName = name; mData = data; } protected void sendData(OutputStream out) throws IOException { out.write(mData); } protected long lengthOfData() throws IOException { return mData.length; } protected void sendDispositionHeader(OutputStream out) throws IOException { super.sendDispositionHeader(out); StringBuilder buf = new StringBuilder(); buf.append("; filename=\"").append(mName).append("\""); out.write(buf.toString().getBytes()); } } private static String getCause(int statusCode) { String cause = null; switch (statusCode) { case NOT_MODIFIED: break; case BAD_REQUEST: cause = "The request was invalid. An accompanying error message will explain why. This is the status code will be returned during rate limiting."; break; case NOT_AUTHORIZED: cause = "Authentication credentials were missing or incorrect."; break; case FORBIDDEN: cause = "The request is understood, but it has been refused. An accompanying error message will explain why."; break; case NOT_FOUND: cause = "The URI requested is invalid or the resource requested, such as a user, does not exists."; break; case NOT_ACCEPTABLE: cause = "Returned by the Search API when an invalid format is specified in the request."; break; case INTERNAL_SERVER_ERROR: cause = "Something is broken. Please post to the group so the Weibo team can investigate."; break; case BAD_GATEWAY: cause = "Weibo is down or being upgraded."; break; case SERVICE_UNAVAILABLE: cause = "Service Unavailable: The Weibo servers are up, but overloaded with requests. Try again later. The search and trend methods use this to indicate when you are being rate limited."; break; default: cause = ""; } return statusCode + ":" + cause; } }
jpbirdy/WordsDetection
weibo/src/main/java/weibo4j/http/HttpClient.java
Java
apache-2.0
18,712
/** * @license * Copyright 2014 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Asynchronous eval workaround for lack of eval in Chrome Apps. Do not add // workaround in Cordova Chrome Apps. if ( ! (window.cordova && window.chrome) ) { TemplateUtil.compile = function() { return function() { return this.name_ + " wasn't required. Models must be arequired()'ed for Templates to be compiled in Packaged Apps."; }; }; var __EVAL_CALLBACKS__ = {}; var aeval = (function() { var nextID = 0; var future = afuture(); if ( ! document.body ) window.addEventListener('load', future.set); else future.set(); return function(src) { return aseq( future.get, function(ret) { var id = 'c' + (nextID++); var newjs = ['__EVAL_CALLBACKS__["' + id + '"](' + src + ');']; var blob = new Blob(newjs, {type: 'text/javascript'}); var url = window.URL.createObjectURL(blob); // TODO: best values? // url.defer = ?; // url.async = ?; __EVAL_CALLBACKS__[id] = function(data) { delete __EVAL_CALLBACKS__[id]; ret && ret.call(this, data); }; var script = document.createElement('script'); script.src = url; script.onload = function() { this.remove(); window.URL.revokeObjectURL(url); // document.body.removeChild(this); }; document.body.appendChild(script); }); }; })(); var TEMPLATE_FUNCTIONS = []; var aevalTemplate = function(t, model) { var doEval_ = function(t) { // Parse result: [isSimple, maybeCode]: [true, null] or [false, codeString]. var parseResult = TemplateCompiler.parseString(t.template); // Simple case, just a string literal if ( parseResult[0] ) return aconstant(ConstantTemplate(t.language === 'css' ? X.foam.grammars.CSS3.create().parser.parseString(t.template).toString() : t.template)); var code = TemplateUtil.HEADER + parseResult[1] + TemplateUtil.FOOTERS[t.language]; var args = ['opt_out']; if ( t.args ) { for ( var i = 0 ; i < t.args.length ; i++ ) { args.push(t.args[i].name); } } return aeval('function(' + args.join(',') + '){' + code + '}'); }; var doEval = function(t) { try { return doEval_(t); } catch (err) { console.log('Template Error: ', err); console.log(code); return aconstant(function() {return 'TemplateError: Check console.';}); } }; var i = TEMPLATE_FUNCTIONS.length; TEMPLATE_FUNCTIONS[i] = ''; return aseq( t.futureTemplate, function(ret, t) { doEval(t)(ret); }, function(ret, f) { TEMPLATE_FUNCTIONS[i] = f; ret(f); }); }; }
osric-the-knight/foam
core/ChromeEval.js
JavaScript
apache-2.0
3,509
package mx.fiscoflex.contabilidad.util; public class UUIDCheck { public static boolean isUUID(String uuid) { return uuid.matches("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[34][0-9a-fA-F]{3}-[89ab][0-9a-fA-F]{3}-[0-9a-fA-F]{12}"); } }
fiscoflex/erp
fiscoflex-api/src/main/java/mx/fiscoflex/contabilidad/util/UUIDCheck.java
Java
apache-2.0
229
/** * Copyright 2005-2013 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.rice.ksb.messaging.remotedservices; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; /** * JAX-RS annotated interface for a baseball card collection service which might track the * cards in a collection. * * @author Kuali Rice Team (rice.collab@kuali.org) * */ @Path("/") public interface BaseballCardCollectionService { @GET public List<BaseballCard> getAll(); /** * gets a card by it's (arbitrary) identifier */ @GET @Path("/BaseballCard/id/{id}") public BaseballCard get(@PathParam("id") Integer id); /** * gets all the cards in the collection with the given player name */ @GET @Path("/BaseballCard/playerName/{playerName}") public List<BaseballCard> get(@PathParam("playerName") String playerName); /** * Add a card to the collection. This is a non-idempotent method * (because you can more one of the same card), so we'll use @POST * @return the (arbitrary) numerical identifier assigned to this card by the service */ @POST @Path("/BaseballCard") public Integer add(BaseballCard card); /** * update the card for the given identifier. This will replace the card that was previously * associated with that identifier. */ @PUT @Path("/BaseballCard/id/{id}") @Consumes("application/xml") public void update(@PathParam("id") Integer id, BaseballCard card); /** * delete the card with the given identifier. */ @DELETE @Path("/BaseballCard/id/{id}") public void delete(@PathParam("id") Integer id); /** * This method lacks JAX-RS annotations */ public void unannotatedMethod(); }
ua-eas/ksd-kc5.2.1-rice2.3.6-ua
rice-middleware/it/ksb/src/test/java/org/kuali/rice/ksb/messaging/remotedservices/BaseballCardCollectionService.java
Java
apache-2.0
2,496
/* * Copyright 2016 Jalotsav * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.jalotsav.sarvamsugar.navgtndrawer; import android.Manifest; import android.app.DatePickerDialog; import android.content.pm.PackageManager; import android.graphics.Color; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.support.v7.widget.AppCompatAutoCompleteTextView; import android.support.v7.widget.AppCompatButton; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.DatePicker; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.Spinner; import android.widget.TextView; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.jalotsav.sarvamsugar.R; import com.jalotsav.sarvamsugar.adapters.RcyclrOutstandingAdapter; import com.jalotsav.sarvamsugar.common.AppConstants; import com.jalotsav.sarvamsugar.common.GeneralFuncations; import com.jalotsav.sarvamsugar.common.LogManager; import com.jalotsav.sarvamsugar.common.RecyclerViewEmptySupport; import com.jalotsav.sarvamsugar.common.UserSessionManager; import com.jalotsav.sarvamsugar.model.MdlOutstanding; import com.jalotsav.sarvamsugar.model.MdlOutstandingData; import com.jalotsav.sarvamsugar.retrofitapihelper.RetroAPI; import com.mikepenz.community_material_typeface_library.CommunityMaterial; import com.mikepenz.iconics.IconicsDrawable; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Calendar; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; /** * Created by JALOTSAV Dev. on 20/7/16. */ public class FrgmntOutstandingRprt extends Fragment implements AppConstants, View.OnClickListener { UserSessionManager mSession; CoordinatorLayout mCordntrlyotMain; ProgressBar mPrgrsbrMain; LinearLayout mLnrlyotAppearHere; TextView mTvAppearHere; RecyclerViewEmptySupport mRecyclerView; RecyclerView.LayoutManager mLayoutManager; RcyclrOutstandingAdapter mAdapter; FloatingActionButton mFabFilters, mFabApply; LinearLayout mLnrlyotFilters; ImageView mImgvwFltrRemove, mImgvwFltrClose; Spinner mSpnrFltrBy, mSpnrDateType, mSpnrSortby; AppCompatAutoCompleteTextView mAppcmptAutocmplttvSlctdFltrVal; AppCompatButton mAppcmptbtnToDate; MdlOutstanding mObjMdlOutstndng; ArrayList<MdlOutstandingData> mArrylstOutstndngData; ArrayList<String> mArrylstParty, mArrylstDalal, mArrylstArea, mArrylstZone; Calendar mCalndr; int mCrntYear, mCrntMonth, mCrntDay, mToYear, mToMonth, mToDay; String mReqstToDt, mQueryParty, mQueryDalal, mQueryArea, mQueryZone, mReqstType, mReqstSortby; boolean isAPICall = false; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.lo_frgmnt_outstanding_report, container, false); setHasOptionsMenu(true); mCordntrlyotMain = (CoordinatorLayout) rootView.findViewById(R.id.cordntrlyot_outstndng); mPrgrsbrMain = (ProgressBar) rootView.findViewById(R.id.prgrsbr_outstndng_main); mLnrlyotAppearHere = (LinearLayout) rootView.findViewById(R.id.lnrlyot_recyclremptyvw_appearhere); mTvAppearHere = (TextView) rootView.findViewById(R.id.tv_recyclremptyvw_appearhere); mRecyclerView = (RecyclerViewEmptySupport) rootView.findViewById(R.id.rcyclrvw_outstndng); mFabFilters = (FloatingActionButton) rootView.findViewById(R.id.fab_outstndng_filters); mFabApply = (FloatingActionButton) rootView.findViewById(R.id.fab_outstndng_apply); mLnrlyotFilters = (LinearLayout) rootView.findViewById(R.id.lnrlyot_outstndng_filtersvw); mImgvwFltrRemove = (ImageView) rootView.findViewById(R.id.imgvw_outstndng_fltrremove); mImgvwFltrClose = (ImageView) rootView.findViewById(R.id.imgvw_outstndng_fltrclose); mSpnrFltrBy = (Spinner) rootView.findViewById(R.id.spnr_outstndng_filterby); mSpnrDateType = (Spinner) rootView.findViewById(R.id.spnr_outstndng_datetype); mSpnrSortby = (Spinner) rootView.findViewById(R.id.spnr_outstndng_sortby); mAppcmptAutocmplttvSlctdFltrVal = (AppCompatAutoCompleteTextView) rootView.findViewById(R.id.apcmptautocmplttv_outstndng_slctdfilterval); mAppcmptbtnToDate = (AppCompatButton) rootView.findViewById(R.id.appcmptbtn_outstndng_slcttodate); mLayoutManager = new LinearLayoutManager(getActivity()); mRecyclerView.setHasFixedSize(true); mRecyclerView.setLayoutManager(mLayoutManager); mRecyclerView.setEmptyView(mLnrlyotAppearHere); mSession = new UserSessionManager(getActivity()); mFabFilters.setImageDrawable(new IconicsDrawable(getActivity()) .icon(CommunityMaterial.Icon.cmd_filter) .color(Color.WHITE)); mFabFilters.setVisibility(View.GONE); mFabApply.setImageDrawable(new IconicsDrawable(getActivity()) .icon(CommunityMaterial.Icon.cmd_check) .color(Color.WHITE)); mFabFilters.setOnClickListener(this); mFabApply.setOnClickListener(this); mImgvwFltrRemove.setOnClickListener(this); mImgvwFltrClose.setOnClickListener(this); mAppcmptbtnToDate.setOnClickListener(this); mTvAppearHere.setText(getString(R.string.outstndng_appear_here)); mArrylstOutstndngData = new ArrayList<>(); mArrylstParty = new ArrayList<>(); mArrylstDalal = new ArrayList<>(); mArrylstArea = new ArrayList<>(); mArrylstZone = new ArrayList<>(); ArrayList<MdlOutstandingData> arrylstOutstndngData = new ArrayList<>(); mAdapter = new RcyclrOutstandingAdapter(getActivity(), arrylstOutstndngData); mRecyclerView.setAdapter(mAdapter); mCalndr = Calendar.getInstance(); mCrntYear = mToYear = mCalndr.get(Calendar.YEAR); mCrntMonth = mToMonth = mCalndr.get(Calendar.MONTH); mCrntDay = mToDay = mCalndr.get(Calendar.DAY_OF_MONTH); mReqstToDt = GeneralFuncations.setDateIn2Digit(mToDay) + "-" + GeneralFuncations.setDateIn2Digit(mToMonth+1) + "-" + mToYear; // Format "15-09-2016" mAppcmptbtnToDate.setText(getResources().getString(R.string.to_date_val, mReqstToDt)); mQueryParty = ""; mQueryDalal = ""; mQueryArea = ""; mQueryZone = ""; mReqstType = ""; mReqstSortby = ""; // Check Storage permission before call AsyncTask for data isAPICall = false; checkStoragePermission(); mSpnrFltrBy.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) { ((TextView) adapterView.getChildAt(0)).setTextColor(ContextCompat.getColor(getActivity(), R.color.colorPrimaryAmber)); mAppcmptAutocmplttvSlctdFltrVal.setText(""); if (position == 0) { mAppcmptAutocmplttvSlctdFltrVal.setVisibility(View.GONE); // mFabApply.setVisibility(View.GONE); } else { mAppcmptAutocmplttvSlctdFltrVal.setVisibility(View.VISIBLE); // mFabApply.setVisibility(View.VISIBLE); setAutoCompltTvAdapter(position); } } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); mSpnrDateType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) { ((TextView) adapterView.getChildAt(0)).setTextColor(ContextCompat.getColor(getActivity(), R.color.colorPrimaryAmber)); if (position == 2) mReqstType = "1"; else mReqstType = "0"; } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); mSpnrSortby.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) { ((TextView) adapterView.getChildAt(0)).setTextColor(ContextCompat.getColor(getActivity(), R.color.colorPrimaryAmber)); if (position == 2) mReqstSortby = "1"; else mReqstSortby = "0"; } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); return rootView; } private void checkStoragePermission() { try { if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { LogManager.printLog(LOGTYPE_INFO, "Permission Granted"); if (isAPICall) getOutstandingAPI(); // Call API through Retrofit and store response JSON into device storage file else new getOutstandingFromFileAsync().execute(); // AsyncTask through get JSON data of API from device storage file } else { if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)) GeneralFuncations.showtoastLngthlong(getActivity(), getString(R.string.you_must_allow_permsn)); requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_PERMSN_STORAGE); } } catch (Exception e) { e.printStackTrace(); } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_PERMSN_STORAGE) { if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) checkStoragePermission(); else showMySnackBar(getString(R.string.permsn_denied)); } } // Call API through Retrofit and store response JSON into device storage file private void getOutstandingAPI() { mPrgrsbrMain.setVisibility(View.VISIBLE); mFabFilters.setVisibility(View.GONE); OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder(); clientBuilder.connectTimeout(3, TimeUnit.MINUTES); clientBuilder.readTimeout(3, TimeUnit.MINUTES); Retrofit objRetrofit = new Retrofit.Builder() .baseUrl(API_ROOT_URL) .client(clientBuilder.build()) .addConverterFactory(GsonConverterFactory.create()) .build(); RetroAPI apiDalalwsSls = objRetrofit.create(RetroAPI.class); Call<ResponseBody> callGodownStck = apiDalalwsSls.getOutstanding( API_METHOD_GETOUTSTAND, mSession.getUserId(), mSession.getUserType(), mReqstToDt, mReqstType, mQueryParty, mQueryDalal, mQueryArea, mQueryZone, mReqstSortby ); callGodownStck.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if (mPrgrsbrMain.isShown()) mPrgrsbrMain.setVisibility(View.GONE); if (response.isSuccessful()) { String[] strArray = new String[1]; try { LogManager.printLog(LOGTYPE_INFO, "Reponse is successful: " + response.isSuccessful()); strArray[0] = response.body().string(); // Create and save API response in device storage in .json file storeJSONDataToStorage(strArray[0]); // AsynTask through get JSON data of API from device storage file new getOutstandingFromFileAsync().execute(); } catch (Exception e) { e.printStackTrace(); } } else showMySnackBar(getString(R.string.there_are_some_server_prblm)); } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { t.printStackTrace(); mPrgrsbrMain.setVisibility(View.GONE); if (!mFabFilters.isShown()) mFabFilters.setVisibility(View.VISIBLE); showMySnackBar(getString(R.string.there_are_some_prblm)); } }); } // Create and save API response in device storage in .json file private void storeJSONDataToStorage(String strResponse) { try { File filesDirectory = PATH_SARVAMSUGAR_FILES; if (!filesDirectory.exists()) filesDirectory.mkdirs(); File fileJson = new File(filesDirectory, OUTSTANDING_JSON); if (fileJson.exists()) fileJson.delete(); fileJson.createNewFile(); FileOutputStream fOut = new FileOutputStream(fileJson); OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut); myOutWriter.append(strResponse); myOutWriter.close(); fOut.close(); } catch (Exception e) { e.printStackTrace(); } } // AsynTask through get JSON data of API from device storage file public class getOutstandingFromFileAsync extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { super.onPreExecute(); mPrgrsbrMain.setVisibility(View.VISIBLE); } @Override protected Void doInBackground(Void... voids) { mObjMdlOutstndng = getJSONDataFromStorage(); if (mObjMdlOutstndng != null) { if (TextUtils.isEmpty(mObjMdlOutstndng.getResult()) || mObjMdlOutstndng.getData() == null) { showMySnackBar(getString(R.string.sync_data_msg)); } else if (mObjMdlOutstndng.getResult().equalsIgnoreCase(RESULT_ONE)) { mArrylstOutstndngData = mObjMdlOutstndng.getData(); if (!mArrylstOutstndngData.isEmpty()) { for(MdlOutstandingData objMdlOutstandingData : mArrylstOutstndngData) { if(!mArrylstParty.contains(objMdlOutstandingData.getPname())) mArrylstParty.add(objMdlOutstandingData.getPname()); if(!mArrylstDalal.contains(objMdlOutstandingData.getDalalName())) mArrylstDalal.add(objMdlOutstandingData.getDalalName()); if(!mArrylstArea.contains(objMdlOutstandingData.getArea())) mArrylstArea.add(objMdlOutstandingData.getArea()); if(!mArrylstZone.contains(objMdlOutstandingData.getZone())) mArrylstZone.add(objMdlOutstandingData.getZone()); } if(isAdded()) setAutoCompltTvAdapter(0); } } else showMySnackBar(getString(R.string.there_are_some_prblm)); } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); if(isAdded()) { mPrgrsbrMain.setVisibility(View.GONE); if (!mArrylstOutstndngData.isEmpty()) { showMySnackBar(getResources().getString(R.string.value_records_sml, mArrylstOutstndngData.size())); mFabFilters.setVisibility(View.VISIBLE); } mAdapter.setFilter(mArrylstOutstndngData); } } } // Create and save API response in device storage in .json file private MdlOutstanding getJSONDataFromStorage() { try { mObjMdlOutstndng = new MdlOutstanding(); File filesDirectory = PATH_SARVAMSUGAR_FILES; if (!filesDirectory.exists()) filesDirectory.mkdirs(); File fileJson = new File(filesDirectory, OUTSTANDING_JSON); if (fileJson.exists()) { FileInputStream fIn = new FileInputStream(fileJson); BufferedReader myReader = new BufferedReader( new InputStreamReader(fIn)); String aDataRow = ""; String aBuffer = ""; while ((aDataRow = myReader.readLine()) != null) { aBuffer += aDataRow + "\n"; } myReader.close(); Gson mGson = new GsonBuilder().create(); mObjMdlOutstndng = mGson.fromJson(aBuffer, MdlOutstanding.class); } } catch (Exception e) { e.printStackTrace(); } return mObjMdlOutstndng; } private void setAutoCompltTvAdapter(int spnrSlctdPosition) { mAppcmptAutocmplttvSlctdFltrVal.setThreshold(1); ArrayAdapter<String> adapterPName = new ArrayAdapter<> (getActivity(), android.R.layout.simple_list_item_1, mArrylstParty); ArrayAdapter<String> adapterDalal = new ArrayAdapter<> (getActivity(), android.R.layout.simple_list_item_1, mArrylstDalal); ArrayAdapter<String> adapterArea = new ArrayAdapter<> (getActivity(), android.R.layout.simple_list_item_1, mArrylstArea); ArrayAdapter<String> adapterZone = new ArrayAdapter<> (getActivity(), android.R.layout.simple_list_item_1, mArrylstZone); switch (spnrSlctdPosition) { case 1: mAppcmptAutocmplttvSlctdFltrVal.setAdapter(adapterPName); break; case 2: mAppcmptAutocmplttvSlctdFltrVal.setAdapter(adapterDalal); break; case 3: mAppcmptAutocmplttvSlctdFltrVal.setAdapter(adapterArea); break; case 4: mAppcmptAutocmplttvSlctdFltrVal.setAdapter(adapterZone); break; } } @Override public void onClick(View view) { switch (view.getId()) { case R.id.fab_outstndng_filters: showFiltersView(); // Show Filters View break; case R.id.fab_outstndng_apply: String slctdFltrVal = mAppcmptAutocmplttvSlctdFltrVal.getText().toString().trim(); if (!TextUtils.isEmpty(slctdFltrVal)) { switch (mSpnrFltrBy.getSelectedItemPosition()) { case 1: mQueryParty = slctdFltrVal; break; case 2: mQueryDalal = slctdFltrVal; break; case 3: mQueryArea = slctdFltrVal; break; case 4: mQueryZone = slctdFltrVal; break; } } if (!GeneralFuncations.isNetConnected(getActivity())) { mAdapter.setFilter(filters(mArrylstOutstndngData)); } else getOutstandingAPI(); hideFiltersView(); // Hide Filters View break; case R.id.imgvw_outstndng_fltrremove: mToDay = mCrntDay; mToMonth = mCrntMonth; mToYear = mCrntYear; mReqstToDt = GeneralFuncations.setDateIn2Digit(mToDay) + "-" + GeneralFuncations.setDateIn2Digit(mToMonth+1) + "-" + mToYear; // Format "15-09-2016" mAppcmptbtnToDate.setText(getResources().getString(R.string.to_date_val, mReqstToDt)); ArrayList<MdlOutstandingData> arrylstOutstndngData = new ArrayList<>(); mAdapter.setFilter(arrylstOutstndngData); mSpnrFltrBy.setSelection(0); mAppcmptAutocmplttvSlctdFltrVal.setText(""); mQueryParty = ""; mQueryDalal = ""; mQueryArea = ""; mQueryZone = ""; mReqstType = ""; mReqstSortby = ""; // Check Storage permission before call AsyncTask for data isAPICall = false; checkStoragePermission(); hideFiltersView(); // Hide Filters View break; case R.id.imgvw_outstndng_fltrclose: hideFiltersView(); // Hide Filters View break; case R.id.appcmptbtn_outstndng_slcttodate: DatePickerDialog mToDatePckrDlg = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker datePicker, int year, int month, int day) { mToYear = year; mToMonth = month; mToDay = day; month++; mReqstToDt = GeneralFuncations.setDateIn2Digit(day) + "-" + GeneralFuncations.setDateIn2Digit(month) + "-" + year; mAppcmptbtnToDate.setText(getResources().getString(R.string.to_date_val, mReqstToDt)); } }, mToYear, mToMonth, mToDay); mToDatePckrDlg.show(); break; } } // Show Filters View private void showFiltersView() { mFabFilters.setVisibility(View.GONE); mLnrlyotFilters.setVisibility(View.VISIBLE); mFabApply.setVisibility(View.VISIBLE); } // Hide Filters View private void hideFiltersView() { mFabFilters.setVisibility(View.VISIBLE); mLnrlyotFilters.setVisibility(View.GONE); mFabApply.setVisibility(View.GONE); } private ArrayList<MdlOutstandingData> filters(ArrayList<MdlOutstandingData> arrylstMdlOutstandingData) { ArrayList<MdlOutstandingData> fltrdOutstandingData = new ArrayList<>(); for (MdlOutstandingData objMdlOutstandingData : arrylstMdlOutstandingData) { String targetParty = objMdlOutstandingData.getPname().toLowerCase(); String targetDalal = objMdlOutstandingData.getDalalName().toLowerCase(); String targetArea = objMdlOutstandingData.getArea().toLowerCase(); String targetZone = objMdlOutstandingData.getZone().toLowerCase(); if (targetParty.contains(mQueryParty.toLowerCase()) && targetDalal.contains(mQueryDalal.toLowerCase()) && targetArea.contains(mQueryArea.toLowerCase()) && targetZone.contains(mQueryZone.toLowerCase())) { fltrdOutstandingData.add(objMdlOutstandingData); } } return fltrdOutstandingData; } // Show SnackBar with given message private void showMySnackBar(String message) { Snackbar.make(mCordntrlyotMain, message, Snackbar.LENGTH_LONG).show(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.menu_refresh, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_refresh: if (!GeneralFuncations.isNetConnected(getActivity())) { // Show SnackBar with given message showMySnackBar(getResources().getString(R.string.no_intrnt_cnctn)); } else { isAPICall = true; checkStoragePermission(); } break; } return super.onOptionsItemSelected(item); } }
jalotsav/Sarvam-Sugar
app/src/main/java/com/jalotsav/sarvamsugar/navgtndrawer/FrgmntOutstandingRprt.java
Java
apache-2.0
25,900
/** * Copyright 2020 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {mod} from '../../../src/utils/math'; /** * @enum {number} */ export const Axis = { X: 0, Y: 1, }; /** * @enum {string} */ export const Alignment = { START: 'start', CENTER: 'center', }; /** * @enum {string} */ export const Orientation = { HORIZONTAL: 'horizontal', VERTICAL: 'vertical', }; /** * @typedef {{ * start: number, * end: number, * length: number, * }} */ let BaseCarouselDimensionDef; /** * @param {!Axis} axis The Axis to get the Dimension for. * @param {*} el The Element to get the Dimension For. * @return {!BaseCarouselDimensionDef} The dimension for the Element along the given Axis. */ export function getDimension(axis, el) { const { top, bottom, height, left, right, width, } = el./*OK*/ getBoundingClientRect(); return { start: Math.round(axis == Axis.X ? left : top), end: Math.round(axis == Axis.X ? right : bottom), length: Math.round(axis == Axis.X ? width : height), }; } /** * @param {!Axis} axis The axis to get the center point for. * @param {!Element} el The Element to get the center point for. * @return {number} The center point. */ export function getCenter(axis, el) { const {start, end} = getDimension(axis, el); return (start + end) / 2; } /** * @param {!Axis} axis The axis to get the start point for. * @param {!Element} el The Element to get the start point for. * @return {number} The start point. */ export function getStart(axis, el) { const {start} = getDimension(axis, el); return start; } /** * @param {!Axis} axis The Axis to get the position for. * @param {!Alignment} alignment The Alignment to get the position for. * @param {!Element} el The Element to get the position for. * @return {number} The position for the given Element along the given axis for * the given alignment. */ export function getPosition(axis, alignment, el) { return alignment == Alignment.START ? getStart(axis, el) : getCenter(axis, el); } /** * @param {!Axis} axis The axis to check for overlap. * @param {!Element} el The Element to check for overlap. * @param {number} position A position to check. * @return {boolean} If the element overlaps the position along the given axis. */ export function overlaps(axis, el, position) { const {start, end} = getDimension(axis, el); // Ignore the end point, since that is shared with the adjacent Element. return start <= position && position < end; } /** * @param {!Axis} axis The axis to align on. * @param {!Alignment} alignment The desired alignment. * @param {!Element} container The container to align against. * @param {!Element} el The Element get the offset for. * @return {number} How far el is from alignment, as a percentage of its length. */ export function getPercentageOffsetFromAlignment( axis, alignment, container, el ) { const elPos = getPosition(axis, alignment, el); const containerPos = getPosition(axis, alignment, container); const {length: elLength} = getDimension(axis, el); return (elPos - containerPos) / elLength; } /** * Finds the index of a child that overlaps a point within the parent, * determined by an axis and alignment. A startIndex is used to look at the * children that are more likely to overlap first. * @param {!Axis} axis The axis to look along. * @param {!Alignment} alignment The alignment to look for within the parent * container. * @param {!Element} container The parent container to look in. * @param {!HTMLCollection} children The children to look among. * @param {number} startIndex The index to start looking at. * @return {number|undefined} The overlapping index, if one exists. */ export function findOverlappingIndex( axis, alignment, container, children, startIndex ) { const pos = getPosition(axis, alignment, container); // First look at the start index, since is the most likely to overlap. if (overlaps(axis, children[startIndex], pos)) { return startIndex; } // Move outwards, since the closer indicies are more likely to overlap. for (let i = 1; i <= children.length / 2; i++) { const nextIndex = mod(startIndex + i, children.length); const prevIndex = mod(startIndex - i, children.length); if (overlaps(axis, children[nextIndex], pos)) { return nextIndex; } if (overlaps(axis, children[prevIndex], pos)) { return prevIndex; } } } /** * Gets the current scroll position for an element along a given axis. * @param {!Axis} axis The axis to set the scroll position for. * @param {!Element} el The Element to set the scroll position for. * @return {number} The scroll position. */ export function getScrollPosition(axis, el) { if (axis == Axis.X) { return el./*OK*/ scrollLeft; } return el./*OK*/ scrollTop; } /** * Sets the scroll position for an element along a given axis. * @param {!Axis} axis The axis to set the scroll position for. * @param {!Element} el The Element to set the scroll position for. * @param {number} position The scroll position. */ export function setScrollPosition(axis, el, position) { if (axis == Axis.X) { el./*OK*/ scrollLeft = position; } else { el./*OK*/ scrollTop = position; } } /** * Updates the scroll position for an element along a given axis. * @param {!Axis} axis The axis to set the scroll position for. * @param {!Element} el The Element to set the scroll position for. * @param {number} delta The scroll delta. */ export function updateScrollPosition(axis, el, delta) { setScrollPosition(axis, el, getScrollPosition(axis, el) + delta); } /** * Scrolls the position within a scrolling container to an Element. Unlike * `scrollIntoView`, this function does not scroll the container itself into * view. * @param {!Axis} axis The axis to scroll along. * @param {!Alignment} alignment How to align the element within the container. * @param {!Element} container The scrolling container. * @param {!Element} el The Element to scroll to. * @param {number} offset A percentage offset within the element to scroll to. * @return {boolean} Whether not scrolling was performed. */ export function scrollContainerToElement( axis, alignment, container, el, offset = 0 ) { const startAligned = alignment == Alignment.START; const {length} = getDimension(axis, el); const snapOffset = startAligned ? getStart(axis, el) : getCenter(axis, el); const scrollOffset = startAligned ? getStart(axis, container) : getCenter(axis, container); const delta = Math.round(snapOffset - scrollOffset - offset * length); updateScrollPosition(axis, container, delta); return !!delta; }
jmadler/amphtml
extensions/amp-base-carousel/1.0/dimensions.js
JavaScript
apache-2.0
7,290
using System; namespace CompSharp { [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = true)] public class SupportAttribute : Attribute { } }
Dykam/CompSharp
src/CompSharp/SupportAttribute.cs
C#
apache-2.0
196
package com.weather.app.db; import java.util.ArrayList; import java.util.List; import com.weather.app.model.City; import com.weather.app.model.County; import com.weather.app.model.Province; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; public class WeatherDB { public static final String DB_NAME = "weather"; public static final int VERSION = 1; private static WeatherDB weatherDB; private SQLiteDatabase db; private WeatherDB(Context context){ WeatherOpenHelper dbHelper = new WeatherOpenHelper(context, DB_NAME, null, VERSION); db = dbHelper.getWritableDatabase(); } public synchronized static WeatherDB getInstance(Context context){ if(weatherDB == null){ weatherDB = new WeatherDB(context); } return weatherDB; } public void saveProvince(Province province){ if(province != null){ ContentValues values = new ContentValues(); values.put("province_name", province.getProvinceName()); values.put("province_code", province.getProvinceCode()); db.insert("Province", null, values); } } public List<Province> loadProvinces(){ List<Province> list = new ArrayList<Province>(); Cursor cursor = db.query("Province", null, null, null, null, null, null); if(cursor.moveToFirst()){ do{ Province province = new Province(); province.setId(cursor.getInt(cursor.getColumnIndex("id"))); province.setProvinceName(cursor.getString(cursor.getColumnIndex("province_name"))); province.setProvinceCode(cursor.getString(cursor.getColumnIndex("province_code"))); list.add(province); }while(cursor.moveToNext()); } return list; } public void saveCity(City city){ if(city != null){ ContentValues values = new ContentValues(); values.put("city_name", city.getCityName()); values.put("city_code", city.getCityCode()); values.put("province_id", city.getProvinceId()); db.insert("City", null, values); } } public List<City> loadCities(int provinceId){ List<City> list = new ArrayList<City>(); Cursor cursor = db.query("City", null, "province_id = ?", new String[]{String.valueOf(provinceId)}, null, null, null); if(cursor.moveToFirst()){ do{ City city = new City(); city.setId(cursor.getInt(cursor.getColumnIndex("id"))); city.setCityName(cursor.getString(cursor.getColumnIndex("city_name"))); city.setCityCode(cursor.getString(cursor.getColumnIndex("city_code"))); city.setProvinceId(provinceId); list.add(city); }while(cursor.moveToNext()); } return list; } public void saveCounty(County county){ if(county != null){ ContentValues values = new ContentValues(); values.put("county_name", county.getCountyName()); values.put("county_code", county.getCountyCode()); values.put("city_id", county.getCityId()); db.insert("County", null, values); } } public List<County> loadCounties(int cityId){ List<County> list = new ArrayList<County>(); Cursor cursor = db.query("County", null, "city_id = ?", new String[]{String.valueOf(cityId)}, null, null, null); if(cursor.moveToFirst()){ do{ County county = new County(); county.setId(cursor.getInt(cursor.getColumnIndex("id"))); county.setCountyName(cursor.getString(cursor.getColumnIndex("county_name"))); county.setCountyCode(cursor.getString(cursor.getColumnIndex("county_code"))); county.setCityId(cityId); list.add(county); }while(cursor.moveToNext()); } return list; } }
3p14/weather
src/com/weather/app/db/WeatherDB.java
Java
apache-2.0
3,630
package com.rizal.lovins.smartkasir.activity; import android.content.Context; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.app.FragmentActivity; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.rizal.lovins.smartkasir.R; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { private GoogleMap mMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device, the user will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; // Add a marker in Sydney and move the camera LatLng sydney = new LatLng(-34, 151); LocationManager mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } Location location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location != null) { sydney = new LatLng(location.getLatitude(), location.getLongitude()); } mMap.addMarker(new MarkerOptions().position(sydney).title("Current Position")); mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney)); } }
RizalLovins/LovinsSmartKasir
app/src/main/java/com/rizal/lovins/smartkasir/activity/MapsActivity.java
Java
apache-2.0
3,259
package com.topie.humantask.rule; import java.util.Collections; import java.util.List; import com.topie.api.org.OrgConnector; import com.topie.core.spring.ApplicationContextHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 获得指定用户的上级领导. * */ public class SuperiorAssigneeRule implements AssigneeRule { private static Logger logger = LoggerFactory .getLogger(SuperiorAssigneeRule.class); private OrgConnector orgConnector; public List<String> process(String value, String initiator) { return Collections.singletonList(this.process(initiator)); } /** * 获得员工的直接上级. */ public String process(String initiator) { if (orgConnector == null) { orgConnector = ApplicationContextHelper.getBean(OrgConnector.class); } return orgConnector.getSuperiorId(initiator); } }
topie/topie-oa
src/main/java/com/topie/humantask/rule/SuperiorAssigneeRule.java
Java
apache-2.0
922
// Copyright © 2013 - 2014, Alain Metge. All rights reserved. // // This file is part of Hyperstore (http://www.hyperstore.org) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #region Imports using System; using System.Collections.Generic; using System.Linq; using Hyperstore.Modeling.Events; using Hyperstore.Modeling.HyperGraph; #endregion namespace Hyperstore.Modeling.Commands { /// <summary> /// Tracking elements /// </summary> internal class SessionTrackingData : ISessionTrackingData { private readonly Dictionary<Identity, TrackedElement> _elements; private readonly ISession _session; private bool _modelElementsPrepared; ///------------------------------------------------------------------------------------------------- /// <summary> /// Constructor. /// </summary> /// <param name="session"> /// The session. /// </param> ///------------------------------------------------------------------------------------------------- public SessionTrackingData(ISession session) { DebugContract.Requires(session); _session = session; _elements = new Dictionary<Identity, TrackedElement>(); } ///------------------------------------------------------------------------------------------------- /// <summary> /// Gets the involved tracking elements. /// </summary> /// <value> /// The involved elements. /// </value> ///------------------------------------------------------------------------------------------------- public IEnumerable<TrackedElement> InvolvedTrackedElements { get { return _elements.Values; } } ///------------------------------------------------------------------------------------------------- /// <summary> /// Gets the involved model elements. /// </summary> /// <exception cref="Exception"> /// Thrown when an exception error condition occurs. /// </exception> /// <value> /// The involved model elements. /// </value> ///------------------------------------------------------------------------------------------------- public IEnumerable<IModelElement> InvolvedModelElements { get { if (!_modelElementsPrepared) throw new HyperstoreException(ExceptionMessages.InvolvedModelElementsOnlyAvalaibleWhenSessionIsBeingDisposed); return _elements.Values.Where(e => e.ModelElement != null) .Select(e => e.ModelElement); // Simule readonly } } ///------------------------------------------------------------------------------------------------- /// <summary> /// Gets elements by state. /// </summary> /// <param name="state"> /// The state. /// </param> /// <returns> /// An enumerator that allows foreach to be used to process the tracking elements by states in /// this collection. /// </returns> ///------------------------------------------------------------------------------------------------- public IEnumerable<TrackedElement> GetTrackedElementsByState(TrackingState state) { return _elements.Values.Where(elem => elem.State == state); } ///------------------------------------------------------------------------------------------------- /// <summary> /// Gets the state of an element. /// </summary> /// <param name="id"> /// The identifier. /// </param> /// <returns> /// The tracking element state. /// </returns> ///------------------------------------------------------------------------------------------------- public TrackingState GetTrackedElementState(Identity id) { TrackedElement elem; if (_elements.TryGetValue(id, out elem)) return elem.State; return TrackingState.Unknown; } internal void OnEvent(IEvent @event) { DebugContract.Requires(@event); // ----------------------------------------------------------------- // Add Element // ----------------------------------------------------------------- var addEvent = @event as AddEntityEvent; if (addEvent != null) { var entity = new TrackedElement { DomainName = @event.Domain, Extension = @event.ExtensionName, State = TrackingState.Added, Id = addEvent.Id, SchemaId = addEvent.SchemaId, Version = @event.Version }; _elements.Add(entity.Id, entity); return; } // ----------------------------------------------------------------- // Remove Element // ----------------------------------------------------------------- var removeEvent = @event as RemoveEntityEvent; if (removeEvent != null) { TrackedElement entity; if (!_elements.TryGetValue(removeEvent.Id, out entity)) { entity = new TrackedElement { DomainName = @event.Domain, Extension = @event.ExtensionName, State = TrackingState.Removed, Id = removeEvent.Id, SchemaId = removeEvent.SchemaId }; _elements.Add(entity.Id, entity); } else entity.State = TrackingState.Removed; return; } // ----------------------------------------------------------------- // Add metadata element // ----------------------------------------------------------------- var addMetadataEvent = @event as AddSchemaEntityEvent; if (addMetadataEvent != null) { var entity = new TrackedElement { DomainName = @event.Domain, Extension = @event.ExtensionName, State = TrackingState.Added, Id = addMetadataEvent.Id, SchemaId = addMetadataEvent.SchemaId, IsSchema = true, Version = @event.Version }; _elements.Add(entity.Id, entity); return; } // ----------------------------------------------------------------- // Change Element // ----------------------------------------------------------------- var changeEvent = @event as ChangePropertyValueEvent; if (changeEvent != null) { TrackedElement entity; if (!_elements.TryGetValue(changeEvent.Id, out entity)) { entity = new TrackedElement { DomainName = @event.Domain, Extension = @event.ExtensionName, State = TrackingState.Updated, Id = changeEvent.Id, SchemaId = changeEvent.SchemaId }; _elements.Add(entity.Id, entity); } var prop = new PropertyValue { Value = changeEvent.GetInternalValue(), CurrentVersion = changeEvent.Version, OldValue = changeEvent.GetInternalOldValue() }; entity.Properties[changeEvent.PropertyName] = prop; entity.Version = Math.Max(entity.Version, changeEvent.Version); return; } // ----------------------------------------------------------------- // Add relationship // ----------------------------------------------------------------- var addRelationEvent = @event as AddRelationshipEvent; if (addRelationEvent != null) { var entity = new TrackedRelationship { DomainName = @event.Domain, Extension = @event.ExtensionName, State = TrackingState.Added, Id = addRelationEvent.Id, SchemaId = addRelationEvent.SchemaId, StartId = addRelationEvent.StartId, EndId = addRelationEvent.EndId, Version = @event.Version }; _elements.Add(entity.Id, entity); return; } // ----------------------------------------------------------------- // Remove relationship // ----------------------------------------------------------------- var removeRelationshipEvent = @event as RemoveRelationshipEvent; if (removeRelationshipEvent != null) { TrackedElement entity; if (!_elements.TryGetValue(removeRelationshipEvent.Id, out entity)) { entity = new TrackedRelationship { DomainName = @event.Domain, Extension = @event.ExtensionName, State = TrackingState.Removed, Id = removeRelationshipEvent.Id, SchemaId = removeRelationshipEvent.SchemaId, StartId = removeRelationshipEvent.StartId, EndId = removeRelationshipEvent.EndId, }; _elements.Add(entity.Id, entity); } else entity.State = TrackingState.Removed; return; } // ----------------------------------------------------------------- // Add relationship metadata // ----------------------------------------------------------------- var addRelationMetadataEvent = @event as AddSchemaRelationshipEvent; if (addRelationMetadataEvent != null) { var entity = new TrackedRelationship { DomainName = @event.Domain, Extension = @event.ExtensionName, State = TrackingState.Added, Id = addRelationMetadataEvent.Id, SchemaId = addRelationMetadataEvent.SchemaId, StartId = addRelationMetadataEvent.StartId, EndId = addRelationMetadataEvent.EndId, IsSchema = true, Version = @event.Version }; _elements.Add(entity.Id, entity); } } /// <summary> /// Liste des éléments impactés par les commandes lors de la session. Si plusieurs commandes opérent sur un même /// élément, il ne sera répertorié qu'une fois. /// </summary> /// <value> /// The involved elements. /// </value> internal bool PrepareModelElements(bool isAborted, bool schemaLoading) { if (_modelElementsPrepared) return _elements.Count > 0; _modelElementsPrepared = true; // On est dans le cas d'une session annulée ou lors d'un chargement de metadonnées if (schemaLoading) return false; var set = new HashSet<Identity>(); var list = _elements.Values.ToList(); foreach (var element in list) { if (element is TrackedRelationship) { var relationship = element as TrackedRelationship; if (relationship.IsSchema) { //element.ModelElement = session.Store.GetMetaRelationship(element.Id); continue; } if (set.Add(relationship.Id)) { if (relationship.State != TrackingState.Removed) { var rel = _session.Store.GetRelationship(relationship.Id); if (rel != null) { if (isAborted) { ((IDisposable)rel).Dispose(); } element.ModelElement = rel; } } if (set.Add(relationship.StartId) && GetTrackedElementState(relationship.StartId) != TrackingState.Removed) { var mel = _session.Store.GetElement(relationship.StartId); if (mel != null) // Au cas ou il a été supprimé { TrackedElement data; if (!_elements.TryGetValue(mel.Id, out data)) { data = new TrackedElement { State = TrackingState.Unknown, Id = mel.Id, SchemaId = mel.SchemaInfo.Id }; _elements.Add(mel.Id, data); } data.ModelElement = mel; } } if (set.Add(relationship.EndId) && GetTrackedElementState(relationship.EndId) != TrackingState.Removed) { var mel = _session.Store.GetElement(relationship.EndId); if (mel != null) // Au cas ou il a été supprimé { TrackedElement data; if (!_elements.TryGetValue(mel.Id, out data)) { data = new TrackedElement { State = TrackingState.Unknown, // N'a pas de conséquense sur la mise à jour de l'entité Id = mel.Id, SchemaId = mel.SchemaInfo.Id }; _elements.Add(mel.Id, data); } data.ModelElement = mel; } } } } else { // Element if (element.IsSchema) { //element.ModelElement = session.Store.GetMetadata(element.Id); } else { if (set.Add(element.Id)) { var mel = _session.Store.GetElement(element.Id); if (mel != null) { if (element.State != TrackingState.Removed) { element.ModelElement = mel; if (isAborted) { ((IDisposable)mel).Dispose(); } } else if (element.State == TrackingState.Removed) { ((IDisposable)mel).Dispose(); } } } } } } return _elements.Count > 0 && !isAborted; } } }
Hyperstore/Hyperstore.Core
Hyperstore/Commands/Impls/Session/SessionTrackingData.cs
C#
apache-2.0
17,951
/** * Copyright 2015 Peter Nerg * * <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 javascalautils.concurrent; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; import static javascalautils.concurrent.PromiseCompanion.Promise; /** * Implements the executor interface. <br> * Internally uses a Java concurrent executor to provide the thread execution mechanism. * * @author Peter Nerg * @since 1.2 */ final class ExecutorImpl implements Executor { /** The internal Java concurrent executor to perform the actual work. */ private final java.util.concurrent.Executor executor; /** * Creates an instance using the provided SDK {@link java.util.concurrent.Executor} for thread * management. * * @param executor The underlying executor to use * @since 1.2 */ ExecutorImpl(java.util.concurrent.Executor executor) { this.executor = executor; } /* * (non-Javadoc) * * @see javascalautils.concurrent.Executor#execute(javascalautils.concurrent.Executable) */ @Override public <T> Future<T> execute(final Executable<T> executable) { final Promise<T> promise = Promise(); return execute( promise, () -> { try { executable.execute(promise); // if the implementation didn't respond to the Promise we mark it as a failure. if (!promise.isCompleted()) { promise.failure(new IllegalStateException("No response was provided by the Promise")); } } catch (Exception ex) { promise.failure(ex); } }); } /* * (non-Javadoc) * * @see javascalautils.concurrent.Executor#execute(java.util.concurrent.Callable) */ @Override public <T> Future<T> execute(final Callable<T> callable) { final Promise<T> promise = Promise(); return execute( promise, () -> { try { promise.success(callable.call()); } catch (Exception ex) { promise.failure(ex); } }); } /* * (non-Javadoc) * * @see javascalautils.concurrent.Executor#executeAll(javascalautils.concurrent.Executable<T>[]) */ @Override public <T> List<Future<T>> executeAll( @SuppressWarnings("unchecked") Executable<T>... executables) { List<Future<T>> responses = new ArrayList<>(); for (Executable<T> executable : executables) { responses.add(execute(executable)); } return responses; } /* * (non-Javadoc) * * @see javascalautils.concurrent.Executor#executeAll(java.util.concurrent.Callable<T>[]) */ @Override public <T> List<Future<T>> executeAll(@SuppressWarnings("unchecked") Callable<T>... callables) { List<Future<T>> responses = new ArrayList<>(); for (Callable<T> callable : callables) { responses.add(execute(callable)); } return responses; } /** * Executes the provided {@link Runnable} on the internal executor. <br> * Any issues related to the internal executor are reported to the provided {@link Promise} * * @param promise The promise to fulfill once the work is finished * @param runnable The runnable to execute in the executor * @return The Future holding the response-to-be */ private <T> Future<T> execute(Promise<T> promise, Runnable runnable) { try { executor.execute(runnable); } catch (RejectedExecutionException ex) { // could be rejected due to resource starvation, report a failure promise.failure(ex); } return promise.future(); } /* * (non-Javadoc) * * @see javascalautils.concurrent.Executor#shutdown() */ @Override public void shutdown() { if (executor instanceof ExecutorService) { ((ExecutorService) executor).shutdown(); } } /* * (non-Javadoc) * * @see javascalautils.concurrent.Executor#awaitTermination(long, java.util.concurrent.TimeUnit) */ @Override public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { if (executor instanceof ExecutorService) { return ((ExecutorService) executor).awaitTermination(timeout, unit); } return true; } }
pnerg/java-scala-util
src/main/java/javascalautils/concurrent/ExecutorImpl.java
Java
apache-2.0
4,857
// Copyright 2016 Pikkpoiss Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 animation import ( "time" ) type GroupedAnimation struct { animators []Animator callback AnimatorCallback } func NewGroupedAnimation(animators []Animator) *GroupedAnimation { return &GroupedAnimation{animators, nil} } func (a *GroupedAnimation) SetCallback(callback AnimatorCallback) { a.callback = callback } func (a *GroupedAnimation) IsDone() bool { var done = true for _, animator := range a.animators { if !animator.IsDone() { done = false } } return done } func (a *GroupedAnimation) Update(elapsed time.Duration) time.Duration { var ( total time.Duration remainder time.Duration done = true ) for _, animator := range a.animators { remainder = animator.Update(elapsed) if !animator.IsDone() { done = false } if remainder != 0 && (total == 0 || remainder < total) { total = remainder // Take the smallest nonzero remainder. } } if done { if a.callback != nil { a.callback() } return total } return 0 } func (a *GroupedAnimation) Reset() { for _, animator := range a.animators { animator.Reset() } } func (a *GroupedAnimation) Delete() { for _, animator := range a.animators { animator.Delete() } a.animators = []Animator{} }
pikkpoiss/animation
v1/animation/grouped_animation.go
GO
apache-2.0
1,815
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddPublishedColumnToGameFlavor extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('game_flavor', function ($table) { $table->boolean('published')->default(false); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('game_flavor', function(Blueprint $table){ $table->dropColumn('published'); }); } }
scify/memori-online-games-repository
database/migrations/2017_01_03_115106_add_published_column_to_game_flavor.php
PHP
apache-2.0
664
/* * #! * Ontopia Engine * #- * Copyright (C) 2001 - 2013 The Ontopia Project * #- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 net.ontopia.topicmaps.cmdlineutils.rdbms; import java.util.Iterator; import java.io.File; import net.ontopia.infoset.core.LocatorIF; import net.ontopia.topicmaps.core.TopicIF; import net.ontopia.topicmaps.core.TopicMapIF; import net.ontopia.topicmaps.core.UniquenessViolationException; import net.ontopia.topicmaps.impl.rdbms.RDBMSTopicMapStore; import net.ontopia.topicmaps.utils.MergeUtils; import net.ontopia.utils.CmdlineOptions; import net.ontopia.utils.CmdlineUtils; import net.ontopia.utils.URIUtils; /** * INTERNAL: Command line utility for translating the source locators * in an imported topic map from their original base to the new base. * * @since 2.0 */ public class TranslateSourceLocators { public static void main(String[] argv) throws Exception { // Initialize logging CmdlineUtils.initializeLogging(); // Register logging options CmdlineOptions options = new CmdlineOptions("TranslateSourceLocators", argv); CmdlineUtils.registerLoggingOptions(options); // Parse command line options try { options.parse(); } catch (CmdlineOptions.OptionsException e) { System.err.println("Error: " + e.getMessage()); System.exit(1); } // Get command line arguments String[] args = options.getArguments(); if (args.length < 3 || args.length > 3) { usage(); System.exit(3); } translate(args[0], args[1], args[2]); } private static void translate(String propfile, String tmid, String tmfile) throws Exception { RDBMSTopicMapStore store = new RDBMSTopicMapStore(propfile, Integer.parseInt(tmid)); TopicMapIF tm = store.getTopicMap(); LocatorIF newbase = store.getBaseAddress(); String oldbase = newbase.resolveAbsolute(URIUtils.toURL(new File(tmfile)).toString()).getAddress(); int oldlen = oldbase.length(); Iterator it = tm.getTopics().iterator(); while (it.hasNext()) { TopicIF topic = (TopicIF) it.next(); Object[] srclocs = topic.getItemIdentifiers().toArray(); for (int ix = 0; ix < srclocs.length; ix++) { LocatorIF srcloc = (LocatorIF) srclocs[ix]; String url = srcloc.getAddress(); if (url.startsWith(oldbase)) { LocatorIF newloc = newbase.resolveAbsolute(url.substring(oldlen)); topic.removeItemIdentifier(srcloc); try { topic.addItemIdentifier(newloc); } catch (UniquenessViolationException e) { // ooops! this topic already exists, so we must merge TopicIF other = (TopicIF) tm.getObjectByItemIdentifier(newloc); if (other == null) other = tm.getTopicBySubjectIdentifier(newloc); MergeUtils.mergeInto(other, topic); // this kills our topic, not the other } } } } store.commit(); store.close(); } private static void usage() { System.out.println("java net.ontopia.topicmaps.cmdlineutils.rdbms.TranslateSourceLocators [options] <dbprops> <tmid> <tmfile>"); System.out.println(""); System.out.println(" Translates the base addresses of source locators to that of the topic map."); System.out.println(""); System.out.println(" Options:"); CmdlineUtils.printLoggingOptionsUsage(System.out); System.out.println(""); System.out.println(" <dbprops>: the database configuration file"); System.out.println(" <tmid> : the id of the topic map to modify"); System.out.println(" <tmfile> : the original file name"); System.out.println(""); } }
ontopia/ontopia
ontopia-engine/src/main/java/net/ontopia/topicmaps/cmdlineutils/rdbms/TranslateSourceLocators.java
Java
apache-2.0
4,242
/* * Copyright 2011 SearchWorkings.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.explorer.client.core.manager.ui; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.PopupPanel; import com.google.gwt.user.client.Window; /** * A simple implementation of a {@link ProgressIndicator} that shows a message on the middle-top part of the screen. * * @author Uri Boness */ public class DefaultProgressIndicator extends PopupPanel implements ProgressIndicator { private Label messageLabel; /** * Constructs a new MessageProgressIndicator with a default message. */ public DefaultProgressIndicator() { this("Loading..."); } /** * Constructs a new MessageProgressIndicator with a given initial message to be displayed. * * @param message The initial message to be displayed. */ public DefaultProgressIndicator(String message) { super(false, true); messageLabel = new Label(message); messageLabel.setStyleName("Label"); setPopupPositionAndShow(new PopupPanel.PositionCallback() { public void setPosition(int offsetWidth, int offsetHeight) { int x = Window.getClientWidth()/2 - offsetWidth/2; setPopupPosition(x, 0); } }); setWidget(messageLabel); setStyleName("DefaultProgressIndicator"); } /** * Sets the message this indicator should display. Can be set while the indicator is already displayed. * * @param message The message this indicator should display. */ public void setMessage(String message) { messageLabel.setText(message); } }
cominvent/solr-explorer
src/main/java/org/apache/solr/explorer/client/core/manager/ui/DefaultProgressIndicator.java
Java
apache-2.0
2,187
/* * Copyright (C) 2014 Balys Valentukevicius * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.balysv.materialmenu; import android.content.Context; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorFilter; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.drawable.Animatable; import android.graphics.drawable.Drawable; import android.util.TypedValue; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import com.nineoldandroids.animation.Animator; import com.nineoldandroids.animation.ObjectAnimator; import com.nineoldandroids.util.Property; import static android.graphics.Paint.Style; public class MaterialMenuDrawable extends Drawable implements Animatable { public enum IconState { BURGER, ARROW, X, CHECK } public enum Stroke { /** * 3 dip */ REGULAR(3), /** * 2 dip */ THIN(2), /** * 1 dip */ EXTRA_THIN(1); private final int strokeWidth; Stroke(int strokeWidth) { this.strokeWidth = strokeWidth; } protected static Stroke valueOf(int strokeWidth) { switch (strokeWidth) { case 3: return REGULAR; case 2: return THIN; case 1: return EXTRA_THIN; default: return REGULAR; } } } public static final int DEFAULT_COLOR = Color.WHITE; public static final int DEFAULT_SCALE = 1; public static final int DEFAULT_TRANSFORM_DURATION = 800; public static final int DEFAULT_PRESSED_DURATION = 400; private enum AnimationState { BURGER_ARROW, BURGER_X, ARROW_X, ARROW_CHECK, BURGER_CHECK, X_CHECK } private static final int BASE_DRAWABLE_WIDTH = 40; private static final int BASE_DRAWABLE_HEIGHT = 40; private static final int BASE_ICON_WIDTH = 20; private static final int BASE_CIRCLE_RADIUS = 18; private static final int BASE_GRID_OFFSET = 6; private static final float ARROW_MID_LINE_ANGLE = 180; private static final float ARROW_TOP_LINE_ANGLE = 135; private static final float ARROW_BOT_LINE_ANGLE = 225; private static final float X_TOP_LINE_ANGLE = 44; private static final float X_BOT_LINE_ANGLE = -44; private static final float X_ROTATION_ANGLE = 90; private static final float CHECK_MIDDLE_ANGLE = 135; private static final float CHECK_BOTTOM_ANGLE = -90; private static final float TRANSFORMATION_START = 0; private static final float TRANSFORMATION_MID = 1.0f; private static final float TRANSFORMATION_END = 2.0f; private static final int DEFAULT_CIRCLE_ALPHA = 200; private final float diph; private final float dip1; private final float dip2; private final float dip3; private final float dip4; private final float dip6; private final float dip8; private final int width; private final int height; private final float strokeWidth; private final float iconWidth; private final float topPadding; private final float sidePadding; private final float circleRadius; private final float gridOffset; private final Stroke stroke; private final Paint gridPaint; private final Paint iconPaint; private final Paint circlePaint; private float transformationValue = 0f; private float pressedProgressValue = 0f; private boolean transformationRunning = false; private boolean drawGrid = false; private IconState currentIconState = IconState.BURGER; private AnimationState animationState = AnimationState.BURGER_ARROW; private IconState animatingIconState; private boolean drawTouchCircle; private boolean neverDrawTouch; private ObjectAnimator transformation; private ObjectAnimator pressedCircle; public MaterialMenuDrawable(Context context, int color, Stroke stroke) { this(context, color, stroke, DEFAULT_SCALE, DEFAULT_TRANSFORM_DURATION, DEFAULT_PRESSED_DURATION); } public MaterialMenuDrawable(Context context, int color, Stroke stroke, int transformDuration, int pressedDuration) { this(context, color, stroke, DEFAULT_SCALE, transformDuration, pressedDuration); } public MaterialMenuDrawable(Context context, int color, Stroke stroke, int scale, int transformDuration, int pressedDuration) { Resources resources = context.getResources(); // convert each separately due to various densities this.dip1 = dpToPx(resources, 1) * scale; this.dip2 = dpToPx(resources, 2) * scale; this.dip3 = dpToPx(resources, 3) * scale; this.dip4 = dpToPx(resources, 4) * scale; this.dip6 = dpToPx(resources, 6) * scale; this.dip8 = dpToPx(resources, 8) * scale; this.diph = dip1 / 2; this.stroke = stroke; this.width = (int) (dpToPx(resources, BASE_DRAWABLE_WIDTH) * scale); this.height = (int) (dpToPx(resources, BASE_DRAWABLE_HEIGHT) * scale); this.iconWidth = dpToPx(resources, BASE_ICON_WIDTH) * scale; this.circleRadius = dpToPx(resources, BASE_CIRCLE_RADIUS) * scale; this.strokeWidth = dpToPx(resources, stroke.strokeWidth) * scale; this.sidePadding = (width - iconWidth) / 2; this.topPadding = (height - 5 * dip3) / 2; this.gridOffset = dpToPx(resources, BASE_GRID_OFFSET) * scale; gridPaint = new Paint(); gridPaint.setAntiAlias(false); gridPaint.setColor(Color.GREEN); gridPaint.setStrokeWidth(1); iconPaint = new Paint(); iconPaint.setAntiAlias(true); iconPaint.setStyle(Style.STROKE); iconPaint.setStrokeWidth(strokeWidth); iconPaint.setColor(color); circlePaint = new Paint(); circlePaint.setAntiAlias(true); circlePaint.setStyle(Style.FILL); circlePaint.setColor(color); circlePaint.setAlpha(DEFAULT_CIRCLE_ALPHA); setBounds(0, 0, width, height); initAnimations(transformDuration, pressedDuration); } /* * Drawing */ @Override public void draw(Canvas canvas) { if (drawGrid) drawGrid(canvas); final float ratio = transformationValue <= 1 ? transformationValue : 2 - transformationValue; drawTopLine(canvas, ratio); drawMiddleLine(canvas, ratio); drawBottomLine(canvas, ratio); if (drawTouchCircle) drawTouchCircle(canvas); } private void drawTouchCircle(Canvas canvas) { canvas.restore(); canvas.drawCircle(width / 2, height / 2, pressedProgressValue, circlePaint); } private void drawMiddleLine(Canvas canvas, float ratio) { canvas.restore(); canvas.save(); float rotation = 0; float pivotX = width / 2; float pivotY = width / 2; float startX = sidePadding; float startY = topPadding + dip3 / 2 * 5; float stopX = width - sidePadding; float stopY = topPadding + dip3 / 2 * 5; int alpha = 255; switch (animationState) { case BURGER_ARROW: // rotate by 180 if (isMorphingForward()) { rotation = ratio * ARROW_MID_LINE_ANGLE; } else { rotation = ARROW_MID_LINE_ANGLE + (1 - ratio) * ARROW_MID_LINE_ANGLE; } // shorten one end stopX -= ratio * resolveStrokeModifier(ratio) / 2; break; case BURGER_X: // fade out alpha = (int) ((1 - ratio) * 255); break; case ARROW_X: // fade out and shorten one end alpha = (int) ((1 - ratio) * 255); startX += (1 - ratio) * dip2; break; case ARROW_CHECK: if (isMorphingForward()) { // rotate until required angle rotation = ratio * CHECK_MIDDLE_ANGLE; // lengthen both ends startX += dip3 / 2 + ratio * dip4; stopX += ratio * (dip8 + diph); } else { // rotate back to starting angle rotation = CHECK_MIDDLE_ANGLE - CHECK_MIDDLE_ANGLE * (1 - ratio); // shorten one end and lengthen the other startX += dip3 / 2 + dip4 - (1 - ratio) * (dip2 + diph); stopX += dip8 - (1 - ratio) * (dip2 + dip6); } pivotX = width / 2 + dip3 * 2; break; case BURGER_CHECK: // rotate until required angle rotation = ratio * CHECK_MIDDLE_ANGLE; // lengthen both ends startX += ratio * (dip4 + dip3 / 2); stopX += ratio * (dip8 + diph); pivotX = width / 2 + dip3 * 2; break; case X_CHECK: // fade in alpha = (int) (ratio * 255); // rotation to check angle rotation = ratio * CHECK_MIDDLE_ANGLE; // lengthen both ends startX += ratio * (dip4 + dip3 / 2); stopX += ratio * (dip8 + diph); pivotX = width / 2 + dip3 * 2; break; } iconPaint.setAlpha(alpha); canvas.rotate(rotation, pivotX, pivotY); canvas.drawLine(startX, startY, stopX, stopY, iconPaint); iconPaint.setAlpha(255); } private void drawTopLine(Canvas canvas, float ratio) { canvas.save(); float rotation = 0, pivotX = 0, pivotY = 0; float rotation2 = 0; // pivot at center of line float pivotX2 = width / 2 + dip3 / 2; float pivotY2 = topPadding + dip2; float startX = sidePadding; float startY = topPadding + dip2; float stopX = width - sidePadding; float stopY = topPadding + dip2; int alpha = 255; switch (animationState) { case BURGER_ARROW: if (isMorphingForward()) { // rotate until required angle rotation = ratio * ARROW_BOT_LINE_ANGLE; } else { // rotate back to start doing a 360 rotation = ARROW_BOT_LINE_ANGLE + (1 - ratio) * ARROW_TOP_LINE_ANGLE; } // rotate by middle pivotX = width / 2; pivotY = height / 2; // shorten both ends stopX -= resolveStrokeModifier(ratio); startX += dip3 * ratio; break; case BURGER_X: // rotate until required angles rotation = X_TOP_LINE_ANGLE * ratio; rotation2 = X_ROTATION_ANGLE * ratio; // pivot at left corner of line pivotX = sidePadding + dip4; pivotY = topPadding + dip3; // lengthen one end stopX += dip3 * ratio; break; case ARROW_X: // rotate from ARROW angle to X angle rotation = ARROW_BOT_LINE_ANGLE + (X_TOP_LINE_ANGLE - ARROW_BOT_LINE_ANGLE) * ratio; rotation2 = X_ROTATION_ANGLE * ratio; // move pivot from ARROW pivot to X pivot pivotX = width / 2 + (sidePadding + dip4 - width / 2) * ratio; pivotY = height / 2 + (topPadding + dip3 - height / 2) * ratio; // lengthen both ends stopX -= resolveStrokeModifier(ratio); startX += dip3 * (1 - ratio); break; case ARROW_CHECK: // fade out alpha = (int) ((1 - ratio) * 255); // retain starting arrow configuration rotation = ARROW_BOT_LINE_ANGLE; pivotX = width / 2; pivotY = height / 2; // shorted both ends stopX -= resolveStrokeModifier(1); startX += dip3; break; case BURGER_CHECK: // fade out alpha = (int) ((1 - ratio) * 255); break; case X_CHECK: // retain X configuration rotation = X_TOP_LINE_ANGLE; rotation2 = X_ROTATION_ANGLE; pivotX = sidePadding + dip4; pivotY = topPadding + dip3; stopX += dip3; // fade out alpha = (int) ((1 - ratio) * 255); break; } iconPaint.setAlpha(alpha); canvas.rotate(rotation, pivotX, pivotY); canvas.rotate(rotation2, pivotX2, pivotY2); canvas.drawLine(startX, startY, stopX, stopY, iconPaint); iconPaint.setAlpha(255); } private void drawBottomLine(Canvas canvas, float ratio) { canvas.restore(); canvas.save(); float rotation = 0, pivotX = 0, pivotY = 0; float rotation2 = 0; // pivot at center of line float pivotX2 = width / 2 + dip3 / 2; float pivotY2 = height - topPadding - dip2; float startX = sidePadding; float startY = height - topPadding - dip2; float stopX = width - sidePadding; float stopY = height - topPadding - dip2; switch (animationState) { case BURGER_ARROW: if (isMorphingForward()) { // rotate to required angle rotation = ARROW_TOP_LINE_ANGLE * ratio; } else { // rotate back to start doing a 360 rotation = ARROW_TOP_LINE_ANGLE + (1 - ratio) * ARROW_BOT_LINE_ANGLE; } // pivot center of canvas pivotX = width / 2; pivotY = height / 2; // shorten both ends stopX = width - sidePadding - resolveStrokeModifier(ratio); startX = sidePadding + dip3 * ratio; break; case BURGER_X: if (isMorphingForward()) { // rotate around rotation2 = -X_ROTATION_ANGLE * ratio; } else { // rotate directly rotation2 = X_ROTATION_ANGLE * ratio; } // rotate to required angle rotation = X_BOT_LINE_ANGLE * ratio; // pivot left corner of line pivotX = sidePadding + dip4; pivotY = height - topPadding - dip3; // lengthen one end stopX += dip3 * ratio; break; case ARROW_X: // rotate from ARROW angle to X angle rotation = ARROW_TOP_LINE_ANGLE + (360 + X_BOT_LINE_ANGLE - ARROW_TOP_LINE_ANGLE) * ratio; rotation2 = -X_ROTATION_ANGLE * ratio; // move pivot from ARROW pivot to X pivot pivotX = width / 2 + (sidePadding + dip4 - width / 2) * ratio; pivotY = height / 2 + (height / 2 - topPadding - dip3) * ratio; // lengthen both ends stopX -= resolveStrokeModifier(ratio); startX += dip3 * (1 - ratio); break; case ARROW_CHECK: // rotate from ARROW angle to CHECK angle rotation = ARROW_TOP_LINE_ANGLE + ratio * CHECK_BOTTOM_ANGLE; // move pivot from ARROW pivot to CHECK pivot pivotX = width / 2 - dip3 * ratio; pivotY = height / 2 - dip3 * ratio; // length stays same as ARROW stopX -= resolveStrokeModifier(1); startX += dip3; break; case BURGER_CHECK: // rotate from ARROW angle to CHECK angle rotation = ratio * (CHECK_BOTTOM_ANGLE + ARROW_TOP_LINE_ANGLE); // move pivot from ARROW pivot to CHECK pivot pivotX = width / 2 - dip3 * ratio; pivotY = height / 2 - dip3 * ratio; // length stays same as BURGER startX += dip3 * ratio; stopX -= resolveStrokeModifier(ratio); break; case X_CHECK: // rotate from X to CHECK angles rotation2 = -X_ROTATION_ANGLE * (1 - ratio); rotation = X_BOT_LINE_ANGLE + (CHECK_BOTTOM_ANGLE + ARROW_TOP_LINE_ANGLE - X_BOT_LINE_ANGLE) * ratio; // move pivot from X to CHECK pivotX = sidePadding + dip4 + (width / 2 - sidePadding - dip3 - dip4) * ratio; pivotY = height - topPadding - dip3 + (topPadding + height / 2 - height) * ratio; // shorten both ends startX += dip3 - dip3 * (1 - ratio); stopX -= resolveStrokeModifier(1 - ratio); break; } canvas.rotate(rotation, pivotX, pivotY); canvas.rotate(rotation2, pivotX2, pivotY2); canvas.drawLine(startX, startY, stopX, stopY, iconPaint); } private void drawGrid(Canvas canvas) { for (int i = 0; i < width + 1; i += dip1) { if (i % sidePadding == 0) gridPaint.setColor(Color.BLUE); canvas.drawLine(i, 0, i, height, gridPaint); if (i % sidePadding == 0) gridPaint.setColor(Color.GREEN); } for (int i = 0; i < height + 1; i += dip1) { if (i % gridOffset == 0) gridPaint.setColor(Color.BLUE); canvas.drawLine(0, i, width, i, gridPaint); if (i % gridOffset == 0) gridPaint.setColor(Color.GREEN); } } private boolean isMorphingForward() { return transformationValue <= TRANSFORMATION_MID; } private float resolveStrokeModifier(float ratio) { switch (stroke) { case REGULAR: if (animationState == AnimationState.ARROW_X || animationState == AnimationState.X_CHECK) { return dip3 - (dip6 * ratio); } return ratio * dip3; case THIN: if (animationState == AnimationState.ARROW_X || animationState == AnimationState.X_CHECK) { return dip3 + diph - (dip6 + diph) * ratio; } return ratio * (dip3 + diph); case EXTRA_THIN: if (animationState == AnimationState.ARROW_X || animationState == AnimationState.X_CHECK) { return dip4 - ((dip6 + dip1) * ratio); } return ratio * dip4; } return 0; } @Override public void setAlpha(int alpha) { iconPaint.setAlpha(alpha); } @Override public void setColorFilter(ColorFilter cf) { iconPaint.setColorFilter(cf); } @Override public int getOpacity() { return PixelFormat.TRANSPARENT; } /* * Accessor methods */ public void setColor(int color) { iconPaint.setColor(color); circlePaint.setColor(color); invalidateSelf(); } protected void setDrawGrid(boolean drawGrid) { this.drawGrid = drawGrid; } public void setTransformationDuration(int duration) { transformation.setDuration(duration); } public void setPressedDuration(int duration) { pressedCircle.setDuration(duration); } public void setInterpolator(Interpolator interpolator) { transformation.setInterpolator(interpolator); } public void setNeverDrawTouch(boolean neverDrawTouch) { this.neverDrawTouch = neverDrawTouch; } public synchronized void setIconState(IconState iconState) { if (transformationRunning) { transformation.cancel(); transformationRunning = false; } if (currentIconState == iconState) return; switch (iconState) { case BURGER: animationState = AnimationState.BURGER_ARROW; transformationValue = TRANSFORMATION_START; break; case ARROW: animationState = AnimationState.BURGER_ARROW; transformationValue = TRANSFORMATION_MID; break; case X: animationState = AnimationState.BURGER_X; transformationValue = TRANSFORMATION_MID; break; case CHECK: animationState = AnimationState.BURGER_CHECK; transformationValue = TRANSFORMATION_MID; } currentIconState = iconState; invalidateSelf(); } public synchronized void animateIconState(IconState state, boolean drawTouch) { if (transformationRunning) { transformation.end(); pressedCircle.end(); } drawTouchCircle = drawTouch; animatingIconState = state; start(); } /* * Animations */ private Property<MaterialMenuDrawable, Float> transformationProperty = new Property<MaterialMenuDrawable, Float>(Float.class, "transformation") { @Override public Float get(MaterialMenuDrawable object) { return object.getTransformationValue(); } @Override public void set(MaterialMenuDrawable object, Float value) { object.setTransformationValue(value); } }; private Property<MaterialMenuDrawable, Float> pressedProgressProperty = new Property<MaterialMenuDrawable, Float>(Float.class, "pressedProgress") { @Override public Float get(MaterialMenuDrawable object) { return object.getPressedProgress(); } @Override public void set(MaterialMenuDrawable object, Float value) { object.setPressedProgress(value); } }; public Float getTransformationValue() { return transformationValue; } public void setTransformationValue(Float value) { this.transformationValue = value; invalidateSelf(); } public Float getPressedProgress() { return pressedProgressValue; } public void setPressedProgress(Float value) { this.pressedProgressValue = value; circlePaint.setAlpha((int) (DEFAULT_CIRCLE_ALPHA * (1 - value / (circleRadius * 1.22f)))); invalidateSelf(); } private void initAnimations(int transformDuration, int pressedDuration) { transformation = ObjectAnimator.ofFloat(this, transformationProperty, 0); transformation.setInterpolator(new DecelerateInterpolator(3)); transformation.setDuration(transformDuration); transformation.addListener(new SimpleAnimatorListener() { @Override public void onAnimationEnd(Animator animation) { transformationRunning = false; setIconState(animatingIconState); } }); pressedCircle = ObjectAnimator.ofFloat(this, pressedProgressProperty, 0, 0); pressedCircle.setDuration(pressedDuration); pressedCircle.setInterpolator(new DecelerateInterpolator()); pressedCircle.addListener(new SimpleAnimatorListener() { @Override public void onAnimationEnd(Animator animation) { pressedProgressValue = 0; } @Override public void onAnimationCancel(Animator animation) { pressedProgressValue = 0; } }); } private boolean resolveTransformation() { boolean isCurrentBurger = currentIconState == IconState.BURGER; boolean isCurrentArrow = currentIconState == IconState.ARROW; boolean isCurrentX = currentIconState == IconState.X; boolean isCurrentCheck = currentIconState == IconState.CHECK; boolean isAnimatingBurger = animatingIconState == IconState.BURGER; boolean isAnimatingArrow = animatingIconState == IconState.ARROW; boolean isAnimatingX = animatingIconState == IconState.X; boolean isAnimatingCheck = animatingIconState == IconState.CHECK; if ((isCurrentBurger && isAnimatingArrow) || (isCurrentArrow && isAnimatingBurger)) { animationState = AnimationState.BURGER_ARROW; return isCurrentBurger; } if ((isCurrentArrow && isAnimatingX) || (isCurrentX && isAnimatingArrow)) { animationState = AnimationState.ARROW_X; return isCurrentArrow; } if ((isCurrentBurger && isAnimatingX) || (isCurrentX && isAnimatingBurger)) { animationState = AnimationState.BURGER_X; return isCurrentBurger; } if ((isCurrentArrow && isAnimatingCheck) || (isCurrentCheck && isAnimatingArrow)) { animationState = AnimationState.ARROW_CHECK; return isCurrentArrow; } if ((isCurrentBurger && isAnimatingCheck) || (isCurrentCheck && isAnimatingBurger)) { animationState = AnimationState.BURGER_CHECK; return isCurrentBurger; } if ((isCurrentX && isAnimatingCheck) || (isCurrentCheck && isAnimatingX)) { animationState = AnimationState.X_CHECK; return isCurrentX; } throw new IllegalStateException( String.format("Animating from %s to %s is not supported", currentIconState, animatingIconState) ); } @Override public void start() { if (transformationRunning || animatingIconState == null || animatingIconState == currentIconState) return; transformationRunning = true; final boolean direction = resolveTransformation(); transformation.setFloatValues( direction ? TRANSFORMATION_START : TRANSFORMATION_MID, direction ? TRANSFORMATION_MID : TRANSFORMATION_END ); transformation.start(); if (pressedCircle.isRunning()) { pressedCircle.cancel(); } if (drawTouchCircle && !neverDrawTouch) { pressedCircle.setFloatValues(0, circleRadius * 1.22f); pressedCircle.start(); } invalidateSelf(); } @Override public void stop() { if (!isRunning()) return; if (transformation.isRunning()) { transformation.end(); } else { transformationRunning = false; invalidateSelf(); } } @Override public boolean isRunning() { return transformationRunning; } @Override public int getIntrinsicWidth() { return width; } @Override public int getIntrinsicHeight() { return height; } private class SimpleAnimatorListener implements Animator.AnimatorListener { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } } static float dpToPx(Resources resources, float dp) { return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, resources.getDisplayMetrics()); } }
infakt/material-menu
library/src/main/java/com/balysv/materialmenu/MaterialMenuDrawable.java
Java
apache-2.0
26,723
package org.hl7.fhir.dstu3.model; /* Copyright (c) 2011+, HL7, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Generated on Mon, Apr 17, 2017 17:38-0400 for FHIR v3.0.1 import java.util.*; import org.hl7.fhir.utilities.Utilities; import org.hl7.fhir.dstu3.model.Enumerations.*; import ca.uhn.fhir.model.api.annotation.ResourceDef; import ca.uhn.fhir.model.api.annotation.SearchParamDefinition; import ca.uhn.fhir.model.api.annotation.Child; import ca.uhn.fhir.model.api.annotation.ChildOrder; import ca.uhn.fhir.model.api.annotation.Description; import ca.uhn.fhir.model.api.annotation.Block; import org.hl7.fhir.instance.model.api.*; import org.hl7.fhir.exceptions.FHIRException; /** * A person who is directly or indirectly involved in the provisioning of healthcare. */ @ResourceDef(name="Practitioner", profile="http://hl7.org/fhir/Profile/Practitioner") public class Practitioner extends DomainResource { @Block() public static class PractitionerQualificationComponent extends BackboneElement implements IBaseBackboneElement { /** * An identifier that applies to this person's qualification in this role. */ @Child(name = "identifier", type = {Identifier.class}, order=1, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false) @Description(shortDefinition="An identifier for this qualification for the practitioner", formalDefinition="An identifier that applies to this person's qualification in this role." ) protected List<Identifier> identifier; /** * Coded representation of the qualification. */ @Child(name = "code", type = {CodeableConcept.class}, order=2, min=1, max=1, modifier=false, summary=false) @Description(shortDefinition="Coded representation of the qualification", formalDefinition="Coded representation of the qualification." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/v2-2.7-0360") protected CodeableConcept code; /** * Period during which the qualification is valid. */ @Child(name = "period", type = {Period.class}, order=3, min=0, max=1, modifier=false, summary=false) @Description(shortDefinition="Period during which the qualification is valid", formalDefinition="Period during which the qualification is valid." ) protected Period period; /** * Organization that regulates and issues the qualification. */ @Child(name = "issuer", type = {Organization.class}, order=4, min=0, max=1, modifier=false, summary=false) @Description(shortDefinition="Organization that regulates and issues the qualification", formalDefinition="Organization that regulates and issues the qualification." ) protected Reference issuer; /** * The actual object that is the target of the reference (Organization that regulates and issues the qualification.) */ protected Organization issuerTarget; private static final long serialVersionUID = 1095219071L; /** * Constructor */ public PractitionerQualificationComponent() { super(); } /** * Constructor */ public PractitionerQualificationComponent(CodeableConcept code) { super(); this.code = code; } /** * @return {@link #identifier} (An identifier that applies to this person's qualification in this role.) */ public List<Identifier> getIdentifier() { if (this.identifier == null) this.identifier = new ArrayList<Identifier>(); return this.identifier; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public PractitionerQualificationComponent setIdentifier(List<Identifier> theIdentifier) { this.identifier = theIdentifier; return this; } public boolean hasIdentifier() { if (this.identifier == null) return false; for (Identifier item : this.identifier) if (!item.isEmpty()) return true; return false; } public Identifier addIdentifier() { //3 Identifier t = new Identifier(); if (this.identifier == null) this.identifier = new ArrayList<Identifier>(); this.identifier.add(t); return t; } public PractitionerQualificationComponent addIdentifier(Identifier t) { //3 if (t == null) return this; if (this.identifier == null) this.identifier = new ArrayList<Identifier>(); this.identifier.add(t); return this; } /** * @return The first repetition of repeating field {@link #identifier}, creating it if it does not already exist */ public Identifier getIdentifierFirstRep() { if (getIdentifier().isEmpty()) { addIdentifier(); } return getIdentifier().get(0); } /** * @return {@link #code} (Coded representation of the qualification.) */ public CodeableConcept getCode() { if (this.code == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create PractitionerQualificationComponent.code"); else if (Configuration.doAutoCreate()) this.code = new CodeableConcept(); // cc return this.code; } public boolean hasCode() { return this.code != null && !this.code.isEmpty(); } /** * @param value {@link #code} (Coded representation of the qualification.) */ public PractitionerQualificationComponent setCode(CodeableConcept value) { this.code = value; return this; } /** * @return {@link #period} (Period during which the qualification is valid.) */ public Period getPeriod() { if (this.period == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create PractitionerQualificationComponent.period"); else if (Configuration.doAutoCreate()) this.period = new Period(); // cc return this.period; } public boolean hasPeriod() { return this.period != null && !this.period.isEmpty(); } /** * @param value {@link #period} (Period during which the qualification is valid.) */ public PractitionerQualificationComponent setPeriod(Period value) { this.period = value; return this; } /** * @return {@link #issuer} (Organization that regulates and issues the qualification.) */ public Reference getIssuer() { if (this.issuer == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create PractitionerQualificationComponent.issuer"); else if (Configuration.doAutoCreate()) this.issuer = new Reference(); // cc return this.issuer; } public boolean hasIssuer() { return this.issuer != null && !this.issuer.isEmpty(); } /** * @param value {@link #issuer} (Organization that regulates and issues the qualification.) */ public PractitionerQualificationComponent setIssuer(Reference value) { this.issuer = value; return this; } /** * @return {@link #issuer} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (Organization that regulates and issues the qualification.) */ public Organization getIssuerTarget() { if (this.issuerTarget == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create PractitionerQualificationComponent.issuer"); else if (Configuration.doAutoCreate()) this.issuerTarget = new Organization(); // aa return this.issuerTarget; } /** * @param value {@link #issuer} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (Organization that regulates and issues the qualification.) */ public PractitionerQualificationComponent setIssuerTarget(Organization value) { this.issuerTarget = value; return this; } protected void listChildren(List<Property> childrenList) { super.listChildren(childrenList); childrenList.add(new Property("identifier", "Identifier", "An identifier that applies to this person's qualification in this role.", 0, java.lang.Integer.MAX_VALUE, identifier)); childrenList.add(new Property("code", "CodeableConcept", "Coded representation of the qualification.", 0, java.lang.Integer.MAX_VALUE, code)); childrenList.add(new Property("period", "Period", "Period during which the qualification is valid.", 0, java.lang.Integer.MAX_VALUE, period)); childrenList.add(new Property("issuer", "Reference(Organization)", "Organization that regulates and issues the qualification.", 0, java.lang.Integer.MAX_VALUE, issuer)); } @Override public Base[] getProperty(int hash, String name, boolean checkValid) throws FHIRException { switch (hash) { case -1618432855: /*identifier*/ return this.identifier == null ? new Base[0] : this.identifier.toArray(new Base[this.identifier.size()]); // Identifier case 3059181: /*code*/ return this.code == null ? new Base[0] : new Base[] {this.code}; // CodeableConcept case -991726143: /*period*/ return this.period == null ? new Base[0] : new Base[] {this.period}; // Period case -1179159879: /*issuer*/ return this.issuer == null ? new Base[0] : new Base[] {this.issuer}; // Reference default: return super.getProperty(hash, name, checkValid); } } @Override public Base setProperty(int hash, String name, Base value) throws FHIRException { switch (hash) { case -1618432855: // identifier this.getIdentifier().add(castToIdentifier(value)); // Identifier return value; case 3059181: // code this.code = castToCodeableConcept(value); // CodeableConcept return value; case -991726143: // period this.period = castToPeriod(value); // Period return value; case -1179159879: // issuer this.issuer = castToReference(value); // Reference return value; default: return super.setProperty(hash, name, value); } } @Override public Base setProperty(String name, Base value) throws FHIRException { if (name.equals("identifier")) { this.getIdentifier().add(castToIdentifier(value)); } else if (name.equals("code")) { this.code = castToCodeableConcept(value); // CodeableConcept } else if (name.equals("period")) { this.period = castToPeriod(value); // Period } else if (name.equals("issuer")) { this.issuer = castToReference(value); // Reference } else return super.setProperty(name, value); return value; } @Override public Base makeProperty(int hash, String name) throws FHIRException { switch (hash) { case -1618432855: return addIdentifier(); case 3059181: return getCode(); case -991726143: return getPeriod(); case -1179159879: return getIssuer(); default: return super.makeProperty(hash, name); } } @Override public String[] getTypesForProperty(int hash, String name) throws FHIRException { switch (hash) { case -1618432855: /*identifier*/ return new String[] {"Identifier"}; case 3059181: /*code*/ return new String[] {"CodeableConcept"}; case -991726143: /*period*/ return new String[] {"Period"}; case -1179159879: /*issuer*/ return new String[] {"Reference"}; default: return super.getTypesForProperty(hash, name); } } @Override public Base addChild(String name) throws FHIRException { if (name.equals("identifier")) { return addIdentifier(); } else if (name.equals("code")) { this.code = new CodeableConcept(); return this.code; } else if (name.equals("period")) { this.period = new Period(); return this.period; } else if (name.equals("issuer")) { this.issuer = new Reference(); return this.issuer; } else return super.addChild(name); } public PractitionerQualificationComponent copy() { PractitionerQualificationComponent dst = new PractitionerQualificationComponent(); copyValues(dst); if (identifier != null) { dst.identifier = new ArrayList<Identifier>(); for (Identifier i : identifier) dst.identifier.add(i.copy()); }; dst.code = code == null ? null : code.copy(); dst.period = period == null ? null : period.copy(); dst.issuer = issuer == null ? null : issuer.copy(); return dst; } @Override public boolean equalsDeep(Base other) { if (!super.equalsDeep(other)) return false; if (!(other instanceof PractitionerQualificationComponent)) return false; PractitionerQualificationComponent o = (PractitionerQualificationComponent) other; return compareDeep(identifier, o.identifier, true) && compareDeep(code, o.code, true) && compareDeep(period, o.period, true) && compareDeep(issuer, o.issuer, true); } @Override public boolean equalsShallow(Base other) { if (!super.equalsShallow(other)) return false; if (!(other instanceof PractitionerQualificationComponent)) return false; PractitionerQualificationComponent o = (PractitionerQualificationComponent) other; return true; } public boolean isEmpty() { return super.isEmpty() && ca.uhn.fhir.util.ElementUtil.isEmpty(identifier, code, period , issuer); } public String fhirType() { return "Practitioner.qualification"; } } /** * An identifier that applies to this person in this role. */ @Child(name = "identifier", type = {Identifier.class}, order=0, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true) @Description(shortDefinition="A identifier for the person as this agent", formalDefinition="An identifier that applies to this person in this role." ) protected List<Identifier> identifier; /** * Whether this practitioner's record is in active use. */ @Child(name = "active", type = {BooleanType.class}, order=1, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="Whether this practitioner's record is in active use", formalDefinition="Whether this practitioner's record is in active use." ) protected BooleanType active; /** * The name(s) associated with the practitioner. */ @Child(name = "name", type = {HumanName.class}, order=2, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true) @Description(shortDefinition="The name(s) associated with the practitioner", formalDefinition="The name(s) associated with the practitioner." ) protected List<HumanName> name; /** * A contact detail for the practitioner, e.g. a telephone number or an email address. */ @Child(name = "telecom", type = {ContactPoint.class}, order=3, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true) @Description(shortDefinition="A contact detail for the practitioner (that apply to all roles)", formalDefinition="A contact detail for the practitioner, e.g. a telephone number or an email address." ) protected List<ContactPoint> telecom; /** * Address(es) of the practitioner that are not role specific (typically home address). Work addresses are not typically entered in this property as they are usually role dependent. */ @Child(name = "address", type = {Address.class}, order=4, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true) @Description(shortDefinition="Address(es) of the practitioner that are not role specific (typically home address)", formalDefinition="Address(es) of the practitioner that are not role specific (typically home address). \rWork addresses are not typically entered in this property as they are usually role dependent." ) protected List<Address> address; /** * Administrative Gender - the gender that the person is considered to have for administration and record keeping purposes. */ @Child(name = "gender", type = {CodeType.class}, order=5, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="male | female | other | unknown", formalDefinition="Administrative Gender - the gender that the person is considered to have for administration and record keeping purposes." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/administrative-gender") protected Enumeration<AdministrativeGender> gender; /** * The date of birth for the practitioner. */ @Child(name = "birthDate", type = {DateType.class}, order=6, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="The date on which the practitioner was born", formalDefinition="The date of birth for the practitioner." ) protected DateType birthDate; /** * Image of the person. */ @Child(name = "photo", type = {Attachment.class}, order=7, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false) @Description(shortDefinition="Image of the person", formalDefinition="Image of the person." ) protected List<Attachment> photo; /** * Qualifications obtained by training and certification. */ @Child(name = "qualification", type = {}, order=8, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false) @Description(shortDefinition="Qualifications obtained by training and certification", formalDefinition="Qualifications obtained by training and certification." ) protected List<PractitionerQualificationComponent> qualification; /** * A language the practitioner is able to use in patient communication. */ @Child(name = "communication", type = {CodeableConcept.class}, order=9, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false) @Description(shortDefinition="A language the practitioner is able to use in patient communication", formalDefinition="A language the practitioner is able to use in patient communication." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/languages") protected List<CodeableConcept> communication; private static final long serialVersionUID = 2128349259L; /** * Constructor */ public Practitioner() { super(); } /** * @return {@link #identifier} (An identifier that applies to this person in this role.) */ public List<Identifier> getIdentifier() { if (this.identifier == null) this.identifier = new ArrayList<Identifier>(); return this.identifier; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public Practitioner setIdentifier(List<Identifier> theIdentifier) { this.identifier = theIdentifier; return this; } public boolean hasIdentifier() { if (this.identifier == null) return false; for (Identifier item : this.identifier) if (!item.isEmpty()) return true; return false; } public Identifier addIdentifier() { //3 Identifier t = new Identifier(); if (this.identifier == null) this.identifier = new ArrayList<Identifier>(); this.identifier.add(t); return t; } public Practitioner addIdentifier(Identifier t) { //3 if (t == null) return this; if (this.identifier == null) this.identifier = new ArrayList<Identifier>(); this.identifier.add(t); return this; } /** * @return The first repetition of repeating field {@link #identifier}, creating it if it does not already exist */ public Identifier getIdentifierFirstRep() { if (getIdentifier().isEmpty()) { addIdentifier(); } return getIdentifier().get(0); } /** * @return {@link #active} (Whether this practitioner's record is in active use.). This is the underlying object with id, value and extensions. The accessor "getActive" gives direct access to the value */ public BooleanType getActiveElement() { if (this.active == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create Practitioner.active"); else if (Configuration.doAutoCreate()) this.active = new BooleanType(); // bb return this.active; } public boolean hasActiveElement() { return this.active != null && !this.active.isEmpty(); } public boolean hasActive() { return this.active != null && !this.active.isEmpty(); } /** * @param value {@link #active} (Whether this practitioner's record is in active use.). This is the underlying object with id, value and extensions. The accessor "getActive" gives direct access to the value */ public Practitioner setActiveElement(BooleanType value) { this.active = value; return this; } /** * @return Whether this practitioner's record is in active use. */ public boolean getActive() { return this.active == null || this.active.isEmpty() ? false : this.active.getValue(); } /** * @param value Whether this practitioner's record is in active use. */ public Practitioner setActive(boolean value) { if (this.active == null) this.active = new BooleanType(); this.active.setValue(value); return this; } /** * @return {@link #name} (The name(s) associated with the practitioner.) */ public List<HumanName> getName() { if (this.name == null) this.name = new ArrayList<HumanName>(); return this.name; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public Practitioner setName(List<HumanName> theName) { this.name = theName; return this; } public boolean hasName() { if (this.name == null) return false; for (HumanName item : this.name) if (!item.isEmpty()) return true; return false; } public HumanName addName() { //3 HumanName t = new HumanName(); if (this.name == null) this.name = new ArrayList<HumanName>(); this.name.add(t); return t; } public Practitioner addName(HumanName t) { //3 if (t == null) return this; if (this.name == null) this.name = new ArrayList<HumanName>(); this.name.add(t); return this; } /** * @return The first repetition of repeating field {@link #name}, creating it if it does not already exist */ public HumanName getNameFirstRep() { if (getName().isEmpty()) { addName(); } return getName().get(0); } /** * @return {@link #telecom} (A contact detail for the practitioner, e.g. a telephone number or an email address.) */ public List<ContactPoint> getTelecom() { if (this.telecom == null) this.telecom = new ArrayList<ContactPoint>(); return this.telecom; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public Practitioner setTelecom(List<ContactPoint> theTelecom) { this.telecom = theTelecom; return this; } public boolean hasTelecom() { if (this.telecom == null) return false; for (ContactPoint item : this.telecom) if (!item.isEmpty()) return true; return false; } public ContactPoint addTelecom() { //3 ContactPoint t = new ContactPoint(); if (this.telecom == null) this.telecom = new ArrayList<ContactPoint>(); this.telecom.add(t); return t; } public Practitioner addTelecom(ContactPoint t) { //3 if (t == null) return this; if (this.telecom == null) this.telecom = new ArrayList<ContactPoint>(); this.telecom.add(t); return this; } /** * @return The first repetition of repeating field {@link #telecom}, creating it if it does not already exist */ public ContactPoint getTelecomFirstRep() { if (getTelecom().isEmpty()) { addTelecom(); } return getTelecom().get(0); } /** * @return {@link #address} (Address(es) of the practitioner that are not role specific (typically home address). Work addresses are not typically entered in this property as they are usually role dependent.) */ public List<Address> getAddress() { if (this.address == null) this.address = new ArrayList<Address>(); return this.address; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public Practitioner setAddress(List<Address> theAddress) { this.address = theAddress; return this; } public boolean hasAddress() { if (this.address == null) return false; for (Address item : this.address) if (!item.isEmpty()) return true; return false; } public Address addAddress() { //3 Address t = new Address(); if (this.address == null) this.address = new ArrayList<Address>(); this.address.add(t); return t; } public Practitioner addAddress(Address t) { //3 if (t == null) return this; if (this.address == null) this.address = new ArrayList<Address>(); this.address.add(t); return this; } /** * @return The first repetition of repeating field {@link #address}, creating it if it does not already exist */ public Address getAddressFirstRep() { if (getAddress().isEmpty()) { addAddress(); } return getAddress().get(0); } /** * @return {@link #gender} (Administrative Gender - the gender that the person is considered to have for administration and record keeping purposes.). This is the underlying object with id, value and extensions. The accessor "getGender" gives direct access to the value */ public Enumeration<AdministrativeGender> getGenderElement() { if (this.gender == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create Practitioner.gender"); else if (Configuration.doAutoCreate()) this.gender = new Enumeration<AdministrativeGender>(new AdministrativeGenderEnumFactory()); // bb return this.gender; } public boolean hasGenderElement() { return this.gender != null && !this.gender.isEmpty(); } public boolean hasGender() { return this.gender != null && !this.gender.isEmpty(); } /** * @param value {@link #gender} (Administrative Gender - the gender that the person is considered to have for administration and record keeping purposes.). This is the underlying object with id, value and extensions. The accessor "getGender" gives direct access to the value */ public Practitioner setGenderElement(Enumeration<AdministrativeGender> value) { this.gender = value; return this; } /** * @return Administrative Gender - the gender that the person is considered to have for administration and record keeping purposes. */ public AdministrativeGender getGender() { return this.gender == null ? null : this.gender.getValue(); } /** * @param value Administrative Gender - the gender that the person is considered to have for administration and record keeping purposes. */ public Practitioner setGender(AdministrativeGender value) { if (value == null) this.gender = null; else { if (this.gender == null) this.gender = new Enumeration<AdministrativeGender>(new AdministrativeGenderEnumFactory()); this.gender.setValue(value); } return this; } /** * @return {@link #birthDate} (The date of birth for the practitioner.). This is the underlying object with id, value and extensions. The accessor "getBirthDate" gives direct access to the value */ public DateType getBirthDateElement() { if (this.birthDate == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create Practitioner.birthDate"); else if (Configuration.doAutoCreate()) this.birthDate = new DateType(); // bb return this.birthDate; } public boolean hasBirthDateElement() { return this.birthDate != null && !this.birthDate.isEmpty(); } public boolean hasBirthDate() { return this.birthDate != null && !this.birthDate.isEmpty(); } /** * @param value {@link #birthDate} (The date of birth for the practitioner.). This is the underlying object with id, value and extensions. The accessor "getBirthDate" gives direct access to the value */ public Practitioner setBirthDateElement(DateType value) { this.birthDate = value; return this; } /** * @return The date of birth for the practitioner. */ public Date getBirthDate() { return this.birthDate == null ? null : this.birthDate.getValue(); } /** * @param value The date of birth for the practitioner. */ public Practitioner setBirthDate(Date value) { if (value == null) this.birthDate = null; else { if (this.birthDate == null) this.birthDate = new DateType(); this.birthDate.setValue(value); } return this; } /** * @return {@link #photo} (Image of the person.) */ public List<Attachment> getPhoto() { if (this.photo == null) this.photo = new ArrayList<Attachment>(); return this.photo; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public Practitioner setPhoto(List<Attachment> thePhoto) { this.photo = thePhoto; return this; } public boolean hasPhoto() { if (this.photo == null) return false; for (Attachment item : this.photo) if (!item.isEmpty()) return true; return false; } public Attachment addPhoto() { //3 Attachment t = new Attachment(); if (this.photo == null) this.photo = new ArrayList<Attachment>(); this.photo.add(t); return t; } public Practitioner addPhoto(Attachment t) { //3 if (t == null) return this; if (this.photo == null) this.photo = new ArrayList<Attachment>(); this.photo.add(t); return this; } /** * @return The first repetition of repeating field {@link #photo}, creating it if it does not already exist */ public Attachment getPhotoFirstRep() { if (getPhoto().isEmpty()) { addPhoto(); } return getPhoto().get(0); } /** * @return {@link #qualification} (Qualifications obtained by training and certification.) */ public List<PractitionerQualificationComponent> getQualification() { if (this.qualification == null) this.qualification = new ArrayList<PractitionerQualificationComponent>(); return this.qualification; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public Practitioner setQualification(List<PractitionerQualificationComponent> theQualification) { this.qualification = theQualification; return this; } public boolean hasQualification() { if (this.qualification == null) return false; for (PractitionerQualificationComponent item : this.qualification) if (!item.isEmpty()) return true; return false; } public PractitionerQualificationComponent addQualification() { //3 PractitionerQualificationComponent t = new PractitionerQualificationComponent(); if (this.qualification == null) this.qualification = new ArrayList<PractitionerQualificationComponent>(); this.qualification.add(t); return t; } public Practitioner addQualification(PractitionerQualificationComponent t) { //3 if (t == null) return this; if (this.qualification == null) this.qualification = new ArrayList<PractitionerQualificationComponent>(); this.qualification.add(t); return this; } /** * @return The first repetition of repeating field {@link #qualification}, creating it if it does not already exist */ public PractitionerQualificationComponent getQualificationFirstRep() { if (getQualification().isEmpty()) { addQualification(); } return getQualification().get(0); } /** * @return {@link #communication} (A language the practitioner is able to use in patient communication.) */ public List<CodeableConcept> getCommunication() { if (this.communication == null) this.communication = new ArrayList<CodeableConcept>(); return this.communication; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public Practitioner setCommunication(List<CodeableConcept> theCommunication) { this.communication = theCommunication; return this; } public boolean hasCommunication() { if (this.communication == null) return false; for (CodeableConcept item : this.communication) if (!item.isEmpty()) return true; return false; } public CodeableConcept addCommunication() { //3 CodeableConcept t = new CodeableConcept(); if (this.communication == null) this.communication = new ArrayList<CodeableConcept>(); this.communication.add(t); return t; } public Practitioner addCommunication(CodeableConcept t) { //3 if (t == null) return this; if (this.communication == null) this.communication = new ArrayList<CodeableConcept>(); this.communication.add(t); return this; } /** * @return The first repetition of repeating field {@link #communication}, creating it if it does not already exist */ public CodeableConcept getCommunicationFirstRep() { if (getCommunication().isEmpty()) { addCommunication(); } return getCommunication().get(0); } protected void listChildren(List<Property> childrenList) { super.listChildren(childrenList); childrenList.add(new Property("identifier", "Identifier", "An identifier that applies to this person in this role.", 0, java.lang.Integer.MAX_VALUE, identifier)); childrenList.add(new Property("active", "boolean", "Whether this practitioner's record is in active use.", 0, java.lang.Integer.MAX_VALUE, active)); childrenList.add(new Property("name", "HumanName", "The name(s) associated with the practitioner.", 0, java.lang.Integer.MAX_VALUE, name)); childrenList.add(new Property("telecom", "ContactPoint", "A contact detail for the practitioner, e.g. a telephone number or an email address.", 0, java.lang.Integer.MAX_VALUE, telecom)); childrenList.add(new Property("address", "Address", "Address(es) of the practitioner that are not role specific (typically home address). \rWork addresses are not typically entered in this property as they are usually role dependent.", 0, java.lang.Integer.MAX_VALUE, address)); childrenList.add(new Property("gender", "code", "Administrative Gender - the gender that the person is considered to have for administration and record keeping purposes.", 0, java.lang.Integer.MAX_VALUE, gender)); childrenList.add(new Property("birthDate", "date", "The date of birth for the practitioner.", 0, java.lang.Integer.MAX_VALUE, birthDate)); childrenList.add(new Property("photo", "Attachment", "Image of the person.", 0, java.lang.Integer.MAX_VALUE, photo)); childrenList.add(new Property("qualification", "", "Qualifications obtained by training and certification.", 0, java.lang.Integer.MAX_VALUE, qualification)); childrenList.add(new Property("communication", "CodeableConcept", "A language the practitioner is able to use in patient communication.", 0, java.lang.Integer.MAX_VALUE, communication)); } @Override public Base[] getProperty(int hash, String name, boolean checkValid) throws FHIRException { switch (hash) { case -1618432855: /*identifier*/ return this.identifier == null ? new Base[0] : this.identifier.toArray(new Base[this.identifier.size()]); // Identifier case -1422950650: /*active*/ return this.active == null ? new Base[0] : new Base[] {this.active}; // BooleanType case 3373707: /*name*/ return this.name == null ? new Base[0] : this.name.toArray(new Base[this.name.size()]); // HumanName case -1429363305: /*telecom*/ return this.telecom == null ? new Base[0] : this.telecom.toArray(new Base[this.telecom.size()]); // ContactPoint case -1147692044: /*address*/ return this.address == null ? new Base[0] : this.address.toArray(new Base[this.address.size()]); // Address case -1249512767: /*gender*/ return this.gender == null ? new Base[0] : new Base[] {this.gender}; // Enumeration<AdministrativeGender> case -1210031859: /*birthDate*/ return this.birthDate == null ? new Base[0] : new Base[] {this.birthDate}; // DateType case 106642994: /*photo*/ return this.photo == null ? new Base[0] : this.photo.toArray(new Base[this.photo.size()]); // Attachment case -631333393: /*qualification*/ return this.qualification == null ? new Base[0] : this.qualification.toArray(new Base[this.qualification.size()]); // PractitionerQualificationComponent case -1035284522: /*communication*/ return this.communication == null ? new Base[0] : this.communication.toArray(new Base[this.communication.size()]); // CodeableConcept default: return super.getProperty(hash, name, checkValid); } } @Override public Base setProperty(int hash, String name, Base value) throws FHIRException { switch (hash) { case -1618432855: // identifier this.getIdentifier().add(castToIdentifier(value)); // Identifier return value; case -1422950650: // active this.active = castToBoolean(value); // BooleanType return value; case 3373707: // name this.getName().add(castToHumanName(value)); // HumanName return value; case -1429363305: // telecom this.getTelecom().add(castToContactPoint(value)); // ContactPoint return value; case -1147692044: // address this.getAddress().add(castToAddress(value)); // Address return value; case -1249512767: // gender value = new AdministrativeGenderEnumFactory().fromType(castToCode(value)); this.gender = (Enumeration) value; // Enumeration<AdministrativeGender> return value; case -1210031859: // birthDate this.birthDate = castToDate(value); // DateType return value; case 106642994: // photo this.getPhoto().add(castToAttachment(value)); // Attachment return value; case -631333393: // qualification this.getQualification().add((PractitionerQualificationComponent) value); // PractitionerQualificationComponent return value; case -1035284522: // communication this.getCommunication().add(castToCodeableConcept(value)); // CodeableConcept return value; default: return super.setProperty(hash, name, value); } } @Override public Base setProperty(String name, Base value) throws FHIRException { if (name.equals("identifier")) { this.getIdentifier().add(castToIdentifier(value)); } else if (name.equals("active")) { this.active = castToBoolean(value); // BooleanType } else if (name.equals("name")) { this.getName().add(castToHumanName(value)); } else if (name.equals("telecom")) { this.getTelecom().add(castToContactPoint(value)); } else if (name.equals("address")) { this.getAddress().add(castToAddress(value)); } else if (name.equals("gender")) { value = new AdministrativeGenderEnumFactory().fromType(castToCode(value)); this.gender = (Enumeration) value; // Enumeration<AdministrativeGender> } else if (name.equals("birthDate")) { this.birthDate = castToDate(value); // DateType } else if (name.equals("photo")) { this.getPhoto().add(castToAttachment(value)); } else if (name.equals("qualification")) { this.getQualification().add((PractitionerQualificationComponent) value); } else if (name.equals("communication")) { this.getCommunication().add(castToCodeableConcept(value)); } else return super.setProperty(name, value); return value; } @Override public Base makeProperty(int hash, String name) throws FHIRException { switch (hash) { case -1618432855: return addIdentifier(); case -1422950650: return getActiveElement(); case 3373707: return addName(); case -1429363305: return addTelecom(); case -1147692044: return addAddress(); case -1249512767: return getGenderElement(); case -1210031859: return getBirthDateElement(); case 106642994: return addPhoto(); case -631333393: return addQualification(); case -1035284522: return addCommunication(); default: return super.makeProperty(hash, name); } } @Override public String[] getTypesForProperty(int hash, String name) throws FHIRException { switch (hash) { case -1618432855: /*identifier*/ return new String[] {"Identifier"}; case -1422950650: /*active*/ return new String[] {"boolean"}; case 3373707: /*name*/ return new String[] {"HumanName"}; case -1429363305: /*telecom*/ return new String[] {"ContactPoint"}; case -1147692044: /*address*/ return new String[] {"Address"}; case -1249512767: /*gender*/ return new String[] {"code"}; case -1210031859: /*birthDate*/ return new String[] {"date"}; case 106642994: /*photo*/ return new String[] {"Attachment"}; case -631333393: /*qualification*/ return new String[] {}; case -1035284522: /*communication*/ return new String[] {"CodeableConcept"}; default: return super.getTypesForProperty(hash, name); } } @Override public Base addChild(String name) throws FHIRException { if (name.equals("identifier")) { return addIdentifier(); } else if (name.equals("active")) { throw new FHIRException("Cannot call addChild on a primitive type Practitioner.active"); } else if (name.equals("name")) { return addName(); } else if (name.equals("telecom")) { return addTelecom(); } else if (name.equals("address")) { return addAddress(); } else if (name.equals("gender")) { throw new FHIRException("Cannot call addChild on a primitive type Practitioner.gender"); } else if (name.equals("birthDate")) { throw new FHIRException("Cannot call addChild on a primitive type Practitioner.birthDate"); } else if (name.equals("photo")) { return addPhoto(); } else if (name.equals("qualification")) { return addQualification(); } else if (name.equals("communication")) { return addCommunication(); } else return super.addChild(name); } public String fhirType() { return "Practitioner"; } public Practitioner copy() { Practitioner dst = new Practitioner(); copyValues(dst); if (identifier != null) { dst.identifier = new ArrayList<Identifier>(); for (Identifier i : identifier) dst.identifier.add(i.copy()); }; dst.active = active == null ? null : active.copy(); if (name != null) { dst.name = new ArrayList<HumanName>(); for (HumanName i : name) dst.name.add(i.copy()); }; if (telecom != null) { dst.telecom = new ArrayList<ContactPoint>(); for (ContactPoint i : telecom) dst.telecom.add(i.copy()); }; if (address != null) { dst.address = new ArrayList<Address>(); for (Address i : address) dst.address.add(i.copy()); }; dst.gender = gender == null ? null : gender.copy(); dst.birthDate = birthDate == null ? null : birthDate.copy(); if (photo != null) { dst.photo = new ArrayList<Attachment>(); for (Attachment i : photo) dst.photo.add(i.copy()); }; if (qualification != null) { dst.qualification = new ArrayList<PractitionerQualificationComponent>(); for (PractitionerQualificationComponent i : qualification) dst.qualification.add(i.copy()); }; if (communication != null) { dst.communication = new ArrayList<CodeableConcept>(); for (CodeableConcept i : communication) dst.communication.add(i.copy()); }; return dst; } protected Practitioner typedCopy() { return copy(); } @Override public boolean equalsDeep(Base other) { if (!super.equalsDeep(other)) return false; if (!(other instanceof Practitioner)) return false; Practitioner o = (Practitioner) other; return compareDeep(identifier, o.identifier, true) && compareDeep(active, o.active, true) && compareDeep(name, o.name, true) && compareDeep(telecom, o.telecom, true) && compareDeep(address, o.address, true) && compareDeep(gender, o.gender, true) && compareDeep(birthDate, o.birthDate, true) && compareDeep(photo, o.photo, true) && compareDeep(qualification, o.qualification, true) && compareDeep(communication, o.communication, true); } @Override public boolean equalsShallow(Base other) { if (!super.equalsShallow(other)) return false; if (!(other instanceof Practitioner)) return false; Practitioner o = (Practitioner) other; return compareValues(active, o.active, true) && compareValues(gender, o.gender, true) && compareValues(birthDate, o.birthDate, true) ; } public boolean isEmpty() { return super.isEmpty() && ca.uhn.fhir.util.ElementUtil.isEmpty(identifier, active, name , telecom, address, gender, birthDate, photo, qualification, communication); } @Override public ResourceType getResourceType() { return ResourceType.Practitioner; } /** * Search parameter: <b>identifier</b> * <p> * Description: <b>A practitioner's Identifier</b><br> * Type: <b>token</b><br> * Path: <b>Practitioner.identifier</b><br> * </p> */ @SearchParamDefinition(name="identifier", path="Practitioner.identifier", description="A practitioner's Identifier", type="token" ) public static final String SP_IDENTIFIER = "identifier"; /** * <b>Fluent Client</b> search parameter constant for <b>identifier</b> * <p> * Description: <b>A practitioner's Identifier</b><br> * Type: <b>token</b><br> * Path: <b>Practitioner.identifier</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam IDENTIFIER = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_IDENTIFIER); /** * Search parameter: <b>given</b> * <p> * Description: <b>A portion of the given name</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.name.given</b><br> * </p> */ @SearchParamDefinition(name="given", path="Practitioner.name.given", description="A portion of the given name", type="string" ) public static final String SP_GIVEN = "given"; /** * <b>Fluent Client</b> search parameter constant for <b>given</b> * <p> * Description: <b>A portion of the given name</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.name.given</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.StringClientParam GIVEN = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_GIVEN); /** * Search parameter: <b>address</b> * <p> * Description: <b>A server defined search that may match any of the string fields in the Address, including line, city, state, country, postalCode, and/or text</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.address</b><br> * </p> */ @SearchParamDefinition(name="address", path="Practitioner.address", description="A server defined search that may match any of the string fields in the Address, including line, city, state, country, postalCode, and/or text", type="string" ) public static final String SP_ADDRESS = "address"; /** * <b>Fluent Client</b> search parameter constant for <b>address</b> * <p> * Description: <b>A server defined search that may match any of the string fields in the Address, including line, city, state, country, postalCode, and/or text</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.address</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.StringClientParam ADDRESS = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_ADDRESS); /** * Search parameter: <b>address-state</b> * <p> * Description: <b>A state specified in an address</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.address.state</b><br> * </p> */ @SearchParamDefinition(name="address-state", path="Practitioner.address.state", description="A state specified in an address", type="string" ) public static final String SP_ADDRESS_STATE = "address-state"; /** * <b>Fluent Client</b> search parameter constant for <b>address-state</b> * <p> * Description: <b>A state specified in an address</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.address.state</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.StringClientParam ADDRESS_STATE = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_ADDRESS_STATE); /** * Search parameter: <b>gender</b> * <p> * Description: <b>Gender of the practitioner</b><br> * Type: <b>token</b><br> * Path: <b>Practitioner.gender</b><br> * </p> */ @SearchParamDefinition(name="gender", path="Practitioner.gender", description="Gender of the practitioner", type="token" ) public static final String SP_GENDER = "gender"; /** * <b>Fluent Client</b> search parameter constant for <b>gender</b> * <p> * Description: <b>Gender of the practitioner</b><br> * Type: <b>token</b><br> * Path: <b>Practitioner.gender</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam GENDER = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_GENDER); /** * Search parameter: <b>active</b> * <p> * Description: <b>Whether the practitioner record is active</b><br> * Type: <b>token</b><br> * Path: <b>Practitioner.active</b><br> * </p> */ @SearchParamDefinition(name="active", path="Practitioner.active", description="Whether the practitioner record is active", type="token" ) public static final String SP_ACTIVE = "active"; /** * <b>Fluent Client</b> search parameter constant for <b>active</b> * <p> * Description: <b>Whether the practitioner record is active</b><br> * Type: <b>token</b><br> * Path: <b>Practitioner.active</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam ACTIVE = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_ACTIVE); /** * Search parameter: <b>address-postalcode</b> * <p> * Description: <b>A postalCode specified in an address</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.address.postalCode</b><br> * </p> */ @SearchParamDefinition(name="address-postalcode", path="Practitioner.address.postalCode", description="A postalCode specified in an address", type="string" ) public static final String SP_ADDRESS_POSTALCODE = "address-postalcode"; /** * <b>Fluent Client</b> search parameter constant for <b>address-postalcode</b> * <p> * Description: <b>A postalCode specified in an address</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.address.postalCode</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.StringClientParam ADDRESS_POSTALCODE = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_ADDRESS_POSTALCODE); /** * Search parameter: <b>address-country</b> * <p> * Description: <b>A country specified in an address</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.address.country</b><br> * </p> */ @SearchParamDefinition(name="address-country", path="Practitioner.address.country", description="A country specified in an address", type="string" ) public static final String SP_ADDRESS_COUNTRY = "address-country"; /** * <b>Fluent Client</b> search parameter constant for <b>address-country</b> * <p> * Description: <b>A country specified in an address</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.address.country</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.StringClientParam ADDRESS_COUNTRY = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_ADDRESS_COUNTRY); /** * Search parameter: <b>phonetic</b> * <p> * Description: <b>A portion of either family or given name using some kind of phonetic matching algorithm</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.name</b><br> * </p> */ @SearchParamDefinition(name="phonetic", path="Practitioner.name", description="A portion of either family or given name using some kind of phonetic matching algorithm", type="string" ) public static final String SP_PHONETIC = "phonetic"; /** * <b>Fluent Client</b> search parameter constant for <b>phonetic</b> * <p> * Description: <b>A portion of either family or given name using some kind of phonetic matching algorithm</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.name</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.StringClientParam PHONETIC = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_PHONETIC); /** * Search parameter: <b>phone</b> * <p> * Description: <b>A value in a phone contact</b><br> * Type: <b>token</b><br> * Path: <b>Practitioner.telecom(system=phone)</b><br> * </p> */ @SearchParamDefinition(name="phone", path="Practitioner.telecom.where(system='phone')", description="A value in a phone contact", type="token" ) public static final String SP_PHONE = "phone"; /** * <b>Fluent Client</b> search parameter constant for <b>phone</b> * <p> * Description: <b>A value in a phone contact</b><br> * Type: <b>token</b><br> * Path: <b>Practitioner.telecom(system=phone)</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam PHONE = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_PHONE); /** * Search parameter: <b>name</b> * <p> * Description: <b>A server defined search that may match any of the string fields in the HumanName, including family, give, prefix, suffix, suffix, and/or text</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.name</b><br> * </p> */ @SearchParamDefinition(name="name", path="Practitioner.name", description="A server defined search that may match any of the string fields in the HumanName, including family, give, prefix, suffix, suffix, and/or text", type="string" ) public static final String SP_NAME = "name"; /** * <b>Fluent Client</b> search parameter constant for <b>name</b> * <p> * Description: <b>A server defined search that may match any of the string fields in the HumanName, including family, give, prefix, suffix, suffix, and/or text</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.name</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.StringClientParam NAME = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_NAME); /** * Search parameter: <b>address-use</b> * <p> * Description: <b>A use code specified in an address</b><br> * Type: <b>token</b><br> * Path: <b>Practitioner.address.use</b><br> * </p> */ @SearchParamDefinition(name="address-use", path="Practitioner.address.use", description="A use code specified in an address", type="token" ) public static final String SP_ADDRESS_USE = "address-use"; /** * <b>Fluent Client</b> search parameter constant for <b>address-use</b> * <p> * Description: <b>A use code specified in an address</b><br> * Type: <b>token</b><br> * Path: <b>Practitioner.address.use</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam ADDRESS_USE = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_ADDRESS_USE); /** * Search parameter: <b>telecom</b> * <p> * Description: <b>The value in any kind of contact</b><br> * Type: <b>token</b><br> * Path: <b>Practitioner.telecom</b><br> * </p> */ @SearchParamDefinition(name="telecom", path="Practitioner.telecom", description="The value in any kind of contact", type="token" ) public static final String SP_TELECOM = "telecom"; /** * <b>Fluent Client</b> search parameter constant for <b>telecom</b> * <p> * Description: <b>The value in any kind of contact</b><br> * Type: <b>token</b><br> * Path: <b>Practitioner.telecom</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam TELECOM = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_TELECOM); /** * Search parameter: <b>family</b> * <p> * Description: <b>A portion of the family name</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.name.family</b><br> * </p> */ @SearchParamDefinition(name="family", path="Practitioner.name.family", description="A portion of the family name", type="string" ) public static final String SP_FAMILY = "family"; /** * <b>Fluent Client</b> search parameter constant for <b>family</b> * <p> * Description: <b>A portion of the family name</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.name.family</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.StringClientParam FAMILY = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_FAMILY); /** * Search parameter: <b>address-city</b> * <p> * Description: <b>A city specified in an address</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.address.city</b><br> * </p> */ @SearchParamDefinition(name="address-city", path="Practitioner.address.city", description="A city specified in an address", type="string" ) public static final String SP_ADDRESS_CITY = "address-city"; /** * <b>Fluent Client</b> search parameter constant for <b>address-city</b> * <p> * Description: <b>A city specified in an address</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.address.city</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.StringClientParam ADDRESS_CITY = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_ADDRESS_CITY); /** * Search parameter: <b>communication</b> * <p> * Description: <b>One of the languages that the practitioner can communicate with</b><br> * Type: <b>token</b><br> * Path: <b>Practitioner.communication</b><br> * </p> */ @SearchParamDefinition(name="communication", path="Practitioner.communication", description="One of the languages that the practitioner can communicate with", type="token" ) public static final String SP_COMMUNICATION = "communication"; /** * <b>Fluent Client</b> search parameter constant for <b>communication</b> * <p> * Description: <b>One of the languages that the practitioner can communicate with</b><br> * Type: <b>token</b><br> * Path: <b>Practitioner.communication</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam COMMUNICATION = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_COMMUNICATION); /** * Search parameter: <b>email</b> * <p> * Description: <b>A value in an email contact</b><br> * Type: <b>token</b><br> * Path: <b>Practitioner.telecom(system=email)</b><br> * </p> */ @SearchParamDefinition(name="email", path="Practitioner.telecom.where(system='email')", description="A value in an email contact", type="token" ) public static final String SP_EMAIL = "email"; /** * <b>Fluent Client</b> search parameter constant for <b>email</b> * <p> * Description: <b>A value in an email contact</b><br> * Type: <b>token</b><br> * Path: <b>Practitioner.telecom(system=email)</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam EMAIL = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_EMAIL); }
eug48/hapi-fhir
hapi-fhir-structures-dstu3/src/main/java/org/hl7/fhir/dstu3/model/Practitioner.java
Java
apache-2.0
65,552
/* * Copyright 2013 Cyber Eagle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 br.com.cybereagle.androidlibrary.util; import android.app.Activity; import android.view.inputmethod.InputMethodManager; public class Utils { public static void hideSoftKeyboard(Activity activity) { InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0); } }
CyberEagle/AndroidLibrary
library/src/main/java/br/com/cybereagle/androidlibrary/util/Utils.java
Java
apache-2.0
1,060
package org.web3j.abi.datatypes.generated; import java.math.BigInteger; import org.web3j.abi.datatypes.Fixed; /** * <p>Auto generated code.<br> * <strong>Do not modifiy!</strong><br> * Please use {@link org.web3j.codegen.AbiTypesGenerator} to update.</p> */ public class Fixed112x72 extends Fixed { public static final Fixed112x72 DEFAULT = new Fixed112x72(BigInteger.ZERO); public Fixed112x72(BigInteger value) { super(112, 72, value); } public Fixed112x72(int mBitSize, int nBitSize, BigInteger m, BigInteger n) { super(112, 72, m, n); } }
saulbein/web3j
core/src/main/java/org/web3j/abi/datatypes/generated/Fixed112x72.java
Java
apache-2.0
587
package com.krux.stdlib.status; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; public class StatusBean { private final AppState state; private final String message; private final List<String> warnings = new ArrayList<>(); private final List<String> errors = new ArrayList<>(); public StatusBean(AppState appStatus, String message) { this.state = appStatus; this.message = message; } @Override public int hashCode() { // only the status and message contribute to this objects "identity" return Objects.hash(state, message); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null || !getClass().equals(obj.getClass())) { return false; } StatusBean that = (StatusBean) obj; return Objects.equals(this.state, that.state) && Objects.equals(this.message, that.message); } protected ToStringBuilder toStringBuilder() { return new ToStringBuilder(this, ToStringStyle.DEFAULT_STYLE) .append("state", state) .append("message", message) .append("warnings", warnings) .append("errors", errors); } @Override public String toString() { return toStringBuilder().build(); } public AppState getAppStatus() { return state; } public String getMessage() { return message; } public List<String> getWarnings() { return Collections.unmodifiableList(warnings); } public List<String> getErrors() { return Collections.unmodifiableList(errors); } public StatusBean addWarning(String warning) { warnings.add(warning); return this; } public StatusBean addError(String error) { errors.add(error); return this; } }
krux/java-stdlib
krux-stdlib-monitoring/src/main/java/com/krux/stdlib/status/StatusBean.java
Java
apache-2.0
2,094
package com.morgan.grid.server.auth; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.google.inject.Provides; import com.morgan.grid.server.common.constants.AbstractConstantsModule; import com.morgan.grid.server.common.constants.BindConstant; import com.morgan.grid.shared.common.constants.DictionaryConstant; /** * GUICE module for configuring constants related to the auth application. * * @author mark@mark-morgan.net (Mark Morgan) */ final class AuthConstantsModule extends AbstractConstantsModule { @BindConstant(DictionaryConstant.AUTH_TEST_CONSTANT) @Provides protected String provideAuthTestConstant(HttpServletRequest request, HttpServletResponse response, HttpSession session) { return "Auth application for " + request.getRemoteAddr(); } }
mmm2a/GridApp
src/com/morgan/grid/server/auth/AuthConstantsModule.java
Java
apache-2.0
869
package com.sequenceiq.it.cloudbreak.log; import static java.lang.String.format; import java.io.IOException; import java.io.StringWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.ITestResult; import org.testng.Reporter; import com.fasterxml.jackson.databind.ObjectMapper; import com.sequenceiq.it.cloudbreak.dto.CloudbreakTestDto; public class Log<T extends CloudbreakTestDto> { public static final String TEST_CONTEXT_REPORTER = "testContextReporter"; public static final String ALTERNATE_LOG = "alternateLog"; private static final Logger LOGGER = LoggerFactory.getLogger(Log.class); private Log() { } public static void whenJson(Logger logger, String message, Object jsonObject) throws IOException { ObjectMapper mapper = new ObjectMapper(); StringWriter writer = new StringWriter(); mapper.writeValue(writer, jsonObject); log(logger, "When", message, writer.toString()); } public static void whenJson(String message, Object jsonObject) throws IOException { whenJson(null, message, jsonObject); } public static void log(String message, Object... args) { log(null, message, args); } public static void log(Logger logger, String message, Object... args) { String format = String.format(message, args); log(format); if (logger != null) { logger.info(format); } } public static void error(Logger logger, String message, Object... args) { String format = String.format(message, args); log(format); if (logger != null) { logger.error(format); } } private static void log(Logger logger, String step, String message) { log(logger, step, message, null); } private static void log(Logger logger, String step, String message, String json) { TestContextReporter testContextReporter = getReporter(); if (testContextReporter == null) { log(logger, step + " " + message); } else { getReporter().addStep(step, message, json); } publishReport(getReporter()); } public static void given(Logger logger, String message) { log(logger, "Given", message); } public static void as(Logger logger, String message) { log(logger, "As", message); } public static void when(Logger logger, String message) { log(logger, "When", message); } public static void whenException(Logger logger, String message) { log(logger, "WhenException", message); } public static void then(Logger logger, String message) { log(logger, "Then", message); } public static void expect(Logger logger, String message) { log(logger, "Expect", message); } public static void await(Logger logger, String message) { log(logger, "Await", message); } public static void validateError(Logger logger, String message) { log(logger, "Validate", message); } public static void log(String message) { Reporter.log(message); } public static void log(ITestResult testResult) { if (testResult != null) { Throwable testResultException = testResult.getThrowable(); String methodName = testResult.getName(); int status = testResult.getStatus(); if (testResultException != null) { try { String message = testResultException.getCause() != null ? testResultException.getCause().getMessage() : testResultException.getMessage(); String testFailureType = testResultException.getCause() != null ? testResultException.getCause().getClass().getName() : testResultException.getClass().getName(); if (message == null || message.isEmpty()) { log(format(" Test Case: %s have been failed with empty test result! ", methodName)); } else { LOGGER.info("Failed test results are: Test Case: {} | Status: {} | Failure Type: {} | Message: {}", methodName, status, testFailureType, message); log(message); } } catch (Exception e) { log(format(" Test Case: %s got Unexpected Exception: %s ", methodName, e.getMessage())); } } } else { LOGGER.error("Test result is NULL!"); } } private static TestContextReporter getReporter() { ITestResult res = Reporter.getCurrentTestResult(); if (res == null) { return null; } TestContextReporter reporter = (TestContextReporter) res.getAttribute(TEST_CONTEXT_REPORTER); if (reporter == null) { reporter = new TestContextReporter(); res.setAttribute(TEST_CONTEXT_REPORTER, reporter); } return reporter; } private static void publishReport(TestContextReporter testContextReporter) { ITestResult res = Reporter.getCurrentTestResult(); if (res != null) { res.setAttribute(ALTERNATE_LOG, testContextReporter.print()); } } }
hortonworks/cloudbreak
integration-test/src/main/java/com/sequenceiq/it/cloudbreak/log/Log.java
Java
apache-2.0
5,386
package practicaltest02.eim.systems.cs.pub.ro.practicaltest2; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("practicaltest02.eim.systems.cs.pub.ro.practicaltest2", appContext.getPackageName()); } }
hstoenescu/PracticalTest02
PracticalTest2/app/src/androidTest/java/practicaltest02/eim/systems/cs/pub/ro/practicaltest2/ExampleInstrumentedTest.java
Java
apache-2.0
808
package com.lenox.beyondj.action.site; import com.lenox.beyondj.action.BaseActionBean; import com.lenox.beyondj.action.SkipAuthentication; import net.sourceforge.stripes.action.DefaultHandler; import net.sourceforge.stripes.action.ForwardResolution; import net.sourceforge.stripes.action.Resolution; import net.sourceforge.stripes.action.UrlBinding; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @SkipAuthentication @UrlBinding("/web/faqs") public class FAQActionBean extends BaseActionBean { @DefaultHandler public Resolution view() { return new ForwardResolution(JSP); } private static final String JSP = "/WEB-INF/jsp/site/faqs.jsp"; @Override protected Logger getLogger(){ return LOG; } private Logger LOG = LoggerFactory.getLogger(FAQActionBean.class); }
nkasvosve/beyondj
beyondj-admin/beyondj-web-console/src/main/java/com/lenox/beyondj/action/site/FAQActionBean.java
Java
apache-2.0
854
// Copyright 2017 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package data import ( "bytes" "encoding/csv" "encoding/json" "errors" "net/http" "strings" "time" "github.com/spf13/hugo/deps" jww "github.com/spf13/jwalterweatherman" ) // New returns a new instance of the data-namespaced template functions. func New(deps *deps.Deps) *Namespace { return &Namespace{ deps: deps, client: http.DefaultClient, } } // Namespace provides template functions for the "data" namespace. type Namespace struct { deps *deps.Deps client *http.Client } // GetCSV expects a data separator and one or n-parts of a URL to a resource which // can either be a local or a remote one. // The data separator can be a comma, semi-colon, pipe, etc, but only one character. // If you provide multiple parts for the URL they will be joined together to the final URL. // GetCSV returns nil or a slice slice to use in a short code. func (ns *Namespace) GetCSV(sep string, urlParts ...string) (d [][]string, err error) { url := strings.Join(urlParts, "") var clearCacheSleep = func(i int, u string) { jww.ERROR.Printf("Retry #%d for %s and sleeping for %s", i, url, resSleep) time.Sleep(resSleep) deleteCache(url, ns.deps.Fs.Source, ns.deps.Cfg) } for i := 0; i <= resRetries; i++ { var req *http.Request req, err = http.NewRequest("GET", url, nil) if err != nil { jww.ERROR.Printf("Failed to create request for getJSON: %s", err) return nil, err } req.Header.Add("Accept", "text/csv") req.Header.Add("Accept", "text/plain") var c []byte c, err = ns.getResource(req) if err != nil { jww.ERROR.Printf("Failed to read csv resource %q with error message %s", url, err) return nil, err } if !bytes.Contains(c, []byte(sep)) { err = errors.New("Cannot find separator " + sep + " in CSV.") return } if d, err = parseCSV(c, sep); err != nil { jww.ERROR.Printf("Failed to parse csv file %s with error message %s", url, err) clearCacheSleep(i, url) continue } break } return } // GetJSON expects one or n-parts of a URL to a resource which can either be a local or a remote one. // If you provide multiple parts they will be joined together to the final URL. // GetJSON returns nil or parsed JSON to use in a short code. func (ns *Namespace) GetJSON(urlParts ...string) (v interface{}, err error) { url := strings.Join(urlParts, "") for i := 0; i <= resRetries; i++ { var req *http.Request req, err = http.NewRequest("GET", url, nil) if err != nil { jww.ERROR.Printf("Failed to create request for getJSON: %s", err) return nil, err } req.Header.Add("Accept", "application/json") var c []byte c, err = ns.getResource(req) if err != nil { jww.ERROR.Printf("Failed to get json resource %s with error message %s", url, err) return nil, err } err = json.Unmarshal(c, &v) if err != nil { jww.ERROR.Printf("Cannot read json from resource %s with error message %s", url, err) jww.ERROR.Printf("Retry #%d for %s and sleeping for %s", i, url, resSleep) time.Sleep(resSleep) deleteCache(url, ns.deps.Fs.Source, ns.deps.Cfg) continue } break } return } // parseCSV parses bytes of CSV data into a slice slice string or an error func parseCSV(c []byte, sep string) ([][]string, error) { if len(sep) != 1 { return nil, errors.New("Incorrect length of csv separator: " + sep) } b := bytes.NewReader(c) r := csv.NewReader(b) rSep := []rune(sep) r.Comma = rSep[0] r.FieldsPerRecord = 0 return r.ReadAll() }
digitalcraftsman/hugo
tpl/data/data.go
GO
apache-2.0
4,068
package com.example.supertux.Macros; import android.app.AlertDialog; import android.app.Fragment; import android.content.DialogInterface; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; public class EntryFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState) { final View view = inflater.inflate(R.layout.entry_item, container, false); final MainActivity mainActivity = (MainActivity) getActivity(); MyEntry myEntry = mainActivity.databaseH.getEntry(mainActivity.entryName, mainActivity.entryTime); TextView itemNameTextView = (TextView) view.findViewById(R.id.name_text_view); itemNameTextView.setText(mainActivity.entryName, TextView.BufferType.EDITABLE); TextView timeTextView = (TextView) view.findViewById(R.id.entry_time_text_view); timeTextView.setText(mainActivity.entryTime, TextView.BufferType.EDITABLE); TextView caloriesTextView = (TextView) view.findViewById(R.id.calories_text_view); caloriesTextView.setText(caloriesTextView.getText() + myEntry.calories.toString(), TextView.BufferType.EDITABLE); TextView fatsTextView = (TextView) view.findViewById(R.id.fats_text_view); fatsTextView.setText(fatsTextView.getText() + myEntry.fats.toString(), TextView.BufferType.EDITABLE); TextView carbsTextView = (TextView) view.findViewById(R.id.carbs_text_view); carbsTextView.setText(carbsTextView.getText() + myEntry.carbs.toString(), TextView.BufferType.EDITABLE); TextView proteinTextView = (TextView) view.findViewById(R.id.protein_text_view); proteinTextView.setText(proteinTextView.getText() + myEntry.protein.toString(), TextView.BufferType.EDITABLE); TextView servings = (TextView) view.findViewById(R.id.servings_text_view); servings.setText(servings.getText() + myEntry.servings.toString(), TextView.BufferType.EDITABLE); Button deleteEntryButton = (Button) view.findViewById(R.id.delete_entry_button); deleteEntryButton.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { new AlertDialog.Builder(mainActivity) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle("Delete Item") .setMessage("Are you sure?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mainActivity.databaseH.deleteEntry(mainActivity.entryName, mainActivity.entryTime); ListAllEntriesFragment listAllEntriesFragment = new ListAllEntriesFragment(); getFragmentManager().beginTransaction().replace(R.id.fragment_container, listAllEntriesFragment).addToBackStack(null).commit(); } }) .setNegativeButton("No", null) .show(); } }); return view; } }
terryhtran/macros
java/com/example/supertux/Macros/EntryFragment.java
Java
apache-2.0
3,398
package objects; public class Term /*implements Comparable<Term>*/{ private int m; private int n; private int val; //private int frequency; public Term(int m, int n){ this.setM(m); this.setN(n); //frequency = 0; } public int getM() { return m; } private void setM(int m) { this.m = m; } public int getN() { return n; } private void setN(int n) { this.n = n; } public int getVal() { //frequency++; return val; } public void setVal(int val) { this.val = val; } /*public int getFrequency(){ return frequency; } @Override public int compareTo(Term o) { if(frequency > o.getFrequency()) return -1; else if(frequency < o.getFrequency()) return 1; else return 0; }*/ public boolean equals(Object o){ return ((Term) o).getM() == getM() && ((Term) o).getN() == getN(); } /*public String toString(){ return "" + frequency; }*/ }
Noah-Kennedy/MathAndResearch
NewAck/src/objects/Term.java
Java
apache-2.0
964
'use strict'; let lib = { "_id": "5e409c94c5a59210a815262c", "name": "pay", "description": "MS pay service for marketplace", "type": "service", "configuration": { "subType": "ecommerce", "port": 4102, "group": "Marketplace", "requestTimeout": 30, "requestTimeoutRenewal": 5, "maintenance": { "port": { "type": "maintenance" }, "readiness": "/heartbeat" } }, "versions": [ { "version": "1", "extKeyRequired": true, "oauth": true, "provision_ACL": false, "tenant_Profile": false, "urac": false, "urac_ACL": false, "urac_Config": false, "urac_GroupConfig": false, "urac_Profile": false, "apis": [ { l: "pay items", v: "/pay", m: "post", group: "Pay" }, { l: "Get all pay ", v: "/pays", m: "get", group: "Pay" } ], "documentation": {} } ], "metadata": { "tags": ["order", "ecommerce"], "program": ["marketplace"] }, "ui": { "main": "Gateway", "sub": "" }, "settings": { "acl": { "public": { "ro": true } }, "recipes": [], "environments": {} }, "src": { "provider": "github", "owner": "ht", "repo": "mkpl.order" } }; module.exports = lib;
soajs/soajs
test/data/integration/marketplace/pay.js
JavaScript
apache-2.0
1,208
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jbpm.persistence.scripts.quartzmockentities; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.IdClass; @Entity(name = "QRTZ_PAUSED_TRIGGER_GRPS") @IdClass(QrtzPausedTriggersId.class) public class QrtzPausedTriggerGrps { @Id @Column(name = "SCHED_NAME") private String schedulerName; @Id @Column(name = "TRIGGER_GROUP") private String triggerGroup; public QrtzPausedTriggerGrps schedulerName(final String schedulerName) { this.schedulerName = schedulerName; return this; } public QrtzPausedTriggerGrps triggerGroup(final String triggerGroup) { this.triggerGroup = triggerGroup; return this; } }
baldimir/jbpm
jbpm-installer/src/test/java/org/jbpm/persistence/scripts/quartzmockentities/QrtzPausedTriggerGrps.java
Java
apache-2.0
1,376
/* * Copyright (c) 2021 EmeraldPay Inc, All Rights Reserved. * Copyright (c) 2016-2019 Igor Artamonov, 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. */ package io.emeraldpay.etherjar.tx; import io.emeraldpay.etherjar.domain.Address; import org.bouncycastle.jcajce.provider.digest.Keccak; import java.math.BigInteger; import java.util.Arrays; import java.util.Objects; /** * Signature of a message (i.e. of a transaction) */ public class Signature { private byte[] message; private int v; private BigInteger r; private BigInteger s; public Signature() { } /** * Creates existing signature * * @param message a signed message, usually a Keccak256 of some data * @param v v part of signature * @param r R part of signature * @param s S part of signature */ public Signature(byte[] message, int v, BigInteger r, BigInteger s) { this.message = message; this.v = v; this.r = r; this.s = s; } public byte[] getMessage() { return message; } public void setMessage(byte[] message) { this.message = message; } public SignatureType getType() { return SignatureType.LEGACY; } public int getV() { return v; } public void setV(int v) { this.v = v; } public BigInteger getR() { return r; } public void setR(BigInteger r) { this.r = r; } public BigInteger getS() { return s; } public void setS(BigInteger s) { this.s = s; } /** * Recovers address that signed the message. Requires signature (v,R,S) and message to be set * * @return Address which signed the message, or null if address cannot be extracted */ public Address recoverAddress() { try { if (message == null || message.length == 0) { throw new IllegalStateException("Transaction/Message hash are not set"); } byte[] pubkey = Signer.ecrecover(this); if (pubkey == null) { return null; } Keccak.Digest256 digest = new Keccak.Digest256(); digest.update(pubkey); byte[] hash = digest.digest(); byte[] buf = new byte[20]; System.arraycopy(hash, 12, buf, 0, 20); return Address.from(buf); } catch (Exception e) { e.printStackTrace(); } return null; } public int getRecId() { return v - 27; } public boolean canEqual(Signature signature) { return v == signature.v && Arrays.equals(message, signature.message) && Objects.equals(r, signature.r) && Objects.equals(s, signature.s); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Signature signature = (Signature) o; return canEqual(signature); } @Override public int hashCode() { return Objects.hash(r, s); } }
ethereumproject/etherjar
etherjar-tx/src/main/java/io/emeraldpay/etherjar/tx/Signature.java
Java
apache-2.0
3,663
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 __future__ import absolute_import, division, print_function import collections from contextlib import contextmanager import pytest import six from cryptography.exceptions import UnsupportedAlgorithm import cryptography_vectors HashVector = collections.namedtuple("HashVector", ["message", "digest"]) KeyedHashVector = collections.namedtuple( "KeyedHashVector", ["message", "digest", "key"] ) def select_backends(names, backend_list): if names is None: return backend_list split_names = [x.strip() for x in names.split(',')] # this must be duplicated and then removed to preserve the metadata # pytest associates. Appending backends to a new list doesn't seem to work selected_backends = [] for backend in backend_list: if backend.name in split_names: selected_backends.append(backend) if len(selected_backends) > 0: return selected_backends else: raise ValueError( "No backend selected. Tried to select: {0}".format(split_names) ) def check_for_iface(name, iface, item): if name in item.keywords and "backend" in item.funcargs: if not isinstance(item.funcargs["backend"], iface): pytest.skip("{0} backend does not support {1}".format( item.funcargs["backend"], name )) def check_backend_support(item): supported = item.keywords.get("supported") if supported and "backend" in item.funcargs: if not supported.kwargs["only_if"](item.funcargs["backend"]): pytest.skip("{0} ({1})".format( supported.kwargs["skip_message"], item.funcargs["backend"] )) elif supported: raise ValueError("This mark is only available on methods that take a " "backend") @contextmanager def raises_unsupported_algorithm(reason): with pytest.raises(UnsupportedAlgorithm) as exc_info: yield exc_info assert exc_info.value._reason is reason def load_vectors_from_file(filename, loader): with cryptography_vectors.open_vector_file(filename) as vector_file: return loader(vector_file) def load_nist_vectors(vector_data): test_data = None data = [] for line in vector_data: line = line.strip() # Blank lines, comments, and section headers are ignored if not line or line.startswith("#") or (line.startswith("[") and line.endswith("]")): continue if line.strip() == "FAIL": test_data["fail"] = True continue # Build our data using a simple Key = Value format name, value = [c.strip() for c in line.split("=")] # Some tests (PBKDF2) contain \0, which should be interpreted as a # null character rather than literal. value = value.replace("\\0", "\0") # COUNT is a special token that indicates a new block of data if name.upper() == "COUNT": test_data = {} data.append(test_data) continue # For all other tokens we simply want the name, value stored in # the dictionary else: test_data[name.lower()] = value.encode("ascii") return data def load_cryptrec_vectors(vector_data): cryptrec_list = [] for line in vector_data: line = line.strip() # Blank lines and comments are ignored if not line or line.startswith("#"): continue if line.startswith("K"): key = line.split(" : ")[1].replace(" ", "").encode("ascii") elif line.startswith("P"): pt = line.split(" : ")[1].replace(" ", "").encode("ascii") elif line.startswith("C"): ct = line.split(" : ")[1].replace(" ", "").encode("ascii") # after a C is found the K+P+C tuple is complete # there are many P+C pairs for each K cryptrec_list.append({ "key": key, "plaintext": pt, "ciphertext": ct }) else: raise ValueError("Invalid line in file '{}'".format(line)) return cryptrec_list def load_hash_vectors(vector_data): vectors = [] key = None msg = None md = None for line in vector_data: line = line.strip() if not line or line.startswith("#") or line.startswith("["): continue if line.startswith("Len"): length = int(line.split(" = ")[1]) elif line.startswith("Key"): # HMAC vectors contain a key attribute. Hash vectors do not. key = line.split(" = ")[1].encode("ascii") elif line.startswith("Msg"): # In the NIST vectors they have chosen to represent an empty # string as hex 00, which is of course not actually an empty # string. So we parse the provided length and catch this edge case. msg = line.split(" = ")[1].encode("ascii") if length > 0 else b"" elif line.startswith("MD"): md = line.split(" = ")[1] # after MD is found the Msg+MD (+ potential key) tuple is complete if key is not None: vectors.append(KeyedHashVector(msg, md, key)) key = None msg = None md = None else: vectors.append(HashVector(msg, md)) msg = None md = None else: raise ValueError("Unknown line in hash vector") return vectors def load_pkcs1_vectors(vector_data): """ Loads data out of RSA PKCS #1 vector files. """ private_key_vector = None public_key_vector = None attr = None key = None example_vector = None examples = [] vectors = [] for line in vector_data: if ( line.startswith("# PSS Example") or line.startswith("# PKCS#1 v1.5 Signature") ): if example_vector: for key, value in six.iteritems(example_vector): hex_str = "".join(value).replace(" ", "").encode("ascii") example_vector[key] = hex_str examples.append(example_vector) attr = None example_vector = collections.defaultdict(list) if line.startswith("# Message to be signed"): attr = "message" continue elif line.startswith("# Salt"): attr = "salt" continue elif line.startswith("# Signature"): attr = "signature" continue elif ( example_vector and line.startswith("# =============================================") ): for key, value in six.iteritems(example_vector): hex_str = "".join(value).replace(" ", "").encode("ascii") example_vector[key] = hex_str examples.append(example_vector) example_vector = None attr = None elif example_vector and line.startswith("#"): continue else: if attr is not None and example_vector is not None: example_vector[attr].append(line.strip()) continue if ( line.startswith("# Example") or line.startswith("# =============================================") ): if key: assert private_key_vector assert public_key_vector for key, value in six.iteritems(public_key_vector): hex_str = "".join(value).replace(" ", "") public_key_vector[key] = int(hex_str, 16) for key, value in six.iteritems(private_key_vector): hex_str = "".join(value).replace(" ", "") private_key_vector[key] = int(hex_str, 16) private_key_vector["examples"] = examples examples = [] assert ( private_key_vector['public_exponent'] == public_key_vector['public_exponent'] ) assert ( private_key_vector['modulus'] == public_key_vector['modulus'] ) vectors.append( (private_key_vector, public_key_vector) ) public_key_vector = collections.defaultdict(list) private_key_vector = collections.defaultdict(list) key = None attr = None if private_key_vector is None or public_key_vector is None: continue if line.startswith("# Private key"): key = private_key_vector elif line.startswith("# Public key"): key = public_key_vector elif line.startswith("# Modulus:"): attr = "modulus" elif line.startswith("# Public exponent:"): attr = "public_exponent" elif line.startswith("# Exponent:"): if key is public_key_vector: attr = "public_exponent" else: assert key is private_key_vector attr = "private_exponent" elif line.startswith("# Prime 1:"): attr = "p" elif line.startswith("# Prime 2:"): attr = "q" elif line.startswith("# Prime exponent 1:"): attr = "dmp1" elif line.startswith("# Prime exponent 2:"): attr = "dmq1" elif line.startswith("# Coefficient:"): attr = "iqmp" elif line.startswith("#"): attr = None else: if key is not None and attr is not None: key[attr].append(line.strip()) return vectors def load_rsa_nist_vectors(vector_data): test_data = None p = None salt_length = None data = [] for line in vector_data: line = line.strip() # Blank lines and section headers are ignored if not line or line.startswith("["): continue if line.startswith("# Salt len:"): salt_length = int(line.split(":")[1].strip()) continue elif line.startswith("#"): continue # Build our data using a simple Key = Value format name, value = [c.strip() for c in line.split("=")] if name == "n": n = int(value, 16) elif name == "e" and p is None: e = int(value, 16) elif name == "p": p = int(value, 16) elif name == "q": q = int(value, 16) elif name == "SHAAlg": if p is None: test_data = { "modulus": n, "public_exponent": e, "salt_length": salt_length, "algorithm": value, "fail": False } else: test_data = { "modulus": n, "p": p, "q": q, "algorithm": value } if salt_length is not None: test_data["salt_length"] = salt_length data.append(test_data) elif name == "e" and p is not None: test_data["public_exponent"] = int(value, 16) elif name == "d": test_data["private_exponent"] = int(value, 16) elif name == "Result": test_data["fail"] = value.startswith("F") # For all other tokens we simply want the name, value stored in # the dictionary else: test_data[name.lower()] = value.encode("ascii") return data def load_fips_dsa_key_pair_vectors(vector_data): """ Loads data out of the FIPS DSA KeyPair vector files. """ vectors = [] # When reading_key_data is set to True it tells the loader to continue # constructing dictionaries. We set reading_key_data to False during the # blocks of the vectors of N=224 because we don't support it. reading_key_data = True for line in vector_data: line = line.strip() if not line or line.startswith("#"): continue elif line.startswith("[mod = L=1024"): continue elif line.startswith("[mod = L=2048, N=224"): reading_key_data = False continue elif line.startswith("[mod = L=2048, N=256"): reading_key_data = True continue elif line.startswith("[mod = L=3072"): continue if not reading_key_data: continue elif reading_key_data: if line.startswith("P"): vectors.append({'p': int(line.split("=")[1], 16)}) elif line.startswith("Q"): vectors[-1]['q'] = int(line.split("=")[1], 16) elif line.startswith("G"): vectors[-1]['g'] = int(line.split("=")[1], 16) elif line.startswith("X") and 'x' not in vectors[-1]: vectors[-1]['x'] = int(line.split("=")[1], 16) elif line.startswith("X") and 'x' in vectors[-1]: vectors.append({'p': vectors[-1]['p'], 'q': vectors[-1]['q'], 'g': vectors[-1]['g'], 'x': int(line.split("=")[1], 16) }) elif line.startswith("Y"): vectors[-1]['y'] = int(line.split("=")[1], 16) return vectors
Lukasa/cryptography
tests/utils.py
Python
apache-2.0
14,122
import React, {forwardRef} from 'react' import cn from 'classnames' import {Text} from '../Typography/Text' import type {HTMLAttributes, PropsWithRef} from 'react' import type {OmuiColors} from '@/styles/colorType' export type BadgeVariantProp = 'gray' | 'primary' | 'tertiary' | 'quaternary' | 'danger' | 'success' export type BadgeTypeProp = 'outline' | 'subtle' | 'solid' interface Props extends HTMLAttributes<HTMLDivElement> { /** * The variant of the badge. * @defaultValue primary */ variant: BadgeVariantProp /** * The type of the badge. * @defaultValue outline */ type: BadgeTypeProp /** * Indicates if the inner text should be truncated. * @defaultValue outline */ truncate?: boolean } export type BadgeProps = PropsWithRef<Props> const VARIANT_COLORS: Record<BadgeVariantProp, OmuiColors> = { gray: 'gray', primary: 'primary', tertiary: 'violet', quaternary: 'blue', danger: 'error', success: 'success' } as const type Badges = { [K in BadgeVariantProp]: { [O in BadgeTypeProp]: string | string[] } } const badges: Badges = Object.assign( {}, ...(Object.keys(VARIANT_COLORS) as Array<BadgeVariantProp>).map(variant => { const color = VARIANT_COLORS[variant] return { [variant]: { outline: [ 'py-px border', `border-${color}-500 text-${color}-600 dark:border-${color}-200 dark:text-${color}-200` ], subtle: ['py-0.5', `bg-${color}-100 text-${color}-600`], solid: ['py-0.5', color === 'gray' ? `text-primary-200 bg-gray-800` : `text-white bg-${color}-500`] } } }) ) const defaultClass = 'inline-block h-5.5 px-1.5 rounded-sm leading-normal' const Badge = forwardRef<HTMLDivElement, Props>(function Badge( {className, children, variant = 'primary', type = 'outline', truncate = false, ...props}, ref ) { const classes = cn(defaultClass, badges[variant]?.[type], truncate && 'truncate', className) return ( <div className={classes} ref={ref} {...props}> <Text bold size="xs" as="p" className={cn(truncate && 'truncate')}> {children} </Text> </div> ) }) export {Badge}
OpenMined/PySyft
packages/grid/frontend/src/omui/components/Badge/Badge.tsx
TypeScript
apache-2.0
2,164
<?php $url="http://maps.googleapis.com/maps/api/geocode/json?address=South C,Nairobi&key=AIzaSyCVhh7lEde0khX5vIWHRFHWY8UCo9eLDoE"; $urlnearby= $data=file_get_contents($url); print_r($data); ?>
geeknation/brilliantwriters
exercises_solutions/82VY9NXWLC531efc8273330/index.php
PHP
apache-2.0
196
/********************************************************************** // @@@ START COPYRIGHT @@@ // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // // @@@ END COPYRIGHT @@@ **********************************************************************/ /* -*-C++-*- ***************************************************************************** * * File: CliExpExchange.cpp * Description: Move data in and out of user host variables * * * Created: 7/10/95 * Language: C++ * * * * ***************************************************************************** */ #include "Platform.h" #ifdef _DEBUG #include <assert.h> #endif #include "exp_stdh.h" #include "exp_clause_derived.h" #include "ex_stdh.h" #include "cli_stdh.h" #include "exp_datetime.h" #include "exp_interval.h" #if defined( NA_SHADOWCALLS ) #include "sqlclisp.h" //shadow #endif #include "exp_expr.h" #include "ExRLE.h" // defined in exp_eval.C void computeDataPtr(char * start_data_ptr, // start of data row Lng32 field_num, // field number whose address is to be // computed. Zero based. ExpTupleDesc * td,// describes this row char ** opdata, char ** nulldata, char ** varlendata); static Lng32 getIntervalCode(short datatype) { switch (datatype) { case REC_INT_YEAR: return SQLINTCODE_YEAR; case REC_INT_MONTH: return SQLINTCODE_MONTH; case REC_INT_YEAR_MONTH: return SQLINTCODE_YEAR_MONTH; case REC_INT_DAY: return SQLINTCODE_DAY; case REC_INT_HOUR: return SQLINTCODE_HOUR; case REC_INT_DAY_HOUR: return SQLINTCODE_DAY_HOUR; case REC_INT_MINUTE: return SQLINTCODE_MINUTE; case REC_INT_HOUR_MINUTE: return SQLINTCODE_HOUR_MINUTE; case REC_INT_DAY_MINUTE: return SQLINTCODE_DAY_MINUTE; case REC_INT_SECOND: return SQLINTCODE_SECOND; case REC_INT_MINUTE_SECOND: return SQLINTCODE_MINUTE_SECOND; case REC_INT_HOUR_SECOND: return SQLINTCODE_HOUR_SECOND; case REC_INT_DAY_SECOND: return SQLINTCODE_DAY_SECOND; default: break; } return 0; } static void setRowNumberInCli(ComDiagsArea * diagsArea, Lng32 rowNum, Lng32 rowsetSize) { if ((rowsetSize > 0) && diagsArea) { diagsArea->setAllRowNumber(rowNum); } } ex_expr::exp_return_type InputOutputExpr::describeOutput(void * output_desc_, UInt32 flags) { NABoolean isOdbc = isODBC(flags); NABoolean isDbtr = isDBTR(flags); NABoolean isIFIO = isInternalFormatIO(flags); ex_clause *clause = getClauses(); Descriptor * output_desc = (Descriptor *)output_desc_; short entry = 0; #ifdef _DEBUG short tempAtp = -1; // For testing #endif Lng32 prevEntryStartOffset = 0; Lng32 currAlignedOffset = 0; Lng32 firstEntryStartAlignment = 0; Lng32 length = -1; NABoolean firstEntryProcessed = FALSE; while (clause) { if (clause->getType() == ex_clause::INOUT_TYPE) { Attributes * operand = clause->getOperand(0); if(isCall() && output_desc->isDescTypeWide()) entry = ((ex_inout_clause *)clause)->getParamIdx(); else entry++; output_desc->setDescItem(entry, SQLDESC_TYPE_FS, operand->getDatatype(), 0); length = operand->getLength(); if ((operand->getDatatype() >= REC_MIN_INTERVAL) && (operand->getDatatype() <= REC_MAX_INTERVAL)) { // // According to ANSI, interval info is stored in the following // descriptor items: // // DATETIME_INTERVAL_CODE = qualifier code // PRECISION = fractional precision // DATETIME_INTERVAL_PRECISION = leading precision // output_desc->setDescItem(entry, SQLDESC_DATETIME_CODE, getIntervalCode(operand->getDatatype()), 0); output_desc->setDescItem(entry, SQLDESC_PRECISION, operand->getScale(), 0); output_desc->setDescItem(entry, SQLDESC_SCALE, 0, 0); output_desc->setDescItem(entry, SQLDESC_INT_LEAD_PREC, operand->getPrecision(), 0); if (NOT isIFIO) { #pragma warning (disable : 4244) //warning elimination Lng32 displaySize = ExpInterval::getDisplaySize(operand->getDatatype(), #pragma nowarn(1506) // warning elimination operand->getPrecision(), #pragma warn(1506) // warning elimination operand->getScale()); #pragma warning (default : 4244) //warning elimination length = displaySize; } } else if (operand->getDatatype() == REC_DATETIME) { // // According to ANSI, datetime info is stored in the following // descriptor items: // // DATETIME_INTERVAL_CODE = qualifier code // PRECISION = fractional precision // output_desc->setDescItem(entry, SQLDESC_DATETIME_CODE, operand->getPrecision(), 0); output_desc->setDescItem(entry, SQLDESC_PRECISION, operand->getScale(), 0); output_desc->setDescItem(entry, SQLDESC_SCALE, 0, 0); output_desc->setDescItem(entry, SQLDESC_INT_LEAD_PREC, 0, 0); if (((NOT isOdbc) || (output_desc->rowwiseRowsetV2() == FALSE)) && (NOT isIFIO)) { Lng32 displaySize = ExpDatetime::getDisplaySize(operand->getPrecision(), operand->getScale()); length = displaySize; } } else { output_desc->setDescItem(entry, SQLDESC_DATETIME_CODE, 0, 0); output_desc->setDescItem(entry, SQLDESC_PRECISION, operand->getPrecision(), 0); output_desc->setDescItem(entry, SQLDESC_SCALE, operand->getScale(), 0); output_desc->setDescItem(entry, SQLDESC_INT_LEAD_PREC, 0, 0); } // Use SQLDESC_CHAR_SET_NAM (one-part name) for charset if ( DFS2REC::isAnyCharacter(operand->getDatatype()) || (operand->getDatatype() == REC_BLOB) || (operand->getDatatype() == REC_CLOB )) { output_desc->setDescItem(entry, SQLDESC_CHAR_SET_NAM, 0, (char*)CharInfo::getCharSetName(operand->getCharSet())); // reset the length for Unicode if ( operand->getCharSet() == CharInfo::UNICODE || CharInfo::is_NCHAR_MP(operand->getCharSet()) ) { length = operand->getLength()/SQL_DBCHAR_SIZE; } if (operand->isCaseinsensitive()) output_desc->setDescItem(entry, SQLDESC_CASEINSENSITIVE, 1, 0); if (operand->getCollation() != CharInfo::DefaultCollation) output_desc->setDescItem(entry, SQLDESC_COLLATION, operand->getCollation(), 0); } output_desc->setDescItem(entry, SQLDESC_NULLABLE, operand->getNullFlag(), 0); output_desc->setDescItem(entry, SQLDESC_NAME, 0, ((ex_inout_clause *)clause)->getName()); if (((ex_inout_clause *)clause)->getHeading() != 0) output_desc->setDescItem(entry, SQLDESC_HEADING, 0, ((ex_inout_clause *)clause)->getHeading()); if (((ex_inout_clause *)clause)->getTableName() != 0) output_desc->setDescItem(entry, SQLDESC_TABLE_NAME, 0, ((ex_inout_clause *)clause)->getTableName()); if (((ex_inout_clause *)clause)->getSchemaName() != 0) output_desc->setDescItem(entry, SQLDESC_SCHEMA_NAME, 0, ((ex_inout_clause *)clause)->getSchemaName()); if (((ex_inout_clause *)clause)->getCatalogName() != 0) output_desc->setDescItem(entry, SQLDESC_CATALOG_NAME, 0, ((ex_inout_clause *)clause)->getCatalogName()); output_desc->setDescItem(entry, SQLDESC_VAR_PTR, 0, 0); output_desc->setDescItem(entry, SQLDESC_IND_PTR, 0, 0); output_desc->setDescItem(entry, SQLDESC_VAR_DATA, 0, 0); output_desc->setDescItem(entry, SQLDESC_IND_DATA, 0, 0); if (operand->getRowsetSize() > 0) { output_desc->setDescItem(0, SQLDESC_ROWSET_SIZE, operand->getRowsetSize(), 0); output_desc->setDescItem(entry, SQLDESC_ROWSET_VAR_LAYOUT_SIZE, operand->getLength(), 0); output_desc->setDescItem(entry, SQLDESC_ROWSET_IND_LAYOUT_SIZE, operand->getNullIndicatorLength(), 0); } else { output_desc->setDescItem(0, SQLDESC_ROWSET_SIZE, 0, 0); output_desc->setDescItem(entry, SQLDESC_ROWSET_VAR_LAYOUT_SIZE, 0, 0); output_desc->setDescItem(entry, SQLDESC_ROWSET_IND_LAYOUT_SIZE, 0, 0); } short paramMode = ((ex_inout_clause *)clause)->getParamMode(); short paramIdx = ((ex_inout_clause *)clause)->getParamIdx(); short ordPos = ((ex_inout_clause *)clause)->getOrdPos(); BriefAssertion((paramMode == PARAMETER_MODE_INOUT) || (paramMode == PARAMETER_MODE_OUT)|| (paramMode == PARAMETER_MODE_UNDEFINED), "invalid param mode"); BriefAssertion(paramIdx >= 0, "invalid param index"); BriefAssertion(ordPos >= 0, "invalid param ordinal position"); // handle old plan if(paramMode == PARAMETER_MODE_UNDEFINED){ paramMode = PARAMETER_MODE_OUT; } output_desc->setDescItem(entry, SQLDESC_PARAMETER_MODE, paramMode, 0); output_desc->setDescItem(entry, SQLDESC_PARAMETER_INDEX, paramIdx, 0); output_desc->setDescItem(entry, SQLDESC_ORDINAL_POSITION, ordPos, 0); if(isCall()){ short paramMode = ((ex_inout_clause *)clause)->getParamMode(); short paramIdx = ((ex_inout_clause *)clause)->getParamIdx(); short ordPos = ((ex_inout_clause *)clause)->getOrdPos(); output_desc->setDescItem(entry, SQLDESC_PARAMETER_MODE, paramMode, 0); output_desc->setDescItem(entry, SQLDESC_PARAMETER_INDEX, paramIdx, 0); output_desc->setDescItem(entry, SQLDESC_ORDINAL_POSITION, ordPos, 0); } else{ output_desc->setDescItem(entry, SQLDESC_PARAMETER_MODE, PARAMETER_MODE_OUT, 0); output_desc->setDescItem(entry, SQLDESC_PARAMETER_INDEX, entry, 0); output_desc->setDescItem(entry, SQLDESC_ORDINAL_POSITION, 0, 0); } output_desc->setDescItem(entry, SQLDESC_LENGTH, length, 0); // Set up length of null indicator and varcharlen indicator values // in the descriptor. // output_desc->setDescItem(entry, SQLDESC_IND_LENGTH, operand->getNullIndicatorLength(), 0); output_desc->setDescItem(entry, SQLDESC_VC_IND_LENGTH, operand->getVCIndicatorLength(), 0); // Get offsets to data, null indicator and varchar len indicator // in the actual row and set them in the descriptor. // // This is being done for sqlark_exploded_format only. // The offsets that are set in descriptor assume that the returned // row to user is a single contiguous aligned row even though internally // that row could be represented by multiple fragments, each with // different atp index. // // These values are used by caller(mxcs) to set up input and output // data pointers so that they are aligned and set up the same way // as the actual row in cli. // // These values cannot be set by external callers. // Lng32 dataOffset = -1; Lng32 nullIndOffset = -1; Lng32 currEntryStartOffset = -1; Lng32 currEntryStartAlignment = -1; Lng32 outputDatalen = -1; if (output_desc->getDescItem(entry, SQLDESC_OCTET_LENGTH, &outputDatalen, NULL, 0, NULL, 0, NULL, 0) == ERROR) return ex_expr::EXPR_ERROR; Lng32 alignment = 1; if (operand->getNullIndOffset() >= 0) { if (operand->getTupleFormat() == ExpTupleDesc::SQLARK_EXPLODED_FORMAT) alignment = operand->getNullIndicatorLength(); currAlignedOffset = ADJUST(currAlignedOffset, alignment); nullIndOffset = currAlignedOffset; currEntryStartOffset = currAlignedOffset; currEntryStartAlignment = alignment; currAlignedOffset += operand->getNullIndicatorLength(); } if (operand->getVCLenIndOffset() >= 0) { if (operand->getTupleFormat() == ExpTupleDesc::SQLARK_EXPLODED_FORMAT) alignment = operand->getVCIndicatorLength(); currAlignedOffset = ADJUST(currAlignedOffset, alignment); dataOffset = currAlignedOffset; if (currEntryStartOffset == -1) { currEntryStartOffset = currAlignedOffset; currEntryStartAlignment = alignment; } currAlignedOffset += operand->getVCIndicatorLength() + outputDatalen; } else { if (operand->getTupleFormat() == ExpTupleDesc::SQLARK_EXPLODED_FORMAT) alignment = operand->getDataAlignmentSize(); currAlignedOffset = ADJUST(currAlignedOffset, alignment); dataOffset = currAlignedOffset; if (currEntryStartOffset == -1) { currEntryStartOffset = currAlignedOffset; currEntryStartAlignment = alignment; } currAlignedOffset += outputDatalen; } if (NOT firstEntryProcessed) { firstEntryProcessed = TRUE; firstEntryStartAlignment = currEntryStartAlignment; } output_desc->setDescItemInternal(entry, SQLDESC_DATA_OFFSET, dataOffset, 0); output_desc->setDescItemInternal(entry, SQLDESC_NULL_IND_OFFSET, nullIndOffset, 0); output_desc->setDescItemInternal(entry-1, SQLDESC_ALIGNED_LENGTH, currEntryStartOffset - prevEntryStartOffset, 0); prevEntryStartOffset = currEntryStartOffset; #ifdef _DEBUG // Start testing logic ***** // // Set up the descriptor rowwise offsets to enable bulk move when possible. // The offset is only valid for one tuple. Set the values to -1 for all // the other tuples. // if (tempAtp == -1) tempAtp = operand->getAtpIndex(); if (tempAtp == operand->getAtpIndex()){ output_desc->setDescItem(entry, SQLDESC_ROWWISE_VAR_OFFSET, operand->getOffset(), 0); output_desc->setDescItem(entry, SQLDESC_ROWWISE_IND_OFFSET, operand->getNullIndOffset(), 0); } else{ output_desc->setDescItem(entry, SQLDESC_ROWWISE_VAR_OFFSET, -1, 0); output_desc->setDescItem(entry, SQLDESC_ROWWISE_IND_OFFSET, -1, 0); } // End testing logic ***** #endif } clause = clause->getNextClause(); } if (firstEntryProcessed) { currAlignedOffset = ADJUST(currAlignedOffset, firstEntryStartAlignment); output_desc->setDescItemInternal(entry, SQLDESC_ALIGNED_LENGTH, currAlignedOffset - prevEntryStartOffset, 0); } if(!(isCall() && output_desc->isDescTypeWide()) || (entry > output_desc->getUsedEntryCount())) output_desc->setUsedEntryCount(entry); return ex_expr::EXPR_OK; } // // This method will evaluate the characteristics of the operand and descriptor // to determine if a value can be bulk moved given rowwise rowset version 1 // bulk move rules. The method also has the side affect of setting the varPtr // parameter to the proper location in the descriptor's data buffer for this // items bulk move start address. // Descriptor::BulkMoveStatus Descriptor::checkBulkMoveStatusV1( short entry, Attributes * op, Long &varPtr, NABoolean isInputDesc, NABoolean isRWRS, NABoolean isInternalFormatIO) { #ifdef _DEBUG // if (! getenv("DOSLOWBULKMOVE")) // return BULK_MOVE_OFF; if (getenv("BULKMOVEOFF")) return BULK_MOVE_OFF;//LCOV_EXCL_LINE else if (getenv("BULKMOVEDISALLOWED")) return BULK_MOVE_DISALLOWED;//LCOV_EXCL_LINE #endif desc_struct &descItem = desc[entry - 1]; // Zero base // if any of the first set of conditions is true, bulk move cannot // be done for any value of this row. Turn off bulk move completely. if ((rowsetSize > 0 ) || // ((NOT rowwiseRowset()) && (descItem.var_ptr == 0) || (op->getVCIndicatorLength() > 0) || (DFS2REC::isAnyVarChar(op->getDatatype())) || (((DFS2REC::isDateTime(op->getDatatype())) || (DFS2REC::isInterval(op->getDatatype()))) && (NOT isInternalFormatIO)) || (op->isSpecialField()) || (!op->isBulkMoveable()) ) return BULK_MOVE_OFF; // if any of these conditions are true, the bulk move for this // value cannot be done. Turn off bulk move for this value. // // If descriptor item is binary with precision > 0, which means that // it was declared as a NUMERIC datatype, then it needs to // be validated at input and output time. Cannot do bulk move in // that case. // At input, always validate it. // At output, only validate if descItem's precision is greater than // zero, and less than operand's precision or op's precision is zero. // // Bulk move for char datatype is only done if both source and // target are single byte charsets. else if ((descItem.datatype != op->getDatatype()) || ((DFS2REC::isAnyCharacter(op->getDatatype())) && ((descItem.charset != op->getCharSet()) || (NOT CharInfo::isSingleByteCharSet((CharInfo::CharSet)descItem.charset)))) || ((NOT DFS2REC::isAnyCharacter(op->getDatatype())) && (descItem.scale != op->getScale())) || (descItem.length != op->getLength()) || ((descItem.datatype >= REC_MIN_BINARY) && (descItem.datatype <= REC_MAX_BINARY) && (((isInputDesc) && (descItem.precision > 0)) || ((NOT isInputDesc) && (descItem.precision > 0) && ((op->getPrecision() == 0) || (op->getPrecision() > descItem.precision))))) || (op->getNullFlag()) || (descItem.nullable != 0)) return BULK_MOVE_DISALLOWED; // bulk move could be done for this value. else { varPtr = descItem.var_ptr; return BULK_MOVE_OK; } } // end Descriptor::checkBulkMoveStatusV1 // // This method will return the proper location in the // descriptor's data buffer for this entry based on // Long Descriptor::getRowsetVarPtr(short entry) { Long varPtr = 0; desc_struct &descItem = desc[entry - 1]; // Zero base // // Set the varPtr to the appropriate place. // if (descItem.nullable != 0) varPtr = descItem.ind_ptr; else varPtr = descItem.var_ptr; return varPtr; } // end getRowsetVarPtr // // This method will evaluate the characteristics of the operand and descriptor // to determine if a value can be bulk moved given rowwise rowset version 2 // bulk move rules. The method also has the side affect of setting the varPtr // parameter to the proper location in the descriptor's data buffer for this // items bulk move start address. // Descriptor::BulkMoveStatus Descriptor::checkBulkMoveStatusV2( short entry, Attributes * op, Long &varPtr, NABoolean isInputDesc, NABoolean isOdbc, NABoolean isRWRS, NABoolean isInternalFormatIO) { #ifdef _DEBUG // if (! getenv("DOSLOWBULKMOVE")) // return BULK_MOVE_OFF; if (getenv("BULKMOVEOFF")) return BULK_MOVE_OFF; else if (getenv("BULKMOVEDISALLOWED")) return BULK_MOVE_DISALLOWED; #endif desc_struct &descItem = desc[entry - 1]; // Zero base // if any of the first set of conditions is true, bulk move cannot // be done for any value of this row. Turn off bulk move completely. if ((NOT isRWRS) && ((rowsetSize > 0 ) || (descItem.var_ptr == 0) || (op->isSpecialField())) ) return BULK_MOVE_OFF; // If any of these conditions are true, bulk move for this // value cannot be done. Turn off bulk move for this value. // else if ( // Check to make sure the descriptor and operand have the same data type. (descItem.datatype != op->getDatatype()) // Check to make sure the descriptor and operand character sets are the same. || ((DFS2REC::isAnyCharacter(op->getDatatype())) && (descItem.charset != op->getCharSet())) // Check to make sure the descriptor and operand scale is the same. || ((NOT DFS2REC::isAnyCharacter(op->getDatatype())) && (NOT DFS2REC::isDateTime(op->getDatatype())) && (NOT DFS2REC::isInterval(op->getDatatype())) && (descItem.scale != op->getScale())) // Check special case where descriptor is data/time. In that case the scale is stored in the precision. // Check to make sure the descriptor and operand scale is the same. || ((DFS2REC::isDateTime(op->getDatatype()) || DFS2REC::isInterval(op->getDatatype())) && (descItem.precision != op->getScale())) // Check to make sure the descriptor and operand lengths are the same. || (descItem.length != op->getLength()) // Check if descriptor item is binary with precision > 0, which means that // it was declared as a NUMERIC datatype, then it needs to be validated // at input and output time. Cannot do bulk move in that case. At input, // always validate it. At output, only validate if descItem's precision // is greater than zero, and less than operand's precision or op's // precision is zero. || ((descItem.datatype >= REC_MIN_BINARY) && (descItem.datatype <= REC_MAX_BINARY) && (((isInputDesc) && (NOT isRWRS) && (descItem.precision > 0)) || ((NOT isInputDesc) && (descItem.precision > 0) && ((op->getPrecision() == 0) || (op->getPrecision() > descItem.precision))) ) ) // Check to make sure the descriptor and operand both have null flags. || (op->getNullFlag() && !descItem.ind_ptr) // Check to make sure the descriptor and operand both do not have null flags. || (!op->getNullFlag() && descItem.ind_ptr) // Check to make sure the descriptor and operand both not nullable if this is for input values. // || // (isInputDesc && (op->getNullFlag() || descItem.nullable != 0)) // Check to make sure the operand data type is not a binary precision integer. || (op->getDatatype() == REC_BPINT_UNSIGNED) // Check to make sure the operand is bulk movable. || (op->isBulkMoveable() == FALSE) // Check to make sure if the data type is date/time that the request is coming from odbc. || ((DFS2REC::isDateTime(op->getDatatype())) && (isOdbc == FALSE) && (NOT isInternalFormatIO)) // Check to make sure the the operand is not an interval || ((DFS2REC::isInterval(op->getDatatype())) && (NOT isInternalFormatIO)) // Check to make sure that if the descriptor data type is varcha, then it is an ANSI varchar. || ((DFS2REC::isAnyVarChar(descItem.datatype)) && !(descItem.datatype == REC_BYTE_V_ASCII || descItem.datatype == REC_NCHAR_V_UNICODE)) ) { // MXCS must always propertly set up the descriptor to allow bulk move unless the // data type is interval. An interval datatype is returned in external format. //BriefAssertion( !((isOdbc == TRUE) && ((DFS2REC::isInterval(op->getDatatype()) == FALSE))) // , "Only bulk move allowed for rowwise rowsets type 2 and MXCS"); return BULK_MOVE_DISALLOWED; } // end else if // // If nullable, make sure null indicator offsets match // Int32 opIndOffset = 0; Int32 descIndOffset = 0; if (descItem.nullable != 0) { if (op->getVCIndicatorLength()) opIndOffset = op->getNullIndOffset() - op->getVCLenIndOffset(); else opIndOffset = op->getNullIndOffset() - op->getOffset(); descIndOffset = descItem.ind_ptr - descItem.var_ptr; if (opIndOffset != descIndOffset) { // MXCS must always set up the descriptor such that the indicator and var pointers // correctly aligned. //BriefAssertion((isOdbc == FALSE) , "Indicator/var pointer alignment problem for rowwise rowset type 2 with MXCS"); if ((NOT isRWRS) || (NOT isOdbc)) return BULK_MOVE_DISALLOWED; } } // // Bulk move can be done for this value. // Set the varPtr to the appropriate place. // if (descItem.nullable != 0) varPtr = descItem.ind_ptr; else varPtr = descItem.var_ptr; return BULK_MOVE_OK; } // end checkBulkMoveStatusV2 #pragma warning (disable : 4273) //warning elimination void InputOutputExpr::setupBulkMoveInfo(void * desc_, CollHeap * heap, NABoolean isInputDesc, UInt32 flags) { NABoolean isOdbc = isODBC(flags); NABoolean isDbtr = isDBTR(flags); NABoolean isRwrs = isRWRS(flags); NABoolean isIFIO = (isInternalFormatIO(flags) || (isDbtr && isRwrs)); ex_clause * clause = getClauses(); Descriptor * desc = (Descriptor *)desc_; short entry = 0; Long firstDescStartPtr = -1; Long currDescStartPtr = 0; Long currExeStartOffset = 0; short currFirstEntryNum = 0; Long descVarPtr; Lng32 currLength = 0; Long opOffset = 0; short currAtpIndex = 0; short bmEntry = 0; NABoolean currIsVarchar = FALSE; NABoolean currIsNullable = FALSE; if (desc->bulkMoveDisabled()) return; if (getNumEntries() == 0) { desc->setBulkMoveDisabled(TRUE); return; } // bulk move disabled for wide descriptors. if (isCall() && desc->isDescTypeWide()) { desc->setBulkMoveDisabled(TRUE); return; } desc->setBulkMoveDisabled(FALSE); desc->setDoSlowMove(FALSE); NABoolean bulkMoveInfoAllocated = FALSE; while (clause) { if (clause->getType() == ex_clause::INOUT_TYPE) { entry++; Attributes * op = clause->getOperand(0); if (((ex_inout_clause*)clause)->excludeFromBulkMove()) { // this clause has been excluded from bulk move. // It could be used to get rowwise rowset specific // information, like rowset buffer length, max size, etc. // Skip this clause. // move to the next entry goto next_clause; } // firstDescStartPtr - Represents a pointer to the first entry if (entry == 1) firstDescStartPtr = desc->getRowsetVarPtr(entry); Descriptor::BulkMoveStatus bms = desc->checkBulkMoveStatus(entry, op, descVarPtr, isInputDesc, isOdbc, isRwrs, isIFIO); if (bms == Descriptor::BULK_MOVE_OFF) { // It is not possible to do a bulk move desc->deallocBulkMoveInfo(); desc->setBulkMoveDisabled(TRUE); return; } else if (bms == Descriptor::BULK_MOVE_DISALLOWED) { // Bulk move is not allowed for this case, do slow move using convDoIt. // Mark the descriptor indicating slow move. This indicator // will be used in input and outputValues method to call // convDoIt. desc->setDoSlowMove(entry, TRUE); // Also set this flag in the descriptor. desc->setDoSlowMove(TRUE); // move to the next entry goto next_clause; } else { // bulk move could be done. Reset 'slow move' flag. desc->setDoSlowMove(entry, FALSE); bmEntry++; // if first time, allocate bulkMoveInfo. if (NOT bulkMoveInfoAllocated) { desc->allocBulkMoveInfo(); bulkMoveInfoAllocated = TRUE; } } NABoolean opIsVarchar = FALSE; if (op->getDatatype() >= REC_MIN_V_CHAR_H && op->getDatatype() <= REC_NCHAR_V_UNICODE) opIsVarchar = TRUE; if (op->getNullFlag() != 0) opOffset = (Long)op->getNullIndOffset(); else { if (opIsVarchar) opOffset = (Long)op->getVCLenIndOffset(); else opOffset = (Long)op->getOffset(); } if (op->getAtpIndex() == 0) // constant opOffset += (Long)getConstantsArea(); else if (op->getAtpIndex() == 1) // temp opOffset += (Long)getTempsArea(); if ((isInputDesc) && (isOdbc) && (isRwrs)) { descVarPtr = opOffset; if (firstDescStartPtr < 0) firstDescStartPtr = descVarPtr; } // // The following code builds "blocks" of entries that can be bulk moved. That is, // one or move entries are grouped together in blocks if the entries are adjacent // to each other in both descriptor and operand. // // The variables involved and their purpose are as follows: // // bmEntry - Keeps track of the number of operands that have been added // to the bulk move list // opOffset - Holds the offset value of the current bulk move entry // firstDescStartPtr - Represents a pointer to the first entry. // When data is moved, the offset to the bulk move entry // in the descriptor's data will be calculated as an // offset from this pointer. // currDescStartPtr - Represents a pointer to the current bulk move entry // descriptor var pointer. // currExeStartOffset - Holds the offset to the current bulk move block of entries. // currLength - Holds the length of the current move block of entries. // currfirstEntryNum - Represents the entry number of the first entry in the current // block of entries. // // After all entries have been processed, the logic detects the last bulk move, // and adds it to the list of bulk moves. // if (bmEntry == 1) // first time { currDescStartPtr = descVarPtr; currAtpIndex = op->getAtpIndex(); currExeStartOffset = opOffset; if (op->getNullFlag() != 0) currLength = (op->getOffset() - op->getNullIndOffset()) + op->getLength(); else if (opIsVarchar) currLength = op->getLength() + op->getVCIndicatorLength(); else currLength = op->getLength(); currFirstEntryNum = 1; if (!isInputDesc) { currIsVarchar = opIsVarchar; currIsNullable = op->getNullFlag(); } } else if ((op->getAtpIndex() != currAtpIndex) || (opOffset < currExeStartOffset) || (descVarPtr < currDescStartPtr) || ((descVarPtr - currDescStartPtr) != (opOffset - currExeStartOffset)) || (!isInputDesc && (opIsVarchar || currIsVarchar))) // (descVarPtr - currDescStartPtr) != currLength) { desc->bulkMoveInfo()-> addEntry(currLength, (((desc->rowwiseRowset()) && (NOT desc->rowwiseRowsetDisabled())) ? // this one is an offset (char*)(currDescStartPtr - firstDescStartPtr) : (char*)currDescStartPtr), currAtpIndex, (currAtpIndex <= 1 ? TRUE : FALSE), currExeStartOffset, currFirstEntryNum, (short)(bmEntry-1), currIsVarchar, currIsNullable); currDescStartPtr = descVarPtr; currAtpIndex = op->getAtpIndex(); currExeStartOffset = opOffset; if (op->getNullFlag() != 0) currLength = (op->getOffset() - op->getNullIndOffset()) + op->getLength(); else if (opIsVarchar) currLength = op->getLength() + op->getVCIndicatorLength(); else currLength = op->getLength(); currFirstEntryNum = bmEntry; if (!isInputDesc) { currIsVarchar = opIsVarchar; currIsNullable = op->getNullFlag(); } } else { if (op->getNullFlag() != 0) currLength = opOffset - currExeStartOffset + (op->getOffset() - op->getNullIndOffset()) + op->getLength(); else if (opIsVarchar) currLength = opOffset - currExeStartOffset + op->getLength() + op->getVCIndicatorLength(); else currLength = opOffset - currExeStartOffset + op->getLength(); } } next_clause: clause = clause->getNextClause(); } // loop over clauses if ((desc->bulkMoveInfo()) && (bmEntry > 0)) // found at least one entry which does bulk move. desc->bulkMoveInfo()-> addEntry(currLength, (((desc->rowwiseRowset()) && (NOT desc->rowwiseRowsetDisabled())) ? // this one is an offset (char*)(currDescStartPtr - firstDescStartPtr) : (char*)currDescStartPtr), currAtpIndex, (currAtpIndex <= 1 ? TRUE : FALSE), currExeStartOffset, currFirstEntryNum, bmEntry, currIsVarchar, currIsNullable); desc->setBulkMoveSetup(TRUE); //LCOV_EXCL_START if (getenv("BULKMOVE") && getenv("BULKMOVEINFO") && desc->bulkMoveInfo()) { if (isInputDesc) cout << "InputDesc, Used Entries " << desc->bulkMoveInfo()->usedEntries() << endl; else cout << "OutputDesc, Used Entries " << desc->bulkMoveInfo()->usedEntries() << endl; for (UInt32 i = 0; i < desc->bulkMoveInfo()->usedEntries(); i++) { cout << "Entry #" << i+1 << endl; cout << "desc ptr = " << desc->bulkMoveInfo()->getDescDataPtr(i) << ", exe offset = " << desc->bulkMoveInfo()->getExeOffset(i) << ", length = " << desc->bulkMoveInfo()->getLength(i) << ", atpindex = " << desc->bulkMoveInfo()->getExeAtpIndex(i) << endl; cout << "firstEntryNum = " << desc->bulkMoveInfo()->getFirstEntryNum(i) << ", lastEntryNum = " << desc->bulkMoveInfo()->getLastEntryNum(i) << endl; cout << endl; } } //LCOV_EXCL_STOP } #pragma warning (default : 4273) //warning elimination #pragma warning (disable : 4273) //warning elimination ex_expr::exp_return_type InputOutputExpr::doBulkMove(atp_struct * atp, void * desc_, char * tgtRowPtr, NABoolean isInputDesc) { Descriptor * desc = (Descriptor *)desc_; BulkMoveInfo * bmi = desc->bulkMoveInfo(); if (!bmi) return ex_expr::EXPR_OK; for (Int32 i = 0; i < (Lng32)bmi->usedEntries(); i++) { char * dataPtr; if (NOT bmi->isExeDataPtr(i)) { // compute ptr from offset if ((isInputDesc) && (tgtRowPtr)) dataPtr = tgtRowPtr + bmi->getExeOffset(i); else dataPtr = atp->getTupp(bmi->getExeAtpIndex(i)).getDataPointer() + bmi->getExeOffset(i); } else // it is already a pointer. Use it. dataPtr = bmi->getExeDataPtr(i); if (isInputDesc) { char * srcPtr = NULL; if (desc->rowwiseRowset()) srcPtr = (char*)(desc->getCurrRowPtrInRowwiseRowset() + bmi->getDescDataPtr(i)); else srcPtr = bmi->getDescDataPtr(i); str_cpy_all(dataPtr, srcPtr, bmi->getLength(i)); } else { char *destPtr = NULL; if ((desc->rowwiseRowset()) && (NOT desc->rowwiseRowsetDisabled())) destPtr = (char*)(desc->getCurrRowPtrInRowwiseRowset() + bmi->getDescDataPtr(i)); else destPtr = bmi->getDescDataPtr(i); str_cpy_all(destPtr, dataPtr, (Lng32)bmi->getLength(i)); } } return ex_expr::EXPR_OK; } #pragma warning (default : 4273) //warning elimination #pragma warning (disable : 4273) //warning elimination ex_expr::exp_return_type InputOutputExpr::outputValues(atp_struct *atp, void * output_desc_, CollHeap *heap, UInt32 flags) { NABoolean isOdbc = isODBC(flags); NABoolean isIFIO = isInternalFormatIO(flags); ex_clause * clause = getClauses(); Descriptor * output_desc = (Descriptor *)output_desc_; NABoolean useParamIdx = isCall() && output_desc->isDescTypeWide(); Attributes * operand = 0; ComDiagsArea * diagsArea = atp->getDiagsArea(); char * source = 0; char * sourceVCLenInd = 0; char * sourceNullInd = 0; Lng32 sourceLen = 0; // Avoid possible uninitialized variable when saving in savedSourceLen. Lng32 sourceNumProcessed = -1; Lng32 sourceCompiledWithRowsets = FALSE; // True if there is a SELECT .. INTO <rowset> only Lng32 tempSource; char * target; char * realTarget; // Added to show real start position of target, // varchars adjust this position short targetType; Lng32 targetLen; Lng32 targetRowsetSize; // Greater than zero if there is an output rowset in the descriptor, // this can happen in a SELECT .. INTO <rowset> and FETCH INTO <rowset> Lng32 targetScale; Lng32 targetPrecision; char * targetVarPtr = NULL; char * targetIndPtr = NULL; #if defined( NA_SHADOWCALLS ) char * bimodalIndPtr = NULL; #endif char * targetVCLen = NULL; short targetVCLenSize = 0; // Size of an entry of the indicator array Lng32 indSize; Long tempTarget = 0; char * dataPtr = 0; short entry = 0; NABoolean byPassCheck = output_desc->isDescTypeWide(); if (!byPassCheck && (getNumEntries() != output_desc->getUsedEntryCount()) && (!output_desc->thereIsACompoundStatement())) { ExRaiseSqlError(heap, &diagsArea, CLI_STMT_DESC_COUNT_MISMATCH); if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); return ex_expr::EXPR_ERROR; } // If bulk move has not been disabled before, then check to see if bulk // move could be done. This is done by comparing attributes of the // executor items and the descriptor entries. See method // Descriptor::checkBulkMoveStatus() for details on when bulk move will // be disabled. // If bulk move is possible then set up bulk move info, if not already // done. if (NOT output_desc->bulkMoveDisabled()) { if (NOT output_desc->bulkMoveSetup()) { if (output_desc->rowwiseRowset()) output_desc->setRowwiseRowsetDisabled(FALSE); #ifdef _DEBUG if (getenv("DISABLE_ROWWISE_ROWSET")) output_desc->setRowwiseRowsetDisabled(TRUE); #endif setupBulkMoveInfo(output_desc, heap, FALSE /* output desc*/, flags); if ( // rowwise rowsets V1 are only supported if bulk move // is being done for all items. (((output_desc->rowwiseRowset()) && ((output_desc->bulkMoveDisabled()) || (output_desc->doSlowMove())) ) && (output_desc->rowwiseRowsetV1() == TRUE) ) || ( (output_desc->rowwiseRowset()) && ((output_desc->bulkMoveDisabled())) && (output_desc->rowwiseRowsetV2() == TRUE) ) ) { output_desc->setRowwiseRowsetDisabled(TRUE); if (NOT output_desc->bulkMoveDisabled()) // do slow move { // now set up bulk move as a non-rowwise rowset move setupBulkMoveInfo(output_desc, heap, FALSE /* output desc*/, flags); } else { output_desc->deallocBulkMoveInfo(); output_desc->setBulkMoveDisabled(TRUE); } } // rowwise rowset } if (NOT output_desc->bulkMoveDisabled()) { // bulk move is enabled and setup has been done. // Do bulk move now. doBulkMove(atp, output_desc, NULL, FALSE /* output desc */); if (NOT output_desc->doSlowMove()) return ex_expr::EXPR_OK; } } // Note that every output operands must participate in rowsets, or none of // them. That is, you cannot mix rowset host variables and simple host // variables for output purposes (INTO clause). Int32 totalNumOfRowsets = 0; // Number of warnings found so far. This variable keeps track of the total number of // warnings reported so far and is used to set up the indicator if // we find a string overflow warning reported by the latest condDoit() call // for the output. Lng32 numOfWarningsFoundSoFar = 0; while (clause) { if (clause->getType() == ex_clause::INOUT_TYPE) { entry++; // TEMP TEMP TEMP if(useParamIdx){ entry = ((ex_inout_clause *)clause)->getParamIdx(); } // End of TEMP if ((NOT output_desc->bulkMoveDisabled()) && (NOT output_desc->doSlowMove(entry))) goto next_clause; if(useParamIdx){ entry = ((ex_inout_clause *)clause)->getParamIdx(); } operand = clause->getOperand(0); sourceCompiledWithRowsets = (operand->getRowsetSize() > 0); if (sourceCompiledWithRowsets) { totalNumOfRowsets++; } switch (operand->getAtpIndex()) { case 0: // constant source = getConstantsArea() + operand->getOffset(); sourceNullInd = getConstantsArea() + operand->getNullIndOffset(); sourceVCLenInd = getConstantsArea() + operand->getVCLenIndOffset(); break; case 1: // temp source = getTempsArea() + operand->getOffset(); sourceNullInd = getTempsArea() + operand->getNullIndOffset(); sourceVCLenInd = getTempsArea() + operand->getVCLenIndOffset(); if (operand->getNullFlag() && ExpTupleDesc::isNullValue( sourceNullInd, operand->getNullBitIndex(), operand->getTupleFormat() )) { sourceNullInd = 0; // it is a null value } break; default: dataPtr = (atp->getTupp(operand->getAtpIndex())).getDataPointer(); #pragma nowarn(270) // warning elimination if (operand->getOffset() < 0) { #pragma warn(270) // warning elimination // Offset is negative. This indicates that this offset // is the negative of field number in a base table // and this field follows one or more varchar fields. // True for SQL/MP tables only. Needs special logic // to compute the actual address of this field. computeDataPtr(dataPtr, - ((Lng32) operand->getOffset()), atp->getCriDesc()->getTupleDescriptor(operand->getAtpIndex()), &(source), &(sourceNullInd), &(sourceVCLenInd)); } else { if (dataPtr) { source = dataPtr + operand->getOffset(); if (operand->getNullFlag()) { sourceNullInd = dataPtr + operand->getNullIndOffset(); if (ExpTupleDesc::isNullValue( sourceNullInd, operand->getNullBitIndex(), operand->getTupleFormat() )) { sourceNullInd = 0; // it is a null value } } if (operand->getVCIndicatorLength()) sourceVCLenInd = dataPtr + operand->getVCLenIndOffset(); } else { sourceNullInd = 0; sourceVCLenInd = 0; } } } // switch atpIndex // For rowsets, here we extract the number of elements in it. This // only happens for the SELECT .. INTO clause if (source && sourceCompiledWithRowsets) { if (::convDoIt(source, sizeof(Lng32), REC_BIN32_SIGNED, 0, 0, (char *)&tempSource, sizeof(Lng32), REC_BIN32_SIGNED, 0, 0, 0, 0, heap, &diagsArea) != ex_expr::EXPR_OK) { if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); return ex_expr::EXPR_ERROR; } // Increment the location for the next element. source += sizeof(Lng32); // The offsets for rowset SQLVarChar attributes are set as follows. // offset_ points to the start of the rowset info followed by four bytes // of the rowset size. nullIndOffset_ (if nullIndicatorLength_ is not set // to 0) points to (offset_+4). vcLenIndOffset_ (if vcIndicatorLength_ // is not set to 0) points to (offset_+nullIndicatorLength_). The first // data value stars at (offset_+nullIndicatorLength_+vcIndicatorLength_) // or (offset_+vcIndicatorLength_) depending on whether nullIndicatorLength_ // is valid. // Note vcIndicatorLength_ is set to sizeof(short) for rowset SQLVarChars. sourceNullInd = source; if (operand->getNullFlag()) { source += operand->getNullIndicatorLength(); } if (operand->getVCIndicatorLength() > 0) { source += operand->getVCIndicatorLength(); } //Now source points to the start of the first data value of the rowset. if (tempSource < 0) { tempSource = 1; } // We have determined the number of elements in the rowset sourceNumProcessed = tempSource; } else { // No rowset currently being processed, i.e. only one value to process sourceNumProcessed = 1; } // Get the size of an entry of the indicator array output_desc->getDescItem(entry, SQLDESC_ROWSET_IND_LAYOUT_SIZE, &indSize, 0, 0, 0, 0); output_desc->getDescItem(entry, SQLDESC_TYPE_FS, &tempTarget, 0, 0, 0, 0); targetType = (short)tempTarget; output_desc->getDescItem(entry, SQLDESC_ROWSET_SIZE, &targetRowsetSize, 0, 0, 0, 0); targetLen = 0; output_desc->getDescItem(entry, SQLDESC_OCTET_LENGTH, &targetLen, 0, 0, 0, 0); if ((targetType >= REC_MIN_INTERVAL) && (targetType <= REC_MAX_INTERVAL)) { output_desc->getDescItem(entry, SQLDESC_INT_LEAD_PREC, &targetPrecision, 0, 0, 0, 0); // SQLDESC_PRECISION gets the fractional precision. output_desc->getDescItem(entry, SQLDESC_PRECISION, &targetScale, 0, 0, 0, 0); } else if (targetType == REC_DATETIME) { output_desc->getDescItem(entry, SQLDESC_DATETIME_CODE, &targetPrecision, 0, 0, 0, 0); output_desc->getDescItem(entry, SQLDESC_PRECISION, &targetScale, 0, 0, 0, 0); } else { output_desc->getDescItem(entry, SQLDESC_PRECISION, &targetPrecision, 0, 0, 0, 0); output_desc->getDescItem(entry, SQLDESC_SCALE, &targetScale, 0, 0, 0, 0); } CharInfo::CharSet targetCharSet = CharInfo::UnknownCharSet; NABoolean treatAnsivByteAsWideChar = FALSE; if ((targetType >= REC_MIN_CHARACTER ) && (targetType <= REC_MAX_CHARACTER)) { // charset can be retrieved as a long INTERNALLY // using programatic interface by calling getDescItem(), // and can only be retrieved as a character string EXTERNALLY // using "get descriptor" syntax. Lng32 temp_char_set; output_desc->getDescItem(entry, SQLDESC_CHAR_SET, &temp_char_set, 0, 0, 0, 0); targetCharSet = (CharInfo::CharSet)temp_char_set; if ( targetType == REC_BYTE_V_ANSI && CharInfo::is_NCHAR_MP(targetCharSet)) treatAnsivByteAsWideChar = TRUE; // store charset in scale for convDoIt call targetScale = targetCharSet; } // Now convert each element for (Lng32 RowNum = 0; RowNum < sourceNumProcessed; RowNum++) { // save current source and target datatype attributes since // they may get changed later in this method. // Restore them for the next iteration of this for loop. // Do this only for rowsets, for non-rowsets this loop is executed // only once. Lng32 savedSourceLen; short savedTargetType = 0; Lng32 savedTargetPrecision = 0; Lng32 savedTargetScale = 0; Lng32 savedTargetLen = 0; if (targetRowsetSize > 0) { savedSourceLen = sourceLen; savedTargetType = targetType; savedTargetPrecision = targetPrecision; savedTargetScale = targetScale; savedTargetLen = targetLen; } char * rowsetSourcePosition = source; if (sourceCompiledWithRowsets) output_desc->setDescItem(0, SQLDESC_ROWSET_HANDLE, RowNum, 0); output_desc->getDescItem(entry, SQLDESC_IND_PTR, &tempTarget, 0, 0, 0, 0); // Need to decide if we are in rowwise rowsets and adjust the temptarget appropriately if (tempTarget && output_desc->rowwiseRowset() && (NOT output_desc->rowwiseRowsetDisabled())) tempTarget = tempTarget + output_desc->getCurrRowOffsetInRowwiseRowset(); #if defined( NA_SHADOWCALLS ) bimodalIndPtr = (char *)tempTarget; targetIndPtr = SqlCliSp_GetBufPtr(bimodalIndPtr, FALSE); #else targetIndPtr = (char *)tempTarget; #endif if ((operand->getVCIndicatorLength()) && (sourceVCLenInd)) { if (operand->getVCIndicatorLength() == sizeof(short)) sourceLen = *(short*)sourceVCLenInd; else sourceLen = *(Lng32 *)sourceVCLenInd; } else sourceLen = operand->getLength(); output_desc->getDescItem(entry, SQLDESC_VAR_PTR, &tempTarget, 0, 0, 0, 0); // Need to decide if we are in rowwise rowsets and adjust the temptarget appropriately if (tempTarget && output_desc->rowwiseRowset() && (NOT output_desc->rowwiseRowsetDisabled())) tempTarget = tempTarget + output_desc->getCurrRowOffsetInRowwiseRowset(); NABoolean nullMoved = FALSE; if (!tempTarget) { if (operand->getNullFlag() && ((! sourceNullInd) || ExpTupleDesc::isNullValue( sourceNullInd, operand->getNullBitIndex(), operand->getTupleFormat() ))) { output_desc->setDescItem(entry, SQLDESC_IND_DATA, -1, NULL); nullMoved = TRUE; } else output_desc->setDescItem(entry, SQLDESC_IND_DATA, 0, NULL); } else { if (targetIndPtr) { // null indicator specified in target target = targetIndPtr; realTarget = target; if (operand->getNullFlag() && ((! sourceNullInd) || ExpTupleDesc::isNullValue( sourceNullInd, operand->getNullBitIndex(), operand->getTupleFormat() ))) { // sourceNullInd is missing. This indicates a null value. // Move null to the indicator. if (targetRowsetSize > 0) { for (Int32 i = 0; i < indSize; i++) { targetIndPtr[i] = '\377'; } } else { targetIndPtr[0] = '\377'; targetIndPtr[1] = '\377'; } nullMoved = TRUE; } else { // move 'no null' to target indicator if (targetRowsetSize > 0) { for (Int32 i = 0; i < indSize; i++) { targetIndPtr[i] = 0; } } else { targetIndPtr[0] = 0; targetIndPtr[1] = 0; } } } else { // no indicator specified. // Return error if a null value. if (operand->getNullFlag() && (!sourceNullInd)) { ExRaiseSqlError(heap, &diagsArea, EXE_MISSING_INDICATOR_VARIABLE); if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); return ex_expr::EXPR_ERROR; } } } if (! nullMoved) { targetVarPtr = (char *)tempTarget; if (targetVarPtr) { // bound column. Move value to user area. target = targetVarPtr; realTarget = target; } else { // unbound column, move into temp buffer to add VC length target = new (heap) char[targetLen + 10]; // 10 extra bytes should do realTarget = target; } Lng32 tempDataConversionErrorFlag = ex_conv_clause::CONV_RESULT_OK; if ((DFS2REC::isSQLVarChar(targetType)) || (DFS2REC::isLOB(targetType))) { targetVCLen = target; if (targetVarPtr) { #ifdef _DEBUG assert(SQL_VARCHAR_HDR_SIZE == sizeof(short)); #endif // user host vars have VC len of 4 if the targetLen is // more than 32768. Else, VC len is 2. if (targetLen & 0xFFFF8000) targetVCLenSize = sizeof(Lng32); else targetVCLenSize = sizeof(short); } else targetVCLenSize = sizeof(Lng32); // desc entries have VC len 4 target = &target[targetVCLenSize]; } else targetVCLenSize = 0; ex_expr::exp_return_type rc = ex_expr::EXPR_OK; NABoolean implicitConversion = FALSE; short sourceType = operand->getDatatype(); CharInfo::CharSet sourceCharSet = operand->getCharSet(); // if the source and target are not compatible, then do implicit // conversion if skipTypeCheck is set. // Furthermore, if restrictedSkipTypeCheck is set, then only // convert for the conversions that are externally supported. // See usage of default IMPLICIT_HOSTVAR_CONVERSION in generator // (GenExpGenerator.cpp) for restricted conversions. if (NOT areCompatible(sourceType, targetType)) { if ((NOT skipTypeCheck()) || ((restrictedSkipTypeCheck()) && (NOT implicitConversionSupported(sourceType,targetType)))) { ExRaiseSqlError(heap, &diagsArea,EXE_CONVERT_NOT_SUPPORTED); if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); return ex_expr::EXPR_ERROR; } implicitConversion = TRUE; } else { if ( DFS2REC::isAnyCharacter(sourceType) && NOT CharInfo::isAssignmentCompatible(targetCharSet, sourceCharSet) ) { ExRaiseSqlError(heap, &diagsArea, CLI_ASSIGN_INCOMPATIBLE_CHARSET); if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); *diagsArea << DgString0(CharInfo::getCharSetName((CharInfo::CharSet)targetCharSet)) << DgString1(CharInfo::getCharSetName((CharInfo::CharSet)sourceCharSet)); return ex_expr::EXPR_ERROR; } } // if the target is REC_DECIMAL_LS and the source is NOT // REC_DECIMAL_LSE, convert the source to REC_DECIMAL_LSE // first. This conversion already took place during compilation // for rowsets char * intermediate = NULL; Lng32 sourceScale = operand->getScale(); Lng32 sourcePrecision = operand->getPrecision(); if ((targetType == REC_DECIMAL_LS) && (operand->getDatatype() != REC_DECIMAL_LSE) && (targetRowsetSize == 0)) { if ( source ) { intermediate = new (heap) char[targetLen - 1]; if (::convDoIt(source, sourceLen, sourceType, sourcePrecision, sourceScale, intermediate, targetLen - 1, REC_DECIMAL_LSE, targetPrecision, targetScale, NULL, 0, heap, &diagsArea) != ex_expr::EXPR_OK) { if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); NADELETEBASIC(intermediate, heap); if (! targetVarPtr) NADELETEBASIC(realTarget, heap); return ex_expr::EXPR_ERROR; }; source = intermediate; sourceLen = targetLen - 1; } sourceType = REC_DECIMAL_LSE; } // 5/18/98: added to handle SJIS encoding charset case. // This is used in ODBC where the target character set is still // ASCII but the actual character set used is SJIS. // if ( (sourceType == REC_NCHAR_F_UNICODE || sourceType == REC_NCHAR_V_UNICODE ) ) { if ( targetCharSet == CharInfo::SJIS ) { switch ( targetType ) { case REC_BYTE_F_ASCII: targetType = REC_MBYTE_F_SJIS; break; case REC_BYTE_V_ANSI: case REC_BYTE_V_ASCII_LONG: case REC_BYTE_V_ASCII: targetType = REC_MBYTE_V_SJIS; break; default: break; } } } ////////////////////////////////////////////////////////////////// // Conversion for exact numerics is done before doing scaling. // The scale is implicit so a value 1234.56 is stored as 123456. // While converting a value that does downscaling, we may run // into overflow errors which would not be there after scaling. // For example, // a NUMERIC(6,2) type with value 1234.56 is stored as 123456. // Converting this to a target type of SMALLINT will return an // overflow error since 123456 will not fit in 2 bytes. However // after scaling and truncation, this value will become 1234 // that will fit into SMALLINT. ANSI allows truncated results to // be returned. // So...if the source scale is greater than target scale for an // exact numeric conversion, then first convert the source to // largeint(this is the biggest exact numeric type that we // support) and downscale it there. Then convert this scaled // largeint to the target type. ////////////////////////////////////////////////////////////////// if ((sourceScale > targetScale) && (isExactNumeric(sourceType)) && (isExactNumeric(targetType))) { if (DFS2REC::isBigNum(sourceType)) // max numeric precision of 128 is stored as 57 bytes. intermediate = new (heap) char[57]; else intermediate = new (heap) char[8]; if ( source ) { // convert to largeint if (convDoIt(source, sourceLen, sourceType, sourcePrecision, sourceScale, intermediate, (DFS2REC::isBigNum(sourceType) ? 57 : 8), (DFS2REC::isBigNum(sourceType) ? REC_NUM_BIG_SIGNED : REC_BIN64_SIGNED), targetPrecision, targetScale, NULL, 0, heap, &diagsArea) != ex_expr::EXPR_OK) { if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); NADELETEBASIC(intermediate, heap); return ex_expr::EXPR_ERROR; } // scale it if (scaleDoIt( intermediate, (DFS2REC::isBigNum(sourceType) ? 57 : 8), (DFS2REC::isBigNum(sourceType) ? REC_NUM_BIG_SIGNED : REC_BIN64_SIGNED), sourceScale, targetScale, sourceType, heap) != ex_expr::EXPR_OK) { ExRaiseSqlError(heap, &diagsArea, EXE_NUMERIC_OVERFLOW); if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); NADELETEBASIC(intermediate, heap); return ex_expr::EXPR_ERROR; } } // if the target is REC_DECIMAL_LS, convert the source to // REC_DECIMAL_LSE first. Conversion to LS is currently // only supported if source is LSE. if (targetType == REC_DECIMAL_LS) { if ( source ) { char * intermediate2 = new (heap) char[targetLen - 1]; if (::convDoIt(intermediate, 8, REC_BIN64_SIGNED, targetPrecision, targetScale, intermediate2, targetLen - 1, REC_DECIMAL_LSE, targetPrecision, targetScale, NULL, 0, heap, &diagsArea) != ex_expr::EXPR_OK) { if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); NADELETEBASIC(intermediate, heap); NADELETEBASIC(intermediate2, heap); return ex_expr::EXPR_ERROR; }; NADELETEBASIC(intermediate, heap); intermediate = intermediate2; sourceLen = targetLen - 1; } sourceType = REC_DECIMAL_LSE; } // targetType == REC_DECIMAL_LS else { sourceLen = (DFS2REC::isBigNum(sourceType) ? 57 : 8); sourceType = (DFS2REC::isBigNum(sourceType) ? REC_NUM_BIG_SIGNED : REC_BIN64_SIGNED); } if ( source ) source = intermediate; // no more scaling is to be done. sourceScale = 0; targetScale = 0; } // exact numeric with scaling // if incompatible conversions are to be done, // and the target is REC_BYTE_V_ANSI, // and the source is not a string type, convert the source to // REC_BYTE_V_ASCII first. Conversion to V_ANSI is currently // only supported if source is a string type. if (implicitConversion) { if ((targetType == REC_BYTE_V_ANSI) && ((sourceType < REC_MIN_CHARACTER) || (sourceType > REC_MAX_CHARACTER))) { if ( source ) { intermediate = new (heap) char[targetLen]; short intermediateLen; if (::convDoIt(source, sourceLen, sourceType, sourcePrecision, sourceScale, intermediate, targetLen, REC_BYTE_V_ASCII, targetPrecision, targetScale, (char*)&intermediateLen, sizeof(short), heap, &diagsArea) != ex_expr::EXPR_OK) { if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); NADELETEBASIC(intermediate, heap); return ex_expr::EXPR_ERROR; }; sourceType = REC_BYTE_F_ASCII; sourceLen = intermediateLen; sourceScale = 0; source = intermediate; } } // targetType == REC_BYTE_V_ANSI if (((targetType == REC_DATETIME) || (DFS2REC::isInterval(targetType))) && (DFS2REC::isAnyCharacter(sourceType))) { targetType = REC_BYTE_F_ASCII; targetScale = 0; targetPrecision = 0; } } // implicit conversion conv_case_index case_index = CONV_UNKNOWN; ULng32 convFlags = 0; if ((source) && (NOT implicitConversion) && (((sourceType == REC_DATETIME) || ((sourceType >= REC_MIN_INTERVAL) && (sourceType <= REC_MAX_INTERVAL))) && (NOT isIFIO))) { // this is a datetime or interval conversion. // Convert the internal datetime/interval to its // external string format. The conversion follows the // same rules as "CAST(datetime/interval TO CHAR)". // If the two interval types are not the same, then first // convert source to target interval type, and then convert // to its string external representation. if (sourceType == REC_DATETIME) { if ((sourcePrecision != targetPrecision) || (sourceScale != targetScale)) { // source and target must have the same datetime_code, // they must both be date, time or timestamp. ExRaiseSqlError(heap, &diagsArea, EXE_CONVERT_NOT_SUPPORTED); if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); return ex_expr::EXPR_ERROR; } else { // For CALL stmts with wide desc, don't change target // type to ASCII if rowwise rowsets are set by caller. // Caller expects the value in internal format even though // we do not use bulk move for copying. // Also applicable to ODBC calls. if ( ((NOT isOdbc) && (! isCall() || ! output_desc->isDescTypeWide() || ! output_desc->rowwiseRowsetV2())) || (isOdbc && ! output_desc->rowwiseRowsetV1() && ! output_desc->rowwiseRowsetV2()) ) { targetType = REC_BYTE_F_ASCII; targetPrecision = 0; // TBD $$$$ add target max chars later targetScale = SQLCHARSETCODE_ISO88591; // assume target charset is ASCII-compatible } } } else if ((sourceType == targetType) && (sourcePrecision == targetPrecision) && (sourceScale == targetScale)) { // 'interval' source and target match all attributes. // Convert source(internal) to string target(external) format targetType = REC_BYTE_F_ASCII; targetPrecision = 0; // TBD $$$$ add target max chars later targetScale = SQLCHARSETCODE_ISO88591; // assume target charset is ASCII compatible } else { // interval type and source/target do not match. // Convert source to target interval type. short intermediateLen = SQL_LARGE_SIZE; intermediate = new (heap) char[intermediateLen]; if (::convDoIt(source, sourceLen, sourceType, sourcePrecision, sourceScale, intermediate, intermediateLen, targetType, targetPrecision, targetScale, NULL, sizeof(short), heap, &diagsArea) != ex_expr::EXPR_OK) { if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); NADELETEBASIC(intermediate, heap); return ex_expr::EXPR_ERROR; }; sourceType = targetType; sourceLen = intermediateLen; sourceScale = targetScale; sourcePrecision = targetPrecision; source = intermediate; targetType = REC_BYTE_F_ASCII; targetScale = 0; targetPrecision = 0; } // datetime and interval values are left blank padded. convFlags |= CONV_LEFT_PAD; } if ( source ) { if ( treatAnsivByteAsWideChar == TRUE ) { // We substract one here so that the first byte in the // last wide char can be filled with single-byte // null by convDoIt(). // // Note the target length records the number of octets // in target hostvar. The value is even because // KANJI/KSC hostvars are wide characters. targetLen--; } rc = convDoIt (source, sourceLen, sourceType, sourcePrecision, sourceScale, target, targetLen, targetType, targetPrecision, targetScale, targetVCLen, targetVCLenSize, heap, &diagsArea, case_index, 0, convFlags); if (rc == ex_expr::EXPR_ERROR) { if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); NADELETEBASIC(intermediate, heap); if (!targetVarPtr) NADELETEBASIC(realTarget, heap); return ex_expr::EXPR_ERROR; } if ( treatAnsivByteAsWideChar == TRUE ) { // Make the second byte in the last wide char // a null so that the last wide char contains a wide-char // null. target[strlen(target)+1] = 0; } if (diagsArea ) { // Indicator var is also used to test for truncated output value. // The Indicator variable is set to the length of the string in the // database if the character value is truncated.. // numOfWarningsFoundSoFar is the number of warnings we know exists // before the above convDoIt() is called. If warning EXE_STRING_OVERFLOW // exists as a result of the convDoIt() call, it will be recorded in // diagsArea->warnings_ array, in the range // [numOfStringOverflowWarningsFoundSoFar, warnings_.entries()). The // method diagsArea->containsWarning(x, y) will tell us if it is true or // not. If it is true, then we update the indicator. if ( DFS2REC::isAnyCharacter(targetType) && DFS2REC::isAnyCharacter(operand->getDatatype()) && diagsArea -> containsWarning( numOfWarningsFoundSoFar, EXE_STRING_OVERFLOW)) { if (targetIndPtr) { short * tempVCInd = (short *) targetIndPtr; if (DFS2REC::isANSIVarChar(sourceType)) { if ( CharInfo::maxBytesPerChar(sourceCharSet) == 2 ) { *tempVCInd = (short) NAWstrlen((NAWchar *)source); // we are guaranteed that source is // null-terminated as the previous call to convdoit() //would have raised an error otherwise } else { *tempVCInd = (short) strlen(source); } } // if ANSIVarChar else { *tempVCInd = (short)sourceLen; if ( CharInfo::maxBytesPerChar(sourceCharSet) == 2 ) *tempVCInd /= SQL_DBCHAR_SIZE; } } if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); } // character datatype numOfWarningsFoundSoFar = diagsArea->getNumber(DgSqlCode::WARNING_); } NADELETEBASIC(intermediate, heap); // up- or down-scale target. if (targetType >= REC_MIN_NUMERIC && targetType <= REC_MAX_NUMERIC && sourceScale != targetScale && ::scaleDoIt( target, targetLen, targetType, sourceScale, targetScale, sourceType, heap) != ex_expr::EXPR_OK) { ExRaiseSqlError(heap, &diagsArea, EXE_NUMERIC_OVERFLOW); if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); if (!targetVarPtr) NADELETEBASIC(realTarget, heap); return ex_expr::EXPR_ERROR; } if (!targetVarPtr) { // unbound column. Remember it in executor memory. // This value will(probably) be retrieved later by // a call to GetDescItem with SQLDESC_VAR_DATA. Lng32 length; if (targetVCLenSize > 0) length = 0; else length = targetLen; output_desc->setDescItem(entry, SQLDESC_VAR_DATA, length , realTarget); //sourceLen+targetVCLenSize, realTarget); NADELETEBASIC(realTarget, heap); } } } // not NULL moved if ( source != NULL ) { // Increment the location for the next element. if (targetRowsetSize > 0) { source = rowsetSourcePosition; } source += operand->getStorageLength(); if ((operand->getVCIndicatorLength() > 0) && (sourceVCLenInd)) sourceVCLenInd += operand->getStorageLength(); if ((operand->getNullFlag()) && (sourceNullInd)) sourceNullInd += operand->getStorageLength(); } if (targetRowsetSize > 0) { // restore the original datatype attributes. sourceLen = savedSourceLen; targetType = savedTargetType; targetPrecision = savedTargetPrecision; targetScale = savedTargetScale; targetLen = savedTargetLen; } } // end of for (RowNum < sourceNumProcessed) loop } // clause is INOUT type next_clause: clause = clause->getNextClause(); } // loop over clauses if (totalNumOfRowsets) output_desc->setDescItem(0, SQLDESC_ROWSET_NUM_PROCESSED, sourceNumProcessed, 0); return ex_expr::EXPR_OK; } #pragma warning (default : 4273) //warning elimination ex_expr::exp_return_type InputOutputExpr::describeInput(void * input_desc_, void * rwrs_info, UInt32 flags) { NABoolean isOdbc = isODBC(flags); NABoolean isDbtr = isDBTR(flags); NABoolean isRwrs = isRWRS(flags); NABoolean isIFIO = (isInternalFormatIO(flags) || (isDbtr && isRwrs)); RWRSInfo * rwrsInfo = (RWRSInfo *)rwrs_info; ex_clause *clause = getClauses(); Descriptor * input_desc = (Descriptor *)input_desc_; short entry = 0; input_desc->setDescItem(0, SQLDESC_ROWSET_SIZE, // ROWSET_SIZE is a header field and 0, 0); // occurs once per descriptor, not once per // desc item. Its value is 0 if no rowsets are present, otherwise its value is // rowset size of any one of the all rowset input variables in the descriptor. // For dynamic SQl, where describe is used, rowsets sizes must all be the same // so the MIN of all input sizes is not calculated. short dataType; Lng32 prevEntryStartOffset = 0; Lng32 currAlignedOffset = 0; Lng32 firstEntryStartAlignment = 0; Lng32 length = -1; NABoolean firstEntryProcessed = FALSE; while (clause) { if (clause->getType() == ex_clause::INOUT_TYPE) { Attributes * operand = clause->getOperand(0); dataType = operand->getDatatype(); if(isCall() && input_desc->isDescTypeWide()) entry = ((ex_inout_clause *)clause)->getParamIdx(); else entry++; input_desc->setDescItem(entry, SQLDESC_TYPE_FS, dataType, 0); length = operand->getLength(); // Record the display length for DATETIME or INTERVAL operand since either is // represented as a character array externally. The value of this variable is // used to set the SQLDESC_LENGTH field for the descriptor. The same value // will be used to set the SQLDESC_ROWSET_VAR_LAYOUT_SIZE field if the input // is a rowset and its element type is DATETIME or INTERVAL. Lng32 displayLength = 0; if ((dataType >= REC_MIN_INTERVAL) && (dataType <= REC_MAX_INTERVAL)) { // // According to ANSI, interval info is stored in the following // descriptor items: // // DATETIME_INTERVAL_CODE = qualifier code // PRECISION = fractional precision // DATETIME_INTERVAL_PRECISION = leading precision // input_desc->setDescItem(entry, SQLDESC_DATETIME_CODE, getIntervalCode(dataType), 0); input_desc->setDescItem(entry, SQLDESC_PRECISION, operand->getScale(), 0); input_desc->setDescItem(entry, SQLDESC_SCALE, 0, 0); input_desc->setDescItem(entry, SQLDESC_INT_LEAD_PREC, operand->getPrecision(), 0); if (NOT isIFIO) { #pragma warning (disable : 4244) //warning elimination displayLength = ExpInterval::getDisplaySize(dataType, #pragma nowarn(1506) // warning elimination operand->getPrecision(), #pragma warn(1506) // warning elimination operand->getScale()); #pragma warning (default : 4244) //warning elimination length = displayLength; } } else if (dataType == REC_DATETIME) { // // According to ANSI, datetime info is stored in the following // descriptor items: // // DATETIME_INTERVAL_CODE = qualifier code // PRECISION = fractional precision // input_desc->setDescItem(entry, SQLDESC_DATETIME_CODE, operand->getPrecision(), 0); input_desc->setDescItem(entry, SQLDESC_PRECISION, operand->getScale(), 0); input_desc->setDescItem(entry, SQLDESC_SCALE, 0, 0); input_desc->setDescItem(entry, SQLDESC_INT_LEAD_PREC, 0, 0); if (NOT isIFIO) { displayLength = ExpDatetime::getDisplaySize(operand->getPrecision(), operand->getScale()); length = displayLength; } } else { input_desc->setDescItem(entry, SQLDESC_DATETIME_CODE, 0, 0); input_desc->setDescItem(entry, SQLDESC_PRECISION, operand->getPrecision(), 0); input_desc->setDescItem(entry, SQLDESC_SCALE, operand->getScale(), 0); input_desc->setDescItem(entry, SQLDESC_INT_LEAD_PREC, 0, 0); } // Use SQLDESC_CHAR_SET_NAM (one-part name) for charset if (((dataType >= REC_MIN_CHARACTER) && (dataType <= REC_MAX_CHARACTER)) ) { input_desc->setDescItem(entry, SQLDESC_CHAR_SET_NAM, 0, (char*)CharInfo::getCharSetName(operand->getCharSet())); // For Unicode/KSC5601/KANJI, set the length in number of characters if ( CharInfo::maxBytesPerChar(operand->getCharSet()) == SQL_DBCHAR_SIZE ) length = operand->getLength()/SQL_DBCHAR_SIZE; } input_desc->setDescItem(entry, SQLDESC_NULLABLE, operand->getNullFlag(), 0); input_desc->setDescItem(entry, SQLDESC_NAME, 0, ((ex_inout_clause *)clause)->getName()); if (((ex_inout_clause *)clause)->getHeading() != 0) input_desc->setDescItem(entry, SQLDESC_HEADING, 0, ((ex_inout_clause *)clause)->getHeading()); if (((ex_inout_clause *)clause)->getTableName() != 0) input_desc->setDescItem(entry, SQLDESC_TABLE_NAME, 0, ((ex_inout_clause *)clause)->getTableName()); if (((ex_inout_clause *)clause)->getSchemaName() != 0) input_desc->setDescItem(entry, SQLDESC_SCHEMA_NAME, 0, ((ex_inout_clause *)clause)->getSchemaName()); if (((ex_inout_clause *)clause)->getCatalogName() != 0) input_desc->setDescItem(entry, SQLDESC_CATALOG_NAME, 0, ((ex_inout_clause *)clause)->getCatalogName()); input_desc->setDescItem(entry, SQLDESC_VAR_PTR, 0, 0); input_desc->setDescItem(entry, SQLDESC_IND_PTR, 0, 0); input_desc->setDescItem(entry, SQLDESC_VAR_DATA, 0, 0); input_desc->setDescItem(entry, SQLDESC_IND_DATA, 0, 0); if (operand->getRowsetSize() > 0) { input_desc->setDescItem(0, SQLDESC_ROWSET_SIZE, operand->getRowsetSize(), 0); // Use the operand length if the operand is not INTERVAL/DATETIME. if ( displayLength == 0 ) displayLength = operand->getLength(); // Describe Input will set values for VarLayoutSize that are compatible // with C type (i.e null-terminated) hostvariables. For fixed length chars // ANSI varchars, decimal, datetime and interval types // varLayoutSize will be set to OCTET_LENGTH + 1 (+2 for unicode). // Users are expected to override this value, if their arraysize is different. if (DFS2REC::isAnyCharacter(dataType) && !DFS2REC::isSQLVarChar(dataType)) { // all charcter types other than tandem varchar displayLength += CharInfo::maxBytesPerChar(operand->getCharSet()); } else if ((dataType >= REC_MIN_DECIMAL && dataType <= REC_MAX_DECIMAL) || (dataType >= REC_MIN_INTERVAL && dataType <= REC_MAX_INTERVAL_MP) || (dataType == REC_DATETIME)) { // We do not expect to see dataType == REC_DECIMAL_LS (with first byte for sign) // as the compiler currently generates REC_DECIMAL_LSE (leading sign embedded) as // the type for signed decimal columns. If the compiler ever changes is default type // for decimal signed columns to REC_DECIMAL_LS, then the following must be true // RowsetVarLayoutSize = Precison + 2; // If Length = Precision + 1; then the following assertion can be removed and // the behaviour will be correct. If Length = Precision, then when removing // the following assertion add one to displayLength for the REC_DECIMAL_LS datatype. BriefAssertion(dataType != REC_DECIMAL_LS, "RowsetVarLayoutSize must account for the sign byte"); displayLength++; } input_desc->setDescItem(entry, SQLDESC_ROWSET_VAR_LAYOUT_SIZE, displayLength, 0); input_desc->setDescItem(entry, SQLDESC_ROWSET_IND_LAYOUT_SIZE, operand->getNullIndicatorLength(), 0); } else { input_desc->setDescItem(entry, SQLDESC_ROWSET_VAR_LAYOUT_SIZE, 0, 0); input_desc->setDescItem(entry, SQLDESC_ROWSET_IND_LAYOUT_SIZE, 0, 0); } short paramMode = ((ex_inout_clause *)clause)->getParamMode(); short paramIdx = ((ex_inout_clause *)clause)->getParamIdx(); short ordPos = ((ex_inout_clause *)clause)->getOrdPos(); BriefAssertion((paramMode == PARAMETER_MODE_IN)|| (paramMode == PARAMETER_MODE_INOUT)|| (paramMode == PARAMETER_MODE_UNDEFINED), "invalid param mode"); BriefAssertion(paramIdx >= 0, "invalid param index"); BriefAssertion(ordPos >= 0, "invalid param ordinal position"); // handle old plan if(paramMode == PARAMETER_MODE_UNDEFINED){ paramMode = PARAMETER_MODE_IN; } if(paramIdx == 0){ paramIdx = entry; } if(ordPos == 0){ ordPos = entry; } input_desc->setDescItem(entry, SQLDESC_PARAMETER_MODE, paramMode, 0); input_desc->setDescItem(entry, SQLDESC_PARAMETER_INDEX, paramIdx, 0); input_desc->setDescItem(entry, SQLDESC_ORDINAL_POSITION, ordPos, 0); // End if(isCall()){ short paramMode = ((ex_inout_clause *)clause)->getParamMode(); short paramIdx = ((ex_inout_clause *)clause)->getParamIdx(); short ordPos = ((ex_inout_clause *)clause)->getOrdPos(); input_desc->setDescItem(entry, SQLDESC_PARAMETER_MODE, paramMode, 0); input_desc->setDescItem(entry, SQLDESC_PARAMETER_INDEX, paramIdx, 0); input_desc->setDescItem(entry, SQLDESC_ORDINAL_POSITION, ordPos, 0); } else{ input_desc->setDescItem(entry, SQLDESC_PARAMETER_MODE, PARAMETER_MODE_IN, 0); input_desc->setDescItem(entry, SQLDESC_PARAMETER_INDEX, entry, 0); input_desc->setDescItem(entry, SQLDESC_ORDINAL_POSITION, 0, 0); } input_desc->setDescItem(entry, SQLDESC_LENGTH, length, 0); // Set up length of null indicator and varcharlen indicator values // in the descriptor. // input_desc->setDescItem(entry, SQLDESC_IND_LENGTH, operand->getNullIndicatorLength(), 0); input_desc->setDescItem(entry, SQLDESC_VC_IND_LENGTH, operand->getVCIndicatorLength(), 0); // Get offsets to data, null indicator and varchar len indicator // in the actual row and set them in the descriptor. // // This is being done for sqlark_exploded_ and packed formats only. // The offsets that are set in descriptor assume that the returned // row to user is a single contiguous aligned row even though internally // that row could be represented by multiple fragments, each with // different atp index. // // These values are used by caller(mxcs) to set up input and output // data pointers so that they are aligned and set up the same way // as the actual row in cli. // // These values cannot be set by external callers. // // If RWRS buffer is being input, then do this for data params only. // if ((rwrsInfo ) && ((entry == rwrsInfo->rwrsInputSizeIndex()) || (entry == rwrsInfo->rwrsMaxInputRowlenIndex()) || (entry == rwrsInfo->rwrsBufferAddrIndex()) || (entry == rwrsInfo->rwrsPartnNumIndex()))) { // control params, skip them. goto next_clause; } Lng32 dataOffset = -1; Lng32 nullIndOffset = -1; Lng32 currEntryStartOffset = -1; Lng32 currEntryStartAlignment = -1; Lng32 inputDatalen = -1; if (input_desc->getDescItem(entry, SQLDESC_OCTET_LENGTH, &inputDatalen, NULL, 0, NULL, 0, NULL, 0) == ERROR) return ex_expr::EXPR_ERROR; Lng32 alignment = 1; if (operand->getNullIndOffset() >= 0) { if (operand->getTupleFormat() == ExpTupleDesc::SQLARK_EXPLODED_FORMAT) alignment = operand->getNullIndicatorLength(); currAlignedOffset = ADJUST(currAlignedOffset, alignment); nullIndOffset = currAlignedOffset; currEntryStartOffset = currAlignedOffset; currEntryStartAlignment = alignment; currAlignedOffset += operand->getNullIndicatorLength(); } if (operand->getVCLenIndOffset() >= 0) { if (operand->getTupleFormat() == ExpTupleDesc::SQLARK_EXPLODED_FORMAT) alignment = operand->getVCIndicatorLength(); currAlignedOffset = ADJUST(currAlignedOffset, alignment); dataOffset = currAlignedOffset; if (currEntryStartOffset == -1) { currEntryStartOffset = currAlignedOffset; currEntryStartAlignment = alignment; } currAlignedOffset += operand->getVCIndicatorLength() + inputDatalen; } else { if (operand->getTupleFormat() == ExpTupleDesc::SQLARK_EXPLODED_FORMAT) alignment = operand->getDataAlignmentSize(); currAlignedOffset = ADJUST(currAlignedOffset, alignment); dataOffset = currAlignedOffset; if (currEntryStartOffset == -1) { currEntryStartOffset = currAlignedOffset; currEntryStartAlignment = alignment; } currAlignedOffset += inputDatalen; } if (NOT firstEntryProcessed) { firstEntryProcessed = TRUE; firstEntryStartAlignment = currEntryStartAlignment; } input_desc->setDescItemInternal(entry, SQLDESC_DATA_OFFSET, dataOffset, 0); input_desc->setDescItemInternal(entry, SQLDESC_NULL_IND_OFFSET, nullIndOffset, 0); input_desc->setDescItemInternal(entry-1, SQLDESC_ALIGNED_LENGTH, currEntryStartOffset - prevEntryStartOffset, 0); prevEntryStartOffset = currEntryStartOffset; } // INOUT clause next_clause: clause = clause->getNextClause(); } if (firstEntryProcessed) { currAlignedOffset = ADJUST(currAlignedOffset, firstEntryStartAlignment); input_desc->setDescItemInternal(entry, SQLDESC_ALIGNED_LENGTH, currAlignedOffset - prevEntryStartOffset, 0); } if(!(isCall() && input_desc->isDescTypeWide()) || (entry > input_desc->getUsedEntryCount())) input_desc->setUsedEntryCount(entry); return ex_expr::EXPR_OK; } /* If you are adding code to InputValues that will may cause an error to generated (i.e. an SQL error with some SQLCODE value) then please read on. You must make two decision about the error 1. Can this error be raised when rowset input data is being copied in? If YES, is the error data dependent? A data dependent error is one which can occur for row i of the rowset but not on row (i+1). In other words it is not an error that applies to the whole statement but only to a specific row in the rowsets. If the answer to both these questions is YES please place the following line of code at some point after the error is in the diagsarea setRowNumberInCli(diagsArea, RowNum, targetRowsetSize) ; 2. If the answer the previous question(s) were YES, then read on. Now please judge if this error can be considered Nonfatal for rowsets, i.e. does it make sense to continue execution with next rowset row or should we stop right away. If you decide that it is a Nonfatal error (look in the method below for examples) then place the following four lines of code after the call to setRowNumberInCli. if (tolerateNonFatalError && diagsArea->canAcceptMoreErrors()) continue; else return ex_expr::EXPR_ERROR; */ // error path not taken . This is only if something bad happens in NVT //LCOV_EXCL_START #pragma warning (disable : 4273) //warning elimination ex_expr::exp_return_type InputOutputExpr::inputSingleRowValue(atp_struct *atp, void * inputDesc_, char * tgtRowPtr, CollHeap * heap, UInt32 flags) { NABoolean isOdbc = isODBC(flags); NABoolean isDbtr = isDBTR(flags); NABoolean isRwrs = isRWRS(flags); NABoolean isIFIO = (isInternalFormatIO(flags) || (isDbtr && isRwrs)); ex_clause * clause = getClauses(); Descriptor * inputDesc = (Descriptor *)inputDesc_; Attributes * operand = 0; ComDiagsArea *diagsArea = atp->getDiagsArea(); char * target = 0; char * targetVCLenInd = 0; char * targetNullInd = 0; char * source = 0; Lng32 sourceLen; char * sourceIndPtr = 0; short sourceType; Lng32 sourcePrecision; Lng32 sourceScale; char * tempSource = 0; Lng32 tempSourceType = 0; Lng32 indData; short entry = 0; char * intermediate = NULL; short savedSourceType = 0; Lng32 savedSourcePrecision = 0; Lng32 savedSourceScale = 0; Lng32 savedSourceLen = 0; ExeErrorCode errorCode = EXE_OK; // if bulk move has not been disabled before, then check to see if bulk // move could be done. This is done by comparing attributes of the // executor items and the descriptor entries. See method // Descriptor::isBulkMovePossible() for details on when bulk move will // be disabled. // If bulk move is possible then set up bulk move info, if not already // done. if (NOT inputDesc->bulkMoveDisabled()) { if (NOT inputDesc->bulkMoveSetup()) { setupBulkMoveInfo(inputDesc, heap, TRUE /* input desc */, flags); } if (NOT inputDesc->bulkMoveDisabled()) { // bulk move is enabled and setup has been done. // Do bulk move now. doBulkMove(atp, inputDesc, tgtRowPtr, TRUE /* input desc */); if (NOT inputDesc->doSlowMove()) return ex_expr::EXPR_OK; } } CharInfo::CharSet sourceCharSet = CharInfo::UnknownCharSet; CharInfo::CharSet targetCharSet = CharInfo::UnknownCharSet; while (clause) { if (clause->getType() == ex_clause::INOUT_TYPE) { entry++; if ((NOT inputDesc->bulkMoveDisabled()) && (NOT inputDesc->doSlowMove(entry))) goto next_clause; operand = clause->getOperand(0); if (operand->isBlankHV()) { clause = clause->getNextClause(); continue; } char * dataPtr = (tgtRowPtr ? tgtRowPtr : (atp->getTupp(operand->getAtpIndex())).getDataPointer()); target = (char *)(dataPtr + operand->getOffset()); if (operand->getVCIndicatorLength() > 0) targetVCLenInd = (char *)(dataPtr + operand->getVCLenIndOffset()); if (operand->getNullFlag()) targetNullInd = (char*)(dataPtr + operand->getNullIndOffset()); inputDesc->getDescItem(entry, SQLDESC_TYPE_FS, &tempSourceType, 0, 0, 0, 0); sourceType = (short) tempSourceType; if ((sourceType >= REC_MIN_INTERVAL) && (sourceType <= REC_MAX_INTERVAL)) { inputDesc->getDescItem(entry, SQLDESC_INT_LEAD_PREC, &sourcePrecision, 0, 0, 0, 0); // SQLDESC_PRECISION gets the fractional precision inputDesc->getDescItem(entry, SQLDESC_PRECISION, &sourceScale, 0, 0, 0, 0); } else if (sourceType == REC_DATETIME) { inputDesc->getDescItem(entry, SQLDESC_DATETIME_CODE, &sourcePrecision, 0, 0, 0, 0); inputDesc->getDescItem(entry, SQLDESC_PRECISION, &sourceScale, 0, 0, 0, 0); } else { inputDesc->getDescItem(entry, SQLDESC_PRECISION, &sourcePrecision, 0, 0, 0, 0); inputDesc->getDescItem(entry, SQLDESC_SCALE, &sourceScale, 0, 0, 0, 0); }; if ((sourceType >= REC_MIN_CHARACTER) && (sourceType <= REC_MAX_CHARACTER)) { Lng32 temp_char_set; inputDesc->getDescItem( entry, SQLDESC_CHAR_SET, &temp_char_set, NULL, 0, NULL, 0); sourceCharSet = (CharInfo::CharSet)temp_char_set; sourceScale = sourceCharSet; } // 5/18/98: added to handle SJIS encoding charset case. // This is used in ODBC where the target character set is still // ASCII but the actual character set used is SJIS. // short targetType = operand->getDatatype(); targetCharSet = operand->getCharSet(); if ( (targetType == REC_NCHAR_F_UNICODE || targetType == REC_NCHAR_V_UNICODE ) ) { // charset can be retrieved as a long INTERNALLY // using programatic interface by calling getDescItem(), // and can only be retrieved as a character string EXTERNALLY // using "get descriptor" syntax. if ( sourceCharSet == CharInfo::SJIS ) { switch ( sourceType ) { case REC_BYTE_F_ASCII: sourceType = REC_MBYTE_F_SJIS; break; case REC_BYTE_V_ANSI: case REC_BYTE_V_ASCII_LONG: case REC_BYTE_V_ASCII: sourceType = REC_MBYTE_V_SJIS; break; default: break; } } } // The following is redefined at a later point for variable length // strings inputDesc->getDescItem(entry, SQLDESC_OCTET_LENGTH, &sourceLen, 0, 0, 0, 0); inputDesc->getDescItem(entry, SQLDESC_IND_DATA, &indData, 0, 0, 0, 0); if (indData == 0) { inputDesc->getDescItem(entry, SQLDESC_IND_PTR, &tempSource, 0, 0, 0, 0); } else tempSource = (char * )&indData; if ((isOdbc) && (isRwrs)) { if (operand->getNullIndOffset() >= 0) sourceIndPtr = (char*) (inputDesc->getCurrRowPtrInRowwiseRowset() + operand->getNullIndOffset()); else sourceIndPtr = NULL; } else sourceIndPtr = tempSource; NABoolean nullMoved = FALSE; if (sourceIndPtr) { short temp = 0; str_cpy_all((char *)&temp, sourceIndPtr, operand->getNullIndicatorLength()); if (temp > 0) { // invalid null indicator value. // Valid indicator values are 0(not null value) and // -ve (null value). errorCode = EXE_CONVERT_STRING_ERROR; goto error_return; } if (operand->getNullFlag()) { nullMoved = (temp < 0); //if null indicator is a negative //number, the value is null str_cpy_all (targetNullInd, sourceIndPtr, operand->getNullIndicatorLength()); } else { if (temp < 0) { // input is a null value // error. Trying to move a null input value to a // non-nullable buffer. errorCode = EXE_ASSIGNING_NULL_TO_NOT_NULL; goto error_return; } } } else { // indicator not specified. if (operand->getNullFlag()) { // move 0 (non-null value) to first two bytes of buffer. str_pad(targetNullInd, operand->getNullIndicatorLength(), '\0'); } } if ((isOdbc) && (isRwrs)) { if (operand->getOffset() >= 0) source = (char*)(inputDesc->getCurrRowPtrInRowwiseRowset() + operand->getOffset()); else source = NULL; } else source = inputDesc -> getVarData(entry); if (!source) { continue; } if (DFS2REC::isSQLVarChar(sourceType)) { // the first 2 bytes of data are actually the variable // length indicator short VCLen; str_cpy_all((char *) &VCLen, source, sizeof(short)); sourceLen = (Lng32) VCLen; source = &source[sizeof(short)]; #ifdef _DEBUG assert(SQL_VARCHAR_HDR_SIZE == sizeof(short)); #endif } // 12/22/97: added for Unicode Vchar. if (! nullMoved) { ex_expr::exp_return_type retcode = ex_expr::EXPR_OK; Lng32 warningMark; if (diagsArea) warningMark= diagsArea->getNumber(DgSqlCode::WARNING_); else warningMark = 0; NABoolean implicitConversion = FALSE; // if the source and target are not compatible, then do implicit // conversion if skipTypeCheck is set. // Furthermore, if restrictedSkipTypeCheck is set, then only // convert for the conversions that are externally supported. // See usage of default IMPLICIT_HOSTVAR_CONVERSION in generator // (GenExpGenerator.cpp) for restricted conversions. if (NOT areCompatible(sourceType, targetType)) { if ((NOT skipTypeCheck()) || ((restrictedSkipTypeCheck()) && (NOT implicitConversionSupported(sourceType, operand->getDatatype())))) { errorCode = EXE_CONVERT_NOT_SUPPORTED; goto error_return; } implicitConversion = TRUE; } else { // check charset for source and target if they are CHARACTER types. if ( DFS2REC::isAnyCharacter(sourceType) && NOT CharInfo::isAssignmentCompatible(sourceCharSet, targetCharSet) ) { ExRaiseSqlError(heap, &diagsArea, CLI_ASSIGN_INCOMPATIBLE_CHARSET); if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); *diagsArea << DgString0(CharInfo::getCharSetName((CharInfo::CharSet)sourceCharSet)) << DgString1(CharInfo::getCharSetName((CharInfo::CharSet)targetCharSet)); return ex_expr::EXPR_ERROR; } } // Check length limit for KANJI/KSC5601/UCS2 ANSI VARCHAR (i.e., there // should be a wchar_t typed NULL somewhere in the range [1, sourceLen/2] // in the source. We have to do this for KANJI/KSC because their FS type // codes are shared with the ISO88591 CHARACTER types and the conversion // routines for ISO88591 ANSI VARCHAR in convDoIt() can not verify the // wchar_t nulls. // // We also check the ANSI Unicode source here because we then can safely // use the NAWstrlen() function to obtain the length in the next IF block to // check code points. if ((sourceType == REC_BYTE_V_ANSI && CharInfo::is_NCHAR_MP(sourceCharSet)) || sourceType == REC_NCHAR_V_ANSI_UNICODE ) { Lng32 i = 0; Int32 sourceLenInWchar = sourceLen/SQL_DBCHAR_SIZE; wchar_t* sourceInWchar = (wchar_t*)source; while ((i < sourceLenInWchar) && (sourceInWchar[i] != 0)) i++; if ( i == sourceLenInWchar ) { errorCode = EXE_MISSING_NULL_TERMINATOR; goto error_return; }; } if ( DFS2REC::isAnyCharacter(sourceType) && sourceCharSet == CharInfo::UNICODE ) { Lng32 realSourceLen = sourceLen; if (sourceType == REC_NCHAR_V_ANSI_UNICODE) { #pragma nowarn(1506) // warning elimination realSourceLen = NAWstrlen((wchar_t*)source) * SQL_DBCHAR_SIZE; #pragma warn(1506) // warning elimination if ( realSourceLen > sourceLen ) realSourceLen = sourceLen ; } realSourceLen /= SQL_DBCHAR_SIZE; if ( CharInfo::checkCodePoint((wchar_t*)source, realSourceLen, CharInfo::UNICODE ) == FALSE ) { // Error code 3400 falls in CLI error code area, but it is // a perfect fit to use here (as an exeutor error). ExRaiseSqlError(heap, &diagsArea, (ExeErrorCode)3400); if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); *diagsArea << DgString0(SQLCHARSETSTRING_UNICODE); return ex_expr::EXPR_ERROR; } } // if incompatible conversions are to be done, // and the source is REC_BYTE_V_ANSI, // and the target is not a string type, convert the source to // REC_BYTE_F_ASCII first. Conversion from V_ANSI is currently // only supported if target is a string type. if ((implicitConversion) && ((sourceType == REC_BYTE_V_ANSI) && ((targetType < REC_MIN_CHARACTER) || (targetType > REC_MAX_CHARACTER)))) { intermediate = new (heap) char[sourceLen]; if (::convDoIt(source, sourceLen, sourceType, sourcePrecision, sourceScale, intermediate, sourceLen, REC_BYTE_F_ASCII, sourcePrecision, sourceScale, NULL, 0, heap, &diagsArea) != ex_expr::EXPR_OK) { NADELETEBASIC(intermediate, heap); errorCode = EXE_OK; goto error_return; }; sourceType = REC_BYTE_F_ASCII; source = intermediate; } // sourceType == REC_BYTE_V_ANSI if ((sourceType >= REC_MIN_BINARY) && (sourceType <= REC_MAX_BINARY) && (sourceType == operand->getDatatype()) && (sourcePrecision > 0) && (sourcePrecision == operand->getPrecision())) { // validate source precision. Make the source precision // zero, that will trigger the validation. See method // checkPrecision in exp_conv.cpp. sourcePrecision = 0; } ULng32 convFlags = 0; if ((NOT implicitConversion) && (((sourceType == REC_DATETIME) || ((sourceType >= REC_MIN_INTERVAL) && (sourceType <= REC_MAX_INTERVAL))) && (NOT isIFIO))) { // this is a datetime or interval conversion. // Convert the external string datetime/interval to its // internal format. The conversion follows the // same rules as "CAST(char TO datetime/interval)". // If the two interval types are not the same, then first // convert source from its string to its internal format, // and then convert to the target interval type. if (sourceType == REC_DATETIME) { if ((sourcePrecision != operand->getPrecision()) || (sourceScale != operand->getScale())) { // source and target must have the same datetime_code, // they must both be date, time or timestamp. errorCode = EXE_CONVERT_NOT_SUPPORTED; goto error_return; } else sourceType = REC_BYTE_F_ASCII; } else if ((sourceType == targetType) && (sourcePrecision == operand->getPrecision()) && (sourceScale == operand->getScale())) { // 'interval' source and target match all attributes. // Convert source(string external) to target(internal) format sourceType = REC_BYTE_F_ASCII; convFlags |= CONV_ALLOW_SIGN_IN_INTERVAL; } else { // interval type and source/target do not match. // Convert source string interval to corresponding // internal format. short intermediateLen = SQL_LARGE_SIZE; intermediate = new (heap) char[intermediateLen]; convFlags |= CONV_ALLOW_SIGN_IN_INTERVAL; if (::convDoIt(source, sourceLen, REC_BYTE_F_ASCII, 0, //sourcePrecision, 0, //sourceScale, intermediate, intermediateLen, sourceType, sourcePrecision, sourceScale, NULL, 0, heap, &diagsArea, CONV_UNKNOWN, 0, convFlags) != ex_expr::EXPR_OK) { NADELETEBASIC(intermediate, heap); errorCode = EXE_OK; goto error_return; }; source = intermediate; sourceLen = intermediateLen; } } if (noDatetimeValidation()) convFlags |= CONV_NO_DATETIME_VALIDATION; retcode = ::convDoIt(source, sourceLen, sourceType, sourcePrecision, sourceScale, target, operand->getLength(), operand->getDatatype(), operand->getPrecision(), operand->getScale(), targetVCLenInd, operand->getVCIndicatorLength(), heap, &diagsArea, CONV_UNKNOWN, 0, convFlags); // NADELETEBASIC(intermediate, heap); if (retcode != ex_expr::EXPR_OK) { errorCode = EXE_OK; goto error_return; } else if (diagsArea && diagsArea->mainSQLCODE() == EXE_STRING_OVERFLOW) { Int32 warningMark2 = diagsArea->getNumber(DgSqlCode::WARNING_); Int32 counter = warningMark2 - warningMark; diagsArea->deleteWarning(warningMark2-counter); errorCode = EXE_STRING_OVERFLOW; goto error_return; } // up- or down-scale target. if ((operand->getDatatype() >= REC_MIN_NUMERIC) && (operand->getDatatype() <= REC_MAX_NUMERIC) && (sourceScale != operand->getScale()) && ::scaleDoIt(target, operand->getLength(), operand->getDatatype(), sourceScale, operand->getScale(), sourceType, heap) != ex_expr::EXPR_OK) { errorCode = EXE_NUMERIC_OVERFLOW; goto error_return; } } // if (! nullMoved) } // if clause == IN_OUT type next_clause: clause = clause->getNextClause(); } // while(clause) return ex_expr::EXPR_OK; error_return: if (errorCode != EXE_OK) ExRaiseSqlError(heap, &diagsArea, errorCode); if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); return ex_expr::EXPR_ERROR; } //LCOV_EXCL_STOP ex_expr::exp_return_type InputOutputExpr::inputRowwiseRowsetValues(atp_struct *atp, void * inputDesc_, void * rwrs_info, NABoolean tolerateNonFatalError, CollHeap * heap, UInt32 flags) { NABoolean isOdbc = isODBC(flags); NABoolean isDbtr = isDBTR(flags); ex_clause * clause = getClauses(); Descriptor * inputDesc = (Descriptor *)inputDesc_; RWRSInfo * rwrsInfo = (RWRSInfo *)rwrs_info; Attributes * operand = 0; ComDiagsArea *diagsArea = atp->getDiagsArea(); Lng32 targetRowsetSize = -1; Lng32 dynamicRowsetSize = -1; Lng32 rwrsInputBuffer = -1; char * source = NULL; char * target = NULL; short entry = 0; ExeErrorCode errorCode = EXE_OK; Lng32 intParam1 = 0; Lng32 intParam2 = 0; Lng32 intParam3 = 0; Lng32 numRowsProcessed = 0; char * tgtRowAddr = rwrsInfo->getRWRSInternalBufferAddr(); char ** rwrsInternalBufferAddrLoc = NULL; char * rwrsMaxInputRowlenLoc = NULL; Lng32 inputRowsetSize = -1; Lng32 maxInputRowlen = -1; char * bufferAddr = NULL; Lng32 partnNum = -1; // input RWRS are always V2. inputDesc->setRowwiseRowsetV2(TRUE); while (clause) { if (clause->getType() == ex_clause::INOUT_TYPE) { entry++; if ((entry == rwrsInfo->rwrsInputSizeIndex()) || (entry == rwrsInfo->rwrsMaxInputRowlenIndex()) || (entry == rwrsInfo->rwrsBufferAddrIndex()) || (entry == rwrsInfo->rwrsPartnNumIndex())) { operand = clause->getOperand(0); target = (char *)((atp->getTupp(operand->getAtpIndex())). getDataPointer() + operand->getOffset()); // find the number of rows in the input rowset source = inputDesc->getVarData(entry); if (entry == rwrsInfo->rwrsInputSizeIndex()) { if (source) { // do the conversion str_cpy_all(target, source, sizeof(Lng32)); } else { *(Lng32*)target = inputDesc->getRowwiseRowsetSize(); } inputRowsetSize = *((Lng32 *) target); } else if (entry == rwrsInfo->rwrsMaxInputRowlenIndex()) { if (source) { // do the conversion str_cpy_all(target, source, sizeof(Lng32)); } else { *(Lng32*)target = inputDesc->getRowwiseRowsetRowLen(); } maxInputRowlen = *((Lng32 *) target); rwrsMaxInputRowlenLoc = target; } else if (entry == rwrsInfo->rwrsBufferAddrIndex()) { if (source) { // do the conversion str_cpy_all(target, source, sizeof(Long)); } else { *(Long*)target = inputDesc->getRowwiseRowsetPtr(); } bufferAddr = *((char **) target); // We need to send the address of the rowwise rowset // buffer to other nodes below the root. // It will be determined later in this procedure whether // we can send the buffer address of the application's // rowwise rowset buffer or if we first need to move data // to our internal buffer and send the addr of the internal // buffer. rwrsInternalBufferAddrLoc = (char **)target; } else if (entry == rwrsInfo->rwrsPartnNumIndex()) { partnNum = *((Lng32 *) target); } // skip this INOUT clause during rowset bulk move processing. ((ex_inout_clause*)clause)->setExcludeFromBulkMove(TRUE); } // rwrs info } // if inout clause clause = clause->getNextClause(); } // while clause if ((inputRowsetSize < 0) || (inputRowsetSize > rwrsInfo->rwrsMaxSize())) { //raise error errorCode = (ExeErrorCode)30038; //EXE_RW_ROWSET_SIZE_OUTOF_RANGE; goto error_return; } if (maxInputRowlen < 0) { //raise error errorCode = (ExeErrorCode)30039; //EXE_RW_ROWSET_ROWLEN_OUTOF_RANGE; goto error_return; } if (inputRowsetSize == 0) return ex_expr::EXPR_OK; if (rwrsInfo->rwrsIsCompressed() && rwrsInfo->dcompressInMaster()) { // if not already allocated, allocate a buffer to decompress user buf. Lng32 dcomBufLen = maxInputRowlen * rwrsInfo->rwrsMaxSize(); if ((rwrsInfo->getRWRSDcompressedBufferAddr() == NULL) || (rwrsInfo->getRWRSDcompressedBufferLen() < dcomBufLen)) { if (rwrsInfo->getRWRSDcompressedBufferAddr()) { NADELETEBASIC((char *)rwrsInfo->getRWRSDcompressedBufferAddr(), heap); } char * dcomBuf = new(heap) char[dcomBufLen]; rwrsInfo->setRWRSDcompressedBufferAddr(dcomBuf); rwrsInfo->setRWRSDcompressedBufferLen(dcomBufLen); } // dcompress/decode the user buffer into the dcompressedBuffer. // Length of buffer is in the first 4 bytes of bufferAddr. // Pass the pointer to the length bytes to ExDecode. // Pass the buffer length plus size of length bytes. Lng32 compressedBuflen = *(Lng32 *)bufferAddr + sizeof(Lng32); unsigned char * compressedBuf = (unsigned char *)(bufferAddr); Int32 dcompressedBuflen = -1; Lng32 param1 = 0; Lng32 param2 = 0; Lng32 rc = ExDecode(compressedBuf, compressedBuflen, (unsigned char *)rwrsInfo->getRWRSDcompressedBufferAddr(), &dcompressedBuflen, param1, param2); if (rc) { // error. errorCode = (ExeErrorCode)30045; intParam1 = rc; intParam2 = param1; intParam3 = param2; goto error_return; } if (dcompressedBuflen > rwrsInfo->getRWRSDcompressedBufferLen()) { // error. errorCode = (ExeErrorCode)30046; intParam1 = dcompressedBuflen; intParam2 = rwrsInfo->getRWRSDcompressedBufferLen(); goto error_return; } // change user buffer addr to point to the decompressed buffer bufferAddr = rwrsInfo->getRWRSDcompressedBufferAddr(); } // find out if user rwrs buffer could be passed in to the unpack method. // This could be done : // -- bulk move is not disabled and there are no slow bulk moves // -- user row layout is the same as the internal row // -- there is no mismatch in user and internal column definitions // -- columns in user row could be moved with one bulk move to the // internal buffer // if these conditions are met, then user buffer address, user row length // and number of rows are passed on to the unpack buffer. if (NOT inputDesc->bulkMoveDisabled()) { if (NOT inputDesc->bulkMoveSetup()) { rwrsInfo->setUseUserRWRSBuffer(FALSE); setupBulkMoveInfo(inputDesc, heap, TRUE /* input desc */, flags); if ((NOT inputDesc->bulkMoveDisabled()) && (NOT inputDesc->doSlowMove()) && (inputDesc->bulkMoveInfo()->usedEntries() == 1)) { rwrsInfo->setUseUserRWRSBuffer(TRUE); } } } if (rwrsInfo->useUserRWRSBuffer()) { inputDesc->setDescItem(0, SQLDESC_ROWWISE_ROWSET_SIZE, inputRowsetSize, 0); inputDesc->setDescItem(0, SQLDESC_ROWWISE_ROWSET_ROW_LEN, maxInputRowlen, 0); inputDesc->setDescItem(0, SQLDESC_ROWWISE_ROWSET_PTR, (Long)bufferAddr, 0); inputDesc->setDescItem(0, SQLDESC_ROWWISE_ROWSET_PARTN_NUM, partnNum, 0); inputDesc->setDescItem(0, SQLDESC_ROWSET_NUM_PROCESSED, inputRowsetSize, NULL); // move the address of the user rowwise rowset buffer so it could // be passed on to other operators. *rwrsInternalBufferAddrLoc = bufferAddr; // move the max length of each user row so it could be passed on to // other operators. *rwrsMaxInputRowlenLoc = maxInputRowlen; } else { // error path not taken . This is only if something bad happens in NVT //LCOV_EXCL_START if (isDbtr) { // rowwise rowsets from dbtr *must* use the optimized input // path. Something is not setup correctly, if it doesn't. // Return an error. errorCode = (ExeErrorCode)30041; goto error_return; } inputDesc->setDescItem(0, SQLDESC_ROWWISE_ROWSET_SIZE, inputRowsetSize, 0); inputDesc->setDescItem(0, SQLDESC_ROWWISE_ROWSET_ROW_LEN, maxInputRowlen, 0); inputDesc->setDescItem(0, SQLDESC_ROWWISE_ROWSET_PTR, (Long)bufferAddr, 0); while (numRowsProcessed < inputRowsetSize) { inputDesc->setDescItem(0, SQLDESC_ROWSET_NUM_PROCESSED, numRowsProcessed, NULL); setIsRWRS(flags, TRUE); if (inputSingleRowValue(atp, inputDesc, (char*)tgtRowAddr, heap, flags) == ex_expr::EXPR_ERROR) { errorCode = EXE_OK; goto error_return; } numRowsProcessed++; tgtRowAddr += rwrsInfo->rwrsMaxInternalRowlen(); } // reset rows processed inputDesc->setDescItem(0, SQLDESC_ROWSET_NUM_PROCESSED, 0, NULL); // move the address of the internal rowwise rowset buffer so it could // be passed on to other operators. *rwrsInternalBufferAddrLoc = rwrsInfo->getRWRSInternalBufferAddr(); // move the max length of each row so it could be passed on to other // operators. *rwrsMaxInputRowlenLoc = rwrsInfo->rwrsMaxInternalRowlen(); } // use internal buffer return ex_expr::EXPR_OK; error_return: if (errorCode != EXE_OK) ExRaiseSqlError(heap, &diagsArea, errorCode, NULL, (intParam1 != 0 ? &intParam1 : NULL), (intParam2 != 0 ? &intParam2 : NULL), (intParam3 != 0 ? &intParam3 : NULL)); if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); //LCOV_EXCL_STOP return ex_expr::EXPR_ERROR; } ex_expr::exp_return_type InputOutputExpr::inputValues(atp_struct *atp, void * inputDesc_, NABoolean tolerateNonFatalError, CollHeap * heap, UInt32 flags) { NABoolean isOdbc = isODBC(flags); NABoolean isIFIO = isInternalFormatIO(flags); ex_clause * clause = getClauses(); Descriptor * inputDesc = (Descriptor *)inputDesc_; Attributes * operand = 0; ComDiagsArea *diagsArea = atp->getDiagsArea(); char * target = 0; char * targetVCLenInd = 0; char * targetNullInd = 0; Lng32 targetRowsetSize; Lng32 dynamicRowsetSize = 0; // Specified with ROWSET FOR INPUT SIZE <var> // or some other rowset syntax; <var> can // change at run time char * source = 0; Lng32 sourceLen; char * sourceIndPtr = 0; short sourceType; Lng32 sourcePrecision; Lng32 sourceScale; char * tempSource = 0; Lng32 tempSourceType = 0; Lng32 indData; short entry = 0; char * intermediate = NULL; Lng32 rowsetVarLayoutSize; Lng32 rowsetIndLayoutSize; short savedSourceType = 0; Lng32 savedSourcePrecision = 0; Lng32 savedSourceScale = 0; Lng32 savedSourceLen = 0; // We changed the code here, because the previous version uses // isCall() && isWideDescType() as a condition. isCall() returns FALSE when // there is no paramter index in the expression. So the error was // raised when there is no inputs and there is outputs. // We relax the bypass condition. until we have a fix in the generator that // can put a flag in the root to describe whether it is CALL statement. NABoolean useParamIdx = FALSE; if(!inputDesc) { if(getNumEntries() > 0) { ExRaiseSqlError(heap, &diagsArea, CLI_STMT_DESC_COUNT_MISMATCH); if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); return ex_expr::EXPR_ERROR; } else return ex_expr::EXPR_OK; } else{ useParamIdx = isCall() && inputDesc->isDescTypeWide(); NABoolean byPassCheck = inputDesc->isDescTypeWide(); if (!byPassCheck && !inputDesc->thereIsACompoundStatement() && getNumEntries() != inputDesc->getUsedEntryCount()) { ExRaiseSqlError(heap, &diagsArea, CLI_STMT_DESC_COUNT_MISMATCH); if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); return ex_expr::EXPR_ERROR; } } if (inputDesc && inputDesc->rowwiseRowset()) { //LCOV_EXCL_START ExRaiseSqlError(heap, &diagsArea, CLI_ROWWISE_ROWSETS_NOT_SUPPORTED); if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); return ex_expr::EXPR_ERROR; //LCOV_EXCL_STOP } // If bulk move has not been disabled before, then check to see if bulk // move could be done. This is done by comparing attributes of the // executor items and the descriptor entries. See method // Descriptor::checkBulkMoveStatus() for details on when bulk move will // be disabled. // If bulk move is possible then set up bulk move info, if not already // done. if (NOT inputDesc->bulkMoveDisabled()) { if (NOT inputDesc->bulkMoveSetup()) { setupBulkMoveInfo(inputDesc, heap, TRUE /* input desc */, flags); } if (NOT inputDesc->bulkMoveDisabled()) { // bulk move is enabled and setup has been done. // Do bulk move now. doBulkMove(atp, inputDesc, NULL, TRUE /* input desc */); if (NOT inputDesc->doSlowMove()) return ex_expr::EXPR_OK; } } CharInfo::CharSet sourceCharSet = CharInfo::UnknownCharSet; CharInfo::CharSet targetCharSet = CharInfo::UnknownCharSet; // Note that some of the input operands may participate in rowsets, while // other may not. That is, simple host variables and rowset host variables // can be mixed for input purposes. while (clause) { if (clause->getType() == ex_clause::INOUT_TYPE) { entry++; if ((NOT inputDesc->bulkMoveDisabled()) && (NOT inputDesc->doSlowMove(entry))) goto next_clause; if(useParamIdx){ entry = ((ex_inout_clause *)clause)->getParamIdx(); } operand = clause->getOperand(0); if (operand->isBlankHV()) { clause = clause->getNextClause(); continue; } target = (char *)((atp->getTupp(operand->getAtpIndex())).getDataPointer() + operand->getOffset()); if (operand->getVCIndicatorLength() > 0) targetVCLenInd = (char *)((atp->getTupp(operand->getAtpIndex())).getDataPointer() + operand->getVCLenIndOffset()); if (operand->getNullFlag()) targetNullInd = (atp->getTupp(operand->getAtpIndex())).getDataPointer() + operand->getNullIndOffset(); inputDesc->getDescItem(entry, SQLDESC_TYPE_FS, &tempSourceType, 0, 0, 0, 0); sourceType = (short) tempSourceType; if ((sourceType >= REC_MIN_INTERVAL) && (sourceType <= REC_MAX_INTERVAL)) { inputDesc->getDescItem(entry, SQLDESC_INT_LEAD_PREC, &sourcePrecision, 0, 0, 0, 0); // SQLDESC_PRECISION gets the fractional precision inputDesc->getDescItem(entry, SQLDESC_PRECISION, &sourceScale, 0, 0, 0, 0); } else if (sourceType == REC_DATETIME) { inputDesc->getDescItem(entry, SQLDESC_DATETIME_CODE, &sourcePrecision, 0, 0, 0, 0); inputDesc->getDescItem(entry, SQLDESC_PRECISION, &sourceScale, 0, 0, 0, 0); } else { inputDesc->getDescItem(entry, SQLDESC_PRECISION, &sourcePrecision, 0, 0, 0, 0); inputDesc->getDescItem(entry, SQLDESC_SCALE, &sourceScale, 0, 0, 0, 0); }; if ((sourceType >= REC_MIN_CHARACTER) && (sourceType <= REC_MAX_CHARACTER)) { Lng32 temp_char_set; inputDesc->getDescItem( entry, SQLDESC_CHAR_SET, &temp_char_set, NULL, 0, NULL, 0); sourceCharSet = (CharInfo::CharSet)temp_char_set; sourceScale = temp_char_set; } // 5/18/98: added to handle SJIS encoding charset case. // This is used in ODBC where the target character set is still // ASCII but the actual character set used is SJIS. // short targetType = operand->getDatatype(); targetCharSet = operand->getCharSet(); if ( (targetType == REC_NCHAR_F_UNICODE || targetType == REC_NCHAR_V_UNICODE ) ) { // charset can be retrieved as a long INTERNALLY // using programatic interface by calling getDescItem(), // and can only be retrieved as a character string EXTERNALLY // using "get descriptor" syntax. if ( sourceCharSet == CharInfo::SJIS ) { switch ( sourceType ) { case REC_BYTE_F_ASCII: sourceType = REC_MBYTE_F_SJIS; break; case REC_BYTE_V_ANSI: case REC_BYTE_V_ASCII_LONG: case REC_BYTE_V_ASCII: sourceType = REC_MBYTE_V_SJIS; break; default: break; } } } // ex_expr::exp_return_type retcode = ex_expr::EXPR_OK; // long warningMark; // if (diagsArea) // warningMark= diagsArea->getNumber(DgSqlCode::WARNING_); // else // warningMark = 0; // The following is redefined at a later point for variable length // strings inputDesc->getDescItem(entry, SQLDESC_OCTET_LENGTH, &sourceLen, 0, 0, 0, 0); // Verify that the operand deals with the same rowset as specified // in the descriptor. This check was added since the pre-processor // have had generated different information for the module defintion // file and the cpp file. // Find rowset size, if any targetRowsetSize = operand->getRowsetSize(); if (targetRowsetSize > 0) { // dynamicRowsetSize is specified with ROWSET FOR INPUT SIZE <var> // or some other rowset syntax; <var> can change at run time if (dynamicRowsetSize > targetRowsetSize) { ExRaiseSqlError(heap, &diagsArea, EXE_ROWSET_INDEX_OUTOF_RANGE); if (diagsArea != atp->getDiagsArea()) { atp->setDiagsArea(diagsArea); return ex_expr::EXPR_ERROR; } } if (dynamicRowsetSize > 0) { targetRowsetSize = dynamicRowsetSize; } // do the conversion source = (char *)&targetRowsetSize; if (::convDoIt(source, sizeof(Lng32), REC_BIN32_SIGNED, 0, 0, target, sizeof(Lng32), REC_BIN32_SIGNED, 0, 0, 0, 0 ) != ex_expr::EXPR_OK) { if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); return ex_expr::EXPR_ERROR; } // Increment the location for the next element. target += sizeof(Lng32); if (operand->getNullFlag()) { targetNullInd = target; target += operand->getNullIndicatorLength(); } if (operand->getVCIndicatorLength() > 0) { target += operand->getVCIndicatorLength(); } // save current source and target datatype attributes since // they may get changed later in this method. // Restore them for the next iteration of this for loop. // Do this only for rowsets, for non-rowsets this loop is executed // only once. savedSourceType = sourceType; savedSourcePrecision = sourcePrecision; savedSourceScale = sourceScale; savedSourceLen = sourceLen; } // if (targetRowsetSize > 0) else { inputDesc->getDescItem(entry, SQLDESC_ROWSET_VAR_LAYOUT_SIZE, &rowsetVarLayoutSize, 0, 0, 0, 0); if (rowsetVarLayoutSize > 0) { ExRaiseSqlError(heap, &diagsArea, EXE_ROWSET_SCALAR_ARRAY_MISMATCH); if (diagsArea != atp->getDiagsArea()) { atp->setDiagsArea(diagsArea); return ex_expr::EXPR_ERROR; // Raises an error when query was compiled with scalar param // and array value is passed in at runtime. When query is compiled // with array params and some (not all) values are scalars at runtime // we do not raise an error and we duplicate the scalar value. } } } // else (targetRowsetSize > 0) Lng32 numToProcess = ((targetRowsetSize > 0) ? targetRowsetSize : 1); // Define and clear case indexes potentially used for rowsets conv_case_index index1 = CONV_UNKNOWN; conv_case_index index2 = CONV_UNKNOWN; conv_case_index index3 = CONV_UNKNOWN; for (Lng32 RowNum = 0; RowNum < numToProcess; RowNum++) { // Increment the location for the next element. if ((targetRowsetSize > 0) && (RowNum > 0)) { target += operand->getStorageLength(); if (operand->getVCIndicatorLength() > 0) targetVCLenInd += operand->getStorageLength(); if (operand->getNullFlag()) targetNullInd += operand->getStorageLength(); // restore the original datatype attributes. sourceType = savedSourceType; sourcePrecision = savedSourcePrecision; sourceScale = savedSourceScale; sourceLen = savedSourceLen; } if (targetRowsetSize > 0) inputDesc->setDescItem(0, SQLDESC_ROWSET_HANDLE, RowNum, 0); inputDesc->getDescItem(entry, SQLDESC_IND_DATA, &indData, 0, 0, 0, 0); if (indData == 0) { inputDesc->getDescItem(entry, SQLDESC_IND_PTR, &tempSource, 0, 0, 0, 0); inputDesc->getDescItem(entry, SQLDESC_ROWSET_IND_LAYOUT_SIZE, &rowsetIndLayoutSize, 0, 0, 0, 0); if ((!tempSource) && (rowsetIndLayoutSize > 0)) { ExRaiseSqlError(heap, &diagsArea, EXE_ROWSET_VARDATA_OR_INDDATA_ERROR); if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); return ex_expr::EXPR_ERROR; } } else tempSource = (char *)&indData; sourceIndPtr = tempSource; NABoolean nullMoved = FALSE; if (sourceIndPtr) { short temp = 0; str_cpy_all((char *)&temp, sourceIndPtr, operand->getNullIndicatorLength()); if (inputDesc && inputDesc->thereIsACompoundStatement() && (temp > 0)) { // We may be processing input data with invalid indicators if we // are in an IF statement temp = 0; } if (temp > 0) { // invalid null indicator value. // Valid indicator values are 0(not null value) and // -ve (null value). ExRaiseSqlError(heap, &diagsArea, EXE_CONVERT_STRING_ERROR); if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); setRowNumberInCli(diagsArea, RowNum, targetRowsetSize) ; if (tolerateNonFatalError && diagsArea->canAcceptMoreErrors()) continue; else return ex_expr::EXPR_ERROR; } if (operand->getNullFlag()) { nullMoved = (temp < 0); //if null indicator is a negative //number, the value is null str_cpy_all (targetNullInd, sourceIndPtr, operand->getNullIndicatorLength()); } else { if (temp < 0) { // input is a null value // error. Trying to move a null input value to a // non-nullable buffer. ExRaiseSqlError(heap, &diagsArea, EXE_ASSIGNING_NULL_TO_NOT_NULL); if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); setRowNumberInCli(diagsArea, RowNum, targetRowsetSize) ; if (tolerateNonFatalError && diagsArea->canAcceptMoreErrors()) continue; else return ex_expr::EXPR_ERROR; } } } else { // indicator not specified. if (operand->getNullFlag()) { // move 0 (non-null value) to first two bytes of buffer. str_pad(targetNullInd, operand->getNullIndicatorLength(), '\0'); } } source = inputDesc -> getVarData(entry); if (!source) { continue; } if (DFS2REC::isSQLVarChar(sourceType)) { Lng32 vcIndLen = inputDesc->getVarIndicatorLength(entry); sourceLen = ExpTupleDesc::getVarLength(source, vcIndLen); source = &source[vcIndLen]; } // 12/22/97: added for Unicode Vchar. if (! nullMoved) { ex_expr::exp_return_type retcode = ex_expr::EXPR_OK; Lng32 warningMark; if (diagsArea) warningMark= diagsArea->getNumber(DgSqlCode::WARNING_); else warningMark = 0; NABoolean implicitConversion = FALSE; // if the source and target are not compatible, then do implicit // conversion if skipTypeCheck is set. // Furthermore, if restrictedSkipTypeCheck is set, then only // convert for the conversions that are externally supported. // See usage of default IMPLICIT_HOSTVAR_CONVERSION in generator // (GenExpGenerator.cpp) for restricted conversions. if (NOT areCompatible(sourceType, targetType)) { if ((NOT skipTypeCheck()) || ((restrictedSkipTypeCheck()) && (NOT implicitConversionSupported(sourceType, operand->getDatatype())))) { ExRaiseSqlError(heap, &diagsArea,EXE_CONVERT_NOT_SUPPORTED); if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); setRowNumberInCli(diagsArea, RowNum, targetRowsetSize) ; if (tolerateNonFatalError && diagsArea->canAcceptMoreErrors()) continue; else return ex_expr::EXPR_ERROR; } implicitConversion = TRUE; } else { // check charset for source and target if they are CHARACTER types. if ( DFS2REC::isAnyCharacter(sourceType) && NOT CharInfo::isAssignmentCompatible(sourceCharSet, targetCharSet) ) { ExRaiseSqlError(heap, &diagsArea, CLI_ASSIGN_INCOMPATIBLE_CHARSET); if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); *diagsArea << DgString0(CharInfo::getCharSetName((CharInfo::CharSet)sourceCharSet)) << DgString1(CharInfo::getCharSetName((CharInfo::CharSet)targetCharSet)); setRowNumberInCli(diagsArea, RowNum, targetRowsetSize) ; if (tolerateNonFatalError && diagsArea->canAcceptMoreErrors()) continue; else return ex_expr::EXPR_ERROR; } } // In the case of VARCHARS, we zero out remaining elements if (targetRowsetSize > 0) { Int32 i; if ((sourceType >= REC_MIN_V_N_CHAR_H) && (sourceType <= REC_MAX_V_N_CHAR_H)) { #pragma nowarn(1506) // warning elimination for (i = strlen(source); i < operand->getLength(); i++) { #pragma warn(1506) // warning elimination target[i] = 0; } } if (DFS2REC::isSQLVarChar(sourceType)) { for (i = sourceLen; i < operand->getLength(); i++) { target[i] = 0; } } } // Check length limit for KANJI/KSC5601/UCS2 ANSI VARCHAR (i.e., there // should be a NAWchar typed NULL somewhere in the range [1, sourceLen/2] // in the source. We have to do this for KANJI/KSC because their FS type // codes are shared with the ISO88591 CHARACTER types and the conversion // routines for ISO88591 ANSI VARCHAR in convDoIt() can not verify the // NAWchar nulls. // // We also check the ANSI Unicode source here because we then can safely // use the NAWstrlen() function to obtain the length in the next IF block to // check code points. if ((sourceType == REC_BYTE_V_ANSI && CharInfo::is_NCHAR_MP(sourceCharSet)) || sourceType == REC_NCHAR_V_ANSI_UNICODE ) { Lng32 i = 0; Int32 sourceLenInWchar = sourceLen/SQL_DBCHAR_SIZE; NAWchar* sourceInWchar = (NAWchar*)source; while ((i < sourceLenInWchar) && (sourceInWchar[i] != 0)) i++; if ( i == sourceLenInWchar ) { ExRaiseSqlError(heap, &diagsArea, EXE_MISSING_NULL_TERMINATOR); if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); setRowNumberInCli(diagsArea, RowNum, targetRowsetSize) ; if (tolerateNonFatalError && diagsArea->canAcceptMoreErrors()) continue; else return ex_expr::EXPR_ERROR; }; } if ( DFS2REC::isAnyCharacter(sourceType) && sourceCharSet == CharInfo::UNICODE ) { Lng32 realSourceLen = sourceLen; if (sourceType == REC_NCHAR_V_ANSI_UNICODE) { #pragma nowarn(1506) // warning elimination realSourceLen = NAWstrlen((NAWchar*)source) * SQL_DBCHAR_SIZE; #pragma warn(1506) // warning elimination if ( realSourceLen > sourceLen ) realSourceLen = sourceLen ; } realSourceLen /= SQL_DBCHAR_SIZE; if ( CharInfo::checkCodePoint((NAWchar*)source, realSourceLen, CharInfo::UNICODE ) == FALSE ) { //LCOV_EXCL_START // Error code 3400 falls in CLI error code area, but it is // a perfect fit to use here (as an exeutor error). ExRaiseSqlError(heap, &diagsArea, (ExeErrorCode)3400); if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); *diagsArea << DgString0(SQLCHARSETSTRING_UNICODE); setRowNumberInCli(diagsArea, RowNum, targetRowsetSize) ; if (tolerateNonFatalError && diagsArea->canAcceptMoreErrors()) continue; else return ex_expr::EXPR_ERROR; //LCOV_EXCL_STOP } } // if incompatible conversions are to be done, // and the source is REC_BYTE_V_ANSI, // and the target is not a string type, convert the source to // REC_BYTE_F_ASCII first. Conversion from V_ANSI is currently // only supported if target is a string type. if ((implicitConversion) && ((sourceType == REC_BYTE_V_ANSI) && ((targetType < REC_MIN_CHARACTER) || (targetType > REC_MAX_CHARACTER)))) { intermediate = new (heap) char[sourceLen]; // Initialize index for this convDoIt call, if needed if (index1 == CONV_UNKNOWN) { ex_conv_clause tempClause; index1 = tempClause.find_case_index(sourceType, sourceLen, REC_BYTE_F_ASCII, sourceLen, 0); } if (::convDoIt(source, sourceLen, sourceType, sourcePrecision, sourceScale, intermediate, sourceLen, REC_BYTE_F_ASCII, sourcePrecision, sourceScale, NULL, 0, heap, &diagsArea, index1) != ex_expr::EXPR_OK) { if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); NADELETEBASIC(intermediate, heap); setRowNumberInCli(diagsArea, RowNum, targetRowsetSize) ; if (tolerateNonFatalError && diagsArea->canAcceptMoreErrors()) continue; else return ex_expr::EXPR_ERROR; }; sourceType = REC_BYTE_F_ASCII; source = intermediate; } // sourceType == REC_BYTE_V_ANSI if ((sourceType >= REC_MIN_BINARY) && (sourceType <= REC_MAX_BINARY) && (sourceType == operand->getDatatype()) && (sourcePrecision > 0) && (sourcePrecision == operand->getPrecision())) { // validate source precision. Make the source precision // zero, that will trigger the validation. See method // checkPrecision in exp_conv.cpp. sourcePrecision = 0; } ULng32 convFlags = 0; if ((NOT implicitConversion) && (((sourceType == REC_DATETIME) || ((sourceType >= REC_MIN_INTERVAL) && (sourceType <= REC_MAX_INTERVAL))) && (NOT isIFIO))) { // this is a datetime or interval conversion. // Convert the external string datetime/interval to its // internal format. The conversion follows the // same rules as "CAST(char TO datetime/interval)". // If the two interval types are not the same, then first // convert source from its string to its internal format, // and then convert to the target interval type. if (sourceType == REC_DATETIME) { if ((sourcePrecision != operand->getPrecision()) || (sourceScale != operand->getScale())) { // source and target must have the same datetime_code, // they must both be date, time or timestamp. ExRaiseSqlError(heap, &diagsArea, EXE_CONVERT_NOT_SUPPORTED); if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); setRowNumberInCli(diagsArea, RowNum, targetRowsetSize) ; if (tolerateNonFatalError && diagsArea->canAcceptMoreErrors()) continue; else return ex_expr::EXPR_ERROR; } else { sourceType = REC_BYTE_F_ASCII; sourcePrecision = 0; // TBD $$$$ add source max chars later sourceScale = SQLCHARSETCODE_ISO88591; // assume target charset is ASCII-compatible convFlags |= CONV_NO_HADOOP_DATE_FIX; } } else if ((sourceType == targetType) && (sourcePrecision == operand->getPrecision()) && (sourceScale == operand->getScale())) { // 'interval' source and target match all attributes. // Convert source(string external) to target(internal) format sourceType = REC_BYTE_F_ASCII; sourcePrecision = 0; // TBD $$$$ add source max chars later sourceScale = SQLCHARSETCODE_ISO88591; // assume target charset is ASCII-compatible convFlags |= CONV_ALLOW_SIGN_IN_INTERVAL; } else { // interval type and source/target do not match. // Convert source string interval to corresponding // internal format. short intermediateLen = SQL_LARGE_SIZE; intermediate = new (heap) char[intermediateLen]; convFlags |= CONV_ALLOW_SIGN_IN_INTERVAL; // Initialize index for this convDoIt call, if needed if (index2 == CONV_UNKNOWN) { ex_conv_clause tempClause; index2 = tempClause.find_case_index(REC_BYTE_F_ASCII, sourceLen, sourceType, intermediateLen, 0 - sourceScale); } if (noDatetimeValidation()) convFlags |= CONV_NO_DATETIME_VALIDATION; if (::convDoIt(source, sourceLen, REC_BYTE_F_ASCII, 0, //sourcePrecision, 0, //sourceScale, intermediate, intermediateLen, sourceType, sourcePrecision, sourceScale, NULL, 0, heap, &diagsArea, index2, 0, convFlags) != ex_expr::EXPR_OK) { if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); NADELETEBASIC(intermediate, heap); setRowNumberInCli(diagsArea, RowNum, targetRowsetSize) ; if (tolerateNonFatalError && diagsArea->canAcceptMoreErrors()) continue; else return ex_expr::EXPR_ERROR; }; source = intermediate; sourceLen = intermediateLen; } } // Initialize index for this convDoIt call, if needed if (index3 == CONV_UNKNOWN) { ex_conv_clause tempClause; index3 = tempClause.find_case_index(sourceType, sourceLen, operand->getDatatype(), operand->getLength(), sourceScale - operand->getScale()); } if (noDatetimeValidation()) convFlags |= CONV_NO_DATETIME_VALIDATION; retcode = ::convDoIt(source, sourceLen, sourceType, sourcePrecision, sourceScale, target, operand->getLength(), operand->getDatatype(), operand->getPrecision(), operand->getScale(), targetVCLenInd, operand->getVCIndicatorLength(), heap, &diagsArea, index3, 0, convFlags); // NADELETEBASIC(intermediate, heap); if (retcode != ex_expr::EXPR_OK) { if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); setRowNumberInCli(diagsArea, RowNum, targetRowsetSize) ; if (tolerateNonFatalError && diagsArea->canAcceptMoreErrors()) continue; else return ex_expr::EXPR_ERROR; } else if (diagsArea && diagsArea->mainSQLCODE() == EXE_STRING_OVERFLOW) { Int32 warningMark2 = diagsArea->getNumber(DgSqlCode::WARNING_); Int32 counter = warningMark2 - warningMark; diagsArea->deleteWarning(warningMark2-counter); ExRaiseSqlError(heap, &diagsArea, EXE_STRING_OVERFLOW); if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); setRowNumberInCli(diagsArea, RowNum, targetRowsetSize) ; if (tolerateNonFatalError && diagsArea->canAcceptMoreErrors()) continue; else return ex_expr::EXPR_ERROR; } // If the query contains ROWSET FOR INPUT SIZE <var> or // ROWSET <var> ( <list> ) then we get the number of entries // from <var> if (operand->getHVRowsetForInputSize() || operand->getHVRowsetLocalSize()) { short targetType = operand->getDatatype(); switch (targetType) { case REC_BIN8_SIGNED : if (*((Int8 *) target) <= 0) { //raise error ExRaiseSqlError(heap, &diagsArea, EXE_ROWSET_NEGATIVE_SIZE); if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); return ex_expr::EXPR_ERROR; } else { dynamicRowsetSize = *((Int8 *) target); break; } case REC_BIN8_UNSIGNED : if (*((UInt8 *) target) == 0) { //raise error ExRaiseSqlError(heap, &diagsArea, EXE_ROWSET_NEGATIVE_SIZE); if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); return ex_expr::EXPR_ERROR; } else { dynamicRowsetSize = *((UInt8 *) target); break; } case REC_BIN16_SIGNED : if (*((short *) target) <= 0) { //raise error ExRaiseSqlError(heap, &diagsArea, EXE_ROWSET_NEGATIVE_SIZE); if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); return ex_expr::EXPR_ERROR; } else { dynamicRowsetSize = *((short *) target); break; } case REC_BIN16_UNSIGNED : if (*((unsigned short *) target) == 0) { //raise error ExRaiseSqlError(heap, &diagsArea, EXE_ROWSET_NEGATIVE_SIZE); if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); return ex_expr::EXPR_ERROR; } else { dynamicRowsetSize = *((unsigned short *) target); break; } case REC_BIN32_SIGNED : if (*((Lng32 *) target) <= 0) { //raise error ExRaiseSqlError(heap, &diagsArea, EXE_ROWSET_NEGATIVE_SIZE); if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); return ex_expr::EXPR_ERROR; } else { dynamicRowsetSize = *((Lng32 *) target); //long is the same as int break; } case REC_BIN32_UNSIGNED : if (*((ULng32 *) target) == 0) { // unsigned long is the same as unsigned int //raise error ExRaiseSqlError(heap, &diagsArea, EXE_ROWSET_NEGATIVE_SIZE); if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); return ex_expr::EXPR_ERROR; } else { #pragma nowarn(1506) // warning elimination dynamicRowsetSize = *((ULng32 *) target); #pragma warn(1506) // warning elimination break; } default: //raise error ExRaiseSqlError(heap, &diagsArea,EXE_ROWSET_WRONG_SIZETYPE); if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); return ex_expr::EXPR_ERROR; } } // up- or down-scale target, if there is a difference // in scale, but be careful to ignore scale used as charset if ((operand->getDatatype() >= REC_MIN_NUMERIC) && (operand->getDatatype() <= REC_MAX_NUMERIC) && (sourceScale != operand->getScale()) && ::scaleDoIt(target, operand->getLength(), operand->getDatatype(), sourceScale, operand->getScale(), sourceType, heap) != ex_expr::EXPR_OK) { ExRaiseSqlError(heap, &diagsArea, EXE_NUMERIC_OVERFLOW); if (diagsArea != atp->getDiagsArea()) atp->setDiagsArea(diagsArea); setRowNumberInCli(diagsArea, RowNum, targetRowsetSize) ; if (tolerateNonFatalError && diagsArea->canAcceptMoreErrors()) continue; else return ex_expr::EXPR_ERROR; } } // if (! nullMoved) } // loop over rowset elements (RowNum) } // if clause == IN_OUT type next_clause: clause = clause->getNextClause(); } // while(clause) return ex_expr::EXPR_OK; } #pragma warning (disable : 4273) //warning elimination Lng32 InputOutputExpr::getCompiledOutputRowsetSize(atp_struct *atp) { ex_clause * clause = getClauses(); Attributes * operand; Lng32 sourceRowsetSize = 0; // Note that every output operands must participate in rowsets, or none of // them. That is, you cannot mix rowset host variables and simple host // variables for output purposes (INTO clause). if (clause) { operand = clause->getOperand(0); sourceRowsetSize = operand->getRowsetSize(); } return sourceRowsetSize; } #pragma warning (default : 4273) //warning elimination ex_expr::exp_return_type InputOutputExpr::addDescInfoIntoStaticDesc (Descriptor * desc, NABoolean isInput) { ex_clause *clause = getClauses(); short entry = 0; if(isCall() && desc->isDescTypeWide()){ while(clause){ if(clause->getType() == ex_clause::INOUT_TYPE){ entry = ((ex_inout_clause *)clause)->getParamIdx(); if(entry > desc->getUsedEntryCount()) continue; desc->setDescItem(entry, SQLDESC_NAME, 0, ((ex_inout_clause *)clause)->getName()); short paramMode = ((ex_inout_clause *)clause)->getParamMode(); short ordPos = ((ex_inout_clause *)clause)->getOrdPos(); desc->setDescItem(entry, SQLDESC_PARAMETER_MODE, paramMode, 0); desc->setDescItem(entry, SQLDESC_PARAMETER_INDEX, entry, 0); desc->setDescItem(entry, SQLDESC_ORDINAL_POSITION, ordPos, 0); } clause = clause->getNextClause(); } } else if(isCall() && !desc->isDescTypeWide()){ while (clause && entry < desc->getUsedEntryCount()){ if (clause->getType() == ex_clause::INOUT_TYPE){ entry++; desc->setDescItem(entry, SQLDESC_NAME, 0, ((ex_inout_clause *)clause)->getName()); short paramMode = ((ex_inout_clause *)clause)->getParamMode(); short paramIdx = ((ex_inout_clause *)clause)->getParamIdx(); short ordPos = ((ex_inout_clause *)clause)->getOrdPos(); desc->setDescItem(entry, SQLDESC_PARAMETER_MODE, paramMode, 0); desc->setDescItem(entry, SQLDESC_PARAMETER_INDEX, paramIdx, 0); desc->setDescItem(entry, SQLDESC_ORDINAL_POSITION, ordPos, 0); } clause = clause->getNextClause(); } } else{ while (clause && entry < desc->getUsedEntryCount()){ if (clause->getType() == ex_clause::INOUT_TYPE){ entry++; desc->setDescItem(entry, SQLDESC_NAME, 0, ((ex_inout_clause *)clause)->getName()); if(isInput) desc->setDescItem(entry, SQLDESC_PARAMETER_MODE, PARAMETER_MODE_IN, 0); else desc->setDescItem(entry, SQLDESC_PARAMETER_MODE, PARAMETER_MODE_OUT, 0); desc->setDescItem(entry, SQLDESC_PARAMETER_INDEX, entry, 0); desc->setDescItem(entry, SQLDESC_ORDINAL_POSITION, 0, 0); } clause = clause->getNextClause(); } } return ex_expr::EXPR_OK; } Lng32 InputOutputExpr::getMaxParamIdx() { Lng32 maxParamIdx = 0; ex_clause *clause = getClauses(); while(clause){ if(clause->getType() == ex_clause::INOUT_TYPE){ Lng32 paramIdx = ((ex_inout_clause *)clause)->getParamIdx(); if(paramIdx > maxParamIdx) maxParamIdx = paramIdx; } clause = clause->getNextClause(); } return maxParamIdx; }
robertamarton/incubator-trafodion
core/sql/cli/CliExpExchange.cpp
C++
apache-2.0
152,514
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gbif.common.parsers.date; import org.gbif.common.parsers.core.ParseResult; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.Month; import java.time.Year; import java.time.YearMonth; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.temporal.ChronoField; import java.time.temporal.TemporalAccessor; import java.util.function.Function; import javax.annotation.Nullable; import org.junit.jupiter.api.Test; import static org.gbif.common.parsers.utils.CSVBasedAssertions.assertTestFile; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; /** * Unit testing for ThreeTenNumericalDateParser. */ public class ThreeTenNumericalDateParserTest { private static final String BADDATE_TEST_FILE = "parse/date/threeten_bad_date_tests.txt"; private static final String LOCALDATE_TEST_FILE = "parse/date/threeten_localdate_tests.txt"; private static final String LOCALDATETIME_TEST_FILE = "parse/date/threeten_localdatetime_tests.txt"; private static final String LOCALDATETIME_TZ_TEST_FILE = "parse/date/local_datetime_tz_tests.txt"; private static final int RAW_VAL_IDX = 0; private static final int YEAR_VAL_IDX = 1; private static final int MONTH_VAL_IDX = 2; private static final int DAY_VAL_IDX = 3; private static final int HOUR_VAL_IDX = 4; private static final int MIN_VAL_IDX = 5; private static final int SEC_VAL_IDX = 6; private static final int NS_VAL_IDX = 7; private static final int TZ_VAL_IDX = 8; private static final TemporalParser PARSER = ThreeTenNumericalDateParser.newInstance(); @Test public void testLocalDateFromFile() { assertTestFile(LOCALDATE_TEST_FILE, new Function<String[], Void>() { @Nullable @Override public Void apply(@Nullable String[] row) { String raw = row[RAW_VAL_IDX]; try { int year = Integer.parseInt(row[YEAR_VAL_IDX]); int month = Integer.parseInt(row[MONTH_VAL_IDX]); int day = Integer.parseInt(row[DAY_VAL_IDX]); ParseResult<TemporalAccessor> result = PARSER.parse(raw); assertNotNull(result.getPayload(), raw + " generated null payload"); assertEquals(LocalDate.of(year, month, day), LocalDate.from(result.getPayload()), "Test file rawValue: " + raw); } catch (NumberFormatException nfEx){ fail("Error while parsing the test input file content." + nfEx.getMessage()); } return null; } }); } @Test public void testLocalDateTimeFromFile() { assertTestFile(LOCALDATETIME_TEST_FILE, new Function<String[], Void>() { @Nullable @Override public Void apply(@Nullable String[] row) { String raw = row[RAW_VAL_IDX]; try { int year = Integer.parseInt(row[YEAR_VAL_IDX]); int month = Integer.parseInt(row[MONTH_VAL_IDX]); int day = Integer.parseInt(row[DAY_VAL_IDX]); int hour = Integer.parseInt(row[HOUR_VAL_IDX]); int minute = Integer.parseInt(row[MIN_VAL_IDX]); int second = Integer.parseInt(row[SEC_VAL_IDX]); int nanosecond = Integer.parseInt(row[NS_VAL_IDX]); ParseResult<TemporalAccessor> result = PARSER.parse(raw); assertNotNull(result.getPayload(), raw + " generated null payload"); assertEquals(LocalDateTime.of(year, month, day, hour, minute, second, nanosecond), LocalDateTime.from(result.getPayload()), "Test file rawValue: " + raw); } catch (NumberFormatException nfEx) { fail("Error while parsing the test input file content." + nfEx.getMessage()); } return null; } }); } @Test public void testLocalDateTimeWithTimezoneFromFile() { assertTestFile(LOCALDATETIME_TZ_TEST_FILE, new Function<String[], Void>() { @Nullable @Override public Void apply(@Nullable String[] row) { String raw = row[RAW_VAL_IDX]; try { int year = Integer.parseInt(row[YEAR_VAL_IDX]); int month = Integer.parseInt(row[MONTH_VAL_IDX]); int day = Integer.parseInt(row[DAY_VAL_IDX]); int hour = Integer.parseInt(row[HOUR_VAL_IDX]); int minute = Integer.parseInt(row[MIN_VAL_IDX]); int second = Integer.parseInt(row[SEC_VAL_IDX]); int millisecond = Integer.parseInt(row[NS_VAL_IDX]); String zoneId = row[TZ_VAL_IDX]; ParseResult<TemporalAccessor> result = PARSER.parse(raw); assertNotNull(result.getPayload(), raw + " generated null payload"); assertEquals(ZonedDateTime.of(year, month, day, hour, minute, second, 0, ZoneId.of(zoneId)).with(ChronoField.MILLI_OF_SECOND, millisecond), ZonedDateTime.from(result.getPayload()), "Test file rawValue: " + raw); } catch (NumberFormatException nfEx) { fail("Error while parsing the test input file content." + nfEx.getMessage()); } return null; } }); } @Test public void testBadDateFromFile() { assertTestFile(BADDATE_TEST_FILE, new Function<String[], Void>() { @Nullable @Override public Void apply(@Nullable String[] row) { assertEquals(ParseResult.STATUS.FAIL, PARSER.parse(row[RAW_VAL_IDX]).getStatus(), "Test file rawValue: " + row[RAW_VAL_IDX]); return null; } }); } @Test public void testParseAsLocalDateTime() { ThreeTenNumericalDateParser parser = ThreeTenNumericalDateParser.newInstance(Year.of(1900)); // month first with 2 digits years >_< assertEquals(LocalDate.of(1978, Month.DECEMBER, 21), LocalDate.from(parser.parse("122178").getPayload())); assertEquals(LocalDate.of(1978, Month.DECEMBER, 21), LocalDate.from(parser.parse("12/21/78").getPayload())); assertEquals(LocalDate.of(1978, Month.DECEMBER, 21), LocalDate.from(parser.parse("12\\21\\78").getPayload())); assertEquals(LocalDate.of(1978, Month.DECEMBER, 21), LocalDate.from(parser.parse("12.21.78").getPayload())); assertEquals(LocalDate.of(1978, Month.DECEMBER, 21), LocalDate.from(parser.parse("12-21-78").getPayload())); assertEquals(LocalDate.of(1978, Month.DECEMBER, 21), LocalDate.from(parser.parse("12_21_78").getPayload())); // month/year alone assertEquals(YearMonth.of(1978, 12), YearMonth.from(parser.parse("1978-12").getPayload())); // year alone assertEquals(Year.of(1978), Year.from(parser.parse("1978").getPayload())); // assertEquals(Year.of(1978), Year.from(parser.parse("78").getPayload())); } @Test public void testParseAsLocalDateByDateParts() { assertEquals(LocalDate.of(1978, Month.DECEMBER, 21), LocalDate.from(PARSER.parse("1978", "12", "21").getPayload())); assertEquals(LocalDate.of(1978, Month.DECEMBER, 21), LocalDate.from(PARSER.parse(1978, 12, 21).getPayload())); assertEquals(LocalDate.of(1978, Month.DECEMBER, 1), LocalDate.from(PARSER.parse("1978", "12", "1").getPayload())); assertEquals(YearMonth.of(1978, 12), YearMonth.from(PARSER.parse("1978", "12", null).getPayload())); assertEquals(YearMonth.of(1978, 12), YearMonth.from(PARSER.parse(1978, 12, null).getPayload())); assertEquals(Year.of(1978), Year.from(PARSER.parse("1978", "", null).getPayload())); // providing the day without the month should result in an error assertEquals(ParseResult.STATUS.FAIL, PARSER.parse("1978", "", "2").getStatus()); assertEquals(ParseResult.STATUS.FAIL, PARSER.parse(1978, null, 2).getStatus()); } // @Ignore("not implemented yet") // @Test // public void testUnsupportedFormat() { // ParseResult<TemporalAccessor> result = PARSER.parse("16/11/1996 0:00:00"); // // System.out.println(PARSER.parse("1996-11-16T00:00:00")); // } @Test public void testParsePreserveZoneOffset() { ZonedDateTime offsetDateTime = ZonedDateTime.of(1978, 12, 21, 0, 0, 0, 0, ZoneOffset.of("+02:00")); assertEquals(offsetDateTime, PARSER.parse("1978-12-21T00:00:00+02:00").getPayload()); } @Test public void testAmbiguousDates() { ParseResult<TemporalAccessor> result; // Ambiguous result = PARSER.parse("1/2/1996"); assertNull(result.getPayload()); assertEquals(2, result.getAlternativePayloads().size()); assertTrue(result.getAlternativePayloads().contains(LocalDate.of(1996, 2, 1))); assertTrue(result.getAlternativePayloads().contains(LocalDate.of(1996, 1, 2))); // Not ambiguous result = PARSER.parse("1/1/1996"); assertEquals(LocalDate.of(1996, 1, 1), result.getPayload()); assertNull(result.getAlternativePayloads()); result = PARSER.parse("31/1/1996"); assertEquals(LocalDate.of(1996, 1, 31), result.getPayload()); assertNull(result.getAlternativePayloads()); // Dots aren't used in America. result = PARSER.parse("4.5.1996"); assertEquals(LocalDate.of(1996, 5, 4), result.getPayload()); assertNull(result.getAlternativePayloads()); } @Test public void testBlankDates() { assertEquals(ParseResult.STATUS.FAIL, PARSER.parse(" ").getStatus()); assertEquals(ParseResult.STATUS.FAIL, PARSER.parse("").getStatus()); assertEquals(ParseResult.STATUS.FAIL, PARSER.parse(null).getStatus()); } }
gbif/parsers
src/test/java/org/gbif/common/parsers/date/ThreeTenNumericalDateParserTest.java
Java
apache-2.0
10,688
<?php /* * Copyright 2013 Johannes M. Schmitt <schmittjoh@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace JMS\Serializer\Annotation; /** * @Annotation * @Target("CLASS") */ class Discriminator { /** @var array<string> */ public $map; /** @var string */ public $field = 'type'; /** @var boolean */ public $disabled = false; /** @var boolean */ public $xmlAttribute = false; }
apa-opensource/serializer
src/JMS/Serializer/Annotation/Discriminator.php
PHP
apache-2.0
952
/** * JBoss, Home of Professional Open Source. * Copyright 2014-2020 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.pnc.mapper.api; import org.jboss.pnc.dto.DTOEntity; import org.jboss.pnc.model.GenericEntity; import java.io.Serializable; /** * Mappers that converts database entity to DTO entities and vice versa. * * @author Honza Brázdil &lt;jbrazdil@redhat.com&gt; * @param <ID> The type of the entity identifier * @param <DB> The database entity type * @param <DTO> The full DTO entity type * @param <REF> The reference DTO entity type */ public interface EntityMapper<ID extends Serializable, DB extends GenericEntity<ID>, DTO extends REF, REF extends DTOEntity> { /** * Converts DTO entity to database entity. This should be used only when creating new entity. * * @param dtoEntity DTO entity to be converted. * @return Converted database entity. */ DB toEntity(DTO dtoEntity); /** * Converts database entity to DTO entity. * * @param dbEntity database entity to be converted. * @return Converted DTO entity. */ DTO toDTO(DB dbEntity); /** * Converts database entity to DTO reference entity. * * @param dbEntity database entity to be converted. * @return Converted DTO reference entity. */ REF toRef(DB dbEntity); IdMapper<ID, String> getIdMapper(); }
thescouser89/pnc
mapper/src/main/java/org/jboss/pnc/mapper/api/EntityMapper.java
Java
apache-2.0
1,989
/* * #%L * wcm.io * %% * Copyright (C) 2016 wcm.io * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.wcm.config.spi.helpers; import java.lang.reflect.Field; import java.util.HashSet; import java.util.Set; import org.osgi.annotation.versioning.ConsumerType; import com.google.common.collect.ImmutableSet; import io.wcm.config.api.Parameter; import io.wcm.config.spi.ParameterProvider; /** * Abstract implementation of {@link ParameterProvider} providing list of parameters either from given * parameter set, or from reading all public static fields from a given class definition. */ @ConsumerType public abstract class AbstractParameterProvider implements ParameterProvider { private final Set<Parameter<?>> parameters; /** * @param parameters Set of parameters for parameter provider */ protected AbstractParameterProvider(Set<Parameter<?>> parameters) { this.parameters = parameters; } /** * @param type Type containing parameter definitions as public static fields. */ protected AbstractParameterProvider(Class<?> type) { this(getParametersFromPublicFields(type)); } @Override public final Set<Parameter<?>> getParameters() { return parameters; } /** * Get all parameters defined as public static fields in the given type. * @param type Type * @return Set of parameters */ private static Set<Parameter<?>> getParametersFromPublicFields(Class<?> type) { Set<Parameter<?>> params = new HashSet<>(); try { Field[] fields = type.getFields(); for (Field field : fields) { if (field.getType().isAssignableFrom(Parameter.class)) { params.add((Parameter<?>)field.get(null)); } } } catch (IllegalArgumentException | IllegalAccessException ex) { throw new RuntimeException("Unable to access fields of " + type.getName(), ex); } return ImmutableSet.copyOf(params); } }
shadyeltobgy/wcm-io-caconfig
compat/src/main/java/io/wcm/config/spi/helpers/AbstractParameterProvider.java
Java
apache-2.0
2,448
/** * Created by fuliang on 2015/4/22. */ public class UniquePaths { public int uniquePaths(int m, int n) { int[][] nums = new int[m][n]; for (int i = 0; i < nums.length; i++) { nums[i][0] = 1; } for (int j = 0; j < nums[0].length; j++) { nums[0][j] = 1; } for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { nums[i][j] = nums[i-1][j] + nums[i][j-1]; } } return nums[m-1][n-1]; } }
fuliang/leetcode
src/UniquePaths.java
Java
apache-2.0
556
package com.planet_ink.coffee_mud.Locales; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2000-2014 Bo Zimmerman Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ @SuppressWarnings({"unchecked","rawtypes"}) public class StdMaze extends StdGrid { @Override public String ID(){return "StdMaze";} public StdMaze() { super(); } @Override protected Room getGridRoom(int x, int y) { final Room R=super.getGridRoom(x,y); if((R!=null)&&(!CMath.bset(R.phyStats().sensesMask(),PhyStats.SENSE_ROOMUNEXPLORABLE))) { R.basePhyStats().setSensesMask(R.basePhyStats().sensesMask()|PhyStats.SENSE_ROOMUNEXPLORABLE); R.phyStats().setSensesMask(R.phyStats().sensesMask()|PhyStats.SENSE_ROOMUNEXPLORABLE); } return R; } @Override protected Room findCenterRoom(int dirCode) { final Room dirRoom=rawDoors()[dirCode]; if(dirRoom!=null) { final Room altR=super.findCenterRoom(dirCode); if(altR!=null) { final Exit ox=CMClass.getExit("Open"); linkRoom(altR,dirRoom,dirCode,ox,ox); return altR; } } return null; } protected boolean goodDir(int x, int y, int dirCode) { if(dirCode==Directions.UP) return false; if(dirCode==Directions.DOWN) return false; if(dirCode>=Directions.GATE) return false; if((x==0)&&(dirCode==Directions.WEST)) return false; if((y==0)&&(dirCode==Directions.NORTH)) return false; if((x>=(subMap.length-1))&&(dirCode==Directions.EAST)) return false; if((y>=(subMap[0].length-1))&&(dirCode==Directions.SOUTH)) return false; return true; } protected Room roomDir(int x, int y, int dirCode) { if(!goodDir(x,y,dirCode)) return null; return subMap[getX(x,dirCode)][getY(y,dirCode)]; } protected int getY(int y, int dirCode) { switch(dirCode) { case Directions.NORTH: return y-1; case Directions.SOUTH: return y+1; } return y; } protected int getX(int x, int dirCode) { switch(dirCode) { case Directions.EAST: return x+1; case Directions.WEST: return x-1; } return x; } protected void mazify(Hashtable visited, int x, int y) { if(visited.get(subMap[x][y])!=null) return; final Room room=subMap[x][y]; visited.put(room,room); final Exit ox=CMClass.getExit("Open"); boolean okRoom=true; while(okRoom) { okRoom=false; for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--) { if(d==Directions.GATE) continue; final Room possRoom=roomDir(x,y,d); if(possRoom!=null) if(visited.get(possRoom)==null) { okRoom=true; break; } } if(okRoom) { Room goRoom=null; int dirCode=-1; while(goRoom==null) { final int d=CMLib.dice().roll(1,Directions.NUM_DIRECTIONS(),0)-1; final Room possRoom=roomDir(x,y,d); if(possRoom!=null) if(visited.get(possRoom)==null) { goRoom=possRoom; dirCode=d; } } linkRoom(room,goRoom,dirCode,ox,ox); mazify(visited,getX(x,dirCode),getY(y,dirCode)); } } } protected void buildMaze() { final Hashtable visited=new Hashtable(); final int x=xsize/2; final int y=ysize/2; mazify(visited,x,y); } @Override public void buildGrid() { clearGrid(null); try { subMap=new Room[xsize][ysize]; for(int x=0;x<subMap.length;x++) for(int y=0;y<subMap[x].length;y++) { final Room newRoom=getGridRoom(x,y); if(newRoom!=null) subMap[x][y]=newRoom; } buildMaze(); buildFinalLinks(); } catch(final Exception e) { clearGrid(null); } } }
vjanmey/EpicMudfia
com/planet_ink/coffee_mud/Locales/StdMaze.java
Java
apache-2.0
4,718
// checking initialization of static template data memebers template <class T> struct S { static T a; static T b; }; template <class T> T S<T>::a; // <-- NOT initialized template <class T> T S<T>::b = 0; // <-- explicitly initialized int main () { // g++ on DEC OSF and IBM AIX fails to link return S<char>::a + S<char>::b; }
apache/stdcxx
etc/config/src/STATIC_TEMPLATE_MEMBER_INIT.cpp
C++
apache-2.0
356
/* * Copyright (c) 2013-2019 Cinchapi Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cinchapi.common.concurrent; import java.util.Arrays; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RunnableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.stream.Collectors; import com.cinchapi.common.base.Array; import com.google.common.base.Preconditions; /** * An {@link ExecutorRaceService} provides a mechanism for submitting multiple * {@link Callable tasks} to an {@link Executor} and waiting for the first task * to complete. * <p> * This is similar to a {@link ExecutorCompletionService} but the semantics are * slightly different. Central to this service is the concept of "racing". As * such, it is possible to give one task an arbitrary * {@link #raceWithHeadStart(long, TimeUnit, Callable, Callable...) head start} * so that other tasks do not execute if that task completes first. * </p> * * @author Jeff Nelson */ public class ExecutorRaceService<V> { /** * The {@link Executor} that executes the tasks. */ private final Executor executor; /** * Construct a new instance. * * @param executor */ public ExecutorRaceService(Executor executor) { this.executor = executor; } /** * Return the {@link Future} for the first of the {@code task} and * {@code tasks} to complete. * <p> * The {@link Future} is guaranteed to be {@link Future#isDone()} when this * method returns. * </p> * * @param task * @param tasks * @return the {@link Future} of the completed task * @throws InterruptedException */ @SuppressWarnings("unchecked") public Future<V> race(Callable<V> task, Callable<V>... tasks) throws InterruptedException { return raceWithHeadStart(0, TimeUnit.MICROSECONDS, task, tasks); } /** * Return the {@link Future} for the first of the {@code task} and * {@code tasks} to complete. * <p> * The {@link Future} is guaranteed to be {@link Future#isDone()} when this * method returns. * </p> * * @param task * @param tasks * @return the {@link Future} of the completed task * @throws InterruptedException */ public Future<V> race(Runnable task, Runnable... tasks) throws InterruptedException { return raceWithHeadStart(0, TimeUnit.MICROSECONDS, task, tasks); } /** * Return the {@link Future} for the first of the {@code headStartTask} and * {@code tasks} to complete; giving the first {@code task} * {@code headStartTime} {@code headStartTimeUnit} to complete before * allowing the remaining {@code tasks} to race. * <p> * Even if the {@code headStartTask} does not finish within the head start * period, it may still finish before the other {@code tasks} and returns * its {@link Future}. * </p> * <p> * The {@link Future} is guaranteed to be {@link Future#isDone()} when this * method returns. * </p> * * @param headStartTime * @param headStartTimeUnit * @param headStartTask * @param tasks * @return the {@link Future} of the completed task * @throws InterruptedException */ @SuppressWarnings("unchecked") public Future<V> raceWithHeadStart(long headStartTime, TimeUnit headStartTimeUnit, Callable<V> headStartTask, Callable<V>... tasks) throws InterruptedException { BlockingQueue<Future<V>> completed = new LinkedBlockingQueue<Future<V>>(); Preconditions.checkNotNull(headStartTask); Preconditions.checkState(tasks.length > 0); RunnableFuture<V> headStartFuture = new FutureTask<V>(headStartTask); executor.execute(new QueueingFuture(headStartFuture, completed)); try { headStartFuture.get(headStartTime, headStartTimeUnit); return headStartFuture; } catch (ExecutionException | TimeoutException e) { for (Callable<V> task : tasks) { RunnableFuture<V> future = new FutureTask<V>(task); executor.execute(new QueueingFuture(future, completed)); } return completed.take(); } } /** * Return the {@link Future} for the first of the {@code headStartTask} and * {@code tasks} to complete; giving the first {@code task} * {@code headStartTime} {@code headStartTimeUnit} to complete before * allowing the remaining {@code tasks} to race. * <p> * Even if the {@code headStartTask} does not finish within the head start * period, it may still finish before the other {@code tasks} and returns * its {@link Future}. * </p> * <p> * The {@link Future} is guaranteed to be {@link Future#isDone()} when this * method returns. * </p> * * @param headStartTime * @param headStartTimeUnit * @param headStartTask * @param tasks * @return the {@link Future} of the completed task * @throws InterruptedException */ public Future<V> raceWithHeadStart(long headStartTime, TimeUnit headStartTimeUnit, Runnable headStartTask, Runnable... tasks) throws InterruptedException { return raceWithHeadStart(headStartTime, headStartTimeUnit, Executors.callable(headStartTask, null), Arrays.stream(tasks).map(Executors::callable) .collect(Collectors.toList()) .toArray(Array.containing())); } /** * FutureTask extension to enqueue upon completion */ private class QueueingFuture extends FutureTask<Void> { /** * The queue of completed tasks where this one should be added when it * is {@link #done()}. */ private final BlockingQueue<Future<V>> completed; /** * The future that tracks the task completion. */ private final Future<V> task; /** * Construct a new instance. * * @param task * @param completed */ QueueingFuture(RunnableFuture<V> task, BlockingQueue<Future<V>> completed) { super(task, null); this.task = task; this.completed = completed; } @Override protected void done() { completed.add(task); } } }
cinchapi/accent4j
src/main/java/com/cinchapi/common/concurrent/ExecutorRaceService.java
Java
apache-2.0
7,355
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * Copyright 2012-2021 the original author or authors. */ package org.assertj.core.util.introspection; import static java.lang.String.format; import static java.lang.reflect.Modifier.isPublic; import static java.util.Locale.ENGLISH; import static java.util.Objects.requireNonNull; import static org.assertj.core.util.Preconditions.checkNotNullOrEmpty; import static org.assertj.core.util.Strings.quote; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import org.assertj.core.configuration.ConfigurationProvider; import org.assertj.core.util.VisibleForTesting; /** * Utility methods related to <a * href="http://java.sun.com/docs/books/tutorial/javabeans/introspection/index.html">JavaBeans Introspection</a>. * * @author Alex Ruiz */ public final class Introspection { // We want to cache negative results (i.e. absence of methods) to avoid same overhead on subsequent lookups // However ConcurrentHashMap does not permit nulls - Optional allows caching of 'missing' values private static final Map<MethodKey, Optional<Method>> METHOD_CACHE = new ConcurrentHashMap<>(); // set false by default to follow the principle of least surprise as usual property getter are getX() isX(), not x(). private static boolean bareNamePropertyMethods = false; /** * Returns the getter {@link Method} for a property matching the given name in the given object. * * @param propertyName the given property name. * @param target the given object. * @return the getter {@code Method} for a property matching the given name in the given object. * @throws NullPointerException if the given property name is {@code null}. * @throws IllegalArgumentException if the given property name is empty. * @throws NullPointerException if the given object is {@code null}. * @throws IntrospectionError if the getter for the matching property cannot be found or accessed. */ public static Method getPropertyGetter(String propertyName, Object target) { checkNotNullOrEmpty(propertyName); requireNonNull(target); Method getter = findGetter(propertyName, target); if (getter == null) { throw new IntrospectionError(propertyNotFoundErrorMessage("No getter for property %s in %s", propertyName, target)); } if (!isPublic(getter.getModifiers())) { throw new IntrospectionError(propertyNotFoundErrorMessage("No public getter for property %s in %s", propertyName, target)); } try { // force access for static class with public getter getter.setAccessible(true); getter.invoke(target); } catch (Exception t) { throw new IntrospectionError(propertyNotFoundErrorMessage("Unable to find property %s in %s", propertyName, target), t); } return getter; } public static void setExtractBareNamePropertyMethods(boolean barenamePropertyMethods) { ConfigurationProvider.loadRegisteredConfiguration(); bareNamePropertyMethods = barenamePropertyMethods; } @VisibleForTesting public static boolean canExtractBareNamePropertyMethods() { return bareNamePropertyMethods; } private static String propertyNotFoundErrorMessage(String message, String propertyName, Object target) { String targetTypeName = target.getClass().getName(); String property = quote(propertyName); return format(message, property, targetTypeName); } private static Method findGetter(String propertyName, Object target) { String capitalized = propertyName.substring(0, 1).toUpperCase(ENGLISH) + propertyName.substring(1); // try to find getProperty Method getter = findMethod("get" + capitalized, target); if (isValidGetter(getter)) return getter; if (bareNamePropertyMethods) { // try to find bare name property getter = findMethod(propertyName, target); if (isValidGetter(getter)) return getter; } // try to find isProperty for boolean properties Method isAccessor = findMethod("is" + capitalized, target); return isValidGetter(isAccessor) ? isAccessor : null; } private static boolean isValidGetter(Method method) { return method != null && !Modifier.isStatic(method.getModifiers()) && !Void.TYPE.equals(method.getReturnType()); } private static Method findMethod(String name, Object target) { final MethodKey methodKey = new MethodKey(name, target.getClass()); return METHOD_CACHE.computeIfAbsent(methodKey, Introspection::findMethodByKey).orElse(null); } private static Optional<Method> findMethodByKey(MethodKey key) { // try public methods only Class<?> clazz = key.clazz; try { return Optional.of(clazz.getMethod(key.name)); } catch (NoSuchMethodException | SecurityException ignored) {} // search all methods while (clazz != null) { try { return Optional.of(clazz.getDeclaredMethod(key.name)); } catch (NoSuchMethodException | SecurityException ignored) {} clazz = clazz.getSuperclass(); } return Optional.empty(); } private static final class MethodKey { private final String name; private final Class<?> clazz; private MethodKey(final String name, final Class<?> clazz) { this.name = name; this.clazz = clazz; } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final MethodKey methodKey = (MethodKey) o; return Objects.equals(name, methodKey.name) && Objects.equals(clazz, methodKey.clazz); } @Override public int hashCode() { return Objects.hash(name, clazz); } } private Introspection() {} }
hazendaz/assertj-core
src/main/java/org/assertj/core/util/introspection/Introspection.java
Java
apache-2.0
6,316