How to use archiveName method in Puppeteer

Best JavaScript code snippet using puppeteer

ArchiveManager.js

Source:ArchiveManager.js Github

copy

Full Screen

1"use strict";2var Buttercup = require("buttercup"),3 StorageInterface = require("__buttercup_web/StorageInterface.js");4var createCredentials = Buttercup.createCredentials,5 DatasourceAdapter = Buttercup.DatasourceAdapter,6 Workspace = Buttercup.Workspace;7var __sharedManager = null;8/**9 * Archive Manager - manages a set of archives for the browser10 */11class ArchiveManager {12 /**13 * Constructor for the manager14 * @param {StorageInterface=} storage Storage interface reference15 */16 constructor(storage) {17 this._archives = {};18 this._storage = storage || StorageInterface;19 }20 /**21 * Archives reference22 * @type {Object}23 */24 get archives() {25 return this._archives;26 }27 /**28 * Archive details for display29 * @typedef {Object} ArchiveDetailsDisplay30 * @property {String} name The name of the item31 * @property {ArchiveStatus} status The status of the item32 * @property {String} type The type of archive connection33 */34 /**35 * Array of archive details ready for display36 * @type {Array.<ArchiveDetailsDisplay>}37 */38 get displayList() {39 const archives = this.archives;40 return Object.keys(archives).map(archiveName => ({41 name: archiveName,42 status: archives[archiveName].status,43 type: archives[archiveName].type44 }));45 }46 /**47 * Storage reference48 * @type {StorageInterface}49 */50 get storage() {51 return this._storage;52 }53 /**54 * Stored archive entry55 * @typedef {Object} ManagedArchiveItem56 * @property {ArchiveStatus} status The status of the item57 * @property {Workspace|undefined} workspace Reference to the workspace (undefined if locked)58 * @property {Credentials|String} credentials Reference to Credentials instance (encrypted string if locked)59 * @property {String|undefined} password The master password (undefined if locked)60 */61 /**62 * Array of unlocked archive items63 * @type {Array.<ManagedArchiveItem>}64 */65 get unlockedArchives() {66 const archives = this.archives;67 return Object.keys(archives)68 .map(archiveName => Object.assign({ name: archiveName }, archives[archiveName]))69 .filter(details => details.status === ArchiveManager.ArchiveStatus.UNLOCKED);70 }71 /**72 * Add an archive to the manager73 * @param {String} archiveName A unique name for the item74 * @param {Workspace} workspace The workspace that holds the archive, datasource etc.75 * @param {Credentials} credentials The credentials for remote storage etc.76 * (these should also already hold datasource meta information)77 * @param {String} masterPassword The master password78 */79 addArchive(archiveName, workspace, credentials, masterPassword) {80 if (this._archives[archiveName]) {81 throw new Error(`Archive already exists: ${archiveName}`);82 }83 this.archives[archiveName] = {84 status: ArchiveManager.ArchiveStatus.UNLOCKED,85 workspace,86 credentials,87 password: masterPassword,88 type: credentials.type89 };90 }91 /**92 * Check if an item is locked93 * @param {String} archiveName The name of the item94 * @returns {Boolean} True if locked95 * @throws {Error} Throws if the item is not found96 */97 isLocked(archiveName) {98 if (!this.archives[archiveName]) {99 throw new Error(`Archive not found: ${archiveName}`);100 }101 return this.archives[archiveName].status === ArchiveManager.ArchiveStatus.LOCKED;102 }103 /**104 * Load the manager state105 * Used when the page loads to restore the archive items list (all are locked at106 * this stage).107 */108 loadState() {109 var loadedData = this.storage.getData("archiveManager", { archives: {} });110 this._archives = {};111 for (const archiveName in loadedData.archives) {112 if (loadedData.archives.hasOwnProperty(archiveName)) {113 const { content, type } = loadedData.archives[archiveName];114 this.archives[archiveName] = {115 status: ArchiveManager.ArchiveStatus.LOCKED,116 credentials: content,117 type118 };119 }120 }121 }122 /**123 * Lock an item124 * @param {String} archiveName The name of the item to lock125 * @throws {Error} Throws if the item is not found126 * @throws {Error} Throws if the item is already locked127 * @throws {Error} Throws if the item is currently being processed128 * @returns {Promise} A promise that resolves when the item is locked129 */130 lock(archiveName) {131 if (!this.archives[archiveName]) {132 throw new Error(`Archive not found: ${archiveName}`);133 }134 if (this.isLocked(archiveName)) {135 throw new Error(`Archive already locked: ${archiveName}`);136 }137 let details = this.archives[archiveName];138 if (details.status === ArchiveManager.ArchiveStatus.PROCESSING) {139 throw new Error(`Archive is in processing state: ${archiveName}`);140 }141 details.status = ArchiveManager.ArchiveStatus.PROCESSING;142 return details.credentials143 .toSecureString(details.password)144 .then(function(encContent) {145 details.credentials = encContent;146 delete details.workspace;147 delete details.password;148 details.status = ArchiveManager.ArchiveStatus.LOCKED;149 });150 }151 /**152 * Remove an archive by name153 * @param {String} archiveName The name of the archive to remove154 * @returns {Boolean} True if deleted, false if not found155 */156 removeArchive(archiveName) {157 if (this._archives.hasOwnProperty(archiveName)) {158 delete this._archives[archiveName];159 return true;160 }161 return false;162 }163 /**164 * Save the state of the manager to the storage165 * @returns {Promise} A promise that resolves once the state has been saved166 */167 saveState() {168 var packet = {169 archives: {}170 },171 delayed = [Promise.resolve()];172 Object.keys(this.archives).forEach((archiveName) => {173 const archiveDetails = this.archives[archiveName];174 if (archiveDetails.status === ArchiveManager.ArchiveStatus.LOCKED) {175 packet.archives[archiveName] = {176 content: archiveDetails.credentials,177 type: archiveDetails.type178 };179 } else {180 delayed.push(181 archiveDetails.credentials182 .toSecureString(archiveDetails.password)183 .then(function handledConvertedContent(content) {184 packet.archives[archiveName] = {185 content,186 type: archiveDetails.type187 };188 })189 );190 }191 });192 return Promise193 .all(delayed)194 .then(() => {195 this.storage.setData("archiveManager", packet);196 });197 }198 /**199 * Unlock a locked item200 * @param {String} archiveName The name of the item to unlock201 * @param {String} password The master password of the item to unlock202 * @throws {Error} Throws if the item is not locked203 * @returns {Promise} A promise that resolves when the item is unlocked204 */205 unlock(archiveName, password) {206 var archiveDetails = this.archives[archiveName];207 if (!this.isLocked(archiveName)) {208 return Promise.resolve(archiveDetails);209 }210 archiveDetails.status = ArchiveManager.ArchiveStatus.PROCESSING;211 return createCredentials212 .fromSecureString(archiveDetails.credentials, password)213 .then((credentials) => {214 if (!credentials) {215 return Promise.reject(new Error("Failed unlocking credentials: " + archiveName));216 }217 archiveDetails.credentials = credentials;218 archiveDetails.password = password;219 let datasourceInfo = JSON.parse(credentials.getValueOrFail("datasource")),220 ds = DatasourceAdapter.objectToDatasource(datasourceInfo, credentials);221 if (!ds) {222 throw new Error("Failed creating datasource - possible corrupt credentials");223 }224 return Promise.all([225 ds.load(createCredentials.fromPassword(password)),226 Promise.resolve(ds)227 ]);228 })229 .then(([archive, datasource] = []) => {230 const workspace = new Workspace();231 workspace.setPrimaryArchive(archive, datasource, createCredentials.fromPassword(password));232 archiveDetails.workspace = workspace;233 archiveDetails.status = ArchiveManager.ArchiveStatus.UNLOCKED;234 })235 .catch(function(err) {236 archiveDetails.status = ArchiveManager.ArchiveStatus.LOCKED;237 throw err;238 });239 }240 /**241 * Update workspaces that are unlocked242 * @returns {Promise} A promise that resolves after updating all unlocked workspaces243 */244 updateUnlocked() {245 return Promise.all(246 this.unlockedArchives.map(item => item.workspace247 .localDiffersFromRemote()248 .then(function(differs) {249 return differs ?250 item.workspace.mergeSaveablesFromRemote().then(() => true) :251 false;252 })253 .then(function(save) {254 // all up to date255 return save ?256 item.workspace.save() :257 null;258 })259 )260 );261 }262}263/**264 * Stored archive status265 * @name ArchiveStatus266 * @enum267 * @memberof ArchiveManager268 * @static269 */270ArchiveManager.ArchiveStatus = {271 LOCKED: "locked",272 UNLOCKED: "unlocked",273 PROCESSING: "processing"274};275/**276 * Get the singleton shared instance277 * @memberof ArchiveManager278 * @static279 * @returns {ArchiveManager} The shared instance280 */281ArchiveManager.getSharedManager = function getSharedManager() {282 if (__sharedManager === null) {283 __sharedManager = new ArchiveManager();284 __sharedManager.loadState();285 }286 return __sharedManager;287};...

Full Screen

Full Screen

Contenedor.js

Source:Contenedor.js Github

copy

Full Screen

1import fs from 'fs';2import __dirname from '../utils.js';3// const productsURL = __dirname+'/files/products.txt'4class Contenedor {5 constructor(archiveName){6 this.archiveName = archiveName7 }8 9 async saveChat(message){10 try{11 let data = await fs.promises.readFile(__dirname+`/files/${this.archiveName}.txt`, 'utf-8')12 let chat = JSON.parse(data)13 chat.push(message)14 await fs.promises.writeFile(__dirname+`/files/${this.archiveName}.txt`, JSON.stringify(chat, null, 2))15 io.emit('messagelog', chat)16 }catch(err){17 try{18 await fs.promises.writeFile(__dirname+`/files/${this.archiveName}.txt`, JSON.stringify([data], null, 2))19 io.emit('messagelog', [message])20 }21 catch(err){22 console.log(`No se pudo escribir el archivo ${err}`)23 return {status:"error", message:"Error al agregar chat "+err}24 }25 }26 }27 28 async save(product){29 try{30 31 let data = await fs.promises.readFile(__dirname+`/files/${this.archiveName}.txt`, 'utf-8')32 let products = JSON.parse(data)33 34 if(products.some(prod => prod.name === product.name)){35 console.log(`${JSON.stringify(product.name)} El producto ya existe en ${this.archiveName}`)36 return {status:"error", message:"Error, este producto ya existe."}37 }else{38 let data = Object.assign({39 id: products.length + 1,40 timestamp: Date.now(),41 name: product.name,42 description: product.description || "",43 code:product.code || "",44 price: product.price, 45 thumbnail: product.thumbnail,46 stock: product.stock || 0 47 })48 49 products.push(data)50 try{51 await fs.promises.writeFile(__dirname+`/files/${this.archiveName}.txt`, JSON.stringify(products, null, 2))52 console.log(`${product.name} fue agregado a ${__dirname}/files/${this.archiveName}.txt`)53 return {status:"success", message:"Producto Agregado correctamente."}54 }catch(err){55 console.log(`No se pudo agregar el producto ${err}`)56 return {status:"error", message:"Error al agregar producto "+err}57 }58 }59 }60 catch(err){61 let data = Object.assign({62 id: 1,63 timestamp: Date.now(),64 name: product.name,65 description: product.description ||"",66 code:product.code || "",67 price: product.price, 68 thumbnail: product.thumbnail,69 stock:product.stock || 0 70 })71 try{72 await fs.promises.writeFile(__dirname+`/files/${this.archiveName}.txt`, JSON.stringify([data], null, 2))73 console.log(`Se creó ${__dirname+`/files/${this.archiveName}.txt`} y agregó el ${product.name}`)74 return {status:"success", message:`Se creó ${__dirname}/files/${this.archiveName}.txt y agregó el ${product.name}`}75 }76 catch(err){77 console.log(err)78 return {status:"error", message:"Error al agregar producto. "+err}79 }80 }81 }82 83 async getById(idNumber){84 try{85 let data = await fs.promises.readFile(__dirname+`/files/${this.archiveName}.txt`, 'utf-8')86 let products = JSON.parse(data)87 88 let buscarProd = products.find(prod => prod.id === idNumber)89 90 if(buscarProd){91 return buscarProd92 }else{93 console.log(null)94 return null95 }96 97 }98 catch(err){99 console.log(err)100 }101 }102 103 async getAll(){104 try{105 let data = await fs.promises.readFile(__dirname+`/files/${this.archiveName}.txt`, 'utf-8')106 let products = JSON.parse(data)107 return products108 }109 catch(err){110 // console.log(`No existen los productos en ${__dirname}/files/${this.archiveName}.txt - ${err}`)111 }112 }113 114 async updateProduct(id,body){115 try{116 let data = await fs.promises.readFile(__dirname+`/files/${this.archiveName}.txt`,'utf-8');117 let products = JSON.parse(data);118 if(!products.some(prod => prod.id === id)) return {status:"error", message:"No hay productos con el id solicitado."}119 let result = products.map( product => {120 if(product.id === id){121 body = Object.assign(body)122 body = Object.assign({id:product.id,...body});123 return body;124 }else{125 return product;126 }127 })128 try{129 await fs.promises.writeFile(__dirname+`/files/${this.archiveName}.txt`,JSON.stringify(result,null,2));130 return {status:"success", message:"Producto actualizado correctamente."}131 }catch{132 return {status:"error", message:"Error al actualizar el producto."}133 }134 }catch(error){135 return {status:"error",message:"Fallo al actualizar producto: "+error}136 }137 }138 async deleteById(idNumber){139 try{140 let data = await fs.promises.readFile(__dirname+`/files/${this.archiveName}.txt`, 'utf-8')141 let products = JSON.parse(data)142 143 let index = products.findIndex(prod => prod.id === idNumber)144 let borrarProd = products.find(prod => prod.id === idNumber)145 if(index > -1){146 products.splice(index, 1)147 try{148 await fs.promises.writeFile(__dirname+`/files/${this.archiveName}.txt`, JSON.stringify(products, null, 2))149 console.log(`Se eliminó ${borrarProd.title} de ${__dirname}/files/${this.archiveName}.txt`)150 return {status:"success",message:"Producto eliminado correctamente."}151 }152 catch(err){153 console.log(err)154 }155 }else{156 console.log(`Error: no existe uelproducto con el Id solicitado.`)157 return {status:"error", message:"Error: no existe un producto con ese ID."}158 }159 160 }161 catch(err){162 console.log(err)163 return {status:"error", message:"Fallo al eliminar el producto "+err}164 }165 }166 async deleteAll(){167 try{168 await fs.promises.writeFile(__dirname+`/files/${this.archiveName}.txt`, [])169 console.log(`Se eliminó todos los productos de ${__dirname}/files/${this.archiveName}.txt`)170 }171 catch(err){172 console.log(err) 173 }174 }175}...

Full Screen

Full Screen

setup.js

Source:setup.js Github

copy

Full Screen

1const fs = require('fs-extra');2const mv = require('mv');3const request = require('request');4const unzip = require('unzip-stream');5const progress = require('cli-progress');6const releasedVersion = process.env.RELEASE_VERSION || 'v0.11.1';7const baseReleasedUrl = `https://github.com/kintone/cli-kintone/releases/download/${releasedVersion}`;8const platforms = {9 // Ref: https://nodejs.org/api/process.html#process_process_platform10 macOS: 'darwin',11 windows: 'win32',12 linux: ['linux', 'freebsd', 'openbsd', 'sunos', 'aix'],13};14/**15 * @param {string} platform16 * @returns {{fileName: string, archiveName: string, filePath: string, releasedUrl: string}|{fileName: string, archiveName: string, filePath: string, releasedUrl: string}|{fileName: string, archiveName: string, filePath: string, releasedUrl: string}}17 */18const getCompatibleBuild = platform => {19 let buildInfo = {};20 switch (platform) {21 case platforms.macOS:22 buildInfo = {23 fileName: 'cli-kintone',24 filePath: 'build/macos-x64/',25 archiveName: 'macos-x64.zip',26 releasedUrl: `${baseReleasedUrl}/macos-x64.zip`,27 };28 break;29 case platforms.windows:30 buildInfo = {31 fileName: 'cli-kintone.exe',32 filePath: 'build/windows-x64/',33 archiveName: 'windows-x64.zip',34 releasedUrl: `${baseReleasedUrl}/windows-x64.zip`,35 };36 break;37 default:38 // linux cases39 buildInfo = {40 fileName: 'cli-kintone',41 filePath: 'build/linux-x64/',42 archiveName: 'linux-x64.zip',43 releasedUrl: `${baseReleasedUrl}/linux-x64.zip`,44 };45 }46 return buildInfo;47};48/**49 * @param {string} releasedUrl50 * @param {string} archiveName51 * @returns {Promise<>}52 */53async function downloadCliKintoneBuild(releasedUrl, archiveName) {54 return new Promise(resolve => {55 const progressBar = new progress.SingleBar(56 {57 format: 'Downloading progress: {bar} {percentage}% | ETA: {eta}s',58 },59 progress.Presets.legacy60 );61 const writer = fs.createWriteStream(archiveName);62 let receivedBytes = 0;63 request64 .get(releasedUrl)65 .on('response', response => {66 if (response.statusCode !== 200) {67 console.error('Response status was ' + response.statusCode);68 return;69 }70 const totalBytes = response.headers['content-length'];71 progressBar.start(totalBytes, 0);72 })73 .on('data', chunk => {74 receivedBytes += chunk.length;75 progressBar.update(receivedBytes);76 })77 .pipe(writer)78 .on('error', err => {79 fs.unlink(archiveName);80 progressBar.stop();81 console.error(err.message);82 return;83 });84 writer.on('finish', () => {85 progressBar.stop();86 writer.close(resolve);87 });88 writer.on('error', err => {89 fs.unlink(archiveName);90 progressBar.stop();91 console.error(err.message);92 return;93 });94 });95}96/**97 * @param {string} archiveName98 * @returns {Promise<>}99 */100async function unzipCliKintoneBuild(archiveName) {101 return new Promise(resolve => {102 fs.createReadStream(`./${archiveName}`)103 .pipe(unzip.Extract({ path: './' }))104 .on('close', () => {105 resolve();106 });107 });108}109/**110 * @param {string} filePath111 * @param {string} fileName112 * @returns {Promise<void>}113 */114async function moveCliKintoneToRootFolder(filePath, fileName) {115 const currentPath = `./${filePath}${fileName}`;116 const newPath = `./${fileName}`;117 mv(currentPath, newPath, err => {118 if (err) {119 console.error(err);120 } else {121 fs.chmodSync(newPath, '777');122 }123 });124}125async function removeBuildFolder() {126 try {127 await fs.remove('./build');128 } catch (err) {129 console.error(err);130 }131}132/**133 * @param {string} archiveName134 * @returns {Promise<void>}135 */136async function removeBuildArchive(archiveName) {137 fs.unlinkSync(archiveName);138}139module.exports = async () => {140 const buildInfo = getCompatibleBuild(process.platform);141 const path = './' + buildInfo.fileName;142 if (!fs.existsSync(path)) {143 console.log(`\n--------- START PREPARATION CLI-KINTONE BUILD ${releasedVersion} ----------`);144 await downloadCliKintoneBuild(buildInfo.releasedUrl, buildInfo.archiveName);145 console.log('start unzip ... ');146 await unzipCliKintoneBuild(buildInfo.archiveName);147 console.log('unzip finished ... ');148 console.log('move cli to root ... ');149 await moveCliKintoneToRootFolder(buildInfo.filePath, buildInfo.fileName);150 console.log('move finished ... ');151 console.log('remove build folder ... ');152 await removeBuildFolder('./build');153 console.log('remove finished ... ');154 console.log('remove archive folder ... ');155 await removeBuildArchive(buildInfo.archiveName);156 console.log('remove finished ... ');157 console.log(`--------- FINISHED PREPARATION CLI-KINTONE BUILD ${releasedVersion}----------`);158 } else {159 console.log('\n--------- CLI-KINTONE EXIT ----------');160 }...

Full Screen

Full Screen

storage.js

Source:storage.js Github

copy

Full Screen

1// Copyright 2014 The Chromium Authors. All rights reserved.2// Use of this source code is governed by a BSD-style license that can be3// found in the LICENSE file.4storage = new (function() {5this.table_ = null;6this.tableData_ = null;7this.profileMenu_ = null;8this.onDomReady_ = function() {9 // Create the menus for mmap and nheap profiling.10 this.profileMenu_ = $('#storage-profile-menu');11 this.profileMenu_12 .mouseleave(this.profileMenu_.hide.bind(13 this.profileMenu_, {duration: 0}))14 .hide();15 // Initialize the toolbar.16 $('#storage-profile').button({icons:{primary: 'ui-icon-image'}})17 .click(this.profileMmapForSelectedSnapshots.bind(this, null))18 .mouseenter(this.showProfileMenu_.bind(this));19 $('#storage-dump-mmaps').button({icons:{primary: 'ui-icon-calculator'}})20 .click(this.dumpMmapForSelectedSnapshot_.bind(this));21 $('#storage-dump-nheap').button({icons:{primary: 'ui-icon-calculator'}})22 .click(this.dumpNheapForSelectedSnapshot_.bind(this));23 // Create the table.24 this.table_ = new google.visualization.Table($('#storage-table')[0]);25 $('#storage-table').on('contextmenu', this.showProfileMenu_.bind(this));26};27this.reload = function() {28 webservice.ajaxRequest('/storage/list', this.onListAjaxResponse_.bind(this));29}30this.onListAjaxResponse_ = function(data) {31 this.tableData_ = new google.visualization.DataTable(data);32 this.redraw();33};34this.profileMmapForSelectedSnapshots = function(ruleset) {35 // Generates a mmap profile for the selected snapshots.36 var sel = this.table_.getSelection();37 if (!sel.length || !this.tableData_) {38 alert('No snapshots selected!');39 return;40 }41 var archiveName = null;42 var snapshots = [];43 for (var i = 0; i < sel.length; ++i) {44 var row = sel[i].row;45 var curArchive = this.tableData_.getValue(row, 0);46 if (archiveName && curArchive != archiveName) {47 alert('All the selected snapshots must belong to the same archive!');48 return;49 }50 archiveName = curArchive;51 snapshots.push(this.tableData_.getValue(row, 1));52 }53 profiler.profileArchivedMmaps(archiveName, snapshots, ruleset);54 rootUi.showTab('prof');55};56this.dumpMmapForSelectedSnapshot_ = function() {57 var sel = this.table_.getSelection();58 if (sel.length != 1) {59 alert('Please select only one snapshot.')60 return;61 }62 var row = sel[0].row;63 mmap.dumpMmapsFromStorage(this.tableData_.getValue(row, 0),64 this.tableData_.getValue(row, 1))65 rootUi.showTab('mm');66};67this.dumpNheapForSelectedSnapshot_ = function() {68 var sel = this.table_.getSelection();69 if (sel.length != 1) {70 alert('Please select only one snapshot.')71 return;72 }73 var row = sel[0].row;74 if (!this.checkHasNativeHapDump_(row))75 return;76 nheap.dumpNheapFromStorage(this.tableData_.getValue(row, 0),77 this.tableData_.getValue(row, 1))78 rootUi.showTab('nheap');79};80this.profileNativeForSelectedSnapshots = function(ruleset) {81 // Generates a native heap profile for the selected snapshots.82 var sel = this.table_.getSelection();83 if (!sel.length || !this.tableData_) {84 alert('No snapshots selected!');85 return;86 }87 var archiveName = null;88 var snapshots = [];89 for (var i = 0; i < sel.length; ++i) {90 var row = sel[i].row;91 var curArchive = this.tableData_.getValue(row, 0);92 if (archiveName && curArchive != archiveName) {93 alert('All the selected snapshots must belong to the same archive!');94 return;95 }96 if (!this.checkHasNativeHapDump_(row))97 return;98 archiveName = curArchive;99 snapshots.push(this.tableData_.getValue(row, 1));100 }101 profiler.profileArchivedNHeaps(archiveName, snapshots, ruleset);102 rootUi.showTab('prof');103};104this.checkHasNativeHapDump_ = function(row) {105 if (!this.tableData_.getValue(row, 3)) {106 alert('The selected snapshot doesn\'t have a heap dump!');107 return false;108 }109 return true;110}111this.rebuildMenu_ = function() {112 this.profileMenu_.empty();113 this.profileMenu_.append(114 $('<li/>').addClass('header').text('Memory map rules'));115 profiler.rulesets['mmap'].forEach(function(rule) {116 this.profileMenu_.append(117 $('<li/>').text(rule).click(118 this.profileMmapForSelectedSnapshots.bind(this, rule)));119 }, this);120 this.profileMenu_.append(121 $('<li/>').addClass('header').text('Native heap rules'));122 profiler.rulesets['nheap'].forEach(function(rule) {123 this.profileMenu_.append(124 $('<li/>').text(rule).click(125 this.profileNativeForSelectedSnapshots.bind(this, rule)));126 }, this);127 this.profileMenu_.menu();128};129this.showProfileMenu_ = function(evt) {130 console.log(evt);131 var pos;132 if (evt.type == 'contextmenu')133 pos = {my: "left top", at: "left bottom", of: evt};134 else135 pos = {my: "left top", at: "left bottom", of: evt.target};136 this.profileMenu_.show({duration: 0}).position(pos);137 evt.preventDefault();138}139this.redraw = function() {140 this.rebuildMenu_();141 if (!this.tableData_)142 return;143 this.table_.draw(this.tableData_);144};145$(document).ready(this.onDomReady_.bind(this));...

Full Screen

Full Screen

options.js

Source:options.js Github

copy

Full Screen

1/**2 * This file is part of the extension Memento for Chrome.3 * http://mementoweb.org4 * Copyright 2013,5 * Harihar Shankar, Herbert Van de Sompel, 6 * Martin Klein, Robert Sanderson, Lyudmila Balakireva7 * -- Los Alamos National Laboratory. 8 * Licensed under the BSD open source software license.9 * You may not use this file except in compliance with the License.10 * You may obtain a copy of the License at11 * http://mementoweb.github.io/SiteStory/license.html12 * Unless required by applicable law or agreed to in writing, software13 * distributed under the License is distributed on an "AS IS" BASIS,14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.15 * See the License for the specific language governing permissions and16 * limitations under the License.17 */18chrome.storage.local.get(null, function(items) {19 var mementoTimeGateUrlList = items["mementoTimeGateUrlList"];20 21 for (var archiveName in mementoTimeGateUrlList) {22 var cls = "";23 if (!items['mementoTimeGateUrl'] && archiveName == "Memento Aggregator (recommended)") {24 $("#optionsCurrentlyUsedArchiveUrl").empty();25 $("#optionsCurrentlyUsedArchiveUrl").append(chrome.i18n.getMessage("optionsCurrentlyUsedArchiveUrl", [archiveName, mementoTimeGateUrlList[archiveName]]));26 cls = " ui-selected";27 }28 else if (mementoTimeGateUrlList[archiveName] == items["mementoTimeGateUrl"]) {29 selectedArchiveName = archiveName;30 $("#optionsCurrentlyUsedArchiveUrl").empty();31 $("#optionsCurrentlyUsedArchiveUrl").append(chrome.i18n.getMessage("optionsCurrentlyUsedArchiveUrl", [archiveName, mementoTimeGateUrlList[archiveName]]));32 cls = " ui-selected";33 }34 $("#selectable").append("<li class='ui-widget-content"+cls+"'>"+archiveName+"</li>");35 }36 $( "#selectable li" ).click( function() {37 $(this).addClass("ui-selected").siblings().removeClass("ui-selected")38 })39})40$(function() {41 $("#optionsTitle").append(chrome.i18n.getMessage("optionsTitle"))42 $("#optionsArchiveDescription").append(chrome.i18n.getMessage("optionsArchiveDescription"))43 $("#optionsCurrentlyUsedArchiveTitle").append(chrome.i18n.getMessage("optionsCurrentlyUsedArchiveTitle"))44 $("#optionsSelectArchiveTitle").append(chrome.i18n.getMessage("optionsSelectArchiveTitle"))45 46 $("#optionsUpdateButtonText")47 .append(chrome.i18n.getMessage("optionsUpdateButtonText"))48 .button()49 .click( function(event) {50 event.preventDefault()51 $("#userTimeGateError").empty()52 $("#userTimeGateError").removeClass("ui-state-error ui-corner-all")53 var timegateUrl = ""54 var userTimeGate = $("#userTimeGate")[0].value55 if (userTimeGate.trim() != "") {56 var userTimeGateLen = userTimeGate.length57 if (userTimeGate.search("http://") != 0 && userTimeGate.search("https://") != 0 || userTimeGate[userTimeGateLen-1] != "/") {58 $("#userTimeGateError").append(chrome.i18n.getMessage("optionsUnlistedArchiveUrlError"))59 $("#userTimeGateError").addClass("ui-state-error ui-corner-all")60 return61 }62 timegateUrl = userTimeGate63 $("#optionsCurrentlyUsedArchiveUrl").empty()64 $("#optionsCurrentlyUsedArchiveUrl").append(chrome.i18n.getMessage("optionsCurrentlyUsedArchiveUrl", ["Unlisted Archive", timegateUrl]))65 chrome.storage.local.set({'mementoTimeGateUrl': timegateUrl})66 }67 if (timegateUrl == "") {68 var archiveName = $( "#selectable .ui-selected" ).text();69 chrome.storage.local.get("mementoTimeGateUrlList", function(item) {70 $("#optionsCurrentlyUsedArchiveUrl").empty();71 $("#optionsCurrentlyUsedArchiveUrl").append(chrome.i18n.getMessage("optionsCurrentlyUsedArchiveUrl", [archiveName, item["mementoTimeGateUrlList"][archiveName]]));72 timegateUrl = item["mementoTimeGateUrlList"][archiveName];73 chrome.storage.local.set({'mementoTimeGateUrl': timegateUrl})74 });75 }76 })...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1'use strict'2var fs = require('fs');3var ncp = require('ncp').ncp;4var rmdir = require('rimraf');5var uuid = require('node-uuid');6var archiver = require('archiver');7var path = require('path');8var hbs = require('handlebars');9var fs = require('fs');10var _ = require('lodash');11var Definition = require('../server/api/definitions/definition.model');12var generateRoutes = (directory, dfs) => {13 var definitions = dfs || [14 {15 "type" : "POST",16 "url" : "/example/:id",17 "handles" : [18 {19 "module" : "mongodb",20 "x" : 100,21 "y" : 150,22 "config" : {23 "params" : {24 "email" : "{{value.email}}"25 },26 "configuration" : {27 "collection" : "{{value.collection}}",28 "database" : "{{env.database}}",29 "port" : "{{env.port}}",30 "hostname" : "{{env.hostname}}"31 }32 },33 },34 {35 "module" : "twilio",36 "x" : 100,37 "y" : 520,38 "config" : {39 "params" : {40 "body" : "Hi, {{value.name}}! How are you?",41 "to" : "{{value.to}}",42 "from" : "{{value.from}}"43 },44 "configuration" : {45 "authToken" : "{{env.authToken}}",46 "accountSid" : "{{env.accountSid}}"47 }48 },49 }50 ],51 "__v" : 052 }53 ];54 var modules = [];55 for(var i in definitions){56 var route = definitions[i];57 if(route.type == "POST"){58 route.post = true;59 } else if(route.type == "GET"){60 route.get = true;61 }62 var localModules = [];63 for(var j in route.handles){64 var handle = route.handles[j];65 handle.stringconfig = JSON.stringify(handle.config);66 modules.push(handle.module);67 localModules.push(handle.module);68 }69 route.modules = localModules;70 }71 fs.readFile('./server/code-templates/routes.js', 'utf8', function (err, fileContents) {72 if(err){73 console.log(err);74 return;75 }76 // Remove BOM character if there is one at the start of the file.77 if(fileContents.charCodeAt(0) == 65279) fileContents = fileContents.substr(1);78 hbs.registerHelper('json', function(context) {79 return JSON.stringify(context, null, 4);80 });81 hbs.registerHelper('var', function(context) {82 return context.replace(/[\-]+/g,'');83 });84 hbs.registerHelper('lower', function(str) {85 return str.toLowerCase();86 });87 let compiled = hbs.compile(fileContents);88 var routes = compiled({89 modules: _.uniq(modules),90 routes: definitions91 });92 fs.writeFileSync(path.join(directory, 'routes.js'), routes, 'utf8');93 })94}95var generateServer = () => {96 var promise = new Promise(function(resolve, reject){97 Definition.find({}).lean().then(function (defs) {98 console.log("efs" + JSON.stringify(defs));99 var archiveName = uuid.v4();100 ncp('./rest-server/', './' + archiveName, function (err) {101 ncp('./server/api-modules/', './' + archiveName + '/api-modules/', function (err) {102 if (err) {103 return console.error(err);104 }105 console.log('done!');106 generateRoutes('./' + archiveName, defs);107 var output = fs.createWriteStream(archiveName + '.zip');108 var archive = archiver('zip');109 output.on('close', function () {110 console.log(archive.pointer() + ' total bytes');111 console.log('archiver has been finalized and the output file descriptor has closed.');112 rmdir('./' + archiveName, function(error){113 console.log(error);114 });115 resolve(archiveName + '.zip');116 });117 archive.on('error', function(err){118 throw err;119 });120 archive.pipe(output);121 archive.glob('./' + archiveName + '/**/*');122 archive.finalize();123 })})})});124 return promise;125}...

Full Screen

Full Screen

zipOptions.js

Source:zipOptions.js Github

copy

Full Screen

1/* global Vue */2/* eslint no-multi-str: 0 */34try {5 let NAME;6} catch(_e) {}7NAME = 'Compliance Mods';89Vue.component('zip-options', {10 template:11 '<div id="zipOptions">\12 <h4 class="my-3">\13 <label for="aoe" class="d-inline-block noselect">Advanced options </label> <input id="aoe" type="checkbox" v-model="advancedOptionsEnabled" />\14 </h4>\15 <div v-show="advancedOptionsEnabled" id="advancedOptions">\16 <div class="form-row">\17 <div class="form-group col-md-4">\18 <label for="compressionSelect" class="d-block pb-1">Compression level</label>\19 <select id="compressionSelect" class="form-control custom-select" v-model="compressionChosen">\20 <template v-for="(ct, ctindex) in compressionTypes">\21 <optgroup :label="ct" :key="ct">\22 <option v-for="cl in compressionLevels.slice(!!ctindex ? 1 : 0, !ctindex ? 1 : compressionLevelsAvailable)" :key="cl.value" :value="cl.value" :selected="cl.value == compressionChosen">{{ cl.label }}</option>\23 </optgroup>\24 </template>\25 </select>\26 </div>\27 <div class="form-group col-md-4">\28 <label for="archiveName" class="d-block pb-1">Archive name</label>\29 <input type="text" autocomplete="false" name="archiveName" :class="{ \'form-control\': true, empty: !archiveName.trim() }" v-model="archiveName" id="archiveName" placeholder="Leave empty to generate a unique name">\30 </div>\31 <clear-database></clear-database>\32 </div>\33 </div>\34 </div>',35 data: function () {36 return {37 advancedOptionsEnabled: false,38 compressionDefault: 7,39 compressionChosen: 7, // 7 is default compression for ZIP archives40 compressionLevelsAvailable: 10,41 compressionTypes: ['STORE', 'DEFLATE'],42 specialCompressionLabels: {43 '0': 'No compression',44 '1': 'Best speed',45 '7': 'Recommanded',46 '9': 'Best compression'47 },48 archiveName: ''49 }50 },51 computed: {52 chevron: function () {53 return 'fa-caret-' + (this.advancedOptionsEnabled ? 'up' : 'down')54 },55 compressionLevels: function () {56 const result = []57 for (let i = 0; i < this.compressionLevelsAvailable; ++i) {58 result.push({59 value: i,60 label: (String(i) in this.specialCompressionLabels) ? i + ` (${this.specialCompressionLabels[i]})` : String(i)61 })62 }6364 return result65 },66 compressionTypeChosen: function () {67 return this.compressionTypes[(this.compressionLevelChosen > 0) * 1]68 },69 compressionLevelChosen: function () {70 return this.advancedOptionsEnabled ? this.compressionChosen : this.compressionDefault71 },72 zipOptions: function () {73 const result = {74 type: 'blob',75 comment: 'Resource pack generated by ' + NAME,76 compression: this.compressionTypeChosen77 }7879 if (this.compressionTypeChosen === this.compressionTypes[1]) { // if DEFlATE compression chosen80 result.compressionOptions = {81 level: this.compressionLevelChosen82 }83 }8485 return result86 },87 customArchiveName: function () {88 return (this.advancedOptionsEnabled && this.archiveName !== '') ? this.archiveName : undefined89 }90 },91 watch: {92 archiveName: function (newValue, oldValue) {93 if (oldValue !== newValue) {94 const changed = newValue.trim()95 if (changed !== newValue) {96 this.archiveName = changed97 }98 }99 }100 },101 mounted: function () {102 this.$root.$refs.zipOptions = this103 } ...

Full Screen

Full Screen

mongoFreeze.js

Source:mongoFreeze.js Github

copy

Full Screen

1import { spawn } from 'child_process'2import moment from 'moment'3import fs from 'fs'4import { saveToBlobStorage, cleanupBlobs } from './azure'5const { MONGO_ARCHIVE_PREFIX = 'db', MONGO_HOST, MONGO_APP_DB, MONGO_APP_USER, MONGO_APP_PASSWORD } = process.env6const createArchiveNamed = archiveName => new Promise((resolve, reject) => {7 const mongodump = spawn('mongodump', [8 '--gzip',9 `--archive=${archiveName}`,10 `--host=${MONGO_HOST}`,11 '--ssl', '--sslAllowInvalidCertificates',12 `--db=${MONGO_APP_DB}`,13 `--username=${MONGO_APP_USER}`,14 `--password="${MONGO_APP_PASSWORD}"`15 ], { stdio: 'inherit' })16 mongodump.on('error', err => {17 reject(err)18 })19 mongodump.on('exit', exitCode => {20 if (exitCode === 0) {21 resolve(exitCode)22 } else {23 reject(exitCode)24 }25 })26})27const cleanupFile = file => new Promise((resolve, reject) => {28 fs.unlink(file, err => {29 if (err) {30 reject(err)31 } else {32 resolve()33 }34 })35})36export default function mongoFreeze() {37 const timeStamp = moment().utc().format('Y-MM-DD-HH-mm-ss');38 const archiveName = `${MONGO_ARCHIVE_PREFIX}-${timeStamp}.archive`39 createArchiveNamed(archiveName).then(() => {40 console.log(`created archive: ${archiveName}`)41 return saveToBlobStorage(archiveName)42 }).then(() => {43 console.log(`saved ${archiveName} to blob storage`)44 return cleanupFile(archiveName)45 }).then(() => {46 console.log(`cleaned up ${archiveName} after saving`)47 return cleanupBlobs()48 }).then(deletedBlobs => {49 deletedBlobs.forEach(({ name }) => console.log(`clean up blob ${name}`))50 console.log(`cleaned up old blobs after saving ${archiveName} complete`)51 }).catch(console.error)52 return {53 archiveName54 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const {PuppeteerArchiver} = require('puppeteer-archiver');2const puppeteerArchiver = new PuppeteerArchiver();3(async () => {4 const archiveName = await puppeteerArchiver.archiveName();5 console.log(archiveName);6})();7const {PuppeteerArchiver} = require('puppeteer-archiver');8const puppeteerArchiver = new PuppeteerArchiver();9(async () => {10 const archiveName = await puppeteerArchiver.archiveName();11 console.log(archiveName);12})();13const {PuppeteerArchiver} = require('puppeteer-archiver');14const puppeteerArchiver = new PuppeteerArchiver();15(async () => {16 const archiveName = await puppeteerArchiver.archiveName();17 console.log(archiveName);18})();19const {PuppeteerArchiver} = require('puppeteer-archiver');20const puppeteerArchiver = new PuppeteerArchiver();21(async () => {22 const archiveName = await puppeteerArchiver.archiveName();23 console.log(archiveName);24})();25const {PuppeteerArchiver} = require('puppeteer-archiver');26const puppeteerArchiver = new PuppeteerArchiver();27(async () => {28 const archiveName = await puppeteerArchiver.archiveName();29 console.log(archiveName);30})();31const {PuppeteerArchiver} = require('puppeteer-archiver');32const puppeteerArchiver = new PuppeteerArchiver();33(async () => {34 const archiveName = await puppeteerArchiver.archiveName();35 console.log(archiveName);36})();37const {PuppeteerArchiver} = require('puppeteer-archiver');38const puppeteerArchiver = new PuppeteerArchiver();39(async () => {40 const archiveName = await puppeteerArchiver.archiveName();41 console.log(archiveName

Full Screen

Using AI Code Generation

copy

Full Screen

1const PuppeteerArchiver = require('puppeteer-archiver');2const puppeteerArchiver = new PuppeteerArchiver();3puppeteerArchiver.archiveName("test");4const PuppeteerArchiver = require('puppeteer-archiver');5const puppeteerArchiver = new PuppeteerArchiver();6puppeteerArchiver.archiveName("test");7const PuppeteerArchiver = require('puppeteer-archiver');8const puppeteerArchiver = new PuppeteerArchiver();9puppeteerArchiver.archiveName("test");10const PuppeteerArchiver = require('puppeteer-archiver');11const puppeteerArchiver = new PuppeteerArchiver();12puppeteerArchiver.archiveName("test");13const PuppeteerArchiver = require('puppeteer-archiver');14const puppeteerArchiver = new PuppeteerArchiver();15puppeteerArchiver.archiveName("test");16const PuppeteerArchiver = require('puppeteer-archiver');17const puppeteerArchiver = new PuppeteerArchiver();18puppeteerArchiver.archiveName("test");19const PuppeteerArchiver = require('puppeteer-archiver');20const puppeteerArchiver = new PuppeteerArchiver();21puppeteerArchiver.archiveName("test");22const PuppeteerArchiver = require('puppeteer-archiver');23const puppeteerArchiver = new PuppeteerArchiver();24puppeteerArchiver.archiveName("test");25const PuppeteerArchiver = require('puppeteer-archiver');26const puppeteerArchiver = new PuppeteerArchiver();27puppeteerArchiver.archiveName("test");28const PuppeteerArchiver = require('puppeteer-archiver');

Full Screen

Using AI Code Generation

copy

Full Screen

1const { archiveName } = require('puppeteer-archiver');2const { PuppeteerArchiver } = require('puppeteer-archiver');3const puppeteer = require('puppeteer');4const puppeteerArchiver = new PuppeteerArchiver({5});6(async () => {7 await puppeteerArchiver.launch();8 const page = await puppeteerArchiver.newPage();9 await puppeteerArchiver.archive('google.com');10 await puppeteerArchiver.close();11})();12const name = archiveName('google.com');13console.log(name);14#### archiveName(url, [options])15#### new PuppeteerArchiver(options)

Full Screen

Using AI Code Generation

copy

Full Screen

1const { PuppeteerArchiver } = require('puppeteer-archiver');2const puppeteerArchiver = new PuppeteerArchiver();3puppeteerArchiver.archiveName = 'myArchive';4#### PuppeteerArchiver.archive(url, options)5- Returns: {Promise<void>}6- Type: {string}7- Type: {string}8- Type: {boolean}9- Type: {string}10- Type: {string}11- Type: {Object}12Options to pass to Puppeteer. These options will be passed to the `puppeteer.launch()` function. See [Puppeteer documentation](

Full Screen

Using AI Code Generation

copy

Full Screen

1const { PuppeteerArchiver } = require("puppeteer-archiver");2const archiver = new PuppeteerArchiver({3});4const { PuppeteerArchiver } = require("puppeteer-archiver");5const archiver = new PuppeteerArchiver({6});7const { PuppeteerArchiver } = require("puppeteer-archiver");8const archiver = new PuppeteerArchiver({

Full Screen

Using AI Code Generation

copy

Full Screen

1const {PuppeteerArchiver} = require('puppeteer-archiver');2const archive = new PuppeteerArchiver();3const {PuppeteerArchiver} = require('puppeteer-archiver');4const archive = new PuppeteerArchiver();5const {PuppeteerArchiver} = require('puppeteer-archiver');6const archive = new PuppeteerArchiver();7const {PuppeteerArchiver} = require('puppeteer-archiver');8const archive = new PuppeteerArchiver();9This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Puppeteer automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful