Best JavaScript code snippet using devicefarmer-stf
DataView.js
Source:DataView.js
1var util = require('./util');2var DataSet = require('./DataSet');3/**4 * DataView5 *6 * a dataview offers a filtered view on a dataset or an other dataview.7 *8 * @param {DataSet | DataView} data9 * @param {Object} [options] Available options: see method get10 *11 * @constructor DataView12 */13function DataView (data, options) {14 this._data = null;15 this._ids = {}; // ids of the items currently in memory (just contains a boolean true)16 this.length = 0; // number of items in the DataView17 this._options = options || {};18 this._fieldId = 'id'; // name of the field containing id19 this._subscribers = {}; // event subscribers20 var me = this;21 this.listener = function () {22 me._onEvent.apply(me, arguments);23 };24 this.setData(data);25}26// TODO: implement a function .config() to dynamically update things like configured filter27// and trigger changes accordingly28/**29 * Set a data source for the view30 * @param {DataSet | DataView} data31 */32DataView.prototype.setData = function (data) {33 var ids, id, i, len, items;34 if (this._data) {35 // unsubscribe from current dataset36 if (this._data.off) {37 this._data.off('*', this.listener);38 }39 // trigger a remove of all items in memory40 ids = this._data.getIds({filter: this._options && this._options.filter});41 items = [];42 for (i = 0, len = ids.length; i < len; i++) {43 items.push(this._data._data[ids[i]]);44 }45 this._ids = {};46 this.length = 0;47 this._trigger('remove', {items: ids, oldData: items});48 }49 this._data = data;50 if (this._data) {51 // update fieldId52 this._fieldId = this._options.fieldId ||53 (this._data && this._data.options && this._data.options.fieldId) ||54 'id';55 // trigger an add of all added items56 ids = this._data.getIds({filter: this._options && this._options.filter});57 for (i = 0, len = ids.length; i < len; i++) {58 id = ids[i];59 this._ids[id] = true;60 }61 this.length = ids.length;62 this._trigger('add', {items: ids});63 // subscribe to new dataset64 if (this._data.on) {65 this._data.on('*', this.listener);66 }67 }68};69/**70 * Refresh the DataView. Useful when the DataView has a filter function71 * containing a variable parameter.72 */73DataView.prototype.refresh = function () {74 var id, i, len;75 var ids = this._data.getIds({filter: this._options && this._options.filter}),76 oldIds = Object.keys(this._ids),77 newIds = {},78 addedIds = [],79 removedIds = [],80 removedItems = [];81 // check for additions82 for (i = 0, len = ids.length; i < len; i++) {83 id = ids[i];84 newIds[id] = true;85 if (!this._ids[id]) {86 addedIds.push(id);87 this._ids[id] = true;88 }89 }90 // check for removals91 for (i = 0, len = oldIds.length; i < len; i++) {92 id = oldIds[i];93 if (!newIds[id]) {94 removedIds.push(id);95 removedItems.push(this._data._data[id]);96 delete this._ids[id];97 }98 }99 this.length += addedIds.length - removedIds.length;100 // trigger events101 if (addedIds.length) {102 this._trigger('add', {items: addedIds});103 }104 if (removedIds.length) {105 this._trigger('remove', {items: removedIds, oldData: removedItems});106 }107};108/**109 * Get data from the data view110 *111 * Usage:112 *113 * get()114 * get(options: Object)115 * get(options: Object, data: Array | DataTable)116 *117 * get(id: Number)118 * get(id: Number, options: Object)119 * get(id: Number, options: Object, data: Array | DataTable)120 *121 * get(ids: Number[])122 * get(ids: Number[], options: Object)123 * get(ids: Number[], options: Object, data: Array | DataTable)124 *125 * Where:126 *127 * {number | string} id The id of an item128 * {number[] | string{}} ids An array with ids of items129 * {Object} options An Object with options. Available options:130 * {string} [type] Type of data to be returned. Can131 * be 'DataTable' or 'Array' (default)132 * {Object.<string, string>} [convert]133 * {string[]} [fields] field names to be returned134 * {function} [filter] filter items135 * {string | function} [order] Order the items by136 * a field name or custom sort function.137 * {Array | DataTable} [data] If provided, items will be appended to this138 * array or table. Required in case of Google139 * DataTable.140 * @param {Array} args141 * @return {DataSet|DataView}142 */143DataView.prototype.get = function (args) { // eslint-disable-line no-unused-vars144 var me = this;145 // parse the arguments146 var ids, options, data;147 var firstType = util.getType(arguments[0]);148 if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {149 // get(id(s) [, options] [, data])150 ids = arguments[0]; // can be a single id or an array with ids151 options = arguments[1];152 data = arguments[2];153 }154 else {155 // get([, options] [, data])156 options = arguments[0];157 data = arguments[1];158 }159 // extend the options with the default options and provided options160 var viewOptions = util.extend({}, this._options, options);161 // create a combined filter method when needed162 if (this._options.filter && options && options.filter) {163 viewOptions.filter = function (item) {164 return me._options.filter(item) && options.filter(item);165 }166 }167 // build up the call to the linked data set168 var getArguments = [];169 if (ids != undefined) {170 getArguments.push(ids);171 }172 getArguments.push(viewOptions);173 getArguments.push(data);174 return this._data && this._data.get.apply(this._data, getArguments);175};176/**177 * Get ids of all items or from a filtered set of items.178 * @param {Object} [options] An Object with options. Available options:179 * {function} [filter] filter items180 * {string | function} [order] Order the items by181 * a field name or custom sort function.182 * @return {Array.<string|number>} ids183 */184DataView.prototype.getIds = function (options) {185 var ids;186 if (this._data) {187 var defaultFilter = this._options.filter;188 var filter;189 if (options && options.filter) {190 if (defaultFilter) {191 filter = function (item) {192 return defaultFilter(item) && options.filter(item);193 }194 }195 else {196 filter = options.filter;197 }198 }199 else {200 filter = defaultFilter;201 }202 ids = this._data.getIds({203 filter: filter,204 order: options && options.order205 });206 }207 else {208 ids = [];209 }210 return ids;211};212/**213 * Map every item in the dataset.214 * @param {function} callback215 * @param {Object} [options] Available options:216 * {Object.<string, string>} [type]217 * {string[]} [fields] filter fields218 * {function} [filter] filter items219 * {string | function} [order] Order the items by220 * a field name or custom sort function.221 * @return {Object[]} mappedItems222 */223DataView.prototype.map = function (callback,options) {224 var mappedItems = [];225 if (this._data) {226 var defaultFilter = this._options.filter;227 var filter;228 if (options && options.filter) {229 if (defaultFilter) {230 filter = function (item) {231 return defaultFilter(item) && options.filter(item);232 }233 }234 else {235 filter = options.filter;236 }237 }238 else {239 filter = defaultFilter;240 }241 mappedItems = this._data.map(callback,{242 filter: filter,243 order: options && options.order244 });245 }246 else {247 mappedItems = [];248 }249 return mappedItems;250};251/**252 * Get the DataSet to which this DataView is connected. In case there is a chain253 * of multiple DataViews, the root DataSet of this chain is returned.254 * @return {DataSet} dataSet255 */256DataView.prototype.getDataSet = function () {257 var dataSet = this;258 while (dataSet instanceof DataView) {259 dataSet = dataSet._data;260 }261 return dataSet || null;262};263/**264 * Event listener. Will propagate all events from the connected data set to265 * the subscribers of the DataView, but will filter the items and only trigger266 * when there are changes in the filtered data set.267 * @param {string} event268 * @param {Object | null} params269 * @param {string} senderId270 * @private271 */272DataView.prototype._onEvent = function (event, params, senderId) {273 var i, len, id, item;274 var ids = params && params.items;275 var addedIds = [],276 updatedIds = [],277 removedIds = [],278 oldItems = [],279 updatedItems = [],280 removedItems = [];281 if (ids && this._data) {282 switch (event) {283 case 'add':284 // filter the ids of the added items285 for (i = 0, len = ids.length; i < len; i++) {286 id = ids[i];287 item = this.get(id);288 if (item) {289 this._ids[id] = true;290 addedIds.push(id);291 }292 }293 break;294 case 'update':295 // determine the event from the views viewpoint: an updated296 // item can be added, updated, or removed from this view.297 for (i = 0, len = ids.length; i < len; i++) {298 id = ids[i];299 item = this.get(id);300 if (item) {301 if (this._ids[id]) {302 updatedIds.push(id);303 updatedItems.push(params.data[i]);304 oldItems.push(params.oldData[i]);305 }306 else {307 this._ids[id] = true;308 addedIds.push(id);309 }310 }311 else {312 if (this._ids[id]) {313 delete this._ids[id];314 removedIds.push(id);315 removedItems.push(params.oldData[i]);316 }317 else {318 // nothing interesting for me :-(319 }320 }321 }322 break;323 case 'remove':324 // filter the ids of the removed items325 for (i = 0, len = ids.length; i < len; i++) {326 id = ids[i];327 if (this._ids[id]) {328 delete this._ids[id];329 removedIds.push(id);330 removedItems.push(params.oldData[i]);331 }332 }333 break;334 }335 this.length += addedIds.length - removedIds.length;336 if (addedIds.length) {337 this._trigger('add', {items: addedIds}, senderId);338 }339 if (updatedIds.length) {340 this._trigger('update', {items: updatedIds, oldData: oldItems, data: updatedItems}, senderId);341 }342 if (removedIds.length) {343 this._trigger('remove', {items: removedIds, oldData: removedItems}, senderId);344 }345 }346};347// copy subscription functionality from DataSet348DataView.prototype.on = DataSet.prototype.on;349DataView.prototype.off = DataSet.prototype.off;350DataView.prototype._trigger = DataSet.prototype._trigger;351// TODO: make these functions deprecated (replaced with `on` and `off` since version 0.5)352DataView.prototype.subscribe = DataView.prototype.on;353DataView.prototype.unsubscribe = DataView.prototype.off;...
variations.test.js
Source:variations.test.js
1/**2 * Copyright © Magento, Inc. All rights reserved.3 * See COPYING.txt for license details.4 */5define([6 'Magento_ConfigurableProduct/js/variations/variations'7], function (Variations) {8 'use strict';9 describe('Magento_ConfigurableProduct/js/variations/variations', function () {10 var variation;11 beforeEach(function () {12 variation = new Variations();13 variation.source = {14 data: {}15 };16 });17 it('checks that "serializeData" serializes data', function () {18 var matrix = [19 {20 name: 'Product1',21 attributes: 'Color: black',22 price: 10023 },24 {25 name: 'Product2',26 attributes: 'Color: red',27 price: 5028 },29 {30 name: 'Product3',31 attributes: 'Color: white',32 price: 2033 }34 ],35 ids = [1, 2, 3],36 resultMatrix = JSON.stringify(matrix),37 resultIds = JSON.stringify(ids);38 variation.source.data['configurable-matrix'] = matrix;39 variation.source.data['associated_product_ids'] = ids;40 variation.serializeData();41 expect(variation.source.data['configurable-matrix']).toEqual(matrix);42 expect(variation.source.data['associated_product_ids']).toEqual(ids);43 expect(variation.source.data['configurable-matrix-serialized']).toEqual(resultMatrix);44 expect(variation.source.data['associated_product_ids_serialized']).toEqual(resultIds);45 });46 it('checks that "serializeData" uses old data if there is no data to serialize', function () {47 var matrix = [48 {49 name: 'Product4',50 attributes: 'Color: grey',51 price: 552 },53 {54 name: 'Product5',55 attributes: 'Color: pink',56 price: 7057 },58 {59 name: 'Product6',60 attributes: 'Color: brown',61 price: 3062 }63 ],64 ids = [4, 5, 6],65 resultMatrix = JSON.stringify(matrix),66 resultIds = JSON.stringify(ids);67 variation.source.data['configurable-matrix-serialized'] = JSON.stringify(matrix);68 variation.source.data['associated_product_ids_serialized'] = JSON.stringify(ids);69 variation.serializeData();70 expect(variation.source.data['configurable-matrix-serialized']).toEqual(resultMatrix);71 expect(variation.source.data['associated_product_ids_serialized']).toEqual(resultIds);72 });73 it('checks that "serializeData" works correctly if we have new data to be serialized', function () {74 var matrix = [75 {76 name: 'Product7',77 attributes: 'Color: yellow',78 price: 1079 },80 {81 name: 'Product8',82 attributes: 'Color: green',83 price: 20084 },85 {86 name: 'Product9',87 attributes: 'Color: blue',88 price: 50089 }90 ],91 ids = [7, 8, 9],92 resultMatrix = JSON.stringify(matrix),93 resultIds = JSON.stringify(ids);94 variation.source.data['configurable-matrix'] = matrix;95 variation.source.data['associated_product_ids'] = ids;96 variation.source.data['configurable-matrix-serialized'] = JSON.stringify(['some old data']);97 variation.source.data['associated_product_ids_serialized'] = JSON.stringify(['some old data']);98 variation.serializeData();99 expect(variation.source.data['configurable-matrix']).toEqual(matrix);100 expect(variation.source.data['associated_product_ids']).toEqual(ids);101 expect(variation.source.data['configurable-matrix-serialized']).toEqual(resultMatrix);102 expect(variation.source.data['associated_product_ids_serialized']).toEqual(resultIds);103 });104 it('checks that "unserializeData" unserializes data', function () {105 var matrixString = '[{"name":"Small Product","attributes":"Size: small","price":5.5},' +106 '{"name":"Medium Product","attributes":"Size: medium","price":10.99},' +107 '{"name":"Large Product","attributes":"Size: large","price":25}]',108 idString = '[100, 101, 102]',109 resultMatrix = JSON.parse(matrixString),110 resultIds = JSON.parse(idString);111 variation.source.data['configurable-matrix-serialized'] = matrixString;112 variation.source.data['associated_product_ids_serialized'] = idString;113 variation.unserializeData();114 expect(variation.source.data['configurable-matrix-serialized']).toBeUndefined();115 expect(variation.source.data['associated_product_ids_serialized']).toBeUndefined();116 expect(variation.source.data['configurable-matrix']).toEqual(resultMatrix);117 expect(variation.source.data['associated_product_ids']).toEqual(resultIds);118 });119 it('checks that "serializeData" and "unserializeData" give proper result', function () {120 var matrix = [121 {122 name: 'Small Product',123 attributes: 'Size: small',124 price: 5.50125 },126 {127 name: 'Medium Product',128 attributes: 'Size: medium',129 price: 10.99130 },131 {132 name: 'Large Product',133 attributes: 'Size: large',134 price: 25135 }136 ],137 ids = [1, 2, 3],138 resultMatrix = JSON.stringify(matrix),139 resultIds = JSON.stringify(ids);140 variation.source.data['configurable-matrix'] = matrix;141 variation.source.data['associated_product_ids'] = ids;142 variation.serializeData();143 expect(variation.source.data['configurable-matrix']).toEqual(matrix);144 expect(variation.source.data['associated_product_ids']).toEqual(ids);145 expect(variation.source.data['configurable-matrix-serialized']).toEqual(resultMatrix);146 expect(variation.source.data['associated_product_ids_serialized']).toEqual(resultIds);147 variation.unserializeData();148 expect(variation.source.data['configurable-matrix']).toEqual(matrix);149 expect(variation.source.data['associated_product_ids']).toEqual(ids);150 expect(variation.source.data['configurable-matrix-serialized']).toBeUndefined();151 expect(variation.source.data['associated_product_ids_serialized']).toBeUndefined();152 });153 });...
autoScrape.js
Source:autoScrape.js
1/////////////////////////////////////////////////////////////////////2// Auto scrapes Spotify artist data with user determined time interval3/////////////////////////////////////////////////////////////////////4// const inquirer = require('inquirer');5const { Sequelize } = require("sequelize");6const db = require("../models");7const spotify = require("./scrape.js");8/////////////////////////////////////////////9/// Put your sql database password below! ///10/////////////////////////////////////////////11const sequelize = new Sequelize(12 process.env.DB_NAME,13 process.env.DB_USERNAME,14 process.env.DB_PASSWORD,15 {16 host: process.env.HOST,17 dialect: "mysql"18 }19);20// Initial Spotify artist ID determined to begin the auto scraping with related artists21let initialArtistID = "2xvtxDNInKDV4AvGmjw6d1";22// Array idsToDo[] for every spotify artist id you wish to scrape23// these will be used if a scraped artist has no genre tags24// or if all related artists of a scraped artist are already in the database.25// Important: the final location of the array should contain 'done', this location26// will not be used as a scraped Spotify id.27//define idsToDo28let idsToDo = [];29sequelize30 .query("SELECT distinct artistID FROM spotify_db.idstoscrape;", {31 type: sequelize.QueryTypes.SELECT32 })33 .then(function(currentArtistIDs) {34 idsToDo = currentArtistIDs;35 });36console.log(`37 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~38 | « « | Spotify Artist Auto Web Scraper - Using node.js, puppeteer, cheerio, and sequelize | » » |39 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`);40async function RecursiveInsertRecord(scrapedata) {41 console.log(`Next Spotify Artist (id: ${scrapedata.artist_ID}) scrapedata:`);42 // Checks if Spotify artist id is empty/undefined43 if (44 !Array.isArray(scrapedata.artist_genres) ||45 !scrapedata.artist_genres.length46 ) {47 console.log(48 `artist_genres of (${scrapedata.artist_name}: ${scrapedata.artist_ID}) is empty.`49 );50 if (!Array.isArray(idsToDo) || !idsToDo.length) {51 // pre-populated id list array is empty52 console.log(`idsToDo[] list is now empty. Scraping is now complete.`);53 } else {54 // pre-populated id list array is not empty55 console.log(56 `Artist genre or city data is "undefined", Moving to next id in idsToDo[] object. --> ${idsToDo[0]}`57 );58 let nextID = idsToDo[0].artistID;59 spotify(idsToDo[0].artistID, RecursiveInsertRecord);60 idsToDo.shift();61 }62 }63 // Will populate sql table if genres are defined64 else {65 // First for loop runs # of times depending on length of Spotify Artist's genre tags66 if (67 typeof scrapedata.cityData === "undefined" ||68 typeof scrapedata.artist_genres === "undefined"69 ) {70 if (!Array.isArray(idsToDo) || !idsToDo.length) {71 // pre-populated id list array is empty72 console.log(`idsToDo[] list is now empty. Scraping is now complete.`);73 } else {74 // pre-populated id list array is not empty75 console.log(76 `Artist genre or city data is "undefined", Moving to next id in idsToDo[] object. --> ${idsToDo[0].artistID}`77 );78 let nextID = idsToDo[0].artistID;79 spotify(idsToDo[0].artistID, RecursiveInsertRecord);80 idsToDo.shift();81 }82 } else {83 for (let j = 0; j < scrapedata.artist_genres.length; j++) {84 // Second for loop runs # of times depending on length of Spotify cityData length85 for (let i = 0; i < scrapedata.cityData.length; i++) {86 let record = {87 artist_ID: scrapedata.artist_ID,88 artist_name: scrapedata.artist_name,89 artist_genres: scrapedata.artist_genres[j],90 country: scrapedata.cityData[i].country,91 city: scrapedata.cityData[i].city,92 listeners: scrapedata.cityData[i].listeners93 };94 await db.Spotify.create(record).then(function(results) {95 // `results` here would be the newly created table with unique artist and location information96 // res.json(results);97 });98 }99 }100 // findRelatedArtistID() finds the remaining related artist ID's,101 findRelatedArtistID(scrapedata.relatedArtistIDs);102 }103 }104}105spotify(initialArtistID, RecursiveInsertRecord);106// function to return related artist ID that has not a duplicate of current artist id's107function findRelatedArtistID(relatedArtistIDs) {108 // Querys the database to find all of the current artist id's we have scraped109 // will be used to avoid duplicates110 sequelize111 .query("SELECT distinct artist_ID FROM spotify_db.spotifies;", {112 type: sequelize.QueryTypes.SELECT113 })114 .then(function(currentArtistIDs) {115 console.log(`Current Spotify artist id's in db`);116 console.log(currentArtistIDs);117 let idsToCheck = relatedArtistIDs;118 for (let i = 0; i < currentArtistIDs.length; i++) {119 // runs n+1 times120 for (let j = 0; j < relatedArtistIDs.length; j++) {121 // runs n times122 // checks if dup123 if (relatedArtistIDs[j].id === currentArtistIDs[i].artist_ID) {124 idsToCheck.splice(j, 1);125 console.log(`Remaining unused id's from Spotify related artist`);126 console.log(idsToCheck);127 }128 }129 }130 // exit for loop131 if (!Array.isArray(idsToCheck) || !idsToCheck.length) {132 // if idsToCheck is empty133 if (!Array.isArray(idsToDo) || !idsToDo.length) {134 // pre-populated id list array is empty135 console.log(`idsToDo[] list is now empty. Scraping is now complete.`);136 } else {137 // pre-populated id list array is not empty138 console.log(139 `idsToCheck is empty. Moving to next id in idsToDo[] object. --> ${idsToDo[0].artistID}`140 );141 console.log(`idsToDo length: ${idsToDo.length}`);142 spotify(idsToDo[0].artistID, RecursiveInsertRecord);143 idsToDo.shift();144 }145 } else {146 // if idsToCheck is not empty147 console.log(148 `Id's remaining are non-duplicates, choosing location 0: ${idsToCheck[0].id}`149 );150 console.log(`idsToDo length: ${idsToDo.length}`);151 spotify(idsToCheck[0].id, RecursiveInsertRecord);152 }153 });...
narrow_unread.js
Source:narrow_unread.js
...28}29function assert_unread_info(expected) {30 assert.deepEqual(narrow_state.get_first_unread_info(), expected);31}32function candidate_ids() {33 return narrow_state._possible_unread_message_ids();34}35run_test("get_unread_ids", () => {36 unread.declare_bankruptcy();37 narrow_state.reset_current_filter();38 let unread_ids;39 let terms;40 const sub = {41 name: "My Stream",42 stream_id: 55,43 };44 const stream_msg = {45 id: 101,46 type: "stream",47 stream_id: sub.stream_id,48 topic: "my topic",49 unread: true,50 mentioned: true,51 mentioned_me_directly: true,52 };53 const private_msg = {54 id: 102,55 type: "private",56 unread: true,57 display_recipient: [{id: alice.user_id}],58 };59 message_store.get = (msg_id) => {60 if (msg_id === stream_msg.id) {61 return stream_msg;62 } else if (msg_id === private_msg.id) {63 return private_msg;64 }65 throw new Error("unexpected id");66 };67 stream_data.add_sub(sub);68 unread_ids = candidate_ids();69 assert.equal(unread_ids, undefined);70 terms = [{operator: "search", operand: "whatever"}];71 set_filter(terms);72 unread_ids = candidate_ids();73 assert.equal(unread_ids, undefined);74 assert_unread_info({flavor: "cannot_compute"});75 terms = [{operator: "bogus_operator", operand: "me@example.com"}];76 set_filter(terms);77 unread_ids = candidate_ids();78 assert.deepEqual(unread_ids, []);79 assert_unread_info({flavor: "not_found"});80 terms = [{operator: "stream", operand: "bogus"}];81 set_filter(terms);82 unread_ids = candidate_ids();83 assert.deepEqual(unread_ids, []);84 terms = [{operator: "stream", operand: sub.name}];85 set_filter(terms);86 unread_ids = candidate_ids();87 assert.deepEqual(unread_ids, []);88 assert_unread_info({flavor: "not_found"});89 unread.process_loaded_messages([stream_msg]);90 unread_ids = candidate_ids();91 assert.deepEqual(unread_ids, [stream_msg.id]);92 assert_unread_info({93 flavor: "found",94 msg_id: stream_msg.id,95 });96 terms = [97 {operator: "stream", operand: "bogus"},98 {operator: "topic", operand: "my topic"},99 ];100 set_filter(terms);101 unread_ids = candidate_ids();102 assert.deepEqual(unread_ids, []);103 terms = [104 {operator: "stream", operand: sub.name},105 {operator: "topic", operand: "my topic"},106 ];107 set_filter(terms);108 unread_ids = candidate_ids();109 assert.deepEqual(unread_ids, [stream_msg.id]);110 terms = [{operator: "is", operand: "mentioned"}];111 set_filter(terms);112 unread_ids = candidate_ids();113 assert.deepEqual(unread_ids, [stream_msg.id]);114 terms = [{operator: "sender", operand: "me@example.com"}];115 set_filter(terms);116 // note that our candidate ids are just "all" ids now117 unread_ids = candidate_ids();118 assert.deepEqual(unread_ids, [stream_msg.id]);119 // this actually does filtering120 assert_unread_info({flavor: "not_found"});121 terms = [{operator: "pm-with", operand: "alice@example.com"}];122 set_filter(terms);123 unread_ids = candidate_ids();124 assert.deepEqual(unread_ids, []);125 unread.process_loaded_messages([private_msg]);126 unread_ids = candidate_ids();127 assert.deepEqual(unread_ids, [private_msg.id]);128 assert_unread_info({129 flavor: "found",130 msg_id: private_msg.id,131 });132 terms = [{operator: "is", operand: "private"}];133 set_filter(terms);134 unread_ids = candidate_ids();135 assert.deepEqual(unread_ids, [private_msg.id]);136 // For a negated search, our candidate ids will be all137 // unread messages, even ones that don't pass the filter.138 terms = [{operator: "is", operand: "private", negated: true}];139 set_filter(terms);140 unread_ids = candidate_ids();141 assert.deepEqual(unread_ids, [stream_msg.id, private_msg.id]);142 terms = [{operator: "pm-with", operand: "bob@example.com"}];143 set_filter(terms);144 unread_ids = candidate_ids();145 assert.deepEqual(unread_ids, []);146 terms = [{operator: "is", operand: "starred"}];147 set_filter(terms);148 unread_ids = candidate_ids();149 assert.deepEqual(unread_ids, []);150 terms = [{operator: "search", operand: "needle"}];151 set_filter(terms);152 assert_unread_info({153 flavor: "cannot_compute",154 });155 narrow_state.reset_current_filter();156 blueslip.expect("error", "unexpected call to get_first_unread_info");157 assert_unread_info({158 flavor: "cannot_compute",159 });160});161run_test("defensive code", (override) => {162 // Test defensive code. We actually avoid calling...
index.js
Source:index.js
1import { OPERATIONS_IDS } from 'echojs-lib';2import transformTransferOperations from './specifics.ops/transfer';3import transformAccountOperations from './specifics.ops/account';4import transformAssetOperations from './specifics.ops/asset';5import transformProposalOperations from './specifics.ops/proposal';6import transformCommitteeOperations from './specifics.ops/committee';7import transformVestingOperations from './specifics.ops/vesting.balance';8import transformContractOperations from './specifics.ops/contract';9import transformSidechainOperations from './specifics.ops/sidechain';10import transformDidOperations from './specifics.ops/did';11export const transformOperationDataByType = async (opNumber, data) => {12 switch (opNumber) {13 case OPERATIONS_IDS.TRANSFER:14 case OPERATIONS_IDS.TRANSFER_TO_ADDRESS:15 case OPERATIONS_IDS.OVERRIDE_TRANSFER:16 return transformTransferOperations(opNumber, data);17 case OPERATIONS_IDS.ACCOUNT_CREATE:18 case OPERATIONS_IDS.ACCOUNT_UPDATE:19 case OPERATIONS_IDS.ACCOUNT_WHITELIST:20 case OPERATIONS_IDS.ACCOUNT_ADDRESS_CREATE:21 case OPERATIONS_IDS.EVM_ADDRESS_REGISTER:22 case OPERATIONS_IDS.BLOCK_REWARD:23 return transformAccountOperations(opNumber, data);24 case OPERATIONS_IDS.ASSET_CREATE:25 case OPERATIONS_IDS.ASSET_UPDATE:26 case OPERATIONS_IDS.ASSET_UPDATE_BITASSET:27 case OPERATIONS_IDS.ASSET_UPDATE_FEED_PRODUCERS:28 case OPERATIONS_IDS.ASSET_ISSUE:29 case OPERATIONS_IDS.ASSET_RESERVE:30 case OPERATIONS_IDS.ASSET_FUND_FEE_POOL:31 case OPERATIONS_IDS.ASSET_PUBLISH_FEED:32 case OPERATIONS_IDS.ASSET_CLAIM_FEES:33 return transformAssetOperations(opNumber, data);34 case OPERATIONS_IDS.PROPOSAL_CREATE:35 case OPERATIONS_IDS.PROPOSAL_UPDATE:36 case OPERATIONS_IDS.PROPOSAL_DELETE:37 return transformProposalOperations(opNumber, data);38 case OPERATIONS_IDS.COMMITTEE_MEMBER_CREATE:39 case OPERATIONS_IDS.COMMITTEE_MEMBER_UPDATE:40 case OPERATIONS_IDS.COMMITTEE_MEMBER_UPDATE_GLOBAL_PARAMETERS:41 case OPERATIONS_IDS.COMMITTEE_MEMBER_ACTIVATE:42 case OPERATIONS_IDS.COMMITTEE_MEMBER_DEACTIVATE:43 case OPERATIONS_IDS.COMMITTEE_FROZEN_BALANCE_DEPOSIT:44 case OPERATIONS_IDS.COMMITTEE_FROZEN_BALANCE_WITHDRAW:45 return transformCommitteeOperations(opNumber, data);46 case OPERATIONS_IDS.VESTING_BALANCE_CREATE:47 case OPERATIONS_IDS.VESTING_BALANCE_WITHDRAW:48 case OPERATIONS_IDS.BALANCE_CLAIM:49 case OPERATIONS_IDS.BALANCE_FREEZE:50 case OPERATIONS_IDS.BALANCE_UNFREEZE:51 case OPERATIONS_IDS.REQUEST_BALANCE_UNFREEZE:52 return transformVestingOperations(opNumber, data);53 case OPERATIONS_IDS.CONTRACT_CREATE:54 case OPERATIONS_IDS.CONTRACT_CALL:55 case OPERATIONS_IDS.CONTRACT_INTERNAL_CREATE:56 case OPERATIONS_IDS.CONTRACT_INTERNAL_CALL:57 case OPERATIONS_IDS.CONTRACT_SELFDESTRUCT:58 case OPERATIONS_IDS.CONTRACT_UPDATE:59 case OPERATIONS_IDS.CONTRACT_FUND_POOL:60 case OPERATIONS_IDS.CONTRACT_WHITELIST:61 return transformContractOperations(opNumber, data);62 case OPERATIONS_IDS.SIDECHAIN_ETH_CREATE_ADDRESS:63 case OPERATIONS_IDS.SIDECHAIN_ETH_APPROVE_ADDRESS:64 case OPERATIONS_IDS.SIDECHAIN_ETH_DEPOSIT:65 case OPERATIONS_IDS.SIDECHAIN_ETH_SEND_DEPOSIT:66 case OPERATIONS_IDS.SIDECHAIN_ERC20_APPROVE_TOKEN_WITHDRAW:67 case OPERATIONS_IDS.SIDECHAIN_ERC20_ISSUE:68 case OPERATIONS_IDS.SIDECHAIN_ERC20_BURN:69 case OPERATIONS_IDS.SIDECHAIN_ETH_WITHDRAW:70 case OPERATIONS_IDS.SIDECHAIN_ETH_SEND_WITHDRAW:71 case OPERATIONS_IDS.SIDECHAIN_ETH_APPROVE_WITHDRAW:72 case OPERATIONS_IDS.SIDECHAIN_ETH_UPDATE_CONTRACT_ADDRESS:73 case OPERATIONS_IDS.SIDECHAIN_ISSUE:74 case OPERATIONS_IDS.SIDECHAIN_BURN:75 case OPERATIONS_IDS.SIDECHAIN_ERC20_REGISTER_TOKEN:76 case OPERATIONS_IDS.SIDECHAIN_ERC20_DEPOSIT_TOKEN:77 case OPERATIONS_IDS.SIDECHAIN_ERC20_SEND_DEPOSIT_TOKEN:78 case OPERATIONS_IDS.SIDECHAIN_ERC20_WITHDRAW_TOKEN:79 case OPERATIONS_IDS.SIDECHAIN_ERC20_SEND_WITHDRAW_TOKEN:80 case OPERATIONS_IDS.SIDECHAIN_BTC_CREATE_ADDRESS:81 case OPERATIONS_IDS.SIDECHAIN_BTC_CREATE_INTERMEDIATE_DEPOSIT:82 case OPERATIONS_IDS.SIDECHAIN_BTC_INTERMEDIATE_DEPOSIT:83 case OPERATIONS_IDS.SIDECHAIN_BTC_DEPOSIT:84 case OPERATIONS_IDS.SIDECHAIN_BTC_WITHDRAW:85 case OPERATIONS_IDS.SIDECHAIN_BTC_AGGREGATE:86 case OPERATIONS_IDS.SIDECHAIN_BTC_APPROVE_AGGREGATE:87 case OPERATIONS_IDS.SIDECHAIN_STAKE_ETH_UPDATE:88 case OPERATIONS_IDS.SIDECHAIN_BTC_CREATE_STAKE_SCRIPT:89 case OPERATIONS_IDS.SIDECHAIN_STAKE_BTC_UPDATE:90 case OPERATIONS_IDS.SIDECHAIN_ETH_SPV_CREATE:91 case OPERATIONS_IDS.SIDECHAIN_ETH_SPV_ADD_MISSED_TX_RECEIPT:92 case OPERATIONS_IDS.SIDECHAIN_BTC_SPV_CREATE:93 case OPERATIONS_IDS.SIDECHAIN_BTC_SPV_ADD_MISSED_TX_RECEIPT:94 case OPERATIONS_IDS.SIDECHAIN_SPV_EXCHANGE_EXCESS_FUNDS:95 case OPERATIONS_IDS.SIDECHAIN_ERC20_REGISTER_CONTRACT_OPERATION:96 case OPERATIONS_IDS.SIDECHAIN_ERC20_TRANSFER_ASSET:97 return transformSidechainOperations(opNumber, data);98 case OPERATIONS_IDS.DID_CREATE_OPERATION:99 case OPERATIONS_IDS.DID_UPDATE_OPERATION:100 case OPERATIONS_IDS.DID_DELETE_OPERATION:101 return transformDidOperations(opNumber, data);102 default:103 return transformTransferOperations(0, data);104 }...
Arbitraries.ts
Source:Arbitraries.ts
1import { Gene, TestUniverse } from '@ephox/boss';2import { Arr } from '@ephox/katamari';3import Jsc from '@ephox/wrap-jsverify';4const getIds = function (item: Gene, predicate: (g: Gene) => boolean): string[] {5 const rest = Arr.bind(item.children || [], function (id) { return getIds(id, predicate); });6 const self = predicate(item) && item.id !== 'root' ? [ item.id ] : [];7 return self.concat(rest);8};9const textIds = function (universe: TestUniverse) {10 return getIds(universe.get(), universe.property().isText);11};12export interface ArbTextIds {13 startId: string;14 textIds: string[];15}16const arbTextIds = function (universe: TestUniverse) {17 const ids = textIds(universe);18 return Jsc.elements(textIds(universe)).smap(function (id: string): ArbTextIds {19 return {20 startId: id,21 textIds: ids22 };23 }, function (obj: ArbTextIds) {24 return obj.startId;25 });26};27export interface ArbIds {28 startId: string;29 ids: string[];30}31const arbIds = function (universe: TestUniverse, predicate: (g: Gene) => boolean) {32 const ids = getIds(universe.get(), predicate);33 return Jsc.elements(ids).smap(function (id: string): ArbIds {34 return {35 startId: id,36 ids37 };38 }, function (obj: ArbIds) {39 return obj.startId;40 }, function (obj: ArbIds) {41 return '[id :: ' + obj.startId + ']';42 });43};44export interface ArbRangeIds {45 startId: string;46 finishId: string;47 ids: string[];48}49const arbRangeIds = function (universe: TestUniverse, predicate: (g: Gene) => boolean) {50 const ids = getIds(universe.get(), predicate);51 const generator = Jsc.integer(0, ids.length - 1).generator.flatMap(function (startIndex: number) {52 return Jsc.integer(startIndex, ids.length - 1).generator.map(function (finishIndex: number): ArbRangeIds {53 return {54 startId: ids[startIndex],55 finishId: ids[finishIndex],56 ids57 };58 });59 });60 return Jsc.bless({61 generator62 });63};...
Using AI Code Generation
1var devicefarmer = require('devicefarmer-stf');2var ids = devicefarmer.ids;3ids(function(err, devices) {4 if (err) {5 console.log(err);6 } else {7 console.log(devices);8 }9});10var devicefarmer = require('devicefarmer-stf');11var devices = devicefarmer.devices;12devices(function(err, devices) {13 if (err) {14 console.log(err);15 } else {16 console.log(devices);17 }18});19var devicefarmer = require('devicefarmer-stf');20var devices = devicefarmer.devices;21devices(function(err, devices) {22 if (err) {23 console.log(err);24 } else {25 console.log(devices);26 }27});28var devicefarmer = require('devicefarmer-stf');29var devices = devicefarmer.devices;30devices(function(err, devices) {31 if (err) {32 console.log(err);33 } else {34 console.log(devices);35 }36});37var devicefarmer = require('devicefarmer-stf');38var devices = devicefarmer.devices;39devices(function(err, devices) {40 if (err) {41 console.log(err);42 } else {43 console.log(devices);44 }45});46var devicefarmer = require('devicefarmer-stf');47var devices = devicefarmer.devices;48devices(function(err, devices) {49 if (err) {50 console.log(err);51 } else {52 console.log(devices);53 }54});55var devicefarmer = require('devicefarmer-stf');56var devices = devicefarmer.devices;57devices(function(err, devices) {58 if (err) {59 console.log(err);60 } else {61 console.log(devices);62 }63});
Using AI Code Generation
1var devicefarmer = require('devicefarmer-stf-client');2var devices = devicefarmer.devices;3console.log(devices);4var devicefarmer = require('devicefarmer-stf-client');5var ids = devicefarmer.ids;6console.log(ids);7 throw err;8at Function.Module._resolveFilename (module.js:469:15)9at Function.Module._load (module.js:417:25)10at Module.require (module.js:497:17)11at require (internal/module.js:20:19)12at Object.<anonymous> (D:\Projects\DeviceFarmer\test.js:1:13)13at Module._compile (module.js:570:32)14at Object.Module._extensions..js (module.js:579:10)15at Module.load (module.js:487:32)16at tryModuleLoad (module.js:446:12)17at Function.Module._load (module.js:438:3)
Using AI Code Generation
1var id = require('devicefarmer-stf-client').ids;2var device = require('devicefarmer-stf-client').devices;3var util = require('devicefarmer-stf-client').util;4var util = require('devicefarmer-stf-client').util;5util.getDevices(function(err, devices) {6 if (err) {7 console.log(err);8 } else {9 console.log(devices);10 }11});12util.getDevice('deviceid', function(err, device) {13 if (err) {14 console.log(err);15 } else {16 console.log(device);17 }18});19util.getDeviceBySerial('serial', function(err, device) {20 if (err) {21 console.log(err);22 } else {23 console.log(device);24 }25});26util.getDeviceByOwner('owner', function(err, device) {27 if (err) {28 console.log(err);29 } else {30 console.log(device);31 }32});33util.getDeviceByProvider('provider', function(err, device) {34 if (err) {35 console.log(err);36 } else {37 console.log(device);38 }39});40util.getDeviceByGroup('group', function(err, device) {41 if (err) {42 console.log(err);43 } else {44 console.log(device);45 }46});47util.getDeviceByModel('model', function(err, device) {48 if (err) {49 console.log(err);50 } else {51 console.log(device);52 }53});54util.getDeviceByManufacturer('manufacturer', function(err, device) {55 if (err) {56 console.log(err);57 } else {58 console.log(device);59 }60});61util.getDeviceByPlatform('platform', function(err, device) {62 if (err) {63 console.log(err);64 } else {65 console.log(device);66 }67});68util.getDeviceByVersion('version', function(err, device) {69 if (err) {70 console.log(err);71 } else {72 console.log(device);73 }74});75util.getDeviceByProduct('product', function(err, device) {76 if (err) {77 console.log(err);78 } else {79 console.log(device);80 }81});
Using AI Code Generation
1var devicefarmer = require('devicefarmer-stf');2client.getDevices(function(err, devices) {3 if (err) {4 console.error(err);5 } else {6 console.log(devices);7 }8});9client.getDevices({ ids: [ '123456789012345678' ] }, function(err, devices) {10 if (err) {11 console.error(err);12 } else {13 console.log(devices);14 }15});16 at Client._deviceById (/home/rohit/Documents/Nodejs_Projects/DeviceFarm/node_modules/devicefarmer-stf/lib/client.js:173:11)17 at Client._deviceById (/home/rohit/Documents/Nodejs_Projects/DeviceFarm/node_modules/devicefarmer-stf/lib/client.js:173:11)18 at Client._deviceById (/home/rohit/Documents/Nodejs_Projects/DeviceFarm/node_modules/devicefarmer-stf/lib/client.js:173:11)19 at Client._deviceById (/home/rohit/Documents/Nodejs_Projects/DeviceFarm/node_modules/devicefarmer-stf/lib/client.js:173:11)20 at Client._deviceById (/home/rohit/Documents/Nodejs_Projects/DeviceFarm/node_modules/devicefarmer-stf/lib/client.js:173:11)21 at Client._deviceById (/home/rohit/Documents/Nodejs_Projects/DeviceFarm/node_modules/devicefarmer-stf/lib/client.js:173:11)22 at Client._deviceById (/home/rohit/Documents/Nodejs_Projects/DeviceFarm/node_modules/devicefarmer-stf/lib/client.js:173:11)23 at Client._deviceById (/home/rohit/Documents/Nodejs_Projects/DeviceFarm/node_modules/devicefarmer-stf/lib/client.js:173:11)24 at Client._deviceById (/home/rohit/Documents/Nodejs_Projects/DeviceFarm/node_modules/devicefarmer-stf/lib/client.js:173:11)25 at Client._deviceById (/home/rohit/Documents/Nodejs_Projects/DeviceFarm/node_modules/devicefarmer-stf/lib/client.js:173:11)
Using AI Code Generation
1var stf = require('devicefarmer-stf-client');2client.ids(function(err, ids) {3 if (err) {4 console.error(err);5 } else {6 console.log(ids);7 }8});
Using AI Code Generation
1var devicefarmer = require('devicefarmer-stf-client');2var client = devicefarmer.createClient({3});4client.getDevices(function(err, devices) {5 if (err) {6 console.error(err);7 } else {8 console.log(devices);9 }10});11client.getDevicesIds(function(err, devices) {12 if (err) {13 console.error(err);14 } else {15 console.log(devices);16 }17});18{ [Error: connect ECONNREFUSED
Using AI Code Generation
1var stf = require('devicefarmer-stf-api');2var ids = new stf.ids();3ids.getIds(function(err, data) {4 if (err) {5 console.log(err);6 } else {7 console.log(data);8 }9});10var stf = require('devicefarmer-stf-api');11var device = new stf.device();12device.getDevice("R8J7T15B15003140", function(err, data) {13 if (err) {14 console.log(err);15 } else {16 console.log(data);17 }18});19var stf = require('devicefarmer-stf-api');20var devices = new stf.devices();21devices.getDevices(function(err, data) {22 if (err) {23 console.log(err);24 } else {25 console.log(data);26 }27});28var stf = require('devicefarmer-stf-api');29var devices = new stf.devices();30devices.getDevices(function(err, data) {31 if (err) {32 console.log(err);33 } else {34 console.log(data);35 }36});37var stf = require('devicefarmer-stf-api');38var devices = new stf.devices();39devices.getDevices(function(err, data) {40 if (err) {41 console.log(err);42 } else {43 console.log(data);44 }45});46var stf = require('devicefarmer-stf-api');47var devices = new stf.devices();48devices.getDevices(function(err, data) {49 if (err) {50 console.log(err);51 } else {52 console.log(data);53 }54});55var stf = require('devicefarmer-stf-api');56var devices = new stf.devices();57devices.getDevices(function(err, data) {58 if (err) {59 console.log(err);60 } else {
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!