How to use transformPromise method in wpt

Best JavaScript code snippet using wpt

index.js

Source:index.js Github

copy

Full Screen

1#!/usr/bin / env node2'use strict';3// libs init4var program = require('commander');5var colors = require('colors');6var Q = require('bluebird');7var fs = require('fs-extra');8var path = require('path');9var Jimp = require('jimp');10var _ = require('lodash');11var Gauge = require("gauge");12// helpers13var display = {14 info: (str) => {15 console.log(str);16 },17 success: (str) => {18 str = ' ' + 'V'.green + ' ' + str;19 console.log(str);20 },21 error: (str) => {22 str = ' ' + 'X'.red + ' ' + str;23 console.log(str);24 },25 header: (str) => {26 console.log('');27 console.log(str);28 }29};30// app main variables and constants31const PLATFORMS = {32 'android': {33 definitions: ['./platforms/icons/android', './platforms/splash/android']34 },35 'ios': {36 definitions: ['./platforms/icons/ios', './platforms/splash/ios']37 },38 'windows': {39 definitions: ['./platforms/icons/windows', './platforms/splash/windows']40 },41 'blackberry10': {42 definitions: ['./platforms/icons/blackberry10']43 }44};45var g_imageObjects;46var g_selectedPlatforms = [];47// app functions48function check(settings) {49 display.header('Checking files and directories');50 return checkPlatforms(settings)51 .then((selPlatforms) => g_selectedPlatforms = selPlatforms)52 .then(() => getImages(settings))53 .then((iobjs) => {54 g_imageObjects = iobjs;55 })56 .then(() => checkOutPutDir(settings));57}58function checkPlatforms(settings) {59 var platformsKeys = _.keys(PLATFORMS);60 if (!settings.platforms || !Array.isArray(settings.platforms)) {61 display.success('Processing files for all platforms');62 return Q.resolve(platformsKeys);63 }64 var platforms = settings.platforms;65 var platformsToProcess = [];66 var platformsUnknown = [];67 platforms.forEach(platform => {68 if (_.find(platformsKeys, (p) => platform === p)) {69 platformsToProcess.push(platform);70 } else {71 platformsUnknown.push(platform);72 }73 });74 if (platformsUnknown.length > 0) {75 display.error('Bad platforms: ' + platformsUnknown);76 return Q.reject('Bad platforms: ' + platformsUnknown);77 }78 display.success('Processing files for: ' + platformsToProcess);79 return Q.resolve(platformsToProcess);80}81function getImages(settings) {82 var imageObjects = {83 icon: null,84 splash: null85 };86 var promise = Q.resolve();87 if (settings.makeicon) {88 promise = promise.then(() => checkIconFile(settings.iconfile))89 .then((image) => {90 imageObjects.icon = image;91 });92 }93 if (settings.makesplash) {94 promise = promise.then(() => checkSplashFile(settings.splashfile))95 .then((image) => {96 imageObjects.splash = image;97 });98 }99 return promise.then(() => {100 return imageObjects;101 });102 function checkIconFile(iconFileName) {103 var defer = Q.defer();104 Jimp.read(iconFileName)105 .then((image) => {106 var width = image.bitmap.width;107 var height = image.bitmap.height;108 if (width === 1024 && width === height) {109 display.success('Icon file ok (' + width + 'x' + height + ')');110 defer.resolve(image);111 } else {112 display.error('Bad icon file (' + width + 'x' + height + ')');113 defer.reject('Bad image format');114 }115 })116 .catch((err) => {117 display.error('Could not load icon file');118 defer.reject(err);119 });120 return defer.promise;121 }122 function checkSplashFile(splashFileName) {123 var defer = Q.defer();124 Jimp.read(splashFileName)125 .then((image) => {126 var width = image.bitmap.width;127 var height = image.bitmap.height;128 if (width === 2732 && width === height) {129 display.success('Splash file ok (' + width + 'x' + height + ')');130 defer.resolve(image);131 } else {132 display.error('Bad splash file (' + width + 'x' + height + ')');133 defer.reject('Bad image format');134 }135 })136 .catch((err) => {137 display.error('Could not load splash file');138 defer.reject(err);139 });140 return defer.promise;141 }142}143function checkOutPutDir(settings) {144 var dir = settings.outputdirectory;145 return fs.pathExists(dir)146 .then((exists) => {147 if (exists) {148 display.success('Output directory ok (' + dir + ')');149 } else {150 display.error('Output directory not found (' + dir + ')');151 throw ('Output directory not found: ' + dir);152 }153 });154}155function generateForConfig(imageObj, settings, config) {156 var platformPath = path.join(settings.outputdirectory, config.path);157 var transformIcon = (definition) => {158 var defer = Q.defer();159 var image = imageObj.icon.clone();160 var outputFilePath = path.join(platformPath, definition.name);161 image.resize(definition.size, definition.size)162 .write(outputFilePath,163 (err) => {164 if (err) defer.reject(err);165 //display.info('Generated icon file for ' + outputFilePath);166 defer.resolve();167 });168 return defer.promise;169 };170 var transformSplash = (definition) => {171 var defer = Q.defer();172 var image = imageObj.splash.clone();173 var x = (image.bitmap.width - definition.width) / 2;174 var y = (image.bitmap.height - definition.height) / 2;175 var width = definition.width;176 var height = definition.height;177 var outputFilePath = path.join(platformPath, definition.name);178 image179 .crop(x, y, width, height)180 .write(outputFilePath,181 (err) => {182 if (err) defer.reject(err);183 //display.info('Generated splash file for ' + outputFilePath);184 defer.resolve();185 });186 return defer.promise;187 };188 return fs.ensureDir(platformPath)189 .then(() => {190 var definitions = config.definitions;191 var sectionName = "Generating " + config.type + ' files for ' + config.platform;192 var definitionCount = definitions.length;193 var progressIndex = 0;194 var gauge = new Gauge();195 gauge.show(sectionName, 0);196 return Q.mapSeries(definitions, (def) => {197 var transformPromise = Q.resolve();198 transformPromise = transformPromise.then(() => {199 progressIndex++;200 var progressRate = progressIndex / definitionCount;201 gauge.show(sectionName, progressRate);202 gauge.pulse(def.name);203 });204 switch (config.type) {205 case 'icon':206 transformPromise = transformPromise.then(() => transformIcon(def));207 break;208 case 'splash':209 transformPromise = transformPromise.then(() => transformSplash(def));210 break;211 }212 return transformPromise;213 }).then(() => {214 gauge.disable();215 display.success('Generated ' + config.type + ' files for ' + config.platform);216 }).catch((err) => {217 gauge.disable();218 throw (err);219 });220 });221}222function generate(imageObj, settings) {223 display.header('Generating files');224 var configs = [];225 g_selectedPlatforms.forEach((platform) => {226 PLATFORMS[platform].definitions.forEach((def) => configs.push(require(def)));227 });228 var filteredConfigs = _.filter(configs, (config) => {229 if (config.type === 'icon' && settings.makeicon) return true;230 if (config.type === 'splash' && settings.makesplash) return true;231 return false;232 });233 return Q.mapSeries(filteredConfigs, (config) => {234 return generateForConfig(imageObj, settings, config);235 })236 .then(() => {237 //display.success("Successfully generated all files");238 });239}240function catchErrors(err) {241 if (err)242 console.log('Error: ', err);243}244// cli helper configuration245function processList(val) {246 return val.split(',');247}248var pjson = require('./package.json');249program250 .version(pjson.version)251 .description(pjson.description)252 .option('-i, --icon [optional]', 'optional icon file path (default: ./resources/icon.png)')253 .option('-s, --splash [optional]', 'optional splash file path (default: ./resources/splash.png)')254 .option('-p, --platforms [optional]', 'optional platform token comma separated list (default: all platforms processed)', processList)255 .option('-o, --outputdir [optional]', 'optional output directory (default: ./resources/)')256 .option('-I, --makeicon [optional]', 'option to process icon files only')257 .option('-S, --makesplash [optional]', 'option to process splash files only')258 .parse(process.argv);259// app settings and default values260var g_settings = {261 iconfile: program.icon || path.join('.', 'resources', 'icon.png'),262 splashfile: program.splash || path.join('.', 'resources', 'splash.png'),263 platforms: program.platforms || undefined,264 outputdirectory: program.outputdir || path.join('.', 'resources'),265 makeicon: program.makeicon || (!program.makeicon && !program.makesplash) ? true : false,266 makesplash: program.makesplash || (!program.makeicon && !program.makesplash) ? true : false267};268// app entry point269console.log("***************************");270console.log("cordova-res-generator " + pjson.version);271console.log("***************************");272check(g_settings)273 .then(() => generate(g_imageObjects, g_settings))...

Full Screen

Full Screen

editor.js

Source:editor.js Github

copy

Full Screen

1import React from "react";2import { Div } from "glamorous";3import { debounce } from "lodash";4import CodeMirror from "utils/codeMirror";5import { SpinnerOverlay } from "components/Spinner";6import PlaygroundDefaultInlineJS from "../fixtures/playgroundDefault.js";7import PlaygroundDefaultMobileInlineJS from "../fixtures/playgroundDefaultMobile.js";8import { MediaQueries, Color0, Color1, Color2, Color3 } from "constants";9const isProbablyMobile = userAgent => {10 return (11 typeof userAgent === "undefined" ||12 userAgent.match(/Android/i) ||13 userAgent.match(/webOS/i) ||14 userAgent.match(/iPhone/i) ||15 userAgent.match(/iPad/i) ||16 userAgent.match(/iPod/i) ||17 userAgent.match(/BlackBerry/i) ||18 userAgent.match(/Windows Phone/i)19 );20};21// For mobile we want a simplified input to showcase the tool because user has a small screen to view large examples22// We have to infer mobile usage from user agent unreliably but it's good enough23const getInitialInput = req => {24 const userAgent = req ? req.headers["user-agent"] : navigator.userAgent;25 return isProbablyMobile(userAgent)26 ? PlaygroundDefaultMobileInlineJS27 : PlaygroundDefaultInlineJS;28};29export default class Editor extends React.Component {30 static async getInitialProps({ req }) {31 const initialInput = getInitialInput(req);32 return { initialInput };33 }34 static Throttle = 1000;35 static DefaultOutput = "";36 static DefaultLogger = [];37 state = {38 input: this.props.initialInput,39 output: "",40 logger: Editor.DefaultLogger,41 };42 componentDidMount() {43 this.updateOutputImmediate(this.state.input);44 }45 componentWillUnmount() {46 this.unmounted = true;47 }48 updateOutputImmediate = value => {49 const transformPromise = getTransform(value);50 this.setState({51 transformPromise,52 output: Editor.DefaultOutput,53 logger: Editor.DefaultLogger,54 error: undefined,55 });56 transformPromise.then(57 ({ output, logger }) => {58 if (59 !this.unmounted &&60 transformPromise === this.state.transformPromise61 ) {62 console.debug("transform success", logger);63 this.setState({64 output,65 logger,66 transformPromise: undefined,67 });68 } else {69 console.debug("ignoring stale transform result", output, logger);70 }71 },72 e => {73 if (74 !this.unmounted &&75 transformPromise === this.state.transformPromise76 ) {77 console.error("transform error", e);78 this.setState({79 transformPromise: undefined,80 output: Editor.DefaultOutput,81 logger: Editor.DefaultLogger,82 error: e,83 });84 } else {85 console.warn("ignored transform error", e);86 }87 }88 );89 this.setState({ input: value });90 };91 updateOutputDebounced = debounce(92 value => this.updateOutputImmediate(value),93 Editor.Throttle94 );95 onChangeInput = value => {96 this.setState({97 input: value,98 output: Editor.DefaultOutput,99 logger: Editor.DefaultLogger,100 error: undefined,101 // if we are ignoring the change due to debouncing102 // we still want a spinner to immediately appear103 // we know for sure the promise will be replaced on debounced call104 transformPromise: new Promise(() => {}),105 });106 this.updateOutputDebounced(value);107 };108 onChangeOutput = value => {109 this.setState({ output: value });110 };111 render() {112 const { input, output, transformPromise, logger, error } = this.state;113 return (114 <Div115 css={{116 padding: "0 20px",117 [MediaQueries.large]: {118 flex: 1,119 width: "100%",120 display: "flex",121 flexDirection: "row",122 },123 [MediaQueries.small]: {124 width: "100%",125 },126 }}127 >128 <Window129 title="before"130 css={{131 [MediaQueries.large]: {132 marginRight: 20,133 },134 }}135 >136 <CodeMirrorEditor value={input} onChange={this.onChangeInput} />137 </Window>138 <Window139 title="after"140 css={{141 [MediaQueries.small]: {142 marginTop: 20,143 },144 }}145 spinner={!!transformPromise}146 error={error}147 >148 <CodeMirrorEditor value={output} onChange={this.onChangeOutput} />149 </Window>150 </Div>151 );152 }153}154export const WindowControls = () => (155 <svg156 xmlns="http://www.w3.org/2000/svg"157 width="54"158 height="14"159 viewBox="0 0 54 14"160 >161 <g fill="none" fillRule="evenodd" transform="translate(1 1)">162 <circle cx="6" cy="6" r="6" fill={Color1} />163 <circle cx="26" cy="6" r="6" fill={Color2} />164 <circle cx="46" cy="6" r="6" fill={Color3} />165 </g>166 </svg>167);168const FlexColumnGrow = {169 display: "flex",170 flexDirection: "column",171 flex: 1,172};173const Window = ({ children, title, spinner, error, css = {}, ...rest }) => (174 <Div175 position="relative"176 background="#282a36"177 borderRadius={5}178 {...rest}179 {...FlexColumnGrow}180 css={{181 ...css,182 [MediaQueries.small]: {183 ...css[MediaQueries.small],184 height: "38vh",185 minHeight: 250,186 },187 }}188 >189 <Div padding={5} {...FlexColumnGrow}>190 <Div padding={10} flex={0}>191 <Div192 display="flex"193 flexDirection="row"194 alignItems="center"195 justifyContent="center"196 >197 <Div flex={0}>198 <WindowControls />199 </Div>200 <Div201 flex={1}202 marginBottom={3}203 marginLeft={10}204 style={{205 color: "#B4BEDE",206 textTransform: "uppercase",207 fontSize: 11,208 fontWeight: 600,209 letterSpacing: 1,210 }}211 >212 {title}213 </Div>214 </Div>215 </Div>216 <Div217 css={{218 ...FlexColumnGrow,219 "& .react-codemirror2": FlexColumnGrow,220 "& .react-codemirror2 > .CodeMirror": FlexColumnGrow,221 }}222 >223 {children}224 </Div>225 </Div>226 {spinner && <SpinnerOverlay zIndex={10} />}227 {error && (228 <Div229 position="absolute"230 width="100%"231 height="100%"232 backgroundColor="rgba(0, 0, 0, 0.5)"233 display="flex"234 alignItems="center"235 justifyContent="center"236 >237 <Div238 display="flex"239 flexDirection="column"240 alignItems="center"241 justifyContent="center"242 >243 <Div padding={20} fontSize={30} color={"red"}>244 Error245 </Div>246 <Div padding={20} fontSize={20} color={"red"}>247 {error.message}248 </Div>249 </Div>250 </Div>251 )}252 </Div>253);254class CodeMirrorEditor extends React.PureComponent {255 static Options = {256 lineNumbers: true,257 mode: "jsx",258 theme: "dracula",259 scrollBarStyle: "overlay",260 viewportMargin: Infinity,261 lineWrapping: true,262 autoCursor: true,263 tabSize: 2,264 readOnly: false,265 };266 state = { show: false };267 componentDidMount() {268 this.setState({ show: true });269 }270 handleChange = (editor, meta, code) => {271 this.props.onChange(code);272 };273 render() {274 if (!this.state.show) {275 return <SpinnerOverlay zIndex={10} />;276 }277 return (278 <CodeMirror279 onBeforeChange={this.handleChange}280 value={this.props.value}281 options={CodeMirrorEditor.Options}282 />283 );284 }285}286function checkStatus(response) {287 if (response.status >= 200 && response.status < 300) {288 return response;289 } else {290 return response.text().then(text => {291 const error = new Error(text);292 error.response = response;293 throw error;294 });295 }296}297function parseJSON(response) {298 return response.json();299}300const getTransform = input => {301 return fetch("/transform", {302 method: "POST",303 headers: {304 "Content-Type": "application/json",305 },306 body: JSON.stringify({307 input,308 }),309 })310 .then(checkStatus)311 .then(parseJSON);...

Full Screen

Full Screen

model-transforming.service.ts

Source:model-transforming.service.ts Github

copy

Full Screen

1import { Injectable } from '@angular/core';2@Injectable({3 providedIn: 'root'4})5export class ModelTransformingService {6 /**7 This class asynchronously fires off tasks, who's purpose is to8 update (transform) a model.9 The tasks are independent, they should not depend on any attribute10 outside of their perview being present in the model.11 // ** BEGIN EXAMPLE TRANSFORMER **12 this._modelTransformingService.addTransformer((model, done) => {13 let currentUser = this._userService.getCurrentUser();14 if (model['userId'] === currentUser['id']) {15 // call an api. set the results in the model 16 this._pointsService.getCurrentUserPointsAsSum().then((pts) => {17 model["points"]["total"] = pts;18 // call done() to finish the transformation func19 done("pointsService pointsAssum");20 });21 } else {22 // call done() to finish the transformation func23 done("pointsService pointsAssum");24 }25 });26 // ** END EXAMPLE TRANSFORMER **27 then call transform(), passing in your model, to fire all the 28 transformers off.29 */30 transformers = [];31 transformPromise = undefined;32 activeCount = 0;33 constructor() {34 }35 reset() {36 this.transformPromise = undefined;37 this.activeCount = 0;38 }39 addTransformer(func) {40 this.transformers.push(func);41 }42 clearAllTransformers() {43 this.transformers = [];44 // reset(); ?45 }46 transform(model) {47 let self = this;48 if (!self.transformPromise) {49 self.transformPromise = new Promise((resolve, reject) => {50 if (self.transformers.length === 0)51 resolve(model);52 self.transformers.forEach((f) => {53 self.activeCount++54 setTimeout(() => {55 f(model, (transformerName) => { --self.activeCount; if (self.activeCount === 0) { resolve(model); } });56 }, 275);57 })58 })59 }60 return self.transformPromise;61 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptools = require('wptools');2var page = wptools.page('Albert_Einstein');3page.transformPromise('wikitext', 'html').then(function(result) {4 console.log(result);5});6var wptools = require('wptools');7var page = wptools.page('Albert_Einstein');8page.transform('wikitext', 'html', function(result) {9 console.log(result);10});11var wptools = require('wptools');12var page = wptools.page('Albert_Einstein');13page.transform('wikitext', 'html', function(result) {14 console.log(result);15});16var wptools = require('wptools');17var page = wptools.page('Albert_Einstein');18page.transform('wikitext', 'html', function(result) {19 console.log(result);20});21var wptools = require('wptools');22var page = wptools.page('Albert_Einstein');23page.transform('wikitext', 'html', function(result) {24 console.log(result);25});26var wptools = require('wptools');27var page = wptools.page('Albert_Einstein');28page.transform('wikitext', 'html', function(result) {29 console.log(result);30});31var wptools = require('wptools');32var page = wptools.page('Albert_Einstein');33page.transform('wikitext', 'html', function(result) {34 console.log(result);35});36var wptools = require('wptools');37var page = wptools.page('Albert_Einstein');38page.transform('wikitext', 'html', function(result) {39 console.log(result);40});41var wptools = require('wptools');

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('wpt');2var transformPromise = wpt.transformPromise;3transformPromise(transformOptions).then(function (data) {4 console.log(data);5}).catch(function (err) {6 console.log(err);7});8var wpt = require('wpt');9wpt.transform(transformOptions, function (err, data) {10 if (err) {11 console.log(err);12 } else {13 console.log(data);14 }15});16var wpt = require('wpt');17wpt.transform(transformOptions, function (err, data) {18 if (err) {19 console.log(err);20 } else {21 console.log(data);22 }23});24var wpt = require('wpt');25wpt.transform(transformOptions, function (err, data) {26 if (err) {27 console.log(err);28 } else {29 console.log(data);30 }31}, function (data) {32 console.log('custom callback: ' + data);33});34var wpt = require('w

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('wpt.js');2promise.then(function (data) {3 console.log('data: ' + data);4});5var wpt = require('wpt.js');6console.log('data: ' + data);7var wpt = require('wpt.js');8 console.log('data: ' + data);9});10var wpt = require('wpt.js');11 console.log('data: ' + data);12}, function(error) {13 console.log('error: ' + error);14});15var wpt = require('wpt.js');16 console.log('data: ' + data);17}, function(error) {18 console.log('error: ' + error);19}, 'json');20var wpt = require('wpt.js');21 console.log('data: ' + data);22}, function(error) {23 console.log('error: ' + error);24}, 'xml');25var wpt = require('wpt.js');26 console.log('data: ' + data);27}, function(error) {28 console.log('error: ' + error);29}, 'json', 'xml');30var wpt = require('wpt.js');

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('./wpt.js');2var url = process.argv[2];3wpt.transformPromise(url).then(function(data){4}).catch(function(err){5});6var wpt = require('./wpt.js');7var url = process.argv[2];8wpt.transform(url, function(err, data){9 if(err){10 }11});12var wpt = require('./wpt.js');13var url = process.argv[2];14wpt.transform(url, function(err, data){15 if(err){16 }17});18var wpt = require('./wpt.js');19var url = process.argv[2];20wpt.transform(url, function(err, data){21 if(err){22 }23});24var wpt = require('./wpt.js');25var url = process.argv[2];26wpt.transform(url, function(err, data){27 if(err){28 }29});30var wpt = require('./wpt.js');31var url = process.argv[2];32wpt.transform(url, function(err, data){33 if(err){34 }35});36var wpt = require('./wpt.js');37var url = process.argv[2];38wpt.transform(url, function(err, data){39 if(err){40 }

Full Screen

Using AI Code Generation

copy

Full Screen

1 console.log(res);2});3{4 "headers": {5 "content-type": "text/html; charset=UTF-8",6 "x-xss-protection": "1; mode=block",7 },

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptApi = require('wpt-api');2var fs = require('fs');3wptApi.transformPromise(url)4.then(function(data){5 fs.writeFile('transform.txt', data, function(err){6 if(err) throw err;7 console.log('File saved');8 });9})10.catch(function(err){11 console.log(err);12});13{14 "data": {

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org', 'A.8f8b7c2b6f2f7c1c9e9e7c1b6d2f7c2e');3}, function(err, data) {4 if (err) return console.error(err);5 wpt.getTestResults(data.data.testId, function(err, data) {6 if (err) return console.error(err);7 console.log(data.data.median.firstView.SpeedIndex);8 });9});10wpt.getTestResults(data.data.testId, function(err, data) {11 if (err) return console.error(err);12 console.log(data.data.median.firstView.SpeedIndex);13 }).transformPromise(function(data) {14 return {15 }16 });17wpt.getTestResults(data.data.testId, function(err, data) {18 if (err) return console.error(err);19 console.log(data.data.median.firstView.SpeedIndex);20 }).transformPromise(function(data) {21 return {22 }23 });

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 wpt 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