repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
tombujok/hazelcast
hazelcast/src/main/java/com/hazelcast/config/QueueConfig.java
13439
/* * Copyright (c) 2008-2017, Hazelcast, 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. */ package com.hazelcast.config; import com.hazelcast.nio.ObjectDataInput; import com.hazelcast.nio.ObjectDataOutput; import com.hazelcast.nio.serialization.IdentifiedDataSerializable; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static com.hazelcast.internal.serialization.impl.SerializationUtil.readNullableList; import static com.hazelcast.internal.serialization.impl.SerializationUtil.writeNullableList; import static com.hazelcast.util.Preconditions.checkAsyncBackupCount; import static com.hazelcast.util.Preconditions.checkBackupCount; /** * Contains the configuration for an {@link com.hazelcast.core.IQueue}. */ public class QueueConfig implements IdentifiedDataSerializable { /** * Default value for the maximum size of the Queue. */ public static final int DEFAULT_MAX_SIZE = 0; /** * Default value for the sychronous backup count. */ public static final int DEFAULT_SYNC_BACKUP_COUNT = 1; /** * Default value of the asynchronous backup count. */ public static final int DEFAULT_ASYNC_BACKUP_COUNT = 0; /** * Default value for the TTL (time to live) for empty Queue. */ public static final int DEFAULT_EMPTY_QUEUE_TTL = -1; private String name; private List<ItemListenerConfig> listenerConfigs; private int backupCount = DEFAULT_SYNC_BACKUP_COUNT; private int asyncBackupCount = DEFAULT_ASYNC_BACKUP_COUNT; private int maxSize = DEFAULT_MAX_SIZE; private int emptyQueueTtl = DEFAULT_EMPTY_QUEUE_TTL; private QueueStoreConfig queueStoreConfig; private boolean statisticsEnabled = true; private String quorumName; private transient QueueConfigReadOnly readOnly; public QueueConfig() { } public QueueConfig(String name) { setName(name); } public QueueConfig(QueueConfig config) { this(); this.name = config.name; this.backupCount = config.backupCount; this.asyncBackupCount = config.asyncBackupCount; this.maxSize = config.maxSize; this.emptyQueueTtl = config.emptyQueueTtl; this.statisticsEnabled = config.statisticsEnabled; this.quorumName = config.quorumName; this.queueStoreConfig = config.queueStoreConfig != null ? new QueueStoreConfig(config.queueStoreConfig) : null; this.listenerConfigs = new ArrayList<ItemListenerConfig>(config.getItemListenerConfigs()); } /** * Gets immutable version of this configuration. * * @return immutable version of this configuration * @deprecated this method will be removed in 4.0; it is meant for internal usage only */ public QueueConfigReadOnly getAsReadOnly() { if (readOnly == null) { readOnly = new QueueConfigReadOnly(this); } return readOnly; } /** * Returns the TTL (time to live) for emptying the Queue. * * @return the TTL (time to live) for emptying the Queue */ public int getEmptyQueueTtl() { return emptyQueueTtl; } /** * Sets the TTL (time to live) for emptying the Queue. * * @param emptyQueueTtl set the TTL (time to live) for emptying the Queue to this value * @return the Queue configuration */ public QueueConfig setEmptyQueueTtl(int emptyQueueTtl) { this.emptyQueueTtl = emptyQueueTtl; return this; } /** * Returns the maximum size of the Queue. * * @return the maximum size of the Queue */ public int getMaxSize() { return maxSize == 0 ? Integer.MAX_VALUE : maxSize; } /** * Sets the maximum size of the Queue. * * @param maxSize set the maximum size of the Queue to this value * @return the Queue configuration */ public QueueConfig setMaxSize(int maxSize) { if (maxSize < 0) { throw new IllegalArgumentException("Size of the queue can not be a negative value!"); } this.maxSize = maxSize; return this; } /** * Get the total number of backups: the backup count plus the asynchronous backup count. * * @return the total number of backups */ public int getTotalBackupCount() { return backupCount + asyncBackupCount; } /** * Get the number of synchronous backups for this queue. * * @return the synchronous backup count */ public int getBackupCount() { return backupCount; } /** * Sets the number of synchronous backups for this queue. * * @param backupCount the number of synchronous backups to set * @return the current QueueConfig * @throws IllegalArgumentException if backupCount is smaller than 0, * or larger than the maximum number of backups, * or the sum of the backups and async backups is larger than the maximum number of backups * @see #setAsyncBackupCount(int) */ public QueueConfig setBackupCount(int backupCount) { this.backupCount = checkBackupCount(backupCount, asyncBackupCount); return this; } /** * Get the number of asynchronous backups for this queue. * * @return the number of asynchronous backups */ public int getAsyncBackupCount() { return asyncBackupCount; } /** * Sets the number of asynchronous backups. 0 means no backups. * * @param asyncBackupCount the number of asynchronous synchronous backups to set * @return the updated QueueConfig * @throws IllegalArgumentException if asyncBackupCount smaller than 0, * or larger than the maximum number of backup * or the sum of the backups and async backups is larger than the maximum number of backups * @see #setBackupCount(int) * @see #getAsyncBackupCount() */ public QueueConfig setAsyncBackupCount(int asyncBackupCount) { this.asyncBackupCount = checkAsyncBackupCount(backupCount, asyncBackupCount); return this; } /** * Get the QueueStore (load and store queue items from/to a database) configuration. * * @return the QueueStore configuration */ public QueueStoreConfig getQueueStoreConfig() { return queueStoreConfig; } /** * Set the QueueStore (load and store queue items from/to a database) configuration. * * @param queueStoreConfig set the QueueStore configuration to this configuration * @return the QueueStore configuration */ public QueueConfig setQueueStoreConfig(QueueStoreConfig queueStoreConfig) { this.queueStoreConfig = queueStoreConfig; return this; } /** * Check if statistics are enabled for this queue. * * @return {@code true} if statistics are enabled, {@code false} otherwise */ public boolean isStatisticsEnabled() { return statisticsEnabled; } /** * Enables or disables statistics for this queue. * * @param statisticsEnabled {@code true} to enable statistics for this queue, {@code false} to disable * @return the updated QueueConfig */ public QueueConfig setStatisticsEnabled(boolean statisticsEnabled) { this.statisticsEnabled = statisticsEnabled; return this; } /** * @return the name of this queue */ public String getName() { return name; } /** * Set the name for this queue. * * @param name the name to set for this queue * @return this queue configuration */ public QueueConfig setName(String name) { this.name = name; return this; } /** * Add an item listener configuration to this queue. * * @param listenerConfig the item listener configuration to add to this queue * @return the updated queue configuration */ public QueueConfig addItemListenerConfig(ItemListenerConfig listenerConfig) { getItemListenerConfigs().add(listenerConfig); return this; } /** * Get the list of item listener configurations for this queue. * * @return the list of item listener configurations for this queue */ public List<ItemListenerConfig> getItemListenerConfigs() { if (listenerConfigs == null) { listenerConfigs = new ArrayList<ItemListenerConfig>(); } return listenerConfigs; } /** * Set the list of item listener configurations for this queue. * * @param listenerConfigs the list of item listener configurations to set for this queue * @return the updated queue configuration */ public QueueConfig setItemListenerConfigs(List<ItemListenerConfig> listenerConfigs) { this.listenerConfigs = listenerConfigs; return this; } /** * Returns the quorum name for queue operations. * * @return the quorum name */ public String getQuorumName() { return quorumName; } /** * Sets the quorum name for queue operations. * * @param quorumName the quorum name * @return the updated queue configuration */ public QueueConfig setQuorumName(String quorumName) { this.quorumName = quorumName; return this; } @Override public String toString() { return "QueueConfig{" + "name='" + name + '\'' + ", listenerConfigs=" + listenerConfigs + ", backupCount=" + backupCount + ", asyncBackupCount=" + asyncBackupCount + ", maxSize=" + maxSize + ", emptyQueueTtl=" + emptyQueueTtl + ", queueStoreConfig=" + queueStoreConfig + ", statisticsEnabled=" + statisticsEnabled + '}'; } @Override public int getFactoryId() { return ConfigDataSerializerHook.F_ID; } @Override public int getId() { return ConfigDataSerializerHook.QUEUE_CONFIG; } @Override public void writeData(ObjectDataOutput out) throws IOException { out.writeUTF(name); writeNullableList(listenerConfigs, out); out.writeInt(backupCount); out.writeInt(asyncBackupCount); out.writeInt(maxSize); out.writeInt(emptyQueueTtl); out.writeObject(queueStoreConfig); out.writeBoolean(statisticsEnabled); out.writeUTF(quorumName); } @Override public void readData(ObjectDataInput in) throws IOException { name = in.readUTF(); listenerConfigs = readNullableList(in); backupCount = in.readInt(); asyncBackupCount = in.readInt(); maxSize = in.readInt(); emptyQueueTtl = in.readInt(); queueStoreConfig = in.readObject(); statisticsEnabled = in.readBoolean(); quorumName = in.readUTF(); } @Override @SuppressWarnings({"checkstyle:cyclomaticcomplexity", "checkstyle:npathcomplexity"}) public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } QueueConfig that = (QueueConfig) o; if (backupCount != that.backupCount) { return false; } if (asyncBackupCount != that.asyncBackupCount) { return false; } if (getMaxSize() != getMaxSize()) { return false; } if (emptyQueueTtl != that.emptyQueueTtl) { return false; } if (statisticsEnabled != that.statisticsEnabled) { return false; } if (!name.equals(that.name)) { return false; } if (!getItemListenerConfigs().equals(that.getItemListenerConfigs())) { return false; } if (queueStoreConfig != null ? !queueStoreConfig.equals(that.queueStoreConfig) : that.queueStoreConfig != null) { return false; } return quorumName != null ? quorumName.equals(that.quorumName) : that.quorumName == null; } @Override public int hashCode() { int result = name.hashCode(); result = 31 * result + getItemListenerConfigs().hashCode(); result = 31 * result + backupCount; result = 31 * result + asyncBackupCount; result = 31 * result + getMaxSize(); result = 31 * result + emptyQueueTtl; result = 31 * result + (queueStoreConfig != null ? queueStoreConfig.hashCode() : 0); result = 31 * result + (statisticsEnabled ? 1 : 0); result = 31 * result + (quorumName != null ? quorumName.hashCode() : 0); return result; } }
apache-2.0
kSzmit/Fractals
src/Interface/TopMenu.hpp
862
#pragma once #define _CRT_SECURE_NO_DEPRECATE #include <SFGUI/SFGUI.hpp> #include <SFGUI/Widgets.hpp> #include <iomanip> #include <ctime> class Interface; class TopMenu { sfg::Button::Ptr m_buttonKantor; sfg::Button::Ptr m_buttonKoch; sfg::Button::Ptr m_buttonCarpet; sfg::Button::Ptr m_buttonTriangle; sfg::Button::Ptr m_buttonFern; sfg::Button::Ptr m_buttonMandel; sfg::Button::Ptr m_buttonJuli; sfg::Button::Ptr m_buttonTexture; sfg::Button::Ptr m_buttonScreenshot; sfg::Box::Ptr m_boxFractal; sfg::Window::Ptr m_windowFractal; enum fraq { kCantor, kKoch, kSierpinskiCarpet, kTriangle, kFern, kMandel, kJuli, kTerrain }; public: TopMenu(); TopMenu(Interface* interface); void buttonSwitchClick(int switchTo, Interface* interface); void buttonScreenshotClick(Interface* interface); sfg::Window::Ptr getWindow(); };
apache-2.0
thr0w/galen
src/main/java/net/mindengine/galen/suite/reader/GalenSuiteLineProcessor.java
8270
/******************************************************************************* * Copyright 2015 Ivan Shubin http://mindengine.net * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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.mindengine.galen.suite.reader; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.List; import java.util.Properties; import net.mindengine.galen.parser.VarsContext; import net.mindengine.galen.parser.SyntaxException; import net.mindengine.galen.tests.GalenBasicTest; import static net.mindengine.galen.utils.GalenUtils.removeNonPrintableControlSymbols; public class GalenSuiteLineProcessor { private RootNode rootNode = new RootNode(); private Node<?> currentNode = rootNode; private boolean disableNextSuite = false; private String contextPath; private Properties properties; private List<String> groupsForNextTest; public GalenSuiteLineProcessor(Properties properties, String contextPath) { this.contextPath = contextPath; this.properties = properties; } public void processLine(String line, int number) throws IOException { if (!isBlank(line) && !isCommented(line) && !isSeparator(line)) { if (line.startsWith("@@")) { Node<?> node = processSpecialInstruction(new Line(line.substring(2).trim(), number)); if (node != null) { currentNode = node; } } else { int spaces = indentationSpaces(line); Node<?> processingNode = currentNode.findProcessingNodeByIndentation(spaces); Node<?> newNode = processingNode.processNewNode(new Line(line, number)); if (newNode instanceof TestNode) { if (disableNextSuite) { disableNextSuite = false; ((TestNode)newNode).setDisabled(true); } if (groupsForNextTest != null) { ((TestNode)newNode).setGroups(groupsForNextTest); groupsForNextTest = null; } } currentNode = newNode; } } } private Node<?> processSpecialInstruction(Line line) throws FileNotFoundException, IOException { String text = line.getText(); currentNode = rootNode; int indexOfFirstSpace = text.indexOf(' '); String firstWord; String leftover; if (indexOfFirstSpace > 0) { firstWord = text.substring(0, indexOfFirstSpace).toLowerCase(); leftover = text.substring(indexOfFirstSpace).trim(); } else { firstWord = text.toLowerCase(); leftover = ""; } Line leftoverLine = new Line(leftover, line.getNumber()); if (firstWord.equals("set")) { return processInstructionSet(leftoverLine); } else if (firstWord.equals("table")){ return processTable(leftoverLine); } else if (firstWord.equals("parameterized")){ return processParameterized(leftoverLine); } else if (firstWord.equals("disabled")) { markNextSuiteAsDisabled(); return null; } else if (firstWord.equals("groups")) { markNextSuiteGroupedWith(leftover); return null; } else if (firstWord.equals("import")) { List<Node<?>> nodes = importSuite(leftover, line); rootNode.getChildNodes().addAll(nodes); return null; } else throw new SuiteReaderException("Unknown instruction: " + firstWord); } private List<Node<?>> importSuite(String path, Line line) throws FileNotFoundException, IOException { if (path.isEmpty()) { throw new SyntaxException(line, "No path specified for importing"); } String fullChildPath = contextPath + File.separator + path; String childContextPath = new File(fullChildPath).getParent(); GalenSuiteLineProcessor childProcessor = new GalenSuiteLineProcessor(properties, childContextPath); File file = new File(fullChildPath); if (!file.exists()) { throw new SyntaxException(line, "File doesn't exist: " + file.getAbsolutePath()); } childProcessor.readLines(new FileInputStream(file)); return childProcessor.rootNode.getChildNodes(); } private void markNextSuiteGroupedWith(String commaSeparatedGroups) { String[] groupsArray = commaSeparatedGroups.split(","); List<String> groups = new LinkedList<String>(); for (String group : groupsArray) { String trimmedGroup = group.trim(); if (!trimmedGroup.isEmpty()) { groups.add(trimmedGroup); } } this.groupsForNextTest = groups; } private void markNextSuiteAsDisabled() { this.disableNextSuite = true; } private Node<?> processParameterized(Line line) { ParameterizedNode parameterizedNode = new ParameterizedNode(line); if (disableNextSuite) { parameterizedNode.setDisabled(true); disableNextSuite = false; } if (groupsForNextTest != null) { parameterizedNode.setGroups(groupsForNextTest); groupsForNextTest = null; } currentNode.add(parameterizedNode); return parameterizedNode; } private Node<?> processTable(Line line) { TableNode tableNode = new TableNode(line); currentNode.add(tableNode); return tableNode; } private Node<?> processInstructionSet(Line line) { SetNode newNode = new SetNode(line); currentNode.add(newNode); return newNode; } public List<GalenBasicTest> buildSuites() { return rootNode.build(new VarsContext(properties)); } private int indentationSpaces(String line) { int spacesCount = 0; for (int i=0; i<line.length(); i++) { if (line.charAt(i) == ' ') { spacesCount++; } else if (line.charAt(i) == '\t') { spacesCount += 4; } else { return spacesCount; } } return 0; } private boolean isSeparator(String line) { line = line.trim(); if (line.length() > 3) { char ch = line.charAt(0); for (int i = 1; i < line.length(); i++) { if (ch != line.charAt(i)) { return false; } } return true; } else return false; } private boolean isBlank(String line) { return line.trim().isEmpty(); } private boolean isCommented(String line) { return line.trim().startsWith("#"); } public void readLines(InputStream inputStream) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); String line = bufferedReader.readLine(); int lineNumber = 0; while(line != null){ lineNumber++; line = removeNonPrintableControlSymbols(line); processLine(line, lineNumber); line = bufferedReader.readLine(); } } }
apache-2.0
Breeze0925/zxmweather
src/util/Utility.java
3967
package util; //import java.sql.Date; import java.text.SimpleDateFormat; //import java.util.Date; import java.util.Locale; import org.json.JSONException; import org.json.JSONObject; import model.City; import model.Country; import model.Province; import model.ZxmWeatherDB; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.text.TextUtils; public class Utility { /** * 解析和处理服务器返回的省级数据 */ public synchronized static boolean handleProvincesResponse(ZxmWeatherDB zxmWeatherDB,String response) { if(!TextUtils.isEmpty(response)) { String[] allProvinces = response.split(","); if(allProvinces != null && allProvinces.length > 0) { for(String p: allProvinces) { String[] array = p.split("\\|"); Province province = new Province(); province.setProvinceCode(array[0]); province.setProvinceName(array[1]); //将解析出来的数据存储到Province表 zxmWeatherDB.saveProvince(province); } return true; } } return false; } /** * 解析和处理服务器返回的市级数据 */ public static boolean handleCitiesResponse(ZxmWeatherDB zxmWeatherDB,String response,int provinceId) { if(!TextUtils.isEmpty(response)) { String[] allCities = response.split(","); if(allCities !=null && allCities.length>0) { for(String c: allCities) { String[] array = c.split("\\|"); City city = new City(); city.setCityCode(array[0]); city.setCityName(array[1]); city.setProvinceId(provinceId); //将解析出来的数据存储到City表 zxmWeatherDB.saveCity(city); } return true; } } return true; } /** *解析和处理服务器返回的县级数据 */ public static boolean handleCountiesResponse(ZxmWeatherDB zxmWeatherDB,String response,int cityId) { if(!TextUtils.isEmpty(response)) { String[] allCounties = response.split(","); if(allCounties != null && allCounties.length>0) { for(String c : allCounties) { String[] array = c.split("\\|"); Country country = new Country(); country.setCountryCode(array[0]); country.setCountryName(array[1]); country.setCityId(cityId); //将解析处理啊的数据存储到Country表 zxmWeatherDB.saveCountry(country); } return true; } } return false; } /** * 解析服务器返回的JSON数据,并将解析出的数据存储到本地 */ public static void handleWeatherResponse(Context context,String response) { try { JSONObject jsonObject = new JSONObject(response); JSONObject weatherInfo = jsonObject.getJSONObject("weatherinfo"); String cityName = weatherInfo.getString("city"); String weatherCode = weatherInfo.getString("cityid"); String temp1 = weatherInfo.getString("temp1"); String temp2 = weatherInfo.getString("temp2"); String weatherDesp = weatherInfo.getString("weather"); String publishTime = weatherInfo.getString("ptime"); saveWeatherInfo(context,cityName,weatherCode,temp1,temp2,weatherDesp,publishTime); } catch (JSONException e) { e.printStackTrace(); } } private static void saveWeatherInfo(Context context, String cityName, String weatherCode, String temp1, String temp2, String weatherDesp, String publishTime) { // TODO 自动生成的方法存根 SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日",Locale.CHINA); SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit(); editor.putBoolean("city_selected", true); editor.putString("city_name", cityName); editor.putString("weather_code", weatherCode); editor.putString("temp1", temp1); editor.putString("temp2", temp2); editor.putString("weather_desp", weatherDesp); editor.putString("publish_time", publishTime); editor.putString("current_date", sdf.format(new java.util.Date())); editor.commit(); } }
apache-2.0
lsmaira/gradle
subprojects/language-java/src/main/java/org/gradle/api/internal/tasks/compile/incremental/processing/AnnotationProcessingData.java
4126
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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.gradle.api.internal.tasks.compile.incremental.processing; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import org.gradle.api.internal.cache.StringInterner; import org.gradle.internal.serialize.AbstractSerializer; import org.gradle.internal.serialize.Decoder; import org.gradle.internal.serialize.Encoder; import org.gradle.internal.serialize.InterningStringSerializer; import org.gradle.internal.serialize.MapSerializer; import org.gradle.internal.serialize.SetSerializer; import java.util.Map; import java.util.Set; public class AnnotationProcessingData { private final Map<String, Set<String>> generatedTypesByOrigin; private final Set<String> aggregatedTypes; private final Set<String> generatedTypesDependingOnAllOthers; private final String fullRebuildCause; public AnnotationProcessingData() { this(ImmutableMap.<String, Set<String>>of(), ImmutableSet.<String>of(), ImmutableSet.<String>of(), null); } public AnnotationProcessingData(Map<String, Set<String>> generatedTypesByOrigin, Set<String> aggregatedTypes, Set<String> generatedTypesDependingOnAllOthers, String fullRebuildCause) { this.generatedTypesByOrigin = ImmutableMap.copyOf(generatedTypesByOrigin); this.aggregatedTypes = ImmutableSet.copyOf(aggregatedTypes); this.generatedTypesDependingOnAllOthers = ImmutableSet.copyOf(generatedTypesDependingOnAllOthers); this.fullRebuildCause = fullRebuildCause; } public Map<String, Set<String>> getGeneratedTypesByOrigin() { return generatedTypesByOrigin; } public Set<String> getAggregatedTypes() { return aggregatedTypes; } public Set<String> getGeneratedTypesDependingOnAllOthers() { return generatedTypesDependingOnAllOthers; } public String getFullRebuildCause() { return fullRebuildCause; } public static final class Serializer extends AbstractSerializer<AnnotationProcessingData> { private final SetSerializer<String> typesSerializer; private final MapSerializer<String, Set<String>> generatedTypesSerializer; public Serializer(StringInterner interner) { InterningStringSerializer stringSerializer = new InterningStringSerializer(interner); typesSerializer = new SetSerializer<String>(stringSerializer); generatedTypesSerializer = new MapSerializer<String, Set<String>>(stringSerializer, typesSerializer); } @Override public AnnotationProcessingData read(Decoder decoder) throws Exception { Map<String, Set<String>> generatedTypes = generatedTypesSerializer.read(decoder); Set<String> aggregatedTypes = typesSerializer.read(decoder); Set<String> generatedTypesDependingOnAllOthers = typesSerializer.read(decoder); String fullRebuildCause = decoder.readNullableString(); return new AnnotationProcessingData(generatedTypes, aggregatedTypes, generatedTypesDependingOnAllOthers, fullRebuildCause); } @Override public void write(Encoder encoder, AnnotationProcessingData value) throws Exception { generatedTypesSerializer.write(encoder, value.generatedTypesByOrigin); typesSerializer.write(encoder, value.aggregatedTypes); typesSerializer.write(encoder, value.generatedTypesDependingOnAllOthers); encoder.writeNullableString(value.fullRebuildCause); } } }
apache-2.0
zbw911/CasClient
Dev.ClientWeb/Models/AccountModels.cs
3042
//using System; //using System.Collections.Generic; //using System.ComponentModel.DataAnnotations; //using System.ComponentModel.DataAnnotations.Schema; //using System.Data.Entity; //using System.Globalization; //using System.Web.Mvc; //using System.Web.Security; //namespace Dev.ClientWeb.Models //{ // public class UsersContext : DbContext // { // public UsersContext() // : base("DefaultConnection") // { // } // public DbSet<UserProfile> UserProfiles { get; set; } // } // [Table("UserProfile")] // public class UserProfile // { // [Key] // [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] // public int UserId { get; set; } // public string UserName { get; set; } // } // public class RegisterExternalLoginModel // { // [Required] // [Display(Name = "用户名")] // public string UserName { get; set; } // public string ExternalLoginData { get; set; } // } // public class LocalPasswordModel // { // [Required] // [DataType(DataType.Password)] // [Display(Name = "当前密码")] // public string OldPassword { get; set; } // [Required] // [StringLength(100, ErrorMessage = "{0} 必须至少包含 {2} 个字符。", MinimumLength = 6)] // [DataType(DataType.Password)] // [Display(Name = "新密码")] // public string NewPassword { get; set; } // [DataType(DataType.Password)] // [Display(Name = "确认新密码")] // [Compare("NewPassword", ErrorMessage = "新密码和确认密码不匹配。")] // public string ConfirmPassword { get; set; } // } // public class LoginModel // { // [Required] // [Display(Name = "用户名")] // public string UserName { get; set; } // [Required] // [DataType(DataType.Password)] // [Display(Name = "密码")] // public string Password { get; set; } // [Display(Name = "记住我?")] // public bool RememberMe { get; set; } // } // public class RegisterModel // { // [Required] // [Display(Name = "用户名")] // public string UserName { get; set; } // [Required] // [StringLength(100, ErrorMessage = "{0} 必须至少包含 {2} 个字符。", MinimumLength = 6)] // [DataType(DataType.Password)] // [Display(Name = "密码")] // public string Password { get; set; } // [DataType(DataType.Password)] // [Display(Name = "确认密码")] // [Compare("Password", ErrorMessage = "密码和确认密码不匹配。")] // public string ConfirmPassword { get; set; } // } // public class ExternalLogin // { // public string Provider { get; set; } // public string ProviderDisplayName { get; set; } // public string ProviderUserId { get; set; } // } //}
apache-2.0
googlesamples/arcore-illusive-images
Assets/GoogleARCore/Examples/ComputerVision/Scripts/ComputerVisionController.cs
22447
//----------------------------------------------------------------------- // <copyright file="ComputerVisionController.cs" company="Google"> // // 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. // // </copyright> //----------------------------------------------------------------------- namespace GoogleARCore.Examples.ComputerVision { using System; using System.Collections.Generic; using GoogleARCore; using UnityEngine; using UnityEngine.UI; #if UNITY_EDITOR // Set up touch input propagation while using Instant Preview in the editor. using Input = InstantPreviewInput; #endif // UNITY_EDITOR /// <summary> /// Controller for the ComputerVision example that accesses the CPU camera image (i.e. image bytes), performs /// edge detection on the image, and renders an overlay to the screen. /// </summary> public class ComputerVisionController : MonoBehaviour { /// <summary> /// The ARCoreSession monobehavior that manages the ARCore session. /// </summary> public ARCoreSession ARSessionManager; /// <summary> /// An image using a material with EdgeDetectionBackground.shader to render a /// percentage of the edge detection background to the screen over the standard camera background. /// </summary> public Image EdgeDetectionBackgroundImage; /// <summary> /// A Text box that is used to output the camera intrinsics values. /// </summary> public Text CameraIntrinsicsOutput; /// <summary> /// A Text box that is used to show messages at runtime. /// </summary> public Text SnackbarText; /// <summary> /// A toggle that is used to select the low resolution CPU camera configuration. /// </summary> public Toggle LowResConfigToggle; /// <summary> /// A toggle that is used to select the high resolution CPU camera configuration. /// </summary> public Toggle HighResConfigToggle; /// <summary> /// A toggle that is used to toggle between CPU image and GPU texture. /// </summary> public PointClickHandler ImageTextureToggle; /// <summary> /// A toggle that is used to toggle between Fixed and Auto focus modes. /// </summary> public Toggle AutoFocusToggle; /// <summary> /// A buffer that stores the result of performing edge detection on the camera image each frame. /// </summary> private byte[] m_EdgeDetectionResultImage = null; /// <summary> /// Texture created from the result of running edge detection on the camera image bytes. /// </summary> private Texture2D m_EdgeDetectionBackgroundTexture = null; /// <summary> /// These UVs are applied to the background material to crop and rotate 'm_EdgeDetectionBackgroundTexture' /// to match the aspect ratio and rotation of the device display. /// </summary> private DisplayUvCoords m_CameraImageToDisplayUvTransformation; private ScreenOrientation? m_CachedOrientation = null; private Vector2 m_CachedScreenDimensions = Vector2.zero; private bool m_IsQuitting = false; private bool m_UseHighResCPUTexture = false; private ARCoreSession.OnChooseCameraConfigurationDelegate m_OnChoseCameraConfiguration = null; private bool m_Resolutioninitialized = false; private Text m_ImageTextureToggleText; /// <summary> /// The Unity Start() method. /// </summary> public void Start() { Screen.sleepTimeout = SleepTimeout.NeverSleep; ImageTextureToggle.OnPointClickDetected += _OnBackgroundClicked; m_ImageTextureToggleText = ImageTextureToggle.GetComponentInChildren<Text>(); #if UNITY_EDITOR AutoFocusToggle.GetComponentInChildren<Text>().text += "\n(Not supported in editor)"; HighResConfigToggle.GetComponentInChildren<Text>().text += "\n(Not supported in editor)"; SnackbarText.text = "Use mouse/keyboard in the editor Game view to toggle settings.\n" + "(Tapping on the device screen will not work while running in the editor)"; #else SnackbarText.text = string.Empty; #endif // Register the callback to set camera config before arcore session is enabled. m_OnChoseCameraConfiguration = _ChooseCameraConfiguration; ARSessionManager.RegisterChooseCameraConfigurationCallback(m_OnChoseCameraConfiguration); ARSessionManager.enabled = true; } /// <summary> /// The Unity Update() method. /// </summary> public void Update() { if (Input.GetKey(KeyCode.Escape)) { Application.Quit(); } _QuitOnConnectionErrors(); // Change the CPU resolution checkbox visibility. LowResConfigToggle.gameObject.SetActive(EdgeDetectionBackgroundImage.enabled); HighResConfigToggle.gameObject.SetActive(EdgeDetectionBackgroundImage.enabled); m_ImageTextureToggleText.text = EdgeDetectionBackgroundImage.enabled ? "Switch to GPU Texture" : "Switch to CPU Image"; if (!Session.Status.IsValid()) { return; } using (var image = Frame.CameraImage.AcquireCameraImageBytes()) { if (!image.IsAvailable) { return; } _OnImageAvailable(image.Width, image.Height, image.YRowStride, image.Y, 0); } var cameraIntrinsics = EdgeDetectionBackgroundImage.enabled ? Frame.CameraImage.ImageIntrinsics : Frame.CameraImage.TextureIntrinsics; string intrinsicsType = EdgeDetectionBackgroundImage.enabled ? "CPU Image" : "GPU Texture"; CameraIntrinsicsOutput.text = _CameraIntrinsicsToString(cameraIntrinsics, intrinsicsType); } /// <summary> /// Handles the low resolution checkbox toggle changing. /// </summary> /// <param name="newValue">The new value for the checkbox.</param> public void OnLowResolutionCheckboxValueChanged(bool newValue) { m_UseHighResCPUTexture = !newValue; HighResConfigToggle.isOn = !newValue; // Pause and resume the ARCore session to apply the camera configuration. ARSessionManager.enabled = false; ARSessionManager.enabled = true; } /// <summary> /// Handles the high resolution checkbox toggle changing. /// </summary> /// <param name="newValue">The new value for the checkbox.</param> public void OnHighResolutionCheckboxValueChanged(bool newValue) { m_UseHighResCPUTexture = newValue; LowResConfigToggle.isOn = !newValue; // Pause and resume the ARCore session to apply the camera configuration. ARSessionManager.enabled = false; ARSessionManager.enabled = true; } /// <summary> /// Hanldes the auto focus checkbox value changed. /// </summary> /// <param name="autoFocusEnabled">If set to <c>true</c> auto focus will be enabled.</param> public void OnAutoFocusCheckboxValueChanged(bool autoFocusEnabled) { var config = ARSessionManager.SessionConfig; if (config != null) { config.CameraFocusMode = autoFocusEnabled ? CameraFocusMode.Auto : CameraFocusMode.Fixed; } } /// <summary> /// Function get called when the background image got clicked. /// </summary> private void _OnBackgroundClicked() { EdgeDetectionBackgroundImage.enabled = !EdgeDetectionBackgroundImage.enabled; } /// <summary> /// Handles a new CPU image. /// </summary> /// <param name="width">Width of the image, in pixels.</param> /// <param name="height">Height of the image, in pixels.</param> /// <param name="rowStride">Row stride of the image, in pixels.</param> /// <param name="pixelBuffer">Pointer to raw image buffer.</param> /// <param name="bufferSize">The size of the image buffer, in bytes.</param> private void _OnImageAvailable(int width, int height, int rowStride, IntPtr pixelBuffer, int bufferSize) { if (!EdgeDetectionBackgroundImage.enabled) { return; } if (m_EdgeDetectionBackgroundTexture == null || m_EdgeDetectionResultImage == null || m_EdgeDetectionBackgroundTexture.width != width || m_EdgeDetectionBackgroundTexture.height != height) { m_EdgeDetectionBackgroundTexture = new Texture2D(width, height, TextureFormat.R8, false, false); m_EdgeDetectionResultImage = new byte[width * height]; _UpdateCameraImageToDisplayUVs(); } if (m_CachedOrientation != Screen.orientation || m_CachedScreenDimensions.x != Screen.width || m_CachedScreenDimensions.y != Screen.height) { _UpdateCameraImageToDisplayUVs(); m_CachedOrientation = Screen.orientation; m_CachedScreenDimensions = new Vector2(Screen.width, Screen.height); } // Detect edges within the image. if (EdgeDetector.Detect(m_EdgeDetectionResultImage, pixelBuffer, width, height, rowStride)) { // Update the rendering texture with the edge image. m_EdgeDetectionBackgroundTexture.LoadRawTextureData(m_EdgeDetectionResultImage); m_EdgeDetectionBackgroundTexture.Apply(); EdgeDetectionBackgroundImage.material.SetTexture("_ImageTex", m_EdgeDetectionBackgroundTexture); const string TOP_LEFT_RIGHT = "_UvTopLeftRight"; const string BOTTOM_LEFT_RIGHT = "_UvBottomLeftRight"; EdgeDetectionBackgroundImage.material.SetVector(TOP_LEFT_RIGHT, new Vector4( m_CameraImageToDisplayUvTransformation.TopLeft.x, m_CameraImageToDisplayUvTransformation.TopLeft.y, m_CameraImageToDisplayUvTransformation.TopRight.x, m_CameraImageToDisplayUvTransformation.TopRight.y)); EdgeDetectionBackgroundImage.material.SetVector(BOTTOM_LEFT_RIGHT, new Vector4( m_CameraImageToDisplayUvTransformation.BottomLeft.x, m_CameraImageToDisplayUvTransformation.BottomLeft.y, m_CameraImageToDisplayUvTransformation.BottomRight.x, m_CameraImageToDisplayUvTransformation.BottomRight.y)); } } /// <summary> /// Updates the uv transformation from the camera image orientation and aspect to the display's. /// </summary> private void _UpdateCameraImageToDisplayUVs() { int cameraToDisplayRotation = _GetCameraImageToDisplayRotation(); float uBorder; float vBorder; _GetUvBorders(out uBorder, out vBorder); switch (cameraToDisplayRotation) { case 90: m_CameraImageToDisplayUvTransformation.TopLeft = new Vector2(1 - uBorder, 1 - vBorder); m_CameraImageToDisplayUvTransformation.TopRight = new Vector2(1 - uBorder, vBorder); m_CameraImageToDisplayUvTransformation.BottomRight = new Vector2(uBorder, vBorder); m_CameraImageToDisplayUvTransformation.BottomLeft = new Vector2(uBorder, 1 - vBorder); break; case 180: m_CameraImageToDisplayUvTransformation.TopLeft = new Vector2(uBorder, 1 - vBorder); m_CameraImageToDisplayUvTransformation.TopRight = new Vector2(1 - uBorder, 1 - vBorder); m_CameraImageToDisplayUvTransformation.BottomRight = new Vector2(1 - uBorder, vBorder); m_CameraImageToDisplayUvTransformation.BottomLeft = new Vector2(uBorder, vBorder); break; case 270: m_CameraImageToDisplayUvTransformation.TopLeft = new Vector2(uBorder, vBorder); m_CameraImageToDisplayUvTransformation.TopRight = new Vector2(uBorder, 1 - vBorder); m_CameraImageToDisplayUvTransformation.BottomRight = new Vector2(1 - uBorder, 1 - vBorder); m_CameraImageToDisplayUvTransformation.BottomLeft = new Vector2(1 - uBorder, vBorder); break; default: case 0: m_CameraImageToDisplayUvTransformation.TopLeft = new Vector2(1 - uBorder, vBorder); m_CameraImageToDisplayUvTransformation.TopRight = new Vector2(uBorder, vBorder); m_CameraImageToDisplayUvTransformation.BottomRight = new Vector2(uBorder, 1 - vBorder); m_CameraImageToDisplayUvTransformation.BottomLeft = new Vector2(1 - uBorder, 1 - vBorder); break; } } /// <summary> /// Gets the rotation that needs to be applied to the device camera image in order for it to match /// the current orientation of the display. /// </summary> /// <returns>The needed rotation.</returns> private int _GetCameraImageToDisplayRotation() { #if !UNITY_EDITOR AndroidJavaClass cameraClass = new AndroidJavaClass("android.hardware.Camera"); AndroidJavaClass cameraInfoClass = new AndroidJavaClass("android.hardware.Camera$CameraInfo"); AndroidJavaObject cameraInfo = new AndroidJavaObject("android.hardware.Camera$CameraInfo"); cameraClass.CallStatic("getCameraInfo", cameraInfoClass.GetStatic<int>("CAMERA_FACING_BACK"), cameraInfo); int cameraRotationToNaturalDisplayOrientation = cameraInfo.Get<int>("orientation"); AndroidJavaClass contextClass = new AndroidJavaClass("android.content.Context"); AndroidJavaClass unityPlayerClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); AndroidJavaObject unityActivity = unityPlayerClass.GetStatic<AndroidJavaObject>("currentActivity"); AndroidJavaObject windowManager = unityActivity.Call<AndroidJavaObject>("getSystemService", contextClass.GetStatic<string>("WINDOW_SERVICE")); AndroidJavaClass surfaceClass = new AndroidJavaClass("android.view.Surface"); int displayRotationFromNaturalEnum = windowManager .Call<AndroidJavaObject>("getDefaultDisplay").Call<int>("getRotation"); int displayRotationFromNatural = 0; if (displayRotationFromNaturalEnum == surfaceClass.GetStatic<int>("ROTATION_90")) { displayRotationFromNatural = 90; } else if (displayRotationFromNaturalEnum == surfaceClass.GetStatic<int>("ROTATION_180")) { displayRotationFromNatural = 180; } else if (displayRotationFromNaturalEnum == surfaceClass.GetStatic<int>("ROTATION_270")) { displayRotationFromNatural = 270; } return (cameraRotationToNaturalDisplayOrientation + displayRotationFromNatural) % 360; #else // !UNITY_EDITOR // Using Instant Preview in the Unity Editor, the display orientation is always portrait. return 0; #endif // !UNITY_EDITOR } /// <summary> /// Gets the percentage of space needed to be cropped on the device camera image to match the display /// aspect ratio. /// </summary> /// <param name="uBorder">The cropping of the 'u' dimension.</param> /// <param name="vBorder">The cropping of the 'v' dimension.</param> private void _GetUvBorders(out float uBorder, out float vBorder) { int imageWidth = m_EdgeDetectionBackgroundTexture.width; int imageHeight = m_EdgeDetectionBackgroundTexture.height; float screenAspectRatio; var cameraToDisplayRotation = _GetCameraImageToDisplayRotation(); if (cameraToDisplayRotation == 90 || cameraToDisplayRotation == 270) { screenAspectRatio = (float)Screen.height / Screen.width; } else { screenAspectRatio = (float)Screen.width / Screen.height; } var imageAspectRatio = (float)imageWidth / imageHeight; var croppedWidth = 0.0f; var croppedHeight = 0.0f; if (screenAspectRatio < imageAspectRatio) { croppedWidth = imageHeight * screenAspectRatio; croppedHeight = imageHeight; } else { croppedWidth = imageWidth; croppedHeight = imageWidth / screenAspectRatio; } uBorder = (imageWidth - croppedWidth) / imageWidth / 2.0f; vBorder = (imageHeight - croppedHeight) / imageHeight / 2.0f; } /// <summary> /// Quit the application if there was a connection error for the ARCore session. /// </summary> private void _QuitOnConnectionErrors() { if (m_IsQuitting) { return; } // Quit if ARCore was unable to connect and give Unity some time for the toast to appear. if (Session.Status == SessionStatus.ErrorPermissionNotGranted) { _ShowAndroidToastMessage("Camera permission is needed to run this application."); m_IsQuitting = true; Invoke("_DoQuit", 0.5f); } else if (Session.Status == SessionStatus.FatalError) { _ShowAndroidToastMessage("ARCore encountered a problem connecting. Please start the app again."); m_IsQuitting = true; Invoke("_DoQuit", 0.5f); } } /// <summary> /// Show an Android toast message. /// </summary> /// <param name="message">Message string to show in the toast.</param> private void _ShowAndroidToastMessage(string message) { AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); AndroidJavaObject unityActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"); if (unityActivity != null) { AndroidJavaClass toastClass = new AndroidJavaClass("android.widget.Toast"); unityActivity.Call("runOnUiThread", new AndroidJavaRunnable(() => { AndroidJavaObject toastObject = toastClass.CallStatic<AndroidJavaObject>("makeText", unityActivity, message, 0); toastObject.Call("show"); })); } } /// <summary> /// Actually quit the application. /// </summary> private void _DoQuit() { Application.Quit(); } /// <summary> /// Generate string to print the value in CameraIntrinsics. /// </summary> /// <param name="intrinsics">The CameraIntrinsics to generate the string from.</param> /// <param name="intrinsicsType">The string that describe the type of the intrinsics.</param> /// <returns>The generated string.</returns> private string _CameraIntrinsicsToString(CameraIntrinsics intrinsics, string intrinsicsType) { float fovX = 2.0f * Mathf.Atan2(intrinsics.ImageDimensions.x, 2 * intrinsics.FocalLength.x) * Mathf.Rad2Deg; float fovY = 2.0f * Mathf.Atan2(intrinsics.ImageDimensions.y, 2 * intrinsics.FocalLength.y) * Mathf.Rad2Deg; string message = string.Format("Unrotated Camera {4} Intrinsics:{0} Focal Length: {1}{0} " + "Principal Point: {2}{0} Image Dimensions: {3}{0} Unrotated Field of View: ({5}°, {6}°)", Environment.NewLine, intrinsics.FocalLength.ToString(), intrinsics.PrincipalPoint.ToString(), intrinsics.ImageDimensions.ToString(), intrinsicsType, fovX, fovY); return message; } /// <summary> /// Select the desired camera configuration. /// </summary> /// <param name="supportedConfigurations">A list of all supported camera configuration.</param> /// <returns>The desired configuration index.</returns> private int _ChooseCameraConfiguration(List<CameraConfig> supportedConfigurations) { if (!m_Resolutioninitialized) { Vector2 ImageSize = supportedConfigurations[0].ImageSize; LowResConfigToggle.GetComponentInChildren<Text>().text = string.Format( "Low Resolution CPU Image ({0} x {1})", ImageSize.x, ImageSize.y); ImageSize = supportedConfigurations[supportedConfigurations.Count - 1].ImageSize; HighResConfigToggle.GetComponentInChildren<Text>().text = string.Format( "High Resolution CPU Image ({0} x {1})", ImageSize.x, ImageSize.y); m_Resolutioninitialized = true; } if (m_UseHighResCPUTexture) { return supportedConfigurations.Count - 1; } return 0; } } }
apache-2.0
renyi533/tensorflow
tensorflow/python/ops/image_ops_test.py
203687
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for tensorflow.ops.image_ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import colorsys import functools import itertools import math import os import time import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin from tensorflow.core.protobuf import config_pb2 from tensorflow.python.client import session from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors from tensorflow.python.framework import ops from tensorflow.python.framework import test_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import gen_image_ops from tensorflow.python.ops import gradients from tensorflow.python.ops import image_ops from tensorflow.python.ops import image_ops_impl from tensorflow.python.ops import io_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import random_ops from tensorflow.python.ops import variables from tensorflow.python.platform import googletest from tensorflow.python.platform import test class RGBToHSVTest(test_util.TensorFlowTestCase): def testBatch(self): # Build an arbitrary RGB image np.random.seed(7) batch_size = 5 shape = (batch_size, 2, 7, 3) for nptype in [np.float32, np.float64]: inp = np.random.rand(*shape).astype(nptype) # Convert to HSV and back, as a batch and individually with self.cached_session(use_gpu=True) as sess: batch0 = constant_op.constant(inp) batch1 = image_ops.rgb_to_hsv(batch0) batch2 = image_ops.hsv_to_rgb(batch1) split0 = array_ops.unstack(batch0) split1 = list(map(image_ops.rgb_to_hsv, split0)) split2 = list(map(image_ops.hsv_to_rgb, split1)) join1 = array_ops.stack(split1) join2 = array_ops.stack(split2) batch1, batch2, join1, join2 = self.evaluate( [batch1, batch2, join1, join2]) # Verify that processing batch elements together is the same as separate self.assertAllClose(batch1, join1) self.assertAllClose(batch2, join2) self.assertAllClose(batch2, inp) def testRGBToHSVRoundTrip(self): data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] for nptype in [np.float32, np.float64]: rgb_np = np.array(data, dtype=nptype).reshape([2, 2, 3]) / 255. with self.cached_session(use_gpu=True): hsv = image_ops.rgb_to_hsv(rgb_np) rgb = image_ops.hsv_to_rgb(hsv) rgb_tf = self.evaluate(rgb) self.assertAllClose(rgb_tf, rgb_np) class RGBToYIQTest(test_util.TensorFlowTestCase): def testBatch(self): # Build an arbitrary RGB image np.random.seed(7) batch_size = 5 shape = (batch_size, 2, 7, 3) for nptype in [np.float32, np.float64]: inp = np.random.rand(*shape).astype(nptype) # Convert to YIQ and back, as a batch and individually with self.cached_session(use_gpu=True) as sess: batch0 = constant_op.constant(inp) batch1 = image_ops.rgb_to_yiq(batch0) batch2 = image_ops.yiq_to_rgb(batch1) split0 = array_ops.unstack(batch0) split1 = list(map(image_ops.rgb_to_yiq, split0)) split2 = list(map(image_ops.yiq_to_rgb, split1)) join1 = array_ops.stack(split1) join2 = array_ops.stack(split2) batch1, batch2, join1, join2 = self.evaluate( [batch1, batch2, join1, join2]) # Verify that processing batch elements together is the same as separate self.assertAllClose(batch1, join1, rtol=1e-4, atol=1e-4) self.assertAllClose(batch2, join2, rtol=1e-4, atol=1e-4) self.assertAllClose(batch2, inp, rtol=1e-4, atol=1e-4) class RGBToYUVTest(test_util.TensorFlowTestCase): def testBatch(self): # Build an arbitrary RGB image np.random.seed(7) batch_size = 5 shape = (batch_size, 2, 7, 3) for nptype in [np.float32, np.float64]: inp = np.random.rand(*shape).astype(nptype) # Convert to YUV and back, as a batch and individually with self.cached_session(use_gpu=True) as sess: batch0 = constant_op.constant(inp) batch1 = image_ops.rgb_to_yuv(batch0) batch2 = image_ops.yuv_to_rgb(batch1) split0 = array_ops.unstack(batch0) split1 = list(map(image_ops.rgb_to_yuv, split0)) split2 = list(map(image_ops.yuv_to_rgb, split1)) join1 = array_ops.stack(split1) join2 = array_ops.stack(split2) batch1, batch2, join1, join2 = self.evaluate( [batch1, batch2, join1, join2]) # Verify that processing batch elements together is the same as separate self.assertAllClose(batch1, join1, rtol=1e-4, atol=1e-4) self.assertAllClose(batch2, join2, rtol=1e-4, atol=1e-4) self.assertAllClose(batch2, inp, rtol=1e-4, atol=1e-4) class GrayscaleToRGBTest(test_util.TensorFlowTestCase): def _RGBToGrayscale(self, images): is_batch = True if len(images.shape) == 3: is_batch = False images = np.expand_dims(images, axis=0) out_shape = images.shape[0:3] + (1,) out = np.zeros(shape=out_shape, dtype=np.uint8) for batch in xrange(images.shape[0]): for y in xrange(images.shape[1]): for x in xrange(images.shape[2]): red = images[batch, y, x, 0] green = images[batch, y, x, 1] blue = images[batch, y, x, 2] gray = 0.2989 * red + 0.5870 * green + 0.1140 * blue out[batch, y, x, 0] = int(gray) if not is_batch: out = np.squeeze(out, axis=0) return out def _TestRGBToGrayscale(self, x_np): y_np = self._RGBToGrayscale(x_np) with self.cached_session(use_gpu=True): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.rgb_to_grayscale(x_tf) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, y_np) def testBasicRGBToGrayscale(self): # 4-D input with batch dimension. x_np = np.array( [[1, 2, 3], [4, 10, 1]], dtype=np.uint8).reshape([1, 1, 2, 3]) self._TestRGBToGrayscale(x_np) # 3-D input with no batch dimension. x_np = np.array([[1, 2, 3], [4, 10, 1]], dtype=np.uint8).reshape([1, 2, 3]) self._TestRGBToGrayscale(x_np) def testBasicGrayscaleToRGB(self): # 4-D input with batch dimension. x_np = np.array([[1, 2]], dtype=np.uint8).reshape([1, 1, 2, 1]) y_np = np.array( [[1, 1, 1], [2, 2, 2]], dtype=np.uint8).reshape([1, 1, 2, 3]) with self.cached_session(use_gpu=True): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.grayscale_to_rgb(x_tf) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, y_np) # 3-D input with no batch dimension. x_np = np.array([[1, 2]], dtype=np.uint8).reshape([1, 2, 1]) y_np = np.array([[1, 1, 1], [2, 2, 2]], dtype=np.uint8).reshape([1, 2, 3]) with self.cached_session(use_gpu=True): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.grayscale_to_rgb(x_tf) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, y_np) def testGrayscaleToRGBInputValidation(self): # tests whether the grayscale_to_rgb function raises # an exception if the input images' last dimension is # not of size 1, i.e. the images have shape # [batch size, height, width] or [height, width] # tests if an exception is raised if a three dimensional # input is used, i.e. the images have shape [batch size, height, width] with self.cached_session(use_gpu=True): # 3-D input with batch dimension. x_np = np.array([[1, 2]], dtype=np.uint8).reshape([1, 1, 2]) x_tf = constant_op.constant(x_np, shape=x_np.shape) # this is the error message we expect the function to raise err_msg = "Last dimension of a grayscale image should be size 1" with self.assertRaisesRegexp(ValueError, err_msg): image_ops.grayscale_to_rgb(x_tf) # tests if an exception is raised if a two dimensional # input is used, i.e. the images have shape [height, width] with self.cached_session(use_gpu=True): # 1-D input without batch dimension. x_np = np.array([[1, 2]], dtype=np.uint8).reshape([2]) x_tf = constant_op.constant(x_np, shape=x_np.shape) # this is the error message we expect the function to raise err_msg = "A grayscale image must be at least two-dimensional" with self.assertRaisesRegexp(ValueError, err_msg): image_ops.grayscale_to_rgb(x_tf) @test_util.run_deprecated_v1 def testShapeInference(self): # Shape inference works and produces expected output where possible rgb_shape = [7, None, 19, 3] gray_shape = rgb_shape[:-1] + [1] with self.cached_session(use_gpu=True): rgb_tf = array_ops.placeholder(dtypes.uint8, shape=rgb_shape) gray = image_ops.rgb_to_grayscale(rgb_tf) self.assertEqual(gray_shape, gray.get_shape().as_list()) with self.cached_session(use_gpu=True): gray_tf = array_ops.placeholder(dtypes.uint8, shape=gray_shape) rgb = image_ops.grayscale_to_rgb(gray_tf) self.assertEqual(rgb_shape, rgb.get_shape().as_list()) # Shape inference does not break for unknown shapes with self.cached_session(use_gpu=True): rgb_tf_unknown = array_ops.placeholder(dtypes.uint8) gray_unknown = image_ops.rgb_to_grayscale(rgb_tf_unknown) self.assertFalse(gray_unknown.get_shape()) with self.cached_session(use_gpu=True): gray_tf_unknown = array_ops.placeholder(dtypes.uint8) rgb_unknown = image_ops.grayscale_to_rgb(gray_tf_unknown) self.assertFalse(rgb_unknown.get_shape()) class AdjustGamma(test_util.TensorFlowTestCase): @test_util.run_deprecated_v1 def test_adjust_gamma_less_zero_float32(self): """White image should be returned for gamma equal to zero""" with self.cached_session(): x_data = np.random.uniform(0, 1.0, (8, 8)) x_np = np.array(x_data, dtype=np.float32) x = constant_op.constant(x_np, shape=x_np.shape) err_msg = "Gamma should be a non-negative real number" with self.assertRaisesRegexp(ValueError, err_msg): image_ops.adjust_gamma(x, gamma=-1) @test_util.run_deprecated_v1 def test_adjust_gamma_less_zero_uint8(self): """White image should be returned for gamma equal to zero""" with self.cached_session(): x_data = np.random.uniform(0, 255, (8, 8)) x_np = np.array(x_data, dtype=np.uint8) x = constant_op.constant(x_np, shape=x_np.shape) err_msg = "Gamma should be a non-negative real number" with self.assertRaisesRegexp(ValueError, err_msg): image_ops.adjust_gamma(x, gamma=-1) @test_util.run_deprecated_v1 def test_adjust_gamma_less_zero_tensor(self): """White image should be returned for gamma equal to zero""" with self.cached_session(): x_data = np.random.uniform(0, 1.0, (8, 8)) x_np = np.array(x_data, dtype=np.float32) x = constant_op.constant(x_np, shape=x_np.shape) y = constant_op.constant(-1.0, dtype=dtypes.float32) image = image_ops.adjust_gamma(x, gamma=y) err_msg = "Gamma should be a non-negative real number" with self.assertRaisesRegexp(errors.InvalidArgumentError, err_msg): self.evaluate(image) def _test_adjust_gamma_uint8(self, gamma): """Verifying the output with expected results for gamma correction for uint8 images """ with self.cached_session(): x_np = np.random.uniform(0, 255, (8, 8)).astype(np.uint8) x = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.adjust_gamma(x, gamma=gamma) y_tf = np.trunc(y.eval()) # calculate gamma correction using numpy # firstly, transform uint8 to float representation # then perform correction y_np = np.power(x_np / 255.0, gamma) # convert correct numpy image back to uint8 type y_np = np.trunc(np.clip(y_np * 255.5, 0, 255.0)) self.assertAllClose(y_tf, y_np, 1e-6) def _test_adjust_gamma_float32(self, gamma): """Verifying the output with expected results for gamma correction for float32 images """ with self.cached_session(): x_np = np.random.uniform(0, 1.0, (8, 8)) x = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.adjust_gamma(x, gamma=gamma) y_tf = y.eval() y_np = np.clip(np.power(x_np, gamma), 0, 1.0) self.assertAllClose(y_tf, y_np, 1e-6) @test_util.run_deprecated_v1 def test_adjust_gamma_one_float32(self): """Same image should be returned for gamma equal to one""" self._test_adjust_gamma_float32(1.0) @test_util.run_deprecated_v1 def test_adjust_gamma_one_uint8(self): self._test_adjust_gamma_uint8(1.0) @test_util.run_deprecated_v1 def test_adjust_gamma_zero_uint8(self): """White image should be returned for gamma equal to zero for uint8 images """ self._test_adjust_gamma_uint8(gamma=0.0) @test_util.run_deprecated_v1 def test_adjust_gamma_less_one_uint8(self): """Verifying the output with expected results for gamma correction with gamma equal to half for uint8 images """ self._test_adjust_gamma_uint8(gamma=0.5) @test_util.run_deprecated_v1 def test_adjust_gamma_greater_one_uint8(self): """Verifying the output with expected results for gamma correction for uint8 images """ self._test_adjust_gamma_uint8(gamma=1.0) @test_util.run_deprecated_v1 def test_adjust_gamma_less_one_float32(self): """Verifying the output with expected results for gamma correction with gamma equal to half for float32 images """ self._test_adjust_gamma_float32(0.5) @test_util.run_deprecated_v1 def test_adjust_gamma_greater_one_float32(self): """Verifying the output with expected results for gamma correction with gamma equal to two for float32 images """ self._test_adjust_gamma_float32(1.0) @test_util.run_deprecated_v1 def test_adjust_gamma_zero_float32(self): """White image should be returned for gamma equal to zero for float32 images """ self._test_adjust_gamma_float32(0.0) class AdjustHueTest(test_util.TensorFlowTestCase): def testAdjustNegativeHue(self): x_shape = [2, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.uint8).reshape(x_shape) delta = -0.25 y_data = [0, 13, 1, 54, 226, 59, 8, 234, 150, 255, 39, 1] y_np = np.array(y_data, dtype=np.uint8).reshape(x_shape) with self.cached_session(use_gpu=True): x = constant_op.constant(x_np, shape=x_shape) y = image_ops.adjust_hue(x, delta) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, y_np) def testAdjustPositiveHue(self): x_shape = [2, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.uint8).reshape(x_shape) delta = 0.25 y_data = [13, 0, 11, 226, 54, 221, 234, 8, 92, 1, 217, 255] y_np = np.array(y_data, dtype=np.uint8).reshape(x_shape) with self.cached_session(use_gpu=True): x = constant_op.constant(x_np, shape=x_shape) y = image_ops.adjust_hue(x, delta) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, y_np) def testBatchAdjustHue(self): x_shape = [2, 1, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.uint8).reshape(x_shape) delta = 0.25 y_data = [13, 0, 11, 226, 54, 221, 234, 8, 92, 1, 217, 255] y_np = np.array(y_data, dtype=np.uint8).reshape(x_shape) with self.cached_session(use_gpu=True): x = constant_op.constant(x_np, shape=x_shape) y = image_ops.adjust_hue(x, delta) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, y_np) def _adjustHueNp(self, x_np, delta_h): self.assertEqual(x_np.shape[-1], 3) x_v = x_np.reshape([-1, 3]) y_v = np.ndarray(x_v.shape, dtype=x_v.dtype) channel_count = x_v.shape[0] for i in xrange(channel_count): r = x_v[i][0] g = x_v[i][1] b = x_v[i][2] h, s, v = colorsys.rgb_to_hsv(r, g, b) h += delta_h h = math.fmod(h + 10.0, 1.0) r, g, b = colorsys.hsv_to_rgb(h, s, v) y_v[i][0] = r y_v[i][1] = g y_v[i][2] = b return y_v.reshape(x_np.shape) def _adjustHueTf(self, x_np, delta_h): with self.cached_session(use_gpu=True): x = constant_op.constant(x_np) y = image_ops.adjust_hue(x, delta_h) y_tf = self.evaluate(y) return y_tf def testAdjustRandomHue(self): x_shapes = [ [2, 2, 3], [4, 2, 3], [2, 4, 3], [2, 5, 3], [1000, 1, 3], ] test_styles = [ "all_random", "rg_same", "rb_same", "gb_same", "rgb_same", ] for x_shape in x_shapes: for test_style in test_styles: x_np = np.random.rand(*x_shape) * 255. delta_h = np.random.rand() * 2.0 - 1.0 if test_style == "all_random": pass elif test_style == "rg_same": x_np[..., 1] = x_np[..., 0] elif test_style == "rb_same": x_np[..., 2] = x_np[..., 0] elif test_style == "gb_same": x_np[..., 2] = x_np[..., 1] elif test_style == "rgb_same": x_np[..., 1] = x_np[..., 0] x_np[..., 2] = x_np[..., 0] else: raise AssertionError("Invalid test style: %s" % (test_style)) y_np = self._adjustHueNp(x_np, delta_h) y_tf = self._adjustHueTf(x_np, delta_h) self.assertAllClose(y_tf, y_np, rtol=2e-5, atol=1e-5) def testInvalidShapes(self): fused = False if not fused: # The tests are known to pass with the fused adjust_hue. We will enable # them when the fused implementation is the default. return x_np = np.random.rand(2, 3) * 255. delta_h = np.random.rand() * 2.0 - 1.0 fused = False with self.assertRaisesRegexp(ValueError, "Shape must be at least rank 3"): self._adjustHueTf(x_np, delta_h) x_np = np.random.rand(4, 2, 4) * 255. delta_h = np.random.rand() * 2.0 - 1.0 with self.assertRaisesOpError("input must have 3 channels"): self._adjustHueTf(x_np, delta_h) class FlipImageBenchmark(test.Benchmark): def _benchmarkFlipLeftRight(self, device, cpu_count): image_shape = [299, 299, 3] warmup_rounds = 100 benchmark_rounds = 1000 config = config_pb2.ConfigProto() if cpu_count is not None: config.inter_op_parallelism_threads = 1 config.intra_op_parallelism_threads = cpu_count with session.Session("", graph=ops.Graph(), config=config) as sess: with ops.device(device): inputs = variables.Variable( random_ops.random_uniform(image_shape, dtype=dtypes.float32) * 255, trainable=False, dtype=dtypes.float32) run_op = image_ops.flip_left_right(inputs) self.evaluate(variables.global_variables_initializer()) for i in xrange(warmup_rounds + benchmark_rounds): if i == warmup_rounds: start = time.time() self.evaluate(run_op) end = time.time() step_time = (end - start) / benchmark_rounds tag = device + "_%s" % (cpu_count if cpu_count is not None else "_all") print("benchmarkFlipLeftRight_299_299_3_%s step_time: %.2f us" % (tag, step_time * 1e6)) self.report_benchmark( name="benchmarkFlipLeftRight_299_299_3_%s" % (tag), iters=benchmark_rounds, wall_time=step_time) def _benchmarkRandomFlipLeftRight(self, device, cpu_count): image_shape = [299, 299, 3] warmup_rounds = 100 benchmark_rounds = 1000 config = config_pb2.ConfigProto() if cpu_count is not None: config.inter_op_parallelism_threads = 1 config.intra_op_parallelism_threads = cpu_count with session.Session("", graph=ops.Graph(), config=config) as sess: with ops.device(device): inputs = variables.Variable( random_ops.random_uniform(image_shape, dtype=dtypes.float32) * 255, trainable=False, dtype=dtypes.float32) run_op = image_ops.random_flip_left_right(inputs) self.evaluate(variables.global_variables_initializer()) for i in xrange(warmup_rounds + benchmark_rounds): if i == warmup_rounds: start = time.time() self.evaluate(run_op) end = time.time() step_time = (end - start) / benchmark_rounds tag = device + "_%s" % (cpu_count if cpu_count is not None else "_all") print("benchmarkRandomFlipLeftRight_299_299_3_%s step_time: %.2f us" % (tag, step_time * 1e6)) self.report_benchmark( name="benchmarkRandomFlipLeftRight_299_299_3_%s" % (tag), iters=benchmark_rounds, wall_time=step_time) def _benchmarkBatchedRandomFlipLeftRight(self, device, cpu_count): image_shape = [16, 299, 299, 3] warmup_rounds = 100 benchmark_rounds = 1000 config = config_pb2.ConfigProto() if cpu_count is not None: config.inter_op_parallelism_threads = 1 config.intra_op_parallelism_threads = cpu_count with session.Session("", graph=ops.Graph(), config=config) as sess: with ops.device(device): inputs = variables.Variable( random_ops.random_uniform(image_shape, dtype=dtypes.float32) * 255, trainable=False, dtype=dtypes.float32) run_op = image_ops.random_flip_left_right(inputs) self.evaluate(variables.global_variables_initializer()) for i in xrange(warmup_rounds + benchmark_rounds): if i == warmup_rounds: start = time.time() self.evaluate(run_op) end = time.time() step_time = (end - start) / benchmark_rounds tag = device + "_%s" % (cpu_count if cpu_count is not None else "_all") print("benchmarkBatchedRandomFlipLeftRight_16_299_299_3_%s step_time: " "%.2f us" % (tag, step_time * 1e6)) self.report_benchmark( name="benchmarkBatchedRandomFlipLeftRight_16_299_299_3_%s" % (tag), iters=benchmark_rounds, wall_time=step_time) def benchmarkFlipLeftRightCpu1(self): self._benchmarkFlipLeftRight("/cpu:0", 1) def benchmarkFlipLeftRightCpuAll(self): self._benchmarkFlipLeftRight("/cpu:0", None) def benchmarkFlipLeftRightGpu(self): self._benchmarkFlipLeftRight(test.gpu_device_name(), None) def benchmarkRandomFlipLeftRightCpu1(self): self._benchmarkRandomFlipLeftRight("/cpu:0", 1) def benchmarkRandomFlipLeftRightCpuAll(self): self._benchmarkRandomFlipLeftRight("/cpu:0", None) def benchmarkRandomFlipLeftRightGpu(self): self._benchmarkRandomFlipLeftRight(test.gpu_device_name(), None) def benchmarkBatchedRandomFlipLeftRightCpu1(self): self._benchmarkBatchedRandomFlipLeftRight("/cpu:0", 1) def benchmarkBatchedRandomFlipLeftRightCpuAll(self): self._benchmarkBatchedRandomFlipLeftRight("/cpu:0", None) def benchmarkBatchedRandomFlipLeftRightGpu(self): self._benchmarkBatchedRandomFlipLeftRight(test.gpu_device_name(), None) class AdjustHueBenchmark(test.Benchmark): def _benchmarkAdjustHue(self, device, cpu_count): image_shape = [299, 299, 3] warmup_rounds = 100 benchmark_rounds = 1000 config = config_pb2.ConfigProto() if cpu_count is not None: config.inter_op_parallelism_threads = 1 config.intra_op_parallelism_threads = cpu_count with self.benchmark_session(config=config, device=device) as sess: inputs = variables.Variable( random_ops.random_uniform(image_shape, dtype=dtypes.float32) * 255, trainable=False, dtype=dtypes.float32) delta = constant_op.constant(0.1, dtype=dtypes.float32) outputs = image_ops.adjust_hue(inputs, delta) run_op = control_flow_ops.group(outputs) self.evaluate(variables.global_variables_initializer()) for i in xrange(warmup_rounds + benchmark_rounds): if i == warmup_rounds: start = time.time() self.evaluate(run_op) end = time.time() step_time = (end - start) / benchmark_rounds tag = device + "_%s" % (cpu_count if cpu_count is not None else "_all") print("benchmarkAdjustHue_299_299_3_%s step_time: %.2f us" % (tag, step_time * 1e6)) self.report_benchmark( name="benchmarkAdjustHue_299_299_3_%s" % (tag), iters=benchmark_rounds, wall_time=step_time) def benchmarkAdjustHueCpu1(self): self._benchmarkAdjustHue("/cpu:0", 1) def benchmarkAdjustHueCpuAll(self): self._benchmarkAdjustHue("/cpu:0", None) def benchmarkAdjustHueGpu(self): self._benchmarkAdjustHue(test.gpu_device_name(), None) class AdjustSaturationBenchmark(test.Benchmark): def _benchmarkAdjustSaturation(self, device, cpu_count): image_shape = [299, 299, 3] warmup_rounds = 100 benchmark_rounds = 1000 config = config_pb2.ConfigProto() if cpu_count is not None: config.inter_op_parallelism_threads = 1 config.intra_op_parallelism_threads = cpu_count with self.benchmark_session(config=config, device=device) as sess: inputs = variables.Variable( random_ops.random_uniform(image_shape, dtype=dtypes.float32) * 255, trainable=False, dtype=dtypes.float32) delta = constant_op.constant(0.1, dtype=dtypes.float32) outputs = image_ops.adjust_saturation(inputs, delta) run_op = control_flow_ops.group(outputs) self.evaluate(variables.global_variables_initializer()) for _ in xrange(warmup_rounds): self.evaluate(run_op) start = time.time() for _ in xrange(benchmark_rounds): self.evaluate(run_op) end = time.time() step_time = (end - start) / benchmark_rounds tag = device + "_%s" % (cpu_count if cpu_count is not None else "_all") print("benchmarkAdjustSaturation_299_299_3_%s step_time: %.2f us" % (tag, step_time * 1e6)) self.report_benchmark( name="benchmarkAdjustSaturation_299_299_3_%s" % (tag), iters=benchmark_rounds, wall_time=step_time) def benchmarkAdjustSaturationCpu1(self): self._benchmarkAdjustSaturation("/cpu:0", 1) def benchmarkAdjustSaturationCpuAll(self): self._benchmarkAdjustSaturation("/cpu:0", None) def benchmarkAdjustSaturationGpu(self): self._benchmarkAdjustSaturation(test.gpu_device_name(), None) class ResizeBilinearBenchmark(test.Benchmark): def _benchmarkResize(self, image_size, num_channels): batch_size = 1 num_ops = 1000 img = variables.Variable( random_ops.random_normal( [batch_size, image_size[0], image_size[1], num_channels]), name="img") deps = [] for _ in xrange(num_ops): with ops.control_dependencies(deps): resize_op = image_ops.resize_bilinear( img, [299, 299], align_corners=False) deps = [resize_op] benchmark_op = control_flow_ops.group(*deps) with self.benchmark_session() as sess: self.evaluate(variables.global_variables_initializer()) results = self.run_op_benchmark( sess, benchmark_op, name=("resize_bilinear_%s_%s_%s" % (image_size[0], image_size[1], num_channels))) print("%s : %.2f ms/img" % (results["name"], 1000 * results["wall_time"] / (batch_size * num_ops))) def benchmarkSimilar3Channel(self): self._benchmarkResize((183, 229), 3) def benchmarkScaleUp3Channel(self): self._benchmarkResize((141, 186), 3) def benchmarkScaleDown3Channel(self): self._benchmarkResize((749, 603), 3) def benchmarkSimilar1Channel(self): self._benchmarkResize((183, 229), 1) def benchmarkScaleUp1Channel(self): self._benchmarkResize((141, 186), 1) def benchmarkScaleDown1Channel(self): self._benchmarkResize((749, 603), 1) class ResizeBicubicBenchmark(test.Benchmark): def _benchmarkResize(self, image_size, num_channels): batch_size = 1 num_ops = 1000 img = variables.Variable( random_ops.random_normal( [batch_size, image_size[0], image_size[1], num_channels]), name="img") deps = [] for _ in xrange(num_ops): with ops.control_dependencies(deps): resize_op = image_ops.resize_bicubic( img, [299, 299], align_corners=False) deps = [resize_op] benchmark_op = control_flow_ops.group(*deps) with self.benchmark_session() as sess: self.evaluate(variables.global_variables_initializer()) results = self.run_op_benchmark( sess, benchmark_op, min_iters=20, name=("resize_bicubic_%s_%s_%s" % (image_size[0], image_size[1], num_channels))) print("%s : %.2f ms/img" % (results["name"], 1000 * results["wall_time"] / (batch_size * num_ops))) def benchmarkSimilar3Channel(self): self._benchmarkResize((183, 229), 3) def benchmarkScaleUp3Channel(self): self._benchmarkResize((141, 186), 3) def benchmarkScaleDown3Channel(self): self._benchmarkResize((749, 603), 3) def benchmarkSimilar1Channel(self): self._benchmarkResize((183, 229), 1) def benchmarkScaleUp1Channel(self): self._benchmarkResize((141, 186), 1) def benchmarkScaleDown1Channel(self): self._benchmarkResize((749, 603), 1) def benchmarkSimilar4Channel(self): self._benchmarkResize((183, 229), 4) def benchmarkScaleUp4Channel(self): self._benchmarkResize((141, 186), 4) def benchmarkScaleDown4Channel(self): self._benchmarkResize((749, 603), 4) class ResizeAreaBenchmark(test.Benchmark): def _benchmarkResize(self, image_size, num_channels): batch_size = 1 num_ops = 1000 img = variables.Variable( random_ops.random_normal( [batch_size, image_size[0], image_size[1], num_channels]), name="img") deps = [] for _ in xrange(num_ops): with ops.control_dependencies(deps): resize_op = image_ops.resize_area(img, [299, 299], align_corners=False) deps = [resize_op] benchmark_op = control_flow_ops.group(*deps) with self.benchmark_session() as sess: self.evaluate(variables.global_variables_initializer()) results = self.run_op_benchmark( sess, benchmark_op, name=("resize_area_%s_%s_%s" % (image_size[0], image_size[1], num_channels))) print("%s : %.2f ms/img" % (results["name"], 1000 * results["wall_time"] / (batch_size * num_ops))) def benchmarkSimilar3Channel(self): self._benchmarkResize((183, 229), 3) def benchmarkScaleUp3Channel(self): self._benchmarkResize((141, 186), 3) def benchmarkScaleDown3Channel(self): self._benchmarkResize((749, 603), 3) def benchmarkSimilar1Channel(self): self._benchmarkResize((183, 229), 1) def benchmarkScaleUp1Channel(self): self._benchmarkResize((141, 186), 1) def benchmarkScaleDown1Channel(self): self._benchmarkResize((749, 603), 1) class AdjustSaturationTest(test_util.TensorFlowTestCase): def testHalfSaturation(self): x_shape = [2, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.uint8).reshape(x_shape) saturation_factor = 0.5 y_data = [6, 9, 13, 140, 180, 226, 135, 121, 234, 172, 255, 128] y_np = np.array(y_data, dtype=np.uint8).reshape(x_shape) with self.cached_session(use_gpu=True): x = constant_op.constant(x_np, shape=x_shape) y = image_ops.adjust_saturation(x, saturation_factor) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, y_np) def testTwiceSaturation(self): x_shape = [2, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.uint8).reshape(x_shape) saturation_factor = 2.0 y_data = [0, 5, 13, 0, 106, 226, 30, 0, 234, 89, 255, 0] y_np = np.array(y_data, dtype=np.uint8).reshape(x_shape) with self.cached_session(use_gpu=True): x = constant_op.constant(x_np, shape=x_shape) y = image_ops.adjust_saturation(x, saturation_factor) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, y_np) def testBatchSaturation(self): x_shape = [2, 1, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.uint8).reshape(x_shape) saturation_factor = 0.5 y_data = [6, 9, 13, 140, 180, 226, 135, 121, 234, 172, 255, 128] y_np = np.array(y_data, dtype=np.uint8).reshape(x_shape) with self.cached_session(use_gpu=True): x = constant_op.constant(x_np, shape=x_shape) y = image_ops.adjust_saturation(x, saturation_factor) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, y_np) def _adjustSaturationNp(self, x_np, scale): self.assertEqual(x_np.shape[-1], 3) x_v = x_np.reshape([-1, 3]) y_v = np.ndarray(x_v.shape, dtype=x_v.dtype) channel_count = x_v.shape[0] for i in xrange(channel_count): r = x_v[i][0] g = x_v[i][1] b = x_v[i][2] h, s, v = colorsys.rgb_to_hsv(r, g, b) s *= scale s = min(1.0, max(0.0, s)) r, g, b = colorsys.hsv_to_rgb(h, s, v) y_v[i][0] = r y_v[i][1] = g y_v[i][2] = b return y_v.reshape(x_np.shape) @test_util.run_deprecated_v1 def testAdjustRandomSaturation(self): x_shapes = [ [2, 2, 3], [4, 2, 3], [2, 4, 3], [2, 5, 3], [1000, 1, 3], ] test_styles = [ "all_random", "rg_same", "rb_same", "gb_same", "rgb_same", ] with self.cached_session(use_gpu=True): for x_shape in x_shapes: for test_style in test_styles: x_np = np.random.rand(*x_shape) * 255. scale = np.random.rand() if test_style == "all_random": pass elif test_style == "rg_same": x_np[..., 1] = x_np[..., 0] elif test_style == "rb_same": x_np[..., 2] = x_np[..., 0] elif test_style == "gb_same": x_np[..., 2] = x_np[..., 1] elif test_style == "rgb_same": x_np[..., 1] = x_np[..., 0] x_np[..., 2] = x_np[..., 0] else: raise AssertionError("Invalid test style: %s" % (test_style)) y_baseline = self._adjustSaturationNp(x_np, scale) y_fused = image_ops.adjust_saturation(x_np, scale).eval() self.assertAllClose(y_fused, y_baseline, rtol=2e-5, atol=1e-5) class FlipTransposeRotateTest(test_util.TensorFlowTestCase): def testInvolutionLeftRight(self): x_np = np.array([[1, 2, 3], [1, 2, 3]], dtype=np.uint8).reshape([2, 3, 1]) with self.cached_session(use_gpu=True): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.flip_left_right(image_ops.flip_left_right(x_tf)) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, x_np) def testInvolutionLeftRightWithBatch(self): x_np = np.array( [[[1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3]]], dtype=np.uint8).reshape([2, 2, 3, 1]) with self.cached_session(use_gpu=True): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.flip_left_right(image_ops.flip_left_right(x_tf)) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, x_np) @test_util.run_deprecated_v1 def testLeftRight(self): x_np = np.array([[1, 2, 3], [1, 2, 3]], dtype=np.uint8).reshape([2, 3, 1]) y_np = np.array([[3, 2, 1], [3, 2, 1]], dtype=np.uint8).reshape([2, 3, 1]) with self.cached_session(use_gpu=True): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.flip_left_right(x_tf) self.assertTrue(y.op.name.startswith("flip_left_right")) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, y_np) def testLeftRightWithBatch(self): x_np = np.array( [[[1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3]]], dtype=np.uint8).reshape([2, 2, 3, 1]) y_np = np.array( [[[3, 2, 1], [3, 2, 1]], [[3, 2, 1], [3, 2, 1]]], dtype=np.uint8).reshape([2, 2, 3, 1]) with self.cached_session(use_gpu=True): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.flip_left_right(x_tf) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, y_np) @test_util.run_deprecated_v1 def testRandomFlipLeftRight(self): x_np = np.array([[1, 2, 3], [1, 2, 3]], dtype=np.uint8).reshape([2, 3, 1]) y_np = np.array([[3, 2, 1], [3, 2, 1]], dtype=np.uint8).reshape([2, 3, 1]) seed = 42 with self.cached_session(use_gpu=True): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.random_flip_left_right(x_tf, seed=seed) self.assertTrue(y.op.name.startswith("random_flip_left_right")) count_flipped = 0 count_unflipped = 0 for _ in range(100): y_tf = self.evaluate(y) if y_tf[0][0] == 1: self.assertAllEqual(y_tf, x_np) count_unflipped += 1 else: self.assertAllEqual(y_tf, y_np) count_flipped += 1 # 100 trials # Mean: 50 # Std Dev: ~5 # Six Sigma: 50 - (5 * 6) = 20 self.assertGreaterEqual(count_flipped, 20) self.assertGreaterEqual(count_unflipped, 20) @test_util.run_deprecated_v1 def testRandomFlipLeftRightWithBatch(self): batch_size = 16 seed = 42 # create single item of test data x_np_raw = np.array( [[1, 2, 3], [1, 2, 3]], dtype=np.uint8 ).reshape([1, 2, 3, 1]) y_np_raw = np.array( [[3, 2, 1], [3, 2, 1]], dtype=np.uint8 ).reshape([1, 2, 3, 1]) # create batched test data x_np = np.vstack([x_np_raw for _ in range(batch_size)]) y_np = np.vstack([y_np_raw for _ in range(batch_size)]) with self.cached_session(use_gpu=True): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.random_flip_left_right(x_tf, seed=seed) self.assertTrue(y.op.name.startswith("random_flip_left_right")) count_flipped = 0 count_unflipped = 0 for _ in range(100): y_tf = self.evaluate(y) # check every element of the batch for i in range(batch_size): if y_tf[i][0][0] == 1: self.assertAllEqual(y_tf[i], x_np[i]) count_unflipped += 1 else: self.assertAllEqual(y_tf[i], y_np[i]) count_flipped += 1 # 100 trials, each containing batch_size elements # Mean: 50 * batch_size # Std Dev: ~5 * sqrt(batch_size) # Six Sigma: 50 * batch_size - (5 * 6 * sqrt(batch_size)) # = 50 * batch_size - 30 * sqrt(batch_size) = 800 - 30 * 4 = 680 six_sigma = 50 * batch_size - 30 * np.sqrt(batch_size) self.assertGreaterEqual(count_flipped, six_sigma) self.assertGreaterEqual(count_unflipped, six_sigma) def testInvolutionUpDown(self): x_np = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.uint8).reshape([2, 3, 1]) with self.cached_session(use_gpu=True): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.flip_up_down(image_ops.flip_up_down(x_tf)) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, x_np) def testInvolutionUpDownWithBatch(self): x_np = np.array( [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]], dtype=np.uint8).reshape([2, 2, 3, 1]) with self.cached_session(use_gpu=True): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.flip_up_down(image_ops.flip_up_down(x_tf)) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, x_np) @test_util.run_deprecated_v1 def testUpDown(self): x_np = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.uint8).reshape([2, 3, 1]) y_np = np.array([[4, 5, 6], [1, 2, 3]], dtype=np.uint8).reshape([2, 3, 1]) with self.cached_session(use_gpu=True): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.flip_up_down(x_tf) self.assertTrue(y.op.name.startswith("flip_up_down")) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, y_np) def testUpDownWithBatch(self): x_np = np.array( [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]], dtype=np.uint8).reshape([2, 2, 3, 1]) y_np = np.array( [[[4, 5, 6], [1, 2, 3]], [[10, 11, 12], [7, 8, 9]]], dtype=np.uint8).reshape([2, 2, 3, 1]) with self.cached_session(use_gpu=True): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.flip_up_down(x_tf) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, y_np) @test_util.run_deprecated_v1 def testRandomFlipUpDown(self): x_np = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.uint8).reshape([2, 3, 1]) y_np = np.array([[4, 5, 6], [1, 2, 3]], dtype=np.uint8).reshape([2, 3, 1]) seed = 42 with self.cached_session(use_gpu=True): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.random_flip_up_down(x_tf, seed=seed) self.assertTrue(y.op.name.startswith("random_flip_up_down")) count_flipped = 0 count_unflipped = 0 for _ in range(100): y_tf = self.evaluate(y) if y_tf[0][0] == 1: self.assertAllEqual(y_tf, x_np) count_unflipped += 1 else: self.assertAllEqual(y_tf, y_np) count_flipped += 1 # 100 trials # Mean: 50 # Std Dev: ~5 # Six Sigma: 50 - (5 * 6) = 20 self.assertGreaterEqual(count_flipped, 20) self.assertGreaterEqual(count_unflipped, 20) @test_util.run_deprecated_v1 def testRandomFlipUpDownWithBatch(self): batch_size = 16 seed = 42 # create single item of test data x_np_raw = np.array( [[1, 2, 3], [4, 5, 6]], dtype=np.uint8 ).reshape([1, 2, 3, 1]) y_np_raw = np.array( [[4, 5, 6], [1, 2, 3]], dtype=np.uint8 ).reshape([1, 2, 3, 1]) # create batched test data x_np = np.vstack([x_np_raw for _ in range(batch_size)]) y_np = np.vstack([y_np_raw for _ in range(batch_size)]) with self.cached_session(use_gpu=True): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.random_flip_up_down(x_tf, seed=seed) self.assertTrue(y.op.name.startswith("random_flip_up_down")) count_flipped = 0 count_unflipped = 0 for _ in range(100): y_tf = self.evaluate(y) # check every element of the batch for i in range(batch_size): if y_tf[i][0][0] == 1: self.assertAllEqual(y_tf[i], x_np[i]) count_unflipped += 1 else: self.assertAllEqual(y_tf[i], y_np[i]) count_flipped += 1 # 100 trials, each containing batch_size elements # Mean: 50 * batch_size # Std Dev: ~5 * sqrt(batch_size) # Six Sigma: 50 * batch_size - (5 * 6 * sqrt(batch_size)) # = 50 * batch_size - 30 * sqrt(batch_size) = 800 - 30 * 4 = 680 six_sigma = 50 * batch_size - 30 * np.sqrt(batch_size) self.assertGreaterEqual(count_flipped, six_sigma) self.assertGreaterEqual(count_unflipped, six_sigma) def testInvolutionTranspose(self): x_np = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.uint8).reshape([2, 3, 1]) with self.cached_session(use_gpu=True): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.transpose(image_ops.transpose(x_tf)) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, x_np) def testInvolutionTransposeWithBatch(self): x_np = np.array( [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]], dtype=np.uint8).reshape([2, 2, 3, 1]) with self.cached_session(use_gpu=True): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.transpose(image_ops.transpose(x_tf)) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, x_np) @test_util.run_deprecated_v1 def testTranspose(self): x_np = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.uint8).reshape([2, 3, 1]) y_np = np.array([[1, 4], [2, 5], [3, 6]], dtype=np.uint8).reshape([3, 2, 1]) with self.cached_session(use_gpu=True): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.transpose(x_tf) self.assertTrue(y.op.name.startswith("transpose")) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, y_np) def testTransposeWithBatch(self): x_np = np.array( [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]], dtype=np.uint8).reshape([2, 2, 3, 1]) y_np = np.array( [[[1, 4], [2, 5], [3, 6]], [[7, 10], [8, 11], [9, 12]]], dtype=np.uint8).reshape([2, 3, 2, 1]) with self.cached_session(use_gpu=True): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.transpose(x_tf) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, y_np) @test_util.run_deprecated_v1 def testPartialShapes(self): p_unknown_rank = array_ops.placeholder(dtypes.uint8) p_unknown_dims_3 = array_ops.placeholder( dtypes.uint8, shape=[None, None, None]) p_unknown_dims_4 = array_ops.placeholder( dtypes.uint8, shape=[None, None, None, None]) p_unknown_width = array_ops.placeholder(dtypes.uint8, shape=[64, None, 3]) p_unknown_batch = array_ops.placeholder( dtypes.uint8, shape=[None, 64, 64, 3]) p_wrong_rank = array_ops.placeholder(dtypes.uint8, shape=[None, None]) p_zero_dim = array_ops.placeholder(dtypes.uint8, shape=[64, 0, 3]) #Ops that support 3D input for op in [ image_ops.flip_left_right, image_ops.flip_up_down, image_ops.random_flip_left_right, image_ops.random_flip_up_down, image_ops.transpose, image_ops.rot90 ]: transformed_unknown_rank = op(p_unknown_rank) self.assertEqual(3, transformed_unknown_rank.get_shape().ndims) transformed_unknown_dims_3 = op(p_unknown_dims_3) self.assertEqual(3, transformed_unknown_dims_3.get_shape().ndims) transformed_unknown_width = op(p_unknown_width) self.assertEqual(3, transformed_unknown_width.get_shape().ndims) with self.assertRaisesRegexp(ValueError, "must be > 0"): op(p_zero_dim) #Ops that support 4D input for op in [ image_ops.flip_left_right, image_ops.flip_up_down, image_ops.random_flip_left_right, image_ops.random_flip_up_down, image_ops.transpose, image_ops.rot90 ]: transformed_unknown_dims_4 = op(p_unknown_dims_4) self.assertEqual(4, transformed_unknown_dims_4.get_shape().ndims) transformed_unknown_batch = op(p_unknown_batch) self.assertEqual(4, transformed_unknown_batch.get_shape().ndims) with self.assertRaisesRegexp(ValueError, "must be at least three-dimensional"): op(p_wrong_rank) def testRot90GroupOrder(self): image = np.arange(24, dtype=np.uint8).reshape([2, 4, 3]) with self.cached_session(use_gpu=True): rotated = image for _ in xrange(4): rotated = image_ops.rot90(rotated) self.assertAllEqual(image, self.evaluate(rotated)) def testRot90GroupOrderWithBatch(self): image = np.arange(48, dtype=np.uint8).reshape([2, 2, 4, 3]) with self.cached_session(use_gpu=True): rotated = image for _ in xrange(4): rotated = image_ops.rot90(rotated) self.assertAllEqual(image, self.evaluate(rotated)) @test_util.run_deprecated_v1 def testRot90NumpyEquivalence(self): image = np.arange(24, dtype=np.uint8).reshape([2, 4, 3]) with self.cached_session(use_gpu=True): k_placeholder = array_ops.placeholder(dtypes.int32, shape=[]) y_tf = image_ops.rot90(image, k_placeholder) for k in xrange(4): y_np = np.rot90(image, k=k) self.assertAllEqual(y_np, y_tf.eval({k_placeholder: k})) @test_util.run_deprecated_v1 def testRot90NumpyEquivalenceWithBatch(self): image = np.arange(48, dtype=np.uint8).reshape([2, 2, 4, 3]) with self.cached_session(use_gpu=True): k_placeholder = array_ops.placeholder(dtypes.int32, shape=[]) y_tf = image_ops.rot90(image, k_placeholder) for k in xrange(4): y_np = np.rot90(image, k=k, axes=(1, 2)) self.assertAllEqual(y_np, y_tf.eval({k_placeholder: k})) class AdjustContrastTest(test_util.TensorFlowTestCase): def _testContrast(self, x_np, y_np, contrast_factor): with self.cached_session(use_gpu=True): x = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.adjust_contrast(x, contrast_factor) y_tf = self.evaluate(y) self.assertAllClose(y_tf, y_np, 1e-6) def testDoubleContrastUint8(self): x_shape = [1, 2, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.uint8).reshape(x_shape) y_data = [0, 0, 0, 62, 169, 255, 28, 0, 255, 135, 255, 0] y_np = np.array(y_data, dtype=np.uint8).reshape(x_shape) self._testContrast(x_np, y_np, contrast_factor=2.0) def testDoubleContrastFloat(self): x_shape = [1, 2, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.float).reshape(x_shape) / 255. y_data = [ -45.25, -90.75, -92.5, 62.75, 169.25, 333.5, 28.75, -84.75, 349.5, 134.75, 409.25, -116.5 ] y_np = np.array(y_data, dtype=np.float).reshape(x_shape) / 255. self._testContrast(x_np, y_np, contrast_factor=2.0) def testHalfContrastUint8(self): x_shape = [1, 2, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.uint8).reshape(x_shape) y_data = [22, 52, 65, 49, 118, 172, 41, 54, 176, 67, 178, 59] y_np = np.array(y_data, dtype=np.uint8).reshape(x_shape) self._testContrast(x_np, y_np, contrast_factor=0.5) def testBatchDoubleContrast(self): x_shape = [2, 1, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.uint8).reshape(x_shape) y_data = [0, 0, 0, 81, 200, 255, 10, 0, 255, 116, 255, 0] y_np = np.array(y_data, dtype=np.uint8).reshape(x_shape) self._testContrast(x_np, y_np, contrast_factor=2.0) def _adjustContrastNp(self, x_np, contrast_factor): mean = np.mean(x_np, (1, 2), keepdims=True) y_np = mean + contrast_factor * (x_np - mean) return y_np def _adjustContrastTf(self, x_np, contrast_factor): with self.cached_session(use_gpu=True): x = constant_op.constant(x_np) y = image_ops.adjust_contrast(x, contrast_factor) y_tf = self.evaluate(y) return y_tf def testRandomContrast(self): x_shapes = [ [1, 2, 2, 3], [2, 1, 2, 3], [1, 2, 2, 3], [2, 5, 5, 3], [2, 1, 1, 3], ] for x_shape in x_shapes: x_np = np.random.rand(*x_shape) * 255. contrast_factor = np.random.rand() * 2.0 + 0.1 y_np = self._adjustContrastNp(x_np, contrast_factor) y_tf = self._adjustContrastTf(x_np, contrast_factor) self.assertAllClose(y_tf, y_np, rtol=1e-5, atol=1e-5) @test_util.run_deprecated_v1 def testContrastFactorShape(self): x_shape = [1, 2, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.uint8).reshape(x_shape) with self.assertRaisesRegexp( ValueError, 'Shape must be rank 0 but is rank 1'): image_ops.adjust_contrast(x_np, [2.0]) class AdjustBrightnessTest(test_util.TensorFlowTestCase): def _testBrightness(self, x_np, y_np, delta, tol=1e-6): with self.cached_session(use_gpu=True): x = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.adjust_brightness(x, delta) y_tf = self.evaluate(y) self.assertAllClose(y_tf, y_np, tol) def testPositiveDeltaUint8(self): x_shape = [2, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.uint8).reshape(x_shape) y_data = [10, 15, 23, 64, 145, 236, 47, 18, 244, 100, 255, 11] y_np = np.array(y_data, dtype=np.uint8).reshape(x_shape) self._testBrightness(x_np, y_np, delta=10. / 255.) def testPositiveDeltaFloat32(self): x_shape = [2, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.float32).reshape(x_shape) / 255. y_data = [10, 15, 23, 64, 145, 236, 47, 18, 244, 100, 265, 11] y_np = np.array(y_data, dtype=np.float32).reshape(x_shape) / 255. self._testBrightness(x_np, y_np, delta=10. / 255.) def testPositiveDeltaFloat16(self): x_shape = [2, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.float16).reshape(x_shape) / 255. y_data = [10, 15, 23, 64, 145, 236, 47, 18, 244, 100, 265, 11] y_np = np.array(y_data, dtype=np.float16).reshape(x_shape) / 255. self._testBrightness(x_np, y_np, delta=10. / 255., tol=1e-3) def testNegativeDelta(self): x_shape = [2, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.uint8).reshape(x_shape) y_data = [0, 0, 3, 44, 125, 216, 27, 0, 224, 80, 245, 0] y_np = np.array(y_data, dtype=np.uint8).reshape(x_shape) self._testBrightness(x_np, y_np, delta=-10. / 255.) class PerImageWhiteningTest(test_util.TensorFlowTestCase): def _NumpyPerImageWhitening(self, x): num_pixels = np.prod(x.shape) mn = np.mean(x) std = np.std(x) stddev = max(std, 1.0 / math.sqrt(num_pixels)) y = x.astype(np.float32) y -= mn y /= stddev return y @test_util.run_deprecated_v1 def testBasic(self): x_shape = [13, 9, 3] x_np = np.arange(0, np.prod(x_shape), dtype=np.float32).reshape(x_shape) y_np = self._NumpyPerImageWhitening(x_np) with self.cached_session(use_gpu=True): x = constant_op.constant(x_np, shape=x_shape) y = image_ops.per_image_standardization(x) self.assertTrue(y.op.name.startswith("per_image_standardization")) y_tf = self.evaluate(y) self.assertAllClose(y_tf, y_np, atol=1e-4) def testUniformImage(self): im_np = np.ones([19, 19, 3]).astype(np.float32) * 249 im = constant_op.constant(im_np) whiten = image_ops.per_image_standardization(im) with self.cached_session(use_gpu=True): whiten_np = self.evaluate(whiten) self.assertFalse(np.any(np.isnan(whiten_np))) def testBatchWhitening(self): imgs_np = np.random.uniform(0., 255., [4, 24, 24, 3]) whiten_np = [self._NumpyPerImageWhitening(img) for img in imgs_np] with self.cached_session(use_gpu=True): imgs = constant_op.constant(imgs_np) whiten = image_ops.per_image_standardization(imgs) whiten_tf = self.evaluate(whiten) for w_tf, w_np in zip(whiten_tf, whiten_np): self.assertAllClose(w_tf, w_np, atol=1e-4) def testPreservesDtype(self): imgs_npu8 = np.random.uniform(0., 255., [2, 5, 5, 3]).astype(np.uint8) imgs_tfu8 = constant_op.constant(imgs_npu8) whiten_tfu8 = image_ops.per_image_standardization(imgs_tfu8) self.assertEqual(whiten_tfu8.dtype, dtypes.uint8) imgs_npf16 = np.random.uniform(0., 255., [2, 5, 5, 3]).astype(np.float16) imgs_tff16 = constant_op.constant(imgs_npf16) whiten_tff16 = image_ops.per_image_standardization(imgs_tff16) self.assertEqual(whiten_tff16.dtype, dtypes.float16) class CropToBoundingBoxTest(test_util.TensorFlowTestCase): def _CropToBoundingBox(self, x, offset_height, offset_width, target_height, target_width, use_tensor_inputs): if use_tensor_inputs: offset_height = ops.convert_to_tensor(offset_height) offset_width = ops.convert_to_tensor(offset_width) target_height = ops.convert_to_tensor(target_height) target_width = ops.convert_to_tensor(target_width) x_tensor = array_ops.placeholder(x.dtype, shape=[None] * x.ndim) feed_dict = {x_tensor: x} else: x_tensor = x feed_dict = {} y = image_ops.crop_to_bounding_box(x_tensor, offset_height, offset_width, target_height, target_width) if not use_tensor_inputs: self.assertTrue(y.get_shape().is_fully_defined()) with self.cached_session(use_gpu=True): return y.eval(feed_dict=feed_dict) def _assertReturns(self, x, x_shape, offset_height, offset_width, y, y_shape, use_tensor_inputs_options=None): use_tensor_inputs_options = use_tensor_inputs_options or [False, True] target_height, target_width, _ = y_shape x = np.array(x).reshape(x_shape) y = np.array(y).reshape(y_shape) for use_tensor_inputs in use_tensor_inputs_options: y_tf = self._CropToBoundingBox(x, offset_height, offset_width, target_height, target_width, use_tensor_inputs) self.assertAllClose(y, y_tf) def _assertRaises(self, x, x_shape, offset_height, offset_width, target_height, target_width, err_msg, use_tensor_inputs_options=None): use_tensor_inputs_options = use_tensor_inputs_options or [False, True] x = np.array(x).reshape(x_shape) for use_tensor_inputs in use_tensor_inputs_options: try: self._CropToBoundingBox(x, offset_height, offset_width, target_height, target_width, use_tensor_inputs) except Exception as e: if err_msg not in str(e): raise else: raise AssertionError("Exception not raised: %s" % err_msg) def _assertShapeInference(self, pre_shape, height, width, post_shape): image = array_ops.placeholder(dtypes.float32, shape=pre_shape) y = image_ops.crop_to_bounding_box(image, 0, 0, height, width) self.assertEqual(y.get_shape().as_list(), post_shape) @test_util.run_deprecated_v1 def testNoOp(self): x_shape = [10, 10, 10] x = np.random.uniform(size=x_shape) self._assertReturns(x, x_shape, 0, 0, x, x_shape) @test_util.run_deprecated_v1 def testCrop(self): x = [1, 2, 3, 4, 5, 6, 7, 8, 9] x_shape = [3, 3, 1] offset_height, offset_width = [1, 0] y_shape = [2, 3, 1] y = [4, 5, 6, 7, 8, 9] self._assertReturns(x, x_shape, offset_height, offset_width, y, y_shape) offset_height, offset_width = [0, 1] y_shape = [3, 2, 1] y = [2, 3, 5, 6, 8, 9] self._assertReturns(x, x_shape, offset_height, offset_width, y, y_shape) offset_height, offset_width = [0, 0] y_shape = [2, 3, 1] y = [1, 2, 3, 4, 5, 6] self._assertReturns(x, x_shape, offset_height, offset_width, y, y_shape) offset_height, offset_width = [0, 0] y_shape = [3, 2, 1] y = [1, 2, 4, 5, 7, 8] self._assertReturns(x, x_shape, offset_height, offset_width, y, y_shape) @test_util.run_deprecated_v1 def testShapeInference(self): self._assertShapeInference([55, 66, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([59, 69, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([None, 66, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([None, 69, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([55, None, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([59, None, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([None, None, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([55, 66, None], 55, 66, [55, 66, None]) self._assertShapeInference([59, 69, None], 55, 66, [55, 66, None]) self._assertShapeInference([None, None, None], 55, 66, [55, 66, None]) self._assertShapeInference(None, 55, 66, [55, 66, None]) @test_util.run_deprecated_v1 def testNon3DInput(self): # Input image is not 3D x = [0] * 15 offset_height, offset_width = [0, 0] target_height, target_width = [2, 2] for x_shape in ([3, 5], [1, 3, 5, 1, 1]): self._assertRaises(x, x_shape, offset_height, offset_width, target_height, target_width, "'image' must have either 3 or 4 dimensions.") @test_util.run_deprecated_v1 def testZeroLengthInput(self): # Input image has 0-length dimension(s). # Each line is a test configuration: # x_shape, target_height, target_width test_config = (([0, 2, 2], 1, 1), ([2, 0, 2], 1, 1), ([2, 2, 0], 1, 1), ([0, 2, 2], 0, 1), ([2, 0, 2], 1, 0)) offset_height, offset_width = [0, 0] x = [] for x_shape, target_height, target_width in test_config: self._assertRaises( x, x_shape, offset_height, offset_width, target_height, target_width, "inner 3 dims of 'image.shape' must be > 0", use_tensor_inputs_options=[False]) # Multiple assertion could fail, but the evaluation order is arbitrary. # Match gainst generic pattern. self._assertRaises( x, x_shape, offset_height, offset_width, target_height, target_width, "assertion failed:", use_tensor_inputs_options=[True]) @test_util.run_deprecated_v1 def testBadParams(self): x_shape = [4, 4, 1] x = np.zeros(x_shape) # Each line is a test configuration: # (offset_height, offset_width, target_height, target_width), err_msg test_config = (([-1, 0, 3, 3], "offset_height must be >= 0"), ([ 0, -1, 3, 3 ], "offset_width must be >= 0"), ([0, 0, 0, 3], "target_height must be > 0"), ([0, 0, 3, 0], "target_width must be > 0"), ([2, 0, 3, 3], "height must be >= target + offset"), ([0, 2, 3, 3], "width must be >= target + offset")) for params, err_msg in test_config: self._assertRaises(x, x_shape, *params, err_msg=err_msg) @test_util.run_deprecated_v1 def testNameScope(self): image = array_ops.placeholder(dtypes.float32, shape=[55, 66, 3]) y = image_ops.crop_to_bounding_box(image, 0, 0, 55, 66) self.assertTrue(y.name.startswith("crop_to_bounding_box")) class CentralCropTest(test_util.TensorFlowTestCase): def _assertShapeInference(self, pre_shape, fraction, post_shape): image = array_ops.placeholder(dtypes.float32, shape=pre_shape) y = image_ops.central_crop(image, fraction) if post_shape is None: self.assertEqual(y.get_shape().dims, None) else: self.assertEqual(y.get_shape().as_list(), post_shape) @test_util.run_deprecated_v1 def testNoOp(self): x_shapes = [[13, 9, 3], [5, 13, 9, 3]] for x_shape in x_shapes: x_np = np.ones(x_shape, dtype=np.float32) for use_gpu in [True, False]: with self.cached_session(use_gpu=use_gpu): x = constant_op.constant(x_np, shape=x_shape) y = image_ops.central_crop(x, 1.0) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, x_np) self.assertEqual(y.op.name, x.op.name) def testCropping(self): x_shape = [4, 8, 1] x_np = np.array( [[1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8]], dtype=np.int32).reshape(x_shape) y_np = np.array([[3, 4, 5, 6], [3, 4, 5, 6]]).reshape([2, 4, 1]) for use_gpu in [True, False]: with self.cached_session(use_gpu=use_gpu): x = constant_op.constant(x_np, shape=x_shape) y = image_ops.central_crop(x, 0.5) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, y_np) self.assertAllEqual(y_tf.shape, y_np.shape) x_shape = [2, 4, 8, 1] x_np = np.array( [[1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8], [8, 7, 6, 5, 4, 3, 2, 1], [8, 7, 6, 5, 4, 3, 2, 1], [8, 7, 6, 5, 4, 3, 2, 1], [8, 7, 6, 5, 4, 3, 2, 1]], dtype=np.int32).reshape(x_shape) y_np = np.array([[[3, 4, 5, 6], [3, 4, 5, 6]], [[6, 5, 4, 3], [6, 5, 4, 3]]]).reshape([2, 2, 4, 1]) with self.cached_session(use_gpu=True): x = constant_op.constant(x_np, shape=x_shape) y = image_ops.central_crop(x, 0.5) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, y_np) self.assertAllEqual(y_tf.shape, y_np.shape) @test_util.run_deprecated_v1 def testCropping2(self): # Test case for 10315 x_shapes = [[240, 320, 3], [5, 240, 320, 3]] expected_y_shapes = [[80, 106, 3], [5, 80, 106, 3]] for x_shape, y_shape in zip(x_shapes, expected_y_shapes): x_np = np.zeros(x_shape, dtype=np.int32) y_np = np.zeros(y_shape, dtype=np.int32) for use_gpu in [True, False]: with self.cached_session(use_gpu=use_gpu): x = array_ops.placeholder(shape=x_shape, dtype=dtypes.int32) y = image_ops.central_crop(x, 0.33) y_tf = y.eval(feed_dict={x: x_np}) self.assertAllEqual(y_tf, y_np) self.assertAllEqual(y_tf.shape, y_np.shape) @test_util.run_deprecated_v1 def testShapeInference(self): # Test no-op fraction=1.0, with 3-D tensors. self._assertShapeInference([50, 60, 3], 1.0, [50, 60, 3]) self._assertShapeInference([None, 60, 3], 1.0, [None, 60, 3]) self._assertShapeInference([50, None, 3], 1.0, [50, None, 3]) self._assertShapeInference([None, None, 3], 1.0, [None, None, 3]) self._assertShapeInference([50, 60, None], 1.0, [50, 60, None]) self._assertShapeInference([None, None, None], 1.0, [None, None, None]) # Test no-op fraction=0.5, with 3-D tensors. self._assertShapeInference([50, 60, 3], 0.5, [26, 30, 3]) self._assertShapeInference([None, 60, 3], 0.5, [None, 30, 3]) self._assertShapeInference([50, None, 3], 0.5, [26, None, 3]) self._assertShapeInference([None, None, 3], 0.5, [None, None, 3]) self._assertShapeInference([50, 60, None], 0.5, [26, 30, None]) self._assertShapeInference([None, None, None], 0.5, [None, None, None]) # Test no-op fraction=1.0, with 4-D tensors. self._assertShapeInference([5, 50, 60, 3], 1.0, [5, 50, 60, 3]) self._assertShapeInference([5, None, 60, 3], 1.0, [5, None, 60, 3]) self._assertShapeInference([5, 50, None, 3], 1.0, [5, 50, None, 3]) self._assertShapeInference([5, None, None, 3], 1.0, [5, None, None, 3]) self._assertShapeInference([5, 50, 60, None], 1.0, [5, 50, 60, None]) self._assertShapeInference([5, None, None, None], 1.0, [5, None, None, None]) self._assertShapeInference([None, None, None, None], 1.0, [None, None, None, None]) # Test no-op fraction=0.5, with 4-D tensors. self._assertShapeInference([5, 50, 60, 3], 0.5, [5, 26, 30, 3]) self._assertShapeInference([5, None, 60, 3], 0.5, [5, None, 30, 3]) self._assertShapeInference([5, 50, None, 3], 0.5, [5, 26, None, 3]) self._assertShapeInference([5, None, None, 3], 0.5, [5, None, None, 3]) self._assertShapeInference([5, 50, 60, None], 0.5, [5, 26, 30, None]) self._assertShapeInference([5, None, None, None], 0.5, [5, None, None, None]) self._assertShapeInference([None, None, None, None], 0.5, [None, None, None, None]) def testErrorOnInvalidCentralCropFractionValues(self): x_shape = [13, 9, 3] x_np = np.ones(x_shape, dtype=np.float32) for use_gpu in [True, False]: with self.cached_session(use_gpu=use_gpu): x = constant_op.constant(x_np, shape=x_shape) with self.assertRaises(ValueError): _ = image_ops.central_crop(x, 0.0) with self.assertRaises(ValueError): _ = image_ops.central_crop(x, 1.01) def testErrorOnInvalidShapes(self): x_shapes = [None, [], [3], [3, 9], [3, 9, 3, 9, 3]] for x_shape in x_shapes: x_np = np.ones(x_shape, dtype=np.float32) for use_gpu in [True, False]: with self.cached_session(use_gpu=use_gpu): x = constant_op.constant(x_np, shape=x_shape) with self.assertRaises(ValueError): _ = image_ops.central_crop(x, 0.5) @test_util.run_deprecated_v1 def testNameScope(self): x_shape = [13, 9, 3] x_np = np.ones(x_shape, dtype=np.float32) for use_gpu in [True, False]: with self.cached_session(use_gpu=use_gpu): y = image_ops.central_crop(x_np, 1.0) self.assertTrue(y.op.name.startswith("central_crop")) class PadToBoundingBoxTest(test_util.TensorFlowTestCase): def _PadToBoundingBox(self, x, offset_height, offset_width, target_height, target_width, use_tensor_inputs): if use_tensor_inputs: offset_height = ops.convert_to_tensor(offset_height) offset_width = ops.convert_to_tensor(offset_width) target_height = ops.convert_to_tensor(target_height) target_width = ops.convert_to_tensor(target_width) x_tensor = array_ops.placeholder(x.dtype, shape=[None] * x.ndim) feed_dict = {x_tensor: x} else: x_tensor = x feed_dict = {} y = image_ops.pad_to_bounding_box(x_tensor, offset_height, offset_width, target_height, target_width) if not use_tensor_inputs: self.assertTrue(y.get_shape().is_fully_defined()) with self.cached_session(use_gpu=True): return y.eval(feed_dict=feed_dict) def _assertReturns(self, x, x_shape, offset_height, offset_width, y, y_shape, use_tensor_inputs_options=None): use_tensor_inputs_options = use_tensor_inputs_options or [False, True] target_height, target_width, _ = y_shape x = np.array(x).reshape(x_shape) y = np.array(y).reshape(y_shape) for use_tensor_inputs in use_tensor_inputs_options: y_tf = self._PadToBoundingBox(x, offset_height, offset_width, target_height, target_width, use_tensor_inputs) self.assertAllClose(y, y_tf) def _assertRaises(self, x, x_shape, offset_height, offset_width, target_height, target_width, err_msg, use_tensor_inputs_options=None): use_tensor_inputs_options = use_tensor_inputs_options or [False, True] x = np.array(x).reshape(x_shape) for use_tensor_inputs in use_tensor_inputs_options: try: self._PadToBoundingBox(x, offset_height, offset_width, target_height, target_width, use_tensor_inputs) except Exception as e: if err_msg not in str(e): raise else: raise AssertionError("Exception not raised: %s" % err_msg) def _assertShapeInference(self, pre_shape, height, width, post_shape): image = array_ops.placeholder(dtypes.float32, shape=pre_shape) y = image_ops.pad_to_bounding_box(image, 0, 0, height, width) self.assertEqual(y.get_shape().as_list(), post_shape) def testInt64(self): x = [1, 2, 3, 4, 5, 6, 7, 8, 9] x_shape = [3, 3, 1] y = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] y_shape = [4, 3, 1] x = np.array(x).reshape(x_shape) y = np.array(y).reshape(y_shape) i = constant_op.constant([1, 0, 4, 3], dtype=dtypes.int64) y_tf = image_ops.pad_to_bounding_box(x, i[0], i[1], i[2], i[3]) with self.cached_session(use_gpu=True): self.assertAllClose(y, self.evaluate(y_tf)) @test_util.run_deprecated_v1 def testNoOp(self): x_shape = [10, 10, 10] x = np.random.uniform(size=x_shape) offset_height, offset_width = [0, 0] self._assertReturns(x, x_shape, offset_height, offset_width, x, x_shape) @test_util.run_deprecated_v1 def testPadding(self): x = [1, 2, 3, 4, 5, 6, 7, 8, 9] x_shape = [3, 3, 1] offset_height, offset_width = [1, 0] y = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] y_shape = [4, 3, 1] self._assertReturns(x, x_shape, offset_height, offset_width, y, y_shape) offset_height, offset_width = [0, 1] y = [0, 1, 2, 3, 0, 4, 5, 6, 0, 7, 8, 9] y_shape = [3, 4, 1] self._assertReturns(x, x_shape, offset_height, offset_width, y, y_shape) offset_height, offset_width = [0, 0] y = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0] y_shape = [4, 3, 1] self._assertReturns(x, x_shape, offset_height, offset_width, y, y_shape) offset_height, offset_width = [0, 0] y = [1, 2, 3, 0, 4, 5, 6, 0, 7, 8, 9, 0] y_shape = [3, 4, 1] self._assertReturns(x, x_shape, offset_height, offset_width, y, y_shape) @test_util.run_deprecated_v1 def testShapeInference(self): self._assertShapeInference([55, 66, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([50, 60, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([None, 66, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([None, 60, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([55, None, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([50, None, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([None, None, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([55, 66, None], 55, 66, [55, 66, None]) self._assertShapeInference([50, 60, None], 55, 66, [55, 66, None]) self._assertShapeInference([None, None, None], 55, 66, [55, 66, None]) self._assertShapeInference(None, 55, 66, [55, 66, None]) @test_util.run_deprecated_v1 def testNon3DInput(self): # Input image is not 3D x = [0] * 15 offset_height, offset_width = [0, 0] target_height, target_width = [2, 2] for x_shape in ([3, 5], [1, 3, 5, 1, 1]): self._assertRaises(x, x_shape, offset_height, offset_width, target_height, target_width, "'image' must have either 3 or 4 dimensions.") @test_util.run_deprecated_v1 def testZeroLengthInput(self): # Input image has 0-length dimension(s). # Each line is a test configuration: # x_shape, target_height, target_width test_config = (([0, 2, 2], 2, 2), ([2, 0, 2], 2, 2), ([2, 2, 0], 2, 2)) offset_height, offset_width = [0, 0] x = [] for x_shape, target_height, target_width in test_config: self._assertRaises( x, x_shape, offset_height, offset_width, target_height, target_width, "inner 3 dims of 'image.shape' must be > 0", use_tensor_inputs_options=[False]) # The original error message does not contain back slashes. However, they # are added by either the assert op or the runtime. If this behavior # changes in the future, the match string will also needs to be changed. self._assertRaises( x, x_shape, offset_height, offset_width, target_height, target_width, "inner 3 dims of \\'image.shape\\' must be > 0", use_tensor_inputs_options=[True]) @test_util.run_deprecated_v1 def testBadParams(self): x_shape = [3, 3, 1] x = np.zeros(x_shape) # Each line is a test configuration: # offset_height, offset_width, target_height, target_width, err_msg test_config = ((-1, 0, 4, 4, "offset_height must be >= 0"), (0, -1, 4, 4, "offset_width must be >= 0"), (2, 0, 4, 4, "height must be <= target - offset"), (0, 2, 4, 4, "width must be <= target - offset")) for config_item in test_config: self._assertRaises(x, x_shape, *config_item) @test_util.run_deprecated_v1 def testNameScope(self): image = array_ops.placeholder(dtypes.float32, shape=[55, 66, 3]) y = image_ops.pad_to_bounding_box(image, 0, 0, 55, 66) self.assertTrue(y.op.name.startswith("pad_to_bounding_box")) class SelectDistortedCropBoxTest(test_util.TensorFlowTestCase): def _testSampleDistortedBoundingBox(self, image, bounding_box, min_object_covered, aspect_ratio_range, area_range): original_area = float(np.prod(image.shape)) bounding_box_area = float((bounding_box[3] - bounding_box[1]) * (bounding_box[2] - bounding_box[0])) image_size_np = np.array(image.shape, dtype=np.int32) bounding_box_np = ( np.array(bounding_box, dtype=np.float32).reshape([1, 1, 4])) aspect_ratios = [] area_ratios = [] fraction_object_covered = [] num_iter = 1000 with self.cached_session(use_gpu=True): image_tf = constant_op.constant(image, shape=image.shape) image_size_tf = constant_op.constant( image_size_np, shape=image_size_np.shape) bounding_box_tf = constant_op.constant( bounding_box_np, dtype=dtypes.float32, shape=bounding_box_np.shape) begin, size, _ = image_ops.sample_distorted_bounding_box( image_size=image_size_tf, bounding_boxes=bounding_box_tf, min_object_covered=min_object_covered, aspect_ratio_range=aspect_ratio_range, area_range=area_range) y = array_ops.strided_slice(image_tf, begin, begin + size) for _ in xrange(num_iter): y_tf = self.evaluate(y) crop_height = y_tf.shape[0] crop_width = y_tf.shape[1] aspect_ratio = float(crop_width) / float(crop_height) area = float(crop_width * crop_height) aspect_ratios.append(aspect_ratio) area_ratios.append(area / original_area) fraction_object_covered.append(float(np.sum(y_tf)) / bounding_box_area) # min_object_covered as tensor min_object_covered_placeholder = array_ops.placeholder(dtypes.float32) begin, size, _ = image_ops.sample_distorted_bounding_box( image_size=image_size_tf, bounding_boxes=bounding_box_tf, min_object_covered=min_object_covered_placeholder, aspect_ratio_range=aspect_ratio_range, area_range=area_range) y = array_ops.strided_slice(image_tf, begin, begin + size) for _ in xrange(num_iter): y_tf = y.eval(feed_dict={ min_object_covered_placeholder: min_object_covered }) crop_height = y_tf.shape[0] crop_width = y_tf.shape[1] aspect_ratio = float(crop_width) / float(crop_height) area = float(crop_width * crop_height) aspect_ratios.append(aspect_ratio) area_ratios.append(area / original_area) fraction_object_covered.append(float(np.sum(y_tf)) / bounding_box_area) # Ensure that each entry is observed within 3 standard deviations. # num_bins = 10 # aspect_ratio_hist, _ = np.histogram(aspect_ratios, # bins=num_bins, # range=aspect_ratio_range) # mean = np.mean(aspect_ratio_hist) # stddev = np.sqrt(mean) # TODO(wicke, shlens, dga): Restore this test so that it is no longer flaky. # TODO(irving): Since the rejection probability is not independent of the # aspect ratio, the aspect_ratio random value is not exactly uniformly # distributed in [min_aspect_ratio, max_aspect_ratio). This test should be # fixed to reflect the true statistical property, then tightened to enforce # a stricter bound. Or, ideally, the sample_distorted_bounding_box Op # be fixed to not use rejection sampling and generate correctly uniform # aspect ratios. # self.assertAllClose(aspect_ratio_hist, # [mean] * num_bins, atol=3.6 * stddev) # The resulting crop will not be uniformly distributed in area. In practice, # we find that the area skews towards the small sizes. Instead, we perform # a weaker test to ensure that the area ratios are merely within the # specified bounds. self.assertLessEqual(max(area_ratios), area_range[1]) self.assertGreaterEqual(min(area_ratios), area_range[0]) # For reference, here is what the distribution of area ratios look like. area_ratio_hist, _ = np.histogram(area_ratios, bins=10, range=area_range) print("area_ratio_hist ", area_ratio_hist) # Ensure that fraction_object_covered is satisfied. # TODO(wicke, shlens, dga): Restore this test so that it is no longer flaky. # self.assertGreaterEqual(min(fraction_object_covered), min_object_covered) @test_util.run_deprecated_v1 def testWholeImageBoundingBox(self): height = 40 width = 50 image_size = [height, width, 1] bounding_box = [0.0, 0.0, 1.0, 1.0] image = np.arange( 0, np.prod(image_size), dtype=np.int32).reshape(image_size) self._testSampleDistortedBoundingBox( image, bounding_box, min_object_covered=0.1, aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0)) @test_util.run_deprecated_v1 def testWithBoundingBox(self): height = 40 width = 50 x_shape = [height, width, 1] image = np.zeros(x_shape, dtype=np.int32) # Create an object with 1's in a region with area A and require that # the total pixel values >= 0.1 * A. min_object_covered = 0.1 xmin = 2 ymin = 3 xmax = 12 ymax = 13 for x in np.arange(xmin, xmax + 1, 1): for y in np.arange(ymin, ymax + 1, 1): image[x, y] = 1 # Bounding box is specified as (ymin, xmin, ymax, xmax) in # relative coordinates. bounding_box = (float(ymin) / height, float(xmin) / width, float(ymax) / height, float(xmax) / width) self._testSampleDistortedBoundingBox( image, bounding_box=bounding_box, min_object_covered=min_object_covered, aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0)) @test_util.run_deprecated_v1 def testSampleDistortedBoundingBoxShape(self): with self.cached_session(use_gpu=True): image_size = constant_op.constant( [40, 50, 1], shape=[3], dtype=dtypes.int32) bounding_box = constant_op.constant( [[[0.0, 0.0, 1.0, 1.0]]], shape=[1, 1, 4], dtype=dtypes.float32, ) begin, end, bbox_for_drawing = image_ops.sample_distorted_bounding_box( image_size=image_size, bounding_boxes=bounding_box, min_object_covered=0.1, aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0)) # Test that the shapes are correct. self.assertAllEqual([3], begin.get_shape().as_list()) self.assertAllEqual([3], end.get_shape().as_list()) self.assertAllEqual([1, 1, 4], bbox_for_drawing.get_shape().as_list()) # Actual run to make sure shape is correct inside Compute(). begin = self.evaluate(begin) end = self.evaluate(end) bbox_for_drawing = self.evaluate(bbox_for_drawing) begin, end, bbox_for_drawing = image_ops.sample_distorted_bounding_box( image_size=image_size, bounding_boxes=bounding_box, min_object_covered=array_ops.placeholder(dtypes.float32), aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0)) # Test that the shapes are correct. self.assertAllEqual([3], begin.get_shape().as_list()) self.assertAllEqual([3], end.get_shape().as_list()) self.assertAllEqual([1, 1, 4], bbox_for_drawing.get_shape().as_list()) def testDefaultMinObjectCovered(self): # By default min_object_covered=0.1 if not provided with self.cached_session(use_gpu=True): image_size = constant_op.constant( [40, 50, 1], shape=[3], dtype=dtypes.int32) bounding_box = constant_op.constant( [[[0.0, 0.0, 1.0, 1.0]]], shape=[1, 1, 4], dtype=dtypes.float32, ) begin, end, bbox_for_drawing = image_ops.sample_distorted_bounding_box( image_size=image_size, bounding_boxes=bounding_box, aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0)) self.assertAllEqual([3], begin.get_shape().as_list()) self.assertAllEqual([3], end.get_shape().as_list()) self.assertAllEqual([1, 1, 4], bbox_for_drawing.get_shape().as_list()) # Actual run to make sure shape is correct inside Compute(). begin = self.evaluate(begin) end = self.evaluate(end) bbox_for_drawing = self.evaluate(bbox_for_drawing) class ResizeImagesV2Test(test_util.TensorFlowTestCase): METHODS = [ image_ops.ResizeMethod.BILINEAR, image_ops.ResizeMethod.NEAREST_NEIGHBOR, image_ops.ResizeMethod.BICUBIC, image_ops.ResizeMethod.AREA, image_ops.ResizeMethod.LANCZOS3, image_ops.ResizeMethod.LANCZOS5, image_ops.ResizeMethod.GAUSSIAN, image_ops.ResizeMethod.MITCHELLCUBIC ] # Some resize methods, such as Gaussian, are non-interpolating in that they # change the image even if there is no scale change, for some test, we only # check the value on the value preserving methods. INTERPOLATING_METHODS = [ image_ops.ResizeMethod.BILINEAR, image_ops.ResizeMethod.NEAREST_NEIGHBOR, image_ops.ResizeMethod.BICUBIC, image_ops.ResizeMethod.AREA, image_ops.ResizeMethod.LANCZOS3, image_ops.ResizeMethod.LANCZOS5 ] TYPES = [ np.uint8, np.int8, np.uint16, np.int16, np.int32, np.int64, np.float16, np.float32, np.float64 ] def _assertShapeInference(self, pre_shape, size, post_shape): # Try single image resize single_image = array_ops.placeholder(dtypes.float32, shape=pre_shape) y = image_ops.resize_images_v2(single_image, size) self.assertEqual(y.get_shape().as_list(), post_shape) # Try batch images resize with known batch size images = array_ops.placeholder(dtypes.float32, shape=[99] + pre_shape) y = image_ops.resize_images_v2(images, size) self.assertEqual(y.get_shape().as_list(), [99] + post_shape) # Try batch images resize with unknown batch size images = array_ops.placeholder(dtypes.float32, shape=[None] + pre_shape) y = image_ops.resize_images_v2(images, size) self.assertEqual(y.get_shape().as_list(), [None] + post_shape) def shouldRunOnGPU(self, method, nptype): if (method == image_ops.ResizeMethod.NEAREST_NEIGHBOR and nptype in [np.float32, np.float64]): return True else: return False @test_util.disable_xla("align_corners=False not supported by XLA") @test_util.run_deprecated_v1 def testNoOp(self): img_shape = [1, 6, 4, 1] single_shape = [6, 4, 1] # This test is also conducted with int8, so 127 is the maximum # value that can be used. data = [ 127, 127, 64, 64, 127, 127, 64, 64, 64, 64, 127, 127, 64, 64, 127, 127, 50, 50, 100, 100, 50, 50, 100, 100 ] target_height = 6 target_width = 4 for nptype in self.TYPES: img_np = np.array(data, dtype=nptype).reshape(img_shape) for method in self.METHODS: with self.cached_session(use_gpu=True): image = constant_op.constant(img_np, shape=img_shape) y = image_ops.resize_images_v2(image, [target_height, target_width], method) yshape = array_ops.shape(y) resized, newshape = self.evaluate([y, yshape]) self.assertAllEqual(img_shape, newshape) if method in self.INTERPOLATING_METHODS: self.assertAllClose(resized, img_np, atol=1e-5) # Resizing with a single image must leave the shape unchanged also. with self.cached_session(use_gpu=True): img_single = img_np.reshape(single_shape) image = constant_op.constant(img_single, shape=single_shape) y = image_ops.resize_images_v2(image, [target_height, target_width], self.METHODS[0]) yshape = array_ops.shape(y) newshape = self.evaluate(yshape) self.assertAllEqual(single_shape, newshape) # half_pixel_centers unsupported in ResizeBilinear @test_util.run_deprecated_v1 @test_util.disable_xla("b/127616992") def testTensorArguments(self): img_shape = [1, 6, 4, 1] single_shape = [6, 4, 1] # This test is also conducted with int8, so 127 is the maximum # value that can be used. data = [ 127, 127, 64, 64, 127, 127, 64, 64, 64, 64, 127, 127, 64, 64, 127, 127, 50, 50, 100, 100, 50, 50, 100, 100 ] new_size = array_ops.placeholder(dtypes.int32, shape=(2)) img_np = np.array(data, dtype=np.uint8).reshape(img_shape) for method in self.METHODS: with self.cached_session(use_gpu=True) as sess: image = constant_op.constant(img_np, shape=img_shape) y = image_ops.resize_images_v2(image, new_size, method) yshape = array_ops.shape(y) resized, newshape = sess.run([y, yshape], {new_size: [6, 4]}) self.assertAllEqual(img_shape, newshape) if method in self.INTERPOLATING_METHODS: self.assertAllClose(resized, img_np, atol=1e-5) # Resizing with a single image must leave the shape unchanged also. with self.cached_session(use_gpu=True): img_single = img_np.reshape(single_shape) image = constant_op.constant(img_single, shape=single_shape) y = image_ops.resize_images_v2(image, new_size, self.METHODS[0]) yshape = array_ops.shape(y) resized, newshape = sess.run([y, yshape], {new_size: [6, 4]}) self.assertAllEqual(single_shape, newshape) if method in self.INTERPOLATING_METHODS: self.assertAllClose(resized, img_single, atol=1e-5) # Incorrect shape. with self.assertRaises(ValueError): new_size = constant_op.constant(4) _ = image_ops.resize_images_v2(image, new_size, image_ops.ResizeMethod.BILINEAR) with self.assertRaises(ValueError): new_size = constant_op.constant([4]) _ = image_ops.resize_images_v2(image, new_size, image_ops.ResizeMethod.BILINEAR) with self.assertRaises(ValueError): new_size = constant_op.constant([1, 2, 3]) _ = image_ops.resize_images_v2(image, new_size, image_ops.ResizeMethod.BILINEAR) # Incorrect dtypes. with self.assertRaises(ValueError): new_size = constant_op.constant([6.0, 4]) _ = image_ops.resize_images_v2(image, new_size, image_ops.ResizeMethod.BILINEAR) with self.assertRaises(ValueError): _ = image_ops.resize_images_v2(image, [6, 4.0], image_ops.ResizeMethod.BILINEAR) with self.assertRaises(ValueError): _ = image_ops.resize_images_v2(image, [None, 4], image_ops.ResizeMethod.BILINEAR) with self.assertRaises(ValueError): _ = image_ops.resize_images_v2(image, [6, None], image_ops.ResizeMethod.BILINEAR) @test_util.run_deprecated_v1 def testReturnDtype(self): target_shapes = [[6, 4], [3, 2], [ array_ops.placeholder(dtypes.int32), array_ops.placeholder(dtypes.int32) ]] for nptype in self.TYPES: image = array_ops.placeholder(nptype, shape=[1, 6, 4, 1]) for method in self.METHODS: for target_shape in target_shapes: y = image_ops.resize_images_v2(image, target_shape, method) if method == image_ops.ResizeMethod.NEAREST_NEIGHBOR: expected_dtype = image.dtype else: expected_dtype = dtypes.float32 self.assertEqual(y.dtype, expected_dtype) # half_pixel_centers not supported by XLA @test_util.disable_xla("b/127616992") def testSumTensor(self): img_shape = [1, 6, 4, 1] # This test is also conducted with int8, so 127 is the maximum # value that can be used. data = [ 127, 127, 64, 64, 127, 127, 64, 64, 64, 64, 127, 127, 64, 64, 127, 127, 50, 50, 100, 100, 50, 50, 100, 100 ] # Test size where width is specified as a tensor which is a sum # of two tensors. width_1 = constant_op.constant(1) width_2 = constant_op.constant(3) width = math_ops.add(width_1, width_2) height = constant_op.constant(6) img_np = np.array(data, dtype=np.uint8).reshape(img_shape) for method in self.METHODS: with self.cached_session(): image = constant_op.constant(img_np, shape=img_shape) y = image_ops.resize_images_v2(image, [height, width], method) yshape = array_ops.shape(y) resized, newshape = self.evaluate([y, yshape]) self.assertAllEqual(img_shape, newshape) if method in self.INTERPOLATING_METHODS: self.assertAllClose(resized, img_np, atol=1e-5) @test_util.disable_xla("align_corners=False not supported by XLA") def testResizeDown(self): # This test is also conducted with int8, so 127 is the maximum # value that can be used. data = [ 127, 127, 64, 64, 127, 127, 64, 64, 64, 64, 127, 127, 64, 64, 127, 127, 50, 50, 100, 100, 50, 50, 100, 100 ] expected_data = [127, 64, 64, 127, 50, 100] target_height = 3 target_width = 2 # Test out 3-D and 4-D image shapes. img_shapes = [[1, 6, 4, 1], [6, 4, 1]] target_shapes = [[1, target_height, target_width, 1], [target_height, target_width, 1]] for target_shape, img_shape in zip(target_shapes, img_shapes): for nptype in self.TYPES: img_np = np.array(data, dtype=nptype).reshape(img_shape) for method in self.METHODS: if test.is_gpu_available() and self.shouldRunOnGPU(method, nptype): with self.cached_session(use_gpu=True): image = constant_op.constant(img_np, shape=img_shape) y = image_ops.resize_images_v2( image, [target_height, target_width], method) expected = np.array(expected_data).reshape(target_shape) resized = self.evaluate(y) self.assertAllClose(resized, expected, atol=1e-5) @test_util.disable_xla("align_corners=False not supported by XLA") def testResizeUp(self): img_shape = [1, 3, 2, 1] data = [64, 32, 32, 64, 50, 100] target_height = 6 target_width = 4 expected_data = {} expected_data[image_ops.ResizeMethod.BILINEAR] = [ 64.0, 56.0, 40.0, 32.0, 56.0, 52.0, 44.0, 40.0, 40.0, 44.0, 52.0, 56.0, 36.5, 45.625, 63.875, 73.0, 45.5, 56.875, 79.625, 91.0, 50.0, 62.5, 87.5, 100.0 ] expected_data[image_ops.ResizeMethod.NEAREST_NEIGHBOR] = [ 64.0, 64.0, 32.0, 32.0, 64.0, 64.0, 32.0, 32.0, 32.0, 32.0, 64.0, 64.0, 32.0, 32.0, 64.0, 64.0, 50.0, 50.0, 100.0, 100.0, 50.0, 50.0, 100.0, 100.0 ] expected_data[image_ops.ResizeMethod.AREA] = [ 64.0, 64.0, 32.0, 32.0, 64.0, 64.0, 32.0, 32.0, 32.0, 32.0, 64.0, 64.0, 32.0, 32.0, 64.0, 64.0, 50.0, 50.0, 100.0, 100.0, 50.0, 50.0, 100.0, 100.0 ] expected_data[image_ops.ResizeMethod.LANCZOS3] = [ 75.8294, 59.6281, 38.4313, 22.23, 60.6851, 52.0037, 40.6454, 31.964, 35.8344, 41.0779, 47.9383, 53.1818, 24.6968, 43.0769, 67.1244, 85.5045, 35.7939, 56.4713, 83.5243, 104.2017, 44.8138, 65.1949, 91.8603, 112.2413 ] expected_data[image_ops.ResizeMethod.LANCZOS5] = [ 77.5699, 60.0223, 40.6694, 23.1219, 61.8253, 51.2369, 39.5593, 28.9709, 35.7438, 40.8875, 46.5604, 51.7041, 21.5942, 43.5299, 67.7223, 89.658, 32.1213, 56.784, 83.984, 108.6467, 44.5802, 66.183, 90.0082, 111.6109 ] expected_data[image_ops.ResizeMethod.GAUSSIAN] = [ 61.1087, 54.6926, 41.3074, 34.8913, 54.6926, 51.4168, 44.5832, 41.3074, 41.696, 45.2456, 52.6508, 56.2004, 39.4273, 47.0526, 62.9602, 70.5855, 47.3008, 57.3042, 78.173, 88.1764, 51.4771, 62.3638, 85.0752, 95.9619 ] expected_data[image_ops.ResizeMethod.BICUBIC] = [ 70.1453, 59.0252, 36.9748, 25.8547, 59.3195, 53.3386, 41.4789, 35.4981, 36.383, 41.285, 51.0051, 55.9071, 30.2232, 42.151, 65.8032, 77.731, 41.6492, 55.823, 83.9288, 98.1026, 47.0363, 62.2744, 92.4903, 107.7284 ] expected_data[image_ops.ResizeMethod.MITCHELLCUBIC] = [ 66.0382, 56.6079, 39.3921, 29.9618, 56.7255, 51.9603, 43.2611, 38.4959, 39.1828, 43.4664, 51.2864, 55.57, 34.6287, 45.1812, 64.4458, 74.9983, 43.8523, 56.8078, 80.4594, 93.4149, 48.9943, 63.026, 88.6422, 102.6739 ] for nptype in self.TYPES: for method in expected_data: with self.cached_session(use_gpu=True): img_np = np.array(data, dtype=nptype).reshape(img_shape) image = constant_op.constant(img_np, shape=img_shape) y = image_ops.resize_images_v2(image, [target_height, target_width], method) resized = self.evaluate(y) expected = np.array(expected_data[method]).reshape( [1, target_height, target_width, 1]) self.assertAllClose(resized, expected, atol=1e-04) # XLA doesn't implement half_pixel_centers @test_util.disable_xla("b/127616992") def testLegacyBicubicMethodsMatchNewMethods(self): img_shape = [1, 3, 2, 1] data = [64, 32, 32, 64, 50, 100] target_height = 6 target_width = 4 methods_to_test = ((gen_image_ops.resize_bilinear, "triangle"), (gen_image_ops.resize_bicubic, "keyscubic")) for legacy_method, new_method in methods_to_test: with self.cached_session(use_gpu=True): img_np = np.array(data, dtype=np.float32).reshape(img_shape) image = constant_op.constant(img_np, shape=img_shape) legacy_result = legacy_method( image, constant_op.constant([target_height, target_width], dtype=dtypes.int32), half_pixel_centers=True) scale = ( constant_op.constant([target_height, target_width], dtype=dtypes.float32) / math_ops.cast(array_ops.shape(image)[1:3], dtype=dtypes.float32)) new_result = gen_image_ops.scale_and_translate( image, constant_op.constant([target_height, target_width], dtype=dtypes.int32), scale, array_ops.zeros([2]), kernel_type=new_method, antialias=False) self.assertAllClose( self.evaluate(legacy_result), self.evaluate(new_result), atol=1e-04) def testResizeDownArea(self): img_shape = [1, 6, 6, 1] data = [ 128, 64, 32, 16, 8, 4, 4, 8, 16, 32, 64, 128, 128, 64, 32, 16, 8, 4, 5, 10, 15, 20, 25, 30, 30, 25, 20, 15, 10, 5, 5, 10, 15, 20, 25, 30 ] img_np = np.array(data, dtype=np.uint8).reshape(img_shape) target_height = 4 target_width = 4 expected_data = [ 73, 33, 23, 39, 73, 33, 23, 39, 14, 16, 19, 21, 14, 16, 19, 21 ] with self.cached_session(use_gpu=True): image = constant_op.constant(img_np, shape=img_shape) y = image_ops.resize_images_v2(image, [target_height, target_width], image_ops.ResizeMethod.AREA) expected = np.array(expected_data).reshape( [1, target_height, target_width, 1]) resized = self.evaluate(y) self.assertAllClose(resized, expected, atol=1) @test_util.disable_xla("align_corners=False not supported by XLA") def testCompareNearestNeighbor(self): if test.is_gpu_available(): input_shape = [1, 5, 6, 3] target_height = 8 target_width = 12 for nptype in [np.float32, np.float64]: img_np = np.arange( 0, np.prod(input_shape), dtype=nptype).reshape(input_shape) with self.cached_session(use_gpu=True): image = constant_op.constant(img_np, shape=input_shape) new_size = constant_op.constant([target_height, target_width]) out_op = image_ops.resize_images_v2( image, new_size, image_ops.ResizeMethod.NEAREST_NEIGHBOR) gpu_val = self.evaluate(out_op) with self.cached_session(use_gpu=False): image = constant_op.constant(img_np, shape=input_shape) new_size = constant_op.constant([target_height, target_width]) out_op = image_ops.resize_images_v2( image, new_size, image_ops.ResizeMethod.NEAREST_NEIGHBOR) cpu_val = self.evaluate(out_op) self.assertAllClose(cpu_val, gpu_val, rtol=1e-5, atol=1e-5) def testCompareBilinear(self): if test.is_gpu_available(): input_shape = [1, 5, 6, 3] target_height = 8 target_width = 12 for nptype in [np.float32, np.float64]: img_np = np.arange( 0, np.prod(input_shape), dtype=nptype).reshape(input_shape) value = {} for use_gpu in [True, False]: with self.cached_session(use_gpu=use_gpu): image = constant_op.constant(img_np, shape=input_shape) new_size = constant_op.constant([target_height, target_width]) out_op = image_ops.resize_images(image, new_size, image_ops.ResizeMethod.BILINEAR) value[use_gpu] = self.evaluate(out_op) self.assertAllClose(value[True], value[False], rtol=1e-5, atol=1e-5) @test_util.run_deprecated_v1 def testShapeInference(self): self._assertShapeInference([50, 60, 3], [55, 66], [55, 66, 3]) self._assertShapeInference([55, 66, 3], [55, 66], [55, 66, 3]) self._assertShapeInference([59, 69, 3], [55, 66], [55, 66, 3]) self._assertShapeInference([50, 69, 3], [55, 66], [55, 66, 3]) self._assertShapeInference([59, 60, 3], [55, 66], [55, 66, 3]) self._assertShapeInference([None, 60, 3], [55, 66], [55, 66, 3]) self._assertShapeInference([None, 66, 3], [55, 66], [55, 66, 3]) self._assertShapeInference([None, 69, 3], [55, 66], [55, 66, 3]) self._assertShapeInference([50, None, 3], [55, 66], [55, 66, 3]) self._assertShapeInference([55, None, 3], [55, 66], [55, 66, 3]) self._assertShapeInference([59, None, 3], [55, 66], [55, 66, 3]) self._assertShapeInference([None, None, 3], [55, 66], [55, 66, 3]) self._assertShapeInference([50, 60, None], [55, 66], [55, 66, None]) self._assertShapeInference([55, 66, None], [55, 66], [55, 66, None]) self._assertShapeInference([59, 69, None], [55, 66], [55, 66, None]) self._assertShapeInference([50, 69, None], [55, 66], [55, 66, None]) self._assertShapeInference([59, 60, None], [55, 66], [55, 66, None]) self._assertShapeInference([None, None, None], [55, 66], [55, 66, None]) @test_util.run_deprecated_v1 def testNameScope(self): with self.cached_session(use_gpu=True): single_image = array_ops.placeholder(dtypes.float32, shape=[50, 60, 3]) y = image_ops.resize_images(single_image, [55, 66]) self.assertTrue(y.op.name.startswith("resize")) def _ResizeImageCall(self, x, max_h, max_w, preserve_aspect_ratio, use_tensor_inputs): if use_tensor_inputs: target_max = ops.convert_to_tensor([max_h, max_w]) x_tensor = array_ops.placeholder(x.dtype, shape=[None] * x.ndim) feed_dict = {x_tensor: x} else: target_max = [max_h, max_w] x_tensor = x feed_dict = {} y = image_ops.resize_images( x_tensor, ops.convert_to_tensor(target_max), preserve_aspect_ratio=preserve_aspect_ratio) with self.cached_session(use_gpu=True): return y.eval(feed_dict=feed_dict) def _assertResizeEqual(self, x, x_shape, y, y_shape, preserve_aspect_ratio=True, use_tensor_inputs_options=None): use_tensor_inputs_options = use_tensor_inputs_options or [False, True] target_height, target_width, _ = y_shape x = np.array(x).reshape(x_shape) y = np.array(y).reshape(y_shape) for use_tensor_inputs in use_tensor_inputs_options: y_tf = self._ResizeImageCall(x, target_height, target_width, preserve_aspect_ratio, use_tensor_inputs) self.assertAllClose(y, y_tf) def _assertResizeCheckShape(self, x, x_shape, target_shape, y_shape, preserve_aspect_ratio=True, use_tensor_inputs_options=None): use_tensor_inputs_options = use_tensor_inputs_options or [False, True] target_height, target_width = target_shape x = np.array(x).reshape(x_shape) y = np.zeros(y_shape) for use_tensor_inputs in use_tensor_inputs_options: y_tf = self._ResizeImageCall(x, target_height, target_width, preserve_aspect_ratio, use_tensor_inputs) self.assertShapeEqual(y, ops.convert_to_tensor(y_tf)) @test_util.run_deprecated_v1 def testPreserveAspectRatioMultipleImages(self): x_shape = [10, 100, 80, 10] x = np.random.uniform(size=x_shape) for preserve_aspect_ratio in [True, False]: with self.subTest(preserve_aspect_ratio=preserve_aspect_ratio): expect_shape = [10, 250, 200, 10] if preserve_aspect_ratio \ else [10, 250, 250, 10] self._assertResizeCheckShape( x, x_shape, [250, 250], expect_shape, preserve_aspect_ratio=preserve_aspect_ratio) @test_util.run_deprecated_v1 def testPreserveAspectRatioNoOp(self): x_shape = [10, 10, 10] x = np.random.uniform(size=x_shape) self._assertResizeEqual(x, x_shape, x, x_shape) @test_util.run_deprecated_v1 def testPreserveAspectRatioSmaller(self): x_shape = [100, 100, 10] x = np.random.uniform(size=x_shape) self._assertResizeCheckShape(x, x_shape, [75, 50], [50, 50, 10]) @test_util.run_deprecated_v1 def testPreserveAspectRatioSmallerMultipleImages(self): x_shape = [10, 100, 100, 10] x = np.random.uniform(size=x_shape) self._assertResizeCheckShape(x, x_shape, [75, 50], [10, 50, 50, 10]) @test_util.run_deprecated_v1 def testPreserveAspectRatioLarger(self): x_shape = [100, 100, 10] x = np.random.uniform(size=x_shape) self._assertResizeCheckShape(x, x_shape, [150, 200], [150, 150, 10]) @test_util.run_deprecated_v1 def testPreserveAspectRatioSameRatio(self): x_shape = [1920, 1080, 3] x = np.random.uniform(size=x_shape) self._assertResizeCheckShape(x, x_shape, [3840, 2160], [3840, 2160, 3]) @test_util.run_deprecated_v1 def testPreserveAspectRatioSquare(self): x_shape = [299, 299, 3] x = np.random.uniform(size=x_shape) self._assertResizeCheckShape(x, x_shape, [320, 320], [320, 320, 3]) class ResizeImagesTest(test_util.TensorFlowTestCase): METHODS = [ image_ops.ResizeMethodV1.BILINEAR, image_ops.ResizeMethodV1.NEAREST_NEIGHBOR, image_ops.ResizeMethodV1.BICUBIC, image_ops.ResizeMethodV1.AREA ] TYPES = [ np.uint8, np.int8, np.uint16, np.int16, np.int32, np.int64, np.float16, np.float32, np.float64 ] def _assertShapeInference(self, pre_shape, size, post_shape): # Try single image resize single_image = array_ops.placeholder(dtypes.float32, shape=pre_shape) y = image_ops.resize_images(single_image, size) self.assertEqual(y.get_shape().as_list(), post_shape) # Try batch images resize with known batch size images = array_ops.placeholder(dtypes.float32, shape=[99] + pre_shape) y = image_ops.resize_images(images, size) self.assertEqual(y.get_shape().as_list(), [99] + post_shape) # Try batch images resize with unknown batch size images = array_ops.placeholder(dtypes.float32, shape=[None] + pre_shape) y = image_ops.resize_images(images, size) self.assertEqual(y.get_shape().as_list(), [None] + post_shape) def shouldRunOnGPU(self, method, nptype): if (method == image_ops.ResizeMethodV1.NEAREST_NEIGHBOR and nptype in [np.float32, np.float64]): return True else: return False @test_util.disable_xla("align_corners=False not supported by XLA") @test_util.run_deprecated_v1 def testNoOp(self): img_shape = [1, 6, 4, 1] single_shape = [6, 4, 1] # This test is also conducted with int8, so 127 is the maximum # value that can be used. data = [ 127, 127, 64, 64, 127, 127, 64, 64, 64, 64, 127, 127, 64, 64, 127, 127, 50, 50, 100, 100, 50, 50, 100, 100 ] target_height = 6 target_width = 4 for nptype in self.TYPES: img_np = np.array(data, dtype=nptype).reshape(img_shape) for method in self.METHODS: with self.cached_session(use_gpu=True) as sess: image = constant_op.constant(img_np, shape=img_shape) y = image_ops.resize_images(image, [target_height, target_width], method) yshape = array_ops.shape(y) resized, newshape = self.evaluate([y, yshape]) self.assertAllEqual(img_shape, newshape) self.assertAllClose(resized, img_np, atol=1e-5) # Resizing with a single image must leave the shape unchanged also. with self.cached_session(use_gpu=True): img_single = img_np.reshape(single_shape) image = constant_op.constant(img_single, shape=single_shape) y = image_ops.resize_images(image, [target_height, target_width], self.METHODS[0]) yshape = array_ops.shape(y) newshape = self.evaluate(yshape) self.assertAllEqual(single_shape, newshape) @test_util.run_deprecated_v1 def testTensorArguments(self): img_shape = [1, 6, 4, 1] single_shape = [6, 4, 1] # This test is also conducted with int8, so 127 is the maximum # value that can be used. data = [ 127, 127, 64, 64, 127, 127, 64, 64, 64, 64, 127, 127, 64, 64, 127, 127, 50, 50, 100, 100, 50, 50, 100, 100 ] new_size = array_ops.placeholder(dtypes.int32, shape=(2)) img_np = np.array(data, dtype=np.uint8).reshape(img_shape) for method in self.METHODS: with self.cached_session(use_gpu=True) as sess: image = constant_op.constant(img_np, shape=img_shape) y = image_ops.resize_images(image, new_size, method) yshape = array_ops.shape(y) resized, newshape = sess.run([y, yshape], {new_size: [6, 4]}) self.assertAllEqual(img_shape, newshape) self.assertAllClose(resized, img_np, atol=1e-5) # Resizing with a single image must leave the shape unchanged also. with self.cached_session(use_gpu=True): img_single = img_np.reshape(single_shape) image = constant_op.constant(img_single, shape=single_shape) y = image_ops.resize_images(image, new_size, self.METHODS[0]) yshape = array_ops.shape(y) resized, newshape = sess.run([y, yshape], {new_size: [6, 4]}) self.assertAllEqual(single_shape, newshape) self.assertAllClose(resized, img_single, atol=1e-5) # Incorrect shape. with self.assertRaises(ValueError): new_size = constant_op.constant(4) _ = image_ops.resize_images(image, new_size, image_ops.ResizeMethodV1.BILINEAR) with self.assertRaises(ValueError): new_size = constant_op.constant([4]) _ = image_ops.resize_images(image, new_size, image_ops.ResizeMethodV1.BILINEAR) with self.assertRaises(ValueError): new_size = constant_op.constant([1, 2, 3]) _ = image_ops.resize_images(image, new_size, image_ops.ResizeMethodV1.BILINEAR) # Incorrect dtypes. with self.assertRaises(ValueError): new_size = constant_op.constant([6.0, 4]) _ = image_ops.resize_images(image, new_size, image_ops.ResizeMethodV1.BILINEAR) with self.assertRaises(ValueError): _ = image_ops.resize_images(image, [6, 4.0], image_ops.ResizeMethodV1.BILINEAR) with self.assertRaises(ValueError): _ = image_ops.resize_images(image, [None, 4], image_ops.ResizeMethodV1.BILINEAR) with self.assertRaises(ValueError): _ = image_ops.resize_images(image, [6, None], image_ops.ResizeMethodV1.BILINEAR) @test_util.run_deprecated_v1 def testReturnDtype(self): target_shapes = [[6, 4], [3, 2], [ array_ops.placeholder(dtypes.int32), array_ops.placeholder(dtypes.int32) ]] for nptype in self.TYPES: image = array_ops.placeholder(nptype, shape=[1, 6, 4, 1]) for method in self.METHODS: for target_shape in target_shapes: y = image_ops.resize_images(image, target_shape, method) if (method == image_ops.ResizeMethodV1.NEAREST_NEIGHBOR or target_shape == image.shape[1:3]): expected_dtype = image.dtype else: expected_dtype = dtypes.float32 self.assertEqual(y.dtype, expected_dtype) @test_util.disable_xla("align_corners=False not supported by XLA") def testSumTensor(self): img_shape = [1, 6, 4, 1] # This test is also conducted with int8, so 127 is the maximum # value that can be used. data = [ 127, 127, 64, 64, 127, 127, 64, 64, 64, 64, 127, 127, 64, 64, 127, 127, 50, 50, 100, 100, 50, 50, 100, 100 ] # Test size where width is specified as a tensor which is a sum # of two tensors. width_1 = constant_op.constant(1) width_2 = constant_op.constant(3) width = math_ops.add(width_1, width_2) height = constant_op.constant(6) img_np = np.array(data, dtype=np.uint8).reshape(img_shape) for method in self.METHODS: with self.cached_session() as sess: image = constant_op.constant(img_np, shape=img_shape) y = image_ops.resize_images(image, [height, width], method) yshape = array_ops.shape(y) resized, newshape = self.evaluate([y, yshape]) self.assertAllEqual(img_shape, newshape) self.assertAllClose(resized, img_np, atol=1e-5) @test_util.disable_xla("align_corners=False not supported by XLA") def testResizeDown(self): # This test is also conducted with int8, so 127 is the maximum # value that can be used. data = [ 127, 127, 64, 64, 127, 127, 64, 64, 64, 64, 127, 127, 64, 64, 127, 127, 50, 50, 100, 100, 50, 50, 100, 100 ] expected_data = [127, 64, 64, 127, 50, 100] target_height = 3 target_width = 2 # Test out 3-D and 4-D image shapes. img_shapes = [[1, 6, 4, 1], [6, 4, 1]] target_shapes = [[1, target_height, target_width, 1], [target_height, target_width, 1]] for target_shape, img_shape in zip(target_shapes, img_shapes): for nptype in self.TYPES: img_np = np.array(data, dtype=nptype).reshape(img_shape) for method in self.METHODS: if test.is_gpu_available() and self.shouldRunOnGPU(method, nptype): with self.cached_session(use_gpu=True): image = constant_op.constant(img_np, shape=img_shape) y = image_ops.resize_images(image, [target_height, target_width], method) expected = np.array(expected_data).reshape(target_shape) resized = self.evaluate(y) self.assertAllClose(resized, expected, atol=1e-5) @test_util.disable_xla("align_corners=False not supported by XLA") def testResizeUpAlignCornersFalse(self): img_shape = [1, 3, 2, 1] data = [64, 32, 32, 64, 50, 100] target_height = 6 target_width = 4 expected_data = {} expected_data[image_ops.ResizeMethodV1.BILINEAR] = [ 64.0, 48.0, 32.0, 32.0, 48.0, 48.0, 48.0, 48.0, 32.0, 48.0, 64.0, 64.0, 41.0, 61.5, 82.0, 82.0, 50.0, 75.0, 100.0, 100.0, 50.0, 75.0, 100.0, 100.0 ] expected_data[image_ops.ResizeMethodV1.NEAREST_NEIGHBOR] = [ 64.0, 64.0, 32.0, 32.0, 64.0, 64.0, 32.0, 32.0, 32.0, 32.0, 64.0, 64.0, 32.0, 32.0, 64.0, 64.0, 50.0, 50.0, 100.0, 100.0, 50.0, 50.0, 100.0, 100.0 ] expected_data[image_ops.ResizeMethodV1.AREA] = [ 64.0, 64.0, 32.0, 32.0, 64.0, 64.0, 32.0, 32.0, 32.0, 32.0, 64.0, 64.0, 32.0, 32.0, 64.0, 64.0, 50.0, 50.0, 100.0, 100.0, 50.0, 50.0, 100.0, 100.0 ] for nptype in self.TYPES: for method in [ image_ops.ResizeMethodV1.BILINEAR, image_ops.ResizeMethodV1.NEAREST_NEIGHBOR, image_ops.ResizeMethodV1.AREA ]: with self.cached_session(use_gpu=True): img_np = np.array(data, dtype=nptype).reshape(img_shape) image = constant_op.constant(img_np, shape=img_shape) y = image_ops.resize_images( image, [target_height, target_width], method, align_corners=False) resized = self.evaluate(y) expected = np.array(expected_data[method]).reshape( [1, target_height, target_width, 1]) self.assertAllClose(resized, expected, atol=1e-05) def testResizeUpAlignCornersTrue(self): img_shape = [1, 3, 2, 1] data = [6, 3, 3, 6, 6, 9] target_height = 5 target_width = 4 expected_data = {} expected_data[image_ops.ResizeMethodV1.BILINEAR] = [ 6.0, 5.0, 4.0, 3.0, 4.5, 4.5, 4.5, 4.5, 3.0, 4.0, 5.0, 6.0, 4.5, 5.5, 6.5, 7.5, 6.0, 7.0, 8.0, 9.0 ] expected_data[image_ops.ResizeMethodV1.NEAREST_NEIGHBOR] = [ 6.0, 6.0, 3.0, 3.0, 3.0, 3.0, 6.0, 6.0, 3.0, 3.0, 6.0, 6.0, 6.0, 6.0, 9.0, 9.0, 6.0, 6.0, 9.0, 9.0 ] # TODO(b/37749740): Improve alignment of ResizeMethodV1.AREA when # align_corners=True. expected_data[image_ops.ResizeMethodV1.AREA] = [ 6.0, 6.0, 6.0, 3.0, 6.0, 6.0, 6.0, 3.0, 3.0, 3.0, 3.0, 6.0, 3.0, 3.0, 3.0, 6.0, 6.0, 6.0, 6.0, 9.0 ] for nptype in self.TYPES: for method in [ image_ops.ResizeMethodV1.BILINEAR, image_ops.ResizeMethodV1.NEAREST_NEIGHBOR, image_ops.ResizeMethodV1.AREA ]: with self.cached_session(use_gpu=True): img_np = np.array(data, dtype=nptype).reshape(img_shape) image = constant_op.constant(img_np, shape=img_shape) y = image_ops.resize_images( image, [target_height, target_width], method, align_corners=True) resized = self.evaluate(y) expected = np.array(expected_data[method]).reshape( [1, target_height, target_width, 1]) self.assertAllClose(resized, expected, atol=1e-05) def testResizeUpBicubic(self): img_shape = [1, 6, 6, 1] data = [ 128, 128, 64, 64, 128, 128, 64, 64, 64, 64, 128, 128, 64, 64, 128, 128, 50, 50, 100, 100, 50, 50, 100, 100, 50, 50, 100, 100, 50, 50, 100, 100, 50, 50, 100, 100 ] img_np = np.array(data, dtype=np.uint8).reshape(img_shape) target_height = 8 target_width = 8 expected_data = [ 128, 135, 96, 55, 64, 114, 134, 128, 78, 81, 68, 52, 57, 118, 144, 136, 55, 49, 79, 109, 103, 89, 83, 84, 74, 70, 95, 122, 115, 69, 49, 55, 100, 105, 75, 43, 50, 89, 105, 100, 57, 54, 74, 96, 91, 65, 55, 58, 70, 69, 75, 81, 80, 72, 69, 70, 105, 112, 75, 36, 45, 92, 111, 105 ] with self.cached_session(use_gpu=True): image = constant_op.constant(img_np, shape=img_shape) y = image_ops.resize_images(image, [target_height, target_width], image_ops.ResizeMethodV1.BICUBIC) resized = self.evaluate(y) expected = np.array(expected_data).reshape( [1, target_height, target_width, 1]) self.assertAllClose(resized, expected, atol=1) def testResizeDownArea(self): img_shape = [1, 6, 6, 1] data = [ 128, 64, 32, 16, 8, 4, 4, 8, 16, 32, 64, 128, 128, 64, 32, 16, 8, 4, 5, 10, 15, 20, 25, 30, 30, 25, 20, 15, 10, 5, 5, 10, 15, 20, 25, 30 ] img_np = np.array(data, dtype=np.uint8).reshape(img_shape) target_height = 4 target_width = 4 expected_data = [ 73, 33, 23, 39, 73, 33, 23, 39, 14, 16, 19, 21, 14, 16, 19, 21 ] with self.cached_session(use_gpu=True): image = constant_op.constant(img_np, shape=img_shape) y = image_ops.resize_images(image, [target_height, target_width], image_ops.ResizeMethodV1.AREA) expected = np.array(expected_data).reshape( [1, target_height, target_width, 1]) resized = self.evaluate(y) self.assertAllClose(resized, expected, atol=1) @test_util.disable_xla("align_corners=False not supported by XLA") def testCompareNearestNeighbor(self): if test.is_gpu_available(): input_shape = [1, 5, 6, 3] target_height = 8 target_width = 12 for nptype in [np.float32, np.float64]: for align_corners in [True, False]: img_np = np.arange( 0, np.prod(input_shape), dtype=nptype).reshape(input_shape) with self.cached_session(use_gpu=True): image = constant_op.constant(img_np, shape=input_shape) new_size = constant_op.constant([target_height, target_width]) out_op = image_ops.resize_images( image, new_size, image_ops.ResizeMethodV1.NEAREST_NEIGHBOR, align_corners=align_corners) gpu_val = self.evaluate(out_op) with self.cached_session(use_gpu=False): image = constant_op.constant(img_np, shape=input_shape) new_size = constant_op.constant([target_height, target_width]) out_op = image_ops.resize_images( image, new_size, image_ops.ResizeMethodV1.NEAREST_NEIGHBOR, align_corners=align_corners) cpu_val = self.evaluate(out_op) self.assertAllClose(cpu_val, gpu_val, rtol=1e-5, atol=1e-5) def testCompareBilinear(self): if test.is_gpu_available(): input_shape = [1, 5, 6, 3] target_height = 8 target_width = 12 for nptype in [np.float32, np.float64]: for align_corners in [True, False]: img_np = np.arange( 0, np.prod(input_shape), dtype=nptype).reshape(input_shape) value = {} for use_gpu in [True, False]: with self.cached_session(use_gpu=use_gpu): image = constant_op.constant(img_np, shape=input_shape) new_size = constant_op.constant([target_height, target_width]) out_op = image_ops.resize_images( image, new_size, image_ops.ResizeMethodV1.BILINEAR, align_corners=align_corners) value[use_gpu] = self.evaluate(out_op) self.assertAllClose(value[True], value[False], rtol=1e-5, atol=1e-5) @test_util.run_deprecated_v1 def testShapeInference(self): self._assertShapeInference([50, 60, 3], [55, 66], [55, 66, 3]) self._assertShapeInference([55, 66, 3], [55, 66], [55, 66, 3]) self._assertShapeInference([59, 69, 3], [55, 66], [55, 66, 3]) self._assertShapeInference([50, 69, 3], [55, 66], [55, 66, 3]) self._assertShapeInference([59, 60, 3], [55, 66], [55, 66, 3]) self._assertShapeInference([None, 60, 3], [55, 66], [55, 66, 3]) self._assertShapeInference([None, 66, 3], [55, 66], [55, 66, 3]) self._assertShapeInference([None, 69, 3], [55, 66], [55, 66, 3]) self._assertShapeInference([50, None, 3], [55, 66], [55, 66, 3]) self._assertShapeInference([55, None, 3], [55, 66], [55, 66, 3]) self._assertShapeInference([59, None, 3], [55, 66], [55, 66, 3]) self._assertShapeInference([None, None, 3], [55, 66], [55, 66, 3]) self._assertShapeInference([50, 60, None], [55, 66], [55, 66, None]) self._assertShapeInference([55, 66, None], [55, 66], [55, 66, None]) self._assertShapeInference([59, 69, None], [55, 66], [55, 66, None]) self._assertShapeInference([50, 69, None], [55, 66], [55, 66, None]) self._assertShapeInference([59, 60, None], [55, 66], [55, 66, None]) self._assertShapeInference([None, None, None], [55, 66], [55, 66, None]) @test_util.run_deprecated_v1 def testNameScope(self): img_shape = [1, 3, 2, 1] with self.cached_session(use_gpu=True): single_image = array_ops.placeholder(dtypes.float32, shape=[50, 60, 3]) y = image_ops.resize_images(single_image, [55, 66]) self.assertTrue(y.op.name.startswith("resize")) def _ResizeImageCall(self, x, max_h, max_w, preserve_aspect_ratio, use_tensor_inputs): if use_tensor_inputs: target_max = ops.convert_to_tensor([max_h, max_w]) x_tensor = array_ops.placeholder(x.dtype, shape=[None] * x.ndim) feed_dict = {x_tensor: x} else: target_max = [max_h, max_w] x_tensor = x feed_dict = {} y = image_ops.resize_images(x_tensor, target_max, preserve_aspect_ratio=preserve_aspect_ratio) with self.cached_session(use_gpu=True): return y.eval(feed_dict=feed_dict) def _assertResizeEqual(self, x, x_shape, y, y_shape, preserve_aspect_ratio=True, use_tensor_inputs_options=None): use_tensor_inputs_options = use_tensor_inputs_options or [False, True] target_height, target_width, _ = y_shape x = np.array(x).reshape(x_shape) y = np.array(y).reshape(y_shape) for use_tensor_inputs in use_tensor_inputs_options: y_tf = self._ResizeImageCall(x, target_height, target_width, preserve_aspect_ratio, use_tensor_inputs) self.assertAllClose(y, y_tf) def _assertResizeCheckShape(self, x, x_shape, target_shape, y_shape, preserve_aspect_ratio=True, use_tensor_inputs_options=None): use_tensor_inputs_options = use_tensor_inputs_options or [False, True] target_height, target_width = target_shape x = np.array(x).reshape(x_shape) y = np.zeros(y_shape) for use_tensor_inputs in use_tensor_inputs_options: y_tf = self._ResizeImageCall(x, target_height, target_width, preserve_aspect_ratio, use_tensor_inputs) self.assertShapeEqual(y, ops.convert_to_tensor(y_tf)) @test_util.run_deprecated_v1 def testPreserveAspectRatioMultipleImages(self): x_shape = [10, 100, 100, 10] x = np.random.uniform(size=x_shape) self._assertResizeCheckShape(x, x_shape, [250, 250], [10, 250, 250, 10], preserve_aspect_ratio=False) @test_util.run_deprecated_v1 def testPreserveAspectRatioNoOp(self): x_shape = [10, 10, 10] x = np.random.uniform(size=x_shape) self._assertResizeEqual(x, x_shape, x, x_shape) @test_util.run_deprecated_v1 def testPreserveAspectRatioSmaller(self): x_shape = [100, 100, 10] x = np.random.uniform(size=x_shape) self._assertResizeCheckShape(x, x_shape, [75, 50], [50, 50, 10]) @test_util.run_deprecated_v1 def testPreserveAspectRatioSmallerMultipleImages(self): x_shape = [10, 100, 100, 10] x = np.random.uniform(size=x_shape) self._assertResizeCheckShape(x, x_shape, [75, 50], [10, 50, 50, 10]) @test_util.run_deprecated_v1 def testPreserveAspectRatioLarger(self): x_shape = [100, 100, 10] x = np.random.uniform(size=x_shape) self._assertResizeCheckShape(x, x_shape, [150, 200], [150, 150, 10]) @test_util.run_deprecated_v1 def testPreserveAspectRatioSameRatio(self): x_shape = [1920, 1080, 3] x = np.random.uniform(size=x_shape) self._assertResizeCheckShape(x, x_shape, [3840, 2160], [3840, 2160, 3]) @test_util.run_deprecated_v1 def testPreserveAspectRatioSquare(self): x_shape = [299, 299, 3] x = np.random.uniform(size=x_shape) self._assertResizeCheckShape(x, x_shape, [320, 320], [320, 320, 3]) class ResizeImageWithPadV1Test(test_util.TensorFlowTestCase): def _ResizeImageWithPad(self, x, target_height, target_width, use_tensor_inputs): if use_tensor_inputs: target_height = ops.convert_to_tensor(target_height) target_width = ops.convert_to_tensor(target_width) x_tensor = array_ops.placeholder(x.dtype, shape=[None] * x.ndim) feed_dict = {x_tensor: x} else: x_tensor = x feed_dict = {} y = image_ops.resize_image_with_pad_v1(x_tensor, target_height, target_width) if not use_tensor_inputs: self.assertTrue(y.get_shape().is_fully_defined()) with self.cached_session(use_gpu=True): return y.eval(feed_dict=feed_dict) def _assertReturns(self, x, x_shape, y, y_shape, use_tensor_inputs_options=None): use_tensor_inputs_options = use_tensor_inputs_options or [False, True] target_height, target_width, _ = y_shape x = np.array(x).reshape(x_shape) y = np.array(y).reshape(y_shape) for use_tensor_inputs in use_tensor_inputs_options: y_tf = self._ResizeImageWithPad(x, target_height, target_width, use_tensor_inputs) self.assertAllClose(y, y_tf) def _assertRaises(self, x, x_shape, target_height, target_width, err_msg, use_tensor_inputs_options=None): use_tensor_inputs_options = use_tensor_inputs_options or [False, True] x = np.array(x).reshape(x_shape) for use_tensor_inputs in use_tensor_inputs_options: try: self._ResizeImageWithPad(x, target_height, target_width, use_tensor_inputs) except Exception as e: # pylint: disable=broad-except if err_msg not in str(e): raise else: raise AssertionError("Exception not raised: %s" % err_msg) def _assertShapeInference(self, pre_shape, height, width, post_shape): image = array_ops.placeholder(dtypes.float32, shape=pre_shape) y = image_ops.resize_image_with_pad_v1(image, height, width) self.assertEqual(y.get_shape().as_list(), post_shape) @test_util.run_deprecated_v1 def testNoOp(self): x_shape = [10, 10, 10] x = np.random.uniform(size=x_shape) self._assertReturns(x, x_shape, x, x_shape) @test_util.run_deprecated_v1 def testPad(self): # Reduce vertical dimension x = [1, 2, 3, 4, 5, 6, 7, 8] x_shape = [2, 4, 1] y = [0, 1, 3, 0] y_shape = [1, 4, 1] self._assertReturns(x, x_shape, y, y_shape) # Reduce horizontal dimension x = [1, 2, 3, 4, 5, 6, 7, 8] x_shape = [2, 4, 1] y = [1, 3, 0, 0] y_shape = [2, 2, 1] self._assertReturns(x, x_shape, y, y_shape) x = [1, 2, 3, 4, 5, 6, 7, 8] x_shape = [2, 4, 1] y = [1, 3] y_shape = [1, 2, 1] self._assertReturns(x, x_shape, y, y_shape) # half_pixel_centers not supported by XLA @test_util.for_all_test_methods(test_util.disable_xla, "b/127616992") class ResizeImageWithPadV2Test(test_util.TensorFlowTestCase): def _ResizeImageWithPad(self, x, target_height, target_width, use_tensor_inputs): if use_tensor_inputs: target_height = ops.convert_to_tensor(target_height) target_width = ops.convert_to_tensor(target_width) x_tensor = array_ops.placeholder(x.dtype, shape=[None] * x.ndim) feed_dict = {x_tensor: x} else: x_tensor = x feed_dict = {} y = image_ops.resize_image_with_pad_v2(x_tensor, target_height, target_width) if not use_tensor_inputs: self.assertTrue(y.get_shape().is_fully_defined()) with self.cached_session(use_gpu=True): return y.eval(feed_dict=feed_dict) def _assertReturns(self, x, x_shape, y, y_shape, use_tensor_inputs_options=None): use_tensor_inputs_options = use_tensor_inputs_options or [False, True] target_height, target_width, _ = y_shape x = np.array(x).reshape(x_shape) y = np.array(y).reshape(y_shape) for use_tensor_inputs in use_tensor_inputs_options: y_tf = self._ResizeImageWithPad(x, target_height, target_width, use_tensor_inputs) self.assertAllClose(y, y_tf) def _assertRaises(self, x, x_shape, target_height, target_width, err_msg, use_tensor_inputs_options=None): use_tensor_inputs_options = use_tensor_inputs_options or [False, True] x = np.array(x).reshape(x_shape) for use_tensor_inputs in use_tensor_inputs_options: try: self._ResizeImageWithPad(x, target_height, target_width, use_tensor_inputs) except Exception as e: # pylint: disable=broad-except if err_msg not in str(e): raise else: raise AssertionError("Exception not raised: %s" % err_msg) def _assertShapeInference(self, pre_shape, height, width, post_shape): image = array_ops.placeholder(dtypes.float32, shape=pre_shape) y = image_ops.resize_image_with_pad_v1(image, height, width) self.assertEqual(y.get_shape().as_list(), post_shape) @test_util.run_deprecated_v1 def testNoOp(self): x_shape = [10, 10, 10] x = np.random.uniform(size=x_shape) self._assertReturns(x, x_shape, x, x_shape) @test_util.run_deprecated_v1 def testPad(self): # Reduce vertical dimension x = [1, 2, 3, 4, 5, 6, 7, 8] x_shape = [2, 4, 1] y = [0, 3.5, 5.5, 0] y_shape = [1, 4, 1] self._assertReturns(x, x_shape, y, y_shape) # Reduce horizontal dimension x = [1, 2, 3, 4, 5, 6, 7, 8] x_shape = [2, 4, 1] y = [3.5, 5.5, 0, 0] y_shape = [2, 2, 1] self._assertReturns(x, x_shape, y, y_shape) x = [1, 2, 3, 4, 5, 6, 7, 8] x_shape = [2, 4, 1] y = [3.5, 5.5] y_shape = [1, 2, 1] self._assertReturns(x, x_shape, y, y_shape) class ResizeImageWithCropOrPadTest(test_util.TensorFlowTestCase): def _ResizeImageWithCropOrPad(self, x, target_height, target_width, use_tensor_inputs): if use_tensor_inputs: target_height = ops.convert_to_tensor(target_height) target_width = ops.convert_to_tensor(target_width) x_tensor = array_ops.placeholder(x.dtype, shape=[None] * x.ndim) feed_dict = {x_tensor: x} else: x_tensor = x feed_dict = {} y = image_ops.resize_image_with_crop_or_pad(x_tensor, target_height, target_width) if not use_tensor_inputs: self.assertTrue(y.get_shape().is_fully_defined()) with self.cached_session(use_gpu=True): return y.eval(feed_dict=feed_dict) def _assertReturns(self, x, x_shape, y, y_shape, use_tensor_inputs_options=None): use_tensor_inputs_options = use_tensor_inputs_options or [False, True] target_height, target_width, _ = y_shape x = np.array(x).reshape(x_shape) y = np.array(y).reshape(y_shape) for use_tensor_inputs in use_tensor_inputs_options: y_tf = self._ResizeImageWithCropOrPad(x, target_height, target_width, use_tensor_inputs) self.assertAllClose(y, y_tf) def _assertRaises(self, x, x_shape, target_height, target_width, err_msg, use_tensor_inputs_options=None): use_tensor_inputs_options = use_tensor_inputs_options or [False, True] x = np.array(x).reshape(x_shape) for use_tensor_inputs in use_tensor_inputs_options: try: self._ResizeImageWithCropOrPad(x, target_height, target_width, use_tensor_inputs) except Exception as e: if err_msg not in str(e): raise else: raise AssertionError("Exception not raised: %s" % err_msg) def _assertShapeInference(self, pre_shape, height, width, post_shape): image = array_ops.placeholder(dtypes.float32, shape=pre_shape) y = image_ops.resize_image_with_crop_or_pad(image, height, width) self.assertEqual(y.get_shape().as_list(), post_shape) @test_util.run_deprecated_v1 def testNoOp(self): x_shape = [10, 10, 10] x = np.random.uniform(size=x_shape) self._assertReturns(x, x_shape, x, x_shape) @test_util.run_deprecated_v1 def testPad(self): # Pad even along col. x = [1, 2, 3, 4, 5, 6, 7, 8] x_shape = [2, 4, 1] y = [0, 1, 2, 3, 4, 0, 0, 5, 6, 7, 8, 0] y_shape = [2, 6, 1] self._assertReturns(x, x_shape, y, y_shape) # Pad odd along col. x = [1, 2, 3, 4, 5, 6, 7, 8] x_shape = [2, 4, 1] y = [0, 1, 2, 3, 4, 0, 0, 0, 5, 6, 7, 8, 0, 0] y_shape = [2, 7, 1] self._assertReturns(x, x_shape, y, y_shape) # Pad even along row. x = [1, 2, 3, 4, 5, 6, 7, 8] x_shape = [2, 4, 1] y = [0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0] y_shape = [4, 4, 1] self._assertReturns(x, x_shape, y, y_shape) # Pad odd along row. x = [1, 2, 3, 4, 5, 6, 7, 8] x_shape = [2, 4, 1] y = [0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0] y_shape = [5, 4, 1] self._assertReturns(x, x_shape, y, y_shape) @test_util.run_deprecated_v1 def testCrop(self): # Crop even along col. x = [1, 2, 3, 4, 5, 6, 7, 8] x_shape = [2, 4, 1] y = [2, 3, 6, 7] y_shape = [2, 2, 1] self._assertReturns(x, x_shape, y, y_shape) # Crop odd along col. x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] x_shape = [2, 6, 1] y = [2, 3, 4, 8, 9, 10] y_shape = [2, 3, 1] self._assertReturns(x, x_shape, y, y_shape) # Crop even along row. x = [1, 2, 3, 4, 5, 6, 7, 8] x_shape = [4, 2, 1] y = [3, 4, 5, 6] y_shape = [2, 2, 1] self._assertReturns(x, x_shape, y, y_shape) # Crop odd along row. x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] x_shape = [8, 2, 1] y = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12] y_shape = [5, 2, 1] self._assertReturns(x, x_shape, y, y_shape) @test_util.run_deprecated_v1 def testCropAndPad(self): # Pad along row but crop along col. x = [1, 2, 3, 4, 5, 6, 7, 8] x_shape = [2, 4, 1] y = [0, 0, 2, 3, 6, 7, 0, 0] y_shape = [4, 2, 1] self._assertReturns(x, x_shape, y, y_shape) # Crop along row but pad along col. x = [1, 2, 3, 4, 5, 6, 7, 8] x_shape = [4, 2, 1] y = [0, 3, 4, 0, 0, 5, 6, 0] y_shape = [2, 4, 1] self._assertReturns(x, x_shape, y, y_shape) @test_util.run_deprecated_v1 def testShapeInference(self): self._assertShapeInference([50, 60, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([55, 66, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([59, 69, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([50, 69, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([59, 60, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([None, 60, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([None, 66, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([None, 69, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([50, None, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([55, None, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([59, None, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([None, None, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([50, 60, None], 55, 66, [55, 66, None]) self._assertShapeInference([55, 66, None], 55, 66, [55, 66, None]) self._assertShapeInference([59, 69, None], 55, 66, [55, 66, None]) self._assertShapeInference([50, 69, None], 55, 66, [55, 66, None]) self._assertShapeInference([59, 60, None], 55, 66, [55, 66, None]) self._assertShapeInference([None, None, None], 55, 66, [55, 66, None]) self._assertShapeInference(None, 55, 66, [55, 66, None]) @test_util.run_deprecated_v1 def testNon3DInput(self): # Input image is not 3D x = [0] * 15 target_height, target_width = [4, 4] for x_shape in ([3, 5],): self._assertRaises(x, x_shape, target_height, target_width, "'image' must have either 3 or 4 dimensions.") for x_shape in ([1, 3, 5, 1, 1],): self._assertRaises(x, x_shape, target_height, target_width, "'image' must have either 3 or 4 dimensions.") @test_util.run_deprecated_v1 def testZeroLengthInput(self): # Input image has 0-length dimension(s). target_height, target_width = [1, 1] x = [] for x_shape in ([0, 2, 2], [2, 0, 2], [2, 2, 0]): self._assertRaises( x, x_shape, target_height, target_width, "inner 3 dims of 'image.shape' must be > 0", use_tensor_inputs_options=[False]) # The original error message does not contain back slashes. However, they # are added by either the assert op or the runtime. If this behavior # changes in the future, the match string will also needs to be changed. self._assertRaises( x, x_shape, target_height, target_width, "inner 3 dims of \\'image.shape\\' must be > 0", use_tensor_inputs_options=[True]) @test_util.run_deprecated_v1 def testBadParams(self): x_shape = [4, 4, 1] x = np.zeros(x_shape) # target_height <= 0 target_height, target_width = [0, 5] self._assertRaises(x, x_shape, target_height, target_width, "target_height must be > 0") # target_width <= 0 target_height, target_width = [5, 0] self._assertRaises(x, x_shape, target_height, target_width, "target_width must be > 0") @test_util.run_deprecated_v1 def testNameScope(self): image = array_ops.placeholder(dtypes.float32, shape=[50, 60, 3]) y = image_ops.resize_image_with_crop_or_pad(image, 55, 66) self.assertTrue(y.op.name.startswith("resize_image_with_crop_or_pad")) def _SimpleColorRamp(): """Build a simple color ramp RGB image.""" w, h = 256, 200 i = np.arange(h)[:, None] j = np.arange(w) image = np.empty((h, w, 3), dtype=np.uint8) image[:, :, 0] = i image[:, :, 1] = j image[:, :, 2] = (i + j) >> 1 return image class JpegTest(test_util.TensorFlowTestCase): # TODO(irving): Add self.assertAverageLess or similar to test_util def averageError(self, image0, image1): self.assertEqual(image0.shape, image1.shape) image0 = image0.astype(int) # Avoid overflow return np.abs(image0 - image1).sum() / np.prod(image0.shape) def testExisting(self): # Read a real jpeg and verify shape path = ("tensorflow/core/lib/jpeg/testdata/" "jpeg_merge_test1.jpg") with self.cached_session(use_gpu=True) as sess: jpeg0 = io_ops.read_file(path) image0 = image_ops.decode_jpeg(jpeg0) image1 = image_ops.decode_jpeg(image_ops.encode_jpeg(image0)) jpeg0, image0, image1 = self.evaluate([jpeg0, image0, image1]) self.assertEqual(len(jpeg0), 3771) self.assertEqual(image0.shape, (256, 128, 3)) self.assertLess(self.averageError(image0, image1), 1.4) def testCmyk(self): # Confirm that CMYK reads in as RGB base = "tensorflow/core/lib/jpeg/testdata" rgb_path = os.path.join(base, "jpeg_merge_test1.jpg") cmyk_path = os.path.join(base, "jpeg_merge_test1_cmyk.jpg") shape = 256, 128, 3 for channels in 3, 0: with self.cached_session(use_gpu=True) as sess: rgb = image_ops.decode_jpeg( io_ops.read_file(rgb_path), channels=channels) cmyk = image_ops.decode_jpeg( io_ops.read_file(cmyk_path), channels=channels) rgb, cmyk = self.evaluate([rgb, cmyk]) self.assertEqual(rgb.shape, shape) self.assertEqual(cmyk.shape, shape) error = self.averageError(rgb, cmyk) self.assertLess(error, 4) def testCropAndDecodeJpeg(self): with self.cached_session() as sess: # Encode it, then decode it, then encode it base = "tensorflow/core/lib/jpeg/testdata" jpeg0 = io_ops.read_file(os.path.join(base, "jpeg_merge_test1.jpg")) h, w, _ = 256, 128, 3 crop_windows = [[0, 0, 5, 5], [0, 0, 5, w], [0, 0, h, 5], [h - 6, w - 5, 6, 5], [6, 5, 15, 10], [0, 0, h, w]] for crop_window in crop_windows: # Explicit two stages: decode + crop. image1 = image_ops.decode_jpeg(jpeg0) y, x, h, w = crop_window image1_crop = image_ops.crop_to_bounding_box(image1, y, x, h, w) # Combined decode+crop. image2 = image_ops.decode_and_crop_jpeg(jpeg0, crop_window) # Combined decode+crop should have the same shape inference self.assertAllEqual(image1_crop.get_shape().as_list(), image2.get_shape().as_list()) # CropAndDecode should be equal to DecodeJpeg+Crop. image1_crop, image2 = self.evaluate([image1_crop, image2]) self.assertAllEqual(image1_crop, image2) @test_util.run_deprecated_v1 def testCropAndDecodeJpegWithInvalidCropWindow(self): with self.cached_session() as sess: # Encode it, then decode it, then encode it base = "tensorflow/core/lib/jpeg/testdata" jpeg0 = io_ops.read_file(os.path.join(base, "jpeg_merge_test1.jpg")) h, w, _ = 256, 128, 3 # Invalid crop windows. crop_windows = [[-1, 11, 11, 11], [11, -1, 11, 11], [11, 11, -1, 11], [11, 11, 11, -1], [11, 11, 0, 11], [11, 11, 11, 0], [0, 0, h + 1, w], [0, 0, h, w + 1]] for crop_window in crop_windows: result = image_ops.decode_and_crop_jpeg(jpeg0, crop_window) with self.assertRaisesWithPredicateMatch( errors.InvalidArgumentError, lambda e: "Invalid JPEG data or crop window" in str(e)): self.evaluate(result) def testSynthetic(self): with self.cached_session(use_gpu=True) as sess: # Encode it, then decode it, then encode it image0 = constant_op.constant(_SimpleColorRamp()) jpeg0 = image_ops.encode_jpeg(image0) image1 = image_ops.decode_jpeg(jpeg0, dct_method="INTEGER_ACCURATE") image2 = image_ops.decode_jpeg( image_ops.encode_jpeg(image1), dct_method="INTEGER_ACCURATE") jpeg0, image0, image1, image2 = self.evaluate( [jpeg0, image0, image1, image2]) # The decoded-encoded image should be similar to the input self.assertLess(self.averageError(image0, image1), 0.6) # We should be very close to a fixpoint self.assertLess(self.averageError(image1, image2), 0.02) # Smooth ramps compress well (input size is 153600) self.assertGreaterEqual(len(jpeg0), 5000) self.assertLessEqual(len(jpeg0), 6000) def testSyntheticFasterAlgorithm(self): with self.cached_session(use_gpu=True) as sess: # Encode it, then decode it, then encode it image0 = constant_op.constant(_SimpleColorRamp()) jpeg0 = image_ops.encode_jpeg(image0) image1 = image_ops.decode_jpeg(jpeg0, dct_method="INTEGER_FAST") image2 = image_ops.decode_jpeg( image_ops.encode_jpeg(image1), dct_method="INTEGER_FAST") jpeg0, image0, image1, image2 = self.evaluate( [jpeg0, image0, image1, image2]) # The decoded-encoded image should be similar to the input, but # note this is worse than the slower algorithm because it is # less accurate. self.assertLess(self.averageError(image0, image1), 0.95) # Repeated compression / decompression will have a higher error # with a lossier algorithm. self.assertLess(self.averageError(image1, image2), 1.05) # Smooth ramps compress well (input size is 153600) self.assertGreaterEqual(len(jpeg0), 5000) self.assertLessEqual(len(jpeg0), 6000) def testDefaultDCTMethodIsIntegerFast(self): with self.cached_session(use_gpu=True) as sess: # Compare decoding with both dct_option=INTEGER_FAST and # default. They should be the same. image0 = constant_op.constant(_SimpleColorRamp()) jpeg0 = image_ops.encode_jpeg(image0) image1 = image_ops.decode_jpeg(jpeg0, dct_method="INTEGER_FAST") image2 = image_ops.decode_jpeg(jpeg0) image1, image2 = self.evaluate([image1, image2]) # The images should be the same. self.assertAllClose(image1, image2) @test_util.run_deprecated_v1 def testShape(self): with self.cached_session(use_gpu=True) as sess: jpeg = constant_op.constant("nonsense") for channels in 0, 1, 3: image = image_ops.decode_jpeg(jpeg, channels=channels) self.assertEqual(image.get_shape().as_list(), [None, None, channels or None]) @test_util.run_deprecated_v1 def testExtractJpegShape(self): # Read a real jpeg and verify shape. path = ("tensorflow/core/lib/jpeg/testdata/" "jpeg_merge_test1.jpg") with self.cached_session(use_gpu=True) as sess: jpeg = io_ops.read_file(path) # Extract shape without decoding. [image_shape] = sess.run([image_ops.extract_jpeg_shape(jpeg)]) self.assertEqual(image_shape.tolist(), [256, 128, 3]) @test_util.run_deprecated_v1 def testExtractJpegShapeforCmyk(self): # Read a cmyk jpeg image, and verify its shape. path = ("tensorflow/core/lib/jpeg/testdata/" "jpeg_merge_test1_cmyk.jpg") with self.cached_session(use_gpu=True) as sess: jpeg = io_ops.read_file(path) [image_shape] = sess.run([image_ops.extract_jpeg_shape(jpeg)]) # Cmyk jpeg image has 4 channels. self.assertEqual(image_shape.tolist(), [256, 128, 4]) def testRandomJpegQuality(self): # Previous implementation of random_jpeg_quality had a bug. # This unit test tests the fixed version, but due to forward compatibility # this test can only be done when fixed version is used. # Test jpeg quality dynamic randomization. with ops.Graph().as_default(), self.test_session(): np.random.seed(7) path = ("tensorflow/core/lib/jpeg/testdata/medium.jpg") jpeg = io_ops.read_file(path) image = image_ops.decode_jpeg(jpeg) random_jpeg_image = image_ops.random_jpeg_quality(image, 40, 100) with self.cached_session(use_gpu=True) as sess: # Test randomization. random_jpeg_images = [sess.run(random_jpeg_image) for _ in range(5)] are_images_equal = [] for i in range(1, len(random_jpeg_images)): # Most of them should be different if randomization is occurring # correctly. are_images_equal.append( np.array_equal(random_jpeg_images[0], random_jpeg_images[i])) self.assertFalse(all(are_images_equal)) def testAdjustJpegQuality(self): # Test if image_ops.adjust_jpeg_quality works when jpeq quality # is an int (not tensor) for backward compatibility. with ops.Graph().as_default(), self.test_session(): np.random.seed(7) jpeg_quality = np.random.randint(40, 100) path = ("tensorflow/core/lib/jpeg/testdata/medium.jpg") jpeg = io_ops.read_file(path) image = image_ops.decode_jpeg(jpeg) adjust_jpeg_quality_image = image_ops.adjust_jpeg_quality( image, jpeg_quality) with self.cached_session(use_gpu=True) as sess: sess.run(adjust_jpeg_quality_image) @test_util.run_deprecated_v1 def testAdjustJpegQualityShape(self): with self.cached_session(use_gpu=True): image = constant_op.constant( np.arange(24, dtype=np.uint8).reshape([2, 4, 3])) adjusted_image = image_ops.adjust_jpeg_quality(image, 80) self.assertListEqual(adjusted_image.shape.as_list(), [None, None, 3]) class PngTest(test_util.TensorFlowTestCase): def testExisting(self): # Read some real PNGs, converting to different channel numbers prefix = "tensorflow/core/lib/png/testdata/" inputs = ((1, "lena_gray.png"), (4, "lena_rgba.png"), (3, "lena_palette.png"), (4, "lena_palette_trns.png")) for channels_in, filename in inputs: for channels in 0, 1, 3, 4: with self.cached_session(use_gpu=True) as sess: png0 = io_ops.read_file(prefix + filename) image0 = image_ops.decode_png(png0, channels=channels) png0, image0 = self.evaluate([png0, image0]) self.assertEqual(image0.shape, (26, 51, channels or channels_in)) if channels == channels_in: image1 = image_ops.decode_png(image_ops.encode_png(image0)) self.assertAllEqual(image0, self.evaluate(image1)) def testSynthetic(self): with self.cached_session(use_gpu=True) as sess: # Encode it, then decode it image0 = constant_op.constant(_SimpleColorRamp()) png0 = image_ops.encode_png(image0, compression=7) image1 = image_ops.decode_png(png0) png0, image0, image1 = self.evaluate([png0, image0, image1]) # PNG is lossless self.assertAllEqual(image0, image1) # Smooth ramps compress well, but not too well self.assertGreaterEqual(len(png0), 400) self.assertLessEqual(len(png0), 750) def testSyntheticUint16(self): with self.cached_session(use_gpu=True) as sess: # Encode it, then decode it image0 = constant_op.constant(_SimpleColorRamp(), dtype=dtypes.uint16) png0 = image_ops.encode_png(image0, compression=7) image1 = image_ops.decode_png(png0, dtype=dtypes.uint16) png0, image0, image1 = self.evaluate([png0, image0, image1]) # PNG is lossless self.assertAllEqual(image0, image1) # Smooth ramps compress well, but not too well self.assertGreaterEqual(len(png0), 800) self.assertLessEqual(len(png0), 1500) def testSyntheticTwoChannel(self): with self.cached_session(use_gpu=True) as sess: # Strip the b channel from an rgb image to get a two-channel image. gray_alpha = _SimpleColorRamp()[:, :, 0:2] image0 = constant_op.constant(gray_alpha) png0 = image_ops.encode_png(image0, compression=7) image1 = image_ops.decode_png(png0) png0, image0, image1 = self.evaluate([png0, image0, image1]) self.assertEqual(2, image0.shape[-1]) self.assertAllEqual(image0, image1) def testSyntheticTwoChannelUint16(self): with self.cached_session(use_gpu=True) as sess: # Strip the b channel from an rgb image to get a two-channel image. gray_alpha = _SimpleColorRamp()[:, :, 0:2] image0 = constant_op.constant(gray_alpha, dtype=dtypes.uint16) png0 = image_ops.encode_png(image0, compression=7) image1 = image_ops.decode_png(png0, dtype=dtypes.uint16) png0, image0, image1 = self.evaluate([png0, image0, image1]) self.assertEqual(2, image0.shape[-1]) self.assertAllEqual(image0, image1) @test_util.run_deprecated_v1 def testShape(self): with self.cached_session(use_gpu=True): png = constant_op.constant("nonsense") for channels in 0, 1, 3: image = image_ops.decode_png(png, channels=channels) self.assertEqual(image.get_shape().as_list(), [None, None, channels or None]) class GifTest(test_util.TensorFlowTestCase): def _testValid(self, filename): # Read some real GIFs prefix = "tensorflow/core/lib/gif/testdata/" WIDTH = 20 HEIGHT = 40 STRIDE = 5 shape = (12, HEIGHT, WIDTH, 3) with self.cached_session(use_gpu=True) as sess: gif0 = io_ops.read_file(prefix + filename) image0 = image_ops.decode_gif(gif0) gif0, image0 = self.evaluate([gif0, image0]) self.assertEqual(image0.shape, shape) for frame_idx, frame in enumerate(image0): gt = np.zeros(shape[1:], dtype=np.uint8) start = frame_idx * STRIDE end = (frame_idx + 1) * STRIDE print(frame_idx) if end <= WIDTH: gt[:, start:end, :] = 255 else: start -= WIDTH end -= WIDTH gt[start:end, :, :] = 255 self.assertAllClose(frame, gt) def testValid(self): self._testValid("scan.gif") self._testValid("optimized.gif") @test_util.run_deprecated_v1 def testShape(self): with self.cached_session(use_gpu=True) as sess: gif = constant_op.constant("nonsense") image = image_ops.decode_gif(gif) self.assertEqual(image.get_shape().as_list(), [None, None, None, 3]) class ConvertImageTest(test_util.TensorFlowTestCase): def _convert(self, original, original_dtype, output_dtype, expected): x_np = np.array(original, dtype=original_dtype.as_numpy_dtype()) y_np = np.array(expected, dtype=output_dtype.as_numpy_dtype()) with self.cached_session(use_gpu=True): image = constant_op.constant(x_np) y = image_ops.convert_image_dtype(image, output_dtype) self.assertTrue(y.dtype == output_dtype) self.assertAllClose(y.eval(), y_np, atol=1e-5) if output_dtype in [ dtypes.float32, dtypes.float64, dtypes.int32, dtypes.int64 ]: y_saturate = image_ops.convert_image_dtype( image, output_dtype, saturate=True) self.assertTrue(y_saturate.dtype == output_dtype) self.assertAllClose(y_saturate.eval(), y_np, atol=1e-5) @test_util.run_deprecated_v1 def testNoConvert(self): # Make sure converting to the same data type creates only an identity op with self.cached_session(use_gpu=True): image = constant_op.constant([1], dtype=dtypes.uint8) image_ops.convert_image_dtype(image, dtypes.uint8) y = image_ops.convert_image_dtype(image, dtypes.uint8) self.assertEquals(y.op.type, "Identity") self.assertEquals(y.op.inputs[0], image) @test_util.run_deprecated_v1 def testConvertBetweenInteger(self): # Make sure converting to between integer types scales appropriately with self.cached_session(use_gpu=True): self._convert([0, 255], dtypes.uint8, dtypes.int16, [0, 255 * 128]) self._convert([0, 32767], dtypes.int16, dtypes.uint8, [0, 255]) self._convert([0, 2**32], dtypes.int64, dtypes.int32, [0, 1]) self._convert([0, 1], dtypes.int32, dtypes.int64, [0, 2**32]) @test_util.run_deprecated_v1 def testConvertBetweenFloat(self): # Make sure converting to between float types does nothing interesting with self.cached_session(use_gpu=True): self._convert([-1.0, 0, 1.0, 200000], dtypes.float32, dtypes.float64, [-1.0, 0, 1.0, 200000]) self._convert([-1.0, 0, 1.0, 200000], dtypes.float64, dtypes.float32, [-1.0, 0, 1.0, 200000]) @test_util.run_deprecated_v1 def testConvertBetweenIntegerAndFloat(self): # Make sure converting from and to a float type scales appropriately with self.cached_session(use_gpu=True): self._convert([0, 1, 255], dtypes.uint8, dtypes.float32, [0, 1.0 / 255.0, 1]) self._convert([0, 1.1 / 255.0, 1], dtypes.float32, dtypes.uint8, [0, 1, 255]) @test_util.run_deprecated_v1 def testConvertBetweenInt16AndInt8(self): with self.cached_session(use_gpu=True): # uint8, uint16 self._convert([0, 255 * 256], dtypes.uint16, dtypes.uint8, [0, 255]) self._convert([0, 255], dtypes.uint8, dtypes.uint16, [0, 255 * 256]) # int8, uint16 self._convert([0, 127 * 2 * 256], dtypes.uint16, dtypes.int8, [0, 127]) self._convert([0, 127], dtypes.int8, dtypes.uint16, [0, 127 * 2 * 256]) # int16, uint16 self._convert([0, 255 * 256], dtypes.uint16, dtypes.int16, [0, 255 * 128]) self._convert([0, 255 * 128], dtypes.int16, dtypes.uint16, [0, 255 * 256]) class TotalVariationTest(test_util.TensorFlowTestCase): """Tests the function total_variation() in image_ops. We test a few small handmade examples, as well as some larger examples using an equivalent numpy implementation of the total_variation() function. We do NOT test for overflows and invalid / edge-case arguments. """ def _test(self, x_np, y_np): """Test that the TensorFlow implementation of total_variation(x_np) calculates the values in y_np. Note that these may be float-numbers so we only test for approximate equality within some narrow error-bound. """ # Create a TensorFlow session. with self.cached_session(use_gpu=True): # Add a constant to the TensorFlow graph that holds the input. x_tf = constant_op.constant(x_np, shape=x_np.shape) # Add ops for calculating the total variation using TensorFlow. y = image_ops.total_variation(images=x_tf) # Run the TensorFlow session to calculate the result. y_tf = self.evaluate(y) # Assert that the results are as expected within # some small error-bound in case they are float-values. self.assertAllClose(y_tf, y_np) def _total_variation_np(self, x_np): """Calculate the total variation of x_np using numpy. This implements the same function as TensorFlow but using numpy instead. Args: x_np: Numpy array with 3 or 4 dimensions. """ dim = len(x_np.shape) if dim == 3: # Calculate differences for neighboring pixel-values using slices. dif1 = x_np[1:, :, :] - x_np[:-1, :, :] dif2 = x_np[:, 1:, :] - x_np[:, :-1, :] # Sum for all axis. sum_axis = None elif dim == 4: # Calculate differences for neighboring pixel-values using slices. dif1 = x_np[:, 1:, :, :] - x_np[:, :-1, :, :] dif2 = x_np[:, :, 1:, :] - x_np[:, :, :-1, :] # Only sum for the last 3 axis. sum_axis = (1, 2, 3) else: # This should not occur in this test-code. pass tot_var = np.sum(np.abs(dif1), axis=sum_axis) + \ np.sum(np.abs(dif2), axis=sum_axis) return tot_var def _test_tensorflow_vs_numpy(self, x_np): """Test the TensorFlow implementation against a numpy implementation. Args: x_np: Numpy array with 3 or 4 dimensions. """ # Calculate the y-values using the numpy implementation. y_np = self._total_variation_np(x_np) self._test(x_np, y_np) def _generateArray(self, shape): """Generate an array of the given shape for use in testing. The numbers are calculated as the cumulative sum, which causes the difference between neighboring numbers to vary.""" # Flattened length of the array. flat_len = np.prod(shape) a = np.array(range(flat_len), dtype=int) a = np.cumsum(a) a = a.reshape(shape) return a # TODO(b/133851381): re-enable this test. def disabledtestTotalVariationNumpy(self): """Test the TensorFlow implementation against a numpy implementation. The two implementations are very similar so it is possible that both have the same bug, which would not be detected by this test. It is therefore necessary to test with manually crafted data as well.""" # Generate a test-array. # This is an 'image' with 100x80 pixels and 3 color channels. a = self._generateArray(shape=(100, 80, 3)) # Test the TensorFlow implementation vs. numpy implementation. # We use a numpy implementation to check the results that are # calculated using TensorFlow are correct. self._test_tensorflow_vs_numpy(a) self._test_tensorflow_vs_numpy(a + 1) self._test_tensorflow_vs_numpy(-a) self._test_tensorflow_vs_numpy(1.1 * a) # Expand to a 4-dim array. b = a[np.newaxis, :] # Combine several variations of the image into a single 4-dim array. multi = np.vstack((b, b + 1, -b, 1.1 * b)) # Test that the TensorFlow function can also handle 4-dim arrays. self._test_tensorflow_vs_numpy(multi) def testTotalVariationHandmade(self): """Test the total variation for a few handmade examples.""" # We create an image that is 2x2 pixels with 3 color channels. # The image is very small so we can check the result by hand. # Red color channel. # The following are the sum of absolute differences between the pixels. # sum row dif = (4-1) + (7-2) = 3 + 5 = 8 # sum col dif = (2-1) + (7-4) = 1 + 3 = 4 r = [[1, 2], [4, 7]] # Blue color channel. # sum row dif = 18 + 29 = 47 # sum col dif = 7 + 18 = 25 g = [[11, 18], [29, 47]] # Green color channel. # sum row dif = 120 + 193 = 313 # sum col dif = 47 + 120 = 167 b = [[73, 120], [193, 313]] # Combine the 3 color channels into a single 3-dim array. # The shape is (2, 2, 3) corresponding to (height, width and color). a = np.dstack((r, g, b)) # Total variation for this image. # Sum of all pixel differences = 8 + 4 + 47 + 25 + 313 + 167 = 564 tot_var = 564 # Calculate the total variation using TensorFlow and assert it is correct. self._test(a, tot_var) # If we add 1 to all pixel-values then the total variation is unchanged. self._test(a + 1, tot_var) # If we negate all pixel-values then the total variation is unchanged. self._test(-a, tot_var) # Scale the pixel-values by a float. This scales the total variation as # well. b = 1.1 * a self._test(b, 1.1 * tot_var) # Scale by another float. c = 1.2 * a self._test(c, 1.2 * tot_var) # Combine these 3 images into a single array of shape (3, 2, 2, 3) # where the first dimension is for the image-number. multi = np.vstack((a[np.newaxis, :], b[np.newaxis, :], c[np.newaxis, :])) # Check that TensorFlow correctly calculates the total variation # for each image individually and returns the correct array. self._test(multi, tot_var * np.array([1.0, 1.1, 1.2])) class FormatTest(test_util.TensorFlowTestCase): @test_util.run_deprecated_v1 def testFormats(self): prefix = "tensorflow/core/lib" paths = ("png/testdata/lena_gray.png", "jpeg/testdata/jpeg_merge_test1.jpg", "gif/testdata/lena.gif") decoders = { "jpeg": functools.partial(image_ops.decode_jpeg, channels=3), "png": functools.partial(image_ops.decode_png, channels=3), "gif": lambda s: array_ops.squeeze(image_ops.decode_gif(s), axis=0), } with self.cached_session(): for path in paths: contents = io_ops.read_file(os.path.join(prefix, path)).eval() images = {} for name, decode in decoders.items(): image = decode(contents).eval() self.assertEqual(image.ndim, 3) for prev_name, prev in images.items(): print("path %s, names %s %s, shapes %s %s" % (path, name, prev_name, image.shape, prev.shape)) self.assertAllEqual(image, prev) images[name] = image def testError(self): path = "tensorflow/core/lib/gif/testdata/scan.gif" with self.cached_session(): for decode in image_ops.decode_jpeg, image_ops.decode_png: with self.assertRaisesOpError(r"Got 12 frames"): decode(io_ops.read_file(path)).eval() class NonMaxSuppressionTest(test_util.TensorFlowTestCase): @test_util.run_deprecated_v1 def NonMaxSuppressionTest(self): boxes_np = [[0, 0, 1, 1], [0, 0.1, 1, 1.1], [0, -0.1, 1, 0.9], [0, 10, 1, 11], [0, 10.1, 1, 11.1], [0, 100, 1, 101]] scores_np = [0.9, 0.75, 0.6, 0.95, 0.5, 0.3] max_output_size_np = 3 iou_threshold_np = 0.5 with self.cached_session(): boxes = constant_op.constant(boxes_np) scores = constant_op.constant(scores_np) max_output_size = constant_op.constant(max_output_size_np) iou_threshold = constant_op.constant(iou_threshold_np) selected_indices = image_ops.non_max_suppression( boxes, scores, max_output_size, iou_threshold) self.assertAllClose(selected_indices.eval(), [3, 0, 5]) @test_util.run_deprecated_v1 def testInvalidShape(self): # The boxes should be 2D of shape [num_boxes, 4]. with self.assertRaisesRegexp(ValueError, "Shape must be rank 2 but is rank 1"): boxes = constant_op.constant([0.0, 0.0, 1.0, 1.0]) scores = constant_op.constant([0.9]) image_ops.non_max_suppression(boxes, scores, 3, 0.5) with self.assertRaisesRegexp(ValueError, "Dimension must be 4 but is 3"): boxes = constant_op.constant([[0.0, 0.0, 1.0]]) scores = constant_op.constant([0.9]) image_ops.non_max_suppression(boxes, scores, 3, 0.5) # The boxes is of shape [num_boxes, 4], and the scores is # of shape [num_boxes]. So an error will be thrown. with self.assertRaisesRegexp(ValueError, "Dimensions must be equal, but are 1 and 2"): boxes = constant_op.constant([[0.0, 0.0, 1.0, 1.0]]) scores = constant_op.constant([0.9, 0.75]) image_ops.non_max_suppression(boxes, scores, 3, 0.5) # The scores should be 1D of shape [num_boxes]. with self.assertRaisesRegexp(ValueError, "Shape must be rank 1 but is rank 2"): boxes = constant_op.constant([[0.0, 0.0, 1.0, 1.0]]) scores = constant_op.constant([[0.9]]) image_ops.non_max_suppression(boxes, scores, 3, 0.5) # The max_output_size should be a scalar (0-D). with self.assertRaisesRegexp(ValueError, "Shape must be rank 0 but is rank 1"): boxes = constant_op.constant([[0.0, 0.0, 1.0, 1.0]]) scores = constant_op.constant([0.9]) image_ops.non_max_suppression(boxes, scores, [3], 0.5) # The iou_threshold should be a scalar (0-D). with self.assertRaisesRegexp(ValueError, "Shape must be rank 0 but is rank 2"): boxes = constant_op.constant([[0.0, 0.0, 1.0, 1.0]]) scores = constant_op.constant([0.9]) image_ops.non_max_suppression(boxes, scores, 3, [[0.5]]) @test_util.run_deprecated_v1 @test_util.xla_allow_fallback( "non_max_suppression with dynamic output shape unsupported.") def testDataTypes(self): # Test case for GitHub issue 20199. boxes_np = [[0, 0, 1, 1], [0, 0.1, 1, 1.1], [0, -0.1, 1, 0.9], [0, 10, 1, 11], [0, 10.1, 1, 11.1], [0, 100, 1, 101]] scores_np = [0.9, 0.75, 0.6, 0.95, 0.5, 0.3] max_output_size_np = 3 iou_threshold_np = 0.5 score_threshold_np = float("-inf") # Note: There are multiple versions of non_max_suppression v2, v3, v4. # gen_image_ops.non_max_suppression_v2: for dtype in [np.float16, np.float32]: with self.cached_session(): boxes = constant_op.constant(boxes_np, dtype=dtype) scores = constant_op.constant(scores_np, dtype=dtype) max_output_size = constant_op.constant(max_output_size_np) iou_threshold = constant_op.constant(iou_threshold_np, dtype=dtype) selected_indices = gen_image_ops.non_max_suppression_v2( boxes, scores, max_output_size, iou_threshold).eval() self.assertAllClose(selected_indices, [3, 0, 5]) # gen_image_ops.non_max_suppression_v3 for dtype in [np.float16, np.float32]: with self.cached_session(): boxes = constant_op.constant(boxes_np, dtype=dtype) scores = constant_op.constant(scores_np, dtype=dtype) max_output_size = constant_op.constant(max_output_size_np) iou_threshold = constant_op.constant(iou_threshold_np, dtype=dtype) score_threshold = constant_op.constant(score_threshold_np, dtype=dtype) selected_indices = gen_image_ops.non_max_suppression_v3( boxes, scores, max_output_size, iou_threshold, score_threshold) selected_indices = self.evaluate(selected_indices) self.assertAllClose(selected_indices, [3, 0, 5]) # gen_image_ops.non_max_suppression_v4. for dtype in [np.float16, np.float32]: with self.cached_session(): boxes = constant_op.constant(boxes_np, dtype=dtype) scores = constant_op.constant(scores_np, dtype=dtype) max_output_size = constant_op.constant(max_output_size_np) iou_threshold = constant_op.constant(iou_threshold_np, dtype=dtype) score_threshold = constant_op.constant(score_threshold_np, dtype=dtype) selected_indices, _ = gen_image_ops.non_max_suppression_v4( boxes, scores, max_output_size, iou_threshold, score_threshold) selected_indices = self.evaluate(selected_indices) self.assertAllClose(selected_indices, [3, 0, 5]) # gen_image_ops.non_max_suppression_v5. soft_nms_sigma_np = float(0.0) for dtype in [np.float16, np.float32]: with self.cached_session(): boxes = constant_op.constant(boxes_np, dtype=dtype) scores = constant_op.constant(scores_np, dtype=dtype) max_output_size = constant_op.constant(max_output_size_np) iou_threshold = constant_op.constant(iou_threshold_np, dtype=dtype) score_threshold = constant_op.constant(score_threshold_np, dtype=dtype) soft_nms_sigma = constant_op.constant(soft_nms_sigma_np, dtype=dtype) selected_indices, _, _ = gen_image_ops.non_max_suppression_v5( boxes, scores, max_output_size, iou_threshold, score_threshold, soft_nms_sigma) selected_indices = self.evaluate(selected_indices) self.assertAllClose(selected_indices, [3, 0, 5]) class NonMaxSuppressionWithScoresTest(test_util.TensorFlowTestCase): @test_util.run_deprecated_v1 @test_util.xla_allow_fallback( "non_max_suppression with dynamic output shape unsupported.") def testSelectFromThreeClustersWithSoftNMS(self): boxes_np = [[0, 0, 1, 1], [0, 0.1, 1, 1.1], [0, -0.1, 1, 0.9], [0, 10, 1, 11], [0, 10.1, 1, 11.1], [0, 100, 1, 101]] scores_np = [0.9, 0.75, 0.6, 0.95, 0.5, 0.3] max_output_size_np = 6 iou_threshold_np = 1.0 score_threshold_np = 0.0 soft_nms_sigma_np = 0.5 boxes = constant_op.constant(boxes_np) scores = constant_op.constant(scores_np) max_output_size = constant_op.constant(max_output_size_np) iou_threshold = constant_op.constant(iou_threshold_np) score_threshold = constant_op.constant(score_threshold_np) soft_nms_sigma = constant_op.constant(soft_nms_sigma_np) selected_indices, selected_scores = \ image_ops.non_max_suppression_with_scores( boxes, scores, max_output_size, iou_threshold, score_threshold, soft_nms_sigma) selected_indices, selected_scores = self.evaluate( [selected_indices, selected_scores]) self.assertAllClose(selected_indices, [3, 0, 1, 5, 4, 2]) self.assertAllClose(selected_scores, [0.95, 0.9, 0.384, 0.3, 0.256, 0.197], rtol=1e-2, atol=1e-2) class NonMaxSuppressionPaddedTest(test_util.TensorFlowTestCase): @test_util.run_deprecated_v1 @test_util.disable_xla( "b/141236442: " "non_max_suppression with dynamic output shape unsupported.") def testSelectFromThreeClusters(self): boxes_np = [[0, 0, 1, 1], [0, 0.1, 1, 1.1], [0, -0.1, 1, 0.9], [0, 10, 1, 11], [0, 10.1, 1, 11.1], [0, 100, 1, 101]] scores_np = [0.9, 0.75, 0.6, 0.95, 0.5, 0.3] max_output_size_np = 5 iou_threshold_np = 0.5 boxes = constant_op.constant(boxes_np) scores = constant_op.constant(scores_np) max_output_size = constant_op.constant(max_output_size_np) iou_threshold = constant_op.constant(iou_threshold_np) selected_indices_padded, num_valid_padded = \ image_ops.non_max_suppression_padded( boxes, scores, max_output_size, iou_threshold, pad_to_max_output_size=True) selected_indices, num_valid = image_ops.non_max_suppression_padded( boxes, scores, max_output_size, iou_threshold, pad_to_max_output_size=False) # The output shape of the padded operation must be fully defined. self.assertEqual(selected_indices_padded.shape.is_fully_defined(), True) self.assertEqual(selected_indices.shape.is_fully_defined(), False) with self.cached_session(): self.assertAllClose(selected_indices_padded.eval(), [3, 0, 5, 0, 0]) self.assertEqual(num_valid_padded.eval(), 3) self.assertAllClose(selected_indices.eval(), [3, 0, 5]) self.assertEqual(num_valid.eval(), 3) @test_util.run_deprecated_v1 @test_util.xla_allow_fallback( "non_max_suppression with dynamic output shape unsupported.") def testSelectFromContinuousOverLap(self): boxes_np = [[0, 0, 1, 1], [0, 0.2, 1, 1.2], [0, 0.4, 1, 1.4], [0, 0.6, 1, 1.6], [0, 0.8, 1, 1.8], [0, 2, 1, 2]] scores_np = [0.9, 0.75, 0.6, 0.5, 0.4, 0.3] max_output_size_np = 3 iou_threshold_np = 0.5 score_threshold_np = 0.1 boxes = constant_op.constant(boxes_np) scores = constant_op.constant(scores_np) max_output_size = constant_op.constant(max_output_size_np) iou_threshold = constant_op.constant(iou_threshold_np) score_threshold = constant_op.constant(score_threshold_np) selected_indices, num_valid = image_ops.non_max_suppression_padded( boxes, scores, max_output_size, iou_threshold, score_threshold) # The output shape of the padded operation must be fully defined. self.assertEqual(selected_indices.shape.is_fully_defined(), False) with self.cached_session(): self.assertAllClose(selected_indices.eval(), [0, 2, 4]) self.assertEqual(num_valid.eval(), 3) class NonMaxSuppressionWithOverlapsTest(test_util.TensorFlowTestCase): @test_util.run_deprecated_v1 def testSelectOneFromThree(self): overlaps_np = [ [1.0, 0.7, 0.2], [0.7, 1.0, 0.0], [0.2, 0.0, 1.0], ] scores_np = [0.7, 0.9, 0.1] max_output_size_np = 3 overlaps = constant_op.constant(overlaps_np) scores = constant_op.constant(scores_np) max_output_size = constant_op.constant(max_output_size_np) overlap_threshold = 0.6 score_threshold = 0.4 selected_indices = image_ops.non_max_suppression_with_overlaps( overlaps, scores, max_output_size, overlap_threshold, score_threshold) with self.cached_session(): self.assertAllClose(selected_indices.eval(), [1]) class VerifyCompatibleImageShapesTest(test_util.TensorFlowTestCase): """Tests utility function used by ssim() and psnr().""" @test_util.run_deprecated_v1 def testWrongDims(self): img = array_ops.placeholder(dtype=dtypes.float32) img_np = np.array((2, 2)) with self.cached_session(use_gpu=True) as sess: _, _, checks = image_ops_impl._verify_compatible_image_shapes(img, img) with self.assertRaises(errors.InvalidArgumentError): sess.run(checks, {img: img_np}) @test_util.run_deprecated_v1 def testShapeMismatch(self): img1 = array_ops.placeholder(dtype=dtypes.float32) img2 = array_ops.placeholder(dtype=dtypes.float32) img1_np = np.array([1, 2, 2, 1]) img2_np = np.array([1, 3, 3, 1]) with self.cached_session(use_gpu=True) as sess: _, _, checks = image_ops_impl._verify_compatible_image_shapes(img1, img2) with self.assertRaises(errors.InvalidArgumentError): sess.run(checks, {img1: img1_np, img2: img2_np}) class PSNRTest(test_util.TensorFlowTestCase): """Tests for PSNR.""" def _LoadTestImage(self, sess, filename): content = io_ops.read_file(os.path.join( "tensorflow/core/lib/psnr/testdata", filename)) im = image_ops.decode_jpeg(content, dct_method="INTEGER_ACCURATE") im = image_ops.convert_image_dtype(im, dtypes.float32) im, = self.evaluate([im]) return np.expand_dims(im, axis=0) def _LoadTestImages(self): with self.cached_session(use_gpu=True) as sess: q20 = self._LoadTestImage(sess, "cat_q20.jpg") q72 = self._LoadTestImage(sess, "cat_q72.jpg") q95 = self._LoadTestImage(sess, "cat_q95.jpg") return q20, q72, q95 def _PSNR_NumPy(self, orig, target, max_value): """Numpy implementation of PSNR.""" mse = ((orig - target) ** 2).mean(axis=(-3, -2, -1)) return 20 * np.log10(max_value) - 10 * np.log10(mse) def _RandomImage(self, shape, max_val): """Returns an image or image batch with given shape.""" return np.random.rand(*shape).astype(np.float32) * max_val @test_util.run_deprecated_v1 def testPSNRSingleImage(self): image1 = self._RandomImage((8, 8, 1), 1) image2 = self._RandomImage((8, 8, 1), 1) psnr = self._PSNR_NumPy(image1, image2, 1) with self.cached_session(use_gpu=True): tf_image1 = constant_op.constant(image1, shape=image1.shape, dtype=dtypes.float32) tf_image2 = constant_op.constant(image2, shape=image2.shape, dtype=dtypes.float32) tf_psnr = image_ops.psnr(tf_image1, tf_image2, 1.0, "psnr").eval() self.assertAllClose(psnr, tf_psnr, atol=0.001) @test_util.run_deprecated_v1 def testPSNRMultiImage(self): image1 = self._RandomImage((10, 8, 8, 1), 1) image2 = self._RandomImage((10, 8, 8, 1), 1) psnr = self._PSNR_NumPy(image1, image2, 1) with self.cached_session(use_gpu=True): tf_image1 = constant_op.constant(image1, shape=image1.shape, dtype=dtypes.float32) tf_image2 = constant_op.constant(image2, shape=image2.shape, dtype=dtypes.float32) tf_psnr = image_ops.psnr(tf_image1, tf_image2, 1, "psnr").eval() self.assertAllClose(psnr, tf_psnr, atol=0.001) @test_util.run_deprecated_v1 def testGoldenPSNR(self): q20, q72, q95 = self._LoadTestImages() # Verify NumPy implementation first. # Golden values are generated using GNU Octave's psnr() function. psnr1 = self._PSNR_NumPy(q20, q72, 1) self.assertNear(30.321, psnr1, 0.001, msg="q20.dtype=" + str(q20.dtype)) psnr2 = self._PSNR_NumPy(q20, q95, 1) self.assertNear(29.994, psnr2, 0.001) psnr3 = self._PSNR_NumPy(q72, q95, 1) self.assertNear(35.302, psnr3, 0.001) # Test TensorFlow implementation. with self.cached_session(use_gpu=True): tf_q20 = constant_op.constant(q20, shape=q20.shape, dtype=dtypes.float32) tf_q72 = constant_op.constant(q72, shape=q72.shape, dtype=dtypes.float32) tf_q95 = constant_op.constant(q95, shape=q95.shape, dtype=dtypes.float32) tf_psnr1 = image_ops.psnr(tf_q20, tf_q72, 1, "psnr1").eval() tf_psnr2 = image_ops.psnr(tf_q20, tf_q95, 1, "psnr2").eval() tf_psnr3 = image_ops.psnr(tf_q72, tf_q95, 1, "psnr3").eval() self.assertAllClose(psnr1, tf_psnr1, atol=0.001) self.assertAllClose(psnr2, tf_psnr2, atol=0.001) self.assertAllClose(psnr3, tf_psnr3, atol=0.001) @test_util.run_deprecated_v1 def testInfinity(self): q20, _, _ = self._LoadTestImages() psnr = self._PSNR_NumPy(q20, q20, 1) with self.cached_session(use_gpu=True): tf_q20 = constant_op.constant(q20, shape=q20.shape, dtype=dtypes.float32) tf_psnr = image_ops.psnr(tf_q20, tf_q20, 1, "psnr").eval() self.assertAllClose(psnr, tf_psnr, atol=0.001) @test_util.run_deprecated_v1 def testInt(self): img1 = self._RandomImage((10, 8, 8, 1), 255) img2 = self._RandomImage((10, 8, 8, 1), 255) img1 = constant_op.constant(img1, dtypes.uint8) img2 = constant_op.constant(img2, dtypes.uint8) psnr_uint8 = image_ops.psnr(img1, img2, 255) img1 = image_ops.convert_image_dtype(img1, dtypes.float32) img2 = image_ops.convert_image_dtype(img2, dtypes.float32) psnr_float32 = image_ops.psnr(img1, img2, 1.0) with self.cached_session(use_gpu=True): self.assertAllClose( psnr_uint8.eval(), self.evaluate(psnr_float32), atol=0.001) class SSIMTest(test_util.TensorFlowTestCase): """Tests for SSIM.""" _filenames = ["checkerboard1.png", "checkerboard2.png", "checkerboard3.png",] _ssim = np.asarray([[1.000000, 0.230880, 0.231153], [0.230880, 1.000000, 0.996828], [0.231153, 0.996828, 1.000000]]) def _LoadTestImage(self, sess, filename): content = io_ops.read_file(os.path.join( "tensorflow/core/lib/ssim/testdata", filename)) im = image_ops.decode_png(content) im = image_ops.convert_image_dtype(im, dtypes.float32) im, = self.evaluate([im]) return np.expand_dims(im, axis=0) def _LoadTestImages(self): with self.cached_session(use_gpu=True) as sess: return [self._LoadTestImage(sess, f) for f in self._filenames] def _RandomImage(self, shape, max_val): """Returns an image or image batch with given shape.""" return np.random.rand(*shape).astype(np.float32) * max_val @test_util.run_deprecated_v1 def testAgainstMatlab(self): """Tests against values produced by Matlab.""" img = self._LoadTestImages() expected = self._ssim[np.triu_indices(3)] ph = [array_ops.placeholder(dtype=dtypes.float32) for _ in range(2)] ssim = image_ops.ssim( *ph, max_val=1.0, filter_size=11, filter_sigma=1.5, k1=0.01, k2=0.03) with self.cached_session(use_gpu=True): scores = [ssim.eval(dict(zip(ph, t))) for t in itertools.combinations_with_replacement(img, 2)] self.assertAllClose(expected, np.squeeze(scores), atol=1e-4) def testBatch(self): img = self._LoadTestImages() expected = self._ssim[np.triu_indices(3, k=1)] img1, img2 = zip(*itertools.combinations(img, 2)) img1 = np.concatenate(img1) img2 = np.concatenate(img2) ssim = image_ops.ssim( constant_op.constant(img1), constant_op.constant(img2), 1.0, filter_size=11, filter_sigma=1.5, k1=0.01, k2=0.03) with self.cached_session(use_gpu=True): self.assertAllClose(expected, self.evaluate(ssim), atol=1e-4) def testBroadcast(self): img = self._LoadTestImages()[:2] expected = self._ssim[:2, :2] img = constant_op.constant(np.concatenate(img)) img1 = array_ops.expand_dims(img, axis=0) # batch dims: 1, 2. img2 = array_ops.expand_dims(img, axis=1) # batch dims: 2, 1. ssim = image_ops.ssim( img1, img2, 1.0, filter_size=11, filter_sigma=1.5, k1=0.01, k2=0.03) with self.cached_session(use_gpu=True): self.assertAllClose(expected, self.evaluate(ssim), atol=1e-4) @test_util.run_deprecated_v1 def testNegative(self): """Tests against negative SSIM index.""" step = np.expand_dims(np.arange(0, 256, 16, dtype=np.uint8), axis=0) img1 = np.tile(step, (16, 1)) img2 = np.fliplr(img1) img1 = img1.reshape((1, 16, 16, 1)) img2 = img2.reshape((1, 16, 16, 1)) ssim = image_ops.ssim( constant_op.constant(img1), constant_op.constant(img2), 255, filter_size=11, filter_sigma=1.5, k1=0.01, k2=0.03) with self.cached_session(use_gpu=True): self.assertLess(ssim.eval(), 0) @test_util.run_deprecated_v1 def testInt(self): img1 = self._RandomImage((1, 16, 16, 3), 255) img2 = self._RandomImage((1, 16, 16, 3), 255) img1 = constant_op.constant(img1, dtypes.uint8) img2 = constant_op.constant(img2, dtypes.uint8) ssim_uint8 = image_ops.ssim( img1, img2, 255, filter_size=11, filter_sigma=1.5, k1=0.01, k2=0.03) img1 = image_ops.convert_image_dtype(img1, dtypes.float32) img2 = image_ops.convert_image_dtype(img2, dtypes.float32) ssim_float32 = image_ops.ssim( img1, img2, 1.0, filter_size=11, filter_sigma=1.5, k1=0.01, k2=0.03) with self.cached_session(use_gpu=True): self.assertAllClose( ssim_uint8.eval(), self.evaluate(ssim_float32), atol=0.001) class MultiscaleSSIMTest(test_util.TensorFlowTestCase): """Tests for MS-SSIM.""" _filenames = ["checkerboard1.png", "checkerboard2.png", "checkerboard3.png",] _msssim = np.asarray([[1.000000, 0.091016, 0.091025], [0.091016, 1.000000, 0.999567], [0.091025, 0.999567, 1.000000]]) def _LoadTestImage(self, sess, filename): content = io_ops.read_file(os.path.join( "tensorflow/core/lib/ssim/testdata", filename)) im = image_ops.decode_png(content) im = image_ops.convert_image_dtype(im, dtypes.float32) im, = self.evaluate([im]) return np.expand_dims(im, axis=0) def _LoadTestImages(self): with self.cached_session(use_gpu=True) as sess: return [self._LoadTestImage(sess, f) for f in self._filenames] def _RandomImage(self, shape, max_val): """Returns an image or image batch with given shape.""" return np.random.rand(*shape).astype(np.float32) * max_val @test_util.run_deprecated_v1 def testAgainstMatlab(self): """Tests against MS-SSIM computed with Matlab implementation. For color images, MS-SSIM scores are averaged over color channels. """ img = self._LoadTestImages() expected = self._msssim[np.triu_indices(3)] ph = [array_ops.placeholder(dtype=dtypes.float32) for _ in range(2)] msssim = image_ops.ssim_multiscale( *ph, max_val=1.0, filter_size=11, filter_sigma=1.5, k1=0.01, k2=0.03) with self.cached_session(use_gpu=True): scores = [msssim.eval(dict(zip(ph, t))) for t in itertools.combinations_with_replacement(img, 2)] self.assertAllClose(expected, np.squeeze(scores), atol=1e-4) @test_util.run_deprecated_v1 def testUnweightedIsDifferentiable(self): img = self._LoadTestImages() ph = [array_ops.placeholder(dtype=dtypes.float32) for _ in range(2)] scalar = constant_op.constant(1.0, dtype=dtypes.float32) scaled_ph = [x * scalar for x in ph] msssim = image_ops.ssim_multiscale( *scaled_ph, max_val=1.0, power_factors=(1, 1, 1, 1, 1), filter_size=11, filter_sigma=1.5, k1=0.01, k2=0.03) grads = gradients.gradients(msssim, scalar) with self.cached_session(use_gpu=True) as sess: np_grads = sess.run(grads, feed_dict={ph[0]: img[0], ph[1]: img[1]}) self.assertTrue(np.isfinite(np_grads).all()) def testBatch(self): """Tests MS-SSIM computed in batch.""" img = self._LoadTestImages() expected = self._msssim[np.triu_indices(3, k=1)] img1, img2 = zip(*itertools.combinations(img, 2)) img1 = np.concatenate(img1) img2 = np.concatenate(img2) msssim = image_ops.ssim_multiscale( constant_op.constant(img1), constant_op.constant(img2), 1.0, filter_size=11, filter_sigma=1.5, k1=0.01, k2=0.03) with self.cached_session(use_gpu=True): self.assertAllClose(expected, self.evaluate(msssim), 1e-4) def testBroadcast(self): """Tests MS-SSIM broadcasting.""" img = self._LoadTestImages()[:2] expected = self._msssim[:2, :2] img = constant_op.constant(np.concatenate(img)) img1 = array_ops.expand_dims(img, axis=0) # batch dims: 1, 2. img2 = array_ops.expand_dims(img, axis=1) # batch dims: 2, 1. score_tensor = image_ops.ssim_multiscale( img1, img2, 1.0, filter_size=11, filter_sigma=1.5, k1=0.01, k2=0.03) with self.cached_session(use_gpu=True): self.assertAllClose(expected, self.evaluate(score_tensor), 1e-4) def testRange(self): """Tests against low MS-SSIM score. MS-SSIM is a geometric mean of SSIM and CS scores of various scales. If any of the value is negative so that the geometric mean is not well-defined, then treat the MS-SSIM score as zero. """ with self.cached_session(use_gpu=True) as sess: img1 = self._LoadTestImage(sess, "checkerboard1.png") img2 = self._LoadTestImage(sess, "checkerboard3.png") images = [img1, img2, np.zeros_like(img1), np.full_like(img1, fill_value=255)] images = [ops.convert_to_tensor(x, dtype=dtypes.float32) for x in images] msssim_ops = [ image_ops.ssim_multiscale( x, y, 1.0, filter_size=11, filter_sigma=1.5, k1=0.01, k2=0.03) for x, y in itertools.combinations(images, 2) ] msssim = self.evaluate(msssim_ops) msssim = np.squeeze(msssim) self.assertTrue(np.all(msssim >= 0.0)) self.assertTrue(np.all(msssim <= 1.0)) @test_util.run_deprecated_v1 def testInt(self): img1 = self._RandomImage((1, 180, 240, 3), 255) img2 = self._RandomImage((1, 180, 240, 3), 255) img1 = constant_op.constant(img1, dtypes.uint8) img2 = constant_op.constant(img2, dtypes.uint8) ssim_uint8 = image_ops.ssim_multiscale( img1, img2, 255, filter_size=11, filter_sigma=1.5, k1=0.01, k2=0.03) img1 = image_ops.convert_image_dtype(img1, dtypes.float32) img2 = image_ops.convert_image_dtype(img2, dtypes.float32) ssim_float32 = image_ops.ssim_multiscale( img1, img2, 1.0, filter_size=11, filter_sigma=1.5, k1=0.01, k2=0.03) with self.cached_session(use_gpu=True): self.assertAllClose( ssim_uint8.eval(), self.evaluate(ssim_float32), atol=0.001) def testNumpyInput(self): """Test case for GitHub issue 28241.""" image = np.random.random([512, 512, 1]) score_tensor = image_ops.ssim_multiscale(image, image, max_val=1.0) with self.cached_session(use_gpu=True): _ = self.evaluate(score_tensor) class ImageGradientsTest(test_util.TensorFlowTestCase): def testImageGradients(self): shape = [1, 2, 4, 1] img = constant_op.constant([[1, 3, 4, 2], [8, 7, 5, 6]]) img = array_ops.reshape(img, shape) expected_dy = np.reshape([[7, 4, 1, 4], [0, 0, 0, 0]], shape) expected_dx = np.reshape([[2, 1, -2, 0], [-1, -2, 1, 0]], shape) dy, dx = image_ops.image_gradients(img) with self.cached_session(): actual_dy = self.evaluate(dy) actual_dx = self.evaluate(dx) self.assertAllClose(expected_dy, actual_dy) self.assertAllClose(expected_dx, actual_dx) def testImageGradientsMultiChannelBatch(self): batch = [[[[1, 2], [2, 5], [3, 3]], [[8, 4], [5, 1], [9, 8]]], [[[5, 3], [7, 9], [1, 6]], [[1, 2], [6, 3], [6, 3]]]] expected_dy = [[[[7, 2], [3, -4], [6, 5]], [[0, 0], [0, 0], [0, 0]]], [[[-4, -1], [-1, -6], [5, -3]], [[0, 0], [0, 0], [0, 0]]]] expected_dx = [[[[1, 3], [1, -2], [0, 0]], [[-3, -3], [4, 7], [0, 0]]], [[[2, 6], [-6, -3], [0, 0]], [[5, 1], [0, 0], [0, 0]]]] batch = constant_op.constant(batch) assert batch.get_shape().as_list() == [2, 2, 3, 2] dy, dx = image_ops.image_gradients(batch) with self.cached_session(use_gpu=True): actual_dy = self.evaluate(dy) actual_dx = self.evaluate(dx) self.assertAllClose(expected_dy, actual_dy) self.assertAllClose(expected_dx, actual_dx) def testImageGradientsBadShape(self): # [2 x 4] image but missing batch and depth dimensions. img = constant_op.constant([[1, 3, 4, 2], [8, 7, 5, 6]]) with self.assertRaises(ValueError): image_ops.image_gradients(img) class SobelEdgesTest(test_util.TensorFlowTestCase): def disabled_testSobelEdges1x2x3x1(self): img = constant_op.constant([[1, 3, 6], [4, 1, 5]], dtype=dtypes.float32, shape=[1, 2, 3, 1]) expected = np.reshape([[[0, 0], [0, 12], [0, 0]], [[0, 0], [0, 12], [0, 0]]], [1, 2, 3, 1, 2]) sobel = image_ops.sobel_edges(img) with self.cached_session(use_gpu=True): actual_sobel = self.evaluate(sobel) self.assertAllClose(expected, actual_sobel) def testSobelEdges5x3x4x2(self): batch_size = 5 plane = np.reshape([[1, 3, 6, 2], [4, 1, 5, 7], [2, 5, 1, 4]], [1, 3, 4, 1]) two_channel = np.concatenate([plane, plane], axis=3) batch = np.concatenate([two_channel] * batch_size, axis=0) img = constant_op.constant(batch, dtype=dtypes.float32, shape=[batch_size, 3, 4, 2]) expected_plane = np.reshape([[[0, 0], [0, 12], [0, 10], [0, 0]], [[6, 0], [0, 6], [-6, 10], [-6, 0]], [[0, 0], [0, 0], [0, 10], [0, 0]]], [1, 3, 4, 1, 2]) expected_two_channel = np.concatenate( [expected_plane, expected_plane], axis=3) expected_batch = np.concatenate([expected_two_channel] * batch_size, axis=0) sobel = image_ops.sobel_edges(img) with self.cached_session(use_gpu=True): actual_sobel = self.evaluate(sobel) self.assertAllClose(expected_batch, actual_sobel) @test_util.run_all_in_graph_and_eager_modes class DecodeImageTest(test_util.TensorFlowTestCase): def testJpegUint16(self): with self.cached_session(use_gpu=True) as sess: base = "tensorflow/core/lib/jpeg/testdata" jpeg0 = io_ops.read_file(os.path.join(base, "jpeg_merge_test1.jpg")) image0 = image_ops.decode_image(jpeg0, dtype=dtypes.uint16) image1 = image_ops.convert_image_dtype(image_ops.decode_jpeg(jpeg0), dtypes.uint16) image0, image1 = self.evaluate([image0, image1]) self.assertAllEqual(image0, image1) def testPngUint16(self): with self.cached_session(use_gpu=True) as sess: base = "tensorflow/core/lib/png/testdata" png0 = io_ops.read_file(os.path.join(base, "lena_rgba.png")) image0 = image_ops.decode_image(png0, dtype=dtypes.uint16) image1 = image_ops.convert_image_dtype( image_ops.decode_png(png0, dtype=dtypes.uint16), dtypes.uint16) image0, image1 = self.evaluate([image0, image1]) self.assertAllEqual(image0, image1) # NumPy conversions should happen before x = np.random.randint(256, size=(4, 4, 3), dtype=np.uint16) x_str = image_ops_impl.encode_png(x) x_dec = image_ops_impl.decode_image( x_str, channels=3, dtype=dtypes.uint16) self.assertAllEqual(x, x_dec) def testGifUint16(self): with self.cached_session(use_gpu=True) as sess: base = "tensorflow/core/lib/gif/testdata" gif0 = io_ops.read_file(os.path.join(base, "scan.gif")) image0 = image_ops.decode_image(gif0, dtype=dtypes.uint16) image1 = image_ops.convert_image_dtype(image_ops.decode_gif(gif0), dtypes.uint16) image0, image1 = self.evaluate([image0, image1]) self.assertAllEqual(image0, image1) def testBmpUint16(self): with self.cached_session(use_gpu=True) as sess: base = "tensorflow/core/lib/bmp/testdata" bmp0 = io_ops.read_file(os.path.join(base, "lena.bmp")) image0 = image_ops.decode_image(bmp0, dtype=dtypes.uint16) image1 = image_ops.convert_image_dtype(image_ops.decode_bmp(bmp0), dtypes.uint16) image0, image1 = self.evaluate([image0, image1]) self.assertAllEqual(image0, image1) def testJpegFloat32(self): with self.cached_session(use_gpu=True) as sess: base = "tensorflow/core/lib/jpeg/testdata" jpeg0 = io_ops.read_file(os.path.join(base, "jpeg_merge_test1.jpg")) image0 = image_ops.decode_image(jpeg0, dtype=dtypes.float32) image1 = image_ops.convert_image_dtype(image_ops.decode_jpeg(jpeg0), dtypes.float32) image0, image1 = self.evaluate([image0, image1]) self.assertAllEqual(image0, image1) def testPngFloat32(self): with self.cached_session(use_gpu=True) as sess: base = "tensorflow/core/lib/png/testdata" png0 = io_ops.read_file(os.path.join(base, "lena_rgba.png")) image0 = image_ops.decode_image(png0, dtype=dtypes.float32) image1 = image_ops.convert_image_dtype( image_ops.decode_png(png0, dtype=dtypes.uint16), dtypes.float32) image0, image1 = self.evaluate([image0, image1]) self.assertAllEqual(image0, image1) def testGifFloat32(self): with self.cached_session(use_gpu=True) as sess: base = "tensorflow/core/lib/gif/testdata" gif0 = io_ops.read_file(os.path.join(base, "scan.gif")) image0 = image_ops.decode_image(gif0, dtype=dtypes.float32) image1 = image_ops.convert_image_dtype(image_ops.decode_gif(gif0), dtypes.float32) image0, image1 = self.evaluate([image0, image1]) self.assertAllEqual(image0, image1) def testBmpFloat32(self): with self.cached_session(use_gpu=True) as sess: base = "tensorflow/core/lib/bmp/testdata" bmp0 = io_ops.read_file(os.path.join(base, "lena.bmp")) image0 = image_ops.decode_image(bmp0, dtype=dtypes.float32) image1 = image_ops.convert_image_dtype(image_ops.decode_bmp(bmp0), dtypes.float32) image0, image1 = self.evaluate([image0, image1]) self.assertAllEqual(image0, image1) def testExpandAnimations(self): with self.cached_session(use_gpu=True) as sess: base = "tensorflow/core/lib/gif/testdata" gif0 = io_ops.read_file(os.path.join(base, "scan.gif")) image0 = image_ops.decode_image( gif0, dtype=dtypes.float32, expand_animations=False) # image_ops.decode_png() handles GIFs and returns 3D tensors animation = image_ops.decode_gif(gif0) first_frame = array_ops.gather(animation, 0) image1 = image_ops.convert_image_dtype(first_frame, dtypes.float32) image0, image1 = self.evaluate([image0, image1]) self.assertEqual(len(image0.shape), 3) self.assertAllEqual(list(image0.shape), [40, 20, 3]) self.assertAllEqual(image0, image1) if __name__ == "__main__": googletest.main()
apache-2.0
hymanme/MaterialHome
app/src/main/java/com/hymane/materialhome/module/zxing/camera/PlanarYUVLuminanceSource.java
4094
/* * Copyright 2009 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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.hymane.materialhome.module.zxing.camera; import com.google.zxing.LuminanceSource; import android.graphics.Bitmap; /** * This object extends LuminanceSource around an array of YUV data returned from the camera driver, * with the option to crop to a rectangle within the full data. This can be used to exclude * superfluous pixels around the perimeter and speed up decoding. * * It works for any pixel format where the Y channel is planar and appears first, including * YCbCr_420_SP and YCbCr_422_SP. * * @author dswitkin@google.com (Daniel Switkin) */ public final class PlanarYUVLuminanceSource extends LuminanceSource { private final byte[] yuvData; private final int dataWidth; private final int dataHeight; private final int left; private final int top; public PlanarYUVLuminanceSource(byte[] yuvData, int dataWidth, int dataHeight, int left, int top, int width, int height) { super(width, height); if (left + width > dataWidth || top + height > dataHeight) { throw new IllegalArgumentException("Crop rectangle does not fit within image data."); } this.yuvData = yuvData; this.dataWidth = dataWidth; this.dataHeight = dataHeight; this.left = left; this.top = top; } @Override public byte[] getRow(int y, byte[] row) { if (y < 0 || y >= getHeight()) { throw new IllegalArgumentException("Requested row is outside the image: " + y); } int width = getWidth(); if (row == null || row.length < width) { row = new byte[width]; } int offset = (y + top) * dataWidth + left; System.arraycopy(yuvData, offset, row, 0, width); return row; } @Override public byte[] getMatrix() { int width = getWidth(); int height = getHeight(); // If the caller asks for the entire underlying image, save the copy and give them the // original data. The docs specifically warn that result.length must be ignored. if (width == dataWidth && height == dataHeight) { return yuvData; } int area = width * height; byte[] matrix = new byte[area]; int inputOffset = top * dataWidth + left; // If the width matches the full width of the underlying data, perform a single copy. if (width == dataWidth) { System.arraycopy(yuvData, inputOffset, matrix, 0, area); return matrix; } // Otherwise copy one cropped row at a time. byte[] yuv = yuvData; for (int y = 0; y < height; y++) { int outputOffset = y * width; System.arraycopy(yuv, inputOffset, matrix, outputOffset, width); inputOffset += dataWidth; } return matrix; } @Override public boolean isCropSupported() { return true; } public int getDataWidth() { return dataWidth; } public int getDataHeight() { return dataHeight; } public Bitmap renderCroppedGreyscaleBitmap() { int width = getWidth(); int height = getHeight(); int[] pixels = new int[width * height]; byte[] yuv = yuvData; int inputOffset = top * dataWidth + left; for (int y = 0; y < height; y++) { int outputOffset = y * width; for (int x = 0; x < width; x++) { int grey = yuv[inputOffset + x] & 0xff; pixels[outputOffset + x] = 0xFF000000 | (grey * 0x00010101); } inputOffset += dataWidth; } Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, width, 0, 0, width, height); return bitmap; } }
apache-2.0
pantiushenkov/conference_central
src/main/java/com/google/devrel/training/conference/servlet/SetAnnouncementServlet.java
2643
package com.google.devrel.training.conference.servlet; /** * Created by vlad on 3/28/17. */ import static com.google.devrel.training.conference.service.OfyService.ofy; import com.google.appengine.api.memcache.MemcacheService; import com.google.appengine.api.memcache.MemcacheServiceFactory; import com.google.common.base.Joiner; import com.google.devrel.training.conference.Constants; import com.google.devrel.training.conference.domain.Conference; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * A servlet for putting announcements in memcache. * The announcement announces conferences that are nearly sold out * (defined as having 1 - 5 seats left) */ @SuppressWarnings("serial") public class SetAnnouncementServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO // Query for conferences with less than 5 seats left Iterable<Conference> iterable = ofy().load().type(Conference.class). filter("seatsAvailable <", 5); // TODO // Iterate over the conferences with less than 5 seats less // and get the name of each one List<String> conferenceNames = new ArrayList<>(0); for (Conference conference : iterable) { conferenceNames.add(conference.getName()); } if (conferenceNames.size() > 0) { // Build a String that announces the nearly sold-out conferences StringBuilder announcementStringBuilder = new StringBuilder( "Last chance to attend! The following conferences are nearly sold out: "); Joiner joiner = Joiner.on(", ").skipNulls(); announcementStringBuilder.append(joiner.join(conferenceNames)); // TODO // Get the Memcache Service MemcacheService memcacheService = MemcacheServiceFactory.getMemcacheService(); // TODO // Put the announcement String in memcache, // keyed by memcacheService.put(Constants.MEMCACHE_ANNOUNCEMENTS_KEY, announcementStringBuilder.toString()); } // Set the response status to 204 which means // the request was successful but there's no data to send back // Browser stays on the same page if the get came from the browser response.setStatus(204); } }
apache-2.0
iris-dni/iris-frontend
src/components/FormFieldsIterator/index.js
672
import React from 'react'; import { get } from 'lodash/object'; import FormField from 'components/FormField'; import styles from './form-field-iterator.scss'; const FormFieldsIterator = ({ reduxFormFields, fieldsArray = [], trustedFields = {} }) => ( <div className={styles.root}> {fieldsArray.map(field => ( <div key={field.name} className={field.half ? styles['field-half'] : styles.field}> <FormField key={field.name} isTrusted={trustedFields[field.name] || false} config={field} helper={get(reduxFormFields, field.name)} /> </div> ))} </div> ); export default FormFieldsIterator;
apache-2.0
aslakknutsen/arquillian-example-chameleon-wildfly
src/test/java/org/arquillian/example/chameleon/wildfly/ManagementClientTestCase.java
1354
package org.arquillian.example.chameleon.wildfly; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.container.test.api.TargetsContainer; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(Arquillian.class) public class ManagementClientTestCase { @Deployment(testable = false, name = "A") @TargetsContainer("jbossas") public static WebArchive deploy() { return ShrinkWrap.create(WebArchive.class) .addAsWebResource(EmptyAsset.INSTANCE, "index.html"); } @Deployment(testable = false, name = "B") @TargetsContainer("wildfly") public static WebArchive deploy2() { return ShrinkWrap.create(WebArchive.class) .addAsWebResource(EmptyAsset.INSTANCE, "index.html"); } @ArquillianResource private ManagementClient mc; @Test @OperateOnDeployment("A") public void shouldWorkJBoss() throws Exception { System.out.println(mc.getWebUri()); } @Test @OperateOnDeployment("B") public void shouldWorkWildFly() throws Exception { System.out.println(mc.getWebUri()); } }
apache-2.0
bright-tools/coverage
annotator/coverage-annotator.cpp
5599
/* Copyright 2013 John Bailey Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 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 project was kick-started by the public domain example provided by Eli Bendersky (eliben@gmail.com) at http://eli.thegreenplace.net/2012/06/08/basic-source-to-source-transformation-with-clang/ Grateful thanks are due to Eli for sharing his knowledge */ #include "clang/ASTMatchers/ASTMatchers.h" #include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/Basic/SourceManager.h" #include "clang/Frontend/FrontendActions.h" #include "clang/Lex/Lexer.h" #include "clang/Tooling/CompilationDatabase.h" #include "clang/Tooling/Refactoring.h" #include "clang/Tooling/Tooling.h" #include "llvm/ADT/OwningPtr.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Signals.h" #include "llvm/Support/raw_ostream.h" #include "clang/Rewrite/Core/Rewriter.h" #include "clang/Rewrite/Frontend/Rewriters.h" #include "clang/Frontend/TextDiagnosticPrinter.h" #include "ForAnnotator.hpp" #include "WhileAnnotator.hpp" #include "IfAnnotator.hpp" #include "CaseAnnotator.hpp" #include "coverage-annotator-cl.hpp" #include <string> using namespace clang; using namespace clang::ast_matchers; using namespace clang::tooling; using namespace llvm; namespace { class ToolTemplateCallback : public MatchFinder::MatchCallback { public: ToolTemplateCallback(Replacements *Replace) : Replace(Replace) {} virtual void run(const MatchFinder::MatchResult &Result) { // TODO: This routine will get called for each thing that the matchers find. // At this point, you can examine the match, and do whatever you want, // including replacing the matched text with other text (void) Replace; // This to prevent an "unused member variable" warning; } private: Replacements *Replace; }; } // end anonymous namespace // Set up the command line options cl::opt<std::string> BuildPath( cl::Positional, cl::desc("<build-path>")); cl::opt<std::string> ProjectRoot( "r", cl::desc("Set project root directory"), cl::value_desc("filename")); cl::opt<std::string> SourcePaths( cl::Positional, cl::desc("<source>"), cl::Required); StatementMatcher LoopMatcher = forStmt().bind("forLoop"); StatementMatcher IfMatcher = ifStmt().bind("ifStmt"); StatementMatcher WhileMatcher = whileStmt().bind("whileLoop"); StatementMatcher CaseMatcher = caseStmt().bind("caseStmt"); // TODO: default ... case doesn't cover that. // TODO: do .. while // TODO: goto // TODO: while ... // TODO: function decl // TODO: return .. int main(int argc, const char **argv) { llvm::sys::PrintStackTraceOnErrorSignal(); llvm::OwningPtr<CompilationDatabase> Compilations( FixedCompilationDatabase::loadFromCommandLine(argc, argv)); cl::ParseCommandLineOptions(argc, argv); if (!Compilations) { // Couldn't find a compilation DB from the command line std::string ErrorMessage; Compilations.reset( !BuildPath.empty() ? CompilationDatabase::autoDetectFromDirectory(BuildPath, ErrorMessage) : CompilationDatabase::autoDetectFromSource(SourcePaths, ErrorMessage) ); // Still no compilation DB? - bail. if (!Compilations) { llvm::report_fatal_error(ErrorMessage); } } RefactoringTool Tool(*Compilations, SourcePaths); ast_matchers::MatchFinder Finder; //ToolTemplateCallback Callback(&Tool.getReplacements()); ForAnnotator forAnnotator(&Tool.getReplacements()); Finder.addMatcher(LoopMatcher, &forAnnotator); IfAnnotator ifAnnotator(&Tool.getReplacements()); Finder.addMatcher(IfMatcher, &ifAnnotator); WhileAnnotator whileAnnotator(&Tool.getReplacements()); Finder.addMatcher(WhileMatcher, &whileAnnotator); CaseAnnotator caseAnnotator(&Tool.getReplacements()); Finder.addMatcher(CaseMatcher, &caseAnnotator); int Result = Tool.run(newFrontendActionFactory(&Finder)); if( !Result ) { LangOptions DefaultLangOptions; IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions(); TextDiagnosticPrinter DiagnosticPrinter(llvm::errs(), &*DiagOpts); DiagnosticsEngine Diagnostics( IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts, &DiagnosticPrinter, false); SourceManager Sources(Diagnostics, Tool.getFiles()); Rewriter Rewrite(Sources, DefaultLangOptions); const FileEntry *FileIn = Sources.getFileManager().getFile(SourcePaths); FileID f = Sources.createMainFileID(FileIn); if (!tooling::applyAllReplacements(Tool.getReplacements(),Rewrite)) { llvm::errs() << "Skipped some replacements.\n"; } const RewriteBuffer *RewriteBuf = Rewrite.getRewriteBufferFor(f); if( RewriteBuf == NULL ) { /* No re-writes? Use file verbatim */ llvm::errs() << "Couldn't get rewrite buffer.\n"; const MemoryBuffer* verbatimBuffer = Sources.getFileManager().getBufferForFile(FileIn); llvm::outs() << std::string(verbatimBuffer->getBufferStart(), verbatimBuffer->getBufferEnd()); } else { llvm::outs() << std::string(RewriteBuf->begin(), RewriteBuf->end()); } } return Result; }
apache-2.0
chanil1218/elasticsearch
src/main/java/org/elasticsearch/http/netty/NettyHttpServerTransport.java
14281
/* * Licensed to ElasticSearch and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. ElasticSearch 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.elasticsearch.http.netty; import org.elasticsearch.ElasticSearchException; import org.elasticsearch.common.component.AbstractLifecycleComponent; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.netty.OpenChannelsHandler; import org.elasticsearch.common.network.NetworkService; import org.elasticsearch.common.network.NetworkUtils; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.BoundTransportAddress; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.common.transport.NetworkExceptionHelper; import org.elasticsearch.common.transport.PortsRange; import org.elasticsearch.common.unit.ByteSizeUnit; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.http.*; import org.elasticsearch.http.HttpRequest; import org.elasticsearch.transport.BindTransportException; import org.elasticsearch.transport.netty.NettyInternalESLoggerFactory; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.*; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.jboss.netty.channel.socket.oio.OioServerSocketChannelFactory; import org.jboss.netty.handler.codec.http.*; import org.jboss.netty.handler.timeout.ReadTimeoutException; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicReference; import static org.elasticsearch.common.network.NetworkService.TcpSettings.*; import static org.elasticsearch.common.util.concurrent.EsExecutors.daemonThreadFactory; /** * */ public class NettyHttpServerTransport extends AbstractLifecycleComponent<HttpServerTransport> implements HttpServerTransport { static { InternalLoggerFactory.setDefaultFactory(new NettyInternalESLoggerFactory() { @Override public InternalLogger newInstance(String name) { return super.newInstance(name.replace("org.jboss.netty.", "netty.").replace("org.jboss.netty.", "netty.")); } }); } private final NetworkService networkService; final ByteSizeValue maxContentLength; final ByteSizeValue maxInitialLineLength; final ByteSizeValue maxHeaderSize; final ByteSizeValue maxChunkSize; private final int workerCount; private final boolean blockingServer; final boolean compression; private final int compressionLevel; final boolean resetCookies; private final String port; private final String bindHost; private final String publishHost; private final Boolean tcpNoDelay; private final Boolean tcpKeepAlive; private final Boolean reuseAddress; private final ByteSizeValue tcpSendBufferSize; private final ByteSizeValue tcpReceiveBufferSize; private volatile ServerBootstrap serverBootstrap; private volatile BoundTransportAddress boundAddress; private volatile Channel serverChannel; OpenChannelsHandler serverOpenChannels; private volatile HttpServerAdapter httpServerAdapter; @Inject public NettyHttpServerTransport(Settings settings, NetworkService networkService) { super(settings); this.networkService = networkService; ByteSizeValue maxContentLength = componentSettings.getAsBytesSize("max_content_length", settings.getAsBytesSize("http.max_content_length", new ByteSizeValue(100, ByteSizeUnit.MB))); this.maxChunkSize = componentSettings.getAsBytesSize("max_chunk_size", settings.getAsBytesSize("http.max_chunk_size", new ByteSizeValue(8, ByteSizeUnit.KB))); this.maxHeaderSize = componentSettings.getAsBytesSize("max_header_size", settings.getAsBytesSize("http.max_header_size", new ByteSizeValue(8, ByteSizeUnit.KB))); this.maxInitialLineLength = componentSettings.getAsBytesSize("max_initial_line_length", settings.getAsBytesSize("http.max_initial_line_length", new ByteSizeValue(4, ByteSizeUnit.KB))); // don't reset cookies by default, since I don't think we really need to, and parsing of cookies with netty is slow // and requires a large stack allocation because of the use of regex this.resetCookies = componentSettings.getAsBoolean("reset_cookies", settings.getAsBoolean("http.reset_cookies", false)); this.workerCount = componentSettings.getAsInt("worker_count", Runtime.getRuntime().availableProcessors() * 2); this.blockingServer = settings.getAsBoolean("http.blocking_server", settings.getAsBoolean(TCP_BLOCKING_SERVER, settings.getAsBoolean(TCP_BLOCKING, false))); this.port = componentSettings.get("port", settings.get("http.port", "9200-9300")); this.bindHost = componentSettings.get("bind_host", settings.get("http.bind_host", settings.get("http.host"))); this.publishHost = componentSettings.get("publish_host", settings.get("http.publish_host", settings.get("http.host"))); this.tcpNoDelay = componentSettings.getAsBoolean("tcp_no_delay", settings.getAsBoolean(TCP_NO_DELAY, true)); this.tcpKeepAlive = componentSettings.getAsBoolean("tcp_keep_alive", settings.getAsBoolean(TCP_KEEP_ALIVE, true)); this.reuseAddress = componentSettings.getAsBoolean("reuse_address", settings.getAsBoolean(TCP_REUSE_ADDRESS, NetworkUtils.defaultReuseAddress())); this.tcpSendBufferSize = componentSettings.getAsBytesSize("tcp_send_buffer_size", settings.getAsBytesSize(TCP_SEND_BUFFER_SIZE, TCP_DEFAULT_SEND_BUFFER_SIZE)); this.tcpReceiveBufferSize = componentSettings.getAsBytesSize("tcp_receive_buffer_size", settings.getAsBytesSize(TCP_RECEIVE_BUFFER_SIZE, TCP_DEFAULT_RECEIVE_BUFFER_SIZE)); this.compression = settings.getAsBoolean("http.compression", false); this.compressionLevel = settings.getAsInt("http.compression_level", 6); // validate max content length if (maxContentLength.bytes() > Integer.MAX_VALUE) { logger.warn("maxContentLength[" + maxContentLength + "] set to high value, resetting it to [100mb]"); maxContentLength = new ByteSizeValue(100, ByteSizeUnit.MB); } this.maxContentLength = maxContentLength; logger.debug("using max_chunk_size[{}], max_header_size[{}], max_initial_line_length[{}], max_content_length[{}]", maxChunkSize, maxHeaderSize, maxInitialLineLength, this.maxContentLength); } public void httpServerAdapter(HttpServerAdapter httpServerAdapter) { this.httpServerAdapter = httpServerAdapter; } @Override protected void doStart() throws ElasticSearchException { this.serverOpenChannels = new OpenChannelsHandler(logger); if (blockingServer) { serverBootstrap = new ServerBootstrap(new OioServerSocketChannelFactory( Executors.newCachedThreadPool(daemonThreadFactory(settings, "http_server_boss")), Executors.newCachedThreadPool(daemonThreadFactory(settings, "http_server_worker")) )); } else { serverBootstrap = new ServerBootstrap(new NioServerSocketChannelFactory( Executors.newCachedThreadPool(daemonThreadFactory(settings, "http_server_boss")), Executors.newCachedThreadPool(daemonThreadFactory(settings, "http_server_worker")), workerCount)); } serverBootstrap.setPipelineFactory(new MyChannelPipelineFactory(this)); if (tcpNoDelay != null) { serverBootstrap.setOption("child.tcpNoDelay", tcpNoDelay); } if (tcpKeepAlive != null) { serverBootstrap.setOption("child.keepAlive", tcpKeepAlive); } if (tcpSendBufferSize != null) { serverBootstrap.setOption("child.sendBufferSize", tcpSendBufferSize.bytes()); } if (tcpReceiveBufferSize != null) { serverBootstrap.setOption("child.receiveBufferSize", tcpReceiveBufferSize.bytes()); } if (reuseAddress != null) { serverBootstrap.setOption("reuseAddress", reuseAddress); serverBootstrap.setOption("child.reuseAddress", reuseAddress); } // Bind and start to accept incoming connections. InetAddress hostAddressX; try { hostAddressX = networkService.resolveBindHostAddress(bindHost); } catch (IOException e) { throw new BindHttpException("Failed to resolve host [" + bindHost + "]", e); } final InetAddress hostAddress = hostAddressX; PortsRange portsRange = new PortsRange(port); final AtomicReference<Exception> lastException = new AtomicReference<Exception>(); boolean success = portsRange.iterate(new PortsRange.PortCallback() { @Override public boolean onPortNumber(int portNumber) { try { serverChannel = serverBootstrap.bind(new InetSocketAddress(hostAddress, portNumber)); } catch (Exception e) { lastException.set(e); return false; } return true; } }); if (!success) { throw new BindHttpException("Failed to bind to [" + port + "]", lastException.get()); } InetSocketAddress boundAddress = (InetSocketAddress) serverChannel.getLocalAddress(); InetSocketAddress publishAddress; try { publishAddress = new InetSocketAddress(networkService.resolvePublishHostAddress(publishHost), boundAddress.getPort()); } catch (Exception e) { throw new BindTransportException("Failed to resolve publish address", e); } this.boundAddress = new BoundTransportAddress(new InetSocketTransportAddress(boundAddress), new InetSocketTransportAddress(publishAddress)); } @Override protected void doStop() throws ElasticSearchException { if (serverChannel != null) { serverChannel.close().awaitUninterruptibly(); serverChannel = null; } if (serverOpenChannels != null) { serverOpenChannels.close(); serverOpenChannels = null; } if (serverBootstrap != null) { serverBootstrap.releaseExternalResources(); serverBootstrap = null; } } @Override protected void doClose() throws ElasticSearchException { } public BoundTransportAddress boundAddress() { return this.boundAddress; } @Override public HttpStats stats() { OpenChannelsHandler channels = serverOpenChannels; return new HttpStats(channels == null ? 0 : channels.numberOfOpenChannels(), channels == null ? 0 : channels.totalChannels()); } void dispatchRequest(HttpRequest request, HttpChannel channel) { httpServerAdapter.dispatchRequest(request, channel); } void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { if (e.getCause() instanceof ReadTimeoutException) { if (logger.isTraceEnabled()) { logger.trace("Connection timeout [{}]", ctx.getChannel().getRemoteAddress()); } ctx.getChannel().close(); } else { if (!lifecycle.started()) { // ignore return; } if (!NetworkExceptionHelper.isCloseConnectionException(e.getCause())) { logger.warn("Caught exception while handling client http traffic, closing connection {}", e.getCause(), ctx.getChannel()); ctx.getChannel().close(); } else { logger.debug("Caught exception while handling client http traffic, closing connection {}", e.getCause(), ctx.getChannel()); ctx.getChannel().close(); } } } static class MyChannelPipelineFactory implements ChannelPipelineFactory { private final NettyHttpServerTransport transport; private final HttpRequestHandler requestHandler; MyChannelPipelineFactory(NettyHttpServerTransport transport) { this.transport = transport; this.requestHandler = new HttpRequestHandler(transport); } @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("openChannels", transport.serverOpenChannels); pipeline.addLast("decoder", new HttpRequestDecoder( (int) transport.maxInitialLineLength.bytes(), (int) transport.maxHeaderSize.bytes(), (int) transport.maxChunkSize.bytes() )); if (transport.compression) { pipeline.addLast("decoder_compress", new HttpContentDecompressor()); } pipeline.addLast("aggregator", new HttpChunkAggregator((int) transport.maxContentLength.bytes())); pipeline.addLast("encoder", new HttpResponseEncoder()); if (transport.compression) { pipeline.addLast("encoder_compress", new HttpContentCompressor(transport.compressionLevel)); } pipeline.addLast("handler", requestHandler); return pipeline; } } }
apache-2.0
tchellomello/home-assistant
homeassistant/components/ping/binary_sensor.py
8032
"""Tracks the latency of a host by sending ICMP echo requests (ping).""" import asyncio from datetime import timedelta from functools import partial import logging import re import sys from typing import Any, Dict from icmplib import SocketPermissionError, ping as icmp_ping import voluptuous as vol from homeassistant.components.binary_sensor import ( DEVICE_CLASS_CONNECTIVITY, PLATFORM_SCHEMA, BinarySensorEntity, ) from homeassistant.const import CONF_HOST, CONF_NAME import homeassistant.helpers.config_validation as cv from homeassistant.helpers.reload import setup_reload_service from . import DOMAIN, PLATFORMS, async_get_next_ping_id from .const import PING_TIMEOUT _LOGGER = logging.getLogger(__name__) ATTR_ROUND_TRIP_TIME_AVG = "round_trip_time_avg" ATTR_ROUND_TRIP_TIME_MAX = "round_trip_time_max" ATTR_ROUND_TRIP_TIME_MDEV = "round_trip_time_mdev" ATTR_ROUND_TRIP_TIME_MIN = "round_trip_time_min" CONF_PING_COUNT = "count" DEFAULT_NAME = "Ping" DEFAULT_PING_COUNT = 5 SCAN_INTERVAL = timedelta(minutes=5) PARALLEL_UPDATES = 0 PING_MATCHER = re.compile( r"(?P<min>\d+.\d+)\/(?P<avg>\d+.\d+)\/(?P<max>\d+.\d+)\/(?P<mdev>\d+.\d+)" ) PING_MATCHER_BUSYBOX = re.compile( r"(?P<min>\d+.\d+)\/(?P<avg>\d+.\d+)\/(?P<max>\d+.\d+)" ) WIN32_PING_MATCHER = re.compile(r"(?P<min>\d+)ms.+(?P<max>\d+)ms.+(?P<avg>\d+)ms") PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_NAME): cv.string, vol.Optional(CONF_PING_COUNT, default=DEFAULT_PING_COUNT): vol.Range( min=1, max=100 ), } ) def setup_platform(hass, config, add_entities, discovery_info=None) -> None: """Set up the Ping Binary sensor.""" setup_reload_service(hass, DOMAIN, PLATFORMS) host = config[CONF_HOST] count = config[CONF_PING_COUNT] name = config.get(CONF_NAME, f"{DEFAULT_NAME} {host}") try: # Verify we can create a raw socket, or # fallback to using a subprocess icmp_ping("127.0.0.1", count=0, timeout=0) ping_cls = PingDataICMPLib except SocketPermissionError: ping_cls = PingDataSubProcess ping_data = ping_cls(hass, host, count) add_entities([PingBinarySensor(name, ping_data)], True) class PingBinarySensor(BinarySensorEntity): """Representation of a Ping Binary sensor.""" def __init__(self, name: str, ping) -> None: """Initialize the Ping Binary sensor.""" self._name = name self._ping = ping @property def name(self) -> str: """Return the name of the device.""" return self._name @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_CONNECTIVITY @property def is_on(self) -> bool: """Return true if the binary sensor is on.""" return self._ping.available @property def device_state_attributes(self) -> Dict[str, Any]: """Return the state attributes of the ICMP checo request.""" if self._ping.data is not False: return { ATTR_ROUND_TRIP_TIME_AVG: self._ping.data["avg"], ATTR_ROUND_TRIP_TIME_MAX: self._ping.data["max"], ATTR_ROUND_TRIP_TIME_MDEV: self._ping.data["mdev"], ATTR_ROUND_TRIP_TIME_MIN: self._ping.data["min"], } async def async_update(self) -> None: """Get the latest data.""" await self._ping.async_update() class PingData: """The base class for handling the data retrieval.""" def __init__(self, hass, host, count) -> None: """Initialize the data object.""" self.hass = hass self._ip_address = host self._count = count self.data = {} self.available = False class PingDataICMPLib(PingData): """The Class for handling the data retrieval using icmplib.""" async def async_update(self) -> None: """Retrieve the latest details from the host.""" _LOGGER.debug("ping address: %s", self._ip_address) data = await self.hass.async_add_executor_job( partial( icmp_ping, self._ip_address, count=self._count, id=async_get_next_ping_id(self.hass), ) ) self.available = data.is_alive if not self.available: self.data = False return self.data = { "min": data.min_rtt, "max": data.max_rtt, "avg": data.avg_rtt, "mdev": "", } class PingDataSubProcess(PingData): """The Class for handling the data retrieval using the ping binary.""" def __init__(self, hass, host, count) -> None: """Initialize the data object.""" super().__init__(hass, host, count) if sys.platform == "win32": self._ping_cmd = [ "ping", "-n", str(self._count), "-w", "1000", self._ip_address, ] else: self._ping_cmd = [ "ping", "-n", "-q", "-c", str(self._count), "-W1", self._ip_address, ] async def async_ping(self): """Send ICMP echo request and return details if success.""" pinger = await asyncio.create_subprocess_exec( *self._ping_cmd, stdin=None, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) try: out_data, out_error = await asyncio.wait_for( pinger.communicate(), self._count + PING_TIMEOUT ) if out_data: _LOGGER.debug( "Output of command: `%s`, return code: %s:\n%s", " ".join(self._ping_cmd), pinger.returncode, out_data, ) if out_error: _LOGGER.debug( "Error of command: `%s`, return code: %s:\n%s", " ".join(self._ping_cmd), pinger.returncode, out_error, ) if pinger.returncode > 1: # returncode of 1 means the host is unreachable _LOGGER.exception( "Error running command: `%s`, return code: %s", " ".join(self._ping_cmd), pinger.returncode, ) if sys.platform == "win32": match = WIN32_PING_MATCHER.search(str(out_data).split("\n")[-1]) rtt_min, rtt_avg, rtt_max = match.groups() return {"min": rtt_min, "avg": rtt_avg, "max": rtt_max, "mdev": ""} if "max/" not in str(out_data): match = PING_MATCHER_BUSYBOX.search(str(out_data).split("\n")[-1]) rtt_min, rtt_avg, rtt_max = match.groups() return {"min": rtt_min, "avg": rtt_avg, "max": rtt_max, "mdev": ""} match = PING_MATCHER.search(str(out_data).split("\n")[-1]) rtt_min, rtt_avg, rtt_max, rtt_mdev = match.groups() return {"min": rtt_min, "avg": rtt_avg, "max": rtt_max, "mdev": rtt_mdev} except asyncio.TimeoutError: _LOGGER.exception( "Timed out running command: `%s`, after: %ss", self._ping_cmd, self._count + PING_TIMEOUT, ) if pinger: try: await pinger.kill() except TypeError: pass del pinger return False except AttributeError: return False async def async_update(self) -> None: """Retrieve the latest details from the host.""" self.data = await self.async_ping() self.available = bool(self.data)
apache-2.0
wallee-payment/wallee-php-sdk
lib/Service/TokenVersionService.php
17041
<?php /** * wallee SDK * * This library allows to interact with the wallee payment service. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 Wallee\Sdk\Service; use Wallee\Sdk\ApiClient; use Wallee\Sdk\ApiException; use Wallee\Sdk\ApiResponse; use Wallee\Sdk\Http\HttpRequest; use Wallee\Sdk\ObjectSerializer; /** * TokenVersionService service * * @category Class * @package Wallee\Sdk * @author customweb GmbH * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 */ class TokenVersionService { /** * The API client instance. * * @var ApiClient */ private $apiClient; /** * Constructor. * * @param ApiClient $apiClient the api client */ public function __construct(ApiClient $apiClient) { if (is_null($apiClient)) { throw new \InvalidArgumentException('The api client is required.'); } $this->apiClient = $apiClient; } /** * Returns the API client instance. * * @return ApiClient */ public function getApiClient() { return $this->apiClient; } /** * Operation activeVersion * * Active Version * * @param int $space_id (required) * @param int $id The id of a token for which you want to look up the current active token version. (required) * @throws \Wallee\Sdk\ApiException * @throws \Wallee\Sdk\VersioningException * @throws \Wallee\Sdk\Http\ConnectionException * @return \Wallee\Sdk\Model\TokenVersion */ public function activeVersion($space_id, $id) { return $this->activeVersionWithHttpInfo($space_id, $id)->getData(); } /** * Operation activeVersionWithHttpInfo * * Active Version * * @param int $space_id (required) * @param int $id The id of a token for which you want to look up the current active token version. (required) * @throws \Wallee\Sdk\ApiException * @throws \Wallee\Sdk\VersioningException * @throws \Wallee\Sdk\Http\ConnectionException * @return ApiResponse */ public function activeVersionWithHttpInfo($space_id, $id) { // verify the required parameter 'space_id' is set if (is_null($space_id)) { throw new \InvalidArgumentException('Missing the required parameter $space_id when calling activeVersion'); } // verify the required parameter 'id' is set if (is_null($id)) { throw new \InvalidArgumentException('Missing the required parameter $id when calling activeVersion'); } // header params $headerParams = []; $headerAccept = $this->apiClient->selectHeaderAccept(['application/json;charset=utf-8']); if (!is_null($headerAccept)) { $headerParams[HttpRequest::HEADER_KEY_ACCEPT] = $headerAccept; } $headerParams[HttpRequest::HEADER_KEY_CONTENT_TYPE] = $this->apiClient->selectHeaderContentType(['*/*']); // query params $queryParams = []; if (!is_null($space_id)) { $queryParams['spaceId'] = $this->apiClient->getSerializer()->toQueryValue($space_id); } if (!is_null($id)) { $queryParams['id'] = $this->apiClient->getSerializer()->toQueryValue($id); } // path params $resourcePath = '/token-version/active-version'; // default format to json $resourcePath = str_replace('{format}', 'json', $resourcePath); // form params $formParams = []; // for model (json/xml) $httpBody = ''; if (isset($tempBody)) { $httpBody = $tempBody; // $tempBody is the method argument, if present } elseif (!empty($formParams)) { $httpBody = $formParams; // for HTTP post (form) } // make the API Call try { $this->apiClient->setConnectionTimeout(ApiClient::CONNECTION_TIMEOUT); $response = $this->apiClient->callApi( $resourcePath, 'GET', $queryParams, $httpBody, $headerParams, '\Wallee\Sdk\Model\TokenVersion', '/token-version/active-version' ); return new ApiResponse($response->getStatusCode(), $response->getHeaders(), $this->apiClient->getSerializer()->deserialize($response->getData(), '\Wallee\Sdk\Model\TokenVersion', $response->getHeaders())); } catch (ApiException $e) { switch ($e->getCode()) { case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), '\Wallee\Sdk\Model\TokenVersion', $e->getResponseHeaders() ); $e->setResponseObject($data); break; case 442: $data = ObjectSerializer::deserialize( $e->getResponseBody(), '\Wallee\Sdk\Model\ClientError', $e->getResponseHeaders() ); $e->setResponseObject($data); break; case 542: $data = ObjectSerializer::deserialize( $e->getResponseBody(), '\Wallee\Sdk\Model\ServerError', $e->getResponseHeaders() ); $e->setResponseObject($data); break; } throw $e; } } /** * Operation count * * Count * * @param int $space_id (required) * @param \Wallee\Sdk\Model\EntityQueryFilter $filter The filter which restricts the entities which are used to calculate the count. (optional) * @throws \Wallee\Sdk\ApiException * @throws \Wallee\Sdk\VersioningException * @throws \Wallee\Sdk\Http\ConnectionException * @return int */ public function count($space_id, $filter = null) { return $this->countWithHttpInfo($space_id, $filter)->getData(); } /** * Operation countWithHttpInfo * * Count * * @param int $space_id (required) * @param \Wallee\Sdk\Model\EntityQueryFilter $filter The filter which restricts the entities which are used to calculate the count. (optional) * @throws \Wallee\Sdk\ApiException * @throws \Wallee\Sdk\VersioningException * @throws \Wallee\Sdk\Http\ConnectionException * @return ApiResponse */ public function countWithHttpInfo($space_id, $filter = null) { // verify the required parameter 'space_id' is set if (is_null($space_id)) { throw new \InvalidArgumentException('Missing the required parameter $space_id when calling count'); } // header params $headerParams = []; $headerAccept = $this->apiClient->selectHeaderAccept(['application/json;charset=utf-8']); if (!is_null($headerAccept)) { $headerParams[HttpRequest::HEADER_KEY_ACCEPT] = $headerAccept; } $headerParams[HttpRequest::HEADER_KEY_CONTENT_TYPE] = $this->apiClient->selectHeaderContentType(['application/json;charset=utf-8']); // query params $queryParams = []; if (!is_null($space_id)) { $queryParams['spaceId'] = $this->apiClient->getSerializer()->toQueryValue($space_id); } // path params $resourcePath = '/token-version/count'; // default format to json $resourcePath = str_replace('{format}', 'json', $resourcePath); // form params $formParams = []; // body params $tempBody = null; if (isset($filter)) { $tempBody = $filter; } // for model (json/xml) $httpBody = ''; if (isset($tempBody)) { $httpBody = $tempBody; // $tempBody is the method argument, if present } elseif (!empty($formParams)) { $httpBody = $formParams; // for HTTP post (form) } // make the API Call try { $this->apiClient->setConnectionTimeout(ApiClient::CONNECTION_TIMEOUT); $response = $this->apiClient->callApi( $resourcePath, 'POST', $queryParams, $httpBody, $headerParams, 'int', '/token-version/count' ); return new ApiResponse($response->getStatusCode(), $response->getHeaders(), $this->apiClient->getSerializer()->deserialize($response->getData(), 'int', $response->getHeaders())); } catch (ApiException $e) { switch ($e->getCode()) { case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), 'int', $e->getResponseHeaders() ); $e->setResponseObject($data); break; case 442: $data = ObjectSerializer::deserialize( $e->getResponseBody(), '\Wallee\Sdk\Model\ClientError', $e->getResponseHeaders() ); $e->setResponseObject($data); break; case 542: $data = ObjectSerializer::deserialize( $e->getResponseBody(), '\Wallee\Sdk\Model\ServerError', $e->getResponseHeaders() ); $e->setResponseObject($data); break; } throw $e; } } /** * Operation read * * Read * * @param int $space_id (required) * @param int $id The id of the token version which should be returned. (required) * @throws \Wallee\Sdk\ApiException * @throws \Wallee\Sdk\VersioningException * @throws \Wallee\Sdk\Http\ConnectionException * @return \Wallee\Sdk\Model\TokenVersion */ public function read($space_id, $id) { return $this->readWithHttpInfo($space_id, $id)->getData(); } /** * Operation readWithHttpInfo * * Read * * @param int $space_id (required) * @param int $id The id of the token version which should be returned. (required) * @throws \Wallee\Sdk\ApiException * @throws \Wallee\Sdk\VersioningException * @throws \Wallee\Sdk\Http\ConnectionException * @return ApiResponse */ public function readWithHttpInfo($space_id, $id) { // verify the required parameter 'space_id' is set if (is_null($space_id)) { throw new \InvalidArgumentException('Missing the required parameter $space_id when calling read'); } // verify the required parameter 'id' is set if (is_null($id)) { throw new \InvalidArgumentException('Missing the required parameter $id when calling read'); } // header params $headerParams = []; $headerAccept = $this->apiClient->selectHeaderAccept(['application/json;charset=utf-8']); if (!is_null($headerAccept)) { $headerParams[HttpRequest::HEADER_KEY_ACCEPT] = $headerAccept; } $headerParams[HttpRequest::HEADER_KEY_CONTENT_TYPE] = $this->apiClient->selectHeaderContentType(['*/*']); // query params $queryParams = []; if (!is_null($space_id)) { $queryParams['spaceId'] = $this->apiClient->getSerializer()->toQueryValue($space_id); } if (!is_null($id)) { $queryParams['id'] = $this->apiClient->getSerializer()->toQueryValue($id); } // path params $resourcePath = '/token-version/read'; // default format to json $resourcePath = str_replace('{format}', 'json', $resourcePath); // form params $formParams = []; // for model (json/xml) $httpBody = ''; if (isset($tempBody)) { $httpBody = $tempBody; // $tempBody is the method argument, if present } elseif (!empty($formParams)) { $httpBody = $formParams; // for HTTP post (form) } // make the API Call try { $this->apiClient->setConnectionTimeout(ApiClient::CONNECTION_TIMEOUT); $response = $this->apiClient->callApi( $resourcePath, 'GET', $queryParams, $httpBody, $headerParams, '\Wallee\Sdk\Model\TokenVersion', '/token-version/read' ); return new ApiResponse($response->getStatusCode(), $response->getHeaders(), $this->apiClient->getSerializer()->deserialize($response->getData(), '\Wallee\Sdk\Model\TokenVersion', $response->getHeaders())); } catch (ApiException $e) { switch ($e->getCode()) { case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), '\Wallee\Sdk\Model\TokenVersion', $e->getResponseHeaders() ); $e->setResponseObject($data); break; case 442: $data = ObjectSerializer::deserialize( $e->getResponseBody(), '\Wallee\Sdk\Model\ClientError', $e->getResponseHeaders() ); $e->setResponseObject($data); break; case 542: $data = ObjectSerializer::deserialize( $e->getResponseBody(), '\Wallee\Sdk\Model\ServerError', $e->getResponseHeaders() ); $e->setResponseObject($data); break; } throw $e; } } /** * Operation search * * Search * * @param int $space_id (required) * @param \Wallee\Sdk\Model\EntityQuery $query The query restricts the token versions which are returned by the search. (required) * @throws \Wallee\Sdk\ApiException * @throws \Wallee\Sdk\VersioningException * @throws \Wallee\Sdk\Http\ConnectionException * @return \Wallee\Sdk\Model\TokenVersion[] */ public function search($space_id, $query) { return $this->searchWithHttpInfo($space_id, $query)->getData(); } /** * Operation searchWithHttpInfo * * Search * * @param int $space_id (required) * @param \Wallee\Sdk\Model\EntityQuery $query The query restricts the token versions which are returned by the search. (required) * @throws \Wallee\Sdk\ApiException * @throws \Wallee\Sdk\VersioningException * @throws \Wallee\Sdk\Http\ConnectionException * @return ApiResponse */ public function searchWithHttpInfo($space_id, $query) { // verify the required parameter 'space_id' is set if (is_null($space_id)) { throw new \InvalidArgumentException('Missing the required parameter $space_id when calling search'); } // verify the required parameter 'query' is set if (is_null($query)) { throw new \InvalidArgumentException('Missing the required parameter $query when calling search'); } // header params $headerParams = []; $headerAccept = $this->apiClient->selectHeaderAccept(['application/json;charset=utf-8']); if (!is_null($headerAccept)) { $headerParams[HttpRequest::HEADER_KEY_ACCEPT] = $headerAccept; } $headerParams[HttpRequest::HEADER_KEY_CONTENT_TYPE] = $this->apiClient->selectHeaderContentType(['application/json;charset=utf-8']); // query params $queryParams = []; if (!is_null($space_id)) { $queryParams['spaceId'] = $this->apiClient->getSerializer()->toQueryValue($space_id); } // path params $resourcePath = '/token-version/search'; // default format to json $resourcePath = str_replace('{format}', 'json', $resourcePath); // form params $formParams = []; // body params $tempBody = null; if (isset($query)) { $tempBody = $query; } // for model (json/xml) $httpBody = ''; if (isset($tempBody)) { $httpBody = $tempBody; // $tempBody is the method argument, if present } elseif (!empty($formParams)) { $httpBody = $formParams; // for HTTP post (form) } // make the API Call try { $this->apiClient->setConnectionTimeout(ApiClient::CONNECTION_TIMEOUT); $response = $this->apiClient->callApi( $resourcePath, 'POST', $queryParams, $httpBody, $headerParams, '\Wallee\Sdk\Model\TokenVersion[]', '/token-version/search' ); return new ApiResponse($response->getStatusCode(), $response->getHeaders(), $this->apiClient->getSerializer()->deserialize($response->getData(), '\Wallee\Sdk\Model\TokenVersion[]', $response->getHeaders())); } catch (ApiException $e) { switch ($e->getCode()) { case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), '\Wallee\Sdk\Model\TokenVersion[]', $e->getResponseHeaders() ); $e->setResponseObject($data); break; case 442: $data = ObjectSerializer::deserialize( $e->getResponseBody(), '\Wallee\Sdk\Model\ClientError', $e->getResponseHeaders() ); $e->setResponseObject($data); break; case 542: $data = ObjectSerializer::deserialize( $e->getResponseBody(), '\Wallee\Sdk\Model\ServerError', $e->getResponseHeaders() ); $e->setResponseObject($data); break; } throw $e; } } }
apache-2.0
rishipatel/ariatemplates
src/aria/widgets/action/SortIndicator.js
13860
/* * Copyright 2012 Amadeus s.a.s. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Sort Indicator widget * @class aria.widgets.action.SortIndicator * @extends aria.widgets.action.ActionWidget */ Aria.classDefinition({ $classpath : "aria.widgets.action.SortIndicator", $extends : "aria.widgets.action.ActionWidget", $dependencies : ["aria.widgets.container.Div", "aria.widgets.Icon", "aria.utils.Ellipsis", "aria.utils.Dom", "aria.DomEvent", "aria.utils.String", "aria.utils.Type"], $css : ["aria.widgets.action.SortIndicatorStyle"], /** * SortIndicator constructor * @param {aria.widgets.CfgBeans.SortIndicatorCfg} cfg the widget configuration * @param {aria.templates.TemplateCtxt} ctxt template context * @param {Number} lineNumber Line number corresponding in the .tpl file where the widget is created */ $constructor : function (cfg, ctxt, lineNumber) { this.$ActionWidget.constructor.apply(this, arguments); this._setSkinObj("SortIndicator"); this._setInputType(); this._setIconPrefix(); /** * Internal widget state [normal, disabled, ...] * @type String * @protected * @override */ this._state = this._setState(cfg); /** * Instance of the Icon widget used by this widget. * @type aria.widgets.Icon * @protected */ this._icon = new aria.widgets.Icon({ icon : this._getIconName(this._state) }, ctxt, lineNumber); if (aria.utils.Type.isString(cfg.ellipsis)) { /** * Activate ellipsis ot not * @type Boolean * @protected */ this._activateEllipsis = true; /** * Flag for widget that get initialized right after being displayed. * @type Boolean * @protected */ this._directInit = true; } // #04464481 this was done in the init by modifying the style property ofthe DOM element // can be done here instead, and directly inserted in the generated markup var width = this._cfg.width; /** * Styling information for the containing span * @protected * @type String */ this._spanStyle = [(width > 0) ? "width:" + width + "px;" : "", "display:inline-block;", "white-space:nowrap;"].join(""); /** * Moment in which the widget gets initialized * @type Date */ this.loadTime = null; }, $destructor : function () { this._icon.$dispose(); this.textContent = null; if (this._ellipsis) { this._ellipsis.$dispose(); this._ellipsis = null; } this.loadTime = null; this._hasMouseOver = null; this._hasFocus = null; this._state = null; this.$ActionWidget.$destructor.call(this); }, $statics : { /** * Ascending and descending are used to refer to the icon image sprite * @type {String} */ ASCENDING_STATE : 'ascending', DESCENDING_STATE : 'descending', NORMAL_STATE : "normal" }, $prototype : { /** * Activate ellipsis ot not * @private * @type Boolean */ _activateEllipsis : false, /** * Status flag to check if the widget currently has mouseover * @private * @type Boolean */ _hasMouseOver : false, /** * Status flag to check if the widget currently has the focus * @private * @type Boolean */ _hasFocus : false, /** * Tells if the widgets is using a tabindex (for tab navigation). * @private * @type Boolean */ _customTabIndexProvided : true, /** * Called when a new instance is initialized * @param {HTMLElement} actingDom Element on which actions happen * @protected */ _initActionWidget : function (actingDom) { this.loadTime = new Date(); if (actingDom) { this._actingDom = actingDom; var domElt = this.getDom(); this._initializeFocusableElement(); if (this._activateEllipsis) { this._initializeEllipsis(); } } }, /** * Called when a new instance is created if an ellipsis is needed on this SortIndicator instance * @protected */ _initializeEllipsis : function () { var cfg = this._cfg; var anchorElement = aria.utils.Dom.getDomElementChild(this.getDom(), 0); var ellipseElement = Aria.$window.document.createElement("span"); ellipseElement.innerHTML = aria.utils.String.escapeHTML(cfg.label); this.textContent = cfg.label; if (ellipseElement.innerHTML) { anchorElement.insertBefore(ellipseElement, anchorElement.firstChild); } var labelWidth = cfg.labelWidth; if (labelWidth > 0) { this._ellipsis = new aria.utils.Ellipsis(ellipseElement, labelWidth, cfg.ellipsisLocation, cfg.ellipsis, this._context); } if (ellipseElement.innerHTML) { anchorElement.removeChild(anchorElement.childNodes[1]); } }, /** * Called when a new instance is created if there is a dom element that receives actions and thus focus * @protected */ _initializeFocusableElement : function () { this._focusElt = this._actingDom; }, /** * Internal function to override to generate the internal widget markup * @param {aria.templates.MarkupWriter} out Markup writer * @protected */ _widgetMarkup : function (out) { var cfg = this._cfg; var tabString = (cfg.tabIndex != null ? ' tabindex="' + this._calculateTabIndex() + '" ' : ' '); out.write(['<a', Aria.testMode ? ' id="' + this._domId + '_link"' : '', ' class="sortIndicatorLink" href="#"' + tabString + '>' + aria.utils.String.escapeHTML(cfg.label)].join("")); this._icon.writeMarkup(out); out.write('</a>'); }, /** * Internal method to set the initial _state property from the _cfg description based on the config properties * @protected * @param {Object} cfg Config properties * @return {String} new state */ _setState : function (cfg) { if (cfg.view.sortName == cfg.sortName) { if (cfg.view.sortOrder == 'A') { return this.ASCENDING_STATE; } else if (cfg.view.sortOrder == 'D') { return this.DESCENDING_STATE; } } else { return this.NORMAL_STATE; } }, /** * Internal method to sort the list * @protected */ _sortList : function () { this._cfg.view.toggleSortOrder(this._cfg.sortName, this._cfg.sortKeyGetter); this._cfg.view.refresh(); this._state = this._setState(this._cfg); this._icon.changeIcon(this._getIconName(this._state)); }, /** * A private method to set this objects skin object * @param {String} widgetName Name of the widget * @protected */ _setSkinObj : function (widgetName) { this._skinObj = aria.widgets.AriaSkinInterface.getSkinObject(widgetName, this._cfg.sclass); }, /** * Protected method to get the icon name based on the _cfg description * @param {String} state widget state * @return {String} Icon name * @protected */ _getIconName : function (state) { var cfg = this._cfg; return cfg._iconSet + ":" + cfg._iconPrefix + state; }, /** * Internal method to set the _inputType property from the _cfg description * @protected */ _setInputType : function () { this._cfg._inputType = "sortindicator"; }, /** * Internal method to set the _iconPrefix property from the _cfg description * @protected */ _setIconPrefix : function () { this._cfg._iconSet = this._skinObj.iconset; this._cfg._iconPrefix = this._skinObj.iconprefix; }, /** * Perform a partial refresh of some sections * @param {Array} Array of $refresh configuration Objects, aria.templates.CfgBeans.RefreshCfg * @protected */ _doPartialRefresh : function (refreshArgs) { var i = refreshArgs.length; while (i--) { this._context.$refresh(refreshArgs[i]); } }, /** * Internal method to handle the mouse over event * @protected * @param {aria.DomEvent} domEvt Mouse over event */ _dom_onmouseover : function (domEvt) { this.$ActionWidget._dom_onmouseover.call(this, domEvt); if (this._ellipsis) { var mouseOverTime = new Date(); /* * James says: When they click on the full text of the ellipses, the refresh removes the full text, but * then the mouseover is raised which puts the full text back in the way again. This makes sure that a * time has passed from initialisation before displaying it. */ var timeDifference = mouseOverTime.getTime() - this.loadTime.getTime(); if (timeDifference > 200) { this._hasMouseOver = true; var offset; if (aria.core.Browser.isFirefox) { offset = { left : 1, top : 2 }; } else if (aria.core.Browser.isIE8) { offset = { left : 0, top : 1 }; } else { offset = { left : 1, top : 1 }; } if (this._ellipsis) { this._ellipsis.displayFullText(offset); } } } }, /** * The method called when the mouse leaves the widget * @param {aria.DomEvent} domEvt Mouse out event * @protected */ _dom_onmouseout : function (domEvt) { this.$ActionWidget._dom_onmouseout.call(this, domEvt); if (this._ellipsis) { if (this._hasFocus === false && this._hasMouseOver === true) { this._hasMouseOver = false; if (this._ellipsis) { this._ellipsis._hideFullText(domEvt.relatedTarget); } } } }, /** * The method called when the widget gets focus * @param {aria.DomEvent} domEvt Focus event * @protected */ _dom_onfocus : function (domEvt) { if (this._actingDom && this._hasMouseOver === false) { this._hasFocus = true; var offset; if (aria.core.Browser.isFirefox) { offset = { left : 1, top : 2 }; } else { offset = { left : 1, top : 1 }; } if (this._ellipsis) { this._ellipsis.displayFullText(offset); } } }, /** * The method called when focus leaves the widget * @param {aria.DomEvent} domEvt Blur event * @protected */ _dom_onblur : function (domEvt) { if (this._hasMouseOver === false && this._hasFocus === true) { this._hasFocus = false; if (this._ellipsis) { this._ellipsis._hideFullText(domEvt.relatedTarget); } } }, /** * The method called when the markup of the widget is clicked * @param {aria.DomEvent} domEvt Click event * @protected */ _dom_onclick : function (domEvt) { this._sortList(); // handle an onclick event this.$ActionWidget._dom_onclick.apply(this, arguments); if (this._cfg.refreshArgs) { this._doPartialRefresh(this._cfg.refreshArgs); } else { this._context.$refresh(); } domEvt.preventDefault(); return false; } } });
apache-2.0
Bersh/AndroidSPP
app/src/main/java/com/example/androidspp/prasers/truepulse/TruePulseHTCommand.java
322
package com.example.androidspp.prasers.truepulse; import java.io.UnsupportedEncodingException; public class TruePulseHTCommand extends TruePulseHVCommand{ public TruePulseHTCommand(byte[][] data) throws UnsupportedEncodingException { super(data); } public double getHeight(){ return horizontalDistance; } }
apache-2.0
eic-cefet-rj/sagitarii-teapot
src/main/java/cmabreu/sagitarii/teapot/TaskRunner.java
3750
package cmabreu.sagitarii.teapot; /** * Copyright 2015 Carlos Magno Abreu * magno.mabreu@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. * */ import java.net.URLEncoder; import java.util.Calendar; import java.util.List; import java.util.UUID; import java.util.concurrent.TimeUnit; import cmabreu.sagitarii.teapot.comm.Communicator; public class TaskRunner extends Thread { private TaskManager teapot; private Logger logger = LogManager.getLogger( this.getClass().getName() ); private String serial; private String response; private boolean active = true; private String startTime; private long startTimeMillis; private Communicator communicator; private Configurator configurator; public String getStartTime() { return startTime; } public boolean isActive() { return active; } public String getSerial() { return serial; } public List<Activation> getJobPool() { return teapot.getJobPool(); } public Task getCurrentTask() { return teapot.getCurrentTask(); } public Activation getCurrentActivation() { return teapot.getCurrentActivation(); } public void notifySagitarii( String message ) { message = "[TASKRUNNER] " + message; try { String parameters = "macAddress=" + configurator.getSystemProperties().getMacAddress() + "&errorLog=" + URLEncoder.encode( message, "UTF-8"); communicator.send("receiveErrorLog", parameters); } catch ( Exception e ) { logger.error("cannot notify Sagitarii: " + e.getMessage() ); } } public TaskRunner( String response, Communicator communicator, Configurator configurator ) { this.communicator = communicator; this.configurator = configurator; this.teapot = new TaskManager( communicator, configurator); this.serial = UUID.randomUUID().toString().substring(0, 5).toUpperCase(); this.response = response; setName("TaskManager Task Runner " + this.serial ); } public String getTime() { long millis = getTimeMillis(); String time = String.format("%03d %02d:%02d:%02d", TimeUnit.MILLISECONDS.toDays( millis ), TimeUnit.MILLISECONDS.toHours( millis ), TimeUnit.MILLISECONDS.toMinutes( millis ) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours( millis ) ), TimeUnit.MILLISECONDS.toSeconds( millis ) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes( millis ) ) ); return time; } public long getTimeMillis() { long estimatedTime = ( Calendar.getInstance().getTimeInMillis() - startTimeMillis ); return estimatedTime; } @Override public void run() { startTime = DateLibrary.getInstance().getHourTextHuman(); startTimeMillis = Calendar.getInstance().getTimeInMillis(); try { logger.debug("[" + serial + "] runner thread start"); notifySagitarii("thread " + serial + " started"); // Blocking call teapot.process( response ); notifySagitarii("thread " + serial + " finished"); logger.debug("[" + serial + "] runner thread end"); } catch ( Exception e ) { e.printStackTrace(); logger.error("[" + serial + "] " + e.getMessage() ); } active = false; } }
apache-2.0
sacloud/terraform-provider-sakuracloud
sakuracloud/resource_sakuracloud_sim.go
6729
// Copyright 2016-2022 terraform-provider-sakuracloud authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 sakuracloud import ( "context" "time" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/sacloud/libsacloud/v2/helper/cleanup" "github.com/sacloud/libsacloud/v2/helper/query" "github.com/sacloud/libsacloud/v2/sacloud" "github.com/sacloud/libsacloud/v2/sacloud/types" ) func resourceSakuraCloudSIM() *schema.Resource { resourceName := "SIM" return &schema.Resource{ CreateContext: resourceSakuraCloudSIMCreate, ReadContext: resourceSakuraCloudSIMRead, UpdateContext: resourceSakuraCloudSIMUpdate, DeleteContext: resourceSakuraCloudSIMDelete, Importer: &schema.ResourceImporter{ StateContext: schema.ImportStatePassthroughContext, }, Timeouts: &schema.ResourceTimeout{ Create: schema.DefaultTimeout(5 * time.Minute), Update: schema.DefaultTimeout(5 * time.Minute), Delete: schema.DefaultTimeout(5 * time.Minute), }, Schema: map[string]*schema.Schema{ "name": schemaResourceName(resourceName), "iccid": { Type: schema.TypeString, Required: true, ForceNew: true, Description: "ICCID(Integrated Circuit Card ID) assigned to the SIM", }, "passcode": { Type: schema.TypeString, Required: true, ForceNew: true, Sensitive: true, Description: "The passcord to authenticate the SIM", }, "imei": { Type: schema.TypeString, Optional: true, Description: "The id of the device to restrict devices that can use the SIM", }, "carrier": { Type: schema.TypeSet, Required: true, Elem: &schema.Schema{Type: schema.TypeString}, Set: schema.HashString, MinItems: 1, MaxItems: 3, Description: descf( "A list of a communication company. Each element must be one of %s", types.SIMOperatorShortNames(), ), }, "enabled": { Type: schema.TypeBool, Optional: true, Default: true, Description: "The flag to enable the SIM", }, "icon_id": schemaResourceIconID(resourceName), "description": schemaResourceDescription(resourceName), "tags": schemaResourceTags(resourceName), "mobile_gateway_id": { Type: schema.TypeString, Computed: true, Description: "The id of the MobileGateway which the SIM is assigned", }, "ip_address": { Type: schema.TypeString, Computed: true, Description: "The IP address assigned to the SIM", }, }, } } func resourceSakuraCloudSIMCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { client, _, err := sakuraCloudClient(d, meta) if err != nil { return diag.FromErr(err) } if err := validateCarrier(d); err != nil { return diag.FromErr(err) } builder := expandSIMBuilder(d, client) if err := builder.Validate(ctx); err != nil { return diag.Errorf("validating SakuraCloud SIM is failed: %s", err) } sim, err := builder.Build(ctx) if err != nil { return diag.Errorf("creating SakuraCloud SIM is failed: %s", err) } d.SetId(sim.ID.String()) return resourceSakuraCloudSIMRead(ctx, d, meta) } func resourceSakuraCloudSIMRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { client, _, err := sakuraCloudClient(d, meta) if err != nil { return diag.FromErr(err) } simOp := sacloud.NewSIMOp(client) sim, err := query.FindSIMByID(ctx, simOp, sakuraCloudID(d.Id())) if err != nil { if sacloud.IsNotFoundError(err) { d.SetId("") return nil } return diag.Errorf("could not read SakuraCloud SIM[%s]: %s", d.Id(), err) } return setSIMResourceData(ctx, d, client, sim) } func resourceSakuraCloudSIMUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { client, _, err := sakuraCloudClient(d, meta) if err != nil { return diag.FromErr(err) } simOp := sacloud.NewSIMOp(client) if err := validateCarrier(d); err != nil { return diag.FromErr(err) } sim, err := query.FindSIMByID(ctx, simOp, types.StringID(d.Id())) if err != nil { return diag.Errorf("could not read SakuraCloud SIM[%s]: %s", d.Id(), err) } builder := expandSIMBuilder(d, client) if err := builder.Validate(ctx); err != nil { return diag.Errorf("validating SakuraCloud SIM[%s] is failed: %s", d.Id(), err) } _, err = builder.Update(ctx, sim.ID) if err != nil { return diag.Errorf("updating SakuraCloud SIM[%s] is failed: %s", d.Id(), err) } return resourceSakuraCloudSIMRead(ctx, d, meta) } func resourceSakuraCloudSIMDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { client, _, err := sakuraCloudClient(d, meta) if err != nil { return diag.FromErr(err) } simOp := sacloud.NewSIMOp(client) // read sim info sim, err := query.FindSIMByID(ctx, simOp, sakuraCloudID(d.Id())) if err != nil { if sacloud.IsNotFoundError(err) { d.SetId("") return nil } return diag.Errorf("could not read SakuraCloud SIM[%s]: %s", d.Id(), err) } if err := cleanup.DeleteSIMWithReferencedCheck(ctx, client, client.zones, sim.ID, client.checkReferencedOption()); err != nil { return diag.Errorf("deleting SakuraCloud SIM[%s] is failed: %s", d.Id(), err) } d.SetId("") return nil } func setSIMResourceData(ctx context.Context, d *schema.ResourceData, client *APIClient, data *sacloud.SIM) diag.Diagnostics { simOp := sacloud.NewSIMOp(client) carrierInfo, err := simOp.GetNetworkOperator(ctx, data.ID) if err != nil { return diag.Errorf("reading SIM[%s] NetworkOperator is failed: %s", data.ID, err) } d.Set("name", data.Name) // nolint d.Set("icon_id", data.IconID.String()) // nolint d.Set("description", data.Description) // nolint d.Set("iccid", data.ICCID) // nolint if data.Info != nil { d.Set("ip_address", data.Info.IP) // nolint d.Set("mobile_gateway_id", data.Info.SIMGroupID) // nolint } if err := d.Set("carrier", flattenSIMCarrier(carrierInfo)); err != nil { return diag.FromErr(err) } return diag.FromErr(d.Set("tags", flattenTags(data.Tags))) }
apache-2.0
jzachr/goldenorb
src/test/java/org/goldenorb/zookeeper/TestWatchMemberData.java
1683
/** * */ package org.goldenorb.zookeeper; import static org.junit.Assert.*; import java.io.IOException; import java.util.List; import java.util.concurrent.CountDownLatch; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.ZooKeeper; import org.goldenorb.zookeeper.OrbZKFailure; import org.goldenorb.zookeeper.ZookeeperUtils; import org.junit.Test; public class TestWatchMemberData { private static ZooKeeper zk; private static String basePath = "/TestWatchMemberData"; private static TMember member = new TMember(); /** * */ @Test public void WatchMemberData() throws IOException, InterruptedException, OrbZKFailure, KeeperException { zk = ZookeeperUtils.connect("localhost:21810"); int data = 1; member.setData(data); ZookeeperUtils.tryToCreateNode(zk, basePath, CreateMode.PERSISTENT); CountDownLatch dataChangedCdl = new CountDownLatch(1); CountDownLatch startCdl = new CountDownLatch(1); CountDownLatch leaderChangeCdl = new CountDownLatch(1); CountDownLatch leaveCdl = new CountDownLatch(1); TTracker tt = new TTracker(zk, data, basePath, startCdl,leaderChangeCdl, leaveCdl, dataChangedCdl); tt.run(); startCdl.await(); int newData = 9999; tt.changeMemberData(newData); dataChangedCdl.await(); assertTrue(tt.getMemberData() == newData); tt.leave(); List<String> children = zk.getChildren(basePath, false); for(String node : children) { ZookeeperUtils.deleteNodeIfEmpty(zk, basePath+"/"+node); } ZookeeperUtils.deleteNodeIfEmpty(zk, basePath); } }
apache-2.0
DavidBate/taokeeper
taokeeper-monitor/src/main/java/com/taobao/taokeeper/monitor/core2/task/AlertTask.java
1458
package com.taobao.taokeeper.monitor.core2.task; import java.util.concurrent.ExecutorService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; //import com.taobao.jm.alert.AlertManager; //import com.taobao.jm.alert.DefaultAlertManager; import com.taobao.taokeeper.model.AlertInfo; /** * * @author pingwei 2014-3-25 下午1:19:22 */ public class AlertTask { static final Logger log = LoggerFactory.getLogger(AlertTask.class); // static final AlertManager alertManager = new DefaultAlertManager("taokeeper", "pingwei@0325"); // static{ // alertManager.init(); // } // public static void main(String[] args) { // System.out.println(alertManager.sendTbWWAlert("平威", "taokeeper报警", "daily test")); // } AlertInfo alert; ExecutorService pool; public AlertTask(ExecutorService pool, AlertInfo alert) { this.pool = pool; this.alert = alert; } public String taskDesc() { return ""; } public void work() { if(pool == null){ alert(); } else { pool.execute(new Runnable() { @Override public void run() { alert(); } }); } } private void alert(){ // if (alert == null) { // return; // } // for (String ww : alert.getWangwangAsList()) { // log.info(alertManager.sendTbWWAlert(ww, "taokeeper报警", alert.getContent()).toString()); // } // // for(String mobile : alert.getMobileAsList()){ // log.info(alertManager.sendSms(mobile, alert.getContent()).toString()); // } } }
apache-2.0
apavlo/peloton
test/codegen/bloom_filter_test.cpp
13670
//===----------------------------------------------------------------------===// // // Peloton // // bloom_filter_test.cpp // // Identification: test/codegen/bloom_filter_test.cpp // // Copyright (c) 2015-17, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <cstdlib> #include <unordered_set> #include <vector> #include "codegen/bloom_filter_accessor.h" #include "codegen/codegen.h" #include "codegen/counting_consumer.h" #include "codegen/function_builder.h" #include "codegen/lang/if.h" #include "codegen/lang/loop.h" #include "codegen/proxy/bloom_filter_proxy.h" #include "codegen/query_parameters.h" #include "codegen/testing_codegen_util.h" #include "codegen/util/bloom_filter.h" #include "common/timer.h" #include "concurrency/transaction_manager_factory.h" #include "executor/executor_context.h" #include "executor/plan_executor.h" #include "optimizer/optimizer.h" #include "planner/hash_join_plan.h" #include "planner/seq_scan_plan.h" #include "sql/testing_sql_util.h" namespace peloton { namespace test { class BloomFilterCodegenTest : public PelotonCodeGenTest { public: BloomFilterCodegenTest() { // Create test db auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(); auto txn = txn_manager.BeginTransaction(); catalog::Catalog::GetInstance()->CreateDatabase(DEFAULT_DB_NAME, txn); txn_manager.CommitTransaction(txn); } ~BloomFilterCodegenTest() { // Drop test db auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(); auto txn = txn_manager.BeginTransaction(); catalog::Catalog::GetInstance()->DropDatabaseWithName(DEFAULT_DB_NAME, txn); txn_manager.CommitTransaction(txn); } int UpDivide(int num1, int num2) { return (num1 + num2 - 1) / num2; } void InsertTuple(const std::vector<int> &vals, storage::DataTable *table, concurrency::TransactionContext *txn); void CreateTable(std::string table_name, int tuple_size, concurrency::TransactionContext *txn); double ExecuteJoin(std::string query, concurrency::TransactionContext *txn, int num_iter, unsigned inner_table_cardinality, bool enable_bloom_filter); const std::string table1_name = "test1"; const std::string table2_name = "test2"; }; TEST_F(BloomFilterCodegenTest, FalsePositiveRateTest) { codegen::CodeContext code_context; codegen::CodeGen codegen(code_context); // Generate an array of distinct random numbers. // Insert the first half into the bloom filter and // use the second half to test the false positive rate const int size = 100000; std::unordered_set<int> number_set; while (number_set.size() != size) { number_set.insert(rand()); } std::vector<int> numbers(number_set.begin(), number_set.end()); codegen::BloomFilterAccessor bloom_filter_accessor; // Build the test function that has the following logic: // define @TestBloomFilter(BloomFilter* bloom_filter, i32* numbers, i32 size, // i32* false_positive_cnt) { // // Insert the first half into the bloom filter // for (i32 i = 0; i < size / 2; i++) { // bloom_filter.Add(numbers[i]); // } // // Test the second half and measure false positive cnt // for (i32 i = size / 2; i < size; i++) { // if (bloom_filter.Contains) { // *false_positive_cnt ++; // } // } // } codegen::FunctionBuilder func{ code_context, "TestBloomFilter", codegen.VoidType(), {{"bloom_filter", codegen::BloomFilterProxy::GetType(codegen)->getPointerTo()}, {"numbers", codegen.Int32Type()->getPointerTo()}, {"size", codegen.Int32Type()}, {"false_positive_cnt", codegen.Int32Type()->getPointerTo()}}}; { llvm::Value *bloom_filter = func.GetArgumentByPosition(0); llvm::Value *number_array = func.GetArgumentByPosition(1); llvm::Value *size_val = func.GetArgumentByPosition(2); llvm::Value *false_positive_cnt = func.GetArgumentByPosition(3); llvm::Value *index = codegen.Const32(0); llvm::Value *half_size = codegen->CreateUDiv(size_val, codegen.Const32(2)); llvm::Value *finish_cond = codegen->CreateICmpULT(index, half_size); // Loop that inserts the first half of array into the bloom filter codegen::lang::Loop insert_loop{codegen, finish_cond, {{"i", index}}}; { index = insert_loop.GetLoopVar(0); // Get numbers[i] llvm::Value *number = codegen->CreateLoad( codegen->CreateInBoundsGEP(codegen.Int32Type(), number_array, index)); codegen::Value number_val{ codegen::type::Type(peloton::type::TypeId::INTEGER, false), number}; // Insert numbers[i] into bloom filter bloom_filter_accessor.Add(codegen, bloom_filter, {number_val}); index = codegen->CreateAdd(index, codegen.Const32(1)); insert_loop.LoopEnd(codegen->CreateICmpULT(index, half_size), {index}); } // Loop that test the false positive rate finish_cond = codegen->CreateICmpULT(half_size, size_val); codegen::lang::Loop test_loop{codegen, finish_cond, {{"i", half_size}}}; { index = test_loop.GetLoopVar(0); // Get numbers[i] llvm::Value *number = codegen->CreateLoad( codegen->CreateInBoundsGEP(codegen.Int32Type(), number_array, index)); codegen::Value number_val{ codegen::type::Type(peloton::type::TypeId::INTEGER, false), number}; // Test if numbers[i] is contained in bloom filter llvm::Value *contains = bloom_filter_accessor.Contains(codegen, bloom_filter, {number_val}); codegen::lang::If if_contains{codegen, contains}; { codegen->CreateStore( codegen->CreateAdd(codegen->CreateLoad(false_positive_cnt), codegen.Const32(1)), false_positive_cnt); } if_contains.EndIf(); index = codegen->CreateAdd(index, codegen.Const32(1)); test_loop.LoopEnd(codegen->CreateICmpULT(index, size_val), {index}); } func.ReturnAndFinish(); } ASSERT_TRUE(code_context.Compile()); typedef void (*ftype)(codegen::util::BloomFilter * bloom_filter, int *, int, int *); ftype f = (ftype)code_context.GetRawFunctionPointer(func.GetFunction()); codegen::util::BloomFilter bloom_filter; bloom_filter.Init(size / 2); int num_false_positive = 0; // Run the function f(&bloom_filter, &numbers[0], size, &num_false_positive); double actual_FPR = (double)num_false_positive / (size / 2); double expected_FPR = codegen::util::BloomFilter::kFalsePositiveRate; LOG_INFO("Expected FPR %f, Actula FPR: %f", expected_FPR, actual_FPR); // Difference should be within 10% EXPECT_LT(expected_FPR * 0.9, actual_FPR); EXPECT_LT(actual_FPR, expected_FPR * 1.1); bloom_filter.Destroy(); } // Testing whether bloom filter can improve the performance of hash join // when the hash table is bigger than L3 cache and selectivity is low TEST_F(BloomFilterCodegenTest, PerformanceTest) { auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(); auto *catalog = catalog::Catalog::GetInstance(); auto *txn = txn_manager.BeginTransaction(); // Initialize tables. test1 is the inner table from which we build the // hash table. test2 is the outer table which will probe the hash table. const int table1_tuple_size = 4096; const int table2_tuple_size = 8; const int bigint_size = 8; CreateTable(table1_name, table1_tuple_size, txn); CreateTable(table2_name, table2_tuple_size, txn); // Note: This should be changed to the size of L3 cache on the running machine const int L3_cache_size = 60000; const int table1_target_size = L3_cache_size * 10; const double selectivity = 0.2; const int outer_to_inner_ratio = 5; // Load the test1 until its size is bigger than a certain ratio of L3 cache. int curr_size = 0; std::vector<int> numbers; std::unordered_set<int> number_set; auto *table1 = catalog->GetTableWithName(DEFAULT_DB_NAME, DEFAULT_SCHEMA_NAME, table1_name, txn); while (curr_size < table1_target_size) { // Find a unique random number int random; do { random = rand(); } while (number_set.count(random) == 1); numbers.push_back(random); number_set.insert(random); // Insert tuple into the table std::vector<int> vals(UpDivide(table1_tuple_size, bigint_size), random); InsertTuple(vals, table1, txn); curr_size += table1_tuple_size; } LOG_INFO("Finish populating test1"); // Load the inner table which contains twice tuples as the outer table auto *table2 = catalog->GetTableWithName(DEFAULT_DB_NAME, DEFAULT_SCHEMA_NAME, table2_name, txn); unsigned outer_table_cardinality = numbers.size() * outer_to_inner_ratio; for (unsigned i = 0; i < outer_table_cardinality; i++) { int number; if (rand() % 100 < selectivity * 100) { // Pick a random number from the inner table number = numbers[rand() % numbers.size()]; } else { // Pick a random number that is not in inner table do { number = rand(); } while (number_set.count(number) == 1); } std::vector<int> vals(UpDivide(table2_tuple_size, bigint_size), number); InsertTuple(vals, table2, txn); } LOG_INFO("Finish populating test2\n"); // Build and execute the join plan int num_iter = 3; std::string query = "SELECT * FROM test1 as t1, test2 as t2 " "WHERE t1.c0 = t2.c0"; // Execute plan with bloom filter disabled LOG_INFO("Executing without bloom filter"); double runtime1 = ExecuteJoin(query, txn, num_iter, numbers.size(), false); // Execute plan with bloom filter enabled LOG_INFO("\n"); LOG_INFO("Executing with bloom filter"); double runtime2 = ExecuteJoin(query, txn, num_iter, numbers.size(), true); LOG_INFO("Avg With Bloom Filter Disabled: %f", runtime1); LOG_INFO("Avg With Bloom Filter Enabled: %f", runtime2); LOG_INFO("Ratio: %f", runtime2 / runtime1); txn_manager.CommitTransaction(txn); } double BloomFilterCodegenTest::ExecuteJoin(std::string query, concurrency::TransactionContext *txn, int num_iter, unsigned inner_table_cardinality, bool enable_bloom_filter) { std::unique_ptr<optimizer::AbstractOptimizer> optimizer( new optimizer::Optimizer()); double total_runtime = 0; // Run hash join multiple times and calculate the average runtime for (int i = 0; i < num_iter; i++) { auto plan = TestingSQLUtil::GeneratePlanWithOptimizer(optimizer, query, txn); assert(((planner::SeqScanPlan *)plan->GetChild(0))->GetTable()->GetName() == table1_name); // Change the bloom filter flag and set the correct cardinality in the plan const_cast<planner::AbstractPlan *>(plan->GetChild(0)) ->SetCardinality(inner_table_cardinality); dynamic_cast<planner::HashJoinPlan *>(plan.get()) ->SetBloomFilterFlag(enable_bloom_filter); // Binding planner::BindingContext context; plan->PerformBinding(context); executor::ExecutorContext executor_context{txn}; // Use simple CountConsumer since we don't care about the result codegen::CountingConsumer consumer; // Compile the query codegen::QueryCompiler compiler; codegen::Query::RuntimeStats stats; auto compiled_query = compiler.Compile( *plan, executor_context.GetParams().GetQueryParametersMap(), consumer); // Run compiled_query->Execute(executor_context, consumer, &stats); LOG_INFO("Execution Time: %0.0f ms", stats.plan_ms); total_runtime += stats.plan_ms; } return total_runtime / num_iter; } // Create a table where all the columns are BIGINT and each tuple has desired // tuple size void BloomFilterCodegenTest::CreateTable(std::string table_name, int tuple_size, concurrency::TransactionContext *txn) { int curr_size = 0; size_t bigint_size = type::Type::GetTypeSize(type::TypeId::BIGINT); std::vector<catalog::Column> cols; while (curr_size < tuple_size) { cols.push_back( catalog::Column{type::TypeId::BIGINT, bigint_size, "c" + std::to_string(curr_size / bigint_size), true}); curr_size += bigint_size; } auto *catalog = catalog::Catalog::GetInstance(); catalog->CreateTable( DEFAULT_DB_NAME, DEFAULT_SCHEMA_NAME, table_name, std::unique_ptr<catalog::Schema>(new catalog::Schema(cols)), txn); } // Insert a tuple to specific table void BloomFilterCodegenTest::InsertTuple(const std::vector<int> &vals, storage::DataTable *table, concurrency::TransactionContext *txn) { auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(); storage::Tuple tuple{table->GetSchema(), true}; for (unsigned i = 0; i < vals.size(); i++) { tuple.SetValue(i, type::ValueFactory::GetBigIntValue(vals[i])); } ItemPointer *index_entry_ptr = nullptr; auto tuple_slot_id = table->InsertTuple(&tuple, txn, &index_entry_ptr); PELOTON_ASSERT(tuple_slot_id.block != INVALID_OID); PELOTON_ASSERT(tuple_slot_id.offset != INVALID_OID); txn_manager.PerformInsert(txn, tuple_slot_id, index_entry_ptr); } } // namespace test } // namespace peloton
apache-2.0
meta-magic/amexio.github.io
src/module/forms/chips/chips.component.ts
7113
/* * Copyright [2019] [Metamagic] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 { AfterContentInit, Component, ContentChildren, ElementRef, EventEmitter, Input, OnInit, Output, QueryList, Renderer2, ViewChild } from '@angular/core'; import { AmexioChipComponent } from '../chip/chip.component'; @Component({ selector: 'amexio-chips', templateUrl: './chips.component.html', }) export class AmexioChipsComponent implements AfterContentInit, OnInit { @ContentChildren(AmexioChipComponent) queryChips: QueryList<AmexioChipComponent>; chipCollection: AmexioChipComponent[]; /* Properties name : data datatype : version : 5.3onwards default : description : The Data is set of json value like icon,label and closable. */ @Input('data') data: any[]; /* Events name : displayfield datatype : none version : none default : none description : It will display the key of the json passed. */ @Input('display-field') displayfield: any; /* Events name : selectedRowData datatype : none version : none default : none description : It will fire only on selection of checkbox and gives you selected record data. */ @Output() selectedchipsData: any = new EventEmitter<any>(); @Output() closeClick: any = new EventEmitter<any>(); componentId: any; chipindex = -1; prevchipindex = -1; chiplabel: any; documentClickListener: any; obj: any = {}; constructor(public renderer: Renderer2) { } ngAfterContentInit() { this.chipCollection = this.queryChips.toArray(); if (this.chipCollection.length > 0) { this.data = this.chipCollection; } this.generateIndex(); this.listenChipOutClick(); } ngOnInit() { this.componentId = 'chips' + window.crypto.getRandomValues(new Uint32Array(1))[0]; } listenChipOutClick() { this.documentClickListener = this.renderer .listen('document', 'click', (event: any) => { if (this.data.length > 0) { this.data.forEach((element: any, index: number) => { if (this.data[index]['selected'] === true) { this.data[index]['selected'] = false; this.chipindex = -1; this.prevchipindex = -1; } }); } }); } onCloseChipsClick(item: any) { if (this.chipindex > -1) { this.data[this.chipindex]['selected'] = false; } if (this.data.length > 0) { this.data.forEach((element: any, index: number) => { if (element.label === item.label) { this.data.splice(index, 1); } }); this.emitCloseData(item); } } emitCloseData(item: any) { const cloneNode = JSON.parse(JSON.stringify(item)); delete cloneNode['index']; if (this.chipCollection.length > 0) { this.obj['icon'] = item.icon; this.obj['label'] = item.label; this.obj['badge'] = item.badge; this.obj['closable'] = item.closable; this.obj['color'] = item.color; this.closeClick.emit(this.obj); } else { this.closeClick.emit(cloneNode); } } closeFocusedChip(item: any, chipdata: any) { let closeindex: number; let emitdata: any; this.obj = {}; if (this.data.length > 0) { chipdata.forEach((element: any, index: number) => { if (chipdata[index]['selected'] === true) { emitdata = element; this.chiplabel = chipdata[index]['label'] + 'closed'; this.data.splice(index, 1); closeindex = index; } }); this.obj['icon'] = emitdata.icon; this.obj['label'] = emitdata.label; this.obj['badge'] = emitdata.badge; this.obj['closable'] = emitdata.closable; this.obj['color'] = emitdata.color; this.closeChip(closeindex); this.emitSelectedLabel(chipdata); } } emitSelectedLabel(item: any) { const cloneNode = JSON.parse(JSON.stringify(item)); delete cloneNode['index']; if (this.chipCollection.length > 0) { this.obj['icon'] = item.icon; this.obj['label'] = item.label; this.obj['badge'] = item.badge; this.obj['closable'] = item.closable; this.obj['color'] = item.color; this.selectedchipsData.emit(this.obj); } else { this.selectedchipsData.emit(cloneNode); } } generateIndex() { this.data.forEach((element, index) => { element['index'] = this.componentId + 'chip' + index; element['selected'] = false; }); } onchipsKeyup(event: any) { if (this.data.length > 0) { this.navigateChips(event); } } navigateChips(event: any) { if (event.keyCode === 37) { this.leftArrowKeyNavigation(event); } else if (event.keyCode === 39) { this.rightArrowKeyNavigation(event); } } leftArrowKeyNavigation(event: any) { if (this.prevchipindex > -1) { this.data[this.prevchipindex]['selected'] = false; } this.prevchipindex--; if (this.prevchipindex === -1) { this.prevchipindex = this.data.length - 1; this.chipindex = -1; } this.setAriaActiveDescendant(this.prevchipindex); if (this.prevchipindex === 0) { this.chipindex = 0; } } rightArrowKeyNavigation(event: any) { if (this.prevchipindex > -1) { this.data[this.prevchipindex]['selected'] = false; } this.chipindex++; this.prevchipindex = this.chipindex; if (this.chipindex >= this.data.length) { this.chipindex = 0; this.prevchipindex = 0; } this.setAriaActiveDescendant(this.chipindex); } setAriaActiveDescendant(rowindex: any) { this.data[rowindex]['selected'] = true; const inputid = document.getElementById(this.componentId); inputid.setAttribute('aria-activedescendant', this.data[rowindex]['index']); } focusToLastChip(event: any) { if (this.prevchipindex > -1) { this.data[this.prevchipindex]['selected'] = false; } this.prevchipindex = this.data.length - 1; this.chipindex = -1; this.setAriaActiveDescendant(this.prevchipindex); } focusToFirstChip(event: any) { if (this.prevchipindex > -1) { this.data[this.prevchipindex]['selected'] = false; } this.chipindex = 0; this.prevchipindex = 0; this.setAriaActiveDescendant(this.chipindex); } closeChip(closeindex: any) { if (closeindex !== 0) { this.chipindex = closeindex - 1; this.prevchipindex = closeindex - 1; this.setAriaActiveDescendant(closeindex - 1); } else { this.chipindex = closeindex; this.prevchipindex = closeindex; this.setAriaActiveDescendant(closeindex); } } }
apache-2.0
nasa/Common-Metadata-Repository
graph-db/serverless/src/utils/chunkArray.js
571
/** * Split an array into an array of smaller arrays * @param {Array} myArray The array to be split up into chunks * @param {Number} chunkSize The size of the chunks to split the array into * @return {Array} An array of arrays split up into the requested sizes */ export const chunkArray = (myArray, chunkSize) => { let index = 0 const arrayLength = myArray.length const tempArray = [] for (index = 0; index < arrayLength; index += chunkSize) { const myChunk = myArray.slice(index, index + chunkSize) tempArray.push(myChunk) } return tempArray }
apache-2.0
nate-rcl/irplus
ir_service/test/edu/ur/ir/institution/service/DefaultInstitutionalCollectionServiceTest.java
39755
/** Copyright 2008 University of Rochester Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 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 edu.ur.ir.institution.service; import java.io.File; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Properties; import java.util.Set; import org.springframework.context.ApplicationContext; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import org.testng.annotations.Test; import edu.ur.exception.DuplicateNameException; import edu.ur.file.IllegalFileSystemNameException; import edu.ur.file.db.LocationAlreadyExistsException; import edu.ur.ir.file.IrFile; import edu.ur.ir.handle.HandleInfo; import edu.ur.ir.handle.HandleNameAuthority; import edu.ur.ir.handle.HandleService; import edu.ur.ir.index.IndexProcessingType; import edu.ur.ir.index.IndexProcessingTypeService; import edu.ur.ir.institution.CollectionDoesNotAcceptItemsException; import edu.ur.ir.institution.DeletedInstitutionalItemService; import edu.ur.ir.institution.InstitutionalCollection; import edu.ur.ir.institution.InstitutionalCollectionSecurityService; import edu.ur.ir.institution.InstitutionalCollectionService; import edu.ur.ir.institution.InstitutionalItem; import edu.ur.ir.institution.InstitutionalItemIndexProcessingRecord; import edu.ur.ir.institution.InstitutionalItemIndexProcessingRecordService; import edu.ur.ir.institution.InstitutionalItemService; import edu.ur.ir.item.GenericItem; import edu.ur.ir.item.ItemService; import edu.ur.ir.repository.LicenseService; import edu.ur.ir.repository.Repository; import edu.ur.ir.repository.RepositoryLicenseNotAcceptedException; import edu.ur.ir.repository.RepositoryService; import edu.ur.ir.repository.VersionedLicense; import edu.ur.ir.repository.service.test.helper.ContextHolder; import edu.ur.ir.repository.service.test.helper.PropertiesLoader; import edu.ur.ir.repository.service.test.helper.RepositoryBasedTestHelper; import edu.ur.ir.security.IrClassTypePermission; import edu.ur.ir.security.PermissionNotGrantedException; import edu.ur.ir.security.SecurityService; import edu.ur.ir.user.IrUser; import edu.ur.ir.user.IrUserGroup; import edu.ur.ir.user.UserDeletedPublicationException; import edu.ur.ir.user.UserEmail; import edu.ur.ir.user.UserGroupService; import edu.ur.ir.user.UserHasPublishedDeleteException; import edu.ur.ir.user.UserRepositoryLicense; import edu.ur.ir.user.UserService; import edu.ur.util.FileUtil; /** * Tests for the Institutional collection service. * * @author Nathan Sarr * */ @Test(groups = { "baseTests" }, enabled = true) public class DefaultInstitutionalCollectionServiceTest { /** Spring application context */ ApplicationContext ctx = ContextHolder.getApplicationContext(); /** Repository service */ RepositoryService repositoryService = (RepositoryService) ctx.getBean("repositoryService"); /** Collection security service */ InstitutionalCollectionSecurityService institutionalCollectionSecurityService = (InstitutionalCollectionSecurityService) ctx.getBean("institutionalCollectionSecurityService"); /** Collection service */ InstitutionalCollectionService institutionalCollectionService = (InstitutionalCollectionService) ctx.getBean("institutionalCollectionService"); /** Institutional Item service */ InstitutionalItemService institutionalItemService = (InstitutionalItemService) ctx.getBean("institutionalItemService"); /** Deleted Institutional Item service */ DeletedInstitutionalItemService deletedInstitutionalItemService = (DeletedInstitutionalItemService) ctx.getBean("deletedInstitutionalItemService"); /** user service */ UserService userService = (UserService) ctx.getBean("userService"); /** Base Security data access */ SecurityService securityService = (SecurityService) ctx .getBean("securityService"); /** transaction manager for dealing with transactions */ PlatformTransactionManager tm = (PlatformTransactionManager) ctx.getBean("transactionManager"); /** the transaction definition */ TransactionDefinition td = new DefaultTransactionDefinition( TransactionDefinition.PROPAGATION_REQUIRED); /** Properties file with testing specific information. */ PropertiesLoader propertiesLoader = new PropertiesLoader(); /** Get the properties file */ Properties properties = propertiesLoader.getProperties(); /** Item Service */ ItemService itemService = (ItemService) ctx .getBean("itemService"); /** User data access */ UserGroupService userGroupService = (UserGroupService) ctx .getBean("userGroupService"); /** index processing type record service */ IndexProcessingTypeService indexProcessingTypeService = (IndexProcessingTypeService) ctx.getBean("indexProcessingTypeService"); /** Institutional Item index processing record service */ InstitutionalItemIndexProcessingRecordService recordProcessingService = (InstitutionalItemIndexProcessingRecordService) ctx.getBean("institutionalItemIndexProcessingRecordService"); /** Default license service */ LicenseService licenseService = (LicenseService) ctx.getBean("licenseService"); /** Service for dealing with handles */ HandleService handleService = (HandleService) ctx.getBean("handleService"); /** * Test moving collections to an existing collection * * @throws DuplicateNameException * @throws LocationAlreadyExistsException */ public void moveCollectionToCollectionTest() throws DuplicateNameException, LocationAlreadyExistsException, CollectionDoesNotAcceptItemsException { // start a new transaction TransactionStatus ts = tm.getTransaction(td); RepositoryBasedTestHelper helper = new RepositoryBasedTestHelper(ctx); Repository repo = helper.createTestRepositoryDefaultFileServer(properties); // save the repository tm.commit(ts); // Start the transaction - create collections ts = tm.getTransaction(td); repo = repositoryService.getRepository(repo.getId(), false); InstitutionalCollection collection = repo.createInstitutionalCollection("collection"); assert collection != null : "collection should be created"; InstitutionalCollection subCollection = collection.createChild("subChild"); institutionalCollectionService.saveCollection(collection); InstitutionalCollection destination = repo.createInstitutionalCollection("destination"); assert destination != null : "destination collection should be created"; tm.commit(ts); // start new transaction ts = tm.getTransaction(td); assert collection.getId() != null : "Institutional colletion should not have a null id " + collection; List<InstitutionalCollection> collectionsToMove = new LinkedList<InstitutionalCollection>(); collectionsToMove.add(collection); institutionalCollectionService.moveCollectionInformation(destination, collectionsToMove, null); tm.commit(ts); //new transaction // make sure the collection was moved. ts = tm.getTransaction(td); InstitutionalCollection theDestination = repo.getInstitutionalCollection(destination.getName()); InstitutionalCollection newChild = theDestination.getChild(collection.getName()); assert newChild != null : "Was not able to find " + collection + " in children of " + theDestination ; assert newChild.getLeftValue().equals(2l) : "new child left value should = 2 but equals " + newChild.getLeftValue(); assert newChild.getRightValue().equals(5l) : "new child right value should = 5l but equals " + newChild.getRightValue(); String path = "/" + destination.getName() + "/" + newChild.getName() + "/"; assert newChild.getFullPath().equals(path) : "new child path should = " + path + " but equals " + newChild.getFullPath(); InstitutionalCollection aSubChild = newChild.getChild(subCollection.getName()); assert aSubChild != null : "Sub child should not be null"; assert aSubChild.getLeftValue().equals(3l) : "a sub child left value should = 3 but equals " + aSubChild.getLeftValue(); assert aSubChild.getRightValue().equals(4l) : "new child right value should = 4l but equals " + aSubChild.getRightValue(); path = path + aSubChild.getName() + "/"; assert aSubChild.getFullPath().equals(path) : " a sub child path should = " + path + " but equals " + aSubChild.getFullPath(); tm.commit(ts); // Start new transaction ts = tm.getTransaction(td); helper.cleanUpRepository(); tm.commit(ts); } /** * Test deleting a collection with at least one item * @throws LocationAlreadyExistsException * @throws DuplicateNameException * @throws UserDeletedPublicationException * @throws UserHasPublishedDeleteException */ public void testDeleteInstitutinalCollectionWithItems() throws LocationAlreadyExistsException, DuplicateNameException, UserHasPublishedDeleteException, UserDeletedPublicationException, CollectionDoesNotAcceptItemsException { // Start the transaction - create the repository TransactionStatus ts = tm.getTransaction(td); RepositoryBasedTestHelper helper = new RepositoryBasedTestHelper(ctx); Repository repo = helper.createTestRepositoryDefaultFileServer(properties); // save the repository tm.commit(ts); ts = tm.getTransaction(td); String userEmail1 = properties.getProperty("user_1_email"); UserEmail email = new UserEmail(userEmail1); IrUser user = userService.createUser("password", "username", email); repo = repositoryService.getRepository(repo.getId(), false); InstitutionalCollection collection = repo.createInstitutionalCollection("collection"); InstitutionalCollection subCollection = collection.createChild("sub-collection"); institutionalCollectionService.saveCollection(collection); // create the generic items GenericItem genericItem1 = new GenericItem("aItem"); GenericItem genericItem2 = new GenericItem("subItem"); // add the item to the collection InstitutionalItem institutionalItem1 = collection.createInstitutionalItem(genericItem1); InstitutionalItem institutionalItem2 = collection.createInstitutionalItem(genericItem2); institutionalItemService.saveInstitutionalItem(institutionalItem1); institutionalItemService.saveInstitutionalItem(institutionalItem2); tm.commit(ts); // delete data ts = tm.getTransaction(td); InstitutionalCollection topLevelCollection = institutionalCollectionService.getCollection(collection.getId(), false); // delete the to level collection institutionalCollectionService.deleteCollection(topLevelCollection, user); tm.commit(ts); // Start new transaction - make sure things deleted clean up remaining data ts = tm.getTransaction(td); topLevelCollection = institutionalCollectionService.getCollection(collection.getId(), false); assert topLevelCollection == null : "Should not be able to find top level collection " + topLevelCollection; subCollection = institutionalCollectionService.getCollection(subCollection.getId(), false); assert subCollection == null : "Should not be able to find sub collection " + subCollection; institutionalItem1 = institutionalItemService.getInstitutionalItem(institutionalItem1.getId(), false); assert institutionalItem1 == null : "Should not be able to find institutional item " + institutionalItem1; institutionalItem2 = institutionalItemService.getInstitutionalItem(institutionalItem2.getId(), false); assert institutionalItem2 == null : "Should not be able to find institutional item " + institutionalItem2; helper.cleanUpRepository(); deletedInstitutionalItemService.deleteAllInstitutionalItemHistory(); IrUser userToDelete = userService.getUser(user.getUsername()); userService.deleteUser(userToDelete, userToDelete); tm.commit(ts); } /** * Test moving collections to an existing collection * * @throws DuplicateNameException * @throws LocationAlreadyExistsException */ public void moveCollectionToRootTest() throws DuplicateNameException, LocationAlreadyExistsException { // start a new transaction TransactionStatus ts = tm.getTransaction(td); RepositoryBasedTestHelper helper = new RepositoryBasedTestHelper(ctx); Repository repo = helper.createTestRepositoryDefaultFileServer(properties); // save the repository tm.commit(ts); // Start the transaction - create collections ts = tm.getTransaction(td); repo = repositoryService.getRepository(repo.getId(), false); InstitutionalCollection collection = repo.createInstitutionalCollection("collection"); InstitutionalCollection subCollection = collection.createChild("subChild"); institutionalCollectionService.saveCollection(collection); tm.commit(ts); // start new transaction ts = tm.getTransaction(td); //reload the objects for new transaction repo = repositoryService.getRepository(repo.getId(), false); collection = repo.getInstitutionalCollection(collection.getName()); subCollection = collection.getChild(subCollection.getName()); assert collection.getId() != null : "Institutional colletion should not have a null id " + collection; List<InstitutionalCollection> collectionsToMove = new LinkedList<InstitutionalCollection>(); collectionsToMove.add(subCollection); institutionalCollectionService.moveCollectionInformation(repo, collectionsToMove); tm.commit(ts); //new transaction // make sure the collection was moved. ts = tm.getTransaction(td); InstitutionalCollection newRoot = repo.getInstitutionalCollection(subCollection.getName()); InstitutionalCollection oldParent = repo.getInstitutionalCollection(collection.getName()); assert oldParent.getLeftValue().equals(1l) : "old parent left value should = 1l but equals " + oldParent.getLeftValue(); assert oldParent.getRightValue().equals(2l) : "old parent right value should = 2l but equals " + oldParent.getRightValue(); InstitutionalCollection oldChild = oldParent.getChild(subCollection.getName()); assert oldChild == null : "old child should be null"; assert newRoot.getLeftValue().equals(1l) : "new root left value should = 4 but equals " + newRoot.getLeftValue(); assert newRoot.getRightValue().equals(2l) : "new root right value should = 5l but equals " + newRoot.getRightValue(); String path = "/" + newRoot.getName() + "/"; assert newRoot.getFullPath().equals(path) : " new root path should = " + path + " but equals " + newRoot.getFullPath(); tm.commit(ts); // Start new transaction ts = tm.getTransaction(td); helper.cleanUpRepository(); tm.commit(ts); } /** * Test adding subscribers to collection * * @throws UserHasPublishedDeleteException * @throws LocationAlreadyExistsException * */ public void collectionSubscriptionTest() throws DuplicateNameException, UserHasPublishedDeleteException, UserDeletedPublicationException, LocationAlreadyExistsException { // start a new transaction TransactionStatus ts = tm.getTransaction(td); RepositoryBasedTestHelper helper = new RepositoryBasedTestHelper(ctx); Repository repo = helper.createTestRepositoryDefaultFileServer(properties); String userEmail1 = properties.getProperty("user_1_email"); UserEmail email = new UserEmail(userEmail1); IrUser user = userService.createUser("password", "username", email); // save the repository tm.commit(ts); // Start the transaction - create collections ts = tm.getTransaction(td); repo = repositoryService.getRepository(repo.getId(), false); InstitutionalCollection collection = repo.createInstitutionalCollection("collection"); collection.addSuscriber(user); institutionalCollectionService.saveCollection(collection); tm.commit(ts); // start new transaction ts = tm.getTransaction(td); //reload the objects for new transaction assert collection.getSubscriptions().size() == 1 : "Institutional colletion should have subscriptions"; assert collection.hasSubscriber(user) : "Collection should have subscriber - " + user.getUsername(); collection.removeSubscriber(user); institutionalCollectionService.saveCollection(collection); tm.commit(ts); // Start new transaction ts = tm.getTransaction(td); InstitutionalCollection otherCollection = institutionalCollectionService.getCollection(collection.getId(), false); assert otherCollection.getSubscriptions().size() == 0: "Collection should not have subscribers"; institutionalCollectionService.deleteCollection(otherCollection, user); IrUser userToDelete = userService.getUser(user.getUsername()); userService.deleteUser(userToDelete, userToDelete); helper.cleanUpRepository(); tm.commit(ts); } public void testSetAllPublicationsWithinCollectionPublic() throws IllegalFileSystemNameException, DuplicateNameException, UserHasPublishedDeleteException, UserDeletedPublicationException, UserDeletedPublicationException, LocationAlreadyExistsException, CollectionDoesNotAcceptItemsException{ // Start the transaction - create the repository TransactionStatus ts = tm.getTransaction(td); RepositoryBasedTestHelper helper = new RepositoryBasedTestHelper(ctx); Repository repo = helper.createTestRepositoryDefaultFileServer(properties); // save the repository repo = repositoryService.getRepository(repo.getId(), false); InstitutionalCollection collection = repo.createInstitutionalCollection("collection"); UserEmail email = new UserEmail("email"); IrUser user = userService.createUser("password", "username", email); // create the first file to store in the temporary folder String tempDirectory = properties.getProperty("ir_service_temp_directory"); File directory = new File(tempDirectory); // helper to create the file FileUtil testUtil = new FileUtil(); testUtil.createDirectory(directory); File f = testUtil.creatFile(directory, "testFile", "Hello - irFile This is text in a file - VersionedFileDAO test"); assert f != null : "File should not be null"; assert user.getId() != null : "User id should not be null"; assert repo.getFileDatabase().getId() != null : "File database id should not be null"; IrFile irFile = repositoryService.createIrFile(repo, f, "fileName", "description"); // create a personal item to publish into the repository GenericItem genericItem = new GenericItem("item name"); genericItem.addFile(irFile).setPublic(false); genericItem.setPubliclyViewable(false); collection.createInstitutionalItem(genericItem); institutionalCollectionService.saveCollection(collection); tm.commit(ts); // test searching for the data ts = tm.getTransaction(td); collection = institutionalCollectionService.getCollection(collection.getId(), false); institutionalCollectionService.setAllItemsWithinCollectionPublic(collection); GenericItem otherItem = itemService.getGenericItem(genericItem.getId(), false); assert otherItem.isPubliclyViewable() : "The item should be public"; assert otherItem.getItemFile("fileName").isPublic(): "The item file should be public"; tm.commit(ts); // Start new transaction - clean up the data ts = tm.getTransaction(td); institutionalCollectionService.deleteCollection(institutionalCollectionService.getCollection(collection.getId(),false), user); deletedInstitutionalItemService.deleteAllInstitutionalItemHistory(); IrUser deleteUser = userService.getUser(user.getId(), false); userService.deleteUser(deleteUser, deleteUser); helper.cleanUpRepository(); tm.commit(ts); } public void testSetAllPublicationsWithinCollectionPrivate() throws IllegalFileSystemNameException, DuplicateNameException, UserDeletedPublicationException, UserHasPublishedDeleteException, LocationAlreadyExistsException, CollectionDoesNotAcceptItemsException{ // Start the transaction - create the repository TransactionStatus ts = tm.getTransaction(td); RepositoryBasedTestHelper helper = new RepositoryBasedTestHelper(ctx); Repository repo = helper.createTestRepositoryDefaultFileServer(properties); // save the repository repo = repositoryService.getRepository(repo.getId(), false); InstitutionalCollection collection = repo.createInstitutionalCollection("collection"); UserEmail email = new UserEmail("email"); IrUser user = userService.createUser("password", "username", email); // create the first file to store in the temporary folder String tempDirectory = properties.getProperty("ir_service_temp_directory"); File directory = new File(tempDirectory); // helper to create the file FileUtil testUtil = new FileUtil(); testUtil.createDirectory(directory); File f = testUtil.creatFile(directory, "testFile", "Hello - irFile This is text in a file - VersionedFileDAO test"); assert f != null : "File should not be null"; assert user.getId() != null : "User id should not be null"; assert repo.getFileDatabase().getId() != null : "File database id should not be null"; IrFile irFile = repositoryService.createIrFile(repo, f, "fileName", "description"); // create a personal item to publish into the repository GenericItem genericItem = new GenericItem("item name"); genericItem.addFile(irFile); collection.createInstitutionalItem(genericItem); institutionalCollectionService.saveCollection(collection); tm.commit(ts); // test searching for the data ts = tm.getTransaction(td); collection = institutionalCollectionService.getCollection(collection.getId(), false); institutionalCollectionService.setAllItemsWithinCollectionPrivate(collection); GenericItem otherItem = itemService.getGenericItem(genericItem.getId(), false); assert !otherItem.isPubliclyViewable() : "The item should be private"; assert !otherItem.getItemFile("fileName").isPublic(): "The item file should be private"; tm.commit(ts); // Start new transaction - clean up the data ts = tm.getTransaction(td); institutionalCollectionService.deleteCollection(institutionalCollectionService.getCollection(collection.getId(),false), user); deletedInstitutionalItemService.deleteAllInstitutionalItemHistory(); IrUser deleteUser = userService.getUser(user.getId(), false); userService.deleteUser(deleteUser, deleteUser); helper.cleanUpRepository(); tm.commit(ts); } /** * * Use the service to add an item to a collection * * @throws LocationAlreadyExistsException * @throws DuplicateNameException * @throws CollectionDoesNotAcceptItemsException * @throws RepositoryLicenseNotAcceptedException * @throws PermissionNotGrantedException * @throws UserDeletedPublicationException * @throws UserHasPublishedDeleteException */ public void testAddItemToCollectionWithoutHandleTest() throws LocationAlreadyExistsException, DuplicateNameException, PermissionNotGrantedException, RepositoryLicenseNotAcceptedException, CollectionDoesNotAcceptItemsException, UserHasPublishedDeleteException, UserDeletedPublicationException { // Start the transaction - create the repository TransactionStatus ts = tm.getTransaction(td); RepositoryBasedTestHelper helper = new RepositoryBasedTestHelper(ctx); Repository repo = helper.createTestRepositoryDefaultFileServer(properties); // save the repository repo = repositoryService.getRepository(repo.getId(), false); InstitutionalCollection collection = repo.createInstitutionalCollection("collection"); UserEmail email = new UserEmail("email"); IrUser user = userService.createUser("password", "username", email); institutionalCollectionService.saveCollection(collection); VersionedLicense license = licenseService.createLicense(user, "text", " a license ", "this is a license description"); repo.updateDefaultLicense(user, license.getCurrentVersion()); repositoryService.saveRepository(repo); user.addAcceptedLicense(license.getCurrentVersion()); userService.makeUserPersistent(user); IrUserGroup userGroup = new IrUserGroup("directSubmitGroup"); userGroup.addUser(user); userGroupService.save(userGroup); // set up direct submit permissions IrClassTypePermission directSubmitPermission = securityService.getPermissionForClass(collection, InstitutionalCollectionSecurityService.DIRECT_SUBMIT_PERMISSION.getPermission()); List<IrClassTypePermission> permissions = new ArrayList<IrClassTypePermission>(); permissions.add(directSubmitPermission); securityService.createPermissions(collection, userGroup, permissions); // create the generic item GenericItem item = new GenericItem("item name"); // index processing types IndexProcessingType updateProcessingType = new IndexProcessingType(IndexProcessingTypeService.UPDATE); indexProcessingTypeService.save(updateProcessingType); IndexProcessingType deleteProcessingType = new IndexProcessingType(IndexProcessingTypeService.DELETE); indexProcessingTypeService.save(deleteProcessingType); IndexProcessingType insertProcessingType = new IndexProcessingType(IndexProcessingTypeService.INSERT); indexProcessingTypeService.save(insertProcessingType); tm.commit(ts); ts = tm.getTransaction(td); // create an item user service to add it to collection assert repo.getDefaultLicense() != null; InstitutionalItem institutionalItem = institutionalCollectionService.addItemToCollection(user, item, collection); assert institutionalItem != null : "institutional item should not be null"; assert institutionalItem.getInstitutionalCollection().equals(collection) : "institutional item collection should equal " + collection + " but equals " + institutionalItem.getInstitutionalCollection(); assert institutionalItem.getVersionedInstitutionalItem().getCurrentVersion().getRepositoryLicense().getLicenseVersion().equals(repo.getDefaultLicense().getVersionedLicense().getCurrentVersion()) : "License should equal " + repo.getDefaultLicense().getVersionedLicense().getCurrentVersion() + " but equals " + institutionalItem.getVersionedInstitutionalItem().getCurrentVersion().getRepositoryLicense().getLicenseVersion(); tm.commit(ts); ts = tm.getTransaction(td); /** Institutional Item index processing record service */ List<InstitutionalItemIndexProcessingRecord> processingRecords = recordProcessingService.getAll(); for(InstitutionalItemIndexProcessingRecord pr : processingRecords ) { recordProcessingService.delete(pr); } indexProcessingTypeService.delete(indexProcessingTypeService.get(IndexProcessingTypeService.UPDATE)); indexProcessingTypeService.delete(indexProcessingTypeService.get(IndexProcessingTypeService.DELETE)); indexProcessingTypeService.delete(indexProcessingTypeService.get(IndexProcessingTypeService.INSERT)); securityService.deletePermissions(collection.getId(), collection.getClass().getName(), userGroup); institutionalCollectionService.deleteCollection(institutionalCollectionService.getCollection(collection.getId(),false), user); deletedInstitutionalItemService.deleteAllInstitutionalItemHistory(); userGroupService.delete(userGroupService.get(userGroup.getId(), false)); helper.cleanUpRepository(); IrUser deleteUser = userService.getUser(user.getId(), false); Set<UserRepositoryLicense> licenses = deleteUser.getAcceptedLicenses(); for(UserRepositoryLicense url : licenses) { deleteUser.removeAcceptedLicense(url); } userService.makeUserPersistent(deleteUser); tm.commit(ts); ts = tm.getTransaction(td); licenseService.delete(licenseService.get(license.getId(), false)); deleteUser = userService.getUser(user.getId(), false); userService.deleteUser(deleteUser, deleteUser); tm.commit(ts); } /** * * Use the service to add an item to a collection * * @throws LocationAlreadyExistsException * @throws DuplicateNameException * @throws CollectionDoesNotAcceptItemsException * @throws RepositoryLicenseNotAcceptedException * @throws PermissionNotGrantedException * @throws UserDeletedPublicationException * @throws UserHasPublishedDeleteException */ public void testAddItemToCollectionWithHandleTest() throws LocationAlreadyExistsException, DuplicateNameException, PermissionNotGrantedException, RepositoryLicenseNotAcceptedException, CollectionDoesNotAcceptItemsException, UserHasPublishedDeleteException, UserDeletedPublicationException { // Start the transaction - create the repository TransactionStatus ts = tm.getTransaction(td); RepositoryBasedTestHelper helper = new RepositoryBasedTestHelper(ctx); Repository repo = helper.createTestRepositoryDefaultFileServer(properties); HandleNameAuthority authority = new HandleNameAuthority("1802"); // save the repository repo = repositoryService.getRepository(repo.getId(), false); repo.setDefaultHandleNameAuthority(authority); repositoryService.saveRepository(repo); InstitutionalCollection collection = repo.createInstitutionalCollection("collection"); UserEmail email = new UserEmail("email"); IrUser user = userService.createUser("password", "username", email); institutionalCollectionService.saveCollection(collection); IrUserGroup userGroup = new IrUserGroup("directSubmitGroup"); userGroup.addUser(user); userGroupService.save(userGroup); // set up direct submit permissions IrClassTypePermission directSubmitPermission = securityService.getPermissionForClass(collection, InstitutionalCollectionSecurityService.DIRECT_SUBMIT_PERMISSION.getPermission()); List<IrClassTypePermission> permissions = new ArrayList<IrClassTypePermission>(); permissions.add(directSubmitPermission); securityService.createPermissions(collection, userGroup, permissions); // create the generic item GenericItem item = new GenericItem("item name"); // index processing types IndexProcessingType updateProcessingType = new IndexProcessingType(IndexProcessingTypeService.UPDATE); indexProcessingTypeService.save(updateProcessingType); IndexProcessingType deleteProcessingType = new IndexProcessingType(IndexProcessingTypeService.DELETE); indexProcessingTypeService.save(deleteProcessingType); IndexProcessingType insertProcessingType = new IndexProcessingType(IndexProcessingTypeService.INSERT); indexProcessingTypeService.save(insertProcessingType); InstitutionalItem institutionalItem = institutionalCollectionService.addItemToCollection(user, item, collection); tm.commit(ts); ts = tm.getTransaction(td); // create an item user service to add it to collection institutionalItem = institutionalItemService.getInstitutionalItem(institutionalItem.getId(), false); assert institutionalItem != null : "institutional item should not be null"; assert institutionalItem.getInstitutionalCollection().equals(collection) : "institutional item collection should equal " + collection + " but equals " + institutionalItem.getInstitutionalCollection(); HandleInfo handleInfo = institutionalItem.getVersionedInstitutionalItem().getCurrentVersion().getHandleInfo(); assert handleInfo != null : "Should have a handle info object"; assert handleInfo.getNameAuthority().equals(authority) : "Info authority should equal " + authority + " but equals " + handleInfo.getNameAuthority(); assert handleInfo.getData() != null : "Data should not be null"; assert !handleInfo.getData().equals("") : "Data should not be an empty string"; /** Institutional Item index processing record service */ List<InstitutionalItemIndexProcessingRecord> processingRecords = recordProcessingService.getAll(); for(InstitutionalItemIndexProcessingRecord pr : processingRecords ) { recordProcessingService.delete(pr); } indexProcessingTypeService.delete(indexProcessingTypeService.get(IndexProcessingTypeService.UPDATE)); indexProcessingTypeService.delete(indexProcessingTypeService.get(IndexProcessingTypeService.DELETE)); indexProcessingTypeService.delete(indexProcessingTypeService.get(IndexProcessingTypeService.INSERT)); securityService.deletePermissions(collection.getId(), collection.getClass().getName(), userGroup); institutionalCollectionService.deleteCollection(institutionalCollectionService.getCollection(collection.getId(),false), user); deletedInstitutionalItemService.deleteAllInstitutionalItemHistory(); IrUser deleteUser = userService.getUser(user.getId(), false); userService.deleteUser(deleteUser, deleteUser); userGroupService.delete(userGroupService.get(userGroup.getId(), false)); helper.cleanUpRepository(); tm.commit(ts); ts = tm.getTransaction(td); handleService.delete(handleService.getHandleInfo(handleInfo.getId(), false)); handleService.delete(handleService.getNameAuthority(authority.getId(), false)); tm.commit(ts); } /** * * Use the service to add an item to a collection * * @throws LocationAlreadyExistsException * @throws DuplicateNameException * @throws CollectionDoesNotAcceptItemsException * @throws RepositoryLicenseNotAcceptedException * @throws PermissionNotGrantedException * @throws UserDeletedPublicationException * @throws UserHasPublishedDeleteException */ public void testAddItemToCollectionWithNoPermissions() throws LocationAlreadyExistsException, DuplicateNameException, RepositoryLicenseNotAcceptedException, CollectionDoesNotAcceptItemsException, UserHasPublishedDeleteException, UserDeletedPublicationException { // Start the transaction - create the repository TransactionStatus ts = tm.getTransaction(td); RepositoryBasedTestHelper helper = new RepositoryBasedTestHelper(ctx); Repository repo = helper.createTestRepositoryDefaultFileServer(properties); InstitutionalCollection collection = repo.createInstitutionalCollection("collection"); UserEmail email = new UserEmail("email"); IrUser user = userService.createUser("password", "username", email); institutionalCollectionService.saveCollection(collection); tm.commit(ts); ts = tm.getTransaction(td); // create an item user service to add it to collection InstitutionalItem institutionalItem = null; try { // create the generic item GenericItem item = new GenericItem("item name"); institutionalItem = institutionalCollectionService.addItemToCollection(user, item, collection); assert false : "this should fail with permission granted exception "; } catch (PermissionNotGrantedException e) { // swallow error } assert institutionalItem == null : "institutional item should be null"; tm.commit(ts); ts = tm.getTransaction(td); institutionalCollectionService.deleteCollection(institutionalCollectionService.getCollection(collection.getId(),false), user); deletedInstitutionalItemService.deleteAllInstitutionalItemHistory(); IrUser deleteUser = userService.getUser(user.getId(), false); userService.deleteUser(deleteUser, deleteUser); helper.cleanUpRepository(); tm.commit(ts); } /** * * Use the service to add an item to a collection when the repository has a license the * user must accept * * @throws LocationAlreadyExistsException * @throws DuplicateNameException * @throws CollectionDoesNotAcceptItemsException * @throws RepositoryLicenseNotAcceptedException * @throws PermissionNotGrantedException * @throws UserDeletedPublicationException * @throws UserHasPublishedDeleteException */ public void testAddItemToCollectionWithLicense() throws LocationAlreadyExistsException, DuplicateNameException, CollectionDoesNotAcceptItemsException, UserHasPublishedDeleteException, UserDeletedPublicationException, PermissionNotGrantedException { // Start the transaction - create the repository TransactionStatus ts = tm.getTransaction(td); RepositoryBasedTestHelper helper = new RepositoryBasedTestHelper(ctx); Repository repo = helper.createTestRepositoryDefaultFileServer(properties); InstitutionalCollection collection = repo.createInstitutionalCollection("collection"); UserEmail email = new UserEmail("email"); IrUser user = userService.createUser("password", "username", email); institutionalCollectionService.saveCollection(collection); VersionedLicense license = licenseService.createLicense(user, "text", " a license ", "this is a license description"); repo.updateDefaultLicense(user, license.getCurrentVersion()); repositoryService.saveRepository(repo); // create the generic item GenericItem item = new GenericItem("item name"); tm.commit(ts); ts = tm.getTransaction(td); // create an item user service to add it to collection InstitutionalItem institutionalItem = null; try { institutionalItem = institutionalCollectionService.addItemToCollection(user, item, collection); assert false : "Should not make it here"; } catch (RepositoryLicenseNotAcceptedException e) { //swallow error } assert institutionalItem == null : "institutional item should be null"; tm.commit(ts); ts = tm.getTransaction(td); institutionalCollectionService.deleteCollection(institutionalCollectionService.getCollection(collection.getId(),false), user); IrUser deleteUser = userService.getUser(user.getId(), false); helper.cleanUpRepository(); licenseService.delete(licenseService.get(license.getId(), false)); userService.deleteUser(deleteUser, deleteUser); tm.commit(ts); } }
apache-2.0
ndrmc/cats
Cats.Web.Adminstration/ViewModelBinder/CommodityGradeViewModelBinder.cs
1349
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Cats.Models; using Cats.Web.Adminstration.Models.ViewModels; namespace Cats.Web.Adminstration.ViewModelBinder { public class CommodityGradeViewModelBinder { public static CommodityGradeViewModel BindCommodityGradeViewModel(CommodityGrade commodityGrade) { return new CommodityGradeViewModel() { CommodityGradeID=commodityGrade.CommodityGradeID, Name=commodityGrade.Name, Description = commodityGrade.Description }; } public static List<CommodityGradeViewModel> BindListCommodityGradeViewModel(List<CommodityGrade> commodityGrades) { return commodityGrades.Select(BindCommodityGradeViewModel).ToList(); } public static CommodityGrade BindCommodityGrade(CommodityGradeViewModel commodityGradeViewModel, CommodityGrade commodityGrade = null) { return commodityGrade ?? new CommodityGrade() { CommodityGradeID=commodityGradeViewModel.CommodityGradeID, Name=commodityGradeViewModel.Name, Description=commodityGradeViewModel.Description }; } } }
apache-2.0
hannesstruss/WindFish
app/src/main/java/de/hannesstruss/windfish/WindFishTileService.java
1252
package de.hannesstruss.windfish; import android.graphics.drawable.Icon; import android.service.quicksettings.Tile; import android.service.quicksettings.TileService; import rx.Subscription; public class WindFishTileService extends TileService { private WindFishState state; private Subscription stateSubscription; @Override public void onCreate() { super.onCreate(); state = ((WindFishApp) getApplicationContext()).state(); } @Override public void onDestroy() { super.onDestroy(); if (stateSubscription != null) { stateSubscription.unsubscribe(); } } @Override public void onStartListening() { super.onStartListening(); stateSubscription = state.mode().subscribe(this::updateTile); } @Override public void onClick() { super.onClick(); state.toggle(); } private void updateTile(WindFishState.Mode mode) { Tile tile = getQsTile(); tile.setState(mode != WindFishState.Mode.ALWAYS_OFF ? Tile.STATE_ACTIVE : Tile.STATE_INACTIVE); int iconRes = mode == WindFishState.Mode.ON_WHEN_CHARGING ? R.drawable.tile_power : R.drawable.tile; tile.setIcon(Icon.createWithResource(getApplicationContext(), iconRes)); tile.updateTile(); } }
apache-2.0
chronolaw/boost_guide
container/variant2.cpp
2543
// Copyright (c) 2015 // Author: Chrono Law #include <std.hpp> using namespace std; #include <boost/assign.hpp> #include <boost/variant2/variant.hpp> using namespace boost::variant2; ////////////////////////////////////////// void case1() { variant<int, float, string> v; v = "123"; cout << get<string>(v) << endl; assert(get<2>(v) == get<string>(v)); } ////////////////////////////////////////// void case2() { typedef variant<int, double, string> var_t; var_t v(1); //v->int v = 2.13; //v->double //assert(v.type() == typeid(double)); var_t v2("string type"); //v2->string cout << get<string>(v2); v2 = v; //v2->double cout << get<int>(var_t(108)); } #if 0 ////////////////////////////////////////// void case3() { typedef variant<int, double, string> var_t; var_t v; //assert(v.type() == typeid(int)); assert(v.which() == 0); v = "variant demo"; cout << *get<string>(&v) << endl; try { cout << get<double>(v) << endl; } catch (bad_get &) { cout << "bad_get" << endl; } } ////////////////////////////////////////// struct var_print : public static_visitor<> { template<typename T> void operator()(T &i) const { i *= 2; cout << i << endl; } void operator()(vector<int> &v) const { v.reserve(v.size()*2); copy(v.begin(),v.end(),back_inserter(v)) ; for (auto& x : v) { cout << x << ","; //输出以验证 } cout << endl; } }; void case4() { typedef variant<int, double, vector<int> > var_t; var_t v(1); var_print vp; visit(vp, v); v = 3.414; visit(vp, v); //using namespace boost::assign; //v = vector<int>({1,2}); vector<int> tmp = {1,2}; v = tmp; visit(vp, v); auto vp2 = visit(vp); vp2(v); } ////////////////////////////////////////// template<BOOST_VARIANT_ENUM_PARAMS(typename T)> void op_var(variant<BOOST_VARIANT_ENUM_PARAMS(T)>& v) { cout << v << endl;} #include <boost/mpl/vector.hpp> void case5() { typedef boost::mpl::vector< int, double, std::vector<string> > var_types; make_variant_over<var_types>::type v; v = 2.13; } #endif ////////////////////////////////////////// int main() { case1(); case2(); //case3(); //case4(); //case5(); }
apache-2.0
coastland/gsp-dba-maven-plugin
src/test/resources/jp/co/tis/gsp/tools/dba/mojo/GenerateEntity_test/another_schema/sqlserver/expected/output/jp/co/tis/gsptest/entity/entity/View1.java
938
package jp.co.tis.gsptest.entity.entity; import java.io.Serializable; import javax.annotation.Generated; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; /** * View1エンティティクラス * */ @Generated("GSP") @Entity @Table(schema = "gspanother", name = "VIEW1") public class View1 implements Serializable { private static final long serialVersionUID = 1L; /** testTbl1Nameプロパティ */ private String testTbl1Name; /** * testTbl1Nameを返します。 * * @return testTbl1Name */ @Column(name = "TEST_TBL1_NAME", length = 30, nullable = true, unique = false) public String getTestTbl1Name() { return testTbl1Name; } /** * testTbl1Nameを設定します。 * * @param testTbl1Name */ public void setTestTbl1Name(String testTbl1Name) { this.testTbl1Name = testTbl1Name; } }
apache-2.0
AMDL/amdl2maml
amdl2maml/Converter/Properties/Resources.Designer.cs
5197
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Amdl.Maml.Converter.Properties { using System; using System.Reflection; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Amdl.Maml.Converter.Properties.Resources", typeof(Resources).GetTypeInfo().Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Concepts. /// </summary> internal static string ConceptsTitle { get { return ResourceManager.GetString("ConceptsTitle", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Glossary. /// </summary> internal static string GlossaryNameLast { get { return ResourceManager.GetString("GlossaryNameLast", resourceCulture); } } /// <summary> /// Looks up a localized string similar to HowTo. /// </summary> internal static string HowToNameFirst { get { return ResourceManager.GetString("HowToNameFirst", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Orientation. /// </summary> internal static string OrientationNameLast { get { return ResourceManager.GetString("OrientationNameLast", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Other Resources. /// </summary> internal static string OtherResourcesTitle { get { return ResourceManager.GetString("OtherResourcesTitle", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Reference. /// </summary> internal static string ReferenceTitle { get { return ResourceManager.GetString("ReferenceTitle", resourceCulture); } } /// <summary> /// Looks up a localized string similar to See Also. /// </summary> internal static string SeeAlsoTitle { get { return ResourceManager.GetString("SeeAlsoTitle", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Tasks. /// </summary> internal static string TasksTitle { get { return ResourceManager.GetString("TasksTitle", resourceCulture); } } } }
apache-2.0
guardian/scala-automation
src/main/scala/com/gu/automation/support/page/PageCompanion.scala
391
package com.gu.automation.support.page import com.gu.automation.support.Config import org.openqa.selenium.WebDriver trait PageCompanion[A] { val relativeUrl: String = "" protected def makePage(implicit driver: WebDriver): A def goto(urlAppend: String = "")(implicit driver: WebDriver): A = { driver.get(Config().getTestBaseUrl() + relativeUrl + urlAppend) makePage } }
apache-2.0
ewilde/crane
src/Crane.Core/Api/Builders/ProjectBuilder.cs
448
using Crane.Core.Api.Model; namespace Crane.Core.Api.Builders { public class ProjectBuilder { private Project _project; public ProjectBuilder() { _project = new Project(); } public ProjectBuilder WithName(string name) { _project.Name = name; return this; } public Project Build() { return null; } } }
apache-2.0
cloudwall/libcwfincore
cwfinjava/src/main/java/cloudwall/tradedb/gdax/GdaxExchangeSyncer.java
2173
/* * (C) Copyright 2017 Kyle F. Downey. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 cloudwall.tradedb.gdax; import cloudwall.appconfig.Blade; import cloudwall.exchange.coinbase.CoinbaseServiceModule; import cloudwall.tradedb.common.ProductEntitySyncer; import dagger.Component; import javax.inject.Inject; import javax.inject.Singleton; import java.util.concurrent.ExecutionException; /** * Standalone application for synchronizing exchange data to our local database. * * @author <a href="mailto:kyle.downey@gmail.com">Kyle F. Downey</a> */ public class GdaxExchangeSyncer implements Blade { private final ProductEntitySyncer productEntitySyncer; private final GdaxTransactionSyncer transactionSyncer; private final GdaxAccountSyncer accountSyncer; @Inject public GdaxExchangeSyncer(ProductEntitySyncer productEntitySyncer, GdaxTransactionSyncer transactionSyncer, GdaxAccountSyncer accountSyncer) { this.productEntitySyncer = productEntitySyncer; this.transactionSyncer = transactionSyncer; this.accountSyncer = accountSyncer; } @Override public void run() { try { productEntitySyncer.sync().get(); transactionSyncer.sync().get(); accountSyncer.sync().get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } } @Singleton @Component(modules = {CoinbaseServiceModule.class, SyncerServiceModule.class }) public interface SyncerComponent { @SuppressWarnings("unused") GdaxExchangeSyncer tool(); } }
apache-2.0
shgli/cpp-protobuf
src/parser/Utils.cpp
613
#include "gcc.h" #include "Utils.h" std::string GetDeclNamespace(tree decl) { std::string s, tmp; for (tree scope (CP_DECL_CONTEXT (decl)); scope != global_namespace; scope = CP_DECL_CONTEXT (scope)) { tmp = "::"; if(CLASS_TYPE_P(scope)) { scope = TYPE_NAME(scope); tmp += GetNameByTree(scope); } else { tmp += GetNameByTree(scope); } tmp += s; s.swap (tmp); } return s; } std::string GetNameByTree(tree decl) { tree id = DECL_NAME(decl); const char *name = id ? IDENTIFIER_POINTER (id) : "<unnamed>"; return std::string(name); }
apache-2.0
floored/pooperator
assets/js/lib/luma/Shader.js
4790
var Geometry = require('./Geometry'); var shaders = require('./shaders/main'); function Shader(renderContext, name) { this.rc = renderContext; this.name = name; this.vertexShaderId = this.rc.gl.createShader(this.rc.gl.VERTEX_SHADER); this.fragmentShaderId = this.rc.gl.createShader(this.rc.gl.FRAGMENT_SHADER); this.programId = null; this.load(); } Shader.prototype.validateCompilation = function(shaderId) { if (!this.rc.gl.getShaderParameter(shaderId, this.rc.gl.COMPILE_STATUS)) { var errorLog = this.rc.gl.getShaderInfoLog(shaderId); console.log("Error compiling shader:\n" + errorLog); this.rc.gl.deleteShader(shaderId); return false; } return true; }; Shader.prototype.load = function() { console.log("Loading shader " + this.name); this.rc.gl.shaderSource(this.vertexShaderId, shaders[this.name].vert); this.rc.gl.shaderSource(this.fragmentShaderId, shaders[this.name].frag); this.rc.gl.compileShader(this.vertexShaderId); if (!this.validateCompilation(this.vertexShaderId)) { return false; } this.rc.gl.compileShader(this.fragmentShaderId); if (!this.validateCompilation(this.fragmentShaderId)) { return false; } this.programId = this.rc.gl.createProgram(); if(this.programId === 0) { console.log('Failed to create program id.'); //Log error! } this.rc.gl.attachShader(this.programId, this.vertexShaderId); this.rc.gl.attachShader(this.programId, this.fragmentShaderId); this.rc.gl.bindAttribLocation(this.programId, Geometry.VERTEX_ATTRIBUTES.POSITION, "vertexPosition"); this.rc.gl.bindAttribLocation(this.programId, Geometry.VERTEX_ATTRIBUTES.UV, "vertexTexCoords"); this.rc.gl.bindAttribLocation(this.programId, Geometry.VERTEX_ATTRIBUTES.NORMAL, "vartexNormal"); this.rc.gl.bindAttribLocation(this.programId, Geometry.VERTEX_ATTRIBUTES.TANGENT, "vertexTangent"); this.rc.gl.bindAttribLocation(this.programId, Geometry.VERTEX_ATTRIBUTES.BITANGENT, "vertexBitangent"); this.rc.gl.linkProgram(this.programId); var linkStatus = this.rc.gl.getProgramParameter(this.programId, this.rc.gl.LINK_STATUS); if(!linkStatus && !this.rc.gl.isContextLost()) { var errorLog = this.rc.gl.getProgramInfoLog(this.programId); this.rc.gl.deleteProgram(this.programId); this.programId = null; console.log('Error compiling shader: '+errorLog); return false; } console.log('Loaded shader '+this.name+' sucessfully.'); }; Shader.prototype.bind = function() { this.rc.gl.useProgram(this.programId); }; Shader.prototype.unbind = function() { this.rc.gl.useProgram(null); }; Shader.prototype.setUniformInt1 = function(name, value) { var location = this.rc.gl.getUniformLocation(this.programId, name); if (location) { this.rc.gl.uniform1i(location, value); } }; Shader.prototype.setUniformInt2 = function(name, value) { var location = this.rc.gl.getUniformLocation(this.programId, name); if (location) { this.rc.gl.uniform2i(location, value[0], value[1]); } }; Shader.prototype.setUniformInt3 = function(name, value) { var location = this.rc.gl.getUniformLocation(this.programId, name); if (location) { this.rc.gl.uniform3i(location, value[0], value[1], value[2]); } }; Shader.prototype.setUniformInt4 = function(name, value) { var location = this.rc.gl.getUniformLocation(this.programId, name); if (location) { this.rc.gl.uniform4i(location, value[0], value[1], value[2], value[3]); } }; Shader.prototype.setUniformFloat1 = function(name, value) { var location = this.rc.gl.getUniformLocation(this.programId, name); if (location) { this.rc.gl.uniform1f(location, value); } }; Shader.prototype.setUniformFloat2 = function(name, value) { var location = this.rc.gl.getUniformLocation(this.programId, name); if (location) { this.rc.gl.uniform2f(location, value[0], value[1]); } }; Shader.prototype.setUniformFloat3 = function(name, value) { var location = this.rc.gl.getUniformLocation(this.programId, name); if (location) { this.rc.gl.uniform3f(location, value[0], value[1], value[2]); } }; Shader.prototype.setUniformFloat4 = function(name, value) { var location = this.rc.gl.getUniformLocation(this.programId, name); if (location) { this.rc.gl.uniform4f(location, value[0], value[1], value[2], value[3]); } }; Shader.prototype.setUniformMatrix3x3 = function(name, value) { var location = this.rc.gl.getUniformLocation(this.programId, name); if (location) { this.rc.gl.uniformMatrix3fv(location, this.rc.gl.FALSE, value); } }; Shader.prototype.setUniformMatrix4x4 = function(name, value) { var location = this.rc.gl.getUniformLocation(this.programId, name); if (location) { this.rc.gl.uniformMatrix4fv(location, this.rc.gl.FALSE, value); } }; return Shader;
apache-2.0
googleads/google-ads-java
google-ads-stubs-v8/src/main/java/com/google/ads/googleads/v8/services/MutateBiddingDataExclusionsResponseOrBuilder.java
3202
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v8/services/bidding_data_exclusion_service.proto package com.google.ads.googleads.v8.services; public interface MutateBiddingDataExclusionsResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:google.ads.googleads.v8.services.MutateBiddingDataExclusionsResponse) com.google.protobuf.MessageOrBuilder { /** * <pre> * Errors that pertain to operation failures in the partial failure mode. * Returned only when partial_failure = true and all errors occur inside the * operations. If any errors occur outside the operations (e.g. auth errors), * we return an RPC level error. * </pre> * * <code>.google.rpc.Status partial_failure_error = 3;</code> * @return Whether the partialFailureError field is set. */ boolean hasPartialFailureError(); /** * <pre> * Errors that pertain to operation failures in the partial failure mode. * Returned only when partial_failure = true and all errors occur inside the * operations. If any errors occur outside the operations (e.g. auth errors), * we return an RPC level error. * </pre> * * <code>.google.rpc.Status partial_failure_error = 3;</code> * @return The partialFailureError. */ com.google.rpc.Status getPartialFailureError(); /** * <pre> * Errors that pertain to operation failures in the partial failure mode. * Returned only when partial_failure = true and all errors occur inside the * operations. If any errors occur outside the operations (e.g. auth errors), * we return an RPC level error. * </pre> * * <code>.google.rpc.Status partial_failure_error = 3;</code> */ com.google.rpc.StatusOrBuilder getPartialFailureErrorOrBuilder(); /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v8.services.MutateBiddingDataExclusionsResult results = 2;</code> */ java.util.List<com.google.ads.googleads.v8.services.MutateBiddingDataExclusionsResult> getResultsList(); /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v8.services.MutateBiddingDataExclusionsResult results = 2;</code> */ com.google.ads.googleads.v8.services.MutateBiddingDataExclusionsResult getResults(int index); /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v8.services.MutateBiddingDataExclusionsResult results = 2;</code> */ int getResultsCount(); /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v8.services.MutateBiddingDataExclusionsResult results = 2;</code> */ java.util.List<? extends com.google.ads.googleads.v8.services.MutateBiddingDataExclusionsResultOrBuilder> getResultsOrBuilderList(); /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v8.services.MutateBiddingDataExclusionsResult results = 2;</code> */ com.google.ads.googleads.v8.services.MutateBiddingDataExclusionsResultOrBuilder getResultsOrBuilder( int index); }
apache-2.0
iliantrifonov/TelerikAcademy
Web services and Cloud/ExamPreparation/Web/Controllers/ArticlesController.cs
3864
namespace Web.Controllers { using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using Microsoft.AspNet.Identity; using Data; using Model; using Web.DataModels; public class ArticlesController : BaseApiController { private const int PageAmount = 10; public ArticlesController(IApplicationData data) : base(data) { } //[Authorize] [HttpPost] public IHttpActionResult PostArticle([FromBody]ArticleInputDataModel model) { if (model == null ||!this.ModelState.IsValid) { return BadRequest(); } var category = this.data.Categories.All().FirstOrDefault(c => c.Name == model.Category); if (category == null) { category = new Category() { Name = model.Category, }; this.data.Categories.Add(category); } var tags = GetTags(model); var articleForDb = new Article() { AuthorID = this.User.Identity.GetUserId(), Category = category, Content = model.Content, DateCreated = DateTime.Now, Title = model.Title, Tags = tags, }; this.data.Articles.Add(articleForDb); this.data.SaveChanges(); var outputModel = this.data.Articles.All() .Where(a => a.Id == articleForDb.Id) .Select(ArticleOutputDataModel.ToOutputModel); return Ok(outputModel); } [HttpGet] public IHttpActionResult GetArticles(int page, string category) { var articlesToReturn = this.GetSortedArticles() .Where(c => category == null ? true : category == c.Category.Name) .Skip(PageAmount * page) .Take(PageAmount) .Select(ArticleOutputDataModel.ToOutputModel); return Ok(articlesToReturn); } [HttpGet] public IHttpActionResult GetDetailedArticlesById(int id) { var articleToReturn = this.data.Articles.All() .Select(ArticleDetailedOutputModel.ToOutputModel) .FirstOrDefault(a => a.Id == id); if (articleToReturn == null) { return NotFound(); } return Ok(articleToReturn); } [HttpGet] public IHttpActionResult GetArticles() { return this.GetArticles(0, null); } [HttpGet] public IHttpActionResult GetArticles(int page) { return this.GetArticles(page, null); } [NonAction] private IQueryable<Article> GetSortedArticles() { return this.data.Articles.All().OrderBy(a => a.DateCreated); } private ICollection<Tag> GetTags(ArticleInputDataModel model) { var titletgas = model.Title.Split(' '); var allTags = new HashSet<string>(titletgas); foreach (var modelTag in model.Tags) { allTags.Add(modelTag); } var articleTags = new HashSet<Tag>(); foreach (var tagName in allTags) { var tag = this.data.Tags.All() .FirstOrDefault(t => t.Name == tagName); if (tag == null) { tag = new Tag { Name = tagName }; this.data.Tags.Add(tag); } articleTags.Add(tag); } return articleTags; } } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-cloudfront/src/main/java/com/amazonaws/services/cloudfront/model/GetFieldLevelEncryptionProfileConfigResult.java
6807
/* * Copyright 2017-2022 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.cloudfront.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/GetFieldLevelEncryptionProfileConfig" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class GetFieldLevelEncryptionProfileConfigResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * Return the field-level encryption profile configuration information. * </p> */ private FieldLevelEncryptionProfileConfig fieldLevelEncryptionProfileConfig; /** * <p> * The current version of the field-level encryption profile configuration result. For example: * <code>E2QWRUHAPOMQZL</code>. * </p> */ private String eTag; /** * <p> * Return the field-level encryption profile configuration information. * </p> * * @param fieldLevelEncryptionProfileConfig * Return the field-level encryption profile configuration information. */ public void setFieldLevelEncryptionProfileConfig(FieldLevelEncryptionProfileConfig fieldLevelEncryptionProfileConfig) { this.fieldLevelEncryptionProfileConfig = fieldLevelEncryptionProfileConfig; } /** * <p> * Return the field-level encryption profile configuration information. * </p> * * @return Return the field-level encryption profile configuration information. */ public FieldLevelEncryptionProfileConfig getFieldLevelEncryptionProfileConfig() { return this.fieldLevelEncryptionProfileConfig; } /** * <p> * Return the field-level encryption profile configuration information. * </p> * * @param fieldLevelEncryptionProfileConfig * Return the field-level encryption profile configuration information. * @return Returns a reference to this object so that method calls can be chained together. */ public GetFieldLevelEncryptionProfileConfigResult withFieldLevelEncryptionProfileConfig(FieldLevelEncryptionProfileConfig fieldLevelEncryptionProfileConfig) { setFieldLevelEncryptionProfileConfig(fieldLevelEncryptionProfileConfig); return this; } /** * <p> * The current version of the field-level encryption profile configuration result. For example: * <code>E2QWRUHAPOMQZL</code>. * </p> * * @param eTag * The current version of the field-level encryption profile configuration result. For example: * <code>E2QWRUHAPOMQZL</code>. */ public void setETag(String eTag) { this.eTag = eTag; } /** * <p> * The current version of the field-level encryption profile configuration result. For example: * <code>E2QWRUHAPOMQZL</code>. * </p> * * @return The current version of the field-level encryption profile configuration result. For example: * <code>E2QWRUHAPOMQZL</code>. */ public String getETag() { return this.eTag; } /** * <p> * The current version of the field-level encryption profile configuration result. For example: * <code>E2QWRUHAPOMQZL</code>. * </p> * * @param eTag * The current version of the field-level encryption profile configuration result. For example: * <code>E2QWRUHAPOMQZL</code>. * @return Returns a reference to this object so that method calls can be chained together. */ public GetFieldLevelEncryptionProfileConfigResult withETag(String eTag) { setETag(eTag); return this; } /** * 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("{"); if (getFieldLevelEncryptionProfileConfig() != null) sb.append("FieldLevelEncryptionProfileConfig: ").append(getFieldLevelEncryptionProfileConfig()).append(","); if (getETag() != null) sb.append("ETag: ").append(getETag()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof GetFieldLevelEncryptionProfileConfigResult == false) return false; GetFieldLevelEncryptionProfileConfigResult other = (GetFieldLevelEncryptionProfileConfigResult) obj; if (other.getFieldLevelEncryptionProfileConfig() == null ^ this.getFieldLevelEncryptionProfileConfig() == null) return false; if (other.getFieldLevelEncryptionProfileConfig() != null && other.getFieldLevelEncryptionProfileConfig().equals(this.getFieldLevelEncryptionProfileConfig()) == false) return false; if (other.getETag() == null ^ this.getETag() == null) return false; if (other.getETag() != null && other.getETag().equals(this.getETag()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getFieldLevelEncryptionProfileConfig() == null) ? 0 : getFieldLevelEncryptionProfileConfig().hashCode()); hashCode = prime * hashCode + ((getETag() == null) ? 0 : getETag().hashCode()); return hashCode; } @Override public GetFieldLevelEncryptionProfileConfigResult clone() { try { return (GetFieldLevelEncryptionProfileConfigResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
apache-2.0
tucan21/python_zadania
test/test_modify_contact.py
3076
from model.contact import Contact from random import randrange #def test_modify_contact(app, db, check_ui): # old_contacts = db.get_contact_list() # if app.contact.count_contact() == 0: # app.contact.create_contact(Contact(firstname="Ola", middlename="Katarzyna", lastname="Pawlak", nickname="12345678", # title="987654321", # company="CBO", address="Katowice", homephone="2233665544", mobilephone="6012345678", # workphone="227895632", fax="224147856", email1="asdfgh@02.pl", email2="qazwsx@o2.pl", # address2="", secondaryphone="")) # new_contact_value = Contact(firstname="Jan", middlename="Krzysztof", lastname="Pawlowski", nickname="1111111", title="2222222", # company="3333333", address="4444444", homephone="5555555", mobilephone="6666666", workphone="7777777", # fax="8888888", # email1="qwertyu@02.pl", email2="zxcv@op.pl", address2="9999999", secondaryphone="0000000") # edited_contact_id = app.contact.edit_contact_and_get_id(new_contact_value) # new_contact_value.id = edited_contact_id # new_contacts = db.get_contact_list() # assert sorted([contact for contact in old_contacts if contact.id != edited_contact_id],key=Contact.id_or_max) == sorted([contact for contact in new_contacts if contact.id != edited_contact_id], key=Contact.id_or_max) # assert [contact for contact in new_contacts if contact.id == edited_contact_id] == [new_contact_value] # if check_ui: # assert sorted(new_contacts, key=Contact.id_or_max) == sorted(app.contact.get_contact_list(), key=Contact.id_or_max) def test_modify_some_contact(app): if app.contact.count_contact() == 0: app.contact(Contact(firstname="Ola", middlename="Katarzyna", lastname="Pawlak", nickname="12345678", title="987654321", company="CBO", address="Katowice", homephone="2233665544", mobilephone="6012345678", workphone="227895632", fax="224147856", email1="asdfgh@02.pl", email2="qazwsx@o2.pl", address2="", secondaryphone="")) old_contacts = app.contact.get_contact_list() index = randrange(len(old_contacts)) contact = Contact(firstname="Paulina", middlename="Magda-xxx", lastname="Kowalska--xxx", nickname="Paula--xxx", title="Mrs--xxx", company="DB--xxx", address="Krakow--xxx", homephone="2233665544--xxx", mobilephone="6012345678--xxx", workphone="227895632--xxx", fax="224147856--xxx", email1="asdfgh@02.pl--xxx", email2="sdf@op.pl--xxx", address2="--xxx", secondaryphone="-modyf") contact.id = old_contacts[index].id app.contact.edit_contact_by_index(index, contact) new_contacts = app.contact.get_contact_list() assert len(old_contacts) == len(new_contacts) # old_contacts[index] = contact # assert sorted(old_contacts, key=Contact.id_or_max) == sorted(new_contacts, key=Contact.id_or_max)
apache-2.0
ty-po/code-dot-org
apps/src/netsim/NetSimVizAutoDnsNode.js
744
/** * @overview Visualization auto-dns node. */ /* jshint funcscope: true, newcap: true, nonew: true, shadow: false, unused: true, maxlen: 90, maxstatements: 200 */ 'use strict'; require('../utils'); var netsimGlobals = require('./netsimGlobals'); var NetSimVizNode = require('./NetSimVizNode'); /** * @constructor * @augments NetSimVizNode */ var NetSimVizAutoDnsNode = module.exports = function () { NetSimVizNode.call(this); this.getRoot().addClass('auto-dns-node'); var levelConfig = netsimGlobals.getLevelConfig(); if (levelConfig.showHostnameInGraph) { this.setName('dns'); } else { this.setName('DNS'); } this.setIsDnsNode(true); this.render(); }; NetSimVizAutoDnsNode.inherits(NetSimVizNode);
apache-2.0
yusuke/samurai
samurai-swing/src/main/java/one/cafebabe/samurai/swing/TakeThreadDump.java
5904
/* * Copyright 2003-2015 Yusuke Yamamoto * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 one.cafebabe.samurai.swing; import com.sun.tools.attach.AttachNotSupportedException; import one.cafebabe.samurai.remotedump.ProcessUtil; import one.cafebabe.samurai.remotedump.VM; import one.cafebabe.samurai.remotedump.VirtualMachineUtil; import one.cafebabe.samurai.util.Configuration; import one.cafebabe.samurai.util.GUIResourceBundle; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import sun.jvmstat.monitor.MonitorException; import javax.swing.*; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class TakeThreadDump { private static final Logger logger = LogManager.getLogger(); private static final GUIResourceBundle resources = GUIResourceBundle.getInstance(); private final FileHistory fileHistory; JMenu takeThreadDumpMenu; public TakeThreadDump(Configuration config, FileHistory fileHistory, JMenu takeThreadDumpMenu) { config.apply(this); this.takeThreadDumpMenu = takeThreadDumpMenu; this.fileHistory = fileHistory; takeThreadDumpMenu.addMenuListener(new MenuListener() { @Override public void menuSelected(MenuEvent e) { updateChildMenuItems(); } @Override public void menuDeselected(MenuEvent e) { } @Override public void menuCanceled(MenuEvent e) { } }); } public JMenu getTakeThreadDumpMenu() { return this.takeThreadDumpMenu; } private void updateChildMenuItems() { try { List<VM> currentVms = ProcessUtil.getVMs("localhost"); for (int i = 0; i < takeThreadDumpMenu.getItemCount(); i++) { LocalProcessMenuItem item = (LocalProcessMenuItem) takeThreadDumpMenu.getItem(i); boolean found = false; for (VM vm : currentVms) { if (item.getVm().pid == vm.pid) { found = true; break; } } if (!found) { takeThreadDumpMenu.remove(item); } } for (VM vm : currentVms) { boolean found = false; for (int i = 0; i < takeThreadDumpMenu.getItemCount(); i++) { LocalProcessMenuItem item = (LocalProcessMenuItem) takeThreadDumpMenu.getItem(i); if (item.getVm().pid == vm.pid) { found = true; break; } } if (!found) { JMenuItem localProcess = new LocalProcessMenuItem(vm); localProcess.setToolTipText(vm.fullCommandLine); takeThreadDumpMenu.add(localProcess); } } } catch (URISyntaxException | MonitorException e) { logger.warn("unable to monitor", e); e.printStackTrace(); } } private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); ExecutorService executor = Executors.newFixedThreadPool(1); class LocalProcessMenuItem extends JMenuItem { private static final long serialVersionUID = 2629440395264682598L; final VM vm; public LocalProcessMenuItem(VM vm) { super(vm.toLabel()); this.vm = vm; addActionListener(e -> executor.execute(() -> { try { Path path = Paths.get(System.getProperty("user.home"), String.format("%s-%d-%s.txt", vm.fqcn, vm.pid, LocalDateTime.now().format(dateTimeFormatter))); Files.writeString(path, LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) + "\n", StandardOpenOption.CREATE, StandardOpenOption.APPEND); Files.writeString(path, "pid: " + vm.pid + "\n\n", StandardOpenOption.CREATE, StandardOpenOption.APPEND); Files.writeString(path, "FQCN: " + vm.fqcn + "\n\n", StandardOpenOption.CREATE, StandardOpenOption.APPEND); Files.writeString(path, String.format("Command line:\n%s\n\n", vm.fullCommandLine), StandardOpenOption.CREATE, StandardOpenOption.APPEND); fileHistory.open(path.toFile()); for (int i = 0; i < 3; i++) { Files.write(path, VirtualMachineUtil.getThreadDump(vm.pid), StandardOpenOption.CREATE, StandardOpenOption.APPEND); Thread.sleep(1000); } } catch (InterruptedException | AttachNotSupportedException | IOException e1) { logger.warn("failed to attach pid[{}]",vm.pid, e1); } })); } public VM getVm() { return vm; } } }
apache-2.0
Geomatys/sis
core/sis-referencing/src/main/java/org/apache/sis/referencing/datum/DefaultPrimeMeridian.java
21978
/* * 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.sis.referencing.datum; import java.util.Map; import java.util.Objects; import javax.measure.Unit; import javax.measure.quantity.Angle; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import org.opengis.util.GenericName; import org.opengis.util.InternationalString; import org.opengis.metadata.Identifier; import org.opengis.referencing.datum.PrimeMeridian; import org.opengis.referencing.crs.GeneralDerivedCRS; import org.apache.sis.referencing.AbstractIdentifiedObject; import org.apache.sis.internal.referencing.Formulas; import org.apache.sis.internal.referencing.WKTUtilities; import org.apache.sis.internal.referencing.ReferencingUtilities; import org.apache.sis.internal.metadata.MetadataUtilities; import org.apache.sis.internal.metadata.WKTKeywords; import org.apache.sis.internal.jaxb.gml.Measure; import org.apache.sis.internal.util.Numerics; import org.apache.sis.io.wkt.Formatter; import org.apache.sis.io.wkt.Convention; import org.apache.sis.util.ComparisonMode; import org.apache.sis.measure.Units; import static org.apache.sis.util.ArgumentChecks.ensureFinite; import static org.apache.sis.util.ArgumentChecks.ensureNonNull; /** * Defines the origin from which longitude values are determined. * * <div class="section">Creating new prime meridian instances</div> * New instances can be created either directly by specifying all information to a factory method (choices 3 * and 4 below), or indirectly by specifying the identifier of an entry in a database (choices 1 and 2 below). * In particular, the <a href="http://www.epsg.org">EPSG</a> database provides definitions for many prime meridians, * and Apache SIS provides convenience shortcuts for some of them. * * <p>Choice 1 in the following list is the easiest but most restrictive way to get a prime meridian. * The other choices provide more freedom. Each choice delegates its work to the subsequent items * (in the default configuration), so this list can been seen as <cite>top to bottom</cite> API.</p> * * <ol> * <li>Create a {@code PrimeMeridian} from one of the static convenience shortcuts listed in * {@link org.apache.sis.referencing.CommonCRS#primeMeridian()}.</li> * <li>Create a {@code PrimeMeridian} from an identifier in a database by invoking * {@link org.opengis.referencing.datum.DatumAuthorityFactory#createPrimeMeridian(String)}.</li> * <li>Create a {@code PrimeMeridian} by invoking the {@code DatumFactory.createPrimeMeridian(…)} method * (implemented for example by {@link org.apache.sis.referencing.factory.GeodeticObjectFactory}).</li> * <li>Create a {@code DefaultPrimeMeridian} by invoking the * {@linkplain #DefaultPrimeMeridian(Map, double, Unit) constructor}.</li> * </ol> * * <b>Example:</b> the following code gets the Greenwich prime meridian: * * {@preformat java * PrimeMeridian pm = CommonCRS.WGS84.primeMeridian(); * } * * <div class="section">Immutability and thread safety</div> * This class is immutable and thus thread-safe if the property <em>values</em> (not necessarily the map itself) * given to the constructor are also immutable. Unless otherwise noted in the javadoc, this condition holds if * all components were created using only SIS factories and static constants. * * @author Martin Desruisseaux (IRD, Geomatys) * @author Cédric Briançon (Geomatys) * @version 0.7 * * @see org.apache.sis.referencing.CommonCRS#primeMeridian() * @see org.apache.sis.referencing.factory.GeodeticAuthorityFactory#createPrimeMeridian(String) * * @since 0.4 * @module */ @XmlType(name = "PrimeMeridianType") @XmlRootElement(name = "PrimeMeridian") public class DefaultPrimeMeridian extends AbstractIdentifiedObject implements PrimeMeridian { /** * Serial number for inter-operability with different versions. */ private static final long serialVersionUID = 541978454643213305L;; /** * Longitude of the prime meridian measured from the Greenwich meridian, positive eastward. * * <p><b>Consider this field as final!</b> * This field is modified only at unmarshalling time by {@link #setGreenwichMeasure(Measure)}</p> */ private double greenwichLongitude; /** * The angular unit of the {@linkplain #getGreenwichLongitude() Greenwich longitude}. * * <p><b>Consider this field as final!</b> * This field is modified only at unmarshalling time by {@link #setGreenwichMeasure(Measure)}</p> */ private Unit<Angle> angularUnit; /** * Creates a prime meridian from the given properties. The properties map is given unchanged to the * {@linkplain AbstractIdentifiedObject#AbstractIdentifiedObject(Map) super-class constructor}. * The following table is a reminder of main (not all) properties: * * <table class="sis"> * <caption>Recognized properties (non exhaustive list)</caption> * <tr> * <th>Property name</th> * <th>Value type</th> * <th>Returned by</th> * </tr> * <tr> * <td>{@value org.opengis.referencing.IdentifiedObject#NAME_KEY}</td> * <td>{@link Identifier} or {@link String}</td> * <td>{@link #getName()}</td> * </tr> * <tr> * <td>{@value org.opengis.referencing.IdentifiedObject#ALIAS_KEY}</td> * <td>{@link GenericName} or {@link CharSequence} (optionally as array)</td> * <td>{@link #getAlias()}</td> * </tr> * <tr> * <td>{@value org.opengis.referencing.IdentifiedObject#IDENTIFIERS_KEY}</td> * <td>{@link Identifier} (optionally as array)</td> * <td>{@link #getIdentifiers()}</td> * </tr> * <tr> * <td>{@value org.opengis.referencing.IdentifiedObject#REMARKS_KEY}</td> * <td>{@link InternationalString} or {@link String}</td> * <td>{@link #getRemarks()}</td> * </tr> * </table> * * @param properties the properties to be given to the identified object. * @param greenwichLongitude the longitude value relative to the Greenwich Meridian. * @param angularUnit the angular unit of the longitude. * * @see org.apache.sis.referencing.factory.GeodeticObjectFactory#createPrimeMeridian(Map, double, Unit) */ public DefaultPrimeMeridian(final Map<String,?> properties, final double greenwichLongitude, final Unit<Angle> angularUnit) { super(properties); ensureFinite("greenwichLongitude", greenwichLongitude); ensureNonNull("angularUnit", angularUnit); this.greenwichLongitude = greenwichLongitude; this.angularUnit = angularUnit; } /** * Creates a new prime meridian with the same values than the specified one. * This copy constructor provides a way to convert an arbitrary implementation into a SIS one * or a user-defined one (as a subclass), usually in order to leverage some implementation-specific API. * * <p>This constructor performs a shallow copy, i.e. the properties are not cloned.</p> * * @param meridian the prime meridian to copy. * * @see #castOrCopy(PrimeMeridian) */ protected DefaultPrimeMeridian(final PrimeMeridian meridian) { super(meridian); greenwichLongitude = meridian.getGreenwichLongitude(); angularUnit = meridian.getAngularUnit(); } /** * Returns a SIS prime meridian implementation with the same values than the given arbitrary implementation. * If the given object is {@code null}, then this method returns {@code null}. * Otherwise if the given object is already a SIS implementation, then the given object is returned unchanged. * Otherwise a new SIS implementation is created and initialized to the attribute values of the given object. * * @param object the object to get as a SIS implementation, or {@code null} if none. * @return a SIS implementation containing the values of the given object (may be the * given object itself), or {@code null} if the argument was null. */ public static DefaultPrimeMeridian castOrCopy(final PrimeMeridian object) { return (object == null) || (object instanceof DefaultPrimeMeridian) ? (DefaultPrimeMeridian) object : new DefaultPrimeMeridian(object); } /** * Returns the GeoAPI interface implemented by this class. * The SIS implementation returns {@code PrimeMeridian.class}. * * <div class="note"><b>Note for implementors:</b> * Subclasses usually do not need to override this method since GeoAPI does not define {@code PrimeMeridian} * sub-interface. Overriding possibility is left mostly for implementors who wish to extend GeoAPI with their * own set of interfaces.</div> * * @return {@code PrimeMeridian.class} or a user-defined sub-interface. */ @Override public Class<? extends PrimeMeridian> getInterface() { return PrimeMeridian.class; } /** * Longitude of the prime meridian measured from the Greenwich meridian, positive eastward. * * @return the prime meridian Greenwich longitude, in {@linkplain #getAngularUnit() angular unit}. */ @Override public double getGreenwichLongitude() { return greenwichLongitude; } /** * Returns the longitude value relative to the Greenwich Meridian, expressed in the specified units. * This convenience method makes it easier to obtain longitude in decimal degrees using the following * code, regardless of the underlying angular units of this prime meridian: * * {@preformat java * double longitudeInDegrees = primeMeridian.getGreenwichLongitude(Units.DEGREE); * } * * @param unit the unit in which to express longitude. * @return the Greenwich longitude in the given units. */ public double getGreenwichLongitude(final Unit<Angle> unit) { return getAngularUnit().getConverterTo(unit).convert(getGreenwichLongitude()); } /** * Returns the angular unit of the Greenwich longitude. * * @return the angular unit of the {@linkplain #getGreenwichLongitude() Greenwich longitude}. */ @Override public Unit<Angle> getAngularUnit() { return angularUnit; } /** * Compares this prime meridian with the specified object for equality. * * @param object the object to compare to {@code this}. * @param mode {@link ComparisonMode#STRICT STRICT} for performing a strict comparison, or * {@link ComparisonMode#IGNORE_METADATA IGNORE_METADATA} for comparing only properties * relevant to coordinate transformations. * @return {@code true} if both objects are equal. */ @Override public boolean equals(final Object object, final ComparisonMode mode) { if (object == this) { return true; // Slight optimization. } if (super.equals(object, mode)) switch (mode) { case STRICT: { final DefaultPrimeMeridian that = (DefaultPrimeMeridian) object; return Numerics.equals(this.greenwichLongitude, that.greenwichLongitude) && Objects.equals(this.angularUnit, that.angularUnit); } case BY_CONTRACT: { final PrimeMeridian that = (PrimeMeridian) object; return Numerics.equals(getGreenwichLongitude(), that.getGreenwichLongitude()) && Objects.equals(getAngularUnit(), that.getAngularUnit()); } default: { final double v1 = getGreenwichLongitude(Units.DEGREE); final double v2 = ReferencingUtilities.getGreenwichLongitude((PrimeMeridian) object, Units.DEGREE); if (mode == ComparisonMode.IGNORE_METADATA) { /* * We relax the check on unit of measurement because EPSG uses sexagesimal degrees * for the Greenwich meridian. Requirying the same unit would make more difficult * for isWGS84(…) methods to recognize EPSG's WGS84. We allow this relaxation here * because the unit of the prime meridian is usually not inherited by axes (indeed, * they are often not the same in the EPSG dataset). The same is not true for other * objects like DefaultEllipsoid. */ return Numerics.equals(v1, v2); } else if (Numerics.epsilonEqual(v1, v2, Formulas.ANGULAR_TOLERANCE)) { return true; } assert (mode != ComparisonMode.DEBUG) : Numerics.messageForDifference("greenwichLongitude", v1, v2); } } return false; } /** * Invoked by {@code hashCode()} for computing the hash code when first needed. * See {@link org.apache.sis.referencing.AbstractIdentifiedObject#computeHashCode()} * for more information. * * @return the hash code value. This value may change in any future Apache SIS version. */ @Override protected long computeHashCode() { return super.computeHashCode() + Double.doubleToLongBits(greenwichLongitude) + Objects.hashCode(angularUnit); } /** * Returns {@code true} if the given formatter is in the process of formatting the prime meridian of a base CRS * of an {@code AbstractDerivedCRS}. In such case, base CRS coordinate system axes shall not be formatted, which * has the consequence of bringing the {@code UNIT[…]} element right below the {@code PRIMEM[…]} one. Example: * * {@preformat wkt * ProjectedCRS[“NTF (Paris) / Lambert zone II”, * BaseGeodCRS[“NTF (Paris)”, * Datum[“Nouvelle Triangulation Francaise”, * Ellipsoid[“NTF”, 6378249.2, 293.4660212936269]], * PrimeMeridian[“Paris”, 2.5969213], * AngleUnit[“grad”, 0.015707963267948967]], * Conversion[“Lambert zone II”, * etc... * } * * If we were not formatting a base CRS, we would have many lines between {@code PrimeMeridian[…]} and * {@code AngleUnit[…]} in the above example, which would make less obvious that the angle unit applies * also to the prime meridian. It does not bring any ambiguity from an ISO 19162 standard point of view, * but historically some other software products interpreted the {@code PRIMEM[…]} units wrongly, which * is why we try to find a compromise between keeping the WKT simple and avoiding an historical ambiguity. * * @see org.apache.sis.referencing.crs.AbstractCRS#isBaseCRS(Formatter) */ private static boolean isElementOfBaseCRS(final Formatter formatter) { return formatter.getEnclosingElement(2) instanceof GeneralDerivedCRS; } /** * Returns {@code true} if {@link #formatTo(Formatter)} should conservatively format the angular unit * even if it would be legal to omit it. * * <div class="section">Rational</div> * According the ISO 19162 standard, it is legal to omit the {@code PrimeMeridian} angular unit when * that unit is the same than the unit of the axes of the enclosing {@code GeographicCRS}. However the * relationship between the CRS axes and the prime meridian is less obvious in WKT2 than it was in WKT1, * because the WKT2 {@code UNIT[…]} element is far from the {@code PRIMEM[…]} element while it was just * below it in WKT1. Furthermore, the {@code PRIMEM[…]} unit is one source of incompatibility between * various WKT1 parsers (i.e. some popular libraries are not conform to OGC 01-009 and ISO 19162). * So we are safer to unconditionally format any unit other than degrees, even if we could legally * omit them. * * <p>However in order to keep the WKT slightly simpler in {@link Convention#WKT2_SIMPLIFIED} mode, * we make an exception to the above-cited safety if the {@code UNIT[…]} element is formatted right * below the {@code PRIMEM[…]} one, which happen if we are inside a base CRS. * See {@link #isElementOfBaseCRS(Formatter)} for more discussion. */ private static boolean beConservative(final Formatter formatter, final Unit<Angle> contextualUnit) { return !contextualUnit.equals(Units.DEGREE) && !isElementOfBaseCRS(formatter); } /** * Formats this prime meridian as a <cite>Well Known Text</cite> {@code PrimeMeridian[…]} element. * * @return {@code "PrimeMeridian"} (WKT 2) or {@code "PrimeM"} (WKT 1). * * @see <a href="http://docs.opengeospatial.org/is/12-063r5/12-063r5.html#53">WKT 2 specification §8.2.2</a> */ @Override protected String formatTo(final Formatter formatter) { super.formatTo(formatter); final Convention convention = formatter.getConvention(); final boolean isWKT1 = (convention.majorVersion() == 1); final Unit<Angle> contextualUnit = formatter.toContextualUnit(Units.DEGREE); Unit<Angle> unit = contextualUnit; if (!isWKT1) { unit = getAngularUnit(); if (convention != Convention.INTERNAL) { unit = WKTUtilities.toFormattable(unit); } } formatter.append(getGreenwichLongitude(unit)); if (isWKT1) { return WKTKeywords.PrimeM; } if (!convention.isSimplified() || !contextualUnit.equals(unit) || beConservative(formatter, contextualUnit)) { formatter.append(unit); } return formatter.shortOrLong(WKTKeywords.PrimeM, WKTKeywords.PrimeMeridian); } ////////////////////////////////////////////////////////////////////////////////////////////////// //////// //////// //////// XML support with JAXB //////// //////// //////// //////// The following methods are invoked by JAXB using reflection (even if //////// //////// they are private) or are helpers for other methods invoked by JAXB. //////// //////// Those methods can be safely removed if Geographic Markup Language //////// //////// (GML) support is not needed. //////// //////// //////// ////////////////////////////////////////////////////////////////////////////////////////////////// /** * Constructs a new object in which every attributes are set to a null value. * <strong>This is not a valid object.</strong> This constructor is strictly * reserved to JAXB, which will assign values to the fields using reflexion. */ private DefaultPrimeMeridian() { super(org.apache.sis.internal.referencing.NilReferencingObject.INSTANCE); /* * Angular units are mandatory for SIS working. We do not verify their presence here (because the * verification would have to be done in an 'afterMarshal(…)' method and throwing an exception in * that method causes the whole unmarshalling to fail). But the CD_PrimeMeridian adapter does some * verifications. */ } /** * Invoked by JAXB for obtaining the Greenwich longitude to marshall together with its {@code "uom"} attribute. */ @XmlElement(name = "greenwichLongitude", required = true) private Measure getGreenwichMeasure() { return new Measure(greenwichLongitude, angularUnit); } /** * Invoked by JAXB for setting the Greenwich longitude and its unit of measurement. */ private void setGreenwichMeasure(final Measure measure) { if (greenwichLongitude == 0 && angularUnit == null) { greenwichLongitude = measure.value; angularUnit = measure.getUnit(Angle.class); if (angularUnit == null) { /* * Missing unit: if the Greenwich longitude is zero, any angular unit gives the same result * (assuming that the missing unit was not applying an offset), so we can select a default. * If the Greenwich longitude is not zero, presume egrees but log a warning. */ angularUnit = Units.DEGREE; if (greenwichLongitude != 0) { Measure.missingUOM(DefaultPrimeMeridian.class, "setGreenwichMeasure"); } } } else { MetadataUtilities.propertyAlreadySet(DefaultPrimeMeridian.class, "setGreenwichMeasure", "greenwichLongitude"); } } }
apache-2.0
interglobalvision/pindropstudio-com
lib/theme-options/about-options.php
2456
<?php // SITE OPTIONS $prefix = '_igv_'; $suffix = '_options'; $page_key = $prefix . 'about' . $suffix; $page_title = 'Partners'; $metabox = array( 'id' => $page_key, // id used as tab page slug, must be unique 'title' => $page_title, 'show_on' => array( 'key' => 'options-page', 'value' => array( $page_key ), ), //value must be same as id 'show_names' => true, 'fields' => array( // custom page home /* array( 'name' => __( 'Partners', 'cmb2' ), 'desc' => __( '', 'cmb2' ), 'id' => $prefix . 'home_title', 'type' => 'title', ), array( 'name' => __( 'People', 'IGV' ), 'desc' => __( '(displays on the About page)', 'IGV' ), 'id' => $prefix . 'people', 'type' => 'group', 'options' => array( 'add_button' => __( 'Add Another Person', 'cmb2' ), 'remove_button' => __( 'Remove Person', 'cmb2' ), ), 'fields' => array( array( 'name' => __( 'Person Name', 'IGV' ), 'id' => $prefix . 'name', 'type' => 'text', ), array( 'name' => __( 'Person Title', 'IGV' ), 'id' => $prefix . 'title', 'type' => 'text', ), array( 'name' => __( 'Person Image', 'IGV' ), 'id' => $prefix . 'image', 'type' => 'file', ), array( 'name' => __( 'Person Text', 'IGV' ), 'id' => $prefix . 'text', 'type' => 'wysiwyg', ), ), ), */ array( 'name' => __( 'Partners', 'IGV' ), 'desc' => __( '(displays on the About page and Partners page)', 'IGV' ), 'id' => $prefix . 'partners', 'type' => 'group', 'options' => array( 'add_button' => __( 'Add Another Partner', 'cmb2' ), 'remove_button' => __( 'Remove Partner', 'cmb2' ), ), 'fields' => array( array( 'name' => __( 'Partner Name', 'IGV' ), 'id' => $prefix . 'name', 'type' => 'text', ), array( 'name' => __( 'Partner Text', 'IGV' ), 'id' => $prefix . 'text', 'type' => 'textarea', ), array( 'name' => __( 'Partner Image', 'IGV' ), 'id' => $prefix . 'image', 'type' => 'file', ), ), ), ) ); IGV_init_options_page($page_key, $page_key, $page_title, $metabox);
apache-2.0
chelu/jdal
vaadin/src/main/java/org/jdal/vaadin/ui/form/FieldBuilder.java
972
/* * Copyright 2009-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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.jdal.vaadin.ui.form; import com.vaadin.ui.Field; /** * Pointer interface for building Fields. * * @author Jose Luis Martin - (jlm@joseluismartin.info) * @since 1.1 */ public interface FieldBuilder { /** * Build a Field * @param name * @param clazz * @return the field */ Field build(Class<?> clazz, String name); }
apache-2.0
blackberry/opendataspace-cascades
src/Singleton.hpp
562
#ifndef SINGLETON_HPP_ #define SINGLETON_HPP_ #include <QObject> // http://www.qtcentre.org/wiki/index.php?title=Singleton_pattern template <class T> class Singleton { public: static T& Instance() { static T _instance; // create static instance of our class return _instance; // return it } private: Singleton(); // hide constructor ~Singleton(); // hide destructor Singleton(const Singleton &); // hide copy constructor Singleton& operator=(const Singleton &); // hide assign op }; #endif /* SINGLETON_HPP_ */
apache-2.0
s3git/s3git-go
internal/cas/key.go
2165
/* * Copyright 2016 Frank Wessels <fwessels@xs4all.nl> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 cas import ( "encoding/hex" ) const stageDir = "stage" const cacheDir = "cache" const BLOB = "blob" var ( // // With the additional constraint that objects are a multiple of 64 in size, this // adds 6 bits to the chance of getting a regular blob in the range, see table: // // PREFIX-SIZE | NR BITS | OCCURRENCE (MLD) // 5 | 20+6 | 0.1 // 6 | 24+6 | 1.1 // 7 | 28+6 | 17.2 // 8 | 32+6 | 275 // prefixChar = '0' prefixNum = 7 prefixCheat = 3 // Number that is cheated in the prefix, like 0000xxx00000 -- will fail in file check mode ) // Size of the CAS keys in bytes. const KeySize = 64 const KeySizeHex = KeySize*2 // A Key that identifies data stored in the CAS. Keys are immutable. type Key struct { object [KeySize]byte } // BadKeySizeError is passed to panic if NewKey is called with input // that is not KeySize long. type BadKeySizeError struct { Key []byte } func newKey(b []byte) Key { k := Key{} n := copy(k.object[:], b) if n != KeySize { panic(BadKeySizeError{Key: b}) } return k } // NewKey makes a new Key with the given byte contents. // // This function is intended for use when unmarshaling keys from // storage. func NewKey(b []byte) Key { k := newKey(b) // if bytes.HasPrefix(k.object[:], specialPrefix) && // k != Empty { // return Invalid // } return k } // String returns a hex encoding of the key. func (k Key) String() string { return hex.EncodeToString(k.object[:]) }
apache-2.0
z123/datacollector
common/src/main/java/com/streamsets/pipeline/lib/parser/log/Errors.java
1835
/* * Copyright 2017 StreamSets 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.streamsets.pipeline.lib.parser.log; import com.streamsets.pipeline.api.ErrorCode; import com.streamsets.pipeline.api.GenerateResourceBundle; @GenerateResourceBundle public enum Errors implements ErrorCode { LOG_PARSER_00("Cannot advance file '{}' to offset '{}'"), LOG_PARSER_01("Error parsing log line '{}', reason : '{}'"), LOG_PARSER_02("Unsupported format {} encountered"), LOG_PARSER_03("Log line '{}' does not conform to '{}'"), LOG_PARSER_04("Max data object length can be -1 or greater than 0"), LOG_PARSER_05("Custom Log Format field cannot be empty"), LOG_PARSER_06("Error parsing custom log format string {}, reason {}"), LOG_PARSER_07("Error parsing regex {}, reason {}"), LOG_PARSER_08("RegEx {} contains {} groups but the field Path to group mapping specifies group {}."), LOG_PARSER_09("Error parsing grok pattern {}, reason {}"), LOG_PARSER_10("Max stack trace lines field cannot be less than 0"), LOG_PARSER_11("Error compiling grok pattern definition {}, reason {}"), ; private final String msg; Errors(String msg) { this.msg = msg; } @Override public String getCode() { return name(); } @Override public String getMessage() { return msg; } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-codeartifact/src/main/java/com/amazonaws/services/codeartifact/model/DisposePackageVersionsResult.java
13278
/* * Copyright 2017-2022 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.codeartifact.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/DisposePackageVersions" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DisposePackageVersionsResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * A list of the package versions that were successfully disposed. * </p> */ private java.util.Map<String, SuccessfulPackageVersionInfo> successfulVersions; /** * <p> * A <code>PackageVersionError</code> object that contains a map of errors codes for the disposed package versions * that failed. The possible error codes are: * </p> * <ul> * <li> * <p> * <code>ALREADY_EXISTS</code> * </p> * </li> * <li> * <p> * <code>MISMATCHED_REVISION</code> * </p> * </li> * <li> * <p> * <code>MISMATCHED_STATUS</code> * </p> * </li> * <li> * <p> * <code>NOT_ALLOWED</code> * </p> * </li> * <li> * <p> * <code>NOT_FOUND</code> * </p> * </li> * <li> * <p> * <code>SKIPPED</code> * </p> * </li> * </ul> */ private java.util.Map<String, PackageVersionError> failedVersions; /** * <p> * A list of the package versions that were successfully disposed. * </p> * * @return A list of the package versions that were successfully disposed. */ public java.util.Map<String, SuccessfulPackageVersionInfo> getSuccessfulVersions() { return successfulVersions; } /** * <p> * A list of the package versions that were successfully disposed. * </p> * * @param successfulVersions * A list of the package versions that were successfully disposed. */ public void setSuccessfulVersions(java.util.Map<String, SuccessfulPackageVersionInfo> successfulVersions) { this.successfulVersions = successfulVersions; } /** * <p> * A list of the package versions that were successfully disposed. * </p> * * @param successfulVersions * A list of the package versions that were successfully disposed. * @return Returns a reference to this object so that method calls can be chained together. */ public DisposePackageVersionsResult withSuccessfulVersions(java.util.Map<String, SuccessfulPackageVersionInfo> successfulVersions) { setSuccessfulVersions(successfulVersions); return this; } /** * Add a single SuccessfulVersions entry * * @see DisposePackageVersionsResult#withSuccessfulVersions * @returns a reference to this object so that method calls can be chained together. */ public DisposePackageVersionsResult addSuccessfulVersionsEntry(String key, SuccessfulPackageVersionInfo value) { if (null == this.successfulVersions) { this.successfulVersions = new java.util.HashMap<String, SuccessfulPackageVersionInfo>(); } if (this.successfulVersions.containsKey(key)) throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided."); this.successfulVersions.put(key, value); return this; } /** * Removes all the entries added into SuccessfulVersions. * * @return Returns a reference to this object so that method calls can be chained together. */ public DisposePackageVersionsResult clearSuccessfulVersionsEntries() { this.successfulVersions = null; return this; } /** * <p> * A <code>PackageVersionError</code> object that contains a map of errors codes for the disposed package versions * that failed. The possible error codes are: * </p> * <ul> * <li> * <p> * <code>ALREADY_EXISTS</code> * </p> * </li> * <li> * <p> * <code>MISMATCHED_REVISION</code> * </p> * </li> * <li> * <p> * <code>MISMATCHED_STATUS</code> * </p> * </li> * <li> * <p> * <code>NOT_ALLOWED</code> * </p> * </li> * <li> * <p> * <code>NOT_FOUND</code> * </p> * </li> * <li> * <p> * <code>SKIPPED</code> * </p> * </li> * </ul> * * @return A <code>PackageVersionError</code> object that contains a map of errors codes for the disposed package * versions that failed. The possible error codes are: </p> * <ul> * <li> * <p> * <code>ALREADY_EXISTS</code> * </p> * </li> * <li> * <p> * <code>MISMATCHED_REVISION</code> * </p> * </li> * <li> * <p> * <code>MISMATCHED_STATUS</code> * </p> * </li> * <li> * <p> * <code>NOT_ALLOWED</code> * </p> * </li> * <li> * <p> * <code>NOT_FOUND</code> * </p> * </li> * <li> * <p> * <code>SKIPPED</code> * </p> * </li> */ public java.util.Map<String, PackageVersionError> getFailedVersions() { return failedVersions; } /** * <p> * A <code>PackageVersionError</code> object that contains a map of errors codes for the disposed package versions * that failed. The possible error codes are: * </p> * <ul> * <li> * <p> * <code>ALREADY_EXISTS</code> * </p> * </li> * <li> * <p> * <code>MISMATCHED_REVISION</code> * </p> * </li> * <li> * <p> * <code>MISMATCHED_STATUS</code> * </p> * </li> * <li> * <p> * <code>NOT_ALLOWED</code> * </p> * </li> * <li> * <p> * <code>NOT_FOUND</code> * </p> * </li> * <li> * <p> * <code>SKIPPED</code> * </p> * </li> * </ul> * * @param failedVersions * A <code>PackageVersionError</code> object that contains a map of errors codes for the disposed package * versions that failed. The possible error codes are: </p> * <ul> * <li> * <p> * <code>ALREADY_EXISTS</code> * </p> * </li> * <li> * <p> * <code>MISMATCHED_REVISION</code> * </p> * </li> * <li> * <p> * <code>MISMATCHED_STATUS</code> * </p> * </li> * <li> * <p> * <code>NOT_ALLOWED</code> * </p> * </li> * <li> * <p> * <code>NOT_FOUND</code> * </p> * </li> * <li> * <p> * <code>SKIPPED</code> * </p> * </li> */ public void setFailedVersions(java.util.Map<String, PackageVersionError> failedVersions) { this.failedVersions = failedVersions; } /** * <p> * A <code>PackageVersionError</code> object that contains a map of errors codes for the disposed package versions * that failed. The possible error codes are: * </p> * <ul> * <li> * <p> * <code>ALREADY_EXISTS</code> * </p> * </li> * <li> * <p> * <code>MISMATCHED_REVISION</code> * </p> * </li> * <li> * <p> * <code>MISMATCHED_STATUS</code> * </p> * </li> * <li> * <p> * <code>NOT_ALLOWED</code> * </p> * </li> * <li> * <p> * <code>NOT_FOUND</code> * </p> * </li> * <li> * <p> * <code>SKIPPED</code> * </p> * </li> * </ul> * * @param failedVersions * A <code>PackageVersionError</code> object that contains a map of errors codes for the disposed package * versions that failed. The possible error codes are: </p> * <ul> * <li> * <p> * <code>ALREADY_EXISTS</code> * </p> * </li> * <li> * <p> * <code>MISMATCHED_REVISION</code> * </p> * </li> * <li> * <p> * <code>MISMATCHED_STATUS</code> * </p> * </li> * <li> * <p> * <code>NOT_ALLOWED</code> * </p> * </li> * <li> * <p> * <code>NOT_FOUND</code> * </p> * </li> * <li> * <p> * <code>SKIPPED</code> * </p> * </li> * @return Returns a reference to this object so that method calls can be chained together. */ public DisposePackageVersionsResult withFailedVersions(java.util.Map<String, PackageVersionError> failedVersions) { setFailedVersions(failedVersions); return this; } /** * Add a single FailedVersions entry * * @see DisposePackageVersionsResult#withFailedVersions * @returns a reference to this object so that method calls can be chained together. */ public DisposePackageVersionsResult addFailedVersionsEntry(String key, PackageVersionError value) { if (null == this.failedVersions) { this.failedVersions = new java.util.HashMap<String, PackageVersionError>(); } if (this.failedVersions.containsKey(key)) throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided."); this.failedVersions.put(key, value); return this; } /** * Removes all the entries added into FailedVersions. * * @return Returns a reference to this object so that method calls can be chained together. */ public DisposePackageVersionsResult clearFailedVersionsEntries() { this.failedVersions = null; return this; } /** * 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("{"); if (getSuccessfulVersions() != null) sb.append("SuccessfulVersions: ").append(getSuccessfulVersions()).append(","); if (getFailedVersions() != null) sb.append("FailedVersions: ").append(getFailedVersions()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DisposePackageVersionsResult == false) return false; DisposePackageVersionsResult other = (DisposePackageVersionsResult) obj; if (other.getSuccessfulVersions() == null ^ this.getSuccessfulVersions() == null) return false; if (other.getSuccessfulVersions() != null && other.getSuccessfulVersions().equals(this.getSuccessfulVersions()) == false) return false; if (other.getFailedVersions() == null ^ this.getFailedVersions() == null) return false; if (other.getFailedVersions() != null && other.getFailedVersions().equals(this.getFailedVersions()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getSuccessfulVersions() == null) ? 0 : getSuccessfulVersions().hashCode()); hashCode = prime * hashCode + ((getFailedVersions() == null) ? 0 : getFailedVersions().hashCode()); return hashCode; } @Override public DisposePackageVersionsResult clone() { try { return (DisposePackageVersionsResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
apache-2.0
zhenshengcai/floodlight-hardware
src/main/java/net/floodlightcontroller/core/web/CounterResource.java
3230
/** * Copyright 2011, Big Switch Networks, Inc. * Originally created by David Erickson, Stanford University * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * 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.floodlightcontroller.core.web; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import net.floodlightcontroller.debugcounter.DebugCounterResource; import org.restlet.resource.Get; public class CounterResource extends CounterResourceBase { @Get("json") public Map<String, Object> retrieve() { String counterTitle = (String) getRequestAttributes().get(CoreWebRoutable.STR_CTR_TITLE); String counterModule = (String) getRequestAttributes().get(CoreWebRoutable.STR_CTR_MODULE); Map<String, Object> model = new HashMap<String, Object>(); long dc; if (counterModule.equalsIgnoreCase(CoreWebRoutable.STR_ALL)) { // get all modules' counters List<DebugCounterResource> counters = this.debugCounterService.getAllCounterValues(); if (counters != null) { Iterator<DebugCounterResource> it = counters.iterator(); while (it.hasNext()) { DebugCounterResource dcr = it.next(); String counterName = dcr.getCounterHierarchy(); dc = dcr.getCounterValue(); model.put(counterName, dc); } } } else if (counterTitle.equalsIgnoreCase(CoreWebRoutable.STR_ALL)) { // get all counters for a specifc module List<DebugCounterResource> counters = this.debugCounterService.getModuleCounterValues(counterModule); if (counters != null) { Iterator<DebugCounterResource> it = counters.iterator(); while (it.hasNext()) { DebugCounterResource dcr = it.next(); String counterName = dcr.getCounterHierarchy(); dc = dcr.getCounterValue(); model.put(counterName, dc); } } } else { // get a specific counter (or subset of counters) for a specific module List<DebugCounterResource> counters = this.debugCounterService.getCounterHierarchy(counterModule, counterTitle); if (counters != null) { Iterator<DebugCounterResource> it = counters.iterator(); while (it.hasNext()) { DebugCounterResource dcr = it.next(); String counterName = dcr.getCounterHierarchy(); dc = dcr.getCounterValue(); model.put(counterName, dc); } } } return model; } }
apache-2.0
hyz0906/syzkaller
sys/align.go
3357
// Copyright 2015 syzkaller project authors. All rights reserved. // Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file. package sys import ( "fmt" ) func initAlign() { var rec func(t Type) rec = func(t Type) { switch t1 := t.(type) { case *PtrType: rec(t1.Type) case *ArrayType: rec(t1.Type) case *StructType: if !t1.padded { t1.padded = true for _, f := range t1.Fields { rec(f) } t1.Varlen() // dummy call to initialize t1.varlen markBitfields(t1) addAlignment(t1) } case *UnionType: for _, opt := range t1.Options { rec(opt) } } } for _, s := range keyedStructs { rec(s) } } func setBitfieldOffset(t Type, offset uintptr, last bool) { switch t1 := t.(type) { case *IntType: t1.BitfieldOff = offset t1.BitfieldLst = last case *ConstType: t1.BitfieldOff = offset t1.BitfieldLst = last case *LenType: t1.BitfieldOff = offset t1.BitfieldLst = last case *FlagsType: t1.BitfieldOff = offset t1.BitfieldLst = last case *ProcType: t1.BitfieldOff = offset t1.BitfieldLst = last default: panic(fmt.Sprintf("type %+v can't be a bitfield", t1)) } } func markBitfields(t *StructType) { var bfOffset uintptr for i, f := range t.Fields { if f.BitfieldLength() == 0 { continue } off, last := bfOffset, false bfOffset += f.BitfieldLength() if i == len(t.Fields)-1 || // Last bitfield in a group, if last field of the struct... t.Fields[i+1].BitfieldLength() == 0 || // or next field is not a bitfield... f.Size() != t.Fields[i+1].Size() || // or next field is of different size... bfOffset+t.Fields[i+1].BitfieldLength() > f.Size()*8 { // or next field does not fit into the current group. last, bfOffset = true, 0 } setBitfieldOffset(f, off, last) } } func addAlignment(t *StructType) { if t.packed { // If a struct is packed, statically sized and has explicitly set alignment, add a padding. if !t.Varlen() && t.align != 0 && t.Size()%t.align != 0 { pad := t.align - t.Size()%t.align t.Fields = append(t.Fields, makePad(pad)) } return } var fields []Type var off uintptr align := t.align for i, f := range t.Fields { a := f.Align() if align < a { align = a } if i > 0 && (t.Fields[i-1].BitfieldLength() == 0 || t.Fields[i-1].BitfieldLast()) { // Append padding if the last field is not a bitfield or it's the last bitfield in a set. if off%a != 0 { pad := a - off%a off += pad fields = append(fields, makePad(pad)) } } if f.Varlen() && i != len(t.Fields)-1 { panic(fmt.Sprintf("variable length field %+v in the middle of a struct %+v", f, t)) } fields = append(fields, f) if (f.BitfieldLength() == 0 || f.BitfieldLast()) && (i != len(t.Fields)-1 || !f.Varlen()) { // Increase offset if the current field is not a bitfield or it's the last bitfield in a set, // except when it's the last field in a struct and has variable length. off += f.Size() } } if align != 0 && off%align != 0 && !t.Varlen() { pad := align - off%align off += pad fields = append(fields, makePad(pad)) } t.Fields = fields } func makePad(sz uintptr) Type { return &ConstType{ IntTypeCommon: IntTypeCommon{ TypeCommon: TypeCommon{TypeName: "pad", IsOptional: false}, TypeSize: sz, }, Val: 0, IsPad: true, } }
apache-2.0
googleapis/java-security-private-ca
proto-google-cloud-security-private-ca-v1beta1/src/main/java/com/google/cloud/security/privateca/v1beta1/KeyUsageOrBuilder.java
5341
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/security/privateca/v1beta1/resources.proto package com.google.cloud.security.privateca.v1beta1; public interface KeyUsageOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.security.privateca.v1beta1.KeyUsage) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * Describes high-level ways in which a key may be used. * </pre> * * <code>.google.cloud.security.privateca.v1beta1.KeyUsage.KeyUsageOptions base_key_usage = 1; * </code> * * @return Whether the baseKeyUsage field is set. */ boolean hasBaseKeyUsage(); /** * * * <pre> * Describes high-level ways in which a key may be used. * </pre> * * <code>.google.cloud.security.privateca.v1beta1.KeyUsage.KeyUsageOptions base_key_usage = 1; * </code> * * @return The baseKeyUsage. */ com.google.cloud.security.privateca.v1beta1.KeyUsage.KeyUsageOptions getBaseKeyUsage(); /** * * * <pre> * Describes high-level ways in which a key may be used. * </pre> * * <code>.google.cloud.security.privateca.v1beta1.KeyUsage.KeyUsageOptions base_key_usage = 1; * </code> */ com.google.cloud.security.privateca.v1beta1.KeyUsage.KeyUsageOptionsOrBuilder getBaseKeyUsageOrBuilder(); /** * * * <pre> * Detailed scenarios in which a key may be used. * </pre> * * <code> * .google.cloud.security.privateca.v1beta1.KeyUsage.ExtendedKeyUsageOptions extended_key_usage = 2; * </code> * * @return Whether the extendedKeyUsage field is set. */ boolean hasExtendedKeyUsage(); /** * * * <pre> * Detailed scenarios in which a key may be used. * </pre> * * <code> * .google.cloud.security.privateca.v1beta1.KeyUsage.ExtendedKeyUsageOptions extended_key_usage = 2; * </code> * * @return The extendedKeyUsage. */ com.google.cloud.security.privateca.v1beta1.KeyUsage.ExtendedKeyUsageOptions getExtendedKeyUsage(); /** * * * <pre> * Detailed scenarios in which a key may be used. * </pre> * * <code> * .google.cloud.security.privateca.v1beta1.KeyUsage.ExtendedKeyUsageOptions extended_key_usage = 2; * </code> */ com.google.cloud.security.privateca.v1beta1.KeyUsage.ExtendedKeyUsageOptionsOrBuilder getExtendedKeyUsageOrBuilder(); /** * * * <pre> * Used to describe extended key usages that are not listed in the * [KeyUsage.ExtendedKeyUsageOptions][google.cloud.security.privateca.v1beta1.KeyUsage.ExtendedKeyUsageOptions] message. * </pre> * * <code> * repeated .google.cloud.security.privateca.v1beta1.ObjectId unknown_extended_key_usages = 3; * </code> */ java.util.List<com.google.cloud.security.privateca.v1beta1.ObjectId> getUnknownExtendedKeyUsagesList(); /** * * * <pre> * Used to describe extended key usages that are not listed in the * [KeyUsage.ExtendedKeyUsageOptions][google.cloud.security.privateca.v1beta1.KeyUsage.ExtendedKeyUsageOptions] message. * </pre> * * <code> * repeated .google.cloud.security.privateca.v1beta1.ObjectId unknown_extended_key_usages = 3; * </code> */ com.google.cloud.security.privateca.v1beta1.ObjectId getUnknownExtendedKeyUsages(int index); /** * * * <pre> * Used to describe extended key usages that are not listed in the * [KeyUsage.ExtendedKeyUsageOptions][google.cloud.security.privateca.v1beta1.KeyUsage.ExtendedKeyUsageOptions] message. * </pre> * * <code> * repeated .google.cloud.security.privateca.v1beta1.ObjectId unknown_extended_key_usages = 3; * </code> */ int getUnknownExtendedKeyUsagesCount(); /** * * * <pre> * Used to describe extended key usages that are not listed in the * [KeyUsage.ExtendedKeyUsageOptions][google.cloud.security.privateca.v1beta1.KeyUsage.ExtendedKeyUsageOptions] message. * </pre> * * <code> * repeated .google.cloud.security.privateca.v1beta1.ObjectId unknown_extended_key_usages = 3; * </code> */ java.util.List<? extends com.google.cloud.security.privateca.v1beta1.ObjectIdOrBuilder> getUnknownExtendedKeyUsagesOrBuilderList(); /** * * * <pre> * Used to describe extended key usages that are not listed in the * [KeyUsage.ExtendedKeyUsageOptions][google.cloud.security.privateca.v1beta1.KeyUsage.ExtendedKeyUsageOptions] message. * </pre> * * <code> * repeated .google.cloud.security.privateca.v1beta1.ObjectId unknown_extended_key_usages = 3; * </code> */ com.google.cloud.security.privateca.v1beta1.ObjectIdOrBuilder getUnknownExtendedKeyUsagesOrBuilder(int index); }
apache-2.0
PATRIC3/p3_solr
solr/solrj/src/java/org/apache/solr/common/util/JavaBinCodec.java
27894
/* * 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.solr.common.util; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.solr.common.EnumFieldValue; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.SolrInputField; import org.noggit.CharArr; /** * The class is designed to optimaly serialize/deserialize any supported types in Solr response. As we know there are only a limited type of * items this class can do it with very minimal amount of payload and code. There are 15 known types and if there is an * object in the object tree which does not fall into these types, It must be converted to one of these. Implement an * ObjectResolver and pass it over It is expected that this class is used on both end of the pipes. The class has one * read method and one write method for each of the datatypes * <p> * Note -- Never re-use an instance of this class for more than one marshal or unmarshall operation. Always create a new * instance. */ public class JavaBinCodec { public static final byte NULL = 0, BOOL_TRUE = 1, BOOL_FALSE = 2, BYTE = 3, SHORT = 4, DOUBLE = 5, INT = 6, LONG = 7, FLOAT = 8, DATE = 9, MAP = 10, SOLRDOC = 11, SOLRDOCLST = 12, BYTEARR = 13, ITERATOR = 14, /** * this is a special tag signals an end. No value is associated with it */ END = 15, SOLRINPUTDOC = 16, SOLRINPUTDOC_CHILDS = 17, ENUM_FIELD_VALUE = 18, MAP_ENTRY = 19, // types that combine tag + length (or other info) in a single byte TAG_AND_LEN = (byte) (1 << 5), STR = (byte) (1 << 5), SINT = (byte) (2 << 5), SLONG = (byte) (3 << 5), ARR = (byte) (4 << 5), // ORDERED_MAP = (byte) (5 << 5), // SimpleOrderedMap (a NamedList subclass, and more common) NAMED_LST = (byte) (6 << 5), // NamedList EXTERN_STRING = (byte) (7 << 5); private static final int MAX_UTF8_SIZE_FOR_ARRAY_GROW_STRATEGY = 65536; private static byte VERSION = 2; private final ObjectResolver resolver; protected FastOutputStream daos; private StringCache stringCache; private WritableDocFields writableDocFields; public JavaBinCodec() { resolver =null; writableDocFields =null; } public JavaBinCodec(ObjectResolver resolver) { this(resolver, null); } public JavaBinCodec setWritableDocFields(WritableDocFields writableDocFields){ this.writableDocFields = writableDocFields; return this; } public JavaBinCodec(ObjectResolver resolver, StringCache stringCache) { this.resolver = resolver; this.stringCache = stringCache; } public ObjectResolver getResolver() { return resolver; } public void marshal(Object nl, OutputStream os) throws IOException { init(FastOutputStream.wrap(os)); try { daos.writeByte(VERSION); writeVal(nl); } finally { daos.flushBuffer(); } } /** expert: sets a new output stream */ public void init(FastOutputStream os) { daos = os; } byte version; public Object unmarshal(InputStream is) throws IOException { FastInputStream dis = FastInputStream.wrap(is); version = dis.readByte(); if (version != VERSION) { throw new RuntimeException("Invalid version (expected " + VERSION + ", but " + version + ") or the data in not in 'javabin' format"); } return readVal(dis); } public SimpleOrderedMap<Object> readOrderedMap(DataInputInputStream dis) throws IOException { int sz = readSize(dis); SimpleOrderedMap<Object> nl = new SimpleOrderedMap<>(); for (int i = 0; i < sz; i++) { String name = (String) readVal(dis); Object val = readVal(dis); nl.add(name, val); } return nl; } public NamedList<Object> readNamedList(DataInputInputStream dis) throws IOException { int sz = readSize(dis); NamedList<Object> nl = new NamedList<>(); for (int i = 0; i < sz; i++) { String name = (String) readVal(dis); Object val = readVal(dis); nl.add(name, val); } return nl; } public void writeNamedList(NamedList<?> nl) throws IOException { writeTag(nl instanceof SimpleOrderedMap ? ORDERED_MAP : NAMED_LST, nl.size()); for (int i = 0; i < nl.size(); i++) { String name = nl.getName(i); writeExternString(name); Object val = nl.getVal(i); writeVal(val); } } public void writeVal(Object val) throws IOException { if (writeKnownType(val)) { return; } else { ObjectResolver resolver = null; if(val instanceof ObjectResolver) { resolver = (ObjectResolver)val; } else { resolver = this.resolver; } if (resolver != null) { Object tmpVal = resolver.resolve(val, this); if (tmpVal == null) return; // null means the resolver took care of it fully if (writeKnownType(tmpVal)) return; } } writeVal(val.getClass().getName() + ':' + val.toString()); } protected static final Object END_OBJ = new Object(); protected byte tagByte; public Object readVal(DataInputInputStream dis) throws IOException { tagByte = dis.readByte(); // if ((tagByte & 0xe0) == 0) { // if top 3 bits are clear, this is a normal tag // OK, try type + size in single byte switch (tagByte >>> 5) { case STR >>> 5: return readStr(dis); case SINT >>> 5: return readSmallInt(dis); case SLONG >>> 5: return readSmallLong(dis); case ARR >>> 5: return readArray(dis); case ORDERED_MAP >>> 5: return readOrderedMap(dis); case NAMED_LST >>> 5: return readNamedList(dis); case EXTERN_STRING >>> 5: return readExternString(dis); } switch (tagByte) { case NULL: return null; case DATE: return new Date(dis.readLong()); case INT: return dis.readInt(); case BOOL_TRUE: return Boolean.TRUE; case BOOL_FALSE: return Boolean.FALSE; case FLOAT: return dis.readFloat(); case DOUBLE: return dis.readDouble(); case LONG: return dis.readLong(); case BYTE: return dis.readByte(); case SHORT: return dis.readShort(); case MAP: return readMap(dis); case SOLRDOC: return readSolrDocument(dis); case SOLRDOCLST: return readSolrDocumentList(dis); case BYTEARR: return readByteArray(dis); case ITERATOR: return readIterator(dis); case END: return END_OBJ; case SOLRINPUTDOC: return readSolrInputDocument(dis); case ENUM_FIELD_VALUE: return readEnumFieldValue(dis); case MAP_ENTRY: return readMapEntry(dis); } throw new RuntimeException("Unknown type " + tagByte); } public boolean writeKnownType(Object val) throws IOException { if (writePrimitive(val)) return true; if (val instanceof NamedList) { writeNamedList((NamedList<?>) val); return true; } if (val instanceof SolrDocumentList) { // SolrDocumentList is a List, so must come before List check writeSolrDocumentList((SolrDocumentList) val); return true; } if (val instanceof Collection) { writeArray((Collection) val); return true; } if (val instanceof Object[]) { writeArray((Object[]) val); return true; } if (val instanceof SolrDocument) { //this needs special treatment to know which fields are to be written writeSolrDocument((SolrDocument) val); return true; } if (val instanceof SolrInputDocument) { writeSolrInputDocument((SolrInputDocument)val); return true; } if (val instanceof Map) { writeMap((Map) val); return true; } if (val instanceof Iterator) { writeIterator((Iterator) val); return true; } if (val instanceof Path) { writeStr(((Path) val).toAbsolutePath().toString()); return true; } if (val instanceof Iterable) { writeIterator(((Iterable) val).iterator()); return true; } if (val instanceof EnumFieldValue) { writeEnumFieldValue((EnumFieldValue) val); return true; } if (val instanceof Map.Entry) { writeMapEntry((Map.Entry)val); return true; } return false; } public void writeTag(byte tag) throws IOException { daos.writeByte(tag); } public void writeTag(byte tag, int size) throws IOException { if ((tag & 0xe0) != 0) { if (size < 0x1f) { daos.writeByte(tag | size); } else { daos.writeByte(tag | 0x1f); writeVInt(size - 0x1f, daos); } } else { daos.writeByte(tag); writeVInt(size, daos); } } public void writeByteArray(byte[] arr, int offset, int len) throws IOException { writeTag(BYTEARR, len); daos.write(arr, offset, len); } public byte[] readByteArray(DataInputInputStream dis) throws IOException { byte[] arr = new byte[readVInt(dis)]; dis.readFully(arr); return arr; } //use this to ignore the writable interface because , child docs will ignore the fl flag // is it a good design? private boolean ignoreWritable =false; public void writeSolrDocument(SolrDocument doc) throws IOException { List<SolrDocument> children = doc.getChildDocuments(); int fieldsCount = 0; if(writableDocFields == null || writableDocFields.wantsAllFields() || ignoreWritable){ fieldsCount = doc.size(); } else { for (Entry<String, Object> e : doc) { if(toWrite(e.getKey())) fieldsCount++; } } int sz = fieldsCount + (children==null ? 0 : children.size()); writeTag(SOLRDOC); writeTag(ORDERED_MAP, sz); for (Map.Entry<String, Object> entry : doc) { String name = entry.getKey(); if(toWrite(name)) { writeExternString(name); Object val = entry.getValue(); writeVal(val); } } if (children != null) { try { ignoreWritable = true; for (SolrDocument child : children) { writeSolrDocument(child); } } finally { ignoreWritable = false; } } } protected boolean toWrite(String key) { return writableDocFields == null || ignoreWritable || writableDocFields.isWritable(key); } public SolrDocument readSolrDocument(DataInputInputStream dis) throws IOException { tagByte = dis.readByte(); int size = readSize(dis); SolrDocument doc = new SolrDocument(); for (int i = 0; i < size; i++) { String fieldName; Object obj = readVal(dis); // could be a field name, or a child document if (obj instanceof SolrDocument) { doc.addChildDocument((SolrDocument)obj); continue; } else { fieldName = (String)obj; } Object fieldVal = readVal(dis); doc.setField(fieldName, fieldVal); } return doc; } public SolrDocumentList readSolrDocumentList(DataInputInputStream dis) throws IOException { SolrDocumentList solrDocs = new SolrDocumentList(); List list = (List) readVal(dis); solrDocs.setNumFound((Long) list.get(0)); solrDocs.setStart((Long) list.get(1)); solrDocs.setMaxScore((Float) list.get(2)); @SuppressWarnings("unchecked") List<SolrDocument> l = (List<SolrDocument>) readVal(dis); solrDocs.addAll(l); return solrDocs; } public void writeSolrDocumentList(SolrDocumentList docs) throws IOException { writeTag(SOLRDOCLST); List<Number> l = new ArrayList<>(3); l.add(docs.getNumFound()); l.add(docs.getStart()); l.add(docs.getMaxScore()); writeArray(l); writeArray(docs); } public SolrInputDocument readSolrInputDocument(DataInputInputStream dis) throws IOException { int sz = readVInt(dis); float docBoost = (Float)readVal(dis); SolrInputDocument sdoc = new SolrInputDocument(); sdoc.setDocumentBoost(docBoost); for (int i = 0; i < sz; i++) { float boost = 1.0f; String fieldName; Object obj = readVal(dis); // could be a boost, a field name, or a child document if (obj instanceof Float) { boost = (Float)obj; fieldName = (String)readVal(dis); } else if (obj instanceof SolrInputDocument) { sdoc.addChildDocument((SolrInputDocument)obj); continue; } else { fieldName = (String)obj; } Object fieldVal = readVal(dis); sdoc.setField(fieldName, fieldVal, boost); } return sdoc; } public void writeSolrInputDocument(SolrInputDocument sdoc) throws IOException { List<SolrInputDocument> children = sdoc.getChildDocuments(); int sz = sdoc.size() + (children==null ? 0 : children.size()); writeTag(SOLRINPUTDOC, sz); writeFloat(sdoc.getDocumentBoost()); for (SolrInputField inputField : sdoc.values()) { if (inputField.getBoost() != 1.0f) { writeFloat(inputField.getBoost()); } writeExternString(inputField.getName()); writeVal(inputField.getValue()); } if (children != null) { for (SolrInputDocument child : children) { writeSolrInputDocument(child); } } } public Map<Object,Object> readMap(DataInputInputStream dis) throws IOException { int sz = readVInt(dis); Map<Object,Object> m = new LinkedHashMap<>(); for (int i = 0; i < sz; i++) { Object key = readVal(dis); Object val = readVal(dis); m.put(key, val); } return m; } public void writeIterator(Iterator iter) throws IOException { writeTag(ITERATOR); while (iter.hasNext()) { writeVal(iter.next()); } writeVal(END_OBJ); } public List<Object> readIterator(DataInputInputStream fis) throws IOException { ArrayList<Object> l = new ArrayList<>(); while (true) { Object o = readVal(fis); if (o == END_OBJ) break; l.add(o); } return l; } public void writeArray(List l) throws IOException { writeTag(ARR, l.size()); for (int i = 0; i < l.size(); i++) { writeVal(l.get(i)); } } public void writeArray(Collection coll) throws IOException { writeTag(ARR, coll.size()); for (Object o : coll) { writeVal(o); } } public void writeArray(Object[] arr) throws IOException { writeTag(ARR, arr.length); for (int i = 0; i < arr.length; i++) { Object o = arr[i]; writeVal(o); } } public List<Object> readArray(DataInputInputStream dis) throws IOException { int sz = readSize(dis); ArrayList<Object> l = new ArrayList<>(sz); for (int i = 0; i < sz; i++) { l.add(readVal(dis)); } return l; } /** * write {@link EnumFieldValue} as tag+int value+string value * @param enumFieldValue to write */ public void writeEnumFieldValue(EnumFieldValue enumFieldValue) throws IOException { writeTag(ENUM_FIELD_VALUE); writeInt(enumFieldValue.toInt()); writeStr(enumFieldValue.toString()); } public void writeMapEntry(Entry<Object,Object> val) throws IOException { writeTag(MAP_ENTRY); writeVal(val.getKey()); writeVal(val.getValue()); } /** * read {@link EnumFieldValue} (int+string) from input stream * @param dis data input stream * @return {@link EnumFieldValue} */ public EnumFieldValue readEnumFieldValue(DataInputInputStream dis) throws IOException { Integer intValue = (Integer) readVal(dis); String stringValue = (String) readVal(dis); return new EnumFieldValue(intValue, stringValue); } public Map.Entry<Object,Object> readMapEntry(DataInputInputStream dis) throws IOException { final Object key = readVal(dis); final Object value = readVal(dis); return new Map.Entry<Object,Object>() { @Override public Object getKey() { return key; } @Override public Object getValue() { return value; } @Override public String toString() { return "MapEntry[" + key + ":" + value + "]"; } @Override public Object setValue(Object value) { throw new UnsupportedOperationException(); } @Override public int hashCode() { int result = 31; result *=31 + getKey().hashCode(); result *=31 + getValue().hashCode(); return result; } @Override public boolean equals(Object obj) { if(this == obj) { return true; } if(!(obj instanceof Entry)) { return false; } Map.Entry<Object, Object> entry = (Entry<Object, Object>) obj; return (this.getKey().equals(entry.getKey()) && this.getValue().equals(entry.getValue())); } }; } /** * write the string as tag+length, with length being the number of UTF-8 bytes */ public void writeStr(String s) throws IOException { if (s == null) { writeTag(NULL); return; } int end = s.length(); int maxSize = end * ByteUtils.MAX_UTF8_BYTES_PER_CHAR; if (maxSize <= MAX_UTF8_SIZE_FOR_ARRAY_GROW_STRATEGY) { if (bytes == null || bytes.length < maxSize) bytes = new byte[maxSize]; int sz = ByteUtils.UTF16toUTF8(s, 0, end, bytes, 0); writeTag(STR, sz); daos.write(bytes, 0, sz); } else { // double pass logic for large strings, see SOLR-7971 int sz = ByteUtils.calcUTF16toUTF8Length(s, 0, end); writeTag(STR, sz); if (bytes == null || bytes.length < 8192) bytes = new byte[8192]; ByteUtils.writeUTF16toUTF8(s, 0, end, daos, bytes); } } byte[] bytes; CharArr arr = new CharArr(); private StringBytes bytesRef = new StringBytes(bytes,0,0); public String readStr(DataInputInputStream dis) throws IOException { return readStr(dis,null); } public String readStr(DataInputInputStream dis, StringCache stringCache) throws IOException { int sz = readSize(dis); if (bytes == null || bytes.length < sz) bytes = new byte[sz]; dis.readFully(bytes, 0, sz); if (stringCache != null) { return stringCache.get(bytesRef.reset(bytes, 0, sz)); } else { arr.reset(); ByteUtils.UTF8toUTF16(bytes, 0, sz, arr); return arr.toString(); } } public void writeInt(int val) throws IOException { if (val > 0) { int b = SINT | (val & 0x0f); if (val >= 0x0f) { b |= 0x10; daos.writeByte(b); writeVInt(val >>> 4, daos); } else { daos.writeByte(b); } } else { daos.writeByte(INT); daos.writeInt(val); } } public int readSmallInt(DataInputInputStream dis) throws IOException { int v = tagByte & 0x0F; if ((tagByte & 0x10) != 0) v = (readVInt(dis) << 4) | v; return v; } public void writeLong(long val) throws IOException { if ((val & 0xff00000000000000L) == 0) { int b = SLONG | ((int) val & 0x0f); if (val >= 0x0f) { b |= 0x10; daos.writeByte(b); writeVLong(val >>> 4, daos); } else { daos.writeByte(b); } } else { daos.writeByte(LONG); daos.writeLong(val); } } public long readSmallLong(DataInputInputStream dis) throws IOException { long v = tagByte & 0x0F; if ((tagByte & 0x10) != 0) v = (readVLong(dis) << 4) | v; return v; } public void writeFloat(float val) throws IOException { daos.writeByte(FLOAT); daos.writeFloat(val); } public boolean writePrimitive(Object val) throws IOException { if (val == null) { daos.writeByte(NULL); return true; } else if (val instanceof String) { writeStr((String) val); return true; } else if (val instanceof Number) { if (val instanceof Integer) { writeInt(((Integer) val).intValue()); return true; } else if (val instanceof Long) { writeLong(((Long) val).longValue()); return true; } else if (val instanceof Float) { writeFloat(((Float) val).floatValue()); return true; } else if (val instanceof Double) { daos.writeByte(DOUBLE); daos.writeDouble(((Double) val).doubleValue()); return true; } else if (val instanceof Byte) { daos.writeByte(BYTE); daos.writeByte(((Byte) val).intValue()); return true; } else if (val instanceof Short) { daos.writeByte(SHORT); daos.writeShort(((Short) val).intValue()); return true; } return false; } else if (val instanceof Date) { daos.writeByte(DATE); daos.writeLong(((Date) val).getTime()); return true; } else if (val instanceof Boolean) { if ((Boolean) val) daos.writeByte(BOOL_TRUE); else daos.writeByte(BOOL_FALSE); return true; } else if (val instanceof byte[]) { writeByteArray((byte[]) val, 0, ((byte[]) val).length); return true; } else if (val instanceof ByteBuffer) { ByteBuffer buf = (ByteBuffer) val; writeByteArray(buf.array(),buf.position(),buf.limit() - buf.position()); return true; } else if (val == END_OBJ) { writeTag(END); return true; } return false; } public void writeMap(Map<?,?> val) throws IOException { writeTag(MAP, val.size()); for (Map.Entry<?,?> entry : val.entrySet()) { Object key = entry.getKey(); if (key instanceof String) { writeExternString((String) key); } else { writeVal(key); } writeVal(entry.getValue()); } } public int readSize(DataInputInputStream in) throws IOException { int sz = tagByte & 0x1f; if (sz == 0x1f) sz += readVInt(in); return sz; } /** * Special method for variable length int (copied from lucene). Usually used for writing the length of a * collection/array/map In most of the cases the length can be represented in one byte (length &lt; 127) so it saves 3 * bytes/object * * @throws IOException If there is a low-level I/O error. */ public static void writeVInt(int i, FastOutputStream out) throws IOException { while ((i & ~0x7F) != 0) { out.writeByte((byte) ((i & 0x7f) | 0x80)); i >>>= 7; } out.writeByte((byte) i); } /** * The counterpart for {@link #writeVInt(int, FastOutputStream)} * * @throws IOException If there is a low-level I/O error. */ public static int readVInt(DataInputInputStream in) throws IOException { byte b = in.readByte(); int i = b & 0x7F; for (int shift = 7; (b & 0x80) != 0; shift += 7) { b = in.readByte(); i |= (b & 0x7F) << shift; } return i; } public static void writeVLong(long i, FastOutputStream out) throws IOException { while ((i & ~0x7F) != 0) { out.writeByte((byte) ((i & 0x7f) | 0x80)); i >>>= 7; } out.writeByte((byte) i); } public static long readVLong(DataInputInputStream in) throws IOException { byte b = in.readByte(); long i = b & 0x7F; for (int shift = 7; (b & 0x80) != 0; shift += 7) { b = in.readByte(); i |= (long) (b & 0x7F) << shift; } return i; } private int stringsCount = 0; private Map<String, Integer> stringsMap; private List<String> stringsList; public void writeExternString(String s) throws IOException { if (s == null) { writeTag(NULL); return; } Integer idx = stringsMap == null ? null : stringsMap.get(s); if (idx == null) idx = 0; writeTag(EXTERN_STRING, idx); if (idx == 0) { writeStr(s); if (stringsMap == null) stringsMap = new HashMap<>(); stringsMap.put(s, ++stringsCount); } } public String readExternString(DataInputInputStream fis) throws IOException { int idx = readSize(fis); if (idx != 0) {// idx != 0 is the index of the extern string return stringsList.get(idx - 1); } else {// idx == 0 means it has a string value tagByte = fis.readByte(); String s = readStr(fis, stringCache); if (stringsList == null) stringsList = new ArrayList<>(); stringsList.add(s); return s; } } public static interface ObjectResolver { public Object resolve(Object o, JavaBinCodec codec) throws IOException; } public interface WritableDocFields { public boolean isWritable(String name); public boolean wantsAllFields(); } public static class StringCache { private final Cache<StringBytes, String> cache; public StringCache(Cache<StringBytes, String> cache) { this.cache = cache; } public String get(StringBytes b) { String result = cache.get(b); if (result == null) { //make a copy because the buffer received may be changed later by the caller StringBytes copy = new StringBytes(Arrays.copyOfRange(b.bytes, b.offset, b.offset + b.length), 0, b.length); CharArr arr = new CharArr(); ByteUtils.UTF8toUTF16(b.bytes, b.offset, b.length, arr); result = arr.toString(); cache.put(copy, result); } return result; } } public static class StringBytes { byte[] bytes; /** * Offset of first valid byte. */ int offset; /** * Length of used bytes. */ private int length; private int hash; public StringBytes(byte[] bytes, int offset, int length) { reset(bytes, offset, length); } StringBytes reset(byte[] bytes, int offset, int length) { this.bytes = bytes; this.offset = offset; this.length = length; hash = bytes == null ? 0 : Hash.murmurhash3_x86_32(bytes, offset, length, 0); return this; } @Override public boolean equals(Object other) { if (other == null) { return false; } if (other instanceof StringBytes) { return this.bytesEquals((StringBytes) other); } return false; } boolean bytesEquals(StringBytes other) { assert other != null; if (length == other.length) { int otherUpto = other.offset; final byte[] otherBytes = other.bytes; final int end = offset + length; for (int upto = offset; upto < end; upto++, otherUpto++) { if (bytes[upto] != otherBytes[otherUpto]) { return false; } } return true; } else { return false; } } @Override public int hashCode() { return hash; } } }
apache-2.0
JoyIfBam5/aws-sdk-cpp
aws-cpp-sdk-pinpoint/source/model/GetSegmentExportJobsRequest.cpp
1586
/* * Copyright 2010-2017 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. */ #include <aws/pinpoint/model/GetSegmentExportJobsRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/http/URI.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::Pinpoint::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws::Http; GetSegmentExportJobsRequest::GetSegmentExportJobsRequest() : m_applicationIdHasBeenSet(false), m_pageSizeHasBeenSet(false), m_segmentIdHasBeenSet(false), m_tokenHasBeenSet(false) { } Aws::String GetSegmentExportJobsRequest::SerializePayload() const { return ""; } void GetSegmentExportJobsRequest::AddQueryStringParameters(URI& uri) const { Aws::StringStream ss; if(m_pageSizeHasBeenSet) { ss << m_pageSize; uri.AddQueryStringParameter("page-size", ss.str()); ss.str(""); } if(m_tokenHasBeenSet) { ss << m_token; uri.AddQueryStringParameter("token", ss.str()); ss.str(""); } }
apache-2.0
krivachy/compgs03_mutation_testing
src/main/java/org/apache/commons/collections4/queue/CircularFifoQueue.java
12240
/* * 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.collections4.queue; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.AbstractCollection; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Queue; import org.apache.commons.collections4.BoundedCollection; /** * CircularFifoQueue is a first-in first-out queue with a fixed size that * replaces its oldest element if full. * <p> * The removal order of a {@link CircularFifoQueue} is based on the * insertion order; elements are removed in the same order in which they * were added. The iteration order is the same as the removal order. * <p> * The {@link #add(Object)}, {@link #remove()}, {@link #peek()}, {@link #poll}, * {@link #offer(Object)} operations all perform in constant time. * All other operations perform in linear time or worse. * <p> * This queue prevents null objects from being added. * * @since 4.0 * @version $Id: CircularFifoQueue.java 1543246 2013-11-19 00:36:29Z ggregory $ */ public class CircularFifoQueue<E> extends AbstractCollection<E> implements Queue<E>, BoundedCollection<E>, Serializable { /** Serialization version. */ private static final long serialVersionUID = -8423413834657610406L; /** Underlying storage array. */ private transient E[] elements; /** Array index of first (oldest) queue element. */ private transient int start = 0; /** * Index mod maxElements of the array position following the last queue * element. Queue elements start at elements[start] and "wrap around" * elements[maxElements-1], ending at elements[decrement(end)]. * For example, elements = {c,a,b}, start=1, end=1 corresponds to * the queue [a,b,c]. */ private transient int end = 0; /** Flag to indicate if the queue is currently full. */ private transient boolean full = false; /** Capacity of the queue. */ private final int maxElements; /** * Constructor that creates a queue with the default size of 32. */ public CircularFifoQueue() { this(32); } /** * Constructor that creates a queue with the specified size. * * @param size the size of the queue (cannot be changed) * @throws IllegalArgumentException if the size is &lt; 1 */ @SuppressWarnings("unchecked") public CircularFifoQueue(final int size) { if (size <= 0) { throw new IllegalArgumentException("The size must be greater than 0"); } elements = (E[]) new Object[size]; maxElements = elements.length; } /** * Constructor that creates a queue from the specified collection. * The collection size also sets the queue size. * * @param coll the collection to copy into the queue, may not be null * @throws NullPointerException if the collection is null */ public CircularFifoQueue(final Collection<? extends E> coll) { this(coll.size()); addAll(coll); } //----------------------------------------------------------------------- /** * Write the queue out using a custom routine. * * @param out the output stream * @throws IOException if an I/O error occurs while writing to the output stream */ private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeInt(size()); for (final E e : this) { out.writeObject(e); } } /** * Read the queue in using a custom routine. * * @param in the input stream * @throws IOException if an I/O error occurs while writing to the output stream * @throws ClassNotFoundException if the class of a serialized object can not be found */ @SuppressWarnings("unchecked") private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); elements = (E[]) new Object[maxElements]; final int size = in.readInt(); for (int i = 0; i < size; i++) { elements[i] = (E) in.readObject(); } start = 0; full = size == maxElements; if (full) { end = 0; } else { end = size; } } //----------------------------------------------------------------------- /** * Returns the number of elements stored in the queue. * * @return this queue's size */ @Override public int size() { int size = 0; if (end < start) { size = maxElements - start + end; } else if (end == start) { size = full ? maxElements : 0; } else { size = end - start; } return size; } /** * Returns true if this queue is empty; false otherwise. * * @return true if this queue is empty */ @Override public boolean isEmpty() { return size() == 0; } /** * {@inheritDoc} * <p> * A {@code CircularFifoQueue} can never be full, thus this returns always * {@code false}. * * @return always returns {@code false} */ public boolean isFull() { return false; } private boolean isAtFullCapacity() { return size() == maxElements; } /** * Gets the maximum size of the collection (the bound). * * @return the maximum number of elements the collection can hold */ public int maxSize() { return maxElements; } /** * Clears this queue. */ @Override public void clear() { full = false; start = 0; end = 0; Arrays.fill(elements, null); } /** * Adds the given element to this queue. If the queue is full, the least recently added * element is discarded so that a new element can be inserted. * * @param element the element to add * @return true, always * @throws NullPointerException if the given element is null */ @Override public boolean add(final E element) { if (null == element) { throw new NullPointerException("Attempted to add null object to queue"); } if (isAtFullCapacity()) { remove(); } elements[end++] = element; if (end >= maxElements) { end = 0; } if (end == start) { full = true; } return true; } /** * Returns the element at the specified position in this queue. * * @param index the position of the element in the queue * @return the element at position {@code index} * @throws NoSuchElementException if the requested position is outside the range [0, size) */ public E get(final int index) { final int sz = size(); if (index < 0 || index >= sz) { throw new NoSuchElementException( String.format("The specified index (%1$d) is outside the available range [0, %2$d)", Integer.valueOf(index), Integer.valueOf(sz))); } final int idx = (start + index) % maxElements; return elements[idx]; } //----------------------------------------------------------------------- /** * Adds the given element to this queue. If the queue is full, the least recently added * element is discarded so that a new element can be inserted. * * @param element the element to add * @return true, always * @throws NullPointerException if the given element is null */ public boolean offer(E element) { return add(element); } public E poll() { if (isEmpty()) { return null; } return remove(); } public E element() { if (isEmpty()) { throw new NoSuchElementException("queue is empty"); } return peek(); } public E peek() { if (isEmpty()) { return null; } return elements[start]; } public E remove() { if (isEmpty()) { throw new NoSuchElementException("queue is empty"); } final E element = elements[start]; if (null != element) { elements[start++] = null; if (start >= maxElements) { start = 0; } full = false; } return element; } //----------------------------------------------------------------------- /** * Increments the internal index. * * @param index the index to increment * @return the updated index */ private int increment(int index) { index++; if (index >= maxElements) { index = 0; } return index; } /** * Decrements the internal index. * * @param index the index to decrement * @return the updated index */ private int decrement(int index) { index--; if (index < 0) { index = maxElements - 1; } return index; } /** * Returns an iterator over this queue's elements. * * @return an iterator over this queue's elements */ @Override public Iterator<E> iterator() { return new Iterator<E>() { private int index = start; private int lastReturnedIndex = -1; private boolean isFirst = full; public boolean hasNext() { return isFirst || index != end; } public E next() { if (!hasNext()) { throw new NoSuchElementException(); } isFirst = false; lastReturnedIndex = index; index = increment(index); return elements[lastReturnedIndex]; } public void remove() { if (lastReturnedIndex == -1) { throw new IllegalStateException(); } // First element can be removed quickly if (lastReturnedIndex == start) { CircularFifoQueue.this.remove(); lastReturnedIndex = -1; return; } int pos = lastReturnedIndex + 1; if (start < lastReturnedIndex && pos < end) { // shift in one part System.arraycopy(elements, pos, elements, lastReturnedIndex, end - pos); } else { // Other elements require us to shift the subsequent elements while (pos != end) { if (pos >= maxElements) { elements[pos - 1] = elements[0]; pos = 0; } else { elements[decrement(pos)] = elements[pos]; pos = increment(pos); } } } lastReturnedIndex = -1; end = decrement(end); elements[end] = null; full = false; index = decrement(index); } }; } }
apache-2.0
hekate-io/hekate
hekate-spring-boot/src/main/java/io/hekate/spring/boot/cluster/HekateCloudSeedNodeProviderConfigurer.java
5244
/* * Copyright 2021 The Hekate Project * * The Hekate Project 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 io.hekate.spring.boot.cluster; import io.hekate.cluster.seed.jclouds.BasicCredentialsSupplier; import io.hekate.cluster.seed.jclouds.CloudSeedNodeProvider; import io.hekate.cluster.seed.jclouds.CloudSeedNodeProviderConfig; import io.hekate.cluster.seed.jclouds.CredentialsSupplier; import io.hekate.cluster.seed.jclouds.aws.AwsCredentialsSupplier; import io.hekate.spring.boot.ConditionalOnHekateEnabled; import java.util.Map; import java.util.Properties; import java.util.Set; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * Auto-configuration for {@link CloudSeedNodeProvider}. * * <p> * This auto-configuration is disabled by default and can be enabled by setting the {@code 'hekate.cluster.seed.cloud.enable'} property to * {@code true} in the application configuration. * </p> * * <p> * The following properties can be used to customize the auto-configured {@link CloudSeedNodeProvider} instance: * </p> * <ul> * <li>{@link CloudSeedNodeProviderConfig#setProvider(String) 'hekate.cluster.seed.cloud.provider'}</li> * <li>{@link CloudSeedNodeProviderConfig#setEndpoint(String) 'hekate.cluster.seed.cloud.endpoint'}</li> * <li>{@link CloudSeedNodeProviderConfig#setCredentials(CredentialsSupplier) 'hekate.cluster.seed.cloud.identity'}</li> * <li>{@link CloudSeedNodeProviderConfig#setCredentials(CredentialsSupplier) 'hekate.cluster.seed.cloud.credential'}</li> * <li>{@link CloudSeedNodeProviderConfig#setRegions(Set) 'hekate.cluster.seed.cloud.regions'}</li> * <li>{@link CloudSeedNodeProviderConfig#setZones(Set) 'hekate.cluster.seed.cloud.zones'}</li> * <li>{@link CloudSeedNodeProviderConfig#setTags(Map) 'hekate.cluster.seed.cloud.tags'}</li> * <li>{@link CloudSeedNodeProviderConfig#setConnectTimeout(Integer)} 'hekate.cluster.seed.cloud.connect-timeout'}</li> * <li>{@link CloudSeedNodeProviderConfig#setSoTimeout(Integer)} 'hekate.cluster.seed.cloud.so-timeout'}</li> * <li>{@link CloudSeedNodeProviderConfig#setProperties(Properties) 'hekate.cluster.seed.cloud.properties'}</li> * </ul> * * @see HekateClusterServiceConfigurer */ @Configuration @ConditionalOnHekateEnabled @AutoConfigureBefore(HekateClusterServiceConfigurer.class) @ConditionalOnProperty(value = "hekate.cluster.seed.cloud.enable", havingValue = "true") public class HekateCloudSeedNodeProviderConfigurer { /** * Conditionally constructs a new credentials supplier based on the provider name. If provider name contains 'aws' then constructs * {@link AwsCredentialsSupplier}; otherwise constructs {@link BasicCredentialsSupplier}. * * @param provider Provider name (see {@link CloudSeedNodeProviderConfig#setProvider(String)}). * * @return Credentials supplier. */ @Bean @ConditionalOnMissingBean(CredentialsSupplier.class) @ConfigurationProperties(prefix = "hekate.cluster.seed.cloud") public CredentialsSupplier cloudCredentialsSupplier(@Value("${hekate.cluster.seed.cloud.provider}") String provider) { if (provider.contains("aws")) { return new AwsCredentialsSupplier(); } return new BasicCredentialsSupplier(); } /** * Conditionally constructs a new configuration for {@link CloudSeedNodeProvider} if application doesn't provide its own {@link Bean} of * {@link CloudSeedNodeProviderConfig} type. * * @param credentials Credentials supplier (see {@link #cloudCredentialsSupplier(String)}). * * @return New configuration. */ @Bean @ConditionalOnMissingBean(CloudSeedNodeProviderConfig.class) @ConfigurationProperties(prefix = "hekate.cluster.seed.cloud") public CloudSeedNodeProviderConfig cloudSeedNodeProviderConfig(CredentialsSupplier credentials) { return new CloudSeedNodeProviderConfig().withCredentials(credentials); } /** * Constructs new {@link CloudSeedNodeProvider}. * * @param cfg Configuration (see {@link #cloudSeedNodeProviderConfig(CredentialsSupplier)}). * * @return New provider. */ @Bean public CloudSeedNodeProvider cloudSeedNodeProvider(CloudSeedNodeProviderConfig cfg) { return new CloudSeedNodeProvider(cfg); } }
apache-2.0
dropwizard/dropwizard
dropwizard-migrations/src/main/java/io/dropwizard/migrations/MigrationsBundle.java
1288
package io.dropwizard.migrations; import io.dropwizard.Configuration; import io.dropwizard.ConfiguredBundle; import io.dropwizard.db.DatabaseConfiguration; import io.dropwizard.setup.Bootstrap; import javax.annotation.Nullable; import java.util.Map; public abstract class MigrationsBundle<T extends Configuration> implements ConfiguredBundle<T>, DatabaseConfiguration<T> { private static final String DEFAULT_NAME = "db"; private static final String DEFAULT_MIGRATIONS_FILE = "migrations.xml"; @Override @SuppressWarnings("unchecked") public final void initialize(Bootstrap<?> bootstrap) { final Class<T> klass = (Class<T>) bootstrap.getApplication().getConfigurationClass(); bootstrap.addCommand(new DbCommand<>(name(), this, klass, getMigrationsFileName(), getScopedObjects())); } public String getMigrationsFileName() { return DEFAULT_MIGRATIONS_FILE; } public String name() { return DEFAULT_NAME; } /** * If overridden, enters a new {@link liquibase.Scope}, in which the provided objects are available. * * @return the objects introduced in the created child {@link liquibase.Scope} */ @Nullable public Map<String, Object> getScopedObjects() { return null; } }
apache-2.0
chengduoZH/Paddle
python/paddle/fluid/tests/unittests/test_feed_data_check_shape_type.py
7953
# Copyright (c) 2019 PaddlePaddle 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. from __future__ import print_function import multiprocessing import numpy as np import os import paddle import paddle.fluid as fluid import paddle.fluid.compiler as compiler import paddle.fluid.core as core import six import unittest os.environ['CPU_NUM'] = str(4) np.random.seed(123) class TestFeedData(unittest.TestCase): ''' Test paddle.fluid.data feeds with different shape and types. Note: paddle.fluid.data is not paddle.fluid.layers.data. ''' def setUp(self): self.hidden_sizes = [25, 20, 15] self.base_batch_size = 10 self.class_num = 10 self.iterations = 5 def _get_batch_size(self, use_cuda, use_parallel_executor): batch_size_times = 1 if use_parallel_executor: batch_size_times = core.get_cuda_device_count( ) if use_cuda else int( os.environ.get('CPU_NUM', multiprocessing.cpu_count())) return self.base_batch_size * batch_size_times def _simple_fc_net(self, in_size, label_size, class_num, hidden_sizes): in_data = fluid.data(name="data", dtype='float32', shape=in_size) label = fluid.data(name='label', dtype='int64', shape=label_size) hidden = in_data for hidden_size in hidden_sizes: hidden = fluid.layers.fc(hidden, size=hidden_size) predict_label = fluid.layers.fc(hidden, size=class_num, act='softmax') loss = fluid.layers.mean( fluid.layers.cross_entropy( input=predict_label, label=label)) optimizer = fluid.optimizer.Adam() optimizer.minimize(loss) return in_data, label, loss def test(self): for use_cuda in [True, False] if core.is_compiled_with_cuda() else [False]: for use_parallel_executor in [False, True]: print('Test Parameters:'), print({ 'use_cuda': use_cuda, 'use_parallel_executor': use_parallel_executor, }) # Test feeding without error self._test_feed_data_match_shape_type(use_cuda, use_parallel_executor) self._test_feed_data_contains_neg_one(use_cuda, use_parallel_executor) # Test exception message when feeding with error batch_size = self._get_batch_size(use_cuda, use_parallel_executor) if six.PY2: in_shape_tuple = (long(-1), long(3), long(4), long(8)) feed_shape_list = [ long(batch_size), long(3), long(4), long(5) ] else: in_shape_tuple = (-1, 3, 4, 8) feed_shape_list = [batch_size, 3, 4, 5] with self.assertRaises(ValueError) as shape_mismatch_err: self._test_feed_data_shape_mismatch(use_cuda, use_parallel_executor) self.assertEqual( str(shape_mismatch_err.exception), "The feeded Variable %r should have dimensions = %r, " "shape = %r, but received feeded shape %r" % (u'data', len(in_shape_tuple), in_shape_tuple, feed_shape_list)) with self.assertRaises(ValueError) as dtype_mismatch_err: self._test_feed_data_dtype_mismatch(use_cuda, use_parallel_executor) self.assertEqual( str(dtype_mismatch_err.exception), "The data type of feeded Variable %r must be 'int64', but " "received 'float64'" % (u'label')) def _test_feed_data_dtype_mismatch(self, use_cuda, use_parallel_executor): batch_size = self._get_batch_size(use_cuda, use_parallel_executor) in_size = [batch_size, 3, 4, 5] feed_in_data = np.random.uniform( size=[batch_size, 3, 4, 5]).astype(np.float32) label_size = [batch_size, 1] feed_label = np.random.randint( low=0, high=self.class_num, size=[batch_size, 1]).astype(np.float64) self._feed_data_in_executor(in_size, label_size, feed_in_data, feed_label, use_cuda, use_parallel_executor) def _test_feed_data_shape_mismatch(self, use_cuda, use_parallel_executor): batch_size = self._get_batch_size(use_cuda, use_parallel_executor) in_size = [None, 3, 4, 8] feed_in_data = np.random.uniform( size=[batch_size, 3, 4, 5]).astype(np.float32) label_size = [-1, 1] feed_label = np.random.randint( low=0, high=self.class_num, size=[batch_size, 1]).astype(np.int64) self._feed_data_in_executor(in_size, label_size, feed_in_data, feed_label, use_cuda, use_parallel_executor) def _test_feed_data_contains_neg_one(self, use_cuda, use_parallel_executor): batch_size = self._get_batch_size(use_cuda, use_parallel_executor) in_size = [-1, 3, 4, 5] feed_in_data = np.random.uniform( size=[batch_size, 3, 4, 5]).astype(np.float32) label_size = (None, 1) feed_label = np.random.randint( low=0, high=self.class_num, size=[batch_size, 1]).astype(np.int64) self._feed_data_in_executor(in_size, label_size, feed_in_data, feed_label, use_cuda, use_parallel_executor) def _test_feed_data_match_shape_type(self, use_cuda, use_parallel_executor): batch_size = self._get_batch_size(use_cuda, use_parallel_executor) in_size = [batch_size, 3, 4, 5] feed_in_data = np.random.uniform(size=in_size).astype(np.float32) label_size = [batch_size, 1] feed_label = np.random.randint( low=0, high=self.class_num, size=label_size).astype(np.int64) self._feed_data_in_executor(in_size, label_size, feed_in_data, feed_label, use_cuda, use_parallel_executor) def _feed_data_in_executor(self, in_size, label_size, feed_in_data, feed_label, use_cuda, use_parallel_executor): startup_program = fluid.Program() main_program = fluid.Program() with fluid.program_guard(main_program, startup_program): in_data, label, loss = self._simple_fc_net( in_size, label_size, self.class_num, self.hidden_sizes) place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace() exe = fluid.Executor(place) exe.run(startup_program) train_program = main_program if use_parallel_executor: train_program = compiler.CompiledProgram( main_program).with_data_parallel(loss_name=loss.name) for i in range(self.iterations): fetches = exe.run( train_program, feed={in_data.name: feed_in_data, label.name: feed_label}, fetch_list=[loss.name]) if __name__ == '__main__': unittest.main()
apache-2.0
miswenwen/My_bird_work
Bird_work/我的项目/配置好的可以直接编译的模块/CGamessLink/src/com/example/cgamesslink/MainActivity.java
540
package com.example.cgamesslink; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent= new Intent(); intent.setAction("android.intent.action.VIEW"); Uri content_url = Uri.parse("http://www.baidu.com"); intent.setData(content_url); startActivity(intent); finish(); } }
apache-2.0
CMPUT301F16T10/Drivr
app/src/test/java/ca/ualberta/cs/drivr/UserTest.java
978
/* * Copyright 2016 CMPUT301F16T10 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 ca.ualberta.cs.drivr; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Created by adam on 2016-10-12. */ public class UserTest { /* This class is a storage class for the data on a user that should not be shown on the public profile. It is only getters and setters so no tests are needed at this time. */ }
apache-2.0
DocnetUK/matt-client
examples/matt.php
446
<?php /** * Examples for MATT client */ require(dirname(__FILE__) . '/../src/Docnet/MATT.class.php'); // This should happen once per day Docnet\MATT::expect('Google upload OK [test]')->every('day'); // Something we expect to happen at least every 15 minutes Docnet\MATT::expect('Order placed [test]')->every('15m')->sms('07715122253'); // This thing should NEVER happen Docnet\MATT::expect('Horrible error [test]')->never()->email('tom');
apache-2.0
zendesk/samlr
test/unit/test_signature.rb
1625
require File.expand_path("test/test_helper") require "openssl" describe Samlr::Signature do before do @response = fixed_saml_response @signature = @response.signature end describe "#signature_algorithm" do it "should defer to Samlr::Tools::algorithm" do Samlr::Tools.stub(:algorithm, "hello") do assert_match "hello", @signature.send(:signature_method) end end end describe "#references" do it "should extract the reference to the signed document" do assert_equal @response.document.children.first, @response.document.at(".//*[@ID='#{@signature.send(:references).first.uri}']") end end describe "#certificate!" do it "should extract the certificate" do assert_equal TEST_CERTIFICATE.to_certificate, @signature.send(:certificate!) end describe "when there is no X509 certificate" do it "should raise a signature error" do @signature.stub(:certificate_node, nil) do assert_raises(Samlr::SignatureError) { @signature.send(:certificate!) } end end end end describe "#verify_digests!" do describe "when there are duplicate element ids" do before do @signature.document.at("/samlp:Response/saml:Assertion")["ID"] = @signature.document.root["ID"] end it "should raise" do begin @signature.send(:verify_digests!) flunk("Excepted to raise due to duplicate elements") rescue Samlr::SignatureError => e assert_equal "Reference validation error: Invalid element references", e.message end end end end end
apache-2.0
optivem/optivem-commons-cs
test/Web/AspNetCore.RestApi.IntegrationTest.Fake/Profiles/Customers/CustomerPostResponseProfile.cs
458
using AutoMapper; using Optivem.Atomiv.Web.AspNetCore.RestApi.IntegrationTest.Fake.Dtos.Customers; using Optivem.Atomiv.Web.AspNetCore.RestApi.IntegrationTest.Fake.Entities; namespace Optivem.Atomiv.Web.AspNetCore.RestApi.IntegrationTest.Fake.Profiles.Customers { public class CustomerPostResponseProfile : Profile { public CustomerPostResponseProfile() { CreateMap<Customer, CustomerPostResponse>(); } } }
apache-2.0
linzhaoming/origin
pkg/oc/lib/newapp/cmd/newapp_test.go
19780
package cmd import ( "bytes" "fmt" "os" "reflect" "strings" "testing" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/apitesting" "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/api/meta/testrestmapper" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/cli-runtime/pkg/genericclioptions/resource" fakev1 "k8s.io/client-go/kubernetes/fake" clientfake "k8s.io/client-go/rest/fake" "k8s.io/client-go/restmapper" clientgotesting "k8s.io/client-go/testing" kapi "k8s.io/kubernetes/pkg/apis/core" "github.com/openshift/api" buildv1 "github.com/openshift/api/build/v1" imagev1 "github.com/openshift/api/image/v1" templatev1 "github.com/openshift/api/template/v1" fakeimagev1client "github.com/openshift/client-go/image/clientset/versioned/fake" routefakev1client "github.com/openshift/client-go/route/clientset/versioned/fake" faketemplatev1client "github.com/openshift/client-go/template/clientset/versioned/fake" "github.com/openshift/origin/pkg/image/apis/image" "github.com/openshift/origin/pkg/oc/lib/newapp" "github.com/openshift/origin/pkg/oc/lib/newapp/app" "github.com/openshift/source-to-image/pkg/scm/git" _ "github.com/openshift/origin/pkg/api/install" ) func TestValidate(t *testing.T) { tests := map[string]struct { cfg AppConfig componentValues []string sourceRepoLocations []string env map[string]string buildEnv map[string]string parms map[string]string }{ "components": { cfg: AppConfig{ ComponentInputs: ComponentInputs{ Components: []string{"one", "two", "three/four"}, }, }, componentValues: []string{"one", "two", "three/four"}, sourceRepoLocations: []string{}, env: map[string]string{}, buildEnv: map[string]string{}, parms: map[string]string{}, }, "envs": { cfg: AppConfig{ GenerationInputs: GenerationInputs{ Environment: []string{"one=first", "two=second", "three=third"}, }, }, componentValues: []string{}, sourceRepoLocations: []string{}, env: map[string]string{"one": "first", "two": "second", "three": "third"}, buildEnv: map[string]string{}, parms: map[string]string{}, }, "build-envs": { cfg: AppConfig{ GenerationInputs: GenerationInputs{ BuildEnvironment: []string{"one=first", "two=second", "three=third"}, }, }, componentValues: []string{}, sourceRepoLocations: []string{}, env: map[string]string{}, buildEnv: map[string]string{"one": "first", "two": "second", "three": "third"}, parms: map[string]string{}, }, "component+source": { cfg: AppConfig{ ComponentInputs: ComponentInputs{ Components: []string{"one~https://server/repo.git"}, }, }, componentValues: []string{"one"}, sourceRepoLocations: []string{"https://server/repo.git"}, env: map[string]string{}, buildEnv: map[string]string{}, parms: map[string]string{}, }, "components+source": { cfg: AppConfig{ ComponentInputs: ComponentInputs{ Components: []string{"mysql+ruby~git://github.com/namespace/repo.git"}, }, }, componentValues: []string{"mysql", "ruby"}, sourceRepoLocations: []string{"git://github.com/namespace/repo.git"}, env: map[string]string{}, buildEnv: map[string]string{}, parms: map[string]string{}, }, "components+parms": { cfg: AppConfig{ ComponentInputs: ComponentInputs{ Components: []string{"ruby-helloworld-sample"}, }, GenerationInputs: GenerationInputs{ TemplateParameters: []string{"one=first", "two=second"}, }, }, componentValues: []string{"ruby-helloworld-sample"}, sourceRepoLocations: []string{}, env: map[string]string{}, buildEnv: map[string]string{}, parms: map[string]string{"one": "first", "two": "second"}, }, } for n, c := range tests { b := &app.ReferenceBuilder{} env, buildEnv, parms, err := c.cfg.validate() if err != nil { t.Errorf("%s: Unexpected error: %v", n, err) continue } if err := AddComponentInputsToRefBuilder(b, &c.cfg.Resolvers, &c.cfg.ComponentInputs, &c.cfg.GenerationInputs, &c.cfg.SourceRepositories, &c.cfg.ImageStreams); err != nil { t.Errorf("%s: Unexpected error: %v", n, err) continue } cr, _, errs := b.Result() if len(errs) > 0 { t.Errorf("%s: Unexpected error: %v", n, errs) continue } compValues := []string{} for _, r := range cr { compValues = append(compValues, r.Input().Value) } if !reflect.DeepEqual(c.componentValues, compValues) { t.Errorf("%s: Component values don't match. Expected: %v, Got: %v", n, c.componentValues, compValues) } if len(env) != len(c.env) { t.Errorf("%s: Environment variables don't match. Expected: %v, Got: %v", n, c.env, env) } for e, v := range env { if c.env[e] != v { t.Errorf("%s: Environment variables don't match. Expected: %v, Got: %v", n, c.env, env) break } } if len(buildEnv) != len(c.buildEnv) { t.Errorf("%s: Environment variables don't match. Expected: %v, Got: %v", n, c.buildEnv, buildEnv) } for e, v := range buildEnv { if c.buildEnv[e] != v { t.Errorf("%s: Environment variables don't match. Expected: %v, Got: %v", n, c.buildEnv, buildEnv) break } } if len(parms) != len(c.parms) { t.Errorf("%s: Template parameters don't match. Expected: %v, Got: %v", n, c.parms, parms) } for p, v := range parms { if c.parms[p] != v { t.Errorf("%s: Template parameters don't match. Expected: %v, Got: %v", n, c.parms, parms) break } } } } func TestBuildTemplates(t *testing.T) { tests := map[string]struct { templateName string namespace string parms map[string]string }{ "simple": { templateName: "first-stored-template", namespace: "default", parms: map[string]string{}, }, } for n, c := range tests { appCfg := AppConfig{} appCfg.Out = &bytes.Buffer{} appCfg.EnvironmentClassificationErrors = map[string]ArgumentClassificationError{} appCfg.SourceClassificationErrors = map[string]ArgumentClassificationError{} appCfg.TemplateClassificationErrors = map[string]ArgumentClassificationError{} appCfg.ComponentClassificationErrors = map[string]ArgumentClassificationError{} appCfg.ClassificationWinners = map[string]ArgumentClassificationWinner{} // the previous fake was broken and didn't 404 properly. this test is relying on that imageFake := fakeimagev1client.NewSimpleClientset() templateFake := faketemplatev1client.NewSimpleClientset() routeFake := routefakev1client.NewSimpleClientset() customScheme, _ := apitesting.SchemeForOrDie(api.Install) appCfg.Builder = resource.NewFakeBuilder( func(version schema.GroupVersion) (resource.RESTClient, error) { return &clientfake.RESTClient{}, nil }, func() (meta.RESTMapper, error) { return testrestmapper.TestOnlyStaticRESTMapper(customScheme, customScheme.PrioritizedVersionsAllGroups()...), nil }, func() (restmapper.CategoryExpander, error) { return resource.FakeCategoryExpander, nil }) appCfg.SetOpenShiftClient( imageFake.ImageV1(), templateFake.TemplateV1(), routeFake.RouteV1(), c.namespace, nil) appCfg.KubeClient = fakev1.NewSimpleClientset() appCfg.TemplateSearcher = fakeTemplateSearcher() appCfg.AddArguments([]string{c.templateName}) appCfg.TemplateParameters = []string{} for k, v := range c.parms { appCfg.TemplateParameters = append(appCfg.TemplateParameters, fmt.Sprintf("%v=%v", k, v)) } _, _, parms, err := appCfg.validate() if err != nil { t.Errorf("%s: Unexpected error: %v", n, err) continue } resolved, err := Resolve(&appCfg) if err != nil { t.Errorf("%s: Unexpected error: %v", n, err) continue } components := resolved.Components err = components.Resolve() if err != nil { t.Errorf("%s: Unexpected error: %v", n, err) continue } _, _, err = appCfg.buildTemplates(components, app.Environment(parms), app.Environment(map[string]string{}), app.Environment(map[string]string{}), fakeTemplateProcessor{}) if err != nil { t.Errorf("%s: Unexpected error: %v", n, err) } for _, component := range components { match := component.Input().ResolvedMatch if !match.IsTemplate() { t.Errorf("%s: Expected template match, got: %v", n, match) } if fmt.Sprintf("%s/%s", c.namespace, c.templateName) != match.Name { t.Errorf("%s: Expected template name %q, got: %q", n, c.templateName, match.Name) } if len(parms) != len(c.parms) { t.Errorf("%s: Template parameters don't match. Expected: %v, Got: %v", n, c.parms, parms) } for p, v := range parms { if c.parms[p] != v { t.Errorf("%s: Template parameters don't match. Expected: %v, Got: %v", n, c.parms, parms) break } } } } } func fakeTemplateSearcher() app.Searcher { client := faketemplatev1client.NewSimpleClientset() client.PrependReactor("list", "templates", func(action clientgotesting.Action) (handled bool, ret runtime.Object, err error) { return true, templateList(), nil }) return app.TemplateSearcher{ Client: client.TemplateV1(), Namespaces: []string{"default"}, } } func templateList() *templatev1.TemplateList { return &templatev1.TemplateList{ Items: []templatev1.Template{ { Objects: []runtime.RawExtension{}, ObjectMeta: metav1.ObjectMeta{ Name: "first-stored-template", Namespace: "default", }, }, }, } } func TestEnsureHasSource(t *testing.T) { gitLocalDir, err := git.CreateLocalGitDirectory() if err != nil { t.Fatal(err) } defer os.RemoveAll(gitLocalDir) tests := []struct { name string cfg AppConfig components app.ComponentReferences repositories []*app.SourceRepository expectedErr string dontExpectToBuild bool }{ { name: "One requiresSource, multiple repositories", components: app.ComponentReferences{ app.ComponentReference(&app.ComponentInput{ ExpectToBuild: true, }), }, repositories: mockSourceRepositories(t, gitLocalDir), expectedErr: "there are multiple code locations provided - use one of the following suggestions", }, { name: "Multiple requiresSource, multiple repositories", components: app.ComponentReferences{ app.ComponentReference(&app.ComponentInput{ ExpectToBuild: true, }), app.ComponentReference(&app.ComponentInput{ ExpectToBuild: true, }), }, repositories: mockSourceRepositories(t, gitLocalDir), expectedErr: "Use '[image]~[repo]' to declare which code goes with which image", }, { name: "One requiresSource, no repositories", components: app.ComponentReferences{ app.ComponentReference(&app.ComponentInput{ ExpectToBuild: true, }), }, repositories: []*app.SourceRepository{}, expectedErr: "", dontExpectToBuild: true, }, { name: "Multiple requiresSource, no repositories", components: app.ComponentReferences{ app.ComponentReference(&app.ComponentInput{ ExpectToBuild: true, }), app.ComponentReference(&app.ComponentInput{ ExpectToBuild: true, }), }, repositories: []*app.SourceRepository{}, expectedErr: "", dontExpectToBuild: true, }, { name: "Successful - one repository", components: app.ComponentReferences{ app.ComponentReference(&app.ComponentInput{ ExpectToBuild: false, }), }, repositories: mockSourceRepositories(t, gitLocalDir)[:1], expectedErr: "", }, { name: "Successful - no requiresSource", components: app.ComponentReferences{ app.ComponentReference(&app.ComponentInput{ ExpectToBuild: false, }), }, repositories: mockSourceRepositories(t, gitLocalDir), expectedErr: "", }, } for _, test := range tests { err := EnsureHasSource(test.components, test.repositories, &test.cfg.GenerationInputs) if err != nil { if !strings.Contains(err.Error(), test.expectedErr) { t.Errorf("%s: Invalid error: Expected %s, got %v", test.name, test.expectedErr, err) } } else if len(test.expectedErr) != 0 { t.Errorf("%s: Expected %s error but got none", test.name, test.expectedErr) } if test.dontExpectToBuild { for _, comp := range test.components { if comp.NeedsSource() { t.Errorf("%s: expected component reference to not require source.", test.name) } } } } } // mockSourceRepositories is a set of mocked source repositories used for // testing. func mockSourceRepositories(t *testing.T, file string) []*app.SourceRepository { var b []*app.SourceRepository for _, location := range []string{ "https://github.com/openshift/ruby-hello-world.git", file, } { s, err := app.NewSourceRepository(location, generate.StrategySource) if err != nil { t.Fatal(err) } b = append(b, s) } return b } // Make sure that buildPipelines defaults DockerImage.Config if needed to // avoid a nil panic. func TestBuildPipelinesWithUnresolvedImage(t *testing.T) { dockerFile, err := app.NewDockerfile("FROM centos\nEXPOSE 1234\nEXPOSE 4567") if err != nil { t.Fatal(err) } sourceRepo, err := app.NewSourceRepository("https://github.com/foo/bar.git", generate.StrategyDocker) if err != nil { t.Fatal(err) } sourceRepo.SetInfo(&app.SourceRepositoryInfo{ Dockerfile: dockerFile, }) refs := app.ComponentReferences{ app.ComponentReference(&app.ComponentInput{ Value: "mysql", Uses: sourceRepo, ExpectToBuild: true, ResolvedMatch: &app.ComponentMatch{ Value: "mysql", }, }), } a := AppConfig{} a.Out = &bytes.Buffer{} group, err := a.buildPipelines(refs, app.Environment{}, app.Environment{}) if err != nil { t.Error(err) } expectedPorts := sets.NewString("1234", "4567") actualPorts := sets.NewString() for port := range group[0].InputImage.Info.Config.ExposedPorts { actualPorts.Insert(port) } if e, a := expectedPorts.List(), actualPorts.List(); !reflect.DeepEqual(e, a) { t.Errorf("Expected ports=%v, got %v", e, a) } } func TestBuildOutputCycleResilience(t *testing.T) { config := &AppConfig{} mockIS := &image.ImageStream{ ObjectMeta: metav1.ObjectMeta{ Name: "mockimagestream", }, Spec: image.ImageStreamSpec{ Tags: make(map[string]image.TagReference), }, } mockIS.Spec.Tags["latest"] = image.TagReference{ From: &kapi.ObjectReference{ Kind: "DockerImage", Name: "mockimage:latest", }, } dfn := "mockdockerfilename" malOutputBC := &buildv1.BuildConfig{ ObjectMeta: metav1.ObjectMeta{ Name: "buildCfgWithWeirdOutputObjectRef", }, Spec: buildv1.BuildConfigSpec{ CommonSpec: buildv1.CommonSpec{ Source: buildv1.BuildSource{ Dockerfile: &dfn, }, Strategy: buildv1.BuildStrategy{ DockerStrategy: &buildv1.DockerBuildStrategy{ From: &corev1.ObjectReference{ Kind: "ImageStreamTag", Name: "mockimagestream:latest", }, }, }, Output: buildv1.BuildOutput{ To: &corev1.ObjectReference{ Kind: "NewTypeOfRef", Name: "Yet-to-be-implemented", }, }, }, }, } _, err := config.followRefToDockerImage(malOutputBC.Spec.Output.To, nil, []runtime.Object{malOutputBC, mockIS}) expected := "Unable to follow reference type: \"NewTypeOfRef\"" if err == nil || err.Error() != expected { t.Errorf("Expected error from followRefToDockerImage: got \"%v\" versus expected %q", err, expected) } } func TestBuildOutputCycleWithCircularTag(t *testing.T) { dfn := "mockdockerfilename" tests := []struct { bc *buildv1.BuildConfig is []runtime.Object expected string }{ { bc: &buildv1.BuildConfig{ ObjectMeta: metav1.ObjectMeta{ Name: "buildCfgWithWeirdOutputObjectRef", }, Spec: buildv1.BuildConfigSpec{ CommonSpec: buildv1.CommonSpec{ Source: buildv1.BuildSource{ Dockerfile: &dfn, }, Strategy: buildv1.BuildStrategy{ DockerStrategy: &buildv1.DockerBuildStrategy{ From: &corev1.ObjectReference{ Kind: "ImageStreamTag", Name: "mockimagestream:latest", }, }, }, Output: buildv1.BuildOutput{ To: &corev1.ObjectReference{ Kind: "ImageStreamTag", Name: "mockimagestream:10.0", }, }, }, }, }, is: []runtime.Object{ &imagev1.ImageStream{ ObjectMeta: metav1.ObjectMeta{ Name: "mockimagestream", }, Spec: imagev1.ImageStreamSpec{ Tags: []imagev1.TagReference{ { Name: "latest", From: &corev1.ObjectReference{ Kind: "ImageStreamTag", Name: "10.0", }, }, { Name: "10.0", From: &corev1.ObjectReference{ Kind: "ImageStreamTag", Name: "latest", }, }, }, }, }, }, expected: "image stream tag reference \"mockimagestream:latest\" is a circular loop of image stream tags", }, { bc: &buildv1.BuildConfig{ ObjectMeta: metav1.ObjectMeta{ Name: "buildCfgWithWeirdOutputObjectRef", }, Spec: buildv1.BuildConfigSpec{ CommonSpec: buildv1.CommonSpec{ Source: buildv1.BuildSource{ Dockerfile: &dfn, }, Strategy: buildv1.BuildStrategy{ DockerStrategy: &buildv1.DockerBuildStrategy{ From: &corev1.ObjectReference{ Kind: "ImageStreamTag", Name: "mockimagestream:latest", }, }, }, Output: buildv1.BuildOutput{ To: &corev1.ObjectReference{ Kind: "ImageStreamTag", Name: "fakeimagestream:latest", }, }, }, }, }, is: []runtime.Object{ &imagev1.ImageStream{ ObjectMeta: metav1.ObjectMeta{ Name: "mockimagestream", }, Spec: imagev1.ImageStreamSpec{ Tags: []imagev1.TagReference{ { Name: "latest", From: &corev1.ObjectReference{ Kind: "ImageStreamTag", Name: "fakeimagestream:latest", }, }, }, }, }, &imagev1.ImageStream{ ObjectMeta: metav1.ObjectMeta{ Name: "fakeimagestream", }, Spec: imagev1.ImageStreamSpec{ Tags: []imagev1.TagReference{ { Name: "latest", From: &corev1.ObjectReference{ Kind: "ImageStreamTag", Name: "mockimagestream:latest", }, }, }, }, }, }, expected: "image stream tag reference \"mockimagestream:latest\" is a circular loop of image stream tags", }, } config := &AppConfig{} for _, test := range tests { imageFake := fakeimagev1client.NewSimpleClientset() imageFakeConfig := fakeimagev1client.NewSimpleClientset(test.is...) objs := append(test.is, test.bc) // so we test both with the fake image client seeded with the image streams, i.e. existing image streams // and without, i.e. the generate flow is creating the image streams as well config.ImageClient = imageFake.ImageV1() err := config.checkCircularReferences(objs) if err == nil || err.Error() != test.expected { t.Errorf("Expected error from followRefToDockerImage: got \"%v\" versus expected %q", err, test.expected) } config.ImageClient = imageFakeConfig.ImageV1() err = config.checkCircularReferences(objs) if err == nil || err.Error() != test.expected { t.Errorf("Expected error from followRefToDockerImage: got \"%v\" versus expected %q", err, test.expected) } } }
apache-2.0
xavilens/prueba
db/migrate/20160513094218_add_polymorphism_to_user.rb
171
class AddPolymorphismToUser < ActiveRecord::Migration def change add_column :users, :userable_id, :integer add_column :users, :userable_type, :integer end end
apache-2.0
narry/odenos
src/main/java/org/o3project/odenos/component/linklayerizer/LinkLayerizerBoundaryTable.java
6018
/* * Copyright 2015 NEC Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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.o3project.odenos.component.linklayerizer; import java.util.HashMap; import java.util.Map; import java.util.UUID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Manage boundaries class. * */ public class LinkLayerizerBoundaryTable { /** logger. */ private static final Logger log = LoggerFactory.getLogger(LinkLayerizerBoundaryTable.class); /** * Map of boundaries. * key : Boundary ID * value : LinkLayerizerBoundary */ private Map<String, LinkLayerizerBoundary> boundaries = new HashMap<>(); /** * Constructors. * */ public LinkLayerizerBoundaryTable() { // do nothing } /** * Get boundaries. * @return boundaries */ public Map<String, LinkLayerizerBoundary> getBoundaries() { return boundaries; } /** * Set boundaries. * @param boundaries map of boundaries. */ public void setBoundaries(Map<String, LinkLayerizerBoundary> boundaries) { this.boundaries = boundaries; } /** * Add a entry of boundary. * @param boundary Registered boundary. * @return added the boundary * @throws LinkLayerizerBoundaryException if parameters were registered or null. */ public LinkLayerizerBoundary addEntry(LinkLayerizerBoundary boundary) throws LinkLayerizerBoundaryException { if (boundary == null) { log.error("boundary is null"); throw new IllegalArgumentException("boundary is null"); } String boundaryId = getUniqueId(); boundary.setId(boundaryId); return updateEntry(boundaryId, boundary); } /** * Add a entry of boundary. * @param boundaryId ID for boundary. * @param boundary Registered boundary. * @return added the boundary * @throws LinkLayerizerBoundaryException if parameters were registered or null. */ public LinkLayerizerBoundary addEntry(String boundaryId, LinkLayerizerBoundary boundary) throws LinkLayerizerBoundaryException { return updateEntry(boundaryId, boundary); } /** * Update a entry of boundary. * @param boundaryId ID for boundary. * @param boundary Replaced boundary. * @return updated the boundary * @throws LinkLayerizerBoundaryException if parameters were registered or null. */ public LinkLayerizerBoundary updateEntry(String boundaryId, LinkLayerizerBoundary boundary) throws LinkLayerizerBoundaryException { if (boundaryId == null) { log.error("boundaryId is null"); throw new IllegalArgumentException("boundaryId is null"); } if (boundary == null) { log.error("boundary is null"); throw new IllegalArgumentException("boundary is null"); } if (!boundaryId.equals(boundary.getId())) { log.warn("set boundaryId: {}", boundaryId); boundary.setId(boundaryId); } boundaries.put(boundaryId, boundary); return boundary; } /** * Get a entry of boundary. * @param boundaryId ID for boundary. * @return got the boundary */ public LinkLayerizerBoundary getEntry(String boundaryId) { if (log.isDebugEnabled()) { log.debug("getEntry: {}", boundaryId); } return boundaries.get(boundaryId); } /** * Get entry of boundary. * @param lowerNwId ID for lower network. * @param lowerNodeId ID for node. * @param lowerPortId ID for port. * @return found the boundary */ public LinkLayerizerBoundary getBoundary( String lowerNwId, String lowerNodeId, String lowerPortId) { log.debug(""); if (lowerNodeId == null || lowerNwId == null || lowerPortId == null) { return null; } for (LinkLayerizerBoundary boundary : boundaries.values()) { if (boundary.getLowerNw().equals(lowerNwId) && boundary.getLowerNwNode().equals(lowerNodeId) && boundary.getLowerNwPort().equals(lowerPortId)) { return boundary; } } return null; } /** * Check boundary port or not. * @param nwId ID for lower or upper network. * @param nodeId ID for node. * @param portId ID for port. * @return If exist boundary port, return true. */ public boolean isBoudaryPort( String nwId, String nodeId, String portId) { log.debug(""); for (LinkLayerizerBoundary boundary : boundaries.values()) { if (boundary.getLowerNw().equals(nwId) && boundary.getLowerNwNode().equals(nodeId) && boundary.getLowerNwPort().equals(portId)) { return true; } if (boundary.getUpperNw().equals(nwId) && boundary.getUpperNwNode().equals(nodeId) && boundary.getUpperNwPort().equals(portId)) { return true; } } return false; } /** * Remove a entry of boundary. * @param boundaryId ID for boundary. * @return deleted the boundary */ public LinkLayerizerBoundary deleteEntry(String boundaryId) { if (log.isDebugEnabled()) { log.debug("deleteEntry: {}", boundaryId); } if (!boundaries.containsKey(boundaryId)) { return null; } LinkLayerizerBoundary resultBoundary = boundaries.remove(boundaryId); return resultBoundary; } /** * Method for assigned generating UUID to ComponentConnectionID. * * @return id ComponentConnectionID. */ protected final String getUniqueId() { String id; do { id = UUID.randomUUID().toString(); } while (boundaries.containsKey(id)); return id; } }
apache-2.0
dagnir/aws-sdk-java
aws-java-sdk-emr/src/main/java/com/amazonaws/services/elasticmapreduce/model/transform/InstanceFleetStatusJsonUnmarshaller.java
3335
/* * Copyright 2012-2017 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.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.elasticmapreduce.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * InstanceFleetStatus JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class InstanceFleetStatusJsonUnmarshaller implements Unmarshaller<InstanceFleetStatus, JsonUnmarshallerContext> { public InstanceFleetStatus unmarshall(JsonUnmarshallerContext context) throws Exception { InstanceFleetStatus instanceFleetStatus = new InstanceFleetStatus(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("State", targetDepth)) { context.nextToken(); instanceFleetStatus.setState(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("StateChangeReason", targetDepth)) { context.nextToken(); instanceFleetStatus.setStateChangeReason(InstanceFleetStateChangeReasonJsonUnmarshaller.getInstance().unmarshall(context)); } if (context.testExpression("Timeline", targetDepth)) { context.nextToken(); instanceFleetStatus.setTimeline(InstanceFleetTimelineJsonUnmarshaller.getInstance().unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return instanceFleetStatus; } private static InstanceFleetStatusJsonUnmarshaller instance; public static InstanceFleetStatusJsonUnmarshaller getInstance() { if (instance == null) instance = new InstanceFleetStatusJsonUnmarshaller(); return instance; } }
apache-2.0
evanx/chronic
src/chronic/metric/SampleSet.java
1063
/* Source https://code.google.com/p/vellum by @evanxsummers 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 chronic.metric; /** * * @author evan.summers */ public class SampleSet { Sample[] minutes = new Sample[60]; Sample[] hours = new Sample[72]; Sample[] days = new Sample[45]; }
apache-2.0
fabapp/priceoffers
purchaseoffer-service/src/main/java/de/appblocks/microservice/purchaseoffer/integration/topics/PurchaseOfferTopicAdapter.java
905
package de.appblocks.microservice.purchaseoffer.integration.topics; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Aspect; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.stereotype.Component; import de.appblocks.microservice.purchaseoffer.domain.PurchaseOffer; @Component @Aspect public class PurchaseOfferTopicAdapter { @Autowired private KafkaTemplate<String, PurchaseOffer> purchaseOffer; @AfterReturning( pointcut="execution (* de.appblocks.microservice.purchaseoffer.web.PurchaseOfferController.saveOffer(de.appblocks.microservice.purchaseoffer.domain.PurchaseOffer))", returning="info") public void listen(PurchaseOffer info) throws Exception { this.purchaseOffer.send(PurchaseOfferTopic.PURCHASE_OFFER_V1_OFFER_NEW, info); } }
apache-2.0
googleinterns/calcite
core/src/main/java/org/apache/calcite/sql/fun/SqlArgumentAssignmentOperator.java
2063
/* * 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.calcite.sql.fun; import org.apache.calcite.sql.SqlAsOperator; import org.apache.calcite.sql.SqlCall; import org.apache.calcite.sql.SqlKind; import org.apache.calcite.sql.SqlWriter; import org.apache.calcite.sql.type.InferTypes; import org.apache.calcite.sql.type.OperandTypes; import org.apache.calcite.sql.type.ReturnTypes; /** * Operator that assigns an argument to a function call to a particular named * parameter. * * <p>Not an expression; just a holder to represent syntax until the validator * has chance to resolve arguments. * * <p>Sub-class of {@link SqlAsOperator} ("AS") out of convenience; to be * consistent with AS, we reverse the arguments. */ class SqlArgumentAssignmentOperator extends SqlAsOperator { SqlArgumentAssignmentOperator() { super("=>", SqlKind.ARGUMENT_ASSIGNMENT, 20, true, ReturnTypes.ARG0, InferTypes.RETURN_TYPE, OperandTypes.ANY_ANY); } @Override public void unparse(SqlWriter writer, SqlCall call, int leftPrec, int rightPrec) { // Arguments are held in reverse order to be consistent with base class (AS). call.operand(1).unparse(writer, leftPrec, getLeftPrec()); writer.keyword(getName()); call.operand(0).unparse(writer, getRightPrec(), rightPrec); } }
apache-2.0
DAIGroup/BagOfKeyPoses
BagOfKeyPoses/Util/Functions.cs
28672
/* Copyright (C) 2014 Alexandros Andre Chaaraoui Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using System.IO; namespace Util { /// <summary> /// Utilities and non-object-specific functions. /// </summary> public static class Functions { // Static public static Random rand = new Random(); // Random generator for all key poses /// <summary> /// Returns Manhattan distance. /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> public static double ManhattanDistance(double[] a, double[] b) { if (a.Length != b.Length) throw new Exception("(Functions::ManhattanDistance) In order to compare vectors they should have the same size."); double distance = 0; for (int i = 0; i < a.Length; ++i) { distance += Math.Abs(a[i] - b[i]); } return distance; } /// <summary> /// Returns Correlation (similarity value) /// (Sample Correlation Coefficient) /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> public static double Correlation(double[] a, double[] b) { if (a.Length != b.Length) throw new Exception("(Functions::Correlation) In order to compare vectors they should have the same size."); double first = 0, second = 0, third = 0; double a_avg = a.Average(), b_avg = b.Average(); for (int i = 0; i < a.Length; ++i) { double a_des = a[i] - a_avg; double b_des = b[i] - b_avg; first += a_des * b_des; second += a_des * a_des; third += b_des * b_des; } return first / Math.Sqrt(second * third); } /// <summary> /// Returns Manhattan distance. /// Optimized to support Branch & Bound (when better = false, the returned value should be ignored) /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <param name="minDistance">Best distance at the moment</param> /// <param name="better">True if no pruning happened</param> /// <returns></returns> public static double ManhattanDistance(double[] a, double[] b, double minDistance, out bool better) { if (a.Length != b.Length) throw new Exception("(Functions::ManhattanDistance) In order to compare vectors they should have the same size."); double distance = 0; better = true; for (int i = 0; i < a.Length; ++i) { distance += Math.Abs(a[i] - b[i]); if (distance >= minDistance) { better = false; break; } } return distance; } /// <summary> /// Obtains Manhattan distance considering missing dimensions (zero-valued), /// and returns a value normalized to the number of coincident elements. /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> public static double ManhattanDistanceNormalized(double[] a, double[] b) { if (a.Length != b.Length) throw new Exception("(Function::ManhattanDistanceNormalized) In order to compare vectors they should have the same size."); double d = 0.0; int matching = 0; for (int i = 0; i < a.Length; ++i) { if (a[i] != 0 && b[i] != 0) // Null values are missing or irrelevant dimensions { d += Math.Abs(a[i] - b[i]); matching++; } } if (matching > 0) // Normalization needed because number of coincident elements may change d = d / matching; else // No matches means that these samples are not similar d = 100000; return d; } /// <summary> /// Returns Euclidean distance /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> public static double EuclideanDistance(double[] a, double[] b) { if (a.Length != b.Length) throw new Exception("(Function::EuclideanDistance) In order to compare vectors they should have the same size."); double distance = 0; for (int i = 0; i < a.Length; ++i) { distance += Math.Pow(a[i] - b[i], 2); } return Math.Sqrt(distance); } /// <summary> /// Returns Euclidean distance /// Optimized to support lower bound (when better = false, the returned value should be ignored) /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> public static double EuclideanDistance(double[] a, double[] b, double minDistance, out bool better) { if (a.Length != b.Length) throw new Exception("(Function::EuclideanDistance) In order to compare vectors they should have the same size."); double distance = 0; better = true; for (int i = 0; i < a.Length; ++i) { distance += Math.Pow(a[i] - b[i], 2); if (distance >= minDistance) { better = false; break; } } return Math.Sqrt(distance); } /// <summary> /// Obtains Euclidean distance considering missing dimensions (zero-valued), /// and returns a value normalized to the number of coincident elements. /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> public static double EuclideanDistanceNormalized(double[] a, double[] b) { if (a.Length != b.Length) throw new Exception("(Function::EuclideanDistanceNormalized) In order to compare vectors they should have the same size."); double d = 0.0; int matching = 0; for (int i = 0; i < a.Length; ++i) { if (a[i] != 0 && b[i] != 0) // Null values are missing or irrelevant dimensions { d += Math.Pow(a[i] - b[i], 2); matching++; } } if (matching > 0) // Normalization needed because number of coincident elements may change d = d / matching; else // No matches means that these samples are not similar d = double.MaxValue - 1; return Math.Sqrt(d); } /// <summary> /// Returns the Chi-Square distance. /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> public static double ChiSquareDistance(double[] a, double[] b) { if (a.Length != b.Length) throw new Exception("(Function::ChiSquareDistance) In order to compare vectors they should have the same size."); int length = a.Length; double dist = 0.0; for (int i = 0; i < length; ++i) { if (a[i] == 0 && b[i] == 0) continue; dist += (a[i] - b[i]) * (a[i] - b[i]) / a[i] + b[i]; } dist /= 2; return dist; } /// <summary> /// Returns the Bhattacharyya coefficient (amount of overlap). /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> public static double BhattacharyyaCoefficient(double[] a, double[] b) { if (a.Length != b.Length) throw new Exception("(Function::BhattacharyyaDistance) In order to compare vectors they should have the same size."); int length = a.Length; double coeff = 0.0; for (int i = 0; i < length; ++i) { coeff += Math.Sqrt(a[i] * b[i]); } return coeff; } /// <summary> /// Returns the Kullback-Leibler divergence (from a to b, not symmetric). /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> public static double KullbackLeiblerDivergence(double[] a, double[] b) { if (a.Length != b.Length) throw new Exception("(Function::KullbackLeiblerDivergence) In order to compare vectors they should have the same size."); int length = a.Length; double klDiv = 0.0; for (int i = 0; i < length; ++i) { if (a[i] == 0) continue; if (b[i] == 0) continue; klDiv += a[i] * Math.Log(a[i] / b[i]); } return klDiv / Math.Log(2); } /// <summary> /// Checks wether or not two arrays are equal /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> public static bool Equal(double[] a, double[] b) { if (a.Length != b.Length) throw new Exception("(Function::Equal) In order to compare vectors they should have the same size."); bool result = true; for (int i = 0; i < a.Length; ++i) { if (a[i] != b[i]) { result = false; break; } } return result; } /// <summary> /// Normalizes the given vector wrt p (divides each element by p) /// </summary> /// <param name="vec"></param> /// <param name="p"></param> /// <returns></returns> public static double[] Normalize(double[] vec, double p) { double[] norm = new double[vec.Length]; if (p != 0) { for (int i = 0; i < norm.Length; ++i) norm[i] = vec[i] / p; } return norm; } /// <summary> /// Normalizes the given array by dividing each element by the corresponding position of count /// </summary> /// <param name="array"></param> /// <param name="count"></param> public static double[] Normalize(double[] array, double[] count) { double[] norm = new double[array.Length]; for (int i = 0; i < array.Length; ++i) if (count[i] > 0) norm[i] = array[i] / count[i]; return norm; } /// <summary> /// Normalizes the given array by dividing each element by the corresponding position of count /// </summary> /// <param name="array"></param> /// <param name="count"></param> public static double[] Normalize(double[] array, int[] count) { double[] norm = new double[array.Length]; for (int i = 0; i < array.Length; ++i) if (count[i] > 0) norm[i] = array[i] / count[i]; return norm; } /// <summary> /// Returns an array with the sums of the i-th values of the given vectors /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> public static double[] SumArrays(double[] a, double[] b) { double[] sum = new double[a.Length]; for (int i = 0; i < sum.Length; ++i) sum[i] = a[i] + b[i]; return sum; } /// <summary> /// Returns the array elevated to the given power /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> public static double[] PowArray(double[] a, double pow) { double[] result = new double[a.Length]; for (int i = 0; i < result.Length; ++i) result[i] = Math.Pow(a[i], pow); return result; } /// <summary> /// Returns the array with its squared root values /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> public static double[] SqrtArray(double[] a) { double[] result = new double[a.Length]; for (int i = 0; i < result.Length; ++i) result[i] = Math.Sqrt(a[i]); return result; } /// <summary> /// Vector substraction /// </summary> /// <param name="vector1"></param> /// <param name="vector2"></param> /// <returns></returns> public static double[] Subtract(double[] vector1, double[] vector2) { double[] sub = new double[vector1.Length]; for (int i = 0; i < vector1.Length; ++i) sub[i] = vector1[i] - vector2[i]; return sub; } /// <summary> /// Returns a random vector of doubles /// </summary> /// <param name="length"></param> /// <returns></returns> public static double[] Random(int length) { double[] random = new double[length]; for (int i = 0; i < length; ++i) random[i] = rand.NextDouble(); // it can't be 1, but 0.99 should do it return random; } /// <summary> /// Adapts the first vector to the second by a certain coeff /// </summary> /// <param name="from"></param> /// <param name="to"></param> /// <returns>adaptation</returns> public static double[] AdaptTo(double[] from, double[] to, double coeff) { double[] result = new double[from.Length]; for (int i = 0; i < result.Length; ++i) result[i] = from[i] + coeff * (to[i] - from[i]); return result; } /// <summary> /// Returns the average vector of the given ones /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> public static double[] Average(double[] a, double[] b) { double[] result = new double[a.Length]; for (int i = 0; i < result.Length; ++i) result[i] = 0.5 * (a[i] + b[i]); return result; } /// <summary> /// Adds to the given total array the sample array and updates the count array with the new amount of non-zero values /// </summary> /// <param name="total"></param> /// <param name="sample"></param> /// <param name="count"></param> public static void SumSamples(double[] total, double[] sample, int[] count) { for (int i = 0; i < sample.Length; ++i) { if (sample[i] != 0) { total[i] += sample[i]; count[i]++; } } } /// <summary> /// Returns the median value (average of medians if there are an even number of values) /// </summary> /// <param name="values"></param> /// <returns></returns> public static double Median(IEnumerable<double> values) { double median; List<double> rSorted = new List<double>(values); rSorted.Sort(); if (rSorted.Count % 2 == 1) median = rSorted[rSorted.Count / 2]; else median = (rSorted[rSorted.Count / 2] + rSorted[(rSorted.Count / 2) - 1]) / 2; return median; } /// <summary> /// Returns the indicated percentil value. Call with 0.25 for 1st quartil, 0.5 for median and 0.75 for 3rd quartil /// </summary> /// <param name="sequence"></param> /// <param name="excelPercentile">0 to 1</param> /// <returns></returns> public static double Percentile(List<double> values, double excelPercentile) { List<double> sequence = new List<double>(values); sequence.Sort(); int N = sequence.Count; double n = (N - 1) * excelPercentile + 1; // Another method: double n = (N + 1) * excelPercentile; if (n == 1d) return sequence[0]; else if (n == N) return sequence[N - 1]; else { int k = (int)n; double d = n - k; return sequence[k - 1] + d * (sequence[k] - sequence[k - 1]); } } /// <summary> /// Obtains the corrected sample standard deviation and returns also the average /// </summary> /// <param name="values"></param> /// <returns></returns> public static double CalculateStdDev(IEnumerable<double> values) { double mean; return CalculateStdDev(values, out mean); } /// <summary> /// Obtains the corrected sample standard deviation and returns also the average /// </summary> /// <param name="values"></param> /// <param name="mean"></param> /// <returns></returns> public static double CalculateStdDev(IEnumerable<double> values, out double mean) { double ret = 0; mean = 0; if (values.Count() > 0) { //Compute the Average double avg = values.Average(); //Perform the Sum of (value-avg)^2 double sum = values.Sum(d => Math.Pow(d - avg, 2)); //Put it all together ret = Math.Sqrt((sum) / (values.Count() - 1)); mean = avg; } return ret; } public static Bitmap RotateBitmap(Bitmap b, float angle) { // Take width/height change into account int R1 = 0, R2 = 0; if (b.Width > b.Height) R2 = b.Width - b.Height; else R1 = b.Height - b.Width; //create a new empty bitmap to hold rotated image int newWidth = b.Width + R1 + 40; int newHeight = b.Height + R2 + 40; Bitmap returnBitmap = new Bitmap(newWidth, newHeight); returnBitmap.SetResolution(b.HorizontalResolution, b.VerticalResolution); //make a graphics object from the empty bitmap Graphics g = Graphics.FromImage(returnBitmap); //move rotation point to center of image g.TranslateTransform((float)newWidth / 2, (float)newHeight / 2); //rotate g.RotateTransform(angle); //move image back g.TranslateTransform(-(float)newWidth / 2, -(float)newHeight / 2); //draw passed in image onto graphics object g.DrawImage(b, new PointF(R1 / 2 + 20, R2 / 2 + 20)); return returnBitmap; } /// <summary> /// Resizes given bitmap to the given size /// </summary> /// <param name="sourceBMP"></param> /// <param name="width"></param> /// <param name="height"></param> /// <returns></returns> public static Bitmap ResizeBitmap(Bitmap sourceBMP, int width, int height) { Bitmap result = new Bitmap(width, height); using (Graphics g = Graphics.FromImage(result)) g.DrawImage(sourceBMP, 0, 0, width, height); return result; } /// <summary> /// Returns the two highest values and the key of the heighest /// </summary> /// <param name="weightingScheme"></param> /// <param name="rSecond"></param> /// <param name="currentHighest"></param> /// <returns></returns> public static double FirstAndSecondMax(AssociativeArray<string, double> weightingScheme, out double rSecond, out string currentHighest) { double rMax = double.MinValue; rSecond = double.MinValue; currentHighest = ""; foreach (var key in weightingScheme.Keys) // Compute the max and the second max { if (weightingScheme[key] > rMax) { rSecond = rMax; rMax = weightingScheme[key]; currentHighest = key; } else if (weightingScheme[key] > rSecond) rSecond = weightingScheme[key]; } return rMax; } /// <summary> /// Returns the sum of squared errors: the sum of squared distances of each sample to its cluster. /// </summary> /// <param name="centers"></param> /// <param name="clusterAssignments"></param> /// <returns></returns> public static double SumOfSquaredErrors(Dictionary<int, double[]> centers, AssociativeArray<int, List<double[]>> clusterAssignments) { double sse = 0.0; if (centers != null && centers.Count > 1) { foreach (int key in clusterAssignments.Keys) { foreach (double[] sample in clusterAssignments[key]) { for (int i = 0; i < sample.Length; ++i) sse += Math.Pow(sample[i] - centers[key][i], 2); } } } return sse; } /// <summary> /// Prints the Q1, median and Q3 values in seperate files for vox plots. /// studyStats[k, l, success_rate] /// </summary> /// <param name="studyStats"></param> public static void Print3DBoxPlotData(AssociativeMatrix<int, int, List<double>> studyStats) { // Print arrays for Median, Q1 and Q3 TextWriter stats = new StreamWriter("Medians.csv"); foreach(var k in studyStats.RowKeys.OrderBy(k => k)) stats.Write(", " + k); stats.WriteLine(); foreach(var l in studyStats.ColumnKeys(studyStats.RowKeys[0]).OrderBy(k => k)) { stats.Write(l); foreach(var k in studyStats.RowKeys.OrderBy(k => k)) { var rates = studyStats[k, l]; double median = Functions.Median(rates); stats.Write("; " + median); } stats.WriteLine(); } stats.Close(); stats = new StreamWriter("Q1s.csv"); foreach (var k in studyStats.RowKeys.OrderBy(k => k)) stats.Write(", " + k); stats.WriteLine(); foreach (var l in studyStats.ColumnKeys(studyStats.RowKeys[0]).OrderBy(k => k)) { stats.Write(l); foreach (var k in studyStats.RowKeys.OrderBy(k => k)) { var rates = studyStats[k, l]; double q1 = Functions.Percentile(rates, 0.25); stats.Write("; " + q1); } stats.WriteLine(); } stats.Close(); stats = new StreamWriter("Q3s.csv"); foreach (var k in studyStats.RowKeys.OrderBy(k => k)) stats.Write(", " + k); stats.WriteLine(); foreach (var l in studyStats.ColumnKeys(studyStats.RowKeys[0]).OrderBy(k => k)) { stats.Write(l); foreach (var k in studyStats.RowKeys.OrderBy(k => k)) { var rates = studyStats[k, l]; double q3 = Functions.Percentile(rates, 0.75); stats.Write("; " + q3); } stats.WriteLine(); } stats.Close(); } /// <summary> /// Returns true if all members are zero /// </summary> /// <param name="feature"></param> /// <returns></returns> public static bool IsZero(double[] feature) { bool result = true; foreach (var f in feature) { if (f != 0.0) { result = false; break; } } return result; } /// <summary> /// 2D Convolution for 1D arrays. /// </summary> /// <param name="source"></param> /// <param name="dimX"></param> /// <param name="dimY"></param> /// <param name="kernel"></param> /// <returns></returns> public static double[] Convolution2D(double[] source, int dimX, int dimY, double[,] kernel) { double kSize = Math.Sqrt(kernel.Length); if (kernel.Length < 9 || kSize % 1 != 0 || kSize % 2 == 0) throw new Exception("(Function::Convolution2D) Invalid kernel."); double[] result = new double[source.Length]; int halfKSize = (int) kSize / 2; for (int i = 0; i < dimX; ++i) { for (int j = 0; j < dimY; ++j) { double value = 0.0; int pos = i * dimY + j; for (int ki = -halfKSize; ki <= halfKSize; ++ki) { for (int kj = -halfKSize; kj <= halfKSize; ++kj) { if (i + ki < 0 || i + ki >= dimX) break; if (j + kj < 0 || j + kj >= dimY) break; value += kernel[halfKSize + ki, halfKSize + kj] * source[(i + ki) * dimY + (j + kj)]; } } result[pos] = value; } } return result; } /// <summary> /// Returns an IEnumerable of integer values that increase by stepSize in the specified range. /// </summary> /// <param name="startIndex"></param> /// <param name="endIndex"></param> /// <param name="stepSize"></param> /// <returns></returns> public static IEnumerable<int> SteppedIterator(int startIndex, int endIndex, int stepSize) { for (int i = startIndex; i < endIndex; i = i + stepSize) { yield return i; } } /// <summary> /// Returns an IEnumerable of double values that increase by stepSize in the specified range. /// </summary> /// <param name="startIndex"></param> /// <param name="endIndex"></param> /// <param name="stepSize"></param> /// <returns></returns> public static IEnumerable<double> SteppedIterator(double startIndex, double endIndex, double stepSize) { for (double i = startIndex; i < endIndex; i = i + stepSize) { yield return i; } } } }
apache-2.0
ederign/uf-js
uf-js-client-only/target/.generated/org/uberfire/client/workbench/widgets/notfound/ActivityNotFoundView_ActivityNotFoundViewBinderImpl.java
5911
package org.uberfire.client.workbench.widgets.notfound; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Element; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiBinderUtil; import com.google.gwt.user.client.ui.Widget; public class ActivityNotFoundView_ActivityNotFoundViewBinderImpl implements UiBinder<com.google.gwt.user.client.ui.Widget, org.uberfire.client.workbench.widgets.notfound.ActivityNotFoundView>, org.uberfire.client.workbench.widgets.notfound.ActivityNotFoundView.ActivityNotFoundViewBinder { public com.google.gwt.user.client.ui.Widget createAndBindUi(final org.uberfire.client.workbench.widgets.notfound.ActivityNotFoundView owner) { return new Widgets(owner).get_f_VerticalPanel1(); } /** * Encapsulates the access to all inner widgets */ class Widgets { private final org.uberfire.client.workbench.widgets.notfound.ActivityNotFoundView owner; final com.google.gwt.event.dom.client.ClickHandler handlerMethodWithNameVeryUnlikelyToCollideWithUserFieldNames1 = new com.google.gwt.event.dom.client.ClickHandler() { public void onClick(com.google.gwt.event.dom.client.ClickEvent event) { owner.onClickOkButton(event); } }; public Widgets(final org.uberfire.client.workbench.widgets.notfound.ActivityNotFoundView owner) { this.owner = owner; } /** * Getter for clientBundleFieldNameUnlikelyToCollideWithUserSpecifiedFieldOkay called 0 times. Type: GENERATED_BUNDLE. Build precedence: 1. */ private org.uberfire.client.workbench.widgets.notfound.ActivityNotFoundView_ActivityNotFoundViewBinderImpl_GenBundle get_clientBundleFieldNameUnlikelyToCollideWithUserSpecifiedFieldOkay() { return build_clientBundleFieldNameUnlikelyToCollideWithUserSpecifiedFieldOkay(); } private org.uberfire.client.workbench.widgets.notfound.ActivityNotFoundView_ActivityNotFoundViewBinderImpl_GenBundle build_clientBundleFieldNameUnlikelyToCollideWithUserSpecifiedFieldOkay() { // Creation section. final org.uberfire.client.workbench.widgets.notfound.ActivityNotFoundView_ActivityNotFoundViewBinderImpl_GenBundle clientBundleFieldNameUnlikelyToCollideWithUserSpecifiedFieldOkay = (org.uberfire.client.workbench.widgets.notfound.ActivityNotFoundView_ActivityNotFoundViewBinderImpl_GenBundle) GWT.create(org.uberfire.client.workbench.widgets.notfound.ActivityNotFoundView_ActivityNotFoundViewBinderImpl_GenBundle.class); // Setup section. return clientBundleFieldNameUnlikelyToCollideWithUserSpecifiedFieldOkay; } /** * Getter for f_VerticalPanel1 called 1 times. Type: DEFAULT. Build precedence: 1. */ private com.google.gwt.user.client.ui.VerticalPanel get_f_VerticalPanel1() { return build_f_VerticalPanel1(); } private com.google.gwt.user.client.ui.VerticalPanel build_f_VerticalPanel1() { // Creation section. final com.google.gwt.user.client.ui.VerticalPanel f_VerticalPanel1 = (com.google.gwt.user.client.ui.VerticalPanel) GWT.create(com.google.gwt.user.client.ui.VerticalPanel.class); // Setup section. f_VerticalPanel1.add(get_f_HorizontalPanel2()); f_VerticalPanel1.add(get_requestedPlaceIdentifierLabel()); f_VerticalPanel1.add(get_okButton()); return f_VerticalPanel1; } /** * Getter for f_HorizontalPanel2 called 1 times. Type: DEFAULT. Build precedence: 2. */ private com.google.gwt.user.client.ui.HorizontalPanel get_f_HorizontalPanel2() { return build_f_HorizontalPanel2(); } private com.google.gwt.user.client.ui.HorizontalPanel build_f_HorizontalPanel2() { // Creation section. final com.google.gwt.user.client.ui.HorizontalPanel f_HorizontalPanel2 = (com.google.gwt.user.client.ui.HorizontalPanel) GWT.create(com.google.gwt.user.client.ui.HorizontalPanel.class); // Setup section. f_HorizontalPanel2.add(get_f_Label3()); return f_HorizontalPanel2; } /** * Getter for f_Label3 called 1 times. Type: DEFAULT. Build precedence: 3. */ private com.google.gwt.user.client.ui.Label get_f_Label3() { return build_f_Label3(); } private com.google.gwt.user.client.ui.Label build_f_Label3() { // Creation section. final com.google.gwt.user.client.ui.Label f_Label3 = (com.google.gwt.user.client.ui.Label) GWT.create(com.google.gwt.user.client.ui.Label.class); // Setup section. f_Label3.setText("Activity not found"); return f_Label3; } /** * Getter for requestedPlaceIdentifierLabel called 1 times. Type: DEFAULT. Build precedence: 2. */ private com.google.gwt.user.client.ui.Label get_requestedPlaceIdentifierLabel() { return build_requestedPlaceIdentifierLabel(); } private com.google.gwt.user.client.ui.Label build_requestedPlaceIdentifierLabel() { // Creation section. final com.google.gwt.user.client.ui.Label requestedPlaceIdentifierLabel = (com.google.gwt.user.client.ui.Label) GWT.create(com.google.gwt.user.client.ui.Label.class); // Setup section. owner.requestedPlaceIdentifierLabel = requestedPlaceIdentifierLabel; return requestedPlaceIdentifierLabel; } /** * Getter for okButton called 1 times. Type: DEFAULT. Build precedence: 2. */ private com.github.gwtbootstrap.client.ui.Button get_okButton() { return build_okButton(); } private com.github.gwtbootstrap.client.ui.Button build_okButton() { // Creation section. final com.github.gwtbootstrap.client.ui.Button okButton = (com.github.gwtbootstrap.client.ui.Button) GWT.create(com.github.gwtbootstrap.client.ui.Button.class); // Setup section. okButton.setText("OK"); okButton.addClickHandler(handlerMethodWithNameVeryUnlikelyToCollideWithUserFieldNames1); return okButton; } } }
apache-2.0
stdlib-js/www
public/docs/api/latest/@stdlib/stats/iter/mmin/benchmark_bundle.js
909008
// 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":169}],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":73,"@stdlib/utils/constructor-name":347,"@stdlib/utils/get-prototype-of":370}],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":61}],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":64}],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":67}],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":70}],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":100,"@stdlib/constants/float64/pinf":247}],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":102}],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":106,"@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":108,"@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":110,"@stdlib/constants/int8/max":252,"@stdlib/constants/int8/min":253}],50:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * Test for native `Symbol.iterator` support. * * @module @stdlib/assert/has-iterator-symbol-support * * @example * var hasIteratorSymbolSupport = require( '@stdlib/assert/has-iterator-symbol-support' ); * * var bool = hasIteratorSymbolSupport(); * // returns <boolean> */ // MODULES // var hasIteratorSymbolSupport = require( './main.js' ); // EXPORTS // module.exports = hasIteratorSymbolSupport; },{"./main.js":51}],51:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var hasOwnProp = require( '@stdlib/assert/has-own-property' ); // MAIN // /** * Tests for native `Symbol.iterator` support. * * @returns {boolean} boolean indicating if an environment has `Symbol.iterator` support * * @example * var bool = hasIteratorSymbolSupport(); * // returns <boolean> */ function hasIteratorSymbolSupport() { return ( typeof Symbol === 'function' && typeof Symbol( 'foo' ) === 'symbol' && hasOwnProp( Symbol, 'iterator' ) && typeof Symbol.iterator === 'symbol' ); } // EXPORTS // module.exports = hasIteratorSymbolSupport; },{"@stdlib/assert/has-own-property":55}],52:[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":437}],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 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":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'; // 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":52,"@stdlib/assert/is-buffer":90}],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 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":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'; // 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; },{}],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 `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":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'; // 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; },{}],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 `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":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 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":57}],61:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * Test for native `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":62}],62:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":63,"@stdlib/assert/is-uint16array":172,"@stdlib/constants/uint16/max":254}],63:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MAIN // var main = ( typeof Uint16Array === 'function' ) ? Uint16Array : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],64:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * 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":65}],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'; // 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":66,"@stdlib/assert/is-uint32array":174,"@stdlib/constants/uint32/max":255}],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'; // MAIN // var main = ( typeof Uint32Array === 'function' ) ? Uint32Array : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],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'; /** * 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":68}],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'; // 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":69,"@stdlib/assert/is-uint8array":176,"@stdlib/constants/uint8/max":256}],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'; // MAIN // var main = ( typeof Uint8Array === 'function' ) ? Uint8Array : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],70:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * Test 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":71}],71:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":72,"@stdlib/assert/is-uint8clampedarray":178}],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 // var main = ( typeof Uint8ClampedArray === 'function' ) ? Uint8ClampedArray : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],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'; /** * 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":74}],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'; // 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; },{}],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 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":77}],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'; /** * 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":75,"./main.js":77,"./polyfill.js":78}],77:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":404}],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 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":55,"@stdlib/assert/is-array":81,"@stdlib/assert/is-enumerable-property":95,"@stdlib/constants/uint32/max":255,"@stdlib/math/base/assert/is-integer":259}],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 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":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 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":239,"@stdlib/math/base/assert/is-integer":259}],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 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":82}],82:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":404}],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'; /** * 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":84,"./object.js":85,"./primitive.js":86,"@stdlib/utils/define-nonenumerable-read-only-property":355}],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'; // 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":85,"./primitive.js":86}],85:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":88,"@stdlib/assert/has-tostringtag-support":59,"@stdlib/utils/native-class":404}],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'; /** * 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; },{}],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'; // eslint-disable-next-line stdlib/no-redeclare var toString = Boolean.prototype.toString; // non-generic // EXPORTS // module.exports = toString; },{}],88:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":87}],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'; // EXPORTS // module.exports = true; },{}],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 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":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 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":147}],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'; /** * 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":93}],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'; // 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":240,"@stdlib/math/base/assert/is-integer":259}],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 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":97}],95:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * Test 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":96}],96:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":94,"./native.js":97,"@stdlib/assert/is-integer":112,"@stdlib/assert/is-nan":122,"@stdlib/assert/is-string":162}],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'; // 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; },{}],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 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":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 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":370,"@stdlib/utils/native-class":404}],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 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":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 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":404}],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 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":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 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":404}],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 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":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 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":431}],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 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":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 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":404}],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 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":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 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":404}],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 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":111}],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 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":404}],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'; /** * 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":114,"./object.js":115,"./primitive.js":116,"@stdlib/utils/define-nonenumerable-read-only-property":355}],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 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":246,"@stdlib/constants/float64/pinf":247,"@stdlib/math/base/assert/is-integer":259}],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 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":115,"./primitive.js":116}],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 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":113,"@stdlib/assert/is-number":141}],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'; // 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":113,"@stdlib/assert/is-number":141}],117:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * Test if a value is iterator-like. * * @module @stdlib/assert/is-iterator-like * * @example * var isIteratorLike = require( '@stdlib/assert/is-iterator-like' ); * * var it = { * 'next': function noop() {} * }; * var bool = isIteratorLike( it ); * // returns true * * bool = isIteratorLike( {} ); * // returns false */ // MODULES // var isIterator = require( './main.js' ); // EXPORTS // module.exports = isIterator; },{"./main.js":118}],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'; // MODULES // var isFunction = require( '@stdlib/assert/is-function' ); // MAIN // /** * Tests if a value is iterator-like. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is iterator-like * * @example * var it = { * 'next': function noop() {} * }; * var bool = isIteratorLike( it ); * // returns true * * @example * var bool = isIteratorLike( {} ); * // returns false * * @example * var bool = isIteratorLike( null ); * // returns false */ function isIteratorLike( value ) { return ( value !== null && typeof value === 'object' && isFunction( value.next ) && value.next.length === 0 ); } // EXPORTS // module.exports = isIteratorLike; },{"@stdlib/assert/is-function":104}],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 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}],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'; /** * 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":121}],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 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":119}],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 `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":123,"./object.js":124,"./primitive.js":125,"@stdlib/utils/define-nonenumerable-read-only-property":355}],123:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // MAIN // /** * Tests if a value is `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":124,"./primitive.js":125}],124:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var isNumber = require( '@stdlib/assert/is-number' ).isObject; 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":141,"@stdlib/math/base/assert/is-nan":261}],125:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive; 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":141,"@stdlib/math/base/assert/is-nan":261}],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 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":127}],127:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // 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; },{}],128:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * Test if a value is 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":129}],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. */ /* 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":126}],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'; /** * 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":131,"@stdlib/assert/tools/array-like-function":183,"@stdlib/utils/define-nonenumerable-read-only-property":355}],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 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":132,"./object.js":133,"./primitive.js":134,"@stdlib/utils/define-nonenumerable-read-only-property":355}],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 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":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 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":112}],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 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":112}],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 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":136,"./object.js":137,"./primitive.js":138,"@stdlib/utils/define-nonenumerable-read-only-property":355}],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'; // 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":137,"./primitive.js":138}],137:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":141}],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 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":141}],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'; /** * 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":140}],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 `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; },{}],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'; /** * 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":142,"./object.js":143,"./primitive.js":144,"@stdlib/utils/define-nonenumerable-read-only-property":355}],142:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":143,"./primitive.js":144}],143:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":146,"@stdlib/assert/has-tostringtag-support":59,"@stdlib/number/ctor":278,"@stdlib/utils/native-class":404}],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 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; },{}],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'; // 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":278}],146:[function(require,module,exports){ arguments[4][88][0].apply(exports,arguments) },{"./tostring.js":145,"dup":88}],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 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":148,"@stdlib/assert/tools/array-function":181,"@stdlib/utils/define-nonenumerable-read-only-property":355}],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'; /** * 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; },{}],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 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":150}],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 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":81}],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'; /** * 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":152}],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 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":55,"@stdlib/assert/is-function":104,"@stdlib/assert/is-object":149,"@stdlib/utils/get-prototype-of":370,"@stdlib/utils/native-class":404}],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'; /** * 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":154,"./object.js":155,"./primitive.js":156,"@stdlib/utils/define-nonenumerable-read-only-property":355}],154:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":155,"./primitive.js":156}],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 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":112}],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 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":112}],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'; var exec = RegExp.prototype.exec; // non-generic // EXPORTS // module.exports = exec; },{}],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 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":159}],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 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":160,"@stdlib/assert/has-tostringtag-support":59,"@stdlib/utils/native-class":404}],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 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":157}],161:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * Test if a value is 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":162,"@stdlib/assert/tools/array-function":181,"@stdlib/utils/define-nonenumerable-read-only-property":355}],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'; /** * 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":163,"./object.js":164,"./primitive.js":165,"@stdlib/utils/define-nonenumerable-read-only-property":355}],163:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":164,"./primitive.js":165}],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 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":166,"@stdlib/assert/has-tostringtag-support":59,"@stdlib/utils/native-class":404}],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'; /** * 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; },{}],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 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":167}],167:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // eslint-disable-next-line stdlib/no-redeclare var valueOf = String.prototype.valueOf; // non-generic // EXPORTS // module.exports = valueOf; },{}],168:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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}],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'; /** * 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":170}],170:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":168,"./names.json":171,"@stdlib/array/float64":5,"@stdlib/assert/has-float64array-support":36,"@stdlib/utils/constructor-name":347,"@stdlib/utils/function-name":367,"@stdlib/utils/get-prototype-of":370}],171:[function(require,module,exports){ module.exports=[ "Int8Array", "Uint8Array", "Uint8ClampedArray", "Int16Array", "Uint16Array", "Int32Array", "Uint32Array", "Float32Array", "Float64Array" ] },{}],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 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":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 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":404}],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 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":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 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":404}],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'; /** * 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":177}],177:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":404}],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'; /** * 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":179}],179:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":404}],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 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":81}],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'; /** * 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":180}],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'; // 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":79}],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'; /** * 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":182}],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'; // 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":206,"./harness":207,"@stdlib/assert/is-function":104,"@stdlib/streams/node/transform":329,"@stdlib/utils/define-nonenumerable-read-only-property":355}],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 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":55}],186:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // EXPORTS // module.exports = clearTimeout; },{}],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'; // 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":307,"@stdlib/string/replace":335,"@stdlib/string/trim":337}],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 // /** * 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; },{}],189:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":226}],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'; // 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; },{}],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 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; },{}],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 // /** * 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; },{}],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 // /** * 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; },{}],194:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":185,"./comment.js":187,"./deep_equal.js":188,"./end.js":189,"./ended.js":190,"./equal.js":191,"./exit.js":192,"./fail.js":193,"./not_deep_equal.js":195,"./not_equal.js":196,"./not_ok.js":197,"./ok.js":198,"./pass.js":199,"./run.js":200,"./skip.js":202,"./todo.js":203,"@stdlib/time/tic":341,"@stdlib/time/toc":345,"@stdlib/utils/define-nonenumerable-read-only-property":355,"@stdlib/utils/define-property":362,"@stdlib/utils/inherit":383,"events":436}],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 // /** * 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; },{}],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'; // 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; },{}],197:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MAIN // /** * 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; },{}],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 // /** * 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; },{}],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 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; },{}],200:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // 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":186,"./set_timeout.js":201}],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'; // EXPORTS // module.exports = setTimeout; },{}],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'; // 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; },{}],203:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MAIN // /** * 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; },{}],204:[function(require,module,exports){ module.exports={ "skip": false, "iterations": null, "repeats": 3, "timeout": 300000 } },{}],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 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":207,"./log":213,"./utils/can_emit_exit.js":224,"./utils/process.js":227,"@stdlib/assert/has-own-property":55,"@stdlib/assert/is-boolean":83,"@stdlib/assert/is-function":104,"@stdlib/assert/is-node-writable-stream-like":128,"@stdlib/assert/is-plain-object":151,"@stdlib/utils/noop":411,"@stdlib/utils/omit":413,"@stdlib/utils/pick":415}],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 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":205,"./utils/can_emit_exit.js":224}],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 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":194,"./../defaults.json":204,"./../runner":221,"./../utils/next_tick.js":226,"./init.js":208,"./validate.js":211,"@stdlib/assert/has-own-property":55,"@stdlib/assert/is-boolean":83,"@stdlib/assert/is-function":104,"@stdlib/assert/is-plain-object":151,"@stdlib/assert/is-string":162,"@stdlib/utils/copy":351,"@stdlib/utils/define-nonenumerable-read-only-accessor":353,"@stdlib/utils/define-nonenumerable-read-only-property":355}],208:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":209,"./pretest.js":210}],209:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // 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":194,"@stdlib/assert/is-string":162,"@stdlib/utils/copy":351}],210:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":194,"@stdlib/assert/is-string":162,"@stdlib/utils/copy":351}],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'; // 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":55,"@stdlib/assert/is-boolean":83,"@stdlib/assert/is-null":139,"@stdlib/assert/is-plain-object":151,"@stdlib/assert/is-positive-integer":153}],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'; /** * 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":184}],213:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // 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":214,"@stdlib/streams/node/transform":329,"@stdlib/string/from-code-point":333}],214:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MAIN // /** * 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; },{}],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'; // MAIN // /** * Removes any pending benchmarks. * * @private */ function clear() { /* eslint-disable no-invalid-this */ this._benchmarks.length = 0; } // EXPORTS // module.exports = clear; },{}],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 // /** * 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; },{}],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. */ /* 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":226,"@stdlib/assert/is-string":162,"@stdlib/streams/node/transform":329}],218:[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":55,"@stdlib/regexp/eol":307,"@stdlib/string/replace":335}],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'; // 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; },{}],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'; // 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; },{}],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 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":215,"./close.js":216,"./create_stream.js":217,"./exit.js":220,"./push.js":222,"./run.js":223,"@stdlib/streams/node/transform":329,"@stdlib/utils/define-property":362,"@stdlib/utils/inherit":383,"events":436}],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. */ /* 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":218,"./encode_result.js":219,"@stdlib/assert/is-string":162}],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'; // MAIN // /** * Runs pending benchmarks. * * @private */ function run() { /* eslint-disable no-invalid-this */ this.emit( '_run' ); } // EXPORTS // module.exports = run; },{}],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'; // 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":225,"@stdlib/assert/is-browser":89}],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'; // MODULES // var proc = require( './process.js' ); // MAIN // var bool = ( proc && typeof proc.exit === 'function' ); // EXPORTS // module.exports = bool; },{"./process.js":227}],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'; // 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; },{}],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'; // MODULES // var proc = require( 'process' ); // EXPORTS // module.exports = proc; },{"process":447}],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'; /** * 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":212}],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'; /** * 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":230,"./ndarray.js":231,"@stdlib/utils/define-nonenumerable-read-only-property":355}],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'; // 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; },{}],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'; // 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; },{}],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'; // MAIN // var ctor = require( 'buffer' ).Buffer; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = ctor; },{"buffer":437}],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'; /** * 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":232,"./polyfill.js":234,"@stdlib/assert/has-node-buffer-support":53}],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'; // TODO: write (browser) polyfill // MAIN // /** * Buffer constructor. * * @throws {Error} not implemented */ function polyfill() { throw new Error( 'not implemented' ); } // EXPORTS // module.exports = polyfill; },{}],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'; // 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":104,"@stdlib/buffer/ctor":233}],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'; /** * 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":235,"./main.js":237,"./polyfill.js":238}],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'; // 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":90,"@stdlib/buffer/ctor":233}],238:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":90,"@stdlib/buffer/ctor":233}],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'; /** * 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; },{}],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'; /** * 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; },{}],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 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; },{}],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'; /** * 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; },{}],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'; /** * 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; },{}],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'; /** * 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; },{}],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'; /** * Maximum double-precision floating-point number. * * @module @stdlib/constants/float64/max * @type {number} * * @example * var FLOAT64_MAX = require( '@stdlib/constants/float64/max' ); * // returns 1.7976931348623157e+308 */ // MAIN // /** * Maximum double-precision floating-point number. * * ## Notes * * The maximum is given by * * ```tex * 2^{1023} (2 - 2^{-52}) * ``` * * @constant * @type {number} * @default 1.7976931348623157e+308 * @see [IEEE 754]{@link http://en.wikipedia.org/wiki/IEEE_754-1985} */ var FLOAT64_MAX = 1.7976931348623157e+308; // EXPORTS // module.exports = FLOAT64_MAX; },{}],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 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":278}],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'; /** * 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; },{}],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 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":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 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":267}],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 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":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'; // 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; },{}],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 negative zero. * * @module @stdlib/math/base/assert/is-negative-zero * * @example * var isNegativeZero = require( '@stdlib/math/base/assert/is-negative-zero' ); * * var bool = isNegativeZero( -0.0 ); * // returns true * * bool = isNegativeZero( 0.0 ); * // returns false */ // MODULES // var isNegativeZero = require( './main.js' ); // EXPORTS // module.exports = isNegativeZero; },{"./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'; // MODULES // var NINF = require( '@stdlib/constants/float64/ninf' ); // MAIN // /** * Tests if a double-precision floating-point numeric value is negative zero. * * @param {number} x - value to test * @returns {boolean} boolean indicating whether the value is negative zero * * @example * var bool = isNegativeZero( -0.0 ); * // returns true * * @example * var bool = isNegativeZero( 0.0 ); * // returns false */ function isNegativeZero( x ) { return (x === 0.0 && 1.0/x === NINF); } // EXPORTS // module.exports = isNegativeZero; },{"@stdlib/constants/float64/ninf":246}],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":247}],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'; /** * 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":268}],268:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // 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; },{}],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'; /** * 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":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'; // 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":246,"@stdlib/constants/float64/pinf":247,"@stdlib/math/base/assert/is-nan":261,"@stdlib/math/base/assert/is-positive-zero":265}],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'; /** * 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":272}],272:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":273}],273:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":241,"@stdlib/constants/float64/high-word-exponent-mask":242,"@stdlib/constants/float64/high-word-significand-mask":243,"@stdlib/constants/float64/pinf":247,"@stdlib/math/base/assert/is-nan":261,"@stdlib/number/float64/base/from-words":280,"@stdlib/number/float64/base/to-words":283}],274:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // 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":275}],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'; // 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; },{}],276:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * 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":277}],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'; // 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; },{}],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'; /** * 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":279}],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'; // EXPORTS // module.exports = Number; // eslint-disable-line stdlib/require-globals },{}],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'; /** * 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":282}],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'; // 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":120}],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 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":281,"@stdlib/array/float64":5,"@stdlib/array/uint32":23}],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'; /** * 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":285}],284:[function(require,module,exports){ arguments[4][281][0].apply(exports,arguments) },{"@stdlib/assert/is-little-endian":120,"dup":281}],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 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":286}],286:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // 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":284,"@stdlib/array/float64":5,"@stdlib/array/uint32":23}],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'; // 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":261}],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. */ /* 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":287,"./rand_int32.js":291,"@stdlib/array/int32":10,"@stdlib/array/to-json":17,"@stdlib/assert/has-own-property":55,"@stdlib/assert/is-boolean":83,"@stdlib/assert/is-collection":92,"@stdlib/assert/is-int32array":108,"@stdlib/assert/is-plain-object":151,"@stdlib/assert/is-positive-integer":153,"@stdlib/blas/base/gcopy":229,"@stdlib/constants/int32/max":250,"@stdlib/math/base/special/floor":267,"@stdlib/utils/define-nonenumerable-read-only-accessor":353,"@stdlib/utils/define-nonenumerable-read-only-property":355,"@stdlib/utils/define-nonenumerable-read-write-accessor":357}],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'; /** * 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":288,"./main.js":290,"@stdlib/utils/define-nonenumerable-read-only-property":355}],290:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":288,"./rand_int32.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'; // 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":267}],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. */ /* 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":295,"@stdlib/array/int32":10,"@stdlib/array/to-json":17,"@stdlib/assert/has-own-property":55,"@stdlib/assert/is-boolean":83,"@stdlib/assert/is-collection":92,"@stdlib/assert/is-int32array":108,"@stdlib/assert/is-plain-object":151,"@stdlib/assert/is-positive-integer":153,"@stdlib/blas/base/gcopy":229,"@stdlib/constants/int32/max":250,"@stdlib/utils/define-nonenumerable-read-only-accessor":353,"@stdlib/utils/define-nonenumerable-read-only-property":355,"@stdlib/utils/define-nonenumerable-read-write-accessor":357}],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'; /** * 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":292,"./main.js":294,"@stdlib/utils/define-nonenumerable-read-only-property":355}],294:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":292,"./rand_int32.js":295}],295:[function(require,module,exports){ arguments[4][291][0].apply(exports,arguments) },{"@stdlib/constants/int32/max":250,"@stdlib/math/base/special/floor":267,"dup":291}],296:[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":299,"@stdlib/array/to-json":17,"@stdlib/array/uint32":23,"@stdlib/assert/has-own-property":55,"@stdlib/assert/is-boolean":83,"@stdlib/assert/is-collection":92,"@stdlib/assert/is-plain-object":151,"@stdlib/assert/is-positive-integer":153,"@stdlib/assert/is-uint32array":174,"@stdlib/blas/base/gcopy":229,"@stdlib/constants/float64/max-safe-integer":244,"@stdlib/constants/uint32/max":255,"@stdlib/math/base/special/max":269,"@stdlib/math/base/special/uimul":276,"@stdlib/utils/define-nonenumerable-read-only-accessor":353,"@stdlib/utils/define-nonenumerable-read-only-property":355,"@stdlib/utils/define-nonenumerable-read-write-accessor":357}],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'; /** * 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":296,"./main.js":298,"@stdlib/utils/define-nonenumerable-read-only-property":355}],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 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":296,"./rand_uint32.js":299}],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 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":267}],300:[function(require,module,exports){ module.exports={ "name": "mt19937", "copy": true } },{}],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 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":300,"./prngs.js":304,"@stdlib/array/to-json":17,"@stdlib/assert/has-own-property":55,"@stdlib/assert/is-boolean":83,"@stdlib/assert/is-plain-object":151,"@stdlib/utils/define-nonenumerable-read-only-accessor":353,"@stdlib/utils/define-nonenumerable-read-only-property":355,"@stdlib/utils/define-nonenumerable-read-write-accessor":357}],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'; /** * 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":301,"./main.js":303,"@stdlib/utils/define-nonenumerable-read-only-property":355}],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 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":301}],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'; // 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":293,"@stdlib/random/base/minstd-shuffle":289,"@stdlib/random/base/mt19937":297}],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'; /** * Create an iterator for generating uniformly distributed pseudorandom numbers between 0 and 1. * * @module @stdlib/random/iter/randu * * @example * var iterator = require( '@stdlib/random/iter/randu' ); * * var iter = iterator(); * * var r = iter.next().value; * // returns <number> * * r = iter.next().value; * // returns <number> * * r = iter.next().value; * // returns <number> * * // ... */ // MODULES // var iterator = require( './main.js' ); // EXPORTS // module.exports = iterator; },{"./main.js":306}],306:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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 copy = require( '@stdlib/utils/copy' ); var isObject = require( '@stdlib/assert/is-plain-object' ); var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive; var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var MAX_VALUE = require( '@stdlib/constants/float64/max' ); var randu = require( '@stdlib/random/base/randu' ).factory; var iteratorSymbol = require( '@stdlib/symbol/iterator' ); // MAIN // /** * Returns an iterator for generating uniformly distributed pseudorandom numbers between 0 and 1. * * @param {Options} [options] - function options * @param {string} [options.name='mt19937'] - name of a supported pseudorandom number generator (PRNG), which will serve as the underlying source of pseudorandom numbers * @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 * @param {NonNegativeInteger} [options.iter] - number of iterations * @throws {TypeError} options argument must be an object * @throws {TypeError} must provide valid options * @throws {Error} must provide a valid state * @returns {Iterator} iterator * * @example * var iter = iterator(); * * var r = iter.next().value; * // returns <number> * * r = iter.next().value; * // returns <number> * * r = iter.next().value; * // returns <number> * * // ... */ function iterator( options ) { var opts; var iter; var rand; var FLG; var i; if ( arguments.length > 0 ) { if ( !isObject( options ) ) { throw new TypeError( 'invalid argument. Options argument must be an object. Value: `'+options+'`.' ); } opts = copy( options, 1 ); if ( hasOwnProp( opts, 'iter' ) ) { if ( !isNonNegativeInteger( opts.iter ) ) { throw new TypeError( 'invalid option. `iter` option must be a nonnegative integer. Option: `'+opts.iter+'`.' ); } } else { opts.iter = MAX_VALUE; } rand = randu( opts ); if ( opts.copy !== false ) { opts.state = rand.state; // cache a copy of the PRNG state } } else { rand = randu(); opts = { 'iter': MAX_VALUE, 'state': rand.state // cache a copy of the PRNG state }; } i = 0; // Create an iterator protocol-compliant object: iter = {}; setReadOnly( iter, 'next', next ); setReadOnly( iter, 'return', end ); setReadOnlyAccessor( iter, 'seed', getSeed ); setReadOnlyAccessor( iter, 'seedLength', getSeedLength ); setReadWriteAccessor( iter, 'state', getState, setState ); setReadOnlyAccessor( iter, 'stateLength', getStateLength ); setReadOnlyAccessor( iter, 'byteLength', getStateSize ); setReadOnly( iter, 'PRNG', rand.PRNG ); // If an environment supports `Symbol.iterator`, make the iterator iterable: if ( iteratorSymbol ) { setReadOnly( iter, iteratorSymbol, factory ); } return iter; /** * Returns an iterator protocol-compliant object containing the next iterated value. * * @private * @returns {Object} iterator protocol-compliant object */ function next() { i += 1; if ( FLG || i > opts.iter ) { return { 'done': true }; } return { 'value': rand(), 'done': false }; } /** * Finishes an iterator. * * @private * @param {*} [value] - value to return * @returns {Object} iterator protocol-compliant object */ function end( value ) { FLG = true; if ( arguments.length ) { return { 'value': value, 'done': true }; } return { 'done': true }; } /** * Returns a new iterator. * * @private * @returns {Iterator} iterator */ function factory() { return iterator( opts ); } /** * Returns the PRNG seed. * * @private * @returns {*} seed */ function getSeed() { return rand.PRNG.seed; } /** * Returns the PRNG seed length. * * @private * @returns {PositiveInteger} seed length */ function getSeedLength() { return rand.PRNG.seedLength; } /** * Returns the PRNG state length. * * @private * @returns {PositiveInteger} state length */ function getStateLength() { return rand.PRNG.stateLength; } /** * Returns the PRNG state size (in bytes). * * @private * @returns {PositiveInteger} state size (in bytes) */ function getStateSize() { return rand.PRNG.byteLength; } /** * Returns the current pseudorandom number generator state. * * @private * @returns {*} current state */ function getState() { return rand.PRNG.state; } /** * Sets the pseudorandom number generator state. * * @private * @param {*} s - generator state * @throws {Error} must provide a valid state */ function setState( s ) { rand.PRNG.state = s; } } // EXPORTS // module.exports = iterator; },{"@stdlib/assert/has-own-property":55,"@stdlib/assert/is-nonnegative-integer":131,"@stdlib/assert/is-plain-object":151,"@stdlib/constants/float64/max":245,"@stdlib/random/base/randu":302,"@stdlib/symbol/iterator":339,"@stdlib/utils/copy":351,"@stdlib/utils/define-nonenumerable-read-only-accessor":353,"@stdlib/utils/define-nonenumerable-read-only-property":355,"@stdlib/utils/define-nonenumerable-read-write-accessor":357}],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'; /** * 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":308,"./regexp.js":309,"./regexp_capture.js":310,"@stdlib/utils/define-nonenumerable-read-only-property":355}],308:[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":311}],309:[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":308}],310:[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":308}],311:[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":55,"@stdlib/assert/is-boolean":83,"@stdlib/assert/is-plain-object":151,"@stdlib/assert/is-string":162}],312:[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":313,"./regexp.js":314,"@stdlib/utils/define-nonenumerable-read-only-property":355}],313:[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; },{}],314:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":313}],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'; /** * 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":316,"./regexp.js":317,"@stdlib/utils/define-nonenumerable-read-only-property":355}],316:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // 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; },{}],317:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // 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":316}],318:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * Compute a moving minimum incrementally. * * @module @stdlib/stats/incr/mmin * * @example * var incrmmin = require( '@stdlib/stats/incr/mmin' ); * * var accumulator = incrmmin( 3 ); * * var m = accumulator(); * // returns null * * m = accumulator( 2.0 ); * // returns 2.0 * * m = accumulator( -5.0 ); * // returns -5.0 * * m = accumulator( 3.0 ); * // returns -5.0 * * m = accumulator( 5.0 ); * // returns -5.0 * * m = accumulator(); * // returns -5.0 */ // MODULES // var incrmmin = require( './main.js' ); // EXPORTS // module.exports = incrmmin; },{"./main.js":319}],319:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive; var isnan = require( '@stdlib/math/base/assert/is-nan' ); var isNegativeZero = require( '@stdlib/math/base/assert/is-negative-zero' ); var PINF = require( '@stdlib/constants/float64/pinf' ); var Float64Array = require( '@stdlib/array/float64' ); // MAIN // /** * Returns an accumulator function which incrementally computes a moving minimum value. * * @param {PositiveInteger} W - window size * @throws {TypeError} must provide a positive integer * @returns {Function} accumulator function * * @example * var accumulator = incrmmin( 3 ); * * var m = accumulator(); * // returns null * * m = accumulator( 2.0 ); * // returns 2.0 * * m = accumulator( -5.0 ); * // returns -5.0 * * m = accumulator( 3.0 ); * // returns -5.0 * * m = accumulator( 5.0 ); * // returns -5.0 * * m = accumulator(); * // returns -5.0 */ function incrmmin( W ) { var buf; var min; var N; var i; if ( !isPositiveInteger( W ) ) { throw new TypeError( 'invalid argument. Must provide a positive integer. Value: `' + W + '`.' ); } buf = new Float64Array( W ); min = PINF; i = -1; N = 0; return accumulator; /** * If provided a value, the accumulator function returns an updated minimum. If not provided a value, the accumulator function returns the current minimum. * * @private * @param {number} [x] - input value * @returns {(number|null)} minimum value or null */ function accumulator( x ) { var v; var k; if ( arguments.length === 0 ) { if ( N === 0 ) { return null; } return min; } // Update the index for managing the circular buffer: i = (i+1) % W; // Case: update initial window... if ( N < W ) { N += 1; if ( isnan( x ) || x < min || ( x === min && isNegativeZero( x ) ) ) { min = x; } } // Case: incoming value is NaN or less than current minimum value... else if ( isnan( x ) || x < min ) { min = x; } // Case: outgoing value is the current minimum and the new value is greater than the minimum, and, thus, we need to find a new minimum among the current values... else if ( ( buf[ i ] === min && x > min ) || isnan( buf[ i ] ) ) { min = x; for ( k = 0; k < W; k++ ) { if ( k !== i ) { v = buf[ k ]; if ( isnan( v ) ) { min = v; break; // no need to continue searching } if ( v < min || ( v === min && isNegativeZero( v ) ) ) { min = v; } } } } // Case: outgoing value is the current minimum, which is zero, and the new value is also zero, and, thus, we need to correctly handle signed zeros... else if ( buf[ i ] === min && x === min && x === 0.0 ) { if ( isNegativeZero( x ) ) { min = x; } else if ( isNegativeZero( buf[ i ] ) ) { // Because the outgoing and incoming are different signs (-,+), we need to search the buffer to see if it contains a negative zero. If so, the minimum value remains negative zero; otherwise, the minimum value is incoming value... min = x; for ( k = 0; k < W; k++ ) { if ( k !== i && isNegativeZero( buf[ k ] ) ) { min = buf[ k ]; break; } } } // Case: the outgoing and incoming values are both positive zero, so nothing changes } // Case: updating existing window; however, the minimum value does not change so nothing to do but update our buffer... buf[ i ] = x; return min; } } // EXPORTS // module.exports = incrmmin; },{"@stdlib/array/float64":5,"@stdlib/assert/is-positive-integer":153,"@stdlib/constants/float64/pinf":247,"@stdlib/math/base/assert/is-nan":261,"@stdlib/math/base/assert/is-negative-zero":263}],320:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2019 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 isnan = require( '@stdlib/math/base/assert/is-nan' ); var isIteratorLike = require( '@stdlib/assert/is-iterator-like' ); var randu = require( '@stdlib/random/iter/randu' ); var pkg = require( './../package.json' ).name; var itermmin = require( './../lib' ); // MAIN // bench( pkg, function benchmark( b ) { var rand; var iter; var i; rand = randu(); b.tic(); for ( i = 0; i < b.iterations; i++ ) { iter = itermmin( rand, 3 ); if ( typeof iter !== 'object' ) { b.fail( 'should return an object' ); } } b.toc(); if ( !isIteratorLike( iter ) ) { b.fail( 'should return an iterator protocol-compliant object' ); } b.pass( 'benchmark finished' ); b.end(); }); bench( pkg+'::iteration', function benchmark( b ) { var iter; var rand; var v; var i; rand = randu(); iter = itermmin( rand, 3 ); b.tic(); for ( i = 0; i < b.iterations; i++ ) { v = iter.next().value; if ( isnan( v ) ) { b.fail( 'should not return NaN' ); } } b.toc(); if ( isnan( v ) ) { b.fail( 'should not return NaN' ); } b.pass( 'benchmark finished' ); b.end(); }); },{"./../lib":321,"./../package.json":323,"@stdlib/assert/is-iterator-like":117,"@stdlib/bench":228,"@stdlib/math/base/assert/is-nan":261,"@stdlib/random/iter/randu":305}],321:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2019 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 an iterator which iteratively computes a moving minimum value. * * @module @stdlib/stats/iter/mmin * * @example * var runif = require( '@stdlib/random/iter/uniform' ); * var itermmin = require( '@stdlib/stats/iter/mmin' ); * * var rand = runif( -10.0, 10.0, { * 'iter': 100 * }); * * var it = itermmin( rand, 3 ); * * var v = it.next().value; * // returns <number> * * v = it.next().value; * // returns <number> * * v = it.next().value; * // returns <number> * * // ... */ // MODULES // var iterator = require( './main.js' ); // EXPORTS // module.exports = iterator; },{"./main.js":322}],322:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2019 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 isIteratorLike = require( '@stdlib/assert/is-iterator-like' ); var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive; var isFunction = require( '@stdlib/assert/is-function' ); var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var iteratorSymbol = require( '@stdlib/symbol/iterator' ); var incrmmin = require( '@stdlib/stats/incr/mmin' ); // MAIN // /** * Returns an iterator which iteratively computes a moving minimum value. * * @param {Iterator} iterator - input iterator * @param {PositiveInteger} W - window size * @throws {TypeError} first argument must be an iterator * @throws {TypeError} second argument must be a positive integer * @returns {Iterator} iterator * * @example * var runif = require( '@stdlib/random/iter/uniform' ); * * var rand = runif( -10.0, 10.0, { * 'iter': 100 * }); * * var it = itermmin( rand, 3 ); * * var v = it.next().value; * // returns <number> * * v = it.next().value; * // returns <number> * * v = it.next().value; * // returns <number> * * // ... */ function itermmin( iterator, W ) { var iter; var FLG; var acc; if ( !isIteratorLike( iterator ) ) { throw new TypeError( 'invalid argument. First argument must be an iterator. Value: `' + iterator + '`.' ); } if ( !isPositiveInteger( W ) ) { throw new TypeError( 'invalid argument. Second argument must be a positive integer. Value: `' + W + '`.' ); } acc = incrmmin( W ); // Create an iterator protocol-compliant object: iter = {}; setReadOnly( iter, 'next', next ); setReadOnly( iter, 'return', end ); // If an environment supports `Symbol.iterator`, make the iterator iterable: if ( iteratorSymbol && isFunction( iterator[ iteratorSymbol ] ) ) { setReadOnly( iter, iteratorSymbol, factory ); } return iter; /** * Returns an iterator protocol-compliant object containing the next iterated value. * * @private * @returns {Object} iterator protocol-compliant object */ function next() { var out; var v; if ( FLG ) { return { 'done': true }; } out = {}; v = iterator.next(); if ( typeof v.value === 'number' ) { out.value = acc( v.value ); } else if ( hasOwnProp( v, 'value' ) ) { out.value = acc( NaN ); } if ( v.done ) { FLG = true; out.done = true; } else { out.done = false; } return out; } /** * Finishes an iterator. * * @private * @param {*} [value] - value to return * @returns {Object} iterator protocol-compliant object */ function end( value ) { FLG = true; if ( arguments.length ) { return { 'value': value, 'done': true }; } return { 'done': true }; } /** * Returns a new iterator. * * @private * @returns {Iterator} iterator */ function factory() { return itermmin( iterator[ iteratorSymbol ](), W ); } } // EXPORTS // module.exports = itermmin; },{"@stdlib/assert/has-own-property":55,"@stdlib/assert/is-function":104,"@stdlib/assert/is-iterator-like":117,"@stdlib/assert/is-positive-integer":153,"@stdlib/stats/incr/mmin":318,"@stdlib/symbol/iterator":339,"@stdlib/utils/define-nonenumerable-read-only-property":355}],323:[function(require,module,exports){ module.exports={ "name": "@stdlib/stats/iter/mmin", "version": "0.0.0", "description": "Create an iterator which iteratively computes a moving minimum value.", "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", "mathematics", "math", "minimum", "min", "extreme", "extent", "range", "moving min", "moving minimum", "sliding window", "sliding", "window", "moving", "iterator", "iterable", "iterate" ] } },{}],324:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":439}],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 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":324,"./defaults.json":326,"./destroy.js":327,"./validate.js":332,"@stdlib/utils/copy":351,"@stdlib/utils/inherit":383,"debug":439,"readable-stream":456}],326:[function(require,module,exports){ module.exports={ "objectMode": false, "encoding": null, "allowHalfOpen": false, "decodeStrings": true } },{}],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'; // 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":409,"debug":439}],328:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // 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":330,"@stdlib/assert/is-plain-object":151,"@stdlib/utils/copy":351}],329:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * 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":325,"./factory.js":328,"./main.js":330,"./object_mode.js":331,"@stdlib/utils/define-nonenumerable-read-only-property":355}],330:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":324,"./defaults.json":326,"./destroy.js":327,"./validate.js":332,"@stdlib/utils/copy":351,"@stdlib/utils/inherit":383,"debug":439,"readable-stream":456}],331:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":330,"@stdlib/assert/is-plain-object":151,"@stdlib/utils/copy":351}],332:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // 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":55,"@stdlib/assert/is-boolean":83,"@stdlib/assert/is-function":104,"@stdlib/assert/is-nonnegative-number":135,"@stdlib/assert/is-plain-object":151,"@stdlib/assert/is-string":162}],333:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * 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":334}],334:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":92,"@stdlib/assert/is-nonnegative-integer":131,"@stdlib/constants/unicode/max":258,"@stdlib/constants/unicode/max-bmp":257}],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'; /** * 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":336}],336:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":104,"@stdlib/assert/is-regexp":158,"@stdlib/assert/is-string":162,"@stdlib/utils/escape-regexp-string":364}],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'; /** * 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":338}],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 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":162,"@stdlib/string/replace":335}],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'; /** * Iterator symbol. * * @module @stdlib/symbol/iterator * * @example * var IteratorSymbol = require( '@stdlib/symbol/iterator' ); * * function iterator() { * var it; * var i; * * i = -1; * * it = {}; * it.next = next; * it.return = done; * * if ( IteratorSymbol ) { * it[ IteratorSymbol ] = iterator; * } * return it; * * function next() { * i += 1; * return { * 'value': i, * 'done': false * }; * } * * function done( value ) { * if ( arguments.length === 0 ) { * return { * 'done': true * }; * } * return { * 'value': value, * 'done': true * }; * } * } * * var obj = iterator(); */ // MAIN // var IteratorSymbol = require( './main.js' ); // EXPORTS // module.exports = IteratorSymbol; },{"./main.js":340}],340:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var hasIteratorSymbolSupport = require( '@stdlib/assert/has-iterator-symbol-support' ); // MAIN // /** * Iterator symbol. * * @name IteratorSymbol * @constant * @type {(symbol|null)} * * @example * function iterator() { * var it; * var i; * * i = -1; * * it = {}; * it.next = next; * it.return = done; * * if ( IteratorSymbol ) { * it[ IteratorSymbol ] = iterator; * } * return it; * * function next() { * i += 1; * return { * 'value': i, * 'done': false * }; * } * * function done( value ) { * if ( arguments.length === 0 ) { * return { * 'done': true * }; * } * return { * 'value': value, * 'done': true * }; * } * } * * var obj = iterator(); */ var IteratorSymbol = ( hasIteratorSymbolSupport() ) ? Symbol.iterator : null; // EXPORTS // module.exports = IteratorSymbol; },{"@stdlib/assert/has-iterator-symbol-support":50}],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 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":343,"@stdlib/assert/is-object":149,"@stdlib/math/base/special/modf":271,"@stdlib/math/base/special/round":274,"@stdlib/utils/global":376}],342:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var isFunction = require( '@stdlib/assert/is-function' ); // MAIN // var bool = isFunction( Date.now ); // EXPORTS // module.exports = bool; },{"@stdlib/assert/is-function":104}],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 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":342,"./polyfill.js":344}],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'; // 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; },{}],345:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * 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":346}],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 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":130,"@stdlib/time/tic":341}],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'; /** * 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":348}],348:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":90,"@stdlib/regexp/function-name":312,"@stdlib/utils/native-class":404}],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 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":350,"@stdlib/assert/is-array":81,"@stdlib/assert/is-nonnegative-integer":131,"@stdlib/constants/float64/pinf":247}],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 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":352,"@stdlib/assert/has-own-property":55,"@stdlib/assert/is-array":81,"@stdlib/assert/is-buffer":90,"@stdlib/assert/is-error":98,"@stdlib/buffer/from-buffer":236,"@stdlib/utils/define-property":362,"@stdlib/utils/get-prototype-of":370,"@stdlib/utils/index-of":380,"@stdlib/utils/keys":397,"@stdlib/utils/property-descriptor":419,"@stdlib/utils/property-names":423,"@stdlib/utils/regexp-from-string":426,"@stdlib/utils/type-of":431}],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'; /** * 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":349}],352:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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}],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'; /** * 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":354}],354:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // 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":362}],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'; /** * 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":356}],356:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":362}],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'; /** * 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":358}],358:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":362}],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'; // 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; },{}],360:[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; },{}],361:[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":360}],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'; /** * 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":359,"./has_define_property_support.js":361,"./polyfill.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. */ /* 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; },{}],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'; /** * 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":365}],365:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // 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":162}],366:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":104,"@stdlib/regexp/function-name":312}],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'; /** * 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":366}],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 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":371,"./polyfill.js":372,"@stdlib/assert/is-function":104}],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 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":368}],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'; /** * 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":369}],371:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MAIN // var getProto = Object.getPrototypeOf; // EXPORTS // module.exports = getProto; },{}],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'; // 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":373,"@stdlib/utils/native-class":404}],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'; /** * 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; },{}],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'; // 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; },{}],375:[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 : {}) },{}],376:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * Return 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":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 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":374,"./global.js":375,"./self.js":378,"./window.js":379,"@stdlib/assert/is-boolean":83}],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 // var obj = ( typeof self === 'object' ) ? self : null; // EXPORTS // module.exports = obj; },{}],379:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MAIN // var obj = ( typeof window === 'object' ) ? window : null; // EXPORTS // module.exports = obj; },{}],380:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * 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":381}],381:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var 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":92,"@stdlib/assert/is-integer":112,"@stdlib/assert/is-nan":122,"@stdlib/assert/is-string":162}],382:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // 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":385,"./polyfill.js":386}],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'; /** * 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":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 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":382,"./validate.js":387,"@stdlib/utils/define-property":362}],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'; // EXPORTS // module.exports = Object.create; },{}],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'; // 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; },{}],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'; /** * 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; },{}],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'; // 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; },{}],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'; // 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":388,"@stdlib/assert/is-arguments":76}],390:[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" ] },{}],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 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":388}],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'; // 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":390,"./is_constructor_prototype.js":398,"./window.js":403,"@stdlib/assert/has-own-property":55,"@stdlib/utils/index-of":380,"@stdlib/utils/type-of":431}],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 // var bool = ( typeof Object.keys !== 'undefined' ); // EXPORTS // module.exports = bool; },{}],394:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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":95,"@stdlib/utils/noop":411}],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'; // 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":95}],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'; // MAIN // var bool = ( typeof window !== 'undefined' ); // EXPORTS // module.exports = bool; },{}],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'; /** * 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":400}],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 // /** * 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; },{}],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'; // 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":392,"./has_window.js":396,"./is_constructor_prototype.js":398}],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 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":388,"./builtin_wrapper.js":389,"./has_arguments_bug.js":391,"./has_builtin.js":393,"./polyfill.js":402}],401:[function(require,module,exports){ module.exports=[ "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "constructor" ] },{}],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'; // 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":394,"./has_non_enumerable_properties_bug.js":395,"./is_constructor_prototype_wrapper.js":399,"./non_enumerable.json":401,"@stdlib/assert/has-own-property":55,"@stdlib/assert/is-arguments":76,"@stdlib/assert/is-object-like":147}],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'; // MAIN // var w = ( typeof window === 'undefined' ) ? void 0 : window; // EXPORTS // module.exports = w; },{}],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'; /** * 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":405,"./polyfill.js":406,"@stdlib/assert/has-tostringtag-support":59}],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'; // 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":407}],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'; // 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":407,"./tostringtag.js":408,"@stdlib/assert/has-own-property":55}],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 // var toStr = Object.prototype.toString; // EXPORTS // module.exports = toStr; },{}],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'; // MAIN // var toStrTag = ( typeof Symbol === 'function' ) ? Symbol.toStringTag : ''; // EXPORTS // module.exports = toStrTag; },{}],409:[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":410}],410:[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":447}],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'; /** * 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":412}],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'; /** * No operation. * * @example * noop(); * // ...does nothing. */ function noop() { // Empty function... } // EXPORTS // module.exports = noop; },{}],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'; /** * 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":414}],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 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":162,"@stdlib/assert/is-string-array":161,"@stdlib/utils/index-of":380,"@stdlib/utils/keys":397}],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'; /** * 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":416}],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'; // 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":55,"@stdlib/assert/is-string":162,"@stdlib/assert/is-string-array":161}],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'; // 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; },{}],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'; // MAIN // var bool = ( typeof Object.getOwnPropertyDescriptor !== 'undefined' ); // EXPORTS // module.exports = bool; },{}],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'; /** * 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":417,"./has_builtin.js":418,"./polyfill.js":420}],420:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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":55}],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'; // 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; },{}],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 bool = ( typeof Object.getOwnPropertyNames !== 'undefined' ); // EXPORTS // module.exports = bool; },{}],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 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":421,"./has_builtin.js":422,"./polyfill.js":424}],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 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":397}],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 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":162,"@stdlib/regexp/regexp":315}],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'; /** * 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":425}],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'; // 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":428,"./fixtures/re.js":429,"./fixtures/typedarray.js":430}],428:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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":376}],429:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],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'; var typedarray = Int8Array; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = typedarray; },{}],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'; /** * 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":427,"./polyfill.js":432,"./typeof.js":433}],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'; // 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":347}],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 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":347}],434:[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('') } },{}],435:[function(require,module,exports){ },{}],436:[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); } } },{}],437:[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":434,"buffer":437,"ieee754":441}],438:[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":443}],439:[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":440,"_process":447}],440:[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":445}],441:[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 } },{}],442:[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 } } } },{}],443:[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)) } },{}],444:[function(require,module,exports){ var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; },{}],445:[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'; } },{}],446:[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":447}],447:[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; }; },{}],448:[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":450,"./_stream_writable":452,"core-util-is":438,"inherits":442,"process-nextick-args":446}],449:[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":451,"core-util-is":438,"inherits":442}],450:[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":448,"./internal/streams/BufferList":453,"./internal/streams/destroy":454,"./internal/streams/stream":455,"_process":447,"core-util-is":438,"events":436,"inherits":442,"isarray":444,"process-nextick-args":446,"safe-buffer":457,"string_decoder/":458,"util":435}],451:[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":448,"core-util-is":438,"inherits":442}],452:[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":448,"./internal/streams/destroy":454,"./internal/streams/stream":455,"_process":447,"core-util-is":438,"inherits":442,"process-nextick-args":446,"safe-buffer":457,"timers":459,"util-deprecate":460}],453:[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":457,"util":435}],454:[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":446}],455:[function(require,module,exports){ module.exports = require('events').EventEmitter; },{"events":436}],456:[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":448,"./lib/_stream_passthrough.js":449,"./lib/_stream_readable.js":450,"./lib/_stream_transform.js":451,"./lib/_stream_writable.js":452}],457:[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":437}],458:[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":457}],459:[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":447,"timers":459}],460:[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 : {}) },{}]},{},[320]);
apache-2.0
vam-google/google-cloud-java
google-api-grpc/proto-google-cloud-automl-v1beta1/src/main/java/com/google/cloud/automl/v1beta1/DeleteDatasetRequestOrBuilder.java
708
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/automl/v1beta1/service.proto package com.google.cloud.automl.v1beta1; public interface DeleteDatasetRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.automl.v1beta1.DeleteDatasetRequest) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * The resource name of the dataset to delete. * </pre> * * <code>string name = 1;</code> */ java.lang.String getName(); /** * * * <pre> * The resource name of the dataset to delete. * </pre> * * <code>string name = 1;</code> */ com.google.protobuf.ByteString getNameBytes(); }
apache-2.0
telerik/mobile-cli-lib
test/unit-tests/stubs.ts
4845
/* tslint:disable:no-empty */ import * as util from "util"; export class CommonLoggerStub implements ILogger { setLevel(level: string): void { } getLevel(): string { return undefined; } fatal(...args: string[]): void { } error(...args: string[]): void { } warn(...args: string[]): void { this.out.apply(this, args); } warnWithLabel(...args: string[]): void { } info(...args: string[]): void { this.out.apply(this, args); } debug(...args: string[]): void { } trace(...args: string[]): void { this.traceOutput += util.format.apply(null, args) + "\n"; } public output = ""; public traceOutput = ""; out(...args: string[]): void { this.output += util.format.apply(null, args) + "\n"; } write(...args: string[]): void { } prepare(item: any): string { return ""; } printInfoMessageOnSameLine(message: string): void { } async printMsgWithTimeout(message: string, timeout: number): Promise<void> { return null; } printMarkdown(message: string): void { this.output += message; } } export class ErrorsStub implements IErrors { printCallStack: boolean = false; fail(formatStr: string, ...args: any[]): never; fail(opts: { formatStr?: string; errorCode?: number; suppressCommandHelp?: boolean }, ...args: any[]): never; fail(...args: any[]): never { if (_.isObject(args) && (<any>args).formatStr) { throw new Error((<any>args).formatStr); } throw new Error(util.format.apply(null, args)); } failWithoutHelp(message: string, ...args: any[]): never { throw new Error(message); } async beginCommand(action: () => Promise<boolean>, printHelpCommand: () => Promise<void>): Promise<boolean> { return action(); } executeAction(action: Function): any { return action(); } verifyHeap(message: string): void { } } export class HooksServiceStub implements IHooksService { async executeBeforeHooks(commandName: string): Promise<void> { return; } async executeAfterHooks(commandName: string): Promise<void> { return; } hookArgsName = "hookArgs"; } export class SettingsService implements ISettingsService { public setSettings(settings: IConfigurationSettings) { // Intentionally left blank } public getProfileDir() { return "profileDir"; } } export class AndroidProcessServiceStub implements Mobile.IAndroidProcessService { public MapAbstractToTcpPortResult = "stub"; public GetDebuggableAppsResult: Mobile.IDeviceApplicationInformation[] = []; public GetMappedAbstractToTcpPortsResult: IDictionary<number> = {}; public GetAppProcessIdResult = "stub"; public GetAppProcessIdFailAttempts = 0; public ForwardFreeTcpToAbstractPortResult = 0; async mapAbstractToTcpPort(deviceIdentifier: string, appIdentifier: string, framework: string): Promise<string> { return this.MapAbstractToTcpPortResult; } async getDebuggableApps(deviceIdentifier: string): Promise<Mobile.IDeviceApplicationInformation[]> { return this.GetDebuggableAppsResult; } async getMappedAbstractToTcpPorts(deviceIdentifier: string, appIdentifiers: string[], framework: string): Promise<IDictionary<number>> { return this.GetMappedAbstractToTcpPortsResult; } async getAppProcessId(deviceIdentifier: string, appIdentifier: string): Promise<string> { while (this.GetAppProcessIdFailAttempts) { this.GetAppProcessIdFailAttempts--; return null; } return this.GetAppProcessIdResult; } async forwardFreeTcpToAbstractPort(portForwardInputData: Mobile.IPortForwardData): Promise<number> { return this.ForwardFreeTcpToAbstractPortResult; } } export class LogcatHelperStub implements Mobile.ILogcatHelper { public StopCallCount = 0; public StartCallCount = 0; public DumpCallCount = 0; public LastStartCallOptions: Mobile.ILogcatStartOptions = { deviceIdentifier: "" }; public LastStopDeviceId = ""; async start(options: Mobile.ILogcatStartOptions): Promise<void> { this.LastStartCallOptions = options; this.StartCallCount++; } stop(deviceIdentifier: string): void { this.LastStopDeviceId = deviceIdentifier; this.StopCallCount++; } dump(): Promise<void> { this.DumpCallCount++; return Promise.resolve(); } } export class DeviceLogProviderStub implements Mobile.IDeviceLogProvider { public logger = new CommonLoggerStub(); public currentDevicePids: IStringDictionary = {}; public currentDeviceProjectNames: IStringDictionary = {}; logData(line: string, platform: string, deviceIdentifier: string): void { this.logger.write(line, platform, deviceIdentifier); } setLogLevel(level: string, deviceIdentifier?: string): void { this.logger.setLevel(level); } setApplicationPidForDevice(deviceIdentifier: string, pid: string): void { this.currentDevicePids[deviceIdentifier] = pid; } setProjectNameForDevice(deviceIdentifier: string, projectName: string): void { this.currentDeviceProjectNames[deviceIdentifier] = projectName; } }
apache-2.0
nicolashernandez/dev-star
uima-star/uima-connectors/src/main/java/fr/univnantes/lina/uima/connectors/csv/CSVWriterAE.java
12942
package fr.univnantes.lina.uima.connectors.csv; /** * UIMA Connectors * Copyright (C) 2010 Nicolas Hernandez * 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. */ import java.io.File; import org.apache.uima.examples.*; import java.lang.reflect.Field; import java.net.MalformedURLException; import java.net.URL; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Set; import org.apache.uima.UimaContext; import org.apache.uima.analysis_component.AnalysisComponent; import org.apache.uima.analysis_component.JCasAnnotator_ImplBase; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.analysis_engine.ResultSpecification; import org.apache.uima.cas.FSIterator; import org.apache.uima.cas.Type; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.tcas.Annotation; import org.apache.uima.resource.ResourceInitializationException; import fr.univnantes.lina.javautil.IOUtilities; import fr.univnantes.lina.uima.common.ae.CommonAE; import fr.univnantes.lina.uima.common.cas.AnnotationUtils; import fr.univnantes.lina.uima.common.cas.FeatureUtils; import fr.univnantes.lina.uima.common.cas.JCasUtils; import fr.univnantes.lina.uima.common.cas.UIMAUtils; /** * Serialize selected features of annotations of a given type * to a csv file. * * Use the sourceDocumentInformation annotation to get the name of * the source document in order to create an ouput name file with the same name * (use a default name otherwise) * * <p> * </p> * * * * @author Nicolas Hernandez */ public class CSVWriterAE extends CommonAE { /* * LOCAL PARAMETER NAMES */ /** * Parameter name for the path of the output directory to write the * csv files. */ public static final String PARAM_OUTPUT_DIR_FOR_CSV = "OuputDir"; /** * Parameter name for the Name of the annotation type whose instances will be turned into lines */ public static final String PARAM_ANNOTATION_TO_LINE = "AnnotationToLine"; /** * Parameter name for Ordered list of feature names of the AnnotationToLine * instances whose values should be turned into columns values. */ public static final String PARAM_FEATURES_TO_COLUMNS = "FeaturesToColumns"; /** * Parameter name of the CSV separator * by default a tabulation, '\t', but can be set to comma ',' ... */ public static final String CSV_SEPARATOR_PARAM = "CSVSeparator"; /** * Parameter name of the default value to set when a specified feature has a null value * If not set, then the value will be 'null' */ public static final String DEFAULT_NULL_VALUE_PARAM = "DefaultNullValue"; /** * View name to consider as the view to process */ //private static String PARAM_NAME_INPUT_VIEW = "InputView"; /* * CONFIGURATION PARAMETER NAMES VALUES */ /** * Path of the output directory to write the * csv files from the context Data Path. */ public File outputDirForCSV; /** * Name of the path of the output directory to write the * csv files from the context Data Path. */ public String outputDirForCSVString; /** * Name of the annotation type whose instances will be turned into lines */ public String annotationToLineString = null; /** * List of feature names of the AnnotationToLine * instances whose values should be turned into columns values. * Type of the feature should be specified first, then the feature name * with the ':' as separator. Currently the types int or Integer, String and * Float are supported. * e.g. int:begin, String:coveredText */ public String[] featuresToColumnsStringArray = null; /** * View to process */ //public String inputViewString = null; /* * LOCAL VARIABLES */ /* * Default view name if none are specified by the view parameter */ //private static String DEFAULT_INPUT_VIEW = "_InitialView"; /** * Name of the default SourceDocumentInformation */ private static String DEFAULT_SOURCE_DOCUMENT_INFORMATION_ANNOTATION = "org.apache.uima.examples.SourceDocumentInformation"; /** * Name of the default document in case of absence of source document information annotation in the CAS */ private static String DEFAULT_DOCUMENT_PREFIX = "cas2csv."; /** * Name of the default csv extension */ private static String DEFAULT_CSV_EXTENSION = ".csv"; /** * Name of the default separator between type and feature name */ private static String DEFAULT_TYPE_AND_FEATURENAME_SEPARATOR = ":"; /** * Name of the default csv separator */ private static String DEFAULT_CSV_SEPARATOR = "\t"; // \t private String csvSeparatorString = ""; private String defaultNullValueString = ""; /** * Get the values of the configuration parameters * * @see AnalysisComponent#initialize(UimaContext) */ public void initialize(UimaContext aContext) throws ResourceInitializationException { // generic AE parameters super.initialize(aContext); // current AE parameter //System.out.println("Debug: aContext.getDataPath() "+aContext.getDataPath()); //System.out.println("Debug: aContext.getDataPath()"+aContext.getResourceFilePath(arg0); // Get the input view // If no input view is specified, we use the default (i.e. _InitialView) // taken in charge by uima-common //inputViewString = (String) aContext.getConfigParameterValue(PARAM_NAME_INPUT_VIEW); //if (inputViewString == null) { // inputViewString = DEFAULT_INPUT_VIEW; //} // Get the output dir name outputDirForCSVString = (String) aContext.getConfigParameterValue(PARAM_OUTPUT_DIR_FOR_CSV); outputDirForCSV = new File(outputDirForCSVString); if (!outputDirForCSV.exists()) { outputDirForCSV.mkdirs(); } // Get the annotation name annotationToLineString = (String) aContext.getConfigParameterValue(PARAM_ANNOTATION_TO_LINE); // Get the features name featuresToColumnsStringArray = (String[]) aContext.getConfigParameterValue(PARAM_FEATURES_TO_COLUMNS); // for (int i = 0; i < featuresToColumnsStringArray.length ; i++) { // System.out.println("Debug: fc"+ featuresToColumnsStringArray[i] + " i"+ i); // } // Get the input csv separator csvSeparatorString = (String) aContext.getConfigParameterValue(CSV_SEPARATOR_PARAM); //System.out.println("Debug: before null test csvSeparatorString>"+csvSeparatorString+"<"); if (csvSeparatorString == null) { csvSeparatorString = DEFAULT_CSV_SEPARATOR; } //else csvSeparatorString = DEFAULT_CSV_SEPARATOR.replaceAll(DEFAULT_CSV_SEPARATOR, csvSeparatorString); // else csvSeparatorString = DEFAULT_CSV_SEPARATOR.replaceAll(DEFAULT_CSV_SEPARATOR, "\t"); else csvSeparatorString = csvSeparatorString.substring(1, csvSeparatorString.length()-1); //csvSeparatorString = csvSeparatorString ; //System.out.println("Debug: after null test csvSeparatorString>"+csvSeparatorString+"<"); //"\\s" // whitespace character //"\t" // tabulation character // Get the default null value to set in case of null value with the feature defaultNullValueString = (String) aContext.getConfigParameterValue(DEFAULT_NULL_VALUE_PARAM); } /** * process each CAS and export to a CSV file a specific annotation type as * lines and selected features as column * */ // @Override protected String processInputView(JCas inputViewJCas, FSIterator<Annotation> contextAnnotationsFSIter, Set<String> inputAnnotationSet, String inputFeatureString, JCas outputViewJCas, String outputAnnotationString, String ouputFeatureString) throws AnalysisEngineProcessException { //public void process(JCas aJCas) throws AnalysisEngineProcessException { // Get the view to process //JCas inputViewJCas = JCasSofaViewUtils.getView(aJCas,inputViewString); // Retrieve the filename of the input file from the CAS // and set the output name of the csv file FSIterator<Annotation> sourceDocumentInformationFSIterator = inputViewJCas.getAnnotationIndex(JCasUtils.getJCasType(inputViewJCas, DEFAULT_SOURCE_DOCUMENT_INFORMATION_ANNOTATION)).iterator(); String outFileName = ""; File inFile = null; if (sourceDocumentInformationFSIterator.hasNext()) { SourceDocumentInformation theSourceDocumentInformation = (SourceDocumentInformation) sourceDocumentInformationFSIterator.next(); try { inFile = new File(new URL(theSourceDocumentInformation.getUri()).getPath()); outFileName = inFile.getName(); if (theSourceDocumentInformation.getOffsetInSource() > 0) { outFileName += ("_" + theSourceDocumentInformation.getOffsetInSource()); } //outFile = new File(outputDirForCSV, outFileName); //System.out.println("Debug: outputDirForCSV "+ outputDirForCSVString+ " outFileName "+outFileName); } catch (MalformedURLException e) { // invalid URL, use default processing below e.printStackTrace(); } } // If SourceDocumentInformation is not present in the CAS then create a if (inFile == null) { byte[] hash = null; try { hash= MessageDigest.getInstance("MD5").digest(inputViewJCas.getSofaDataString().getBytes()); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } outFileName = DEFAULT_DOCUMENT_PREFIX + hash; //inFile = new File(outputDirForCSV, DEFAULT_DOCUMENT_PREFIX + hash ); //System.out.println("Debug: outputDirForCSV "+ outputDirForCSVString+ " outFileName "+DEFAULT_DOCUMENT_PREFIX + hash + DEFAULT_CSV_EXTENSION); } outFileName += DEFAULT_CSV_EXTENSION; FSIterator<Annotation> annotationToLineFSIterator = inputViewJCas.getAnnotationIndex(JCasUtils.getJCasType(inputViewJCas, annotationToLineString)).iterator(); //DataOutputStream dos = null; String[] lines = new String[inputViewJCas.getAnnotationIndex(JCasUtils.getJCasType(inputViewJCas, annotationToLineString)).size()]; int l = 0; while (annotationToLineFSIterator.hasNext()) { // Annotation annotationToLine = null; // Récupère et cast l'annotationToLine courante à manipuler Object annotationObject = annotationToLineFSIterator.next(); Class annotationClass = annotationObject.getClass(); String className = "null"; className = annotationClass.getName(); //System.out.println("Debug: class>"+className+"<"); Class<Annotation> inputAnnotationClass = AnnotationUtils.getAnnotationClass(className); Annotation annotationToLine = (Annotation) annotationObject; inputAnnotationClass.cast(annotationToLine); //Class<Annotation> inputAnnotationClass = UIMAUtilities.retrieveAndCastAnAnnotation(annotationToLineFSIterator, annotationToLine); String columns = ""; for (String featureToColumn : featuresToColumnsStringArray) { String featureToColumnValueString = ""; // In case of null as feature name then do not consider this column //if (!featureToColumn.equalsIgnoreCase("null")) { Object featureToColumnValueObject = null; featureToColumnValueObject = FeatureUtils.invokeFeatureGetterMethod(annotationToLine, FeatureUtils.getFeatureGetterMethod(inputAnnotationClass,featureToColumn)); if (featureToColumnValueObject != null) featureToColumnValueString = featureToColumnValueObject.toString(); else if (!defaultNullValueString.equalsIgnoreCase("")) featureToColumnValueString = defaultNullValueString; else featureToColumnValueString = "null"; // Dans certains cas la valeur peut être null mais pas pour toutes donc on laisse null if (columns.equalsIgnoreCase("")) { //System.out.println("Debug: featureToColumnValueString >"+featureToColumnValueString +"<"); columns = ""+ featureToColumnValueString;} else {columns += csvSeparatorString +featureToColumnValueString;} //} } lines[l] = ""; lines[l] += (""+columns + "\n"); l++; } // Set the whole path including the path to the directory outFileName = outputDirForCSVString+"/"+outFileName; // Serialize IOUtilities.writeStringArrayToFileName( outFileName, lines); // Here your code // La méthode requiert de retourner quelque chose // Le plus simple est de lui retourner l'image d'elle même return inputViewJCas.getSofaDataString(); } }
apache-2.0
iemejia/incubator-beam
sdks/java/extensions/sql/src/main/java/org/apache/beam/sdk/extensions/sql/impl/rel/AbstractBeamCalcRel.java
3715
/* * 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.beam.sdk.extensions.sql.impl.rel; import org.apache.beam.sdk.annotations.Internal; import org.apache.beam.sdk.extensions.sql.impl.planner.BeamCostModel; import org.apache.beam.sdk.extensions.sql.impl.planner.NodeStats; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.plan.RelOptCluster; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.plan.RelOptPlanner; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.plan.RelTraitSet; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.rel.RelNode; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.rel.core.Calc; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.rel.metadata.RelMetadataQuery; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.rex.RexLocalRef; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.rex.RexNode; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.rex.RexProgram; /** BeamRelNode to replace {@code Project} and {@code Filter} node. */ @Internal public abstract class AbstractBeamCalcRel extends Calc implements BeamRelNode { public AbstractBeamCalcRel( RelOptCluster cluster, RelTraitSet traits, RelNode input, RexProgram program) { super(cluster, traits, input, program); } public boolean isInputSortRelAndLimitOnly() { return (input instanceof BeamSortRel) && ((BeamSortRel) input).isLimitOnly(); } public int getLimitCountOfSortRel() { if (input instanceof BeamSortRel) { return ((BeamSortRel) input).getCount(); } throw new RuntimeException("Could not get the limit count from a non BeamSortRel input."); } @Override public NodeStats estimateNodeStats(RelMetadataQuery mq) { NodeStats inputStat = BeamSqlRelUtils.getNodeStats(input, mq); double selectivity = estimateFilterSelectivity(getInput(), program, mq); return inputStat.multiply(selectivity); } private static double estimateFilterSelectivity( RelNode child, RexProgram program, RelMetadataQuery mq) { // Similar to calcite, if the calc node is representing filter operation we estimate the filter // selectivity based on the number of equality conditions, number of inequality conditions, .... RexLocalRef programCondition = program.getCondition(); RexNode condition; if (programCondition == null) { condition = null; } else { condition = program.expandLocalRef(programCondition); } // Currently this gets the selectivity based on Calcite's Selectivity Handler (RelMdSelectivity) return mq.getSelectivity(child, condition); } @Override public BeamCostModel beamComputeSelfCost(RelOptPlanner planner, RelMetadataQuery mq) { NodeStats inputStat = BeamSqlRelUtils.getNodeStats(this.input, mq); return BeamCostModel.FACTORY.makeCost(inputStat.getRowCount(), inputStat.getRate()); } }
apache-2.0
hanom94/java_for_tester
soap-sample/src/main/java/net/webservicex/GeoIPService.java
5442
package net.webservicex; import java.net.MalformedURLException; import java.net.URL; import javax.xml.namespace.QName; import javax.xml.ws.WebEndpoint; import javax.xml.ws.WebServiceClient; import javax.xml.ws.WebServiceFeature; import javax.xml.ws.Service; /** * This class was generated by Apache CXF 3.1.10 * 2017-03-14T11:19:41.740+02:00 * Generated source version: 3.1.10 * */ @WebServiceClient(name = "GeoIPService", wsdlLocation = "file:src/main/resources/geoipservice.wsdl", targetNamespace = "http://www.webservicex.net/") public class GeoIPService extends Service { public final static URL WSDL_LOCATION; public final static QName SERVICE = new QName("http://www.webservicex.net/", "GeoIPService"); public final static QName GeoIPServiceSoap = new QName("http://www.webservicex.net/", "GeoIPServiceSoap"); public final static QName GeoIPServiceSoap12 = new QName("http://www.webservicex.net/", "GeoIPServiceSoap12"); public final static QName GeoIPServiceHttpGet = new QName("http://www.webservicex.net/", "GeoIPServiceHttpGet"); public final static QName GeoIPServiceHttpPost = new QName("http://www.webservicex.net/", "GeoIPServiceHttpPost"); static { URL url = null; try { url = new URL("file:src/main/resources/geoipservice.wsdl"); } catch (MalformedURLException e) { java.util.logging.Logger.getLogger(GeoIPService.class.getName()) .log(java.util.logging.Level.INFO, "Can not initialize the default wsdl from {0}", "file:src/main/resources/geoipservice.wsdl"); } WSDL_LOCATION = url; } public GeoIPService(URL wsdlLocation) { super(wsdlLocation, SERVICE); } public GeoIPService(URL wsdlLocation, QName serviceName) { super(wsdlLocation, serviceName); } public GeoIPService() { super(WSDL_LOCATION, SERVICE); } public GeoIPService(WebServiceFeature ... features) { super(WSDL_LOCATION, SERVICE, features); } public GeoIPService(URL wsdlLocation, WebServiceFeature ... features) { super(wsdlLocation, SERVICE, features); } public GeoIPService(URL wsdlLocation, QName serviceName, WebServiceFeature ... features) { super(wsdlLocation, serviceName, features); } /** * * @return * returns GeoIPServiceSoap */ @WebEndpoint(name = "GeoIPServiceSoap") public GeoIPServiceSoap getGeoIPServiceSoap() { return super.getPort(GeoIPServiceSoap, GeoIPServiceSoap.class); } /** * * @param features * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values. * @return * returns GeoIPServiceSoap */ @WebEndpoint(name = "GeoIPServiceSoap") public GeoIPServiceSoap getGeoIPServiceSoap(WebServiceFeature... features) { return super.getPort(GeoIPServiceSoap, GeoIPServiceSoap.class, features); } /** * * @return * returns GeoIPServiceSoap */ @WebEndpoint(name = "GeoIPServiceSoap12") public GeoIPServiceSoap getGeoIPServiceSoap12() { return super.getPort(GeoIPServiceSoap12, GeoIPServiceSoap.class); } /** * * @param features * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values. * @return * returns GeoIPServiceSoap */ @WebEndpoint(name = "GeoIPServiceSoap12") public GeoIPServiceSoap getGeoIPServiceSoap12(WebServiceFeature... features) { return super.getPort(GeoIPServiceSoap12, GeoIPServiceSoap.class, features); } /** * * @return * returns GeoIPServiceHttpGet */ @WebEndpoint(name = "GeoIPServiceHttpGet") public GeoIPServiceHttpGet getGeoIPServiceHttpGet() { return super.getPort(GeoIPServiceHttpGet, GeoIPServiceHttpGet.class); } /** * * @param features * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values. * @return * returns GeoIPServiceHttpGet */ @WebEndpoint(name = "GeoIPServiceHttpGet") public GeoIPServiceHttpGet getGeoIPServiceHttpGet(WebServiceFeature... features) { return super.getPort(GeoIPServiceHttpGet, GeoIPServiceHttpGet.class, features); } /** * * @return * returns GeoIPServiceHttpPost */ @WebEndpoint(name = "GeoIPServiceHttpPost") public GeoIPServiceHttpPost getGeoIPServiceHttpPost() { return super.getPort(GeoIPServiceHttpPost, GeoIPServiceHttpPost.class); } /** * * @param features * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values. * @return * returns GeoIPServiceHttpPost */ @WebEndpoint(name = "GeoIPServiceHttpPost") public GeoIPServiceHttpPost getGeoIPServiceHttpPost(WebServiceFeature... features) { return super.getPort(GeoIPServiceHttpPost, GeoIPServiceHttpPost.class, features); } }
apache-2.0
maheshika/carbon4-kernel
core/org.wso2.carbon.core/src/main/java/org/wso2/carbon/core/clustering/hazelcast/HazelcastInstanceManager.java
1599
/* * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.carbon.core.clustering.hazelcast; import com.hazelcast.config.Config; import com.hazelcast.core.Hazelcast; import com.hazelcast.core.HazelcastInstance; /** * TODO: class description */ public class HazelcastInstanceManager { private static HazelcastInstanceManager instance = new HazelcastInstanceManager(); private HazelcastInstance hazelcastInstance; public static HazelcastInstanceManager getInstance() { return instance; } public HazelcastInstance init(Config config) { if (hazelcastInstance != null) { throw new IllegalStateException("HazelcastInstanceManager has already been initialized"); } hazelcastInstance = Hazelcast.newHazelcastInstance(config); return hazelcastInstance; } public HazelcastInstance getHazelcastInstance() { return hazelcastInstance; } private HazelcastInstanceManager() { } }
apache-2.0
NSaitoNmiri/netmf_msbuild_parse
src/netmf_msbuild_parse/Properties/AssemblyInfo.cs
1634
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("ConsoleApplication1")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ConsoleApplication1")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // 次の GUID は、このプロジェクトが COM に公開される場合の、typelib の ID です [assembly: Guid("6f6ab3ae-a328-4136-bc06-c49601de60a1")] // アセンブリのバージョン情報は、以下の 4 つの値で構成されています: // // Major Version // Minor Version // Build Number // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
apache-2.0
mguidi/SOA-Code-Factory
com.mguidi.soa/xtend-gen/com/mguidi/soa/generator/swift/ModelGenerator.java
5728
package com.mguidi.soa.generator.swift; import com.google.inject.Inject; import com.mguidi.soa.generator.swift.Utils; import com.mguidi.soa.soa.Comment; import com.mguidi.soa.soa.Entity; import com.mguidi.soa.soa.Feature; import com.mguidi.soa.soa.FeatureType; import org.eclipse.emf.common.util.EList; import org.eclipse.xtend2.lib.StringConcatenation; import org.eclipse.xtext.xbase.lib.Extension; @SuppressWarnings("all") public class ModelGenerator { @Inject @Extension private Utils utils; public CharSequence generateEnum(final com.mguidi.soa.soa.Enum entity) { StringConcatenation _builder = new StringConcatenation(); _builder.append("import Foundation"); _builder.newLine(); _builder.newLine(); _builder.append("/**"); _builder.newLine(); _builder.append("*"); _builder.newLine(); _builder.append("* "); String _className = this.utils.className(entity); _builder.append(_className, ""); _builder.newLineIfNotEmpty(); _builder.append("*"); _builder.newLine(); _builder.append("*/"); _builder.newLine(); _builder.append("public enum "); String _className_1 = this.utils.className(entity); _builder.append(_className_1, ""); _builder.append(" : String "); _builder.newLineIfNotEmpty(); _builder.append("{"); _builder.newLine(); _builder.append("\t"); _builder.append("case"); _builder.newLine(); { EList<String> _features = entity.getFeatures(); for(final String feature : _features) { _builder.append("\t"); _builder.append(feature, "\t"); _builder.append(" = \""); _builder.append(feature, "\t"); _builder.append("\","); _builder.newLineIfNotEmpty(); } } _builder.append("\t"); _builder.append("_UNDEFINED_ = \"_UNDEFINED_\""); _builder.newLine(); _builder.append("}"); _builder.newLine(); return _builder; } public CharSequence generateEntity(final Entity entity) { StringConcatenation _builder = new StringConcatenation(); _builder.append("import Foundation"); _builder.newLine(); _builder.newLine(); _builder.append("/**"); _builder.newLine(); _builder.append("*"); _builder.newLine(); _builder.append("* "); String _className = this.utils.className(entity); _builder.append(_className, ""); _builder.newLineIfNotEmpty(); _builder.append("*"); _builder.newLine(); _builder.append("*/"); _builder.newLine(); _builder.append("public class "); String _className_1 = this.utils.className(entity); _builder.append(_className_1, ""); _builder.append(" "); _builder.newLineIfNotEmpty(); _builder.append("{"); _builder.newLine(); _builder.append("\t"); _builder.newLine(); { EList<Feature> _features = entity.getFeatures(); for(final Feature feature : _features) { _builder.append("\t"); _builder.append("class var "); String _key = this.utils.key(feature); _builder.append(_key, "\t"); _builder.append(" : String { return \""); String _name = feature.getName(); _builder.append(_name, "\t"); _builder.append("\" }"); _builder.newLineIfNotEmpty(); } } _builder.append("\t"); _builder.newLine(); { EList<Feature> _features_1 = entity.getFeatures(); for(final Feature feature_1 : _features_1) { { EList<Comment> _featureComment = feature_1.getFeatureComment(); int _size = _featureComment.size(); boolean _equals = (_size == 1); if (_equals) { _builder.append("\t"); _builder.newLine(); _builder.append("\t"); _builder.append("// "); EList<Comment> _featureComment_1 = feature_1.getFeatureComment(); Comment _get = _featureComment_1.get(0); String _clean = this.utils.clean(_get); _builder.append(_clean, "\t"); _builder.newLineIfNotEmpty(); } else { EList<Comment> _featureComment_2 = feature_1.getFeatureComment(); int _size_1 = _featureComment_2.size(); boolean _greaterThan = (_size_1 > 1); if (_greaterThan) { _builder.append("\t"); _builder.newLine(); _builder.append("\t"); _builder.append("/*"); _builder.newLine(); { EList<Comment> _featureComment_3 = feature_1.getFeatureComment(); for(final Comment comment : _featureComment_3) { _builder.append("\t"); _builder.append("* "); String _clean_1 = this.utils.clean(comment); _builder.append(_clean_1, "\t"); _builder.newLineIfNotEmpty(); } } _builder.append("\t"); _builder.append("*/"); _builder.newLine(); } } } _builder.append("\t"); _builder.append("public var "); String _name_1 = feature_1.getName(); _builder.append(_name_1, "\t"); _builder.append(" : "); FeatureType _type = feature_1.getType(); String _declaration = this.utils.declaration(_type); _builder.append(_declaration, "\t"); _builder.append("?"); _builder.newLineIfNotEmpty(); } } _builder.append("\t"); _builder.newLine(); _builder.append("\t"); _builder.append("init() {}"); _builder.newLine(); _builder.append("\t"); _builder.newLine(); _builder.append("}"); _builder.newLine(); return _builder; } }
apache-2.0
Amplifino/nestor
com.amplifino.nestor.transaction.provider/src/com/amplifino/nestor/transaction/provider/recovery/RecoveryServiceImpl.java
1746
package com.amplifino.nestor.transaction.provider.recovery; import java.util.logging.Logger; import javax.transaction.xa.XAException; import javax.transaction.xa.XAResource; import javax.transaction.xa.Xid; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import com.amplifino.nestor.transaction.provider.spi.GlobalTransaction; import com.amplifino.nestor.transaction.provider.spi.RecoveryService; import com.amplifino.nestor.transaction.provider.spi.TransactionLog; import com.amplifino.nestor.transaction.provider.spi.TransactionLog.GlobalTransactionState; @Component public class RecoveryServiceImpl implements RecoveryService { private Logger logger = Logger.getLogger("com.amplifino.nestor.transaction.provider"); @Reference private TransactionLog log; @Override public void recover(XAResource xaResource) { try { doRecover(xaResource); } catch (XAException e) { throw new RuntimeException(e); } } private void doRecover(XAResource xaResource) throws XAException { Xid[] xids = xaResource.recover(XAResource.TMSTARTRSCAN | XAResource.TMENDRSCAN); for (Xid xid : xids) { if (xid.getFormatId() == log.getFormatId()) { // We created the XID TransactionLog.GlobalTransactionState state = log.state(GlobalTransaction.of(xid)); if (state == GlobalTransactionState.INDOUBT_COMMIT) { xaResource.commit(xid, false); log.forget(xid); } else if (state == GlobalTransactionState.INDOUBT_ROLLBACK) { xaResource.rollback(xid); log.forget(xid); } else { logger.info("No action in recovery of Xid " + xid + ", state: " + state); } } } } }
apache-2.0
PatrickHuang888/Earlgrey
jobs/src/main/scala/com/hxm/earlgrey/jobs/Repository.scala
3345
package com.hxm.earlgrey.jobs import java.text.SimpleDateFormat import java.util.Date import java.util.concurrent.TimeUnit import com.typesafe.config.{Config, ConfigFactory} import org.mongodb.scala.{Completed, Document, MongoClient} import org.mongodb.scala.model.Filters._ import scala.concurrent.Await import scala.concurrent.duration.Duration /** * Created by hxm on 17-4-18. */ class Repository(mongoUri: String) { val mongoClient = MongoClient(mongoUri) val db = mongoClient.getDatabase("EarlGrey") val jobs = db.getCollection("Jobs") val dateFormet = new SimpleDateFormat(Job.TimeFormat) def insertJob(job: Job): Unit = { Await.result(jobs.insertOne(job.doc).toFuture(), Duration(10, TimeUnit.SECONDS)) } def findJob(jobId: String): Option[Job] = { val jobDocOption = Option(Await.result(jobs.find(equal("_id", jobId)).first().toFuture(), Duration(10, TimeUnit.SECONDS))) jobDocOption.map(jobDoc => Job(jobDoc)) } def deleteJob(jobId: String): Unit = { //Refactor: return value Await.result(jobs.deleteOne(equal("_id", jobId)).toFuture(), Duration(10, TimeUnit.SECONDS)) } def startJob(jobId: String): Unit = { Await.result(jobs.updateOne(equal("_id", jobId), Document("$set" -> Document(Job.StatusString -> Job.Status.Started , Job.StartedTimeString -> dateFormet.format(new Date())))).toFuture(), Duration(10, TimeUnit.SECONDS)) } def endJob(jobId: String): Unit = { Await.result(jobs.updateOne(equal("_id", jobId), Document("$set" -> Document(Job.StatusString -> Job.Status.End , Job.EndedTimeString -> dateFormet.format(new Date())))).toFuture(), Duration(10, TimeUnit.SECONDS)) } def jobError(jobId: String, message: String): Unit = { Await.result(jobs.updateOne(equal("_id", jobId), Document("$set" -> Document(Job.StatusString -> Job.Status.Error , Job.StatusDetailString -> message))).toFuture(), Duration(10, TimeUnit.SECONDS)) } private def updateJobStatus(jobId: String, status: String): Boolean = { val result = Await.result(jobs.updateOne(equal("_id", jobId), Document("$set" -> Document(Job.StatusString -> status))).toFuture(), Duration(10, TimeUnit.SECONDS)) if (result.getModifiedCount == 1) true else false } def updateJobProgress(jobId: String, progress: Int): Boolean = { val result = Await.result(jobs.updateOne(equal("_id", jobId), Document("$set" -> Document(Job.ProgressString -> progress))).toFuture(), Duration(10, TimeUnit.SECONDS)) if (result.getModifiedCount == 1) true else false } def insertFlow(collectionName: String, flow: Flow): Unit = { val collection = db.getCollection(collectionName) Await.result(collection.insertOne(flow.toDoc()).toFuture(), Duration(10, TimeUnit.SECONDS)) } def dropCollection(collectionName: String): Unit = { Await.result(db.getCollection(collectionName).drop().toFuture(), Duration(10, TimeUnit.SECONDS)) } def collectionSize(collectionName: String): Long = { Await.result(db.getCollection(collectionName).count().toFuture(), Duration(10, TimeUnit.SECONDS)) } } object Repository { def apply(): Repository = { val config = ConfigFactory.load("application.properties") val mongoUri = config.getString("spring.data.mongodb.uri") new Repository(mongoUri) } }
apache-2.0
JimSadler/theburgessprocess2
RealTalkBlog/wp-content/themes/benevolent/inc/extras.php
23448
<?php /** * Custom functions that act independently of the theme templates. * * Eventually, some of the functionality here could be replaced by core features. * * @package Benevolent */ /** * Adds custom classes to the array of body classes. * * @param array $classes Classes for the body element. * @return array */ function benevolent_body_classes( $classes ) { global $post; // Adds a class of group-blog to blogs with more than 1 published author. if ( is_multi_author() ) { $classes[] = 'group-blog'; } // Adds a class of hfeed to non-singular pages. if ( ! is_singular() ) { $classes[] = 'hfeed'; } // Adds a class of custom-background-image to sites with a custom background image. if ( get_background_image() ) { $classes[] = 'custom-background-image'; } // Adds a class of custom-background-color to sites with a custom background color. if ( get_background_color() != 'ffffff' ) { $classes[] = 'custom-background-color'; } if( !( is_active_sidebar( 'right-sidebar' )) || is_page_template( 'template-home.php' ) || is_search() ) { $classes[] = 'full-width'; } if( is_page() ){ $sidebar_layout = get_post_meta( $post->ID, 'benevolent_sidebar_layout', true ); if( $sidebar_layout == 'no-sidebar' ) $classes[] = 'full-width'; } if( get_theme_mod( 'benevolent_ed_slider' ) ){ $classes[] = 'has-slider'; } return $classes; } add_filter( 'body_class', 'benevolent_body_classes' ); if( ! function_exists( 'benevolent_excerpt' ) ): /** * benevolent_excerpt can truncate a string up to a number of characters while preserving whole words and HTML tags * * @param string $text String to truncate. * @param integer $length Length of returned string, including ellipsis. * @param string $ending Ending to be appended to the trimmed string. * @param boolean $exact If false, $text will not be cut mid-word * @param boolean $considerHtml If true, HTML tags would be handled correctly * * @return string Trimmed string. * * @link http://alanwhipple.com/2011/05/25/php-truncate-string-preserving-html-tags-words/ */ function benevolent_excerpt($text, $length = 100, $ending = '...', $exact = false, $considerHtml = true) { $text = strip_shortcodes( $text ); $text = benevolent_strip_single( 'img', $text ); $text = benevolent_strip_single( 'a', $text ); if ($considerHtml) { // if the plain text is shorter than the maximum length, return the whole text if (strlen(preg_replace('/<.*?>/', '', $text)) <= $length) { return $text; } // splits all html-tags to scanable lines preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER); $total_length = strlen($ending); $open_tags = array(); $truncate = ''; foreach ($lines as $line_matchings) { // if there is any html-tag in this line, handle it and add it (uncounted) to the output if (!empty($line_matchings[1])) { // if it's an "empty element" with or without xhtml-conform closing slash if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) { // do nothing // if tag is a closing tag } else if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) { // delete tag from $open_tags list $pos = array_search($tag_matchings[1], $open_tags); if ($pos !== false) { unset($open_tags[$pos]); } // if tag is an opening tag } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) { // add tag to the beginning of $open_tags list array_unshift($open_tags, strtolower($tag_matchings[1])); } // add html-tag to $truncate'd text $truncate .= $line_matchings[1]; } // calculate the length of the plain text part of the line; handle entities as one character $content_length = strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2])); if ($total_length+$content_length> $length) { // the number of characters which are left $left = $length - $total_length; $entities_length = 0; // search for html entities if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) { // calculate the real length of all entities in the legal range foreach ($entities[0] as $entity) { if ($entity[1]+1-$entities_length <= $left) { $left--; $entities_length += strlen($entity[0]); } else { // no more characters left break; } } } $truncate .= substr($line_matchings[2], 0, $left+$entities_length); // maximum lenght is reached, so get off the loop break; } else { $truncate .= $line_matchings[2]; $total_length += $content_length; } // if the maximum length is reached, get off the loop if($total_length>= $length) { break; } } } else { if (strlen($text) <= $length) { return $text; } else { $truncate = substr($text, 0, $length - strlen($ending)); } } // if the words shouldn't be cut in the middle... if (!$exact) { // ...search the last occurance of a space... $spacepos = strrpos($truncate, ' '); if (isset($spacepos)) { // ...and cut the text in this position $truncate = substr($truncate, 0, $spacepos); } } // add the defined ending to the text $truncate .= $ending; if($considerHtml) { // close all unclosed html-tags foreach ($open_tags as $tag) { $truncate .= '</' . $tag . '>'; } } return $truncate; } endif; // End function_exists /** * Custom Bread Crumb * * @link http://www.qualitytuts.com/wordpress-custom-breadcrumbs-without-plugin/ */ function benevolent_breadcrumbs_cb() { $showOnHome = 0; // 1 - show breadcrumbs on the homepage, 0 - don't show $delimiter = esc_html( get_theme_mod( 'benevolent_breadcrumb_separator', __( '>', 'benevolent' ) ) ); // delimiter between crumbs $home = esc_html( get_theme_mod( 'benevolent_breadcrumb_home_text', __( 'Home', 'benevolent' ) ) ); // text for the 'Home' link $showCurrent = get_theme_mod( 'benevolent_ed_current', '1' ); // 1 - show current post/page title in breadcrumbs, 0 - don't show $before = '<span class="current">'; // tag before the current crumb $after = '</span>'; // tag after the current crumb global $post; $homeLink = esc_url( home_url( ) ); if (is_home() || is_front_page()) { if ($showOnHome == 1) echo '<div id="crumbs"><a href="' . $homeLink . '">' . $home . '</a></div>'; } else { echo '<div id="crumbs"><a href="' . $homeLink . '">' . $home . '</a> ' . $delimiter . ' '; if ( is_category() ) { $thisCat = get_category(get_query_var('cat'), false); if ($thisCat->parent != 0) echo get_category_parents($thisCat->parent, TRUE, ' ' . $delimiter . ' '); echo $before . single_cat_title('', false) . $after; } elseif ( is_search() ) { echo $before . esc_html__( 'Search Result', 'benevolent' ) . $after; } elseif ( is_day() ) { echo '<a href="' . esc_url( get_year_link( get_the_time('Y') ) ) . '">' . esc_html( get_the_time('Y') ) . '</a> ' . $delimiter . ' '; echo '<a href="' . esc_url( get_month_link( get_the_time('Y'), get_the_time('m') ) ) . '">' . esc_html( get_the_time('F') ) . '</a> ' . $delimiter . ' '; echo $before . esc_html( get_the_time('d') ) . $after; } elseif ( is_month() ) { echo '<a href="' . esc_url( get_year_link( get_the_time('Y') ) ) . '">' . esc_html( get_the_time('Y') ) . '</a> ' . $delimiter . ' '; echo $before . esc_html( get_the_time('F') ) . $after; } elseif ( is_year() ) { echo $before . esc_html( get_the_time('Y') ) . $after; } elseif ( is_single() && !is_attachment() ) { if ( get_post_type() != 'post' ) { $post_type = get_post_type_object(get_post_type()); $slug = $post_type->rewrite; echo '<a href="' . $homeLink . '/' . $slug['slug'] . '/">' . esc_html( $post_type->labels->singular_name ) . '</a>'; if ($showCurrent == 1) echo ' ' . $delimiter . ' ' . $before . esc_html( get_the_title() ) . $after; } else { $cat = get_the_category(); $cat = $cat[0]; $cats = get_category_parents($cat, TRUE, ' ' . $delimiter . ' '); if ($showCurrent == 0) $cats = preg_replace("#^(.+)\s$delimiter\s$#", "$1", $cats); echo $cats; if ($showCurrent == 1) echo $before . esc_html( get_the_title() ) . $after; } } elseif ( !is_single() && !is_page() && get_post_type() != 'post' && !is_404() ) { $post_type = get_post_type_object(get_post_type()); echo $before . esc_html( $post_type->labels->singular_name ) . $after; } elseif ( is_attachment() ) { $parent = get_post($post->post_parent); $cat = get_the_category($parent->ID); $cat = $cat[0]; echo get_category_parents($cat, TRUE, ' ' . $delimiter . ' '); echo '<a href="' . esc_url( get_permalink($parent) ) . '">' . esc_html( $parent->post_title ) . '</a>'; if ($showCurrent == 1) echo ' ' . $delimiter . ' ' . $before . esc_html( get_the_title() ) . $after; } elseif ( is_page() && !$post->post_parent ) { if ($showCurrent == 1) echo $before . esc_html( get_the_title() ) . $after; } elseif ( is_page() && $post->post_parent ) { $parent_id = $post->post_parent; $breadcrumbs = array(); while ($parent_id) { $page = get_page($parent_id); $breadcrumbs[] = '<a href="' . esc_url( get_permalink($page->ID) ) . '">' . esc_html( get_the_title( $page->ID ) ) . '</a>'; $parent_id = $page->post_parent; } $breadcrumbs = array_reverse($breadcrumbs); for ($i = 0; $i < count($breadcrumbs); $i++) { echo $breadcrumbs[$i]; if ($i != count($breadcrumbs)-1) echo ' ' . $delimiter . ' '; } if ($showCurrent == 1) echo ' ' . $delimiter . ' ' . $before . esc_html( get_the_title() ) . $after; } elseif ( is_tag() ) { echo $before . esc_html( single_tag_title('', false) ) . $after; } elseif ( is_author() ) { global $author; $userdata = get_userdata($author); echo $before . esc_html( $userdata->display_name ) . $after; } if ( get_query_var('paged') ) { if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) echo ' ('; echo __( 'Page', 'benevolent' ) . ' ' . get_query_var('paged'); if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) echo ')'; } echo '</div>'; } } // end benevolent_breadcrumbs() add_action( 'benevolent_breadcrumbs', 'benevolent_breadcrumbs_cb' ); /** * Social Links Callback */ function benevolent_social_links_cb(){ $facebook = get_theme_mod( 'benevolent_facebook' ); $twitter = get_theme_mod( 'benevolent_twitter' ); $pinterest = get_theme_mod( 'benevolent_pinterest' ); $linkedin = get_theme_mod( 'benevolent_linkedin' ); $gplus = get_theme_mod( 'benevolent_gplus' ); $instagram = get_theme_mod( 'benevolent_instagram' ); $youtube = get_theme_mod( 'benevolent_youtube' ); if( $facebook || $twitter || $pinterest || $linkedin || $gplus || $instagram || $youtube ){ ?> <ul class="social-networks"> <?php if( $facebook ){ ?> <li><a href="<?php echo esc_url( $facebook ); ?>" class="fa fa-facebook" target="_blank" title="<?php esc_attr_e( 'Facebook', 'benevolent' );?>"></a></li> <?php } if( $twitter ){ ?> <li><a href="<?php echo esc_url( $twitter ); ?>" class="fa fa-twitter" target="_blank" title="<?php esc_attr_e( 'Twitter', 'benevolent' );?>"></a></li> <?php } if( $pinterest ){ ?> <li><a href="<?php echo esc_url( $pinterest ); ?>" class="fa fa-pinterest" target="_blank" title="<?php esc_attr_e( 'Pinterst', 'benevolent' );?>"></a></li> <?php } if( $linkedin ){ ?> <li><a href="<?php echo esc_url( $linkedin ); ?>" class="fa fa-linkedin" target="_blank" title="<?php esc_attr_e( 'LinkedIn', 'benevolent' );?>"></a></li> <?php } if( $gplus ){ ?> <li><a href="<?php echo esc_url( $gplus ); ?>" class="fa fa-google-plus" target="_blank" title="<?php esc_attr_e( 'Gooble Plus', 'benevolent' );?>"></a></li> <?php } if( $instagram ){ ?> <li><a href="<?php echo esc_url( $instagram ); ?>" class="fa fa-instagram" target="_blank" title="<?php esc_attr_e( 'Instagram', 'benevolent' );?>"></a></li> <?php } if( $youtube ){ ?> <li><a href="<?php echo esc_url( $youtube ); ?>" class="fa fa-youtube-play" target="_blank" title="<?php esc_attr_e( 'YouTube', 'benevolent' );?>"></a></li> <?php } ?> </ul> <?php } } add_action( 'benevolent_social_links' , 'benevolent_social_links_cb' ); /** * Hook to move comment text field to the bottom in WP 4.4 * * @link http://www.wpbeginner.com/wp-tutorials/how-to-move-comment-text-field-to-bottom-in-wordpress-4-4/ */ function benevolent_move_comment_field_to_bottom( $fields ) { $comment_field = $fields['comment']; unset( $fields['comment'] ); $fields['comment'] = $comment_field; return $fields; } add_filter( 'comment_form_fields', 'benevolent_move_comment_field_to_bottom' ); /** * Callback function for Comment List * * * @link https://codex.wordpress.org/Function_Reference/wp_list_comments */ function benevolent_theme_comment($comment, $args, $depth) { $GLOBALS['comment'] = $comment; extract($args, EXTR_SKIP); if ( 'div' == $args['style'] ) { $tag = 'div'; $add_below = 'comment'; } else { $tag = 'li'; $add_below = 'div-comment'; } ?> <<?php echo $tag ?> <?php comment_class( empty( $args['has_children'] ) ? '' : 'parent' ) ?> id="comment-<?php comment_ID() ?>"> <?php if ( 'div' != $args['style'] ) : ?> <div id="div-comment-<?php comment_ID() ?>" class="comment-body"> <?php endif; ?> <footer class="comment-meta"> <div class="comment-author vcard"> <?php if ( $args['avatar_size'] != 0 ) echo get_avatar( $comment, $args['avatar_size'] ); ?> <?php printf( __( '<b class="fn">%s</b>', 'benevolent' ), get_comment_author_link() ); ?> </div> <?php if ( $comment->comment_approved == '0' ) : ?> <em class="comment-awaiting-moderation"><?php _e( 'Your comment is awaiting moderation.', 'benevolent' ); ?></em> <br /> <?php endif; ?> <div class="comment-metadata commentmetadata"><a href="<?php echo htmlspecialchars( get_comment_link( $comment->comment_ID ) ); ?>"><time datetime="<?php comment_date(); ?>"> <?php /* translators: 1: date, 2: time */ printf( __( '%s', 'benevolent' ), get_comment_date() ); ?></time></a><?php edit_comment_link( __( '(Edit)', 'benevolent' ), ' ', '' ); ?> </div> </footer> <div class="comment-content"><?php comment_text(); ?></div> <div class="reply"> <?php comment_reply_link( array_merge( $args, array( 'add_below' => $add_below, 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) ); ?> </div> <?php if ( 'div' != $args['style'] ) : ?> </div> <?php endif; ?> <?php } /** * Fuction to get Sections */ function benevolent_get_sections(){ $sections = array( 'intro-section' => array( 'class' => 'intro', 'id' => 'intro' ), 'community-section' => array( 'class' => 'our-community', 'id' => 'community' ), 'stats-section' => array( 'class' => 'stats', 'id' => 'stats' ), 'blog-section' => array( 'class' => 'blog-section', 'id' => 'blog' ), 'sponsor-section' => array( 'class' => 'sponsors', 'id' => 'sponsor' ) ); $enabled_section = array(); foreach ( $sections as $section ) { if ( esc_attr( get_theme_mod( 'benevolent_ed_' . $section['id'] . '_section' ) ) == 1 ){ $enabled_section[] = array( 'id' => $section['id'], 'class' => $section['class'] ); } } return $enabled_section; } /** * Callback for Banner Slider */ function benevolent_slider_cb(){ $slider_caption = get_theme_mod( 'benevolent_slider_caption', '1' ); $slider_readmore = get_theme_mod( 'benevolent_slider_readmore', __( 'Learn More', 'benevolent' ) ); $slider_cat = get_theme_mod( 'benevolent_slider_cat' ); if( $slider_cat ){ $slider_qry = new WP_Query( array( 'post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => -1, 'cat' => $slider_cat, 'ignore_sticky_posts' => true ) ); if( $slider_qry->have_posts() ){ echo '<div class="banner"><div class="flexslider"><ul class="slides">'; while( $slider_qry->have_posts()) { $slider_qry->the_post(); if( has_post_thumbnail() ){ ?> <li> <?php the_post_thumbnail( 'benevolent-slider' ); if( $slider_caption ){ ?> <div class="banner-text"> <div class="container"> <div class="text"> <strong class="main-title"><?php the_title(); ?></strong> <?php if( has_excerpt() ) the_excerpt(); ?> <a href="<?php the_permalink(); ?>" class="btn-learn"><?php echo esc_html( $slider_readmore );?></a> </div> </div> </div> <?php } ?> </li> <?php } } echo '</ul></div></div>'; wp_reset_postdata(); } } } add_action( 'benevolent_slider', 'benevolent_slider_cb' ); /** * Callback Function for Promotional Block */ function benevolent_promotional_cb(){ $ed_promotional_section = get_theme_mod( 'benevolent_ed_promotional_section' ); $promotional_section_title = get_theme_mod( 'benevolent_promotional_section_title' ); $promotional_button_text = get_theme_mod( 'benevolent_promotional_button_text' ); $promotional_button_url = get_theme_mod( 'benevolent_promotional_button_url' ); $promotional_section_bg = get_theme_mod( 'benevolent_promotional_section_bg' ); if( $ed_promotional_section ){ ?> <div class="promotional-block" <?php if( $promotional_section_bg ) echo 'style="background: url(' . esc_url( $promotional_section_bg ) . '); background-size: cover; background-repeat: no-repeat; background-position: center;"';?>> <div class="container"> <div class="text"> <?php if( $promotional_section_title ) echo '<h3 class="title">' . esc_html( $promotional_section_title ) . '</h3>'; if( $promotional_button_url && $promotional_button_text ) echo '<a href="' . esc_url( $promotional_button_url ) . '" class="btn-donate" target="_blank">' . esc_html( $promotional_button_text ) . '</a>'; ?> </div> </div> </div> <?php } } add_action( 'benevolent_promotional', 'benevolent_promotional_cb' ); /** * Helper function for listing Intro section */ function benevolent_intro_helper( $image, $logo, $title, $link, $url ){ if( $image ){ $img = wp_get_attachment_image_src( $image, 'full' ); $log = wp_get_attachment_image_src( $logo, 'full' ); echo '<div class="columns-3">'; echo '<div class="img-holder"><img src="' . esc_url( $img[0] ) . '" alt="' . esc_attr( $title ) . '" /></div>'; if( $logo ) echo '<div class="icon-holder"><img src="' . esc_url( $log[0] ) .'" alt="' . esc_attr( $title ) . '" /></div>'; if( $title || $url ){ echo '<div class="text-holder">'; if( $title ) echo '<strong class="title">' . esc_html( $title ) . '</strong>'; if( $url && $link ) echo '<a class="btn" href="' . esc_url( $url ) . '" target="_blank">' . esc_html( $link ) . '<span class="fa fa-angle-right"></span></a>'; echo '</div>'; } echo '</div>'; } } /** * Helper function for listing sponsor */ function benevolent_sponsor_helper( $logo, $url ){ if( $url ) echo '<a href="' . esc_url( $url ) . '" target="_blank">'; if( $logo ) echo '<div class="columns-5"><img src="' . esc_url( $logo ) . '" alt=""></div>'; if( $url ) echo '</a>'; } /** * Helper function for listing stat counter */ function benevolent_stat_helper( $title, $counter ){ if( $counter ){ ?> <div class="columns-4"> <strong class="number"><?php echo absint( $counter );?></strong> <?php if( $title ) echo '<span>' . esc_html( $title ) . '</span>'; ?> </div> <?php } } /** * Custom CSS */ function benevolent_custom_css(){ $custom_css = get_theme_mod( 'benevolent_custom_css' ); if( !empty( $custom_css ) ){ echo '<style type="text/css">'; echo wp_strip_all_tags( $custom_css ); echo '</style>'; } } add_action( 'wp_head', 'benevolent_custom_css', 100 ); if ( ! function_exists( 'benevolent_excerpt_more' ) && ! is_admin() ) : /** * Replaces "[...]" (appended to automatically generated excerpts) with ... * */ function benevolent_excerpt_more() { return ' &hellip; '; } add_filter( 'excerpt_more', 'benevolent_excerpt_more' ); endif; if ( ! function_exists( 'benevolent_excerpt_length' ) ) : /** * Changes the default 55 character in excerpt */ function benevolent_excerpt_length( $length ) { return 60; } add_filter( 'excerpt_length', 'benevolent_excerpt_length', 999 ); endif; /** * Footer Credits */ function benevolent_footer_credit(){ $text = '<div class="site-info"><div class="container"><span class="copyright">'; $text .= esc_html__( '&copy; ', 'benevolent' ) . date('Y'); $text .= ' <a href="' . esc_url( home_url( '/' ) ) . '">' . esc_html( get_bloginfo( 'name' ) ) . '</a>.</span>'; $text .= '<span class="by">'; $text .= '<a href="' . esc_url( 'http://raratheme.com/wordpress-themes/benevolent/' ) .'" rel="author" target="_blank">' . esc_html__( 'Benevolent by Rara Theme', 'benevolent' ) . '</a>. '; $text .= sprintf( esc_html__( 'Powered by %s', 'benevolent' ), '<a href="'. esc_url( __( 'https://wordpress.org/', 'benevolent' ) ) .'" target="_blank">WordPress</a>.' ); $text .= '</span></div></div>'; echo apply_filters( 'benevolent_footer_text', $text ); } add_action( 'benevolent_footer', 'benevolent_footer_credit' ); /** * Return sidebar layouts for pages */ function benevolent_sidebar_layout(){ global $post; if( get_post_meta( $post->ID, 'benevolent_sidebar_layout', true ) ){ return get_post_meta( $post->ID, 'benevolent_sidebar_layout', true ); }else{ return 'right-sidebar'; } } /** * Strip specific tags from string * @link http://www.altafweb.com/2011/12/remove-specific-tag-from-php-string.html */ function benevolent_strip_single( $tag, $string ){ $string = preg_replace('/<'.$tag.'[^>]*>/i', '', $string); $string = preg_replace('/<\/'.$tag.'>/i', '', $string); return $string; }
apache-2.0
hustlijian/oj-jobdu
1109/main_table.cpp
972
//AC:并查集 #include <iostream> #include <cstdio> #include <cstring> using namespace std; const int MAX = 1000 + 5; int n, m; int f[MAX]; void Init(void) { memset(f, -1, sizeof(f)); } int getFather(int u) { return (f[u] == -1)? u : f[u] = getFather(f[u]); } int main() { int i; int u, v; int t; while (scanf("%d %d", &n, &m) && n != 0) { Init(); for (i=1; i<=m; i++) { cin >> u >> v; t = v; int fu = getFather(u); int fv = getFather(v); if (fu != fv) { f[fu] = fv; } } // 如果图连通,那么有且仅有一个结点的父结点编号为-1 int ans = 0; for (i=1; i<=n && ans < 2; i++) { if (-1 == f[i]) { ans++; } } (ans == 1) ? cout << "YES" << endl : cout << "NO" << endl; } return 0; }
apache-2.0
Hexworks/zircon
zircon.jvm.examples/src/main/java/org/hexworks/zircon/examples/playground/TestApp.java
1852
package org.hexworks.zircon.examples.playground; import org.hexworks.zircon.api.*; import org.hexworks.zircon.api.application.AppConfig; import org.hexworks.zircon.api.component.ColorTheme; import org.hexworks.zircon.api.component.ComponentAlignment; import org.hexworks.zircon.api.component.TextArea; import org.hexworks.zircon.api.data.Size; import org.hexworks.zircon.api.grid.TileGrid; import org.hexworks.zircon.api.resource.TilesetResource; import org.hexworks.zircon.api.screen.Screen; import org.hexworks.zircon.api.view.base.BaseView; public class TestApp { private static final TilesetResource defaultTileset = CP437TilesetResources.sb16x16(); public static void main(String[] args) { TileGrid tileGrid = SwingApplications.startTileGrid( AppConfig.newBuilder() .withSize(Size.create(60, 34)) .withDefaultTileset(defaultTileset) .build()); TestTerminalScreen testTerminalScreen = new TestTerminalScreen(tileGrid, ColorThemes.linuxMintDark()); testTerminalScreen.dock(); } public static class TestTerminalScreen extends BaseView { private final TextArea commandLine; public TestTerminalScreen(TileGrid tileGrid, ColorTheme theme) { super(tileGrid, theme); Screen screen = getScreen(); commandLine = Components.textArea() .withPreferredSize(tileGrid.getWidth(), 3) .withDecorations(ComponentDecorations.box()) .withAlignmentWithin(screen, ComponentAlignment.BOTTOM_CENTER) .build(); screen.addComponent(commandLine); } @Override public void onDock() { super.onDock(); commandLine.requestFocus(); } } }
apache-2.0
DegJ/miceschoolproject
MICE/src/mice/staticHelpers/Spelprojekt.java
1987
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package mice.staticHelpers; import java.util.HashMap; import oru.inf.InfException; /** * * @author Nicklas */ public class Spelprojekt { int sid; String beteckning; String startdatum; String releasedatum; int aid; public Spelprojekt(int sid) { this.sid = sid; if (sid >= 0) { loadData(); } } /** * loads data from the Db about the Spelprojekt */ private void loadData() { HashMap<String, String> hm = new HashMap<>(); try { String query = "select beteckning,startdatum,releasedatum,aid from spelprojekt where sid=" + getSid(); hm = DB.fetchRow(query); } catch (InfException e) { e.getMessage(); } beteckning = hm.get("BETECKNING"); startdatum = hm.get("STARTDATUM"); releasedatum = hm.get("RELEASEDATUM"); if (hm.get("AID") != null) { aid = Integer.parseInt(hm.get("AID")); } else { aid = -1; } } /** * Overrides toString method of Object to correctly show what we want in for * example comboboxes * * @return String */ @Override public String toString() { return beteckning; } /** * @return the sid */ public int getSid() { return sid; } /** * @return the beteckning */ public String getBeteckning() { return beteckning; } /** * @return the startdatum */ public String getStartdatum() { return startdatum; } /** * @return the releasedatum */ public String getReleasedatum() { return releasedatum; } /** * @return the aid */ public int getAid() { return aid; } }
apache-2.0
artspb/jdk2trove
jdk2trove-plugin/testData/quickFix/hashmap/tObjectTypeHashMap/beforeStringInt.java
250
// "Use Trove TObjectIntHashMap (may change semantics)" import java.util.HashMap; import java.util.Map; public class THashMapExample { public void stringInt() { <caret>Map<String, Integer> local = new HashMap<String, Integer>(); } }
apache-2.0
hferentschik/hibernate-validator
engine/src/test/java/org/hibernate/validator/test/internal/engine/groups/redefiningdefaultgroup/Car.java
3393
/** * JBoss, Home of Professional Open Source * Copyright 2009, Red Hat, Inc. and/or its affiliates, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hibernate.validator.test.internal.engine.groups.redefiningdefaultgroup; import javax.validation.Valid; import javax.validation.constraints.AssertTrue; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * An example entity class enriched with constraint annotations from * the Bean Validation API (<a href="http://jcp.org/en/jsr/detail?id=303">JSR * 303</a>). Have a look at {@link org.hibernate.validator.quickstart.CarTest} to learn, how the Bean Validation * API can be used to validate {@code Car} instances. * * @author Gunnar Morling * @author Hardy Ferentschik * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ public class Car { //The definition of the message in the constraints is just for testing purpose. //In a real world scenario you would place your messages into resource bundles. /** * By annotating the field with @NotNull we specify, that null is not a valid * value. */ @NotNull(message = "may not be null") private String manufacturer; /** * This String field shall not only not allowed to be null, it shall also between * 2 and 14 characters long. */ @NotNull @Size(min = 2, max = 14, message = "size must be between {min} and {max}") private String licensePlate; /** * This int field shall have a value of at least 2. */ @Min(value = 2, message = "must be greater than or equal to {value}") private int seatCount; @AssertTrue(message = "The car has to pass the vehicle inspection first", groups = CarChecks.class) private boolean passedVehicleInspection; @Valid private Driver driver; public Car(String manufacturer, String licencePlate, int seatCount) { this.manufacturer = manufacturer; this.licensePlate = licencePlate; this.seatCount = seatCount; } public String getManufacturer() { return manufacturer; } public void setManufacturer(String manufacturer) { this.manufacturer = manufacturer; } public String getLicensePlate() { return licensePlate; } public void setLicensePlate(String licensePlate) { this.licensePlate = licensePlate; } public int getSeatCount() { return seatCount; } public void setSeatCount(int seatCount) { this.seatCount = seatCount; } public boolean getPassedVehicleInspection() { return passedVehicleInspection; } public void setPassedVehicleInspection(boolean passed) { this.passedVehicleInspection = passed; } public Driver getDriver() { return driver; } public void setDriver(Driver driver) { this.driver = driver; } }
apache-2.0
yongzhidai/GameServer
src/com/dyz/persist/util/DBUtil.java
1396
package com.dyz.persist.util; import java.io.IOException; import java.io.InputStream; import com.ibatis.common.resources.Resources; import com.ibatis.sqlmap.client.SqlMapClient; import com.ibatis.sqlmap.engine.builder.xml.SqlMapConfigParser; /** * 操作数据库工具类,负责初始化ibatis的SqlMapClient, * 注意,如果ibatis的config文件中没有配置sqlMap元素,不要初始化,否则会报错 * @author dyz * */ public class DBUtil { private static SqlMapClient roledataSqlMapClient; private static SqlMapClient gamedataSqlMapClient; public static void initAllSqlMapClient()throws Exception{ //gamedataSqlMapClient=initSqlMapClient("ibatis-gamedata-config.xml"); roledataSqlMapClient=initSqlMapClient("ibatis-roledata-config.xml"); } private static SqlMapClient initSqlMapClient(String cfgName) throws Exception{ InputStream in = null; SqlMapClient sqlMapClient = null; try{ in = Resources.getResourceAsStream(cfgName); sqlMapClient = new SqlMapConfigParser().parse(in); }finally{ try { in.close(); } catch (IOException e) { e.printStackTrace(); } } return sqlMapClient; } public static SqlMapClient getRoledataSqlMapClient() { return roledataSqlMapClient; } public static SqlMapClient getGamedataSqlMapClient() { return gamedataSqlMapClient; } }
apache-2.0
davityle/ngAndroid
ng-processor/src/main/java/com/github/davityle/ngprocessor/model/Model.java
352
package com.github.davityle.ngprocessor.model; public class Model { private final String name, typeName; public Model(String name, String typeName) { this.name = name; this.typeName = typeName; } public String getName(){ return name; } public String getTypeName(){ return typeName; } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-appmesh/src/main/java/com/amazonaws/services/appmesh/model/Listener.java
12390
/* * Copyright 2017-2022 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.appmesh.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * An object that represents a listener for a virtual node. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/Listener" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class Listener implements Serializable, Cloneable, StructuredPojo { /** * <p> * The connection pool information for the listener. * </p> */ private VirtualNodeConnectionPool connectionPool; /** * <p> * The health check information for the listener. * </p> */ private HealthCheckPolicy healthCheck; /** * <p> * The outlier detection information for the listener. * </p> */ private OutlierDetection outlierDetection; /** * <p> * The port mapping information for the listener. * </p> */ private PortMapping portMapping; /** * <p> * An object that represents timeouts for different protocols. * </p> */ private ListenerTimeout timeout; /** * <p> * A reference to an object that represents the Transport Layer Security (TLS) properties for a listener. * </p> */ private ListenerTls tls; /** * <p> * The connection pool information for the listener. * </p> * * @param connectionPool * The connection pool information for the listener. */ public void setConnectionPool(VirtualNodeConnectionPool connectionPool) { this.connectionPool = connectionPool; } /** * <p> * The connection pool information for the listener. * </p> * * @return The connection pool information for the listener. */ public VirtualNodeConnectionPool getConnectionPool() { return this.connectionPool; } /** * <p> * The connection pool information for the listener. * </p> * * @param connectionPool * The connection pool information for the listener. * @return Returns a reference to this object so that method calls can be chained together. */ public Listener withConnectionPool(VirtualNodeConnectionPool connectionPool) { setConnectionPool(connectionPool); return this; } /** * <p> * The health check information for the listener. * </p> * * @param healthCheck * The health check information for the listener. */ public void setHealthCheck(HealthCheckPolicy healthCheck) { this.healthCheck = healthCheck; } /** * <p> * The health check information for the listener. * </p> * * @return The health check information for the listener. */ public HealthCheckPolicy getHealthCheck() { return this.healthCheck; } /** * <p> * The health check information for the listener. * </p> * * @param healthCheck * The health check information for the listener. * @return Returns a reference to this object so that method calls can be chained together. */ public Listener withHealthCheck(HealthCheckPolicy healthCheck) { setHealthCheck(healthCheck); return this; } /** * <p> * The outlier detection information for the listener. * </p> * * @param outlierDetection * The outlier detection information for the listener. */ public void setOutlierDetection(OutlierDetection outlierDetection) { this.outlierDetection = outlierDetection; } /** * <p> * The outlier detection information for the listener. * </p> * * @return The outlier detection information for the listener. */ public OutlierDetection getOutlierDetection() { return this.outlierDetection; } /** * <p> * The outlier detection information for the listener. * </p> * * @param outlierDetection * The outlier detection information for the listener. * @return Returns a reference to this object so that method calls can be chained together. */ public Listener withOutlierDetection(OutlierDetection outlierDetection) { setOutlierDetection(outlierDetection); return this; } /** * <p> * The port mapping information for the listener. * </p> * * @param portMapping * The port mapping information for the listener. */ public void setPortMapping(PortMapping portMapping) { this.portMapping = portMapping; } /** * <p> * The port mapping information for the listener. * </p> * * @return The port mapping information for the listener. */ public PortMapping getPortMapping() { return this.portMapping; } /** * <p> * The port mapping information for the listener. * </p> * * @param portMapping * The port mapping information for the listener. * @return Returns a reference to this object so that method calls can be chained together. */ public Listener withPortMapping(PortMapping portMapping) { setPortMapping(portMapping); return this; } /** * <p> * An object that represents timeouts for different protocols. * </p> * * @param timeout * An object that represents timeouts for different protocols. */ public void setTimeout(ListenerTimeout timeout) { this.timeout = timeout; } /** * <p> * An object that represents timeouts for different protocols. * </p> * * @return An object that represents timeouts for different protocols. */ public ListenerTimeout getTimeout() { return this.timeout; } /** * <p> * An object that represents timeouts for different protocols. * </p> * * @param timeout * An object that represents timeouts for different protocols. * @return Returns a reference to this object so that method calls can be chained together. */ public Listener withTimeout(ListenerTimeout timeout) { setTimeout(timeout); return this; } /** * <p> * A reference to an object that represents the Transport Layer Security (TLS) properties for a listener. * </p> * * @param tls * A reference to an object that represents the Transport Layer Security (TLS) properties for a listener. */ public void setTls(ListenerTls tls) { this.tls = tls; } /** * <p> * A reference to an object that represents the Transport Layer Security (TLS) properties for a listener. * </p> * * @return A reference to an object that represents the Transport Layer Security (TLS) properties for a listener. */ public ListenerTls getTls() { return this.tls; } /** * <p> * A reference to an object that represents the Transport Layer Security (TLS) properties for a listener. * </p> * * @param tls * A reference to an object that represents the Transport Layer Security (TLS) properties for a listener. * @return Returns a reference to this object so that method calls can be chained together. */ public Listener withTls(ListenerTls tls) { setTls(tls); return this; } /** * 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("{"); if (getConnectionPool() != null) sb.append("ConnectionPool: ").append(getConnectionPool()).append(","); if (getHealthCheck() != null) sb.append("HealthCheck: ").append(getHealthCheck()).append(","); if (getOutlierDetection() != null) sb.append("OutlierDetection: ").append(getOutlierDetection()).append(","); if (getPortMapping() != null) sb.append("PortMapping: ").append(getPortMapping()).append(","); if (getTimeout() != null) sb.append("Timeout: ").append(getTimeout()).append(","); if (getTls() != null) sb.append("Tls: ").append(getTls()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof Listener == false) return false; Listener other = (Listener) obj; if (other.getConnectionPool() == null ^ this.getConnectionPool() == null) return false; if (other.getConnectionPool() != null && other.getConnectionPool().equals(this.getConnectionPool()) == false) return false; if (other.getHealthCheck() == null ^ this.getHealthCheck() == null) return false; if (other.getHealthCheck() != null && other.getHealthCheck().equals(this.getHealthCheck()) == false) return false; if (other.getOutlierDetection() == null ^ this.getOutlierDetection() == null) return false; if (other.getOutlierDetection() != null && other.getOutlierDetection().equals(this.getOutlierDetection()) == false) return false; if (other.getPortMapping() == null ^ this.getPortMapping() == null) return false; if (other.getPortMapping() != null && other.getPortMapping().equals(this.getPortMapping()) == false) return false; if (other.getTimeout() == null ^ this.getTimeout() == null) return false; if (other.getTimeout() != null && other.getTimeout().equals(this.getTimeout()) == false) return false; if (other.getTls() == null ^ this.getTls() == null) return false; if (other.getTls() != null && other.getTls().equals(this.getTls()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getConnectionPool() == null) ? 0 : getConnectionPool().hashCode()); hashCode = prime * hashCode + ((getHealthCheck() == null) ? 0 : getHealthCheck().hashCode()); hashCode = prime * hashCode + ((getOutlierDetection() == null) ? 0 : getOutlierDetection().hashCode()); hashCode = prime * hashCode + ((getPortMapping() == null) ? 0 : getPortMapping().hashCode()); hashCode = prime * hashCode + ((getTimeout() == null) ? 0 : getTimeout().hashCode()); hashCode = prime * hashCode + ((getTls() == null) ? 0 : getTls().hashCode()); return hashCode; } @Override public Listener clone() { try { return (Listener) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.appmesh.model.transform.ListenerMarshaller.getInstance().marshall(this, protocolMarshaller); } }
apache-2.0
libra/libra
consensus/src/liveness/rotating_proposer_test.rs
4653
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::liveness::{ proposer_election::ProposerElection, rotating_proposer_election::RotatingProposer, }; use consensus_types::block::{block_test_utils::certificate_for_genesis, Block}; use diem_types::validator_signer::ValidatorSigner; #[test] fn test_rotating_proposer() { let chosen_validator_signer = ValidatorSigner::random([0u8; 32]); let chosen_author = chosen_validator_signer.author(); let another_validator_signer = ValidatorSigner::random([1u8; 32]); let another_author = another_validator_signer.author(); let proposers = vec![chosen_author, another_author]; let pe: Box<dyn ProposerElection> = Box::new(RotatingProposer::new(proposers, 1)); // Send a proposal from both chosen author and another author, the only winning proposals // follow the round-robin rotation. // Test genesis and the next block let quorum_cert = certificate_for_genesis(); let good_proposal = Block::new_proposal(vec![], 1, 1, quorum_cert.clone(), &another_validator_signer); let bad_proposal = Block::new_proposal(vec![], 1, 2, quorum_cert.clone(), &chosen_validator_signer); let next_good_proposal = Block::new_proposal(vec![], 2, 3, quorum_cert, &chosen_validator_signer); assert!(pe.is_valid_proposal(&good_proposal)); assert!(!pe.is_valid_proposal(&bad_proposal)); assert!(pe.is_valid_proposal(&next_good_proposal),); assert!(!pe.is_valid_proposer(chosen_author, 1)); assert!(pe.is_valid_proposer(another_author, 1),); assert!(pe.is_valid_proposer(chosen_author, 2)); assert!(!pe.is_valid_proposer(another_author, 2)); assert_eq!(pe.get_valid_proposer(1), another_author); assert_eq!(pe.get_valid_proposer(2), chosen_author); } #[test] fn test_rotating_proposer_with_three_contiguous_rounds() { let chosen_validator_signer = ValidatorSigner::random([0u8; 32]); let chosen_author = chosen_validator_signer.author(); let another_validator_signer = ValidatorSigner::random([1u8; 32]); let another_author = another_validator_signer.author(); let proposers = vec![chosen_author, another_author]; let pe: Box<dyn ProposerElection> = Box::new(RotatingProposer::new(proposers, 3)); // Send a proposal from both chosen author and another author, the only winning proposals // follow the round-robin rotation with 3 contiguous rounds. // Test genesis and the next block let quorum_cert = certificate_for_genesis(); let good_proposal = Block::new_proposal(vec![], 1, 1, quorum_cert.clone(), &chosen_validator_signer); let bad_proposal = Block::new_proposal(vec![], 1, 2, quorum_cert.clone(), &another_validator_signer); let next_good_proposal = Block::new_proposal(vec![], 2, 3, quorum_cert, &chosen_validator_signer); assert!(pe.is_valid_proposal(&good_proposal),); assert!(!pe.is_valid_proposal(&bad_proposal)); assert!(pe.is_valid_proposal(&next_good_proposal),); assert!(!pe.is_valid_proposer(another_author, 1)); assert!(pe.is_valid_proposer(chosen_author, 1)); assert!(pe.is_valid_proposer(chosen_author, 2)); assert!(!pe.is_valid_proposer(another_author, 2)); assert_eq!(pe.get_valid_proposer(1), chosen_author); assert_eq!(pe.get_valid_proposer(2), chosen_author); } #[test] fn test_fixed_proposer() { let chosen_validator_signer = ValidatorSigner::random([0u8; 32]); let chosen_author = chosen_validator_signer.author(); let another_validator_signer = ValidatorSigner::random([1u8; 32]); let another_author = another_validator_signer.author(); let pe: Box<dyn ProposerElection> = Box::new(RotatingProposer::new(vec![chosen_author], 1)); // Send a proposal from both chosen author and another author, the only winning proposal is // from the chosen author. // Test genesis and the next block let quorum_cert = certificate_for_genesis(); let good_proposal = Block::new_proposal(vec![], 1, 1, quorum_cert.clone(), &chosen_validator_signer); let bad_proposal = Block::new_proposal(vec![], 1, 2, quorum_cert.clone(), &another_validator_signer); let next_good_proposal = Block::new_proposal(vec![], 2, 3, quorum_cert, &chosen_validator_signer); assert!(pe.is_valid_proposal(&good_proposal)); assert!(!pe.is_valid_proposal(&bad_proposal)); assert!(pe.is_valid_proposal(&next_good_proposal)); assert!(pe.is_valid_proposer(chosen_author, 1)); assert!(!pe.is_valid_proposer(another_author, 1)); assert_eq!(pe.get_valid_proposer(1), chosen_author); }
apache-2.0
CUNY-Hunter-CSCI-Capstone-Summer2014/XMPP-Chat
librambler/Source Code/rambler/XMPP/IM/Client/Client.hpp
8508
/********************************************************************************************************************** * @file ramler/XMPP/IM/Client/Client.hpp * @date 2014-07-16 * @brief <# Brief Description #> * @details <# Detailed Description #> **********************************************************************************************************************/ #pragma once #include "rambler/rambler.hpp" #include "rambler/XML/Namespace.hpp" #include "rambler/XMPP/Core/XMLStream.hpp" #include "rambler/XMPP/IM/Message.hpp" #include "rambler/XMPP/IM/Presence.hpp" #include "rambler/XMPP/IM/RosterItem.hpp" #include "rambler/XMPP/IM/Client/IQRequestType.hpp" namespace rambler { namespace XMPP { namespace IM { namespace Client { class Client { public: using InitiatedSessionEventHandler = function<void(void)>; using FailedToInitiateSessionEventHandler = function<void(void)>; using PasswordRequiredEventHandler = function<String(String)>; using MessageReceivedEventHandler = function<void (StrongPointer<Message const> const)>; using PresenceReceivedEventHandler = function<void(StrongPointer<Presence const> const, StrongPointer<JID const> const)>; using RosterItemReceivedEventHandler = function<void(StrongPointer<RosterItem const> const)>; using RosterItemRemovedEventHandler = function<void(StrongPointer<JID const> const)>; using JIDAcceptedSubscriptionRequestEventHandler = function<void(StrongPointer<JID const> const)>; using JIDCanceledSubscriptionEventHandler = function<void(StrongPointer<JID const> const)>; using JIDRejectedSubscriptionRequestEventHandler = function<void(StrongPointer<JID const> const)>; using JIDUnsubscribedEventHandler = function<void(StrongPointer<JID const> const)>; using SubscriptionRequestReceivedEventHandler = function<void(StrongPointer<JID const> const, String const message)>; RAMBLER_API Client(String username); RAMBLER_API ~Client() = default; RAMBLER_API StrongPointer<JID const> getJID() const; #pragma mark Session Management RAMBLER_API void initiateSessionForUser(String username); //Not Implemented Yet RAMBLER_API void setInitiatedSessionEventHandler(InitiatedSessionEventHandler eventHandler); RAMBLER_API void setFailedToInitiateSessionEventHandler(FailedToInitiateSessionEventHandler eventHandler); #pragma mark Authentication RAMBLER_API void setPasswordRequiredEventHandler(PasswordRequiredEventHandler eventHandler); #pragma mark Message Exchanging RAMBLER_API void sendMessage(StrongPointer<Message const> message); RAMBLER_API void setMessageReceivedEventHandler(MessageReceivedEventHandler eventHandler); #pragma mark Presence Exchanging RAMBLER_API void sendPresence(StrongPointer<Presence const> const presence, StrongPointer<JID const> const jid = nullptr); RAMBLER_API void setPresenceReceivedEventHandler(PresenceReceivedEventHandler eventHandler); #pragma mark Roster Management RAMBLER_API void requestRoster(); RAMBLER_API void updateRosterWithItem(StrongPointer<RosterItem const> const item); RAMBLER_API void removeItemFromRoster(StrongPointer<RosterItem const> const item); RAMBLER_API void setRosterItemReceivedEventHandler(RosterItemReceivedEventHandler eventHandler); RAMBLER_API void setRosterItemRemovedEventHandler(RosterItemRemovedEventHandler eventHandler); #pragma mark Subscription Management RAMBLER_API void acceptSubscriptionRequestFromJID(StrongPointer<JID const> const jid); RAMBLER_API void rejectSubscriptionRequestFromJID(StrongPointer<JID const> const jid); RAMBLER_API void cancelSubscriptionFromJID(StrongPointer<JID const> const jid); RAMBLER_API void unsubscribeFromJID(StrongPointer<JID const> const jid); RAMBLER_API void requestSubscriptionToJID(StrongPointer<JID const> const jid, String const message); RAMBLER_API void setJIDAcceptedSubscriptionRequestEventHandler(JIDAcceptedSubscriptionRequestEventHandler eventHandler); RAMBLER_API void setJIDCanceledSubscriptionEventHandler(JIDCanceledSubscriptionEventHandler eventHandler); RAMBLER_API void setJIDRejectedSubscriptionRequestEventHandler(JIDRejectedSubscriptionRequestEventHandler eventHandler); RAMBLER_API void setJIDUnsubscribedEventHandler(JIDUnsubscribedEventHandler eventHandler); RAMBLER_API void setSubscriptionRequestReceivedEventHandler(SubscriptionRequestReceivedEventHandler eventHandler); #pragma mark Private private: static String ChatStates_Namespace_String; static String Jabber_IQ_Roster_Namespace_String; static String Ping_Namespace_String; static StrongPointer<XML::Namespace const> ChatStates_Namesapce; static StrongPointer<XML::Namespace const> Jabber_IQ_Roster_Namespace; static StrongPointer<XML::Namespace const> Ping_Namespace; StrongPointer<XMLStream> xmlStream; std::map<String, IQRequestType> uniqueID_IQRequestType_map; std::set<StrongPointer<JID const>> pendingSubscriptions; String getPasswordForJID(StrongPointer<JID const> jid); InitiatedSessionEventHandler initiatedSessionEventHandler; FailedToInitiateSessionEventHandler failedToInitiateSessionEventHandler; PasswordRequiredEventHandler passwordRequiredEventHandler; MessageReceivedEventHandler messageReceivedEventHandler; PresenceReceivedEventHandler presenceReceivedEventHandler; RosterItemReceivedEventHandler rosterItemReceivedEventHandler; RosterItemRemovedEventHandler rosterItemRemovedEventHandler; JIDAcceptedSubscriptionRequestEventHandler jidAcceptedSubscriptionRequestEventHandler; JIDCanceledSubscriptionEventHandler jidCanceledSubscriptionEventHandler; JIDRejectedSubscriptionRequestEventHandler jidRejectedSubscriptionRequestEventHandler; JIDUnsubscribedEventHandler jidUnsubscribedEventHandler; SubscriptionRequestReceivedEventHandler subscriptionRequestReceivedEventHandler; /* Event Handling */ #pragma mark Session Handling void handleInitiatedSessionEvent(); void handleFailedToInitiateSessionEvent(); #pragma mark Authentication Handling String handlePasswordRequiredEvent(String username); #pragma mark Message Handling void handleMessageReceivedEvent(StrongPointer<Message const> const message); #pragma mark Presence Handling void handlePresenceReceivedEvent(StrongPointer<Presence const> const presence, StrongPointer<JID const> const jid); #pragma mark RosterItem Handling void handleRosterItemReceivedEvent(StrongPointer<RosterItem const> const rosterItem); void handleRosterItemRemovedEvent(StrongPointer<JID const> const jid); #pragma mark Subscription Handling void handleJIDAcceptedSubscriptionRequestEvent(StrongPointer<JID const> const jid); void handleJIDCanceledSubscriptionEvent(StrongPointer<JID const> const jid); void handleJIDRejectedSubscriptionRequestEvent(StrongPointer<JID const> const jid); void handleJIDUnsubscribedEvent(StrongPointer<JID const> const jid); void handleSubscriptionRequestReceivedEvent(StrongPointer<JID const> const jid, String const message); #pragma mark Stanza Handling void handleIQStanzaReceivedEvent_ping(StrongPointer<XML::Element> const stanza); void handleIQStanzaReceivedEvent_rosterPush(StrongPointer<XML::Element> const stanza); #pragma mark XML Element handling StrongPointer<RosterItem const> createRosterItemFromItemElement(StrongPointer<XML::Element> const itemElement); #pragma mark Subject for deprecation public: /* Subject for deprecation */ using ClientRunloop = function<void(void)>; RAMBLER_API void start(); RAMBLER_API void stop(); RAMBLER_API void setRunloop(ClientRunloop runloop); private: ClientRunloop runloop; bool running { false }; void run(); }; }}}}
apache-2.0
trasa/aws-sdk-java
aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/DescribeNetworkInterfacesRequest.java
62195
/* * Copyright 2010-2016 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.ec2.model; import java.io.Serializable; import com.amazonaws.AmazonWebServiceRequest; import com.amazonaws.Request; import com.amazonaws.services.ec2.model.transform.DescribeNetworkInterfacesRequestMarshaller; /** * Container for the parameters to the {@link com.amazonaws.services.ec2.AmazonEC2#describeNetworkInterfaces(DescribeNetworkInterfacesRequest) DescribeNetworkInterfaces operation}. * <p> * Describes one or more of your network interfaces. * </p> * * @see com.amazonaws.services.ec2.AmazonEC2#describeNetworkInterfaces(DescribeNetworkInterfacesRequest) */ public class DescribeNetworkInterfacesRequest extends AmazonWebServiceRequest implements Serializable, Cloneable, DryRunSupportedRequest<DescribeNetworkInterfacesRequest> { /** * One or more network interface IDs. <p>Default: Describes all your * network interfaces. */ private com.amazonaws.internal.ListWithAutoConstructFlag<String> networkInterfaceIds; /** * One or more filters. <ul> <li> * <p><code>addresses.private-ip-address</code> - The private IP * addresses associated with the network interface. </li> <li> * <p><code>addresses.primary</code> - Whether the private IP address is * the primary IP address associated with the network interface. </li> * <li> <p><code>addresses.association.public-ip</code> - The association * ID returned when the network interface was associated with the Elastic * IP address. </li> <li> <p><code>addresses.association.owner-id</code> * - The owner ID of the addresses associated with the network interface. * </li> <li> <p><code>association.association-id</code> - The * association ID returned when the network interface was associated with * an IP address. </li> <li> <p><code>association.allocation-id</code> - * The allocation ID returned when you allocated the Elastic IP address * for your network interface. </li> <li> * <p><code>association.ip-owner-id</code> - The owner of the Elastic IP * address associated with the network interface. </li> <li> * <p><code>association.public-ip</code> - The address of the Elastic IP * address bound to the network interface. </li> <li> * <p><code>association.public-dns-name</code> - The public DNS name for * the network interface. </li> <li> * <p><code>attachment.attachment-id</code> - The ID of the interface * attachment. </li> <li> <p><code>attachment.attach.time</code> - The * time that the network interface was attached to an instance. </li> * <li> <p><code>attachment.delete-on-termination</code> - Indicates * whether the attachment is deleted when an instance is terminated. * </li> <li> <p><code>attachment.device-index</code> - The device index * to which the network interface is attached. </li> <li> * <p><code>attachment.instance-id</code> - The ID of the instance to * which the network interface is attached. </li> <li> * <p><code>attachment.instance-owner-id</code> - The owner ID of the * instance to which the network interface is attached. </li> <li> * <p><code>attachment.nat-gateway-id</code> - The ID of the NAT gateway * to which the network interface is attached. </li> <li> * <p><code>attachment.status</code> - The status of the attachment * (<code>attaching</code> | <code>attached</code> | * <code>detaching</code> | <code>detached</code>). </li> <li> * <p><code>availability-zone</code> - The Availability Zone of the * network interface. </li> <li> <p><code>description</code> - The * description of the network interface. </li> <li> * <p><code>group-id</code> - The ID of a security group associated with * the network interface. </li> <li> <p><code>group-name</code> - The * name of a security group associated with the network interface. </li> * <li> <p><code>mac-address</code> - The MAC address of the network * interface. </li> <li> <p><code>network-interface-id</code> - The ID of * the network interface. </li> <li> <p><code>owner-id</code> - The AWS * account ID of the network interface owner. </li> <li> * <p><code>private-ip-address</code> - The private IP address or * addresses of the network interface. </li> <li> * <p><code>private-dns-name</code> - The private DNS name of the network * interface. </li> <li> <p><code>requester-id</code> - The ID of the * entity that launched the instance on your behalf (for example, AWS * Management Console, Auto Scaling, and so on). </li> <li> * <p><code>requester-managed</code> - Indicates whether the network * interface is being managed by an AWS service (for example, AWS * Management Console, Auto Scaling, and so on). </li> <li> * <p><code>source-desk-check</code> - Indicates whether the network * interface performs source/destination checking. A value of * <code>true</code> means checking is enabled, and <code>false</code> * means checking is disabled. The value must be <code>false</code> for * the network interface to perform network address translation (NAT) in * your VPC. </li> <li> <p><code>status</code> - The status of the * network interface. If the network interface is not attached to an * instance, the status is <code>available</code>; if a network interface * is attached to an instance the status is <code>in-use</code>. </li> * <li> <p><code>subnet-id</code> - The ID of the subnet for the network * interface. </li> <li> <p><code>tag</code>:<i>key</i>=<i>value</i> - * The key/value combination of a tag assigned to the resource. </li> * <li> <p><code>tag-key</code> - The key of a tag assigned to the * resource. This filter is independent of the <code>tag-value</code> * filter. For example, if you use both the filter "tag-key=Purpose" and * the filter "tag-value=X", you get any resources assigned both the tag * key Purpose (regardless of what the tag's value is), and the tag value * X (regardless of what the tag's key is). If you want to list only * resources where Purpose is X, see the * <code>tag</code>:<i>key</i>=<i>value</i> filter. </li> <li> * <p><code>tag-value</code> - The value of a tag assigned to the * resource. This filter is independent of the <code>tag-key</code> * filter. </li> <li> <p><code>vpc-id</code> - The ID of the VPC for the * network interface. </li> </ul> */ private com.amazonaws.internal.ListWithAutoConstructFlag<Filter> filters; /** * One or more network interface IDs. <p>Default: Describes all your * network interfaces. * * @return One or more network interface IDs. <p>Default: Describes all your * network interfaces. */ public java.util.List<String> getNetworkInterfaceIds() { if (networkInterfaceIds == null) { networkInterfaceIds = new com.amazonaws.internal.ListWithAutoConstructFlag<String>(); networkInterfaceIds.setAutoConstruct(true); } return networkInterfaceIds; } /** * One or more network interface IDs. <p>Default: Describes all your * network interfaces. * * @param networkInterfaceIds One or more network interface IDs. <p>Default: Describes all your * network interfaces. */ public void setNetworkInterfaceIds(java.util.Collection<String> networkInterfaceIds) { if (networkInterfaceIds == null) { this.networkInterfaceIds = null; return; } com.amazonaws.internal.ListWithAutoConstructFlag<String> networkInterfaceIdsCopy = new com.amazonaws.internal.ListWithAutoConstructFlag<String>(networkInterfaceIds.size()); networkInterfaceIdsCopy.addAll(networkInterfaceIds); this.networkInterfaceIds = networkInterfaceIdsCopy; } /** * One or more network interface IDs. <p>Default: Describes all your * network interfaces. * <p> * <b>NOTE:</b> This method appends the values to the existing list (if * any). Use {@link #setNetworkInterfaceIds(java.util.Collection)} or * {@link #withNetworkInterfaceIds(java.util.Collection)} if you want to * override the existing values. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param networkInterfaceIds One or more network interface IDs. <p>Default: Describes all your * network interfaces. * * @return A reference to this updated object so that method calls can be chained * together. */ public DescribeNetworkInterfacesRequest withNetworkInterfaceIds(String... networkInterfaceIds) { if (getNetworkInterfaceIds() == null) setNetworkInterfaceIds(new java.util.ArrayList<String>(networkInterfaceIds.length)); for (String value : networkInterfaceIds) { getNetworkInterfaceIds().add(value); } return this; } /** * One or more network interface IDs. <p>Default: Describes all your * network interfaces. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param networkInterfaceIds One or more network interface IDs. <p>Default: Describes all your * network interfaces. * * @return A reference to this updated object so that method calls can be chained * together. */ public DescribeNetworkInterfacesRequest withNetworkInterfaceIds(java.util.Collection<String> networkInterfaceIds) { if (networkInterfaceIds == null) { this.networkInterfaceIds = null; } else { com.amazonaws.internal.ListWithAutoConstructFlag<String> networkInterfaceIdsCopy = new com.amazonaws.internal.ListWithAutoConstructFlag<String>(networkInterfaceIds.size()); networkInterfaceIdsCopy.addAll(networkInterfaceIds); this.networkInterfaceIds = networkInterfaceIdsCopy; } return this; } /** * One or more filters. <ul> <li> * <p><code>addresses.private-ip-address</code> - The private IP * addresses associated with the network interface. </li> <li> * <p><code>addresses.primary</code> - Whether the private IP address is * the primary IP address associated with the network interface. </li> * <li> <p><code>addresses.association.public-ip</code> - The association * ID returned when the network interface was associated with the Elastic * IP address. </li> <li> <p><code>addresses.association.owner-id</code> * - The owner ID of the addresses associated with the network interface. * </li> <li> <p><code>association.association-id</code> - The * association ID returned when the network interface was associated with * an IP address. </li> <li> <p><code>association.allocation-id</code> - * The allocation ID returned when you allocated the Elastic IP address * for your network interface. </li> <li> * <p><code>association.ip-owner-id</code> - The owner of the Elastic IP * address associated with the network interface. </li> <li> * <p><code>association.public-ip</code> - The address of the Elastic IP * address bound to the network interface. </li> <li> * <p><code>association.public-dns-name</code> - The public DNS name for * the network interface. </li> <li> * <p><code>attachment.attachment-id</code> - The ID of the interface * attachment. </li> <li> <p><code>attachment.attach.time</code> - The * time that the network interface was attached to an instance. </li> * <li> <p><code>attachment.delete-on-termination</code> - Indicates * whether the attachment is deleted when an instance is terminated. * </li> <li> <p><code>attachment.device-index</code> - The device index * to which the network interface is attached. </li> <li> * <p><code>attachment.instance-id</code> - The ID of the instance to * which the network interface is attached. </li> <li> * <p><code>attachment.instance-owner-id</code> - The owner ID of the * instance to which the network interface is attached. </li> <li> * <p><code>attachment.nat-gateway-id</code> - The ID of the NAT gateway * to which the network interface is attached. </li> <li> * <p><code>attachment.status</code> - The status of the attachment * (<code>attaching</code> | <code>attached</code> | * <code>detaching</code> | <code>detached</code>). </li> <li> * <p><code>availability-zone</code> - The Availability Zone of the * network interface. </li> <li> <p><code>description</code> - The * description of the network interface. </li> <li> * <p><code>group-id</code> - The ID of a security group associated with * the network interface. </li> <li> <p><code>group-name</code> - The * name of a security group associated with the network interface. </li> * <li> <p><code>mac-address</code> - The MAC address of the network * interface. </li> <li> <p><code>network-interface-id</code> - The ID of * the network interface. </li> <li> <p><code>owner-id</code> - The AWS * account ID of the network interface owner. </li> <li> * <p><code>private-ip-address</code> - The private IP address or * addresses of the network interface. </li> <li> * <p><code>private-dns-name</code> - The private DNS name of the network * interface. </li> <li> <p><code>requester-id</code> - The ID of the * entity that launched the instance on your behalf (for example, AWS * Management Console, Auto Scaling, and so on). </li> <li> * <p><code>requester-managed</code> - Indicates whether the network * interface is being managed by an AWS service (for example, AWS * Management Console, Auto Scaling, and so on). </li> <li> * <p><code>source-desk-check</code> - Indicates whether the network * interface performs source/destination checking. A value of * <code>true</code> means checking is enabled, and <code>false</code> * means checking is disabled. The value must be <code>false</code> for * the network interface to perform network address translation (NAT) in * your VPC. </li> <li> <p><code>status</code> - The status of the * network interface. If the network interface is not attached to an * instance, the status is <code>available</code>; if a network interface * is attached to an instance the status is <code>in-use</code>. </li> * <li> <p><code>subnet-id</code> - The ID of the subnet for the network * interface. </li> <li> <p><code>tag</code>:<i>key</i>=<i>value</i> - * The key/value combination of a tag assigned to the resource. </li> * <li> <p><code>tag-key</code> - The key of a tag assigned to the * resource. This filter is independent of the <code>tag-value</code> * filter. For example, if you use both the filter "tag-key=Purpose" and * the filter "tag-value=X", you get any resources assigned both the tag * key Purpose (regardless of what the tag's value is), and the tag value * X (regardless of what the tag's key is). If you want to list only * resources where Purpose is X, see the * <code>tag</code>:<i>key</i>=<i>value</i> filter. </li> <li> * <p><code>tag-value</code> - The value of a tag assigned to the * resource. This filter is independent of the <code>tag-key</code> * filter. </li> <li> <p><code>vpc-id</code> - The ID of the VPC for the * network interface. </li> </ul> * * @return One or more filters. <ul> <li> * <p><code>addresses.private-ip-address</code> - The private IP * addresses associated with the network interface. </li> <li> * <p><code>addresses.primary</code> - Whether the private IP address is * the primary IP address associated with the network interface. </li> * <li> <p><code>addresses.association.public-ip</code> - The association * ID returned when the network interface was associated with the Elastic * IP address. </li> <li> <p><code>addresses.association.owner-id</code> * - The owner ID of the addresses associated with the network interface. * </li> <li> <p><code>association.association-id</code> - The * association ID returned when the network interface was associated with * an IP address. </li> <li> <p><code>association.allocation-id</code> - * The allocation ID returned when you allocated the Elastic IP address * for your network interface. </li> <li> * <p><code>association.ip-owner-id</code> - The owner of the Elastic IP * address associated with the network interface. </li> <li> * <p><code>association.public-ip</code> - The address of the Elastic IP * address bound to the network interface. </li> <li> * <p><code>association.public-dns-name</code> - The public DNS name for * the network interface. </li> <li> * <p><code>attachment.attachment-id</code> - The ID of the interface * attachment. </li> <li> <p><code>attachment.attach.time</code> - The * time that the network interface was attached to an instance. </li> * <li> <p><code>attachment.delete-on-termination</code> - Indicates * whether the attachment is deleted when an instance is terminated. * </li> <li> <p><code>attachment.device-index</code> - The device index * to which the network interface is attached. </li> <li> * <p><code>attachment.instance-id</code> - The ID of the instance to * which the network interface is attached. </li> <li> * <p><code>attachment.instance-owner-id</code> - The owner ID of the * instance to which the network interface is attached. </li> <li> * <p><code>attachment.nat-gateway-id</code> - The ID of the NAT gateway * to which the network interface is attached. </li> <li> * <p><code>attachment.status</code> - The status of the attachment * (<code>attaching</code> | <code>attached</code> | * <code>detaching</code> | <code>detached</code>). </li> <li> * <p><code>availability-zone</code> - The Availability Zone of the * network interface. </li> <li> <p><code>description</code> - The * description of the network interface. </li> <li> * <p><code>group-id</code> - The ID of a security group associated with * the network interface. </li> <li> <p><code>group-name</code> - The * name of a security group associated with the network interface. </li> * <li> <p><code>mac-address</code> - The MAC address of the network * interface. </li> <li> <p><code>network-interface-id</code> - The ID of * the network interface. </li> <li> <p><code>owner-id</code> - The AWS * account ID of the network interface owner. </li> <li> * <p><code>private-ip-address</code> - The private IP address or * addresses of the network interface. </li> <li> * <p><code>private-dns-name</code> - The private DNS name of the network * interface. </li> <li> <p><code>requester-id</code> - The ID of the * entity that launched the instance on your behalf (for example, AWS * Management Console, Auto Scaling, and so on). </li> <li> * <p><code>requester-managed</code> - Indicates whether the network * interface is being managed by an AWS service (for example, AWS * Management Console, Auto Scaling, and so on). </li> <li> * <p><code>source-desk-check</code> - Indicates whether the network * interface performs source/destination checking. A value of * <code>true</code> means checking is enabled, and <code>false</code> * means checking is disabled. The value must be <code>false</code> for * the network interface to perform network address translation (NAT) in * your VPC. </li> <li> <p><code>status</code> - The status of the * network interface. If the network interface is not attached to an * instance, the status is <code>available</code>; if a network interface * is attached to an instance the status is <code>in-use</code>. </li> * <li> <p><code>subnet-id</code> - The ID of the subnet for the network * interface. </li> <li> <p><code>tag</code>:<i>key</i>=<i>value</i> - * The key/value combination of a tag assigned to the resource. </li> * <li> <p><code>tag-key</code> - The key of a tag assigned to the * resource. This filter is independent of the <code>tag-value</code> * filter. For example, if you use both the filter "tag-key=Purpose" and * the filter "tag-value=X", you get any resources assigned both the tag * key Purpose (regardless of what the tag's value is), and the tag value * X (regardless of what the tag's key is). If you want to list only * resources where Purpose is X, see the * <code>tag</code>:<i>key</i>=<i>value</i> filter. </li> <li> * <p><code>tag-value</code> - The value of a tag assigned to the * resource. This filter is independent of the <code>tag-key</code> * filter. </li> <li> <p><code>vpc-id</code> - The ID of the VPC for the * network interface. </li> </ul> */ public java.util.List<Filter> getFilters() { if (filters == null) { filters = new com.amazonaws.internal.ListWithAutoConstructFlag<Filter>(); filters.setAutoConstruct(true); } return filters; } /** * One or more filters. <ul> <li> * <p><code>addresses.private-ip-address</code> - The private IP * addresses associated with the network interface. </li> <li> * <p><code>addresses.primary</code> - Whether the private IP address is * the primary IP address associated with the network interface. </li> * <li> <p><code>addresses.association.public-ip</code> - The association * ID returned when the network interface was associated with the Elastic * IP address. </li> <li> <p><code>addresses.association.owner-id</code> * - The owner ID of the addresses associated with the network interface. * </li> <li> <p><code>association.association-id</code> - The * association ID returned when the network interface was associated with * an IP address. </li> <li> <p><code>association.allocation-id</code> - * The allocation ID returned when you allocated the Elastic IP address * for your network interface. </li> <li> * <p><code>association.ip-owner-id</code> - The owner of the Elastic IP * address associated with the network interface. </li> <li> * <p><code>association.public-ip</code> - The address of the Elastic IP * address bound to the network interface. </li> <li> * <p><code>association.public-dns-name</code> - The public DNS name for * the network interface. </li> <li> * <p><code>attachment.attachment-id</code> - The ID of the interface * attachment. </li> <li> <p><code>attachment.attach.time</code> - The * time that the network interface was attached to an instance. </li> * <li> <p><code>attachment.delete-on-termination</code> - Indicates * whether the attachment is deleted when an instance is terminated. * </li> <li> <p><code>attachment.device-index</code> - The device index * to which the network interface is attached. </li> <li> * <p><code>attachment.instance-id</code> - The ID of the instance to * which the network interface is attached. </li> <li> * <p><code>attachment.instance-owner-id</code> - The owner ID of the * instance to which the network interface is attached. </li> <li> * <p><code>attachment.nat-gateway-id</code> - The ID of the NAT gateway * to which the network interface is attached. </li> <li> * <p><code>attachment.status</code> - The status of the attachment * (<code>attaching</code> | <code>attached</code> | * <code>detaching</code> | <code>detached</code>). </li> <li> * <p><code>availability-zone</code> - The Availability Zone of the * network interface. </li> <li> <p><code>description</code> - The * description of the network interface. </li> <li> * <p><code>group-id</code> - The ID of a security group associated with * the network interface. </li> <li> <p><code>group-name</code> - The * name of a security group associated with the network interface. </li> * <li> <p><code>mac-address</code> - The MAC address of the network * interface. </li> <li> <p><code>network-interface-id</code> - The ID of * the network interface. </li> <li> <p><code>owner-id</code> - The AWS * account ID of the network interface owner. </li> <li> * <p><code>private-ip-address</code> - The private IP address or * addresses of the network interface. </li> <li> * <p><code>private-dns-name</code> - The private DNS name of the network * interface. </li> <li> <p><code>requester-id</code> - The ID of the * entity that launched the instance on your behalf (for example, AWS * Management Console, Auto Scaling, and so on). </li> <li> * <p><code>requester-managed</code> - Indicates whether the network * interface is being managed by an AWS service (for example, AWS * Management Console, Auto Scaling, and so on). </li> <li> * <p><code>source-desk-check</code> - Indicates whether the network * interface performs source/destination checking. A value of * <code>true</code> means checking is enabled, and <code>false</code> * means checking is disabled. The value must be <code>false</code> for * the network interface to perform network address translation (NAT) in * your VPC. </li> <li> <p><code>status</code> - The status of the * network interface. If the network interface is not attached to an * instance, the status is <code>available</code>; if a network interface * is attached to an instance the status is <code>in-use</code>. </li> * <li> <p><code>subnet-id</code> - The ID of the subnet for the network * interface. </li> <li> <p><code>tag</code>:<i>key</i>=<i>value</i> - * The key/value combination of a tag assigned to the resource. </li> * <li> <p><code>tag-key</code> - The key of a tag assigned to the * resource. This filter is independent of the <code>tag-value</code> * filter. For example, if you use both the filter "tag-key=Purpose" and * the filter "tag-value=X", you get any resources assigned both the tag * key Purpose (regardless of what the tag's value is), and the tag value * X (regardless of what the tag's key is). If you want to list only * resources where Purpose is X, see the * <code>tag</code>:<i>key</i>=<i>value</i> filter. </li> <li> * <p><code>tag-value</code> - The value of a tag assigned to the * resource. This filter is independent of the <code>tag-key</code> * filter. </li> <li> <p><code>vpc-id</code> - The ID of the VPC for the * network interface. </li> </ul> * * @param filters One or more filters. <ul> <li> * <p><code>addresses.private-ip-address</code> - The private IP * addresses associated with the network interface. </li> <li> * <p><code>addresses.primary</code> - Whether the private IP address is * the primary IP address associated with the network interface. </li> * <li> <p><code>addresses.association.public-ip</code> - The association * ID returned when the network interface was associated with the Elastic * IP address. </li> <li> <p><code>addresses.association.owner-id</code> * - The owner ID of the addresses associated with the network interface. * </li> <li> <p><code>association.association-id</code> - The * association ID returned when the network interface was associated with * an IP address. </li> <li> <p><code>association.allocation-id</code> - * The allocation ID returned when you allocated the Elastic IP address * for your network interface. </li> <li> * <p><code>association.ip-owner-id</code> - The owner of the Elastic IP * address associated with the network interface. </li> <li> * <p><code>association.public-ip</code> - The address of the Elastic IP * address bound to the network interface. </li> <li> * <p><code>association.public-dns-name</code> - The public DNS name for * the network interface. </li> <li> * <p><code>attachment.attachment-id</code> - The ID of the interface * attachment. </li> <li> <p><code>attachment.attach.time</code> - The * time that the network interface was attached to an instance. </li> * <li> <p><code>attachment.delete-on-termination</code> - Indicates * whether the attachment is deleted when an instance is terminated. * </li> <li> <p><code>attachment.device-index</code> - The device index * to which the network interface is attached. </li> <li> * <p><code>attachment.instance-id</code> - The ID of the instance to * which the network interface is attached. </li> <li> * <p><code>attachment.instance-owner-id</code> - The owner ID of the * instance to which the network interface is attached. </li> <li> * <p><code>attachment.nat-gateway-id</code> - The ID of the NAT gateway * to which the network interface is attached. </li> <li> * <p><code>attachment.status</code> - The status of the attachment * (<code>attaching</code> | <code>attached</code> | * <code>detaching</code> | <code>detached</code>). </li> <li> * <p><code>availability-zone</code> - The Availability Zone of the * network interface. </li> <li> <p><code>description</code> - The * description of the network interface. </li> <li> * <p><code>group-id</code> - The ID of a security group associated with * the network interface. </li> <li> <p><code>group-name</code> - The * name of a security group associated with the network interface. </li> * <li> <p><code>mac-address</code> - The MAC address of the network * interface. </li> <li> <p><code>network-interface-id</code> - The ID of * the network interface. </li> <li> <p><code>owner-id</code> - The AWS * account ID of the network interface owner. </li> <li> * <p><code>private-ip-address</code> - The private IP address or * addresses of the network interface. </li> <li> * <p><code>private-dns-name</code> - The private DNS name of the network * interface. </li> <li> <p><code>requester-id</code> - The ID of the * entity that launched the instance on your behalf (for example, AWS * Management Console, Auto Scaling, and so on). </li> <li> * <p><code>requester-managed</code> - Indicates whether the network * interface is being managed by an AWS service (for example, AWS * Management Console, Auto Scaling, and so on). </li> <li> * <p><code>source-desk-check</code> - Indicates whether the network * interface performs source/destination checking. A value of * <code>true</code> means checking is enabled, and <code>false</code> * means checking is disabled. The value must be <code>false</code> for * the network interface to perform network address translation (NAT) in * your VPC. </li> <li> <p><code>status</code> - The status of the * network interface. If the network interface is not attached to an * instance, the status is <code>available</code>; if a network interface * is attached to an instance the status is <code>in-use</code>. </li> * <li> <p><code>subnet-id</code> - The ID of the subnet for the network * interface. </li> <li> <p><code>tag</code>:<i>key</i>=<i>value</i> - * The key/value combination of a tag assigned to the resource. </li> * <li> <p><code>tag-key</code> - The key of a tag assigned to the * resource. This filter is independent of the <code>tag-value</code> * filter. For example, if you use both the filter "tag-key=Purpose" and * the filter "tag-value=X", you get any resources assigned both the tag * key Purpose (regardless of what the tag's value is), and the tag value * X (regardless of what the tag's key is). If you want to list only * resources where Purpose is X, see the * <code>tag</code>:<i>key</i>=<i>value</i> filter. </li> <li> * <p><code>tag-value</code> - The value of a tag assigned to the * resource. This filter is independent of the <code>tag-key</code> * filter. </li> <li> <p><code>vpc-id</code> - The ID of the VPC for the * network interface. </li> </ul> */ public void setFilters(java.util.Collection<Filter> filters) { if (filters == null) { this.filters = null; return; } com.amazonaws.internal.ListWithAutoConstructFlag<Filter> filtersCopy = new com.amazonaws.internal.ListWithAutoConstructFlag<Filter>(filters.size()); filtersCopy.addAll(filters); this.filters = filtersCopy; } /** * One or more filters. <ul> <li> * <p><code>addresses.private-ip-address</code> - The private IP * addresses associated with the network interface. </li> <li> * <p><code>addresses.primary</code> - Whether the private IP address is * the primary IP address associated with the network interface. </li> * <li> <p><code>addresses.association.public-ip</code> - The association * ID returned when the network interface was associated with the Elastic * IP address. </li> <li> <p><code>addresses.association.owner-id</code> * - The owner ID of the addresses associated with the network interface. * </li> <li> <p><code>association.association-id</code> - The * association ID returned when the network interface was associated with * an IP address. </li> <li> <p><code>association.allocation-id</code> - * The allocation ID returned when you allocated the Elastic IP address * for your network interface. </li> <li> * <p><code>association.ip-owner-id</code> - The owner of the Elastic IP * address associated with the network interface. </li> <li> * <p><code>association.public-ip</code> - The address of the Elastic IP * address bound to the network interface. </li> <li> * <p><code>association.public-dns-name</code> - The public DNS name for * the network interface. </li> <li> * <p><code>attachment.attachment-id</code> - The ID of the interface * attachment. </li> <li> <p><code>attachment.attach.time</code> - The * time that the network interface was attached to an instance. </li> * <li> <p><code>attachment.delete-on-termination</code> - Indicates * whether the attachment is deleted when an instance is terminated. * </li> <li> <p><code>attachment.device-index</code> - The device index * to which the network interface is attached. </li> <li> * <p><code>attachment.instance-id</code> - The ID of the instance to * which the network interface is attached. </li> <li> * <p><code>attachment.instance-owner-id</code> - The owner ID of the * instance to which the network interface is attached. </li> <li> * <p><code>attachment.nat-gateway-id</code> - The ID of the NAT gateway * to which the network interface is attached. </li> <li> * <p><code>attachment.status</code> - The status of the attachment * (<code>attaching</code> | <code>attached</code> | * <code>detaching</code> | <code>detached</code>). </li> <li> * <p><code>availability-zone</code> - The Availability Zone of the * network interface. </li> <li> <p><code>description</code> - The * description of the network interface. </li> <li> * <p><code>group-id</code> - The ID of a security group associated with * the network interface. </li> <li> <p><code>group-name</code> - The * name of a security group associated with the network interface. </li> * <li> <p><code>mac-address</code> - The MAC address of the network * interface. </li> <li> <p><code>network-interface-id</code> - The ID of * the network interface. </li> <li> <p><code>owner-id</code> - The AWS * account ID of the network interface owner. </li> <li> * <p><code>private-ip-address</code> - The private IP address or * addresses of the network interface. </li> <li> * <p><code>private-dns-name</code> - The private DNS name of the network * interface. </li> <li> <p><code>requester-id</code> - The ID of the * entity that launched the instance on your behalf (for example, AWS * Management Console, Auto Scaling, and so on). </li> <li> * <p><code>requester-managed</code> - Indicates whether the network * interface is being managed by an AWS service (for example, AWS * Management Console, Auto Scaling, and so on). </li> <li> * <p><code>source-desk-check</code> - Indicates whether the network * interface performs source/destination checking. A value of * <code>true</code> means checking is enabled, and <code>false</code> * means checking is disabled. The value must be <code>false</code> for * the network interface to perform network address translation (NAT) in * your VPC. </li> <li> <p><code>status</code> - The status of the * network interface. If the network interface is not attached to an * instance, the status is <code>available</code>; if a network interface * is attached to an instance the status is <code>in-use</code>. </li> * <li> <p><code>subnet-id</code> - The ID of the subnet for the network * interface. </li> <li> <p><code>tag</code>:<i>key</i>=<i>value</i> - * The key/value combination of a tag assigned to the resource. </li> * <li> <p><code>tag-key</code> - The key of a tag assigned to the * resource. This filter is independent of the <code>tag-value</code> * filter. For example, if you use both the filter "tag-key=Purpose" and * the filter "tag-value=X", you get any resources assigned both the tag * key Purpose (regardless of what the tag's value is), and the tag value * X (regardless of what the tag's key is). If you want to list only * resources where Purpose is X, see the * <code>tag</code>:<i>key</i>=<i>value</i> filter. </li> <li> * <p><code>tag-value</code> - The value of a tag assigned to the * resource. This filter is independent of the <code>tag-key</code> * filter. </li> <li> <p><code>vpc-id</code> - The ID of the VPC for the * network interface. </li> </ul> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if * any). Use {@link #setFilters(java.util.Collection)} or {@link * #withFilters(java.util.Collection)} if you want to override the * existing values. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param filters One or more filters. <ul> <li> * <p><code>addresses.private-ip-address</code> - The private IP * addresses associated with the network interface. </li> <li> * <p><code>addresses.primary</code> - Whether the private IP address is * the primary IP address associated with the network interface. </li> * <li> <p><code>addresses.association.public-ip</code> - The association * ID returned when the network interface was associated with the Elastic * IP address. </li> <li> <p><code>addresses.association.owner-id</code> * - The owner ID of the addresses associated with the network interface. * </li> <li> <p><code>association.association-id</code> - The * association ID returned when the network interface was associated with * an IP address. </li> <li> <p><code>association.allocation-id</code> - * The allocation ID returned when you allocated the Elastic IP address * for your network interface. </li> <li> * <p><code>association.ip-owner-id</code> - The owner of the Elastic IP * address associated with the network interface. </li> <li> * <p><code>association.public-ip</code> - The address of the Elastic IP * address bound to the network interface. </li> <li> * <p><code>association.public-dns-name</code> - The public DNS name for * the network interface. </li> <li> * <p><code>attachment.attachment-id</code> - The ID of the interface * attachment. </li> <li> <p><code>attachment.attach.time</code> - The * time that the network interface was attached to an instance. </li> * <li> <p><code>attachment.delete-on-termination</code> - Indicates * whether the attachment is deleted when an instance is terminated. * </li> <li> <p><code>attachment.device-index</code> - The device index * to which the network interface is attached. </li> <li> * <p><code>attachment.instance-id</code> - The ID of the instance to * which the network interface is attached. </li> <li> * <p><code>attachment.instance-owner-id</code> - The owner ID of the * instance to which the network interface is attached. </li> <li> * <p><code>attachment.nat-gateway-id</code> - The ID of the NAT gateway * to which the network interface is attached. </li> <li> * <p><code>attachment.status</code> - The status of the attachment * (<code>attaching</code> | <code>attached</code> | * <code>detaching</code> | <code>detached</code>). </li> <li> * <p><code>availability-zone</code> - The Availability Zone of the * network interface. </li> <li> <p><code>description</code> - The * description of the network interface. </li> <li> * <p><code>group-id</code> - The ID of a security group associated with * the network interface. </li> <li> <p><code>group-name</code> - The * name of a security group associated with the network interface. </li> * <li> <p><code>mac-address</code> - The MAC address of the network * interface. </li> <li> <p><code>network-interface-id</code> - The ID of * the network interface. </li> <li> <p><code>owner-id</code> - The AWS * account ID of the network interface owner. </li> <li> * <p><code>private-ip-address</code> - The private IP address or * addresses of the network interface. </li> <li> * <p><code>private-dns-name</code> - The private DNS name of the network * interface. </li> <li> <p><code>requester-id</code> - The ID of the * entity that launched the instance on your behalf (for example, AWS * Management Console, Auto Scaling, and so on). </li> <li> * <p><code>requester-managed</code> - Indicates whether the network * interface is being managed by an AWS service (for example, AWS * Management Console, Auto Scaling, and so on). </li> <li> * <p><code>source-desk-check</code> - Indicates whether the network * interface performs source/destination checking. A value of * <code>true</code> means checking is enabled, and <code>false</code> * means checking is disabled. The value must be <code>false</code> for * the network interface to perform network address translation (NAT) in * your VPC. </li> <li> <p><code>status</code> - The status of the * network interface. If the network interface is not attached to an * instance, the status is <code>available</code>; if a network interface * is attached to an instance the status is <code>in-use</code>. </li> * <li> <p><code>subnet-id</code> - The ID of the subnet for the network * interface. </li> <li> <p><code>tag</code>:<i>key</i>=<i>value</i> - * The key/value combination of a tag assigned to the resource. </li> * <li> <p><code>tag-key</code> - The key of a tag assigned to the * resource. This filter is independent of the <code>tag-value</code> * filter. For example, if you use both the filter "tag-key=Purpose" and * the filter "tag-value=X", you get any resources assigned both the tag * key Purpose (regardless of what the tag's value is), and the tag value * X (regardless of what the tag's key is). If you want to list only * resources where Purpose is X, see the * <code>tag</code>:<i>key</i>=<i>value</i> filter. </li> <li> * <p><code>tag-value</code> - The value of a tag assigned to the * resource. This filter is independent of the <code>tag-key</code> * filter. </li> <li> <p><code>vpc-id</code> - The ID of the VPC for the * network interface. </li> </ul> * * @return A reference to this updated object so that method calls can be chained * together. */ public DescribeNetworkInterfacesRequest withFilters(Filter... filters) { if (getFilters() == null) setFilters(new java.util.ArrayList<Filter>(filters.length)); for (Filter value : filters) { getFilters().add(value); } return this; } /** * One or more filters. <ul> <li> * <p><code>addresses.private-ip-address</code> - The private IP * addresses associated with the network interface. </li> <li> * <p><code>addresses.primary</code> - Whether the private IP address is * the primary IP address associated with the network interface. </li> * <li> <p><code>addresses.association.public-ip</code> - The association * ID returned when the network interface was associated with the Elastic * IP address. </li> <li> <p><code>addresses.association.owner-id</code> * - The owner ID of the addresses associated with the network interface. * </li> <li> <p><code>association.association-id</code> - The * association ID returned when the network interface was associated with * an IP address. </li> <li> <p><code>association.allocation-id</code> - * The allocation ID returned when you allocated the Elastic IP address * for your network interface. </li> <li> * <p><code>association.ip-owner-id</code> - The owner of the Elastic IP * address associated with the network interface. </li> <li> * <p><code>association.public-ip</code> - The address of the Elastic IP * address bound to the network interface. </li> <li> * <p><code>association.public-dns-name</code> - The public DNS name for * the network interface. </li> <li> * <p><code>attachment.attachment-id</code> - The ID of the interface * attachment. </li> <li> <p><code>attachment.attach.time</code> - The * time that the network interface was attached to an instance. </li> * <li> <p><code>attachment.delete-on-termination</code> - Indicates * whether the attachment is deleted when an instance is terminated. * </li> <li> <p><code>attachment.device-index</code> - The device index * to which the network interface is attached. </li> <li> * <p><code>attachment.instance-id</code> - The ID of the instance to * which the network interface is attached. </li> <li> * <p><code>attachment.instance-owner-id</code> - The owner ID of the * instance to which the network interface is attached. </li> <li> * <p><code>attachment.nat-gateway-id</code> - The ID of the NAT gateway * to which the network interface is attached. </li> <li> * <p><code>attachment.status</code> - The status of the attachment * (<code>attaching</code> | <code>attached</code> | * <code>detaching</code> | <code>detached</code>). </li> <li> * <p><code>availability-zone</code> - The Availability Zone of the * network interface. </li> <li> <p><code>description</code> - The * description of the network interface. </li> <li> * <p><code>group-id</code> - The ID of a security group associated with * the network interface. </li> <li> <p><code>group-name</code> - The * name of a security group associated with the network interface. </li> * <li> <p><code>mac-address</code> - The MAC address of the network * interface. </li> <li> <p><code>network-interface-id</code> - The ID of * the network interface. </li> <li> <p><code>owner-id</code> - The AWS * account ID of the network interface owner. </li> <li> * <p><code>private-ip-address</code> - The private IP address or * addresses of the network interface. </li> <li> * <p><code>private-dns-name</code> - The private DNS name of the network * interface. </li> <li> <p><code>requester-id</code> - The ID of the * entity that launched the instance on your behalf (for example, AWS * Management Console, Auto Scaling, and so on). </li> <li> * <p><code>requester-managed</code> - Indicates whether the network * interface is being managed by an AWS service (for example, AWS * Management Console, Auto Scaling, and so on). </li> <li> * <p><code>source-desk-check</code> - Indicates whether the network * interface performs source/destination checking. A value of * <code>true</code> means checking is enabled, and <code>false</code> * means checking is disabled. The value must be <code>false</code> for * the network interface to perform network address translation (NAT) in * your VPC. </li> <li> <p><code>status</code> - The status of the * network interface. If the network interface is not attached to an * instance, the status is <code>available</code>; if a network interface * is attached to an instance the status is <code>in-use</code>. </li> * <li> <p><code>subnet-id</code> - The ID of the subnet for the network * interface. </li> <li> <p><code>tag</code>:<i>key</i>=<i>value</i> - * The key/value combination of a tag assigned to the resource. </li> * <li> <p><code>tag-key</code> - The key of a tag assigned to the * resource. This filter is independent of the <code>tag-value</code> * filter. For example, if you use both the filter "tag-key=Purpose" and * the filter "tag-value=X", you get any resources assigned both the tag * key Purpose (regardless of what the tag's value is), and the tag value * X (regardless of what the tag's key is). If you want to list only * resources where Purpose is X, see the * <code>tag</code>:<i>key</i>=<i>value</i> filter. </li> <li> * <p><code>tag-value</code> - The value of a tag assigned to the * resource. This filter is independent of the <code>tag-key</code> * filter. </li> <li> <p><code>vpc-id</code> - The ID of the VPC for the * network interface. </li> </ul> * <p> * Returns a reference to this object so that method calls can be chained together. * * @param filters One or more filters. <ul> <li> * <p><code>addresses.private-ip-address</code> - The private IP * addresses associated with the network interface. </li> <li> * <p><code>addresses.primary</code> - Whether the private IP address is * the primary IP address associated with the network interface. </li> * <li> <p><code>addresses.association.public-ip</code> - The association * ID returned when the network interface was associated with the Elastic * IP address. </li> <li> <p><code>addresses.association.owner-id</code> * - The owner ID of the addresses associated with the network interface. * </li> <li> <p><code>association.association-id</code> - The * association ID returned when the network interface was associated with * an IP address. </li> <li> <p><code>association.allocation-id</code> - * The allocation ID returned when you allocated the Elastic IP address * for your network interface. </li> <li> * <p><code>association.ip-owner-id</code> - The owner of the Elastic IP * address associated with the network interface. </li> <li> * <p><code>association.public-ip</code> - The address of the Elastic IP * address bound to the network interface. </li> <li> * <p><code>association.public-dns-name</code> - The public DNS name for * the network interface. </li> <li> * <p><code>attachment.attachment-id</code> - The ID of the interface * attachment. </li> <li> <p><code>attachment.attach.time</code> - The * time that the network interface was attached to an instance. </li> * <li> <p><code>attachment.delete-on-termination</code> - Indicates * whether the attachment is deleted when an instance is terminated. * </li> <li> <p><code>attachment.device-index</code> - The device index * to which the network interface is attached. </li> <li> * <p><code>attachment.instance-id</code> - The ID of the instance to * which the network interface is attached. </li> <li> * <p><code>attachment.instance-owner-id</code> - The owner ID of the * instance to which the network interface is attached. </li> <li> * <p><code>attachment.nat-gateway-id</code> - The ID of the NAT gateway * to which the network interface is attached. </li> <li> * <p><code>attachment.status</code> - The status of the attachment * (<code>attaching</code> | <code>attached</code> | * <code>detaching</code> | <code>detached</code>). </li> <li> * <p><code>availability-zone</code> - The Availability Zone of the * network interface. </li> <li> <p><code>description</code> - The * description of the network interface. </li> <li> * <p><code>group-id</code> - The ID of a security group associated with * the network interface. </li> <li> <p><code>group-name</code> - The * name of a security group associated with the network interface. </li> * <li> <p><code>mac-address</code> - The MAC address of the network * interface. </li> <li> <p><code>network-interface-id</code> - The ID of * the network interface. </li> <li> <p><code>owner-id</code> - The AWS * account ID of the network interface owner. </li> <li> * <p><code>private-ip-address</code> - The private IP address or * addresses of the network interface. </li> <li> * <p><code>private-dns-name</code> - The private DNS name of the network * interface. </li> <li> <p><code>requester-id</code> - The ID of the * entity that launched the instance on your behalf (for example, AWS * Management Console, Auto Scaling, and so on). </li> <li> * <p><code>requester-managed</code> - Indicates whether the network * interface is being managed by an AWS service (for example, AWS * Management Console, Auto Scaling, and so on). </li> <li> * <p><code>source-desk-check</code> - Indicates whether the network * interface performs source/destination checking. A value of * <code>true</code> means checking is enabled, and <code>false</code> * means checking is disabled. The value must be <code>false</code> for * the network interface to perform network address translation (NAT) in * your VPC. </li> <li> <p><code>status</code> - The status of the * network interface. If the network interface is not attached to an * instance, the status is <code>available</code>; if a network interface * is attached to an instance the status is <code>in-use</code>. </li> * <li> <p><code>subnet-id</code> - The ID of the subnet for the network * interface. </li> <li> <p><code>tag</code>:<i>key</i>=<i>value</i> - * The key/value combination of a tag assigned to the resource. </li> * <li> <p><code>tag-key</code> - The key of a tag assigned to the * resource. This filter is independent of the <code>tag-value</code> * filter. For example, if you use both the filter "tag-key=Purpose" and * the filter "tag-value=X", you get any resources assigned both the tag * key Purpose (regardless of what the tag's value is), and the tag value * X (regardless of what the tag's key is). If you want to list only * resources where Purpose is X, see the * <code>tag</code>:<i>key</i>=<i>value</i> filter. </li> <li> * <p><code>tag-value</code> - The value of a tag assigned to the * resource. This filter is independent of the <code>tag-key</code> * filter. </li> <li> <p><code>vpc-id</code> - The ID of the VPC for the * network interface. </li> </ul> * * @return A reference to this updated object so that method calls can be chained * together. */ public DescribeNetworkInterfacesRequest withFilters(java.util.Collection<Filter> filters) { if (filters == null) { this.filters = null; } else { com.amazonaws.internal.ListWithAutoConstructFlag<Filter> filtersCopy = new com.amazonaws.internal.ListWithAutoConstructFlag<Filter>(filters.size()); filtersCopy.addAll(filters); this.filters = filtersCopy; } return this; } /** * This method is intended for internal use only. * Returns the marshaled request configured with additional parameters to * enable operation dry-run. */ @Override public Request<DescribeNetworkInterfacesRequest> getDryRunRequest() { Request<DescribeNetworkInterfacesRequest> request = new DescribeNetworkInterfacesRequestMarshaller().marshall(this); request.addParameter("DryRun", Boolean.toString(true)); return request; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getNetworkInterfaceIds() != null) sb.append("NetworkInterfaceIds: " + getNetworkInterfaceIds() + ","); if (getFilters() != null) sb.append("Filters: " + getFilters() ); sb.append("}"); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getNetworkInterfaceIds() == null) ? 0 : getNetworkInterfaceIds().hashCode()); hashCode = prime * hashCode + ((getFilters() == null) ? 0 : getFilters().hashCode()); return hashCode; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DescribeNetworkInterfacesRequest == false) return false; DescribeNetworkInterfacesRequest other = (DescribeNetworkInterfacesRequest)obj; if (other.getNetworkInterfaceIds() == null ^ this.getNetworkInterfaceIds() == null) return false; if (other.getNetworkInterfaceIds() != null && other.getNetworkInterfaceIds().equals(this.getNetworkInterfaceIds()) == false) return false; if (other.getFilters() == null ^ this.getFilters() == null) return false; if (other.getFilters() != null && other.getFilters().equals(this.getFilters()) == false) return false; return true; } @Override public DescribeNetworkInterfacesRequest clone() { return (DescribeNetworkInterfacesRequest) super.clone(); } }
apache-2.0
yqritc/glide-transformations
transformations/src/main/java/jp/wasabeef/glide/transformations/RoundedCornersTransformation.java
2495
package jp.wasabeef.glide.transformations; /** * Copyright (C) 2015 Wasabeef * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 com.bumptech.glide.load.Transformation; import com.bumptech.glide.load.engine.Resource; import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool; import com.bumptech.glide.load.resource.bitmap.BitmapResource; import android.graphics.Bitmap; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.Shader; public class RoundedCornersTransformation implements Transformation<Bitmap> { private BitmapPool mBitmapPool; private int radius; private int margin; public RoundedCornersTransformation(BitmapPool pool, int radius, int margin) { this.radius = radius; this.margin = margin; mBitmapPool = pool; } @Override public Resource<Bitmap> transform(Resource<Bitmap> resource, int outWidth, int outHeight) { Bitmap source = resource.get(); int width = source.getWidth(); int height = source.getHeight(); Bitmap.Config config = source.getConfig() != null ? source.getConfig() : Bitmap.Config.ARGB_8888; Bitmap bitmap = mBitmapPool.get(width, height, config); if (bitmap == null) { bitmap = Bitmap.createBitmap(width, height, config); } Canvas canvas = new Canvas(bitmap); Paint paint = new Paint(); paint.setAntiAlias(true); paint.setShader(new BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)); canvas.drawRoundRect(new RectF(margin, margin, width - margin, height - margin), radius, radius, paint); source.recycle(); return BitmapResource.obtain(bitmap, mBitmapPool); } @Override public String getId() { return "RoundedTransformation(radius=" + radius + ", margin=" + margin + ")"; } }
apache-2.0
ecallac/sistemas
applications/rentcar-web/src/main/java/com/ecallac/rentcar/service/RolServiceImpl.java
649
/** * */ package com.ecallac.rentcar.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ecallac.rentcar.domain.Rol; import com.ecallac.rentcar.repository.RolRepository; /** * @author efrain.calla * */ @Service public class RolServiceImpl implements RolService{ @Autowired RolRepository rolRepository; @Override public List<Rol> findAll() { return rolRepository.findAll(); } @Override public List<Rol> findAllByStatus(String status) { // TODO Auto-generated method stub return rolRepository.findAllByStatus(status); } }
apache-2.0
ByteInternet/libcloud
libcloud/common/openstack_identity.py
61346
# 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. """ Common / shared code for handling authentication against OpenStack identity service (Keystone). """ import datetime from libcloud.utils.py3 import httplib from libcloud.utils.iso8601 import parse_date from libcloud.common.base import (ConnectionUserAndKey, Response, CertificateConnection) from libcloud.compute.types import (LibcloudError, InvalidCredsError, MalformedResponseError) try: import simplejson as json except ImportError: import json AUTH_API_VERSION = '1.1' # Auth versions which contain token expiration information. AUTH_VERSIONS_WITH_EXPIRES = [ '1.1', '2.0', '2.0_apikey', '2.0_password', '2.0_voms', '3.0', '3.x_password', '3.x_oidc_access_token' ] # How many seconds to subtract from the auth token expiration time before # testing if the token is still valid. # The time is subtracted to account for the HTTP request latency and prevent # user from getting "InvalidCredsError" if token is about to expire. AUTH_TOKEN_EXPIRES_GRACE_SECONDS = 5 __all__ = [ 'OpenStackIdentityVersion', 'OpenStackIdentityDomain', 'OpenStackIdentityProject', 'OpenStackIdentityUser', 'OpenStackIdentityRole', 'OpenStackServiceCatalog', 'OpenStackServiceCatalogEntry', 'OpenStackServiceCatalogEntryEndpoint', 'OpenStackIdentityEndpointType', 'OpenStackIdentityConnection', 'OpenStackIdentity_1_0_Connection', 'OpenStackIdentity_1_1_Connection', 'OpenStackIdentity_2_0_Connection', 'OpenStackIdentity_2_0_Connection_VOMS', 'OpenStackIdentity_3_0_Connection', 'OpenStackIdentity_3_0_Connection_OIDC_access_token', 'get_class_for_auth_version' ] class OpenStackIdentityEndpointType(object): """ Enum class for openstack identity endpoint type. """ INTERNAL = 'internal' EXTERNAL = 'external' ADMIN = 'admin' class OpenStackIdentityTokenScope(object): """ Enum class for openstack identity token scope. """ PROJECT = 'project' DOMAIN = 'domain' UNSCOPED = 'unscoped' class OpenStackIdentityVersion(object): def __init__(self, version, status, updated, url): self.version = version self.status = status self.updated = updated self.url = url def __repr__(self): return (('<OpenStackIdentityVersion version=%s, status=%s, ' 'updated=%s, url=%s>' % (self.version, self.status, self.updated, self.url))) class OpenStackIdentityDomain(object): def __init__(self, id, name, enabled): self.id = id self.name = name self.enabled = enabled def __repr__(self): return (('<OpenStackIdentityDomain id=%s, name=%s, enabled=%s>' % (self.id, self.name, self.enabled))) class OpenStackIdentityProject(object): def __init__(self, id, name, description, enabled, domain_id=None): self.id = id self.name = name self.description = description self.enabled = enabled self.domain_id = domain_id def __repr__(self): return (('<OpenStackIdentityProject id=%s, domain_id=%s, name=%s, ' 'enabled=%s>' % (self.id, self.domain_id, self.name, self.enabled))) class OpenStackIdentityRole(object): def __init__(self, id, name, description, enabled): self.id = id self.name = name self.description = description self.enabled = enabled def __repr__(self): return (('<OpenStackIdentityRole id=%s, name=%s, description=%s, ' 'enabled=%s>' % (self.id, self.name, self.description, self.enabled))) class OpenStackIdentityUser(object): def __init__(self, id, domain_id, name, email, description, enabled): self.id = id self.domain_id = domain_id self.name = name self.email = email self.description = description self.enabled = enabled def __repr__(self): return (('<OpenStackIdentityUser id=%s, domain_id=%s, name=%s, ' 'email=%s, enabled=%s>' % (self.id, self.domain_id, self.name, self.email, self.enabled))) class OpenStackServiceCatalog(object): """ http://docs.openstack.org/api/openstack-identity-service/2.0/content/ This class should be instantiated with the contents of the 'serviceCatalog' in the auth response. This will do the work of figuring out which services actually exist in the catalog as well as split them up by type, name, and region if available """ _auth_version = None _service_catalog = None def __init__(self, service_catalog, auth_version=AUTH_API_VERSION): self._auth_version = auth_version # Check this way because there are a couple of different 2.0_* # auth types. if '3.x' in self._auth_version: entries = self._parse_service_catalog_auth_v3( service_catalog=service_catalog) elif '2.0' in self._auth_version: entries = self._parse_service_catalog_auth_v2( service_catalog=service_catalog) elif ('1.1' in self._auth_version) or ('1.0' in self._auth_version): entries = self._parse_service_catalog_auth_v1( service_catalog=service_catalog) else: raise LibcloudError('auth version "%s" not supported' % (self._auth_version)) # Force consistent ordering by sorting the entries entries = sorted(entries, key=lambda x: x.service_type + (x.service_name or '')) self._entries = entries # stories all the service catalog entries def get_entries(self): """ Return all the entries for this service catalog. :rtype: ``list`` of :class:`.OpenStackServiceCatalogEntry` """ return self._entries def get_catalog(self): """ Deprecated in the favor of ``get_entries`` method. """ return self.get_entries() def get_public_urls(self, service_type=None, name=None): """ Retrieve all the available public (external) URLs for the provided service type and name. """ endpoints = self.get_endpoints(service_type=service_type, name=name) result = [] for endpoint in endpoints: endpoint_type = endpoint.endpoint_type if endpoint_type == OpenStackIdentityEndpointType.EXTERNAL: result.append(endpoint.url) return result def get_endpoints(self, service_type=None, name=None): """ Retrieve all the endpoints for the provided service type and name. :rtype: ``list`` of :class:`.OpenStackServiceCatalogEntryEndpoint` """ endpoints = [] for entry in self._entries: # Note: "if XXX and YYY != XXX" comparison is used to support # partial lookups. # This allows user to pass in only one argument to the method (only # service_type or name), both of them or neither. if service_type and entry.service_type != service_type: continue if name and entry.service_name != name: continue for endpoint in entry.endpoints: endpoints.append(endpoint) return endpoints def get_endpoint(self, service_type=None, name=None, region=None, endpoint_type=OpenStackIdentityEndpointType.EXTERNAL): """ Retrieve a single endpoint using the provided criteria. Note: If no or more than one matching endpoint is found, an exception is thrown. """ endpoints = [] for entry in self._entries: if service_type and entry.service_type != service_type: continue if name and entry.service_name != name: continue for endpoint in entry.endpoints: if region and endpoint.region != region: continue if endpoint_type and endpoint.endpoint_type != endpoint_type: continue endpoints.append(endpoint) if len(endpoints) == 1: return endpoints[0] elif len(endpoints) > 1: raise ValueError('Found more than 1 matching endpoint') else: raise LibcloudError('Could not find specified endpoint') def get_regions(self, service_type=None): """ Retrieve a list of all the available regions. :param service_type: If specified, only return regions for this service type. :type service_type: ``str`` :rtype: ``list`` of ``str`` """ regions = set() for entry in self._entries: if service_type and entry.service_type != service_type: continue for endpoint in entry.endpoints: if endpoint.region: regions.add(endpoint.region) return sorted(list(regions)) def get_service_types(self, region=None): """ Retrieve all the available service types. :param region: Optional region to retrieve service types for. :type region: ``str`` :rtype: ``list`` of ``str`` """ service_types = set() for entry in self._entries: include = True for endpoint in entry.endpoints: if region and endpoint.region != region: include = False break if include: service_types.add(entry.service_type) return sorted(list(service_types)) def get_service_names(self, service_type=None, region=None): """ Retrieve list of service names that match service type and region. :type service_type: ``str`` :type region: ``str`` :rtype: ``list`` of ``str`` """ names = set() if '2.0' not in self._auth_version: raise ValueError('Unsupported version: %s' % (self._auth_version)) for entry in self._entries: if service_type and entry.service_type != service_type: continue include = True for endpoint in entry.endpoints: if region and endpoint.region != region: include = False break if include and entry.service_name: names.add(entry.service_name) return sorted(list(names)) def _parse_service_catalog_auth_v1(self, service_catalog): entries = [] for service, endpoints in service_catalog.items(): entry_endpoints = [] for endpoint in endpoints: region = endpoint.get('region', None) public_url = endpoint.get('publicURL', None) private_url = endpoint.get('internalURL', None) if public_url: entry_endpoint = OpenStackServiceCatalogEntryEndpoint( region=region, url=public_url, endpoint_type=OpenStackIdentityEndpointType.EXTERNAL) entry_endpoints.append(entry_endpoint) if private_url: entry_endpoint = OpenStackServiceCatalogEntryEndpoint( region=region, url=private_url, endpoint_type=OpenStackIdentityEndpointType.INTERNAL) entry_endpoints.append(entry_endpoint) entry = OpenStackServiceCatalogEntry(service_type=service, endpoints=entry_endpoints) entries.append(entry) return entries def _parse_service_catalog_auth_v2(self, service_catalog): entries = [] for service in service_catalog: service_type = service['type'] service_name = service.get('name', None) entry_endpoints = [] for endpoint in service.get('endpoints', []): region = endpoint.get('region', None) public_url = endpoint.get('publicURL', None) private_url = endpoint.get('internalURL', None) if public_url: entry_endpoint = OpenStackServiceCatalogEntryEndpoint( region=region, url=public_url, endpoint_type=OpenStackIdentityEndpointType.EXTERNAL) entry_endpoints.append(entry_endpoint) if private_url: entry_endpoint = OpenStackServiceCatalogEntryEndpoint( region=region, url=private_url, endpoint_type=OpenStackIdentityEndpointType.INTERNAL) entry_endpoints.append(entry_endpoint) entry = OpenStackServiceCatalogEntry(service_type=service_type, endpoints=entry_endpoints, service_name=service_name) entries.append(entry) return entries def _parse_service_catalog_auth_v3(self, service_catalog): entries = [] for item in service_catalog: service_type = item['type'] service_name = item.get('name', None) entry_endpoints = [] for endpoint in item['endpoints']: region = endpoint.get('region', None) url = endpoint['url'] endpoint_type = endpoint['interface'] if endpoint_type == 'internal': endpoint_type = OpenStackIdentityEndpointType.INTERNAL elif endpoint_type == 'public': endpoint_type = OpenStackIdentityEndpointType.EXTERNAL elif endpoint_type == 'admin': endpoint_type = OpenStackIdentityEndpointType.ADMIN entry_endpoint = OpenStackServiceCatalogEntryEndpoint( region=region, url=url, endpoint_type=endpoint_type) entry_endpoints.append(entry_endpoint) entry = OpenStackServiceCatalogEntry(service_type=service_type, service_name=service_name, endpoints=entry_endpoints) entries.append(entry) return entries class OpenStackServiceCatalogEntry(object): def __init__(self, service_type, endpoints=None, service_name=None): """ :param service_type: Service type. :type service_type: ``str`` :param endpoints: Endpoints belonging to this entry. :type endpoints: ``list`` :param service_name: Optional service name. :type service_name: ``str`` """ self.service_type = service_type self.endpoints = endpoints or [] self.service_name = service_name # For consistency, sort the endpoints self.endpoints = sorted(self.endpoints, key=lambda x: x.url or '') def __eq__(self, other): return (self.service_type == other.service_type and self.endpoints == other.endpoints and other.service_name == self.service_name) def __ne__(self, other): return not self.__eq__(other=other) def __repr__(self): return (('<OpenStackServiceCatalogEntry service_type=%s, ' 'service_name=%s, endpoints=%s' % (self.service_type, self.service_name, repr(self.endpoints)))) class OpenStackServiceCatalogEntryEndpoint(object): VALID_ENDPOINT_TYPES = [ OpenStackIdentityEndpointType.INTERNAL, OpenStackIdentityEndpointType.EXTERNAL, OpenStackIdentityEndpointType.ADMIN, ] def __init__(self, region, url, endpoint_type='external'): """ :param region: Endpoint region. :type region: ``str`` :param url: Endpoint URL. :type url: ``str`` :param endpoint_type: Endpoint type (external / internal / admin). :type endpoint_type: ``str`` """ if endpoint_type not in self.VALID_ENDPOINT_TYPES: raise ValueError('Invalid type: %s' % (endpoint_type)) # TODO: Normalize / lowercase all the region names self.region = region self.url = url self.endpoint_type = endpoint_type def __eq__(self, other): return (self.region == other.region and self.url == other.url and self.endpoint_type == other.endpoint_type) def __ne__(self, other): return not self.__eq__(other=other) def __repr__(self): return (('<OpenStackServiceCatalogEntryEndpoint region=%s, url=%s, ' 'type=%s' % (self.region, self.url, self.endpoint_type))) class OpenStackAuthResponse(Response): def success(self): return self.status in [httplib.OK, httplib.CREATED, httplib.ACCEPTED, httplib.NO_CONTENT, httplib.MULTIPLE_CHOICES, httplib.UNAUTHORIZED, httplib.INTERNAL_SERVER_ERROR] def parse_body(self): if not self.body: return None if 'content-type' in self.headers: key = 'content-type' elif 'Content-Type' in self.headers: key = 'Content-Type' else: raise LibcloudError('Missing content-type header', driver=OpenStackIdentityConnection) content_type = self.headers[key] if content_type.find(';') != -1: content_type = content_type.split(';')[0] if content_type == 'application/json': try: data = json.loads(self.body) except Exception: driver = OpenStackIdentityConnection raise MalformedResponseError('Failed to parse JSON', body=self.body, driver=driver) elif content_type == 'text/plain': data = self.body else: data = self.body return data class OpenStackIdentityConnection(ConnectionUserAndKey): """ Base identity connection class which contains common / shared logic. Note: This class shouldn't be instantiated directly. """ responseCls = OpenStackAuthResponse timeout = None auth_version = None def __init__(self, auth_url, user_id, key, tenant_name=None, domain_name='Default', token_scope=OpenStackIdentityTokenScope.PROJECT, timeout=None, proxy_url=None, parent_conn=None): super(OpenStackIdentityConnection, self).__init__(user_id=user_id, key=key, url=auth_url, timeout=timeout, proxy_url=proxy_url) self.parent_conn = parent_conn # enable tests to use the same mock connection classes. if parent_conn: self.conn_class = parent_conn.conn_class self.driver = parent_conn.driver else: self.driver = None self.auth_url = auth_url self.tenant_name = tenant_name self.domain_name = domain_name self.token_scope = token_scope self.timeout = timeout self.urls = {} self.auth_token = None self.auth_token_expires = None self.auth_user_info = None def authenticated_request(self, action, params=None, data=None, headers=None, method='GET', raw=False): """ Perform an authenticated request against the identity API. """ if not self.auth_token: raise ValueError('Not to be authenticated to perform this request') headers = headers or {} headers['X-Auth-Token'] = self.auth_token return self.request(action=action, params=params, data=data, headers=headers, method=method, raw=raw) def morph_action_hook(self, action): (_, _, _, request_path) = self._tuple_from_url(self.auth_url) if request_path == '': # No path is provided in the auth_url, use action passed to this # method. return action return request_path def add_default_headers(self, headers): headers['Accept'] = 'application/json' headers['Content-Type'] = 'application/json; charset=UTF-8' return headers def is_token_valid(self): """ Return True if the current auth token is already cached and hasn't expired yet. :return: ``True`` if the token is still valid, ``False`` otherwise. :rtype: ``bool`` """ if not self.auth_token: return False if not self.auth_token_expires: return False expires = self.auth_token_expires - \ datetime.timedelta(seconds=AUTH_TOKEN_EXPIRES_GRACE_SECONDS) time_tuple_expires = expires.utctimetuple() time_tuple_now = datetime.datetime.utcnow().utctimetuple() if time_tuple_now < time_tuple_expires: return True return False def authenticate(self, force=False): """ Authenticate against the identity API. :param force: Forcefully update the token even if it's already cached and still valid. :type force: ``bool`` """ raise NotImplementedError('authenticate not implemented') def list_supported_versions(self): """ Retrieve a list of all the identity versions which are supported by this installation. :rtype: ``list`` of :class:`.OpenStackIdentityVersion` """ response = self.request('/', method='GET') result = self._to_versions(data=response.object['versions']['values']) result = sorted(result, key=lambda x: x.version) return result def _to_versions(self, data): result = [] for item in data: version = self._to_version(data=item) result.append(version) return result def _to_version(self, data): try: updated = parse_date(data['updated']) except Exception: updated = None try: url = data['links'][0]['href'] except IndexError: url = None version = OpenStackIdentityVersion(version=data['id'], status=data['status'], updated=updated, url=url) return version def _is_authentication_needed(self, force=False): """ Determine if the authentication is needed or if the existing token (if any exists) is still valid. """ if force: return True if self.auth_version not in AUTH_VERSIONS_WITH_EXPIRES: return True if self.is_token_valid(): return False return True def _to_projects(self, data): result = [] for item in data: project = self._to_project(data=item) result.append(project) return result def _to_project(self, data): project = OpenStackIdentityProject(id=data['id'], name=data['name'], description=data['description'], enabled=data['enabled'], domain_id=data.get('domain_id', None)) return project class OpenStackIdentity_1_0_Connection(OpenStackIdentityConnection): """ Connection class for Keystone API v1.0. """ responseCls = OpenStackAuthResponse name = 'OpenStack Identity API v1.0' auth_version = '1.0' def authenticate(self, force=False): if not self._is_authentication_needed(force=force): return self headers = { 'X-Auth-User': self.user_id, 'X-Auth-Key': self.key, } resp = self.request('/v1.0', headers=headers, method='GET') if resp.status == httplib.UNAUTHORIZED: # HTTP UNAUTHORIZED (401): auth failed raise InvalidCredsError() elif resp.status not in [httplib.NO_CONTENT, httplib.OK]: body = 'code: %s body:%s headers:%s' % (resp.status, resp.body, resp.headers) raise MalformedResponseError('Malformed response', body=body, driver=self.driver) else: headers = resp.headers # emulate the auth 1.1 URL list self.urls = {} self.urls['cloudServers'] = \ [{'publicURL': headers.get('x-server-management-url', None)}] self.urls['cloudFilesCDN'] = \ [{'publicURL': headers.get('x-cdn-management-url', None)}] self.urls['cloudFiles'] = \ [{'publicURL': headers.get('x-storage-url', None)}] self.auth_token = headers.get('x-auth-token', None) self.auth_user_info = None if not self.auth_token: raise MalformedResponseError('Missing X-Auth-Token in' ' response headers') return self class OpenStackIdentity_1_1_Connection(OpenStackIdentityConnection): """ Connection class for Keystone API v1.1. """ responseCls = OpenStackAuthResponse name = 'OpenStack Identity API v1.1' auth_version = '1.1' def authenticate(self, force=False): if not self._is_authentication_needed(force=force): return self reqbody = json.dumps({'credentials': {'username': self.user_id, 'key': self.key}}) resp = self.request('/v1.1/auth', data=reqbody, headers={}, method='POST') if resp.status == httplib.UNAUTHORIZED: # HTTP UNAUTHORIZED (401): auth failed raise InvalidCredsError() elif resp.status != httplib.OK: body = 'code: %s body:%s' % (resp.status, resp.body) raise MalformedResponseError('Malformed response', body=body, driver=self.driver) else: try: body = json.loads(resp.body) except Exception as e: raise MalformedResponseError('Failed to parse JSON', e) try: expires = body['auth']['token']['expires'] self.auth_token = body['auth']['token']['id'] self.auth_token_expires = parse_date(expires) self.urls = body['auth']['serviceCatalog'] self.auth_user_info = None except KeyError as e: raise MalformedResponseError('Auth JSON response is \ missing required elements', e) return self class OpenStackIdentity_2_0_Connection(OpenStackIdentityConnection): """ Connection class for Keystone API v2.0. """ responseCls = OpenStackAuthResponse name = 'OpenStack Identity API v1.0' auth_version = '2.0' def authenticate(self, auth_type='api_key', force=False): if not self._is_authentication_needed(force=force): return self if auth_type == 'api_key': return self._authenticate_2_0_with_api_key() elif auth_type == 'password': return self._authenticate_2_0_with_password() else: raise ValueError('Invalid value for auth_type argument') def _authenticate_2_0_with_api_key(self): # API Key based authentication uses the RAX-KSKEY extension. # http://s.apache.org/oAi data = {'auth': {'RAX-KSKEY:apiKeyCredentials': {'username': self.user_id, 'apiKey': self.key}}} if self.tenant_name: data['auth']['tenantName'] = self.tenant_name reqbody = json.dumps(data) return self._authenticate_2_0_with_body(reqbody) def _authenticate_2_0_with_password(self): # Password based authentication is the only 'core' authentication # method in Keystone at this time. # 'keystone' - http://s.apache.org/e8h data = {'auth': {'passwordCredentials': {'username': self.user_id, 'password': self.key}}} if self.tenant_name: data['auth']['tenantName'] = self.tenant_name reqbody = json.dumps(data) return self._authenticate_2_0_with_body(reqbody) def _authenticate_2_0_with_body(self, reqbody): resp = self.request('/v2.0/tokens', data=reqbody, headers={'Content-Type': 'application/json'}, method='POST') if resp.status == httplib.UNAUTHORIZED: raise InvalidCredsError() elif resp.status not in [httplib.OK, httplib.NON_AUTHORITATIVE_INFORMATION]: body = 'code: %s body: %s' % (resp.status, resp.body) raise MalformedResponseError('Malformed response', body=body, driver=self.driver) else: body = resp.object try: access = body['access'] expires = access['token']['expires'] self.auth_token = access['token']['id'] self.auth_token_expires = parse_date(expires) self.urls = access['serviceCatalog'] self.auth_user_info = access.get('user', {}) except KeyError as e: raise MalformedResponseError('Auth JSON response is \ missing required elements', e) return self def list_projects(self): response = self.authenticated_request('/v2.0/tenants', method='GET') result = self._to_projects(data=response.object['tenants']) return result def list_tenants(self): return self.list_projects() class OpenStackIdentity_3_0_Connection(OpenStackIdentityConnection): """ Connection class for Keystone API v3.x. """ responseCls = OpenStackAuthResponse name = 'OpenStack Identity API v3.x' auth_version = '3.0' VALID_TOKEN_SCOPES = [ OpenStackIdentityTokenScope.PROJECT, OpenStackIdentityTokenScope.DOMAIN, OpenStackIdentityTokenScope.UNSCOPED ] def __init__(self, auth_url, user_id, key, tenant_name=None, domain_name='Default', token_scope=OpenStackIdentityTokenScope.PROJECT, timeout=None, proxy_url=None, parent_conn=None): """ :param tenant_name: Name of the project this user belongs to. Note: When token_scope is set to project, this argument control to which project to scope the token to. :type tenant_name: ``str`` :param domain_name: Domain the user belongs to. Note: Then token_scope is set to token, this argument controls to which domain to scope the token to. :type domain_name: ``str`` :param token_scope: Whether to scope a token to a "project", a "domain" or "unscoped" :type token_scope: ``str`` """ super(OpenStackIdentity_3_0_Connection, self).__init__(auth_url=auth_url, user_id=user_id, key=key, tenant_name=tenant_name, domain_name=domain_name, token_scope=token_scope, timeout=timeout, proxy_url=proxy_url, parent_conn=parent_conn) if self.token_scope not in self.VALID_TOKEN_SCOPES: raise ValueError('Invalid value for "token_scope" argument: %s' % (self.token_scope)) if (self.token_scope == OpenStackIdentityTokenScope.PROJECT and (not self.tenant_name or not self.domain_name)): raise ValueError('Must provide tenant_name and domain_name ' 'argument') elif (self.token_scope == OpenStackIdentityTokenScope.DOMAIN and not self.domain_name): raise ValueError('Must provide domain_name argument') self.auth_user_roles = None def authenticate(self, force=False): """ Perform authentication. """ if not self._is_authentication_needed(force=force): return self data = { 'auth': { 'identity': { 'methods': ['password'], 'password': { 'user': { 'domain': { 'name': self.domain_name }, 'name': self.user_id, 'password': self.key } } } } } if self.token_scope == OpenStackIdentityTokenScope.PROJECT: # Scope token to project (tenant) data['auth']['scope'] = { 'project': { 'domain': { 'name': self.domain_name }, 'name': self.tenant_name } } elif self.token_scope == OpenStackIdentityTokenScope.DOMAIN: # Scope token to domain data['auth']['scope'] = { 'domain': { 'name': self.domain_name } } elif self.token_scope == OpenStackIdentityTokenScope.UNSCOPED: pass else: raise ValueError('Token needs to be scoped either to project or ' 'a domain') data = json.dumps(data) response = self.request('/v3/auth/tokens', data=data, headers={'Content-Type': 'application/json'}, method='POST') if response.status == httplib.UNAUTHORIZED: # Invalid credentials raise InvalidCredsError() elif response.status in [httplib.OK, httplib.CREATED]: headers = response.headers try: body = json.loads(response.body) except Exception as e: raise MalformedResponseError('Failed to parse JSON', e) try: roles = self._to_roles(body['token']['roles']) except Exception as e: roles = [] try: expires = body['token']['expires_at'] self.auth_token = headers['x-subject-token'] self.auth_token_expires = parse_date(expires) # Note: catalog is not returned for unscoped tokens self.urls = body['token'].get('catalog', None) self.auth_user_info = None self.auth_user_roles = roles except KeyError as e: raise MalformedResponseError('Auth JSON response is \ missing required elements', e) body = 'code: %s body:%s' % (response.status, response.body) elif response.status == 300: # ambiguous version request raise LibcloudError( 'Auth request returned ambiguous version error, try' 'using the version specific URL to connect,' ' e.g. identity/v3/auth/tokens') else: body = 'code: %s body:%s' % (response.status, response.body) raise MalformedResponseError('Malformed response', body=body, driver=self.driver) return self def list_domains(self): """ List the available domains. :rtype: ``list`` of :class:`OpenStackIdentityDomain` """ response = self.authenticated_request('/v3/domains', method='GET') result = self._to_domains(data=response.object['domains']) return result def list_projects(self): """ List the available projects. Note: To perform this action, user you are currently authenticated with needs to be an admin. :rtype: ``list`` of :class:`OpenStackIdentityProject` """ response = self.authenticated_request('/v3/projects', method='GET') result = self._to_projects(data=response.object['projects']) return result def list_users(self): """ List the available users. :rtype: ``list`` of :class:`.OpenStackIdentityUser` """ response = self.authenticated_request('/v3/users', method='GET') result = self._to_users(data=response.object['users']) return result def list_roles(self): """ List the available roles. :rtype: ``list`` of :class:`.OpenStackIdentityRole` """ response = self.authenticated_request('/v3/roles', method='GET') result = self._to_roles(data=response.object['roles']) return result def get_domain(self, domain_id): """ Retrieve information about a single domain. :param domain_id: ID of domain to retrieve information for. :type domain_id: ``str`` :rtype: :class:`.OpenStackIdentityDomain` """ response = self.authenticated_request('/v3/domains/%s' % (domain_id), method='GET') result = self._to_domain(data=response.object['domain']) return result def get_user(self, user_id): """ Get a user account by ID. :param user_id: User's id. :type name: ``str`` :return: Located user. :rtype: :class:`.OpenStackIdentityUser` """ response = self.authenticated_request('/v3/users/%s' % user_id) user = self._to_user(data=response.object['user']) return user def list_user_projects(self, user): """ Retrieve all the projects user belongs to. :rtype: ``list`` of :class:`.OpenStackIdentityProject` """ path = '/v3/users/%s/projects' % (user.id) response = self.authenticated_request(path, method='GET') result = self._to_projects(data=response.object['projects']) return result def list_user_domain_roles(self, domain, user): """ Retrieve all the roles for a particular user on a domain. :rtype: ``list`` of :class:`.OpenStackIdentityRole` """ # TODO: Also add "get users roles" and "get assginements" which are # available in 3.1 and 3.3 path = '/v3/domains/%s/users/%s/roles' % (domain.id, user.id) response = self.authenticated_request(path, method='GET') result = self._to_roles(data=response.object['roles']) return result def grant_domain_role_to_user(self, domain, role, user): """ Grant domain role to a user. Note: This function appears to be idempotent. :param domain: Domain to grant the role to. :type domain: :class:`.OpenStackIdentityDomain` :param role: Role to grant. :type role: :class:`.OpenStackIdentityRole` :param user: User to grant the role to. :type user: :class:`.OpenStackIdentityUser` :return: ``True`` on success. :rtype: ``bool`` """ path = ('/v3/domains/%s/users/%s/roles/%s' % (domain.id, user.id, role.id)) response = self.authenticated_request(path, method='PUT') return response.status == httplib.NO_CONTENT def revoke_domain_role_from_user(self, domain, user, role): """ Revoke domain role from a user. :param domain: Domain to revoke the role from. :type domain: :class:`.OpenStackIdentityDomain` :param role: Role to revoke. :type role: :class:`.OpenStackIdentityRole` :param user: User to revoke the role from. :type user: :class:`.OpenStackIdentityUser` :return: ``True`` on success. :rtype: ``bool`` """ path = ('/v3/domains/%s/users/%s/roles/%s' % (domain.id, user.id, role.id)) response = self.authenticated_request(path, method='DELETE') return response.status == httplib.NO_CONTENT def grant_project_role_to_user(self, project, role, user): """ Grant project role to a user. Note: This function appears to be idempotent. :param project: Project to grant the role to. :type project: :class:`.OpenStackIdentityDomain` :param role: Role to grant. :type role: :class:`.OpenStackIdentityRole` :param user: User to grant the role to. :type user: :class:`.OpenStackIdentityUser` :return: ``True`` on success. :rtype: ``bool`` """ path = ('/v3/projects/%s/users/%s/roles/%s' % (project.id, user.id, role.id)) response = self.authenticated_request(path, method='PUT') return response.status == httplib.NO_CONTENT def revoke_project_role_from_user(self, project, role, user): """ Revoke project role from a user. :param project: Project to revoke the role from. :type project: :class:`.OpenStackIdentityDomain` :param role: Role to revoke. :type role: :class:`.OpenStackIdentityRole` :param user: User to revoke the role from. :type user: :class:`.OpenStackIdentityUser` :return: ``True`` on success. :rtype: ``bool`` """ path = ('/v3/projects/%s/users/%s/roles/%s' % (project.id, user.id, role.id)) response = self.authenticated_request(path, method='DELETE') return response.status == httplib.NO_CONTENT def create_user(self, email, password, name, description=None, domain_id=None, default_project_id=None, enabled=True): """ Create a new user account. :param email: User's mail address. :type email: ``str`` :param password: User's password. :type password: ``str`` :param name: User's name. :type name: ``str`` :param description: Optional description. :type description: ``str`` :param domain_id: ID of the domain to add the user to (optional). :type domain_id: ``str`` :param default_project_id: ID of the default user project (optional). :type default_project_id: ``str`` :param enabled: True to enable user after creation. :type enabled: ``bool`` :return: Created user. :rtype: :class:`.OpenStackIdentityUser` """ data = { 'email': email, 'password': password, 'name': name, 'enabled': enabled } if description: data['description'] = description if domain_id: data['domain_id'] = domain_id if default_project_id: data['default_project_id'] = default_project_id data = json.dumps({'user': data}) response = self.authenticated_request('/v3/users', data=data, method='POST') user = self._to_user(data=response.object['user']) return user def enable_user(self, user): """ Enable user account. Note: This operation appears to be idempotent. :param user: User to enable. :type user: :class:`.OpenStackIdentityUser` :return: User account which has been enabled. :rtype: :class:`.OpenStackIdentityUser` """ data = { 'enabled': True } data = json.dumps({'user': data}) response = self.authenticated_request('/v3/users/%s' % (user.id), data=data, method='PATCH') user = self._to_user(data=response.object['user']) return user def disable_user(self, user): """ Disable user account. Note: This operation appears to be idempotent. :param user: User to disable. :type user: :class:`.OpenStackIdentityUser` :return: User account which has been disabled. :rtype: :class:`.OpenStackIdentityUser` """ data = { 'enabled': False } data = json.dumps({'user': data}) response = self.authenticated_request('/v3/users/%s' % (user.id), data=data, method='PATCH') user = self._to_user(data=response.object['user']) return user def _to_domains(self, data): result = [] for item in data: domain = self._to_domain(data=item) result.append(domain) return result def _to_domain(self, data): domain = OpenStackIdentityDomain(id=data['id'], name=data['name'], enabled=data['enabled']) return domain def _to_users(self, data): result = [] for item in data: user = self._to_user(data=item) result.append(user) return result def _to_user(self, data): user = OpenStackIdentityUser(id=data['id'], domain_id=data['domain_id'], name=data['name'], email=data.get('email'), description=data.get('description', None), enabled=data.get('enabled')) return user def _to_roles(self, data): result = [] for item in data: user = self._to_role(data=item) result.append(user) return result def _to_role(self, data): role = OpenStackIdentityRole(id=data['id'], name=data['name'], description=data.get('description', None), enabled=data.get('enabled', True)) return role class OpenStackIdentity_3_0_Connection_OIDC_access_token( OpenStackIdentity_3_0_Connection): """ Connection class for Keystone API v3.x. using OpenID Connect tokens The OIDC token must be set in the self.key attribute. The identity provider name required to get the full path must be set in the self.user_id attribute. The protocol name required to get the full path must be set in the self.tenant_name attribute. The self.domain_name attribute can be used either to select the domain name in case of domain scoped token or to select the project name in case of project scoped token """ responseCls = OpenStackAuthResponse name = 'OpenStack Identity API v3.x with OIDC support' auth_version = '3.0' def authenticate(self, force=False): """ Perform authentication. """ if not self._is_authentication_needed(force=force): return self subject_token = self._get_unscoped_token_from_oidc_token() data = { 'auth': { 'identity': { 'methods': ['token'], 'token': { 'id': subject_token } } } } if self.token_scope == OpenStackIdentityTokenScope.PROJECT: # Scope token to project (tenant) project_id = self._get_project_id(token=subject_token) data['auth']['scope'] = { 'project': { 'id': project_id } } elif self.token_scope == OpenStackIdentityTokenScope.DOMAIN: # Scope token to domain data['auth']['scope'] = { 'domain': { 'name': self.domain_name } } elif self.token_scope == OpenStackIdentityTokenScope.UNSCOPED: pass else: raise ValueError('Token needs to be scoped either to project or ' 'a domain') data = json.dumps(data) response = self.request('/v3/auth/tokens', data=data, headers={'Content-Type': 'application/json'}, method='POST') if response.status == httplib.UNAUTHORIZED: # Invalid credentials raise InvalidCredsError() elif response.status in [httplib.OK, httplib.CREATED]: headers = response.headers try: body = json.loads(response.body) except Exception as e: raise MalformedResponseError('Failed to parse JSON', e) try: roles = self._to_roles(body['token']['roles']) except Exception as e: roles = [] try: expires = body['token']['expires_at'] self.auth_token = headers['x-subject-token'] self.auth_token_expires = parse_date(expires) # Note: catalog is not returned for unscoped tokens self.urls = body['token'].get('catalog', None) self.auth_user_info = None self.auth_user_roles = roles except KeyError as e: raise MalformedResponseError('Auth JSON response is \ missing required elements', e) body = 'code: %s body:%s' % (response.status, response.body) else: body = 'code: %s body:%s' % (response.status, response.body) raise MalformedResponseError('Malformed response', body=body, driver=self.driver) return self def _get_unscoped_token_from_oidc_token(self): """ Get unscoped token from OIDC access token """ path = ('/v3/OS-FEDERATION/identity_providers/%s/protocols/%s/auth' % (self.user_id, self.tenant_name)) response = self.request(path, headers={'Content-Type': 'application/json', 'Authorization': 'Bearer %s' % self.key}, method='GET') if response.status == httplib.UNAUTHORIZED: # Invalid credentials raise InvalidCredsError() elif response.status in [httplib.OK, httplib.CREATED]: if 'x-subject-token' in response.headers: return response.headers['x-subject-token'] else: raise MalformedResponseError('No x-subject-token returned', driver=self.driver) else: raise MalformedResponseError('Malformed response', driver=self.driver, body=response.body) def _get_project_id(self, token): """ Get the first project ID accessible with the specified access token """ # Try new path first (from ver 1.1) path = '/v3/auth/projects' response = self.request(path, headers={'Content-Type': 'application/json', 'X-Auth-Token': token}, method='GET') if response.status not in [httplib.UNAUTHORIZED, httplib.OK, httplib.CREATED]: # In case of error try old one path = '/v3/OS-FEDERATION/projects' response = self.request(path, headers={'Content-Type': 'application/json', 'X-Auth-Token': token}, method='GET') if response.status == httplib.UNAUTHORIZED: # Invalid credentials raise InvalidCredsError() elif response.status in [httplib.OK, httplib.CREATED]: try: body = json.loads(response.body) # We use domain_name in both cases of the scoped tokens # as we have used tenant as the protocol if self.domain_name and self.domain_name != 'Default': for project in body['projects']: if project['name'] == self.domain_name: return project['id'] raise ValueError('Project %s not found' % self.domain_name) else: return body['projects'][0]['id'] except Exception as e: raise MalformedResponseError('Failed to parse JSON', e) else: raise MalformedResponseError('Malformed response', driver=self.driver, body=response.body) class OpenStackIdentity_2_0_Connection_VOMS(OpenStackIdentityConnection, CertificateConnection): """ Connection class for Keystone API v2.0. with VOMS proxy support In this case the key parameter will be the path of the VOMS proxy file. """ responseCls = OpenStackAuthResponse name = 'OpenStack Identity API v2.0 VOMS support' auth_version = '2.0' def __init__(self, auth_url, user_id, key, tenant_name=None, domain_name='Default', token_scope=OpenStackIdentityTokenScope.PROJECT, timeout=None, proxy_url=None, parent_conn=None): CertificateConnection.__init__(self, cert_file=key, url=auth_url, proxy_url=proxy_url, timeout=timeout) self.parent_conn = parent_conn # enable tests to use the same mock connection classes. if parent_conn: self.conn_class = parent_conn.conn_class self.driver = parent_conn.driver else: self.driver = None self.auth_url = auth_url self.tenant_name = tenant_name self.domain_name = domain_name self.token_scope = token_scope self.timeout = timeout self.proxy_url = proxy_url self.urls = {} self.auth_token = None self.auth_token_expires = None self.auth_user_info = None def authenticate(self, force=False): if not self._is_authentication_needed(force=force): return self tenant = self.tenant_name if not tenant: # if the tenant name is not specified look for it token = self._get_unscoped_token() tenant = self._get_tenant_name(token) data = {'auth': {'voms': True, 'tenantName': tenant}} reqbody = json.dumps(data) return self._authenticate_2_0_with_body(reqbody) def _get_unscoped_token(self): """ Get unscoped token from VOMS proxy """ data = {'auth': {'voms': True}} reqbody = json.dumps(data) response = self.request('/v2.0/tokens', data=reqbody, headers={'Content-Type': 'application/json'}, method='POST') if response.status == httplib.UNAUTHORIZED: # Invalid credentials raise InvalidCredsError() elif response.status in [httplib.OK, httplib.CREATED]: try: body = json.loads(response.body) return body['access']['token']['id'] except Exception as e: raise MalformedResponseError('Failed to parse JSON', e) else: raise MalformedResponseError('Malformed response', driver=self.driver, body=response.body) def _get_tenant_name(self, token): """ Get the first available tenant name (usually there are only one) """ headers = {'Accept': 'application/json', 'Content-Type': 'application/json', 'X-Auth-Token': token} response = self.request('/v2.0/tenants', headers=headers, method='GET') if response.status == httplib.UNAUTHORIZED: # Invalid credentials raise InvalidCredsError() elif response.status in [httplib.OK, httplib.CREATED]: try: body = json.loads(response.body) return body["tenants"][0]["name"] except Exception as e: raise MalformedResponseError('Failed to parse JSON', e) else: raise MalformedResponseError('Malformed response', driver=self.driver, body=response.body) def _authenticate_2_0_with_body(self, reqbody): resp = self.request('/v2.0/tokens', data=reqbody, headers={'Content-Type': 'application/json'}, method='POST') if resp.status == httplib.UNAUTHORIZED: raise InvalidCredsError() elif resp.status not in [httplib.OK, httplib.NON_AUTHORITATIVE_INFORMATION]: body = 'code: %s body: %s' % (resp.status, resp.body) raise MalformedResponseError('Malformed response', body=body, driver=self.driver) else: body = resp.object try: access = body['access'] expires = access['token']['expires'] self.auth_token = access['token']['id'] self.auth_token_expires = parse_date(expires) self.urls = access['serviceCatalog'] self.auth_user_info = access.get('user', {}) except KeyError as e: raise MalformedResponseError('Auth JSON response is \ missing required elements', e) return self def get_class_for_auth_version(auth_version): """ Retrieve class for the provided auth version. """ if auth_version == '1.0': cls = OpenStackIdentity_1_0_Connection elif auth_version == '1.1': cls = OpenStackIdentity_1_1_Connection elif auth_version == '2.0' or auth_version == '2.0_apikey': cls = OpenStackIdentity_2_0_Connection elif auth_version == '2.0_password': cls = OpenStackIdentity_2_0_Connection elif auth_version == '2.0_voms': cls = OpenStackIdentity_2_0_Connection_VOMS elif auth_version == '3.x_password': cls = OpenStackIdentity_3_0_Connection elif auth_version == '3.x_oidc_access_token': cls = OpenStackIdentity_3_0_Connection_OIDC_access_token else: raise LibcloudError('Unsupported Auth Version requested') return cls
apache-2.0
szegedim/hadoop
hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/TestContainerOperations.java
3636
/** * 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 * <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 org.apache.hadoop.ozone; import org.apache.hadoop.hdds.conf.OzoneConfiguration; import org.apache.hadoop.hdds.scm.container.common.helpers.ContainerInfo; import org.apache.hadoop.ipc.ProtobufRpcEngine; import org.apache.hadoop.ipc.RPC; import org.apache.hadoop.hdds.protocol.proto.HddsProtos; import org.apache.hadoop.hdds.scm.container.placement.algorithms.ContainerPlacementPolicy; import org.apache.hadoop.hdds.scm.container.placement.algorithms.SCMContainerPlacementCapacity; import org.apache.hadoop.hdds.scm.ScmConfigKeys; import org.apache.hadoop.hdds.scm.XceiverClientManager; import org.apache.hadoop.hdds.scm.client.ContainerOperationClient; import org.apache.hadoop.hdds.scm.client.ScmClient; import org.apache.hadoop.hdds.scm.container.common.helpers.Pipeline; import org.apache.hadoop.hdds.scm.protocolPB.StorageContainerLocationProtocolClientSideTranslatorPB; import org.apache.hadoop.hdds.scm.protocolPB.StorageContainerLocationProtocolPB; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * This class tests container operations (TODO currently only supports create) * from cblock clients. */ public class TestContainerOperations { private static ScmClient storageClient; private static MiniOzoneCluster cluster; private static OzoneConfiguration ozoneConf; @BeforeClass public static void setup() throws Exception { int containerSizeGB = 5; ContainerOperationClient.setContainerSizeB( containerSizeGB * OzoneConsts.GB); ozoneConf = new OzoneConfiguration(); ozoneConf.setClass(ScmConfigKeys.OZONE_SCM_CONTAINER_PLACEMENT_IMPL_KEY, SCMContainerPlacementCapacity.class, ContainerPlacementPolicy.class); cluster = MiniOzoneCluster.newBuilder(ozoneConf).setNumDatanodes(1).build(); StorageContainerLocationProtocolClientSideTranslatorPB client = cluster.getStorageContainerLocationClient(); RPC.setProtocolEngine(ozoneConf, StorageContainerLocationProtocolPB.class, ProtobufRpcEngine.class); storageClient = new ContainerOperationClient( client, new XceiverClientManager(ozoneConf)); cluster.waitForClusterToBeReady(); } @AfterClass public static void cleanup() throws Exception { if(cluster != null) { cluster.shutdown(); } } /** * A simple test to create a container with {@link ContainerOperationClient}. * @throws Exception */ @Test public void testCreate() throws Exception { ContainerInfo container = storageClient.createContainer(HddsProtos .ReplicationType.STAND_ALONE, HddsProtos.ReplicationFactor .ONE, "OZONE"); assertEquals(container.getContainerID(), storageClient.getContainer(container.getContainerID()). getContainerID()); } }
apache-2.0
Javalbert/sql-builder-orm
src/main/java/com/github/javalbert/sqlbuilder/dsl/TableColumn.java
3155
/******************************************************************************* * Copyright 2017 Albert Shun-Dat Chan * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT 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.github.javalbert.sqlbuilder.dsl; import com.github.javalbert.utils.string.Strings; public class TableColumn implements ExpressionBuilder, OrderByColumn, Predicand, SelectColumn<TableColumn>, ValueExpression { public static final TableColumn ALL = new TableColumn() { @Override public String getAlias() { return null; } @Override public TableColumn as(String alias) { return null; } }; private String alias; private String name; private SortType sortType = SortType.ASC; private TableAlias tableAlias; private String tableName; @Override public String getAlias() { return alias; } public String getName() { return name; } @Override public int getNodeType() { return NODE_TABLE_COLUMN; } @Override public SortType getSortType() { return sortType; } @Override public int getOrderByColumnType() { return ORDER_TABLE_COLUMN; } public TableAlias getTableAlias() { return tableAlias; } public String getTableName() { return tableName; } public TableColumn(String name) { this.name = Strings.illegalArgOnEmpty(name, "name cannot be null or empty"); } private TableColumn() {} @Override public TableColumn as(String alias) { TableColumn column = copy(); column.alias = alias; return column; } public SetValue to(Boolean value) { return to(DSL.literal(value)); } public SetValue to(Number value) { return to(DSL.literal(value)); } public SetValue to(String value) { return to(DSL.literal(value)); } public SetValue to(ValueExpression value) { return new SetValue(this, value); } @Override public OrderByColumn asc() { TableColumn column = copy(); column.sortType = SortType.ASC; return column; } @Override public OrderByColumn desc() { TableColumn column = copy(); column.sortType = SortType.DESC; return column; } TableColumn copy() { TableColumn copy = new TableColumn(); copy.alias = alias; copy.name = name; copy.sortType = sortType; copy.tableAlias = tableAlias; copy.tableName = tableName; return copy; } TableColumn table(Table table) { TableColumn column = copy(); column.tableAlias = table != null ? table.getTableAlias() : null; column.tableName = table != null ? table.getName() : null; return column; } TableColumn tableAlias(TableAlias tableAlias) { TableColumn column = copy(); column.tableAlias = tableAlias; return column; } }
apache-2.0