text
stringlengths
7
3.69M
'use strict'; angular.module('happoshuApp') .controller('SimulationGroupFilesCtrl', function ($scope, ScenarioService) { $scope.simulationGroupNames = null; ScenarioService.getSimulationGroupNames().then(function (dataResponse) { $scope.simulationGroupNames = dataResponse; }); $scope.message = 'Hello'; $scope.getSimulationGroupFiles = function (value) { console.log('Our value is ' + value); ScenarioService.getSimulationGroupFiles(value).then(function (dataResponse) { $scope.simulationGroupFiles = dataResponse; }); } });
export const ACTOR_CHEERIO_CHECKER_NAME = 'lukaskrivka/website-checker-cheerio'; export const ACTOR_PUPPETEER_CHECKER_NAME = 'lukaskrivka/website-checker-puppeteer'; export const ACTOR_PLAYWRIGHT_CHECKER_NAME = 'lukaskrivka/website-checker-playwright';
'use strict'; /* jshint node: true */ /* globals browser, describe, it, beforeAll, EC, expect, protractor, xit, afterAll */ var dpage = require('../pages/personalDetailsPage.js'); var homeP = require('../../../common/pages/homePage.js'); var request = require('request'); afterAll(function(done) { process.nextTick(done); }); describe('UIDS-716 Desktop-Mobile-Tablet ADDRESS page ----', function() { browser.ignoreSynchronization = false; it(browser.tc_desc('UIDS-1367 Story TC1 (1) check Menu Link is clickable on address page'), function() { if ( !browser.mobile ) { browser.wait(EC.visibilityOf(homeP.openfooterLink), 12000, 'Menu link is not displayed'); expect(homeP.openfooterLink.isDisplayed()).toBeTruthy(); browser.indirectClick(homeP.openfooterLink); browser.sleep(1000); } else { console.log('This functionality is not for mobile devices'); } }); it(browser.tc_desc('UIDS-1367 Story TC2 (1) check Menu Items are available on address page'), function() { if ( !browser.mobile ) { expect(homeP.footer.header.isDisplayed()).toBeTruthy(); expect(homeP.footer.aboutLink.isDisplayed()).toBeTruthy(); // expect(homeP.footer.fagsLink.isDisplayed()).toBeTruthy(); // expect(homeP.footer.supportLink.isDisplayed()).toBeTruthy(); expect(homeP.footer.privacyLink.isDisplayed()).toBeTruthy(); // expect(homeP.footer.securityLink.isDisplayed()).toBeTruthy(); // expect(homeP.footer.accessibilityLink.isDisplayed()).toBeTruthy(); expect(homeP.footer.language.isDisplayed()).toBeTruthy(); expect(homeP.footer.login.isDisplayed()).toBeTruthy(); } else{ console.log('This functionality is not for mobile devices'); } }); it(browser.tc_desc('UIDS-1367 Story TC3 (1) check Menu can be closed on address page'), function() { if ( !browser.mobile ) { browser.wait(EC.visibilityOf(homeP.closefooterLink), 12000, 'Close menu button is not displayed'); expect(homeP.closefooterLink.isDisplayed()).toBeTruthy(); homeP.closefooterLink.click(); //browser.indirectClick(homeP.closefooterLink); } else { console.log('This functionality is not for mobile devices'); } }); it(browser.tc_desc('check (1) Address edit boxes'), function() { browser.wait(EC.visibilityOf(dpage.address.country), 120000, 'country edit box is missing!'); //expect(dpage.addressPageSubtext.getText()).toBe(browser.params.user.authentication.language.address.stmtInstruction); expect(dpage.address.country.isDisplayed()).toBeTruthy(); }); it(browser.tc_desc('UIDS-1488 TC1 Verify Zentry Logo on address page'), function() { //expect(homeP.footer.copyrightMsgOne.isDisplayed()).toBeTruthy(); if ( !browser.mobile ) { expect(homeP.footer.zentryLogo.isDisplayed()).toBeTruthy(); } else { console.log("This functionality is not for mobile devices"); } }); //Commenting as clicking on back button is having issues to retrieve the information // it(browser.tc_desc('UIDS-1677 TC 4a (1) Click on back button (2) Verify information added in name page is retained'), function() { // browser.wait(EC.visibilityOf(dpage.address.backbtn), 120000, 'Back button on address page is not displayed'); // dpage.address.backbtn.click(); // browser.wait(EC.visibilityOf(dpage.userDetails.Prefix), 120000, 'Prefix field is not visible'); // expect(dpage.userDetails.firstName.getAttribute("value")).toBe('FirstName'); // expect(dpage.userDetails.familyName.getAttribute("value")).toBe('LastName'); // expect(dpage.userDetails.MiddleName.getAttribute("value")).toBe('Middle'); // expect(dpage.userDetails.Suffix.getAttribute("value")).toBe('Su'); // dpage.userDetails.Prefix.getText().then(function(text) // { // expect( text.trim()).toBe('Mr.'); // }); // }); // // it(browser.tc_desc('UIDS-1677 TC 4b (1) Click on continue button (2) Verify user is redirected to address page'), function() { // // dpage.userDetails.continueBtn.click(); // browser.wait(EC.visibilityOf(dpage.address.country), 120000, 'country edit box is missing!'); // expect(dpage.address.country.isDisplayed()).toBeTruthy(); // }); it(browser.tc_desc('UIDS-500 TC3a Verify label and placeholder of country field'), function() { expect(dpage.address.countryLabel.getText()).toEqual(browser.params.user.authentication.language.address.lbCountry); expect(dpage.address.countryPlaceholder.getText()).toEqual(browser.params.user.authentication.language.address.country); }); it(browser.tc_desc('UIDS-500 TC3b Verify label and placeholder of address field'), function() { expect(dpage.address.addressLable.getText()).toEqual(browser.params.user.authentication.language.address.lbStreet); expect(dpage.address.addressPlaceholder.getText()).toEqual(browser.params.user.authentication.language.address.street); }); it(browser.tc_desc('UIDS-500 TC3c Verify label and placeholder of zipcode field'), function() { expect(dpage.address.zipCodeLabel.getText()).toEqual(browser.params.user.authentication.language.address.lbZipcode); expect(dpage.address.zipCodePlaceholder.getText()).toEqual(browser.params.user.authentication.language.address.zipcode); }); it(browser.tc_desc('UIDS-500 TC3d Verify label and placeholder of city field'), function() { expect(dpage.address.cityLabel.getText()).toEqual(browser.params.user.authentication.language.address.lbCity); expect(dpage.address.cityPlaceholder.getText()).toEqual(browser.params.user.authentication.language.address.city); }); it(browser.tc_desc('UIDS-500 TC3e Verify label and placeholder of state field'), function() { expect(dpage.address.stateLabel.getText()).toEqual(browser.params.user.authentication.language.address.lbState); expect(dpage.address.statePlaceholder.getText()).toEqual(browser.params.user.authentication.language.address.state); }); it(browser.tc_desc('UIDS-500 TC3f Verify text and image of the link to add address 2'), function() { expect(dpage.address.address2LinkIcon.isDisplayed()).toBeTruthy(); dpage.address.Address2Link.getText().then(function(text) { expect(text.trim()).toBe(browser.params.user.authentication.language.address.stmtAdding); }); browser.wait(EC.visibilityOf(dpage.address.Address2Link), 5000, 'Address Line2 link is not appearing'); browser.indirectClick(dpage.address.Address2Link); }); it(browser.tc_desc('UIDS-500 TC3g Verify label and placeholder of address2'), function() { expect(dpage.address.extendedAddressLabel.getText()).toEqual(browser.params.user.authentication.language.address.lbAddLine2); expect(dpage.address.extendedAddressPlaceholder.getText()).toEqual(browser.params.user.authentication.language.address.addLine2); }); it(browser.tc_desc('UIDS-500 TC 4b (1) Inspect page header,description,continue button,Coypright text to address page'), function() { if ( !browser.mobile ) { dpage.address.pageTitleWeb.getText().then(function(text) { expect(text.toUpperCase()).toBe(browser.params.user.authentication.language.address.stmtAddress.toUpperCase()); }); expect(homeP.headerLabelOne.getText()).toEqual(browser.params.user.authentication.language.header.universalId); } else { dpage.address.pageTitleMob.getText().then(function(text) { expect(text.toUpperCase()).toBe(browser.params.user.authentication.language.address.stmtAddress.toUpperCase()); }); } expect(dpage.addressPageSubtext.getText()).toEqual(browser.params.user.authentication.language.address.stmtInstruction); dpage.address.continueBtn.getText().then(function(text) { expect((text.trim()).toUpperCase()).toBe(browser.params.user.authentication.language.address.btnContinue.toUpperCase()); }); if (browser.params.langOption === 'es') { homeP.footer.copyrightMsgOne.getText().then(function (text) { var abc = text.toString().replace("\n", " "); expect(abc).toEqual("Copyright Ⓒ 2017 Zentry Proprietary and Confidential _Español"); }); } else if (browser.params.langOption === 'ja') { homeP.footer.copyrightMsgOne.getText().then(function (text) { var abc = text.toString().replace("\n", " "); expect(abc).toEqual("著作権 Ⓒ 2017年 Zentry独自および機密"); }); } else if (browser.params.langOption === 'en') { homeP.footer.copyrightMsgOne.getText().then(function (text) { var abc = text.toString().replace("\n", " "); expect(abc).toEqual("Copyright Ⓒ 2017 Zentry Proprietary and Confidential"); }); } }); it(browser.tc_desc('UIDS-500 TC24a (1) Enter Country, Addresses, State, Zip code and State'), function() { dpage.address.country.sendKeys('United States'); browser.sleep(1000); browser.indirectClick(dpage.address.selectValue); //dpage.address.selectValue.click(); dpage.address.street.sendKeys('151 W 34th St'); if (browser.params.target === 'remote') { if ( browser.mobile ) { dpage.address.pageTitle.click(); // hide virtual keyboards } } browser.wait(EC.visibilityOf(dpage.address.extendedAddress), 12000, 'Address Line2 is not appearing'); dpage.address.extendedAddress.sendKeys('152 S 37th St'); if (browser.params.target === 'remote') { if ( browser.mobile ) { dpage.address.pageTitle.click(); } } dpage.address.zipcode.sendKeys('10001'); browser.indirectClick(dpage.address.city); browser.sleep(15000); // dpage.address.city.sendKeys('New York'); // browser.indirectClick(dpage.address.selectValue); // dpage.address.state.sendKeys('New York'); // browser.sleep(1000); // browser.indirectClick(dpage.address.selectValue); // browser.sleep(1000); expect(dpage.address.continueBtn.isDisplayed()).toBeTruthy(); browser.sleep(1000); browser.indirectClick(dpage.address.continueBtn); browser.waitForAngular(); browser.wait(EC.visibilityOf(dpage.confirmation.ConfirmSubTitle), 120000, 'confirm subtext is missing, or the App is down!'); }); });
const numbers = [2, 3, 4, 5, 6, 7]; // for (let i = 0; i < numbers.length; i++) { // const element = numbers[i]; // const square = element * element; // console.log(square); // } // const result = numbers.filter(x => x > 4); // console.log(result); // function square (element) { // return element * element; // } // const result = numbers.map(square); // console.log(result); // const result = numbers.map(function (element) { // return element * element; // }) // console.log(result); // const result = numbers.filter(x => x < 5); // console.log(result); // const result = numbers.find(x => x > 5); // console.log(result) const info = [ {fname: 'Wahidul', lname: 'Islam'}, {fname: 'Abdul', lname: 'Kadir'}, {fname: 'Abdus', lname: 'Salam'} ] // const fullName = info.map(x => x.fname + ' ' + x.lname); // console.log(fullName); // const result = info.filter(x => x.fname.length > 5); // console.log(result); const result = info.find(x => x.fname.length > 5); console.log(result);
'use strict'; const express = require('express'); const router = express.Router(); const track = require('../../service/track'); // POST /admin/tracks router.post('/', (req, res) => { const title = req.body.title; const genres = JSON.parse(req.body.genres); const artists = JSON.parse(req.body.artists); const rank = req.body.rank; const link = req.body.link; const dropAt = req.body.dropAt; const release = req.body.release; if (title === null || title === '' || genres === null || genres === '' || artists === null || artists === '' || rank === null || rank === '' || link === null || link === '' ||dropAt === null || dropAt === '') { res.status(412).json({}); return; } track.addTrack(title, rank, link, dropAt, release) .then((tracks) => { const addGenre = function(){ return new Promise((resolve, reject) => { const genreRet = []; for(let i=0; i<genres.length; i++) { track.addGenre(tracks.id, genres[i].genreId) .then((genre) => { genreRet.push(genre.tagId); if(i === genres.length-1) { resolve(genreRet); } }) .catch((e) => { reject(e); return; }); } }); } const addCompose = function(){ return new Promise((resolve, reject) => { const artistRet = []; for(let i=0; i<artists.length; i++) { track.addCompose(tracks.id, artists[i].artistId) .then((compose) => { artistRet.push(compose.artistId); if(i === artists.length-1) { resolve(artistRet); } }) .catch((e) => { reject(e); return; }); } }); } Promise.all([ addGenre(genres, track), addCompose(artists, track) ]) .then((value) => { tracks.dataValues.artists = value[0]; tracks.dataValues.genres = value[1]; res.status(201).json(tracks); return; }) .catch(() =>{ res.status(500).json({}); return; }); }) .catch(() => { res.status(500).json({}); return; }); }); router.post('/:id/genres', (req, res) => { const trackId = parseInt(req.params.id); const genreId = parseInt(req.body.genreId); if(trackId === null || trackId === '' || genreId === null || genreId === '') { res.status(412).json({}); return; } track.addGenre(trackId, genreId) .then((data) => { res.status(201).json(data); return; }) .catch(() => { res.status(500).json({}); return; }); }); router.delete('/:trackId/genres/:genreId', (req, res) => { const trackId = parseInt(req.params.trackId); const genreId = parseInt(req.params.genreId); if(trackId === null || trackId === '' || genreId === null || genreId === '') { res.status(412).json({}); return; } track.deleteGenre(trackId, genreId) .then(() => { res.status(204).json({}); return; }) .catch((e) => { console.log(e); res.status(500).json({}); return; }); }); router.post('/:id/artists', (req, res) => { const trackId = parseInt(req.params.id); const artistId = parseInt(req.body.artistId); if(trackId === null || trackId === '' || artistId === null || artistId === '') { res.status(412).json({}); return; } track.addCompose(trackId, artistId) .then((data) => { res.status(201).json(data); return; }) .catch(() => { res.status(500).json({}); return; }); }); router.delete('/:trackId/artists/:artistId', (req, res) => { const trackId = parseInt(req.params.trackId); const artistId = parseInt(req.params.artistId); if(trackId === null || trackId === '' || artistId === null || artistId === '') { res.status(412).json({}); return; } track.deleteCompose(trackId, artistId) .then(() => { res.status(204).json({}); return; }) .catch(() => { res.status(500).json({}); return; }); }); module.exports = router;
/** * Scriptdoc-file for jQuery 1.2.3 * * Created: Jan 25, 2007 19:31:20 GMT * Courtesy of Edwin Martin * * Updated: July 12, 2007 * Updated by Michelle Petersen * * Updated: Oct 15, 2007 * Updated by Davey Waterson * * Updated: Feb 26, 2008 * Updated by Michelle Petersen */ /** * This function accepts a string containing a CSS or basic XPath selector which is then used to match a set of elements. * <br> * <br><b>Alternatives</b><br> * <br> * <b>$</b>(<b>html</b>: String) : jQuery<br> * <br> * Create DOM elements on-the-fly from the provided String of raw HTML.<br> * <br> * <b>$</b>(<b>elems</b>: Element|Array) : jQuery<br> * <br> * Wrap jQuery functionality around a single or multiple DOM Element(s).<br> * <br> * <b>$</b>(<b>fn</b>: Function) : jQuery<br> * <br> * A shorthand for $(document).<br> * <br> * @param {String|Element|Function|jQuery} expr * @param {Element|jQuery} context * @return {jQuery} */ function jQuery(expr, context){}; /** * This function accepts a string containing a CSS or basic XPath selector which is then used to match a set of elements. * <br> * <br><b>Alternatives</b><br> * <br> * <b>$</b>(<b>html</b>: String) : jQuery<br> * <br> * Create DOM elements on-the-fly from the provided String of raw HTML.<br> * <br> * <b>$</b>(<b>elems</b>: Element|Array) : jQuery<br> * <br> * Wrap jQuery functionality around a single or multiple DOM Element(s).<br> * <br> * <b>$</b>(<b>fn</b>: Function) : jQuery<br> * <br> * A shorthand for $(document).<br> * <br> * @param {String} expr * @param {Element|jQuery} context * @return {jQuery} */ var $ = jQuery; /** * The current version of jQuery. * @return {String} */ jQuery.jquery = '1.2.3'; /** * The current version of jQuery. * @return {String} */ $.jquery = '1.2.3'; /** * The number of elements in the jQuery object. * @alias $.length * @type {Number} */ jQuery.prototype.length = 0; /** * The number of elements currently matched. * @return {Number} */ jQuery.prototype.size = function(){}; /** * Access a single matched element. * @param {Number} num Element's index in array * @return {Element} */ jQuery.prototype.get = function(num){}; /** * Get a document via ajax.<br> * This is an easy way to send a simple GET request to a server without having to use * the more complex $.ajax function. <BR> * It allows a single callback function to be specified that will be executed when * the request is complete (and only if the response has a successful response code). * <BR>If you need to have both error and success callbacks, you may want to use * $.ajax.<br> * @param {String} url Document URL * @param {Object} data Parameters hash to send with request * @param {Function} callback Callback function which will be called when document is loaded * @return {XMLHttpRequest} */ jQuery.get = function(url, data, callback){}; /** * Get a document via ajax.<br> * This is an easy way to send a simple GET request to a server without having to use * the more complex $.ajax function. <BR> * It allows a single callback function to be specified that will be executed when * the request is complete (and only if the response has a successful response code). * <BR>If you need to have both error and success callbacks, you may want to use * $.ajax.<br> * @param {String} url Document URL * @param {Object} data Parameters hash to send with request * @param {Function} callback Callback function which will be called when document is loaded * @return {XMLHttpRequest} */ $.get = function(url, data, callback){}; /** * Set the jQuery object to an array of elements, while maintaining the stack. * @param {Element|Array} elems * @return {jQuery} */ jQuery.prototype.pushStack = function(elems){}; /** * Set the jQuery object to an array of elements. * @param {Element|Array} elems * @return {jQuery} */ jQuery.prototype.setArray = function(elems){}; /** * Execute a function within the context of every matched element. * @param {Function} fn * @return {jQuery} */ jQuery.prototype.each = function(fn){}; /** * Searches every matched element for the object and returns the index of the element, if found, starting with zero. * @param {Element} subject * @return {Number} */ jQuery.prototype.index = function(subject){}; /** * Access a property on the first matched element. * <br> * <br><b>Alternatives</b><br> * <br> * <b>attr</b>(<b>properties</b>: Map) : jQuery<br> * <br> * Set a key/value object as properties to all matched elements.<br> * <br> * <b>attr</b>(<b>key</b>: String, <b>value</b>: Object) : jQuery<br> * <br> * Set a single property to a value, on all matched elements.<br> * <br> * <b>attr</b>(<b>key</b>: String, <b>value</b>: Function) : jQuery<br> * <br> * Set a single property to a computed value, on all matched elements.<br> * <br> * @param {String} name * @param {String} value * @return {Object} */ jQuery.prototype.attr = function(name, value){}; /** * Access a style property on the first matched element. * <br> * <br><b>Alternatives</b><br> * <br> * <b>css</b>(<b>properties</b>: Map) : jQuery<br> * <br> * Set a key/value object as style properties to all matched elements.<br> * <br> * <b>css</b>(<b>key</b>: String, <b>value</b>: String|Number) : jQuery<br> * <br> * Set a single style property to a value, on all matched elements.<br> * <br> * @param {String} name * @param {String} value * @return {String} */ jQuery.prototype.css = function(name, value){}; /** * Get the text contents of all matched elements. * <br> * <br><b>Alternatives</b><br> * <br> * <b>text</b>(<b>val</b>: String) : String<br> * <br> * Set the text contents of all matched elements.<br> * @param {String} value * @return {String} */ jQuery.prototype.text = function(value){}; /** * Wrap all matched elements with a structure of other elements. * <br> * <br><b>Alternatives</b><br> * <br> * <b>wrap</b>(<b>elem</b>: Element) : jQuery<br> * <br> * Wrap all matched elements with a structure of other elements.<br> * <br> * @param {String} html * @return {jQuery} */ jQuery.prototype.wrap = function(html){}; /** * Append content to the inside of every matched element. * @param {Element|jQuery|String} content * @return {jQuery} */ jQuery.prototype.append = function(content){}; /** * Prepend content to the inside of every matched element. * @param {Element|jQuery|String} content * @return {jQuery} */ jQuery.prototype.prepend = function(content){}; /** * Insert content before each of the matched elements. * @param {Element|jQuery|String} content * @return {jQuery} */ jQuery.prototype.before = function(content){}; /** * Insert content after each of the matched elements. * @param {Element|jQuery|String} content * @return {jQuery} */ jQuery.prototype.after = function(content){}; /** * End the most recent 'destructive' operation, reverting the list of matched elements back to its previous state. * @return {jQuery} */ jQuery.prototype.end = function(){}; /** * Searches for all elements that match the specified expression. * @param {String} expr * @return {jQuery} */ jQuery.prototype.find = function(expr){}; /** * Clone matched DOM Elements and select the clones.<BR> * <BR> * Calling the clone method with an argument * is being deprecated (the clone method, as a whole, is being kept). <BR> * <BR> * Instead of calling <B>.clone(false)</B> you should now do: <b>.clone().empty()</B> instead. * @return {jQuery} */ jQuery.prototype.clone = function(){}; /** * Removes all elements from the set of matched elements that do not match the specified expression(s). * <br> * <br><b>Alternatives</b><br> * <br> * <b>filter</b>(<b>filter</b>: Function) : jQuery<br> * <br> * Removes all elements from the set of matched elements that do not pass the specified filter.<br> * <br> * @param {String|Function} expression * @return {jQuery} */ jQuery.prototype.filter = function(expression){}; /** * Removes the specified Element from the set of matched elements. * <br> * <br><b>Alternatives</b><br> * <br> * <b>not</b>(<b>expr</b>: String) : jQuery<br> * <br> * Removes elements matching the specified expression from the set of matched elements.<br> * <br> * <b>not</b>(<b>elems</b>: jQuery) : jQuery<br> * <br> * Removes any elements inside the array of elements from the set of matched elements.<br> * <br> * @param {String|jQuery} expr * @return {jQuery} */ jQuery.prototype.not = function(expr){}; /** * Adds more elements, matched by the given expression, to the set of matched elements. * <br> * <br><b>Alternatives</b><br> * <br> * <b>add</b>(<b>html</b>: String) : jQuery<br> * <br> * Adds more elements, created on the fly, to the set of matched elements.<br> * <br> * <b>add</b>(<b>elements</b>: Element|Array) : jQuery<br> * <br> * Adds one or more Elements to the set of matched elements.<br> * <br> * @param {String|Element|Array} expr * @return {jQuery} */ jQuery.prototype.add = function(expr){}; /** * Checks the current selection against an expression and returns true, if at least one element of the selection fits the given expression. * @param {String} expr * @return {Boolean} */ jQuery.prototype.is = function(expr){}; /** * Get the current value of the first matched element. * <br> * <br><b>Alternatives</b><br> * <br> * <b>val</b>(<b>value</b>: String) : jQuery<br> * <br> * Set the value of every matched element.<br> * <br> * @param {String} [value] New value * @return {String} */ jQuery.prototype.val = function(value){}; /** * Get the html contents of the first matched element. * <br> * <br><b>Alternatives</b><br> * <br> * <b>html</b>(<b>value</b>: String) : jQuery<br> * <br> * Set the html contents of every matched element.<br> * <br> * @param {String} [value] New value * @return {String} */ jQuery.prototype.html = function(value){}; /** * @param {Array} args * @param {Boolean} table * @param {Number} dir * @param {Function} fn * @return {jQuery} */ jQuery.prototype.domManip = function(){}; /** * Extends the jQuery object itself. * <br> * <br><b>Alternatives</b><br> * <br> * <b>$.extend</b>(<b>target</b>: Object, <b>prop1</b>: Object, <b>propN</b>: Object) : Object<br> * <br> * Extend one object with one or more others, returning the original, modified, object.<br> * <br> * @param {Object} prop * @return {Object} */ jQuery.extend = function(prop){}; /** * Extends the jQuery object itself. * <br> * <br><b>Alternatives</b><br> * <br> * <b>$.extend</b>(<b>target</b>: Object, <b>prop1</b>: Object, <b>propN</b>: Object) : Object<br> * <br> * Extend one object with one or more others, returning the original, modified, object.<br> * <br> * @param {Object} prop * @return {Object} */ $.extend = function(prop){}; /** * Run this function to give control of the $ variable back to whichever library first implemented it. * <br> * <br><b>Alternatives</b><br> * <br> * <b>$.noConflict</b>(<b>extreme</b>) : jQuery<br> * <BR>Revert control of both the $ and jQuery variables to their original owners. * <B>Use with discretion.</B> * <BR>This is a more-extreme version of the simple noConflict method, * as this one will completely undo what jQuery has introduced. This is to be * used in an extreme case where you'd like to embed jQuery into a high-conflict * environment. * <BR><B>NOTE:</B> It's very likely that plugins won't work after this particular * method has been called. * @return {jQuery} */ jQuery.noConflict = function(){}; /** * A generic iterator function, which can be used to seemlessly iterate over both objects and arrays. * @id jQuery.$.each * @alias $.each * @param {Object} obj * @param {Function} fn * @return {Object} */ jQuery.each = function(obj, fn){}; /** * A generic iterator function, which can be used to seemlessly iterate over both objects and arrays. * @id jQuery.$.each * @alias $.each * @param {Object} obj * @param {Function} fn * @return {Object} */ $.each = function(obj, fn){}; /** * Remove the whitespace from the beginning and end of a string. * @param {String} str * @return {String} */ jQuery.trim = function(str){}; /** * Remove the whitespace from the beginning and end of a string. * @param {String} str * @return {String} */ $.trim = function(str){}; /** * Merge two arrays together, removing all duplicates. * @param {Array} first * @param {Array} second * @return {Array} */ jQuery.merge = function(first, second){}; /** * Merge two arrays together, removing all duplicates. * @param {Array} first * @param {Array} second * @return {Array} */ $.merge = function(first, second){}; /** * Filter items out of an array, by using a filter function. * @param {Array} array * @param {Function} fn * @param {Boolean} inv * @return {Array} */ jQuery.grep = function(array, fn, inv){}; /** * Filter items out of an array, by using a filter function. * @param {Array} array * @param {Function} fn * @param {Boolean} inv * @return {Array} */ $.grep = function(array, fn, inv){}; /** * Translate all items in an array to another array of items. * @param {Array} array * @param {Function} fn * @return {Array} */ jQuery.map = function(array, fn){}; /** * Translate all items in an array to another array of items. * @param {Array} array * @param {Function} fn * @return {Array} */ $.map = function(array, fn){}; /** * Determine the index of the first parameter in the <code>array</code>. * @param {String} value * @param {Array} array * @return {Number} -1 if not found */ jQuery.inArray = function(value, array){}; /** * Determine the index of the first parameter in the <code>array</code>. * @param {String} value * @param {Array} array * @return {Number} -1 if not found */ $.inArray = function(value, array){}; /** * Contains flags for the useragent, read from navigator. */ jQuery.browser = { msie: true, opera: true, mozilla: true, safari: true, version: '' }; /** * Contains flags for the useragent, read from navigator. */ $.browser = { msie: true, opera: true, mozilla: true, safari: true, version: '' }; /** * Get a set of elements containing the unique parents of the matched set of elements. * @param {String} [expr] * @return {jQuery} */ jQuery.prototype.parent = function(expr){}; /** * Get a set of elements containing the unique ancestors of the matched set of elements (except for the root element). * @param {String} [expr] * @return {jQuery} */ jQuery.prototype.parents = function(expr){}; /** * Get a set of elements containing the unique next siblings of each of the matched set of elements. * @param {String} [expr] * @return {jQuery} */ jQuery.prototype.next = function(expr){}; /** * Get a set of elements containing the unique previous siblings of each of the matched set of elements. * @param {String} [expr] * @return {jQuery} */ jQuery.prototype.prev = function(expr){}; /** * Get a set of elements containing all of the unique siblings of each of the matched set of elements. * @param {String} [expr] * @return {jQuery} */ jQuery.prototype.siblings = function(expr){}; /** * Get a set of elements containing all of the unique children of each of the matched set of elements. * @param {String} [expr] * @return {jQuery} */ jQuery.prototype.children = function(expr){}; /** * Append all of the matched elements to another, specified, set of elements. * @param {Element|jQuery} content * @return {jQuery} */ jQuery.prototype.appendTo = function(content){}; /** * Prepend all of the matched elements to another, specified, set of elements. * @param {Element|jQuery} content * @return {jQuery} */ jQuery.prototype.prependTo = function(content){}; /** * Insert all of the matched elements before another, specified, set of elements. * @param {Element|jQuery} content * @return {jQuery} */ jQuery.prototype.insertBefore = function(content){}; /** * Insert all of the matched elements after another, specified, set of elements. * @param {Element|jQuery} content * @return {jQuery} */ jQuery.prototype.insertAfter = function(content){}; /** * Remove an attribute from each of the matched elements. * @param {String} name * @return {jQuery} */ jQuery.prototype.removeAttr = function(name){}; /** * Adds the specified class(es) to each of the set of matched elements. * @param {String} className * @return {jQuery} */ jQuery.prototype.addClass = function(className){}; /** * Replaces one class name to another on each of the set of matched elements. * @param {String} from Class to be replaced. Can contain regexp patterns * @param {String} to New class name, can be empty string * @return {jQuery} */ jQuery.prototype.replaceClass = function(from, to){}; /** * Removes all or the specified class(es) from the set of matched elements. * @param {String} className * @return {jQuery} */ jQuery.prototype.removeClass = function(className){}; /** * Adds the specified class if it is not present, removes it if it is present. * @param {String} className * @return {jQuery} */ jQuery.prototype.toggleClass = function(className){}; /** * Removes all matched elements from the DOM. * @param {String} expr * @return {jQuery} */ jQuery.prototype.remove = function(expr){}; /** * Removes all child nodes from the set of matched elements. * @return {jQuery} */ jQuery.prototype.empty = function(){}; /** * Reduce the set of matched elements to a single element. * @param {Number} pos * @return {jQuery} */ jQuery.prototype.eq = function(pos){}; /** * Reduce the set of matched elements to all elements before a given position.<BR> * <BR>This method is being deprecated in favor of the new <b>.slice()</b> method * (which works identically to an array's slice method). <BR> * <BR> * You can duplicate <b>$("div").lt(2) </B>like so: <b>$("div").slice(0,2);</b> * @deprecated * @param {Number} pos * @return {jQuery} */ jQuery.prototype.lt = function(pos){}; /** * Reduce the set of matched elements to all elements after a given position. * <BR>This method is being deprecated in favor of the new <b>.slice()</b> method * (which works identically to an array's slice method). <BR> * <BR> * You can duplicate <b>$("div").gt(2) </B>like so: <b>$("div").slice(2);</b> * @deprecated * @param {Number} pos * @return {jQuery} */ jQuery.prototype.gt = function(pos){}; /** * Filter the set of elements to those that contain the specified text.<BR> * <BR> * This method is being deprecated in favor of just using a regular .filter() * statement. <BR> * <BR> * You can duplicate <B>.contains()</B> like so: <B>$("div").filter(":contains(Your Text)");</B> * @param {String} str * @return {jQuery} */ jQuery.prototype.contains = function(str){}; /** * Get the current computed, pixel, width of the first matched element. * <br> * <br><b>Alternatives</b><br> * <br> * <b>width</b>(<b>value</b>: String|Number) : jQuery<br> * <br> * Set the CSS width of every matched element.<br> * <br> * @param {String|Number} [value] * @return {Number} */ jQuery.prototype.width = function(value){}; /** * Get the current computed, pixel, height of the first matched element. * <br> * <br><b>Alternatives</b><br> * <br> * <b>height</b>(<b>val</b>: String|Number) : jQuery<br> * <br> * Set the CSS width of every matched element.<br> * <br> * @param {String|Number} [value] * @return {String} */ jQuery.prototype.height = function(value){}; /** * A handy, and fast, way to traverse in a particular direction and find a specific element. * @param {Element} cur * @param {String|Number} num * @param {String} dir * @return {Element} */ jQuery.nth = function(cur, num, dir){}; /** * A handy, and fast, way to traverse in a particular direction and find a specific element. * @param {Element} cur * @param {String|Number} num * @param {String} dir * @return {Element} */ $.nth = function(cur, num, dir){}; /** * All elements on a specified axis. * @param {Element} elem * @return {Array} */ jQuery.sibling = function(elem){}; /** * All elements on a specified axis. * @param {Element} elem * @return {Array} */ $.sibling = function(elem){}; /** * Binds a handler to a particular event (like click) for each matched element. * @param {String} type * @param {Function} fn * @param {Object} data * @return {jQuery} */ jQuery.prototype.bind = function(type, fn){}; /** * Binds a handler to a particular event (like click) for each matched element. * @param {String} type * @param {Function} fn * @param {Object} data * @return {jQuery} */ jQuery.prototype.one = function(type, fn){}; /** * The opposite of bind, removes a bound event from each of the matched elements. * @param {String} type * @param {Function} fn * @return {jQuery} */ jQuery.prototype.unbind = function(type, fn){}; /** * Trigger a type of event on every matched element. * @param {String} type * @return {jQuery} */ jQuery.prototype.trigger = function(type){}; /** * Toggle between two function calls every other click. * <br> * <br><b>Alternatives</b><br> * <br> * <b>toggle</b>() : jQuery<br> * <br> * Toggles each of the set of matched elements.<br> * <br> * @param {Function} even * @param {Function} odd * @return {jQuery} */ jQuery.prototype.toggle = function(odd, even){}; /** * A method for simulating hovering (moving the mouse on, and off, an object). * @param {Function} over * @param {Function} out * @return {jQuery} */ jQuery.prototype.hover = function(over, out){}; /** * Bind a function to be executed whenever the DOM is ready to be traversed and manipulated. * @param {Function} fn * @return {jQuery} */ jQuery.prototype.ready = function(fn){}; /** * Bind a function to the scroll event of each matched element. * @param {Function} fn * @return {jQuery} */ jQuery.prototype.scroll = function(fn){}; /** * Bind a function to the submit event of each matched element. * <br> * <br><b>Alternatives</b><br> * <br> * <b>submit</b>() : jQuery<br> * <br> * Trigger the submit event of each matched element.<br> * <br> * @param {Function} fn * @return {jQuery} */ jQuery.prototype.submit = function(fn){}; /** * Bind a function to the focus event of each matched element. * <br> * <br><b>Alternatives</b><br> * <br> * <b>focus</b>() : jQuery<br> * <br> * Trigger the focus event of each matched element.<br> * <br> * @param {Function} fn * @return {jQuery} */ jQuery.prototype.focus = function(fn){}; /** * Bind a function to the keydown event of each matched element. * @param {Function} fn * @return {jQuery} */ jQuery.prototype.keydown = function(fn){}; /** * Bind a function to the dblclick event of each matched element. * @param {Function} fn * @return {jQuery} */ jQuery.prototype.dblclick = function(fn){}; /** * Bind a function to the keypress event of each matched element. * @id jQuery.keypress * @alias $.keypress * @alias jQuery.prototype.keypress * @param {Function} fn * @return {jQuery} */ jQuery.prototype.keypress = function(){}; /** * Bind a function to the error event of each matched element. * @param {Function} fn * @return {jQuery} */ jQuery.prototype.error = function(fn){}; /** * Bind a function to the blur event of each matched element. * <br> * <br><b>Alternatives</b><br> * <br> * <b>blur</b>() : jQuery<br> * <br> * Trigger the blur event of each matched element.<br> * <br> * @param {Function} fn * @return {jQuery} */ jQuery.prototype.blur = function(fn){}; /** * Bind a function to the load event of each matched element. * <br> * <br><b>Alternatives</b><br> * <br> * <b>load</b>(<b>url</b>: String, <b>params</b>: Object, <b>callback</b>: Function) : jQuery<br> * <br> * Load HTML from a remote file and inject it into the DOM.<br> * <br> * @param {Function} fn * @return {jQuery} */ jQuery.prototype.load = function(fn){}; /** * Bind a function to the select event of each matched element. * <br> * <br><b>Alternatives</b><br> * <br> * <b>select</b>() : jQuery<br> * <br> * Trigger the select event of each matched element.<br> * <br> * @param {Function} fn * @return {jQuery} */ jQuery.prototype.select = function(fn){}; /** * Bind a function to the mouseup event of each matched element. * @param {Function} fn * @return {jQuery} */ jQuery.prototype.mouseup = function(fn){}; /** * Bind a function to the unload event of each matched element. * @param {Function} fn * @return {jQuery} */ jQuery.prototype.unload = function(fn){}; /** * Bind a function to the change event of each matched element. * @param {Function} fn * @return {jQuery} */ jQuery.prototype.change = function(fn){}; /** * Bind a function to the mouseout event of each matched element. * @param {Function} fn * @return {jQuery} */ jQuery.prototype.mouseout = function(fn){}; /** * Bind a function to the keyup event of each matched element. * @param {Function} fn * @return {jQuery} */ jQuery.prototype.keyup = function(fn){}; /** * Bind a function to the click event of each matched element. * <br> * <br><b>Alternatives</b><br> * <br> * <b>click</b>() : jQuery<br> * <br> * Trigger the click event of each matched element.<br> * <br> * @param {Function} fn * @return {jQuery} */ jQuery.prototype.click = function(fn){}; /** * Bind a function to the resize event of each matched element. * @param {Function} fn * @return {jQuery} */ jQuery.prototype.resize = function(fn){}; /** * Bind a function to the mousemove event of each matched element. * @param {Function} fn * @return {jQuery} */ jQuery.prototype.mousemove = function(fn){}; /** * Bind a function to the mousedown event of each matched element. * @param {Function} fn * @return {jQuery} */ jQuery.prototype.mousedown = function(fn){}; /** * Bind a function to the mouseover event of each matched element. * @param {Function} fn * @return {jQuery} */ jQuery.prototype.mouseover = function(fn){}; /** * Displays each of the set of matched elements if they are hidden. * <br> * <br><b>Alternatives</b><br> * <br> * <b>show</b>(<b>speed</b>: String|Number, <b>callback</b>: Function) : jQuery<br> * <br> * Show all matched elements using a graceful animation and firing an optional callback after completion.<br> * <br> * @param {String|Number} [speed] * @param {Function} [callback] * @return {jQuery} */ jQuery.prototype.show = function(speed, callback){}; /** * Hides each of the set of matched elements if they are shown. * <br> * <br><b>Alternatives</b><br> * <br> * <b>hide</b>(<b>speed</b>: String|Number, <b>callback</b>: Function) : jQuery<br> * <br> * Hide all matched elements using a graceful animation and firing an optional callback after completion.<br> * <br> * @param {String|Number} [speed] * @param {Function} [callback] * @return {jQuery} */ jQuery.prototype.hide = function(speed, callback){}; /** * Reveal all matched elements by adjusting their height and firing an optional callback after completion. * @alias jQuery.prototype.slideDown * @param {String|Number} speed * @param {Function} [callback] * @return {jQuery} */ jQuery.prototype.slideDown = function(speed, callback){}; /** * Hide all matched elements by adjusting their height and firing an optional callback after completion. * @param {String|Number} speed * @param {Function} [callback] * @return {jQuery} */ jQuery.prototype.slideUp = function(speed, callback){}; /** * Toggle the visibility of all matched elements by adjusting their height and firing an optional callback after completion. * @param {String|Number} speed * @param {Function} [callback] * @return {jQuery} */ jQuery.prototype.slideToggle = function(speed, callback){}; /** * Fade in all matched elements by adjusting their opacity and firing an optional callback after completion. * @param {String|Number} speed * @param {Function} [callback] * @return {jQuery} */ jQuery.prototype.fadeIn = function(speed, callback){}; /** * Fade out all matched elements by adjusting their opacity and firing an optional callback after completion. * @param {String|Number} speed * @param {Function} [callback] * @return {jQuery} */ jQuery.prototype.fadeOut = function(speed, callback){}; /** * Fade the opacity of all matched elements to a specified opacity and firing an optional callback after completion. * @param {String|Number} speed * @param {Number} opacity * @param {Function} callback * @return {jQuery} */ jQuery.prototype.fadeTo = function(speed, callback){}; /** * A function for making your own, custom, animations. * @param {Object} params * @param {String|Number} speed * @param {String} easing * @param {Function} callback * @return {jQuery} */ jQuery.prototype.animate = function(params, speed, easing, callback){}; /** * Load HTML from a remote file and inject it into the DOM, only * if it's been modified by the server.<BR> * <BR> * This convenience method is being removed in favor of the long form use of $.ajax()<BR> * <BR> * <PRE> * $.ajax({ url: "some.php", ifModified: true, ...}); * </PRE> * @param {String} url * @param {Object} params * @param {Function} callback * @return {jQuery} */ jQuery.prototype.loadIfModified = function(url, params, callback){}; /** * Serializes a set of input elements into a string of data. * @return {String} */ jQuery.prototype.serialize = function(){}; /** * Evaluate all script tags inside this jQuery. * @return {jQuery} */ jQuery.prototype.evalScripts = function(){}; /** * Attach a function to be executed whenever an AJAX request begins and there is none already active. * @param {Function} callback * @return {jQuery} */ jQuery.prototype.ajaxStart = function(callback){}; /** * Attach a function to be executed whenever all AJAX requests have ended. * @param {Function} callback * @return {jQuery} */ jQuery.prototype.ajaxStop = function(callback){}; /** * Attach a function to be executed whenever an AJAX request completes. * @param {Function} callback * @return {jQuery} */ jQuery.prototype.ajaxComplete = function(callback){}; /** * Attach a function to be executed whenever an AJAX request completes successfully. * @param {Function} callback * @return {jQuery} */ jQuery.prototype.ajaxSuccess = function(callback){}; /** * Attach a function to be executed whenever an AJAX request fails. * @param {Function} callback * @return {jQuery} */ jQuery.prototype.ajaxError = function(callback){}; /** * Attach a function to be executed before an AJAX request is sent. * @param {Function} callback * @return {jQuery} */ jQuery.prototype.ajaxSend = function(callback){}; /** * Load a remote page using an HTTP GET request, only if * it has been modified since it was last retrieved.<BR> * <BR> * This convenience method is being removed in favor of the long form use of $.ajax()<BR> * <BR> * <PRE> * $.ajax({ url: "some.php", ifModified: true, ...}); * </PRE> * @param {String} url * @param {Object} params * @param {Function} callback * @return {XMLHttpRequest} */ jQuery.getIfModified = function(url, params, callback){}; /** * Load a remote page using an HTTP GET request, only if * it has been modified since it was last retrieved.<BR> * <BR> * This convenience method is being removed in favor of the long form use of $.ajax()<BR> * <BR> * <PRE> * $.ajax({ url: "some.php", ifModified: true, ...}); * </PRE> * @param {String} url * @param {Object} params * @param {Function} callback * @return {XMLHttpRequest} */ $.getIfModified = function(url, params, callback){}; /** * Loads, and executes, a remote JavaScript file using an HTTP GET request. * @param {String} url * @param {Function} [callback] * @return {XMLHttpRequest} */ jQuery.getScript = function(url, callback){}; /** * Loads, and executes, a remote JavaScript file using an HTTP GET request. * @param {String} url * @param {Function} [callback] * @return {XMLHttpRequest} */ $.getScript = function(url, callback){}; /** * Load JSON data using an HTTP GET request. * @param {String} url * @param {Object} params * @param {Function} callback * @return {XMLHttpRequest} */ jQuery.getJSON = function(url, params, callback){}; /** * Load JSON data using an HTTP GET request. * @param {String} url * @param {Object} params * @param {Function} callback * @return {XMLHttpRequest} */ $.getJSON = function(url, params, callback){}; /** * Load a remote page using an HTTP POST request. * @param {String} url * @param {Object} params * @param {Function} [callback] * @return {XMLHttpRequest} */ jQuery.post = function(url, params, callback){}; /** * Load a remote page using an HTTP POST request. * @param {String} url * @param {Object} params * @param {Function} [callback] * @return {XMLHttpRequest} */ $.post = function(url, params, callback){}; /** * Set the timeout of all AJAX requests to a specific amount of time.<BR> * <BR> * This convenience method is being removed in favor of the long form * use of the more-explicit $.ajaxSetup():<BR> * <BR> * <PRE>$.ajaxSetup({timeout: 3000});</PRE> * @param {Number} time */ jQuery.ajaxTimeout = function(time){}; /** * Set the timeout of all AJAX requests to a specific amount of time.<BR> * <BR> * This convenience method is being removed in favor of the long form * use of the more-explicit $.ajaxSetup():<BR> * <BR> * <PRE>$.ajaxSetup({timeout: 3000});</PRE> * @param {Number} time */ $.ajaxTimeout = function(time){}; /** * Setup global settings for AJAX requests. * @param {Object} settings * @return {undefined} */ jQuery.ajaxSetup = function(){}; /** * Setup global settings for AJAX requests. * @param {Object} settings * @return {undefined} */ $.ajaxSetup = function(){}; /** * Load a remote page using an HTTP request. * @param {Object} properties * @return {XMLHttpRequest} */ jQuery.ajax = function(){}; /** * Load a remote page using an HTTP request. * @param {Object} properties * @return {XMLHttpRequest} */ $.ajax = function(){}; /** * Add the previous selection to the current selection. * <BR>Useful for traversing elements, and then adding something that was matched before the last traversion. * @return {jQuery} */ jQuery.prototype.andSelf = function(){}; /** * Find all the child nodes inside the matched elements (including text nodes), or the content document, if the element is an iframe. * @return {jQuery} */ jQuery.prototype.contents = function(){}; /** * Checks the current selection against a class and returns true, if at least one element of the selection has the given class. * @param {String} className * @return {Boolean} */ jQuery.prototype.hasClass = function(className){}; /** * Selects a subset of the matched elements. * @param {Number} start * @param {Number} [end] * @return {jQuery} */ jQuery.prototype.slice = function(start, end){}; /** * Find all sibling elements before the current element. * @param {String} expr * @return {jQuery} */ jQuery.prototype.prevAll = function(expr){}; /** * Find all sibling elements after the current element. * @param {String} expr * @return {jQuery} */ jQuery.prototype.nextAll = function(expr){}; /** * Wrap all the elements in the matched set into a single wrapper element. * @param {String} html * @return {jQuery} */ jQuery.prototype.wrapAll = function(html){}; /** * Wrap the inner child contents of each matched element (including text nodes) * @param {String} html * @return {jQuery} */ jQuery.prototype.wrapInner = function(html){}; /** * Replaces all matched elements with the specified HTML or DOM elements. * @param {Element|jQuery} content * @return {jQuery} */ jQuery.prototype.replaceWith = function(content){}; /** * Replaces the elements matched by the specified selector with the matched elements. * @param {String} selector * @return {jQuery} */ jQuery.prototype.replaceAll = function(selector){}; /** * This particular method triggers all bound event handlers on an element (for a specific event type) WITHOUT executing the browsers default actions. * @param {String} type * @param {Object} data * @return {jQuery} */ jQuery.prototype.triggerHandler = function(type, data){}; /** * Stops all the currently running animations on all the specified elements. * @return {jQuery} */ jQuery.prototype.stop = function(){}; /** * Returns a reference to the first element's queue (which is an array of functions). * <br> * <br><b>Alternatives</b><br> * <br> * <b>queue</b>(<b>callback</b>: Function) : jQuery<br> * <b>queue</b>(<b>queue</b>) : jQuery<br> * @return {jQuery} */ jQuery.prototype.queue = function(callback){}; /** * Removes a queued function from the front of the queue and executes it. * @return {jQuery} */ jQuery.prototype.dequeue = function(){}; /** * Serializes all forms and form elements (like the .serialize() method) but returns a JSON data structure for you to work with. * @return {Object} */ jQuery.prototype.serializeArray = function(){}; /** * States if the current page, in the user's browser, is being rendered using the W3C CSS Box Model * @type {Boolean} */ jQuery.boxModel = true; /** * States if the current page, in the user's browser, is being rendered using the W3C CSS Box Model * @type {Boolean} */ $.boxModel = true; /** * Remove all duplicate elements from an array of elements. * @param {Array} array * @return {Array} */ jQuery.unique = function(array){}; /** * Remove all duplicate elements from an array of elements. * @param {Array} array * @return {Array} */ $.unique = function(array){}; /** * Get the current offset of the first matched element relative to the viewport. * The returned object contains two integer properties, <code>top</code> and * <code>left</code>. The method works only with visible elements. */ jQuery.prototype.offset = function(){ return {top: 0, left: 0};};
import '../../../node_modules/normalize.css/normalize.css' import './App.scss'; import React from 'react'; import ReactDOM from 'react-dom'; import App from './App.jsx' ReactDOM.render(<App/>, document.body);
import { renderString } from '../../src/index'; describe(`Returns a sequence of blog post objects for the specified blog, by the specified author, sorted by most recent first`, () => { it(`unnamed case 0`, () => { const html = renderString(`{{ blog_recent_author_posts('default', 'jared-stehler', 5) }}`); }); });
import React from 'react' import {shallow} from 'enzyme' import Navbar from './Navbar' describe('Navbar', () => { it('should be defined', () => { expect(Navbar).toBeDefined() }) it('should be rendered', () => { const navbar = shallow(<Navbar />) expect(navbar.find('.navbar')).toHaveLength(1) }) })
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import styled from 'styled-components'; const Link2 = styled(Link) ` z-index: 10; `; const Form = styled.form` padding: 0 10px; `; class Search extends Component { /* --------------- Search props --------------- - submitSearch -> [Function] => Function to submit the search - searchName -> [String] => String to display in the placeholder - searchTerm -> [String] => Value returned from the parent component (For visual rep on the input) - onChangeSearchTerm -> [Function] => Function to change the searchTerm in the parent component. */ render() { return ( <Form onSubmit={this.props.submitSearch} className="input-group"> <input placeholder={`Search ${this.props.searchName}`} className="form-control" value={this.props.searchTerm} onChange={this.props.onChangeSearchTerm} /> <span className="input-group-btn"> <button type="button" onClick={this.props.submitSearch} type="submit" className="btn btn-secondary"> <Link to="/search" id="next-level" style={{ width: '100%', height: '100%', display: 'block' }}> Submit </Link> </button> </span> </Form> ); } } export default Search;
var tokki = angular.module("directives").directive("resumenVenta", ["totalesService", function(totalesService){ return { restrict: "E", templateUrl: "pages/ventas/resumenVenta/resumenVenta.html", } } ])
// @flow import {fetchActivities} from './actions' type ActivityAction = { type: string, payload: any } type Activity = { [key: string]: { schedule: string, price: string, category: string } } type Category = { [key: string]: { description: string, name: string } } type activitiesState = { list: Activity, categories: Category, status: 'init' | 'success' | 'pending' | 'failure' } const activities = ( state: activitiesState = { list: {}, categories: {}, status: 'init' }, {type, payload}: ActivityAction) => { switch (type) { case fetchActivities.SUCCESS: return { ...state, list: payload.list, categories: payload.categories, status: 'success' } case fetchActivities.START: return { ...state, status: 'pending' } case fetchActivities.FAILURE: return { ...state, status: 'failure' } default: return state } } export default activities
import { Component } from 'react' import './App.css' import 'bootstrap/dist/css/bootstrap.min.css' import "react-loader-spinner/dist/loader/css/react-spinner-loader.css" import Routes from './routes' import Navigation from './layout/Navigation/Navigation' import Footer from './layout/Footer/Footer' import AuthService from '../services/auth.service' import RoomService from '../services/room.service' import Alert from './shared/Alert/Alert' class App extends Component { constructor() { super() this.state = { loggedUser: undefined, alert: { show: false, text: '' }, hasRoom: false } this.authService = new AuthService() this.roomService = new RoomService() } roomCheck = () => { this.roomService .roomVerification() .then(room => !room.data ? this.setState({ hasRoom: false }) : this.setState({ hasRoom: true })) .catch(err => console.log(err)) } reloadPage = () => this.state.alert.text === 'Please, log-in' ? (this.props.history.push('/'), window.location.reload(false)) : null storeUser = loggedUser => this.setState({ loggedUser }) showMessage = text => this.setState({ alert: { show: true, text } }) fetchUser = () => { this.authService .isLoggedIn() .then(theLoggedUser => { this.storeUser(theLoggedUser.data) this.roomCheck() this.reloadPage() }) .catch(() => this.storeUser(null)) } componentDidMount = () => { this.fetchUser() } render() { return ( <> <Navigation storeUser={this.storeUser} loggedUser={this.state.loggedUser} hasRoom={this.state.hasRoom} roomCheck={this.roomCheck} showMessage={this.showMessage} /> <Routes storeUser={this.storeUser} loggedUser={this.state.loggedUser} hasRoom={this.state.hasRoom} roomCheck={this.roomCheck} showMessage={this.showMessage} /> <Footer /> <Alert show={this.state.alert.show} text={this.state.alert.text} closeAlert={() => this.setState({ alert: { ...this.state.alert, show: false } })} /> </> ) } } export default App;
import { BASE_PATH_FRAGMENT, WEBSITE_ID_PATH_FRAGMENT } from '../constants'; export const RESOURCE_NAME = 'callmeback'; export const PATHNAME_TEMPLATE = `${BASE_PATH_FRAGMENT}/${RESOURCE_NAME}${WEBSITE_ID_PATH_FRAGMENT}`;
let MultiComponent = require("./multicomponent.js"); class Guide extends MultiComponent{ constructor(params){ super(params); let pos = params.position || {x: 0, y: 0}; this.set.Text = new UI.Components.Text($.extend(true, {position: {x: pos.x + 40, y: pos.y + 14}, id: "Text", color: "white", alignment: "top-left"}, params.text)); this.set.Image = new UI.Components.Image($.extend(true, {position: {x: pos.x + 20, y: pos.y + 10}, alignment: "top-left", img: "interface.header2", id: "Image", height: 24, width: this.set.Text.GetActualWidth() + 40}, params.image)); } } module.exports = Guide;
(function($) { /** * Opens Facebook share dialog and returns success/failvia callback * @param {String} href - URL to share * @param {Object} callback - Callback function accepting one parameter (success Bool) */ window.facebookShare = function(href, callback) { // Append GA tags to href href += '?utm_source=share_desktop&utm_campaign=kite&utm_medium=facebook'; // Build FB dialog URL var url = "https://www.facebook.com/dialog/share?app_id={{appId}}&display=popup&href={{href}}&redirect_uri={{redirectUri}}" .replace('{{appId}}', window.Ekhanei.facebook.appId) .replace('{{href}}', encodeURIComponent(href)) .replace('{{redirectUri}}', encodeURIComponent(window.Ekhanei.facebook.redirectUri)); // Open popup and "listen" for callback page var dialog = window.open(url, "Share on Facebook", "width=550,height=380"); // If popup is closed var closeInterval = setInterval(function() { if (dialog.closed) { clearInterval(closeInterval); callback(false); } }, 100); // If share success window.facebookShared = function() { clearInterval(closeInterval); dialog.close(); callback(true); } } })(window.jQuery);
import React, { Component } from "react"; import TopNav from "./TopNav"; class Notfound extends Component { state = {}; render() { return ( <div> <TopNav /> <h2 className="maintitle title"> Relax. The page you're looking for doesn't exist. </h2> </div> ); } } export default Notfound;
import React from "react"; import WelcomeMessage from "../../components/patient-ui/Home/WelcomeMessage"; import {Container} from "@material-ui/core"; import ServicesCard from "../../components/patient-ui/Home/ServicesCard"; import CovidCard from "../../components/patient-ui/Home/CovidCard"; function Home() { return ( <Container style={{overflowX:"hidden"}}> <WelcomeMessage /> <ServicesCard /> <CovidCard /> </Container> ); } export default Home;
var app = angular.module('baseApp',[]); $.ajaxSetup({ type: 'POST', complete: function(xhr,status) { var sessionStatus = xhr.getResponseHeader('sessionState'); if(sessionStatus == 'SO100-001') { var top = getTopWinow(); top.location.href = '/login.html'; } } }); //获取根节点 function getTopWinow(){ var p = window; while(p != p.parent){ p = p.parent; } return p; } /*app.directive('showContent',function($http){ return { restrict:'E', scope :true , link:function(scope, element, attrs) { debugger var data = { 'id':attrs.itemId }; $http.post('/datadicItem/getItemById',data,postCfg) .success(function(resp){ scope.content= resp.itemName; }); }, template:'<p ng-bind="content"></p>', replace:true }; });*/ app.directive('token', function() { return { restrict: 'E', // template: '<input type="hidden" name="token" value="'+getUuid()+'" />', template: function(tElement,tAttrs){ var _html = ''; _html += '<input type="hidden" name="token" value="'+getUuid()+'"/>'; return _html; }, replace: true }; }); function getUuid(){ var len=32;//32长度 var radix=16;//16进制 var chars='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');var uuid=[],i;radix=radix||chars.length;if(len){for(i=0;i<len;i++)uuid[i]=chars[0|Math.random()*radix];}else{var r;uuid[8]=uuid[13]=uuid[18]=uuid[23]='-';uuid[14]='4';for(i=0;i<36;i++){if(!uuid[i]){r=0|Math.random()*16;uuid[i]=chars[(i==19)?(r&0x3)|0x8:r];}}} return uuid.join(''); } app.directive('tmPagination',function(){ return { restrict: 'E', template: '<div style="text-align:center;height:30px;margin-top:15px">'+ '<ul class="pagination" style="margin: 0px;">'+ '<li ng-class="{disabled:pageInfo.currentPage==1}">'+ '<a ng-click="load_page(1)">首页</a>'+ '</li>'+ '<li ng-class="{disabled:pageInfo.currentPage==1}">'+ '<a ng-disabled="pageInfo.currentPage==1" ng-click="pageInfo.currentPage==1||load_page(pageInfo.currentPage - 1)">&lt;</a>'+ '</li>'+ '<li ng-class="{active:pageInfo.currentPage==page}" ng-repeat="page in pageInfo.pages">'+ '<a ng-click="load_page(page)">{{ page }}</a>'+ '</li>'+ '<li ng-class="{disabled:pageInfo.currentPage==pageInfo.countPage}">'+ '<a ng-disabled="pageInfo.currentPage==pageInfo.countPage" ng-click="pageInfo.currentPage==pageInfo.countPage||load_page(pageInfo.currentPage + 1)">&gt;</a>'+ '</li>'+ '<li ng-class="{disabled:pageInfo.currentPage==pageInfo.countPage}">'+ '<a ng-click="load_page(pageInfo.countPage)">尾页</a>'+ '</li>'+ '</ul>'+ '<span style="vertical-align: 12px;margin-left:20px">&nbsp;'+ '第<input type="text" style="max-width:30px;height: 20px;border-style:groove" ng-model="pageInfo.currentPage" ng-blur="load_page(pageInfo.currentPage)"/>页 ' + '&nbsp;共有:{{pageInfo.total}}&nbsp&nbsp条数据</span>'+ '<span class="r" style="margin-top:4px;width:120px;"> '+ '<span style="vertical-align: 12px;">&nbsp;&nbsp;每页'+ '<select style="margin-left:5px;"'+ 'ng-model="pageInfo.pageSize"'+ 'ng-change="load_page(1,pageInfo.pageSize)" '+ 'ng-options="act for act in pageInfo.currentNumbers">'+ '</select>&nbsp&nbsp条'+ '</span>'+ '</span>'+ '</div>', replace: true }; }); var transform = function(data) { return $.param(data); }, postCfg = { headers : { 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8' }, transformRequest : transform }; //业务类 app.factory('pageService', ['$http', function ($http) { var load_page = function (url,postData) { var index = layer.load(1, {shade: [0.1,'#fff'] //0.1透明度的白色背景 }); $http.post(url, postData,postCfg).success(function(resp){ pageInfo.total=resp.total; pageInfo.list=resp.list; pageInfo.currentPage = resp.pageNum; pageInfo.countPage =Math.ceil(pageInfo.total/postData.rows); pageInfo.pages = reloadPno(pageInfo.currentPage,pageInfo.countPage); layer.close(index); }); return pageInfo; } var pageInfo = { currentPage : 1,//当前页 pageSize : 10,//每页显示数 pages : [],//可扩展几页 countPage : 1,//总页数 total : 1,//总条数 currentNumbers : [10,20,50,100], list : [] //列表 }; var reloadPno = function(currentPage,allPage){ var pages = []; //分页算法 for(var i = 1; i <= allPage; i++) { if(i == 2 && currentPage - 6 > 1) { i = currentPage - 6; }else if(i == currentPage + 6 && currentPage + 6 < allPage) { i = allPage - 1; }else{ pages.push(i); } } return pages; }; return { pageInfo : pageInfo, load_page: function (url,postData) { return load_page(url,postData); } } }]); Array.prototype.indexOf = function(val) { for (var i = 0; i < this.length; i++) { if (this[i] == val) return i; } return -1; }; Array.prototype.remove = function(val) { var index = this.indexOf(val); if (index > -1) { this.splice(index, 1); } }; function validateSuccessData(data){ if((typeof(data) == 'string') && (data == 'true')){ return true; } if((typeof(data) == 'boolean') && (data == true)){ return true; } if(data.id){ return true; } return false; } function stitchingParameter(objectParam,listParam,listName){ if(listName==undefined){ listName = ''; } for(var i = 0;i<listParam.length;i++){ for(var object in listParam[i]){ objectParam[listName+'['+i+'].'+object] = listParam[i][object]; } } return objectParam; }
var API_GET_ALLOWLIST = "/allowlist"; var API_SERVICES = "/settings/service"; var API_CRUD_ALLOWLIST = "/allowlist/entry/"; var API_EXECLOG = "/execution/"; var API_KEY = ""; // Utility functions function convertJsonToGet(formJSON) { let formURL = ""; for (var key in formJSON) { formURL += key + "=" + formJSON[key] + "&"; } formURL.substr(0, formURL.length - 1); return formURL; } // Init Vue instance var app = new Vue({ el: "#app", data: { accountId: "", apiKey: "", allowlistExpanded: false, executionLogExpanded: false, executionLogActionStats: {}, executionLogDataTables: "", executionLogKey: "", executionLogList: [], executionLogMode: "", executionLogRegionStats: {}, executionLogSearchTerm: "", executionLogServiceStats: {}, executionLogTable: [], resourceIdPlaceholder: "", resourceList: [], selectedComment: "", selectedExpiration: 0, selectedOwner: "", selectedResource: "", selectedResourceId: "", selectedService: "", serviceList: [], serviceSettings: [], serviceSettingsFlat: [], showApiKeyPopup: true, showExecutionLogListLoadingGif: false, showExecutionLogLoadingGif: false, showExecutionLogPopup: false, showHelpPopup: false, showAllowlistDeletePopup: false, showAllowlistLoadingGif: false, showAllowlistPopup: false, allowlist: [], allowlistDataTables: "", allowlistSearchTerm: "", }, methods: { // Allowlist closeAllowlistDeletePopup: function () { this.selectedResourceId = ""; this.showAllowlistDeletePopup = false; }, closeAllowlistInsertPopup: function () { this.resourceIdPlaceholder = ""; this.resourceList = []; this.selectedComment = ""; this.selectedExpiration = 0; this.selectedOwner = ""; this.selectedResource = ""; this.selectedResourceId = ""; this.selectedService = ""; this.showAllowlistPopup = false; }, createAllowlistEntry: function () { let formData = { resource_id: this.selectedService + ":" + this.selectedResource + ":" + this.selectedResourceId, owner: this.selectedOwner, comment: this.selectedComment, }; sendApiRequest(convertJsonToGet(formData), "POST"); }, createAllowlistEntryFromExecutionLog: function ( service, resource, resourceId ) { this.selectedService = service.toLowerCase().replace(/ /g, "_"); this.selectedResource = resource.toLowerCase().replace(/ /g, "_"); this.selectedResourceId = resourceId; this.updateResourceList(this.selectedService); this.closeExecutionLogPopup(); this.openAllowlistInsertPopup(); }, deleteAllowlistEntry: function (resourceId) { let formData = { resource_id: resourceId, }; sendApiRequest(convertJsonToGet(formData), "DELETE"); }, expandAllowlist: function () { if (this.allowlistExpanded) { $("#allowlist-message-body").css({ "max-height": "calc(36vh)" }); $("#allowlist-message-body").css({ "min-height": "" }); $("#allowlist-expand-icon").attr( "class", "fas fa-up-right-and-down-left-from-center" ); // $("html").removeClass("remove-overflow"); this.allowlistExpanded = false; } else { $("#allowlist-message-body").css({ "max-height": "calc(90vh)" }); $("#allowlist-message-body").css({ "min-height": "calc(90vh)" }); $("#allowlist-expand-icon").attr( "class", "fas fa-down-left-and-up-right-to-center" ); // $("html").addClass("remove-overflow"); $("html, body").animate( { scrollTop: $("#allowlist-message").offset().top - 20 }, 500 ); this.allowlistExpanded = true; } }, expandExecutionLog: function () { if (this.executionLogExpanded) { $("#execution-log-message-body").css({ "max-height": "calc(36vh)" }); $("#execution-log-message-body").css({ "min-height": "" }); $("#execution-log-expand-icon").attr( "class", "fas fa-up-right-and-down-left-from-center" ); // $("html").removeClass("remove-overflow"); this.executionLogExpanded = false; } else { $("#execution-log-message-body").css({ "max-height": "calc(90vh)" }); $("#execution-log-message-body").css({ "min-height": "calc(90vh)" }); $("#execution-log-expand-icon").attr( "class", "fas fa-down-left-and-up-right-to-center" ); // $("html, body").animate({ scrollTop: $(document).height() }, 1000); $("html, body").animate( { scrollTop: $("#execution-log-message").offset().top - 20 }, 500 ); // $("html").addClass("remove-overflow"); this.executionLogExpanded = true; } }, extendAllowlistEntry: function (rowId) { let row = this.allowlist[rowId - 1]; let formData = { resource_id: row.resource_id, expiration: row.expiration, owner: row.owner, comment: row.comment, }; sendApiRequest(convertJsonToGet(formData), "PUT"); }, updateResourceId: function (service, resource) { this.resourceIdPlaceholder = this.serviceSettings[service][resource]["id"]; }, updateResourceList: function (service) { this.resourceList = Object.keys(this.serviceSettings[service]); // auto select if only 1 option exists if (this.resourceList.length === 1) { this.selectedResource = this.resourceList[0]; this.updateResourceId(service, this.resourceList[0]); } else { this.resourceIdPlaceholder = ""; } }, openAllowlistDeletePopup: function (resourceId) { this.selectedResourceId = resourceId; this.showAllowlistDeletePopup = true; this.resourceIdPlaceholder = ""; }, openAllowlistInsertPopup: function () { this.showAllowlistPopup = true; this.resourceIdPlaceholder = ""; }, searchAllowlist: function () { this.allowlistDataTables.search(this.allowlistSearchTerm).draw(); }, showTemporaryAllowlist: function () { this.allowlistDataTables.column(6).search("Temporary").draw(); $("#show-temporary-allowlist-button").addClass("is-link"); $("#show-permanent-allowlist-button").removeClass("is-link"); }, showPermanentAllowlist: function () { this.allowlistDataTables.column(6).search("Permanent").draw(); $("#show-permanent-allowlist-button").addClass("is-link"); $("#show-temporary-allowlist-button").removeClass("is-link"); }, // Execution Log closeExecutionLogPopup: function () { $("html").removeClass("remove-overflow"); this.executionLogDataTables.clear().draw(); // Reseet variables this.executionLogActionStats = {}; this.executionLogKey = ""; this.executionLogMode = ""; this.executionLogRegionStats = {}; this.executionLogServiceStats = {}; this.executionLogTable = []; this.showExecutionLogPopup = false; }, openExecutionLog: function (keyURL) { $("html").addClass("remove-overflow"); getExecutionLog(keyURL); }, searchExecutionLog: function () { this.executionLogDataTables.search(this.executionLogSearchTerm).draw(); }, // Help closeHelpPopup: function () { this.showHelpPopup = false; }, openHelpPopup: function () { this.showHelpPopup = true; }, // Api Key closeApiKeyPopup: function () { this.showApiKeyPopup = false; }, setApiKey: function () { this.showApiKeyPopup = false; API_KEY = this.apiKey; localStorage.setItem("x-api-key", this.apiKey); init(); }, resetApiKey: function () { API_KEY = ""; localStorage.removeItem("x-api-key"); location.reload(); }, }, mounted: function () { API_KEY = localStorage.getItem("x-api-key"); if (API_KEY !== null) { this.showApiKeyPopup = false; } }, }); function sendApiRequest(formURL, requestMethod) { fetch(API_CRUD_ALLOWLIST + "?" + formURL, { method: requestMethod, headers: { "x-api-key": API_KEY, }, }) .then((response) => response.json()) .then((data) => { refreshAllowlist(); app.closeAllowlistInsertPopup(); app.closeAllowlistDeletePopup(); iziToast.success({ color: "#3FBF61", message: data.message, messageColor: "white", }); }) .catch((error) => { iziToast.error({ color: "#EC2B55", message: error, messageColor: "white", title: "Something went wrong", }); }); } // Get execution log for a single instance function getExecutionLog(executionLogUrl) { app.showExecutionLogPopup = true; app.showExecutionLogLoadingGif = true; fetch(API_EXECLOG + executionLogUrl, { headers: { "x-api-key": API_KEY, }, }) .then((response) => response.json()) .then((data) => { app.executionLogKey = decodeURIComponent(executionLogUrl); app.executionLogTable = data["response"]["body"]; if (data["response"]["is_compressed"]) { try { let compressedData = Uint8Array.from( atob(app.executionLogTable), (c) => c.charCodeAt(0) ); let decompressedData = pako.inflate(compressedData, { to: "string" }); app.executionLogTable = JSON.parse(decompressedData); } catch (error) { console.log(error); } } app.executionLogActionStats = data["response"]["statistics"]["action"]; app.executionLogServiceStats = data["response"]["statistics"]["service"]; app.executionLogRegionStats = data["response"]["statistics"]["region"]; app.executionLogMode = data["response"]["is_dry_run"] === true ? "Dry Run" : "Destroy"; setTimeout(function () { if (!app.executionLogDataTables) { app.executionLogDataTables = $("#execution-log-table").DataTable({ data: app.executionLogTable, autoWidth: true, deferRender: true, pageLength: 500, dom: "rtip", columnDefs: [ { targets: 5, className: "dt-body-nowrap", }, ], }); } else { app.executionLogDataTables .clear() .rows.add(app.executionLogTable) .draw(); } app.showExecutionLogLoadingGif = false; $("#execution-log-table-info").html($("#execution-log-table_info")); $("#execution-log-table-paginate").html( $("#execution-log-table_paginate") ); }, 10); }) .catch((error) => { iziToast.error({ color: "#EC2B55", message: error, messageColor: "white", title: "Something went wrong", }); }); } // Get execution logs list function getExecutionLogList() { app.showExecutionLogListLoadingGif = true; fetch(API_EXECLOG, { headers: { "x-api-key": API_KEY, }, }) .then((response) => response.json()) .then((data) => { app.executionLogList = data["response"]["logs"].map((row) => { let logDate = new Date(row["date"] + " UTC"); let localDate = logDate.toString().split(/ GMT/)[0]; row["key_escape"] = encodeURIComponent(row["key"]); row["local_date"] = localDate; return row; }); setTimeout(function () { $("#execution-log-list-table").DataTable({ dom: "rtp", columnDefs: [ { orderable: false, targets: [0, 1, 2] }, { className: "dt-center", targets: [2] }, ], pageLength: 500, order: [[0, "desc"]], }); $("#execution-log-list-table-paginate").html( $("#execution-log-list-table_paginate") ); }, 10); app.showExecutionLogListLoadingGif = false; }) .catch((error) => { iziToast.error({ color: "#EC2B55", message: error, messageColor: "white", title: "Something went wrong", }); }); } // Get supported services function getServices() { fetch(API_SERVICES, { headers: { "x-api-key": API_KEY, }, }) .then((response) => response.json()) .then((data) => { app.serviceSettings = data["response"]; // get list of supported services app.serviceList = Object.keys(data["response"]); // convert settings to flat table for (const service in data["response"]) { for (resource in data["response"][service]) { app.serviceSettingsFlat.push({ service: service, resource: resource, ttl: data["response"][service][resource]["ttl"], enabled: data["response"][service][resource]["clean"], }); } } }) .catch((error) => { iziToast.error({ color: "#EC2B55", message: error, messageColor: "white", title: "Something went wrong", titleColor: "white", }); }); } // Get allowlist function getAllowlist() { app.allowlist = []; app.showAllowlistLoadingGif = true; fetch(API_GET_ALLOWLIST, { headers: { "x-api-key": API_KEY, }, }) .then((response) => response.json()) .then((data) => { let i = 1; let allowlistRaw = data["response"]["allowlist"]; dayjs.extend(dayjs_plugin_utc); dayjs.extend(dayjs_plugin_timezone); app.allowlist = allowlistRaw.map((item) => { // Parse Resource ID, i.e. split on ":" let parsedResourceId = item["resource_id"].split(":", 2); parsedResourceId.push( item["resource_id"].slice(parsedResourceId.join("").length + 2) ); let readableDate = dayjs.unix(item["expiration"]).tz(dayjs.tz.guess()); item["row_id"] = i++; item["service"] = parsedResourceId[0]; item["resource"] = parsedResourceId[1]; item["id"] = parsedResourceId[2]; item["expiration_readable"] = readableDate.format("DD MMM YYYY"); item["expiration_tooltip"] = readableDate.format( "ddd MMM DD HH:mm:ss YYYY" ); return item; }); setTimeout(function () { app.allowlistDataTables = $("#allowlist").DataTable({ dom: "rtp", columnDefs: [ { className: "dt-center", targets: [5] }, { orderable: false, targets: [0, 1, 2, 3, 4, 5, 6, 7] }, { targets: [6], visible: false, }, { responsivePriority: 1, targets: 7 }, ], order: [[6, "desc"]], pageLength: 500, }); $("#allowlist-paginate").html($("#allowlist_paginate")); app.allowlistDataTables.column(6).search("Temporary").draw(); app.showAllowlistLoadingGif = false; }, 10); }) .catch((error) => { iziToast.error({ color: "#EC2B55", message: error, messageColor: "white", title: "Something went wrong", }); }); } function refreshAllowlist() { app.allowlistDataTables.destroy(); getAllowlist(); } function openTab(evt, tabName) { var i, x, tablinks; x = document.getElementsByClassName("content-tab"); for (i = 0; i < x.length; i++) { x[i].style.display = "none"; } tablinks = document.getElementsByClassName("tab"); for (i = 0; i < x.length; i++) { tablinks[i].className = tablinks[i].className.replace(" is-active", ""); } document.getElementById(tabName).style.display = "block"; evt.currentTarget.className += " is-active"; } function init() { getAllowlist(); getExecutionLogList(); getServices(); } // Get the API Gateway Base URL from manifest file fetch("serverless.manifest.json").then(function (response) { response.json().then(function (data) { let env = Object.keys(data)[0]; let API_BASE = data[env]["urls"]["apiGatewayBaseURL"]; API_GET_ALLOWLIST = API_BASE + API_GET_ALLOWLIST; API_SERVICES = API_BASE + API_SERVICES; API_CRUD_ALLOWLIST = API_BASE + API_CRUD_ALLOWLIST; API_EXECLOG = API_BASE + API_EXECLOG; for (output of data[env]["outputs"]) { if (output["OutputKey"] === "AccountID") { app.accountId = output["OutputValue"]; document.title = "AWS Auto Cleanup - " + output["OutputValue"]; break; } } if (API_KEY) { init(); } }); });
import React, { PureComponent } from 'react'; import { Animated, Text, TextInput, TouchableOpacity, View } from 'react-native'; import PropTypes from 'prop-types'; import styles from './styles'; import * as colors from 'kitsu/constants/colors'; const HIT_SLOP = { top: 10, left: 10, bottom: 10, right: 10, }; export default class QuickUpdateEditor extends PureComponent { static propTypes = { episode: PropTypes.number.isRequired, onCancel: PropTypes.func, onChange: PropTypes.func, onDone: PropTypes.func, value: PropTypes.string, }; static defaultProps = { onCancel: () => {}, onChange: () => {}, onDone: () => {}, value: null, }; state = { headerOpacity: new Animated.Value(0), } componentDidMount = () => { // Animate the header in after the slide. const { headerOpacity } = this.state; Animated.timing(headerOpacity, { toValue: 1, duration: 300, delay: 500, useNativeDriver: true, }).start(); } render() { const { episode, value, onCancel, onDone } = this.props; const { headerOpacity } = this.state; return ( <View style={styles.wrapper}> {/* Header */} <Animated.View style={[styles.header, { opacity: headerOpacity }]}> {/* Dummy View, helps with layout to center text */} <TouchableOpacity onPress={onCancel} hitSlop={HIT_SLOP} style={styles.headerButton}> <Text style={styles.headerButtonText}>Cancel</Text> </TouchableOpacity> <Text style={styles.headerText}>Episode {episode}</Text> <TouchableOpacity onPress={onDone} hitSlop={HIT_SLOP} style={styles.headerButton}> <Text style={styles.headerButtonText}>Done</Text> </TouchableOpacity> </Animated.View> <View style={styles.editorWrapper}> <TextInput autoFocus multiline value={value} style={styles.editor} onChangeText={this.props.onChange} placeholder={`(Optional) Share your thoughts on Episode ${episode}`} placeholderTextColor={colors.lightGrey} /> </View> </View> ); } }
const studentRepository = require('../repositories/student.repository') const roomRepository = require('../repositories/room.repository') const sumCapacity = rooms => rooms.reduce((total, room) => total + room.capacity, 0) const selectRooms = numberOfStudents => (selected, room) => sumCapacity(selected) < numberOfStudents ? [...selected, room] : selected const distributeStudents = students => (selected, room) => [ ...selected, { room, students: students.splice(0, room.capacity), }, ] const distribute = exam => { const students = studentRepository.listForExam(exam) const numberOfStudents = students.length const rooms = roomRepository .listForExam(exam) .reduce(selectRooms(numberOfStudents), []) if (sumCapacity(rooms) < numberOfStudents) throw new Error('Capacidade das salas é insuficiente para os alunos.') return rooms.reduce(distributeStudents(students), []) } module.exports = { distribute, }
import ElementUI from 'element-ui'; import 'element-ui/lib/theme-chalk/index.css'; import { registerMicroApps, start } from 'qiankun'; import Vue from 'vue'; import App from './App.vue'; import router from './router/index'; Vue.use(ElementUI); Vue.config.productionTip = false; // Angular9 // function genActiveRule(urlList) { // return (location) => { // console.log("aaa") // for(let url of urlList) { // if (location.hash === url) { // return true; // } // } // return false; // } // } const apps = [ { name: 'vue app', // app name registered entry: '//localhost:10000', container: '#vue', activeRule: '/vue', // props: {a:1} }, { name: 'reactApp', entry: '//localhost:20000', //默认会加载这个html,解析里面的js动态执行(子应用需要解决跨域)fetch container: '#react', activeRule: '/react', }, { name: 'app', // entry: '//localhost:9063', entry: '//localhost:81', container: '#inspect', activeRule: '/inspect', //genActiveRule(['/inspect']), Angular9 }, { name: 'diag', // entry: '//localhost:9063', entry: '//localhost:80',//window ip container: '#subapp-viewport', activeRule: '/trans-diag', //genActiveRule(['/inspect']), Angular9 }, { name: 'alarm', // entry: '//localhost:9063', entry: '//localhost:82',//window ip container: '#subapp-viewport', activeRule: '/trans-alarm', //genActiveRule(['/inspect']), Angular9 }, ]; registerMicroApps(apps); //注册应用 // start(); start({ prefetch: false, // 取消预加载 }); //开启 new Vue({ router, render: (h) => h(App) }).$mount('#app');
const { Status } = require('./status'); const { Hash } = require('./hash') module.exports = { Status, Hash }
import React, { Component } from 'react'; import { View, Image } from 'react-native'; import {CardSectionNoBorder}from '../../Common' import {Actions,ActionConst}from 'react-native-router-flux'; class WelcomePage extends Component { constructor(props){ super(props) setTimeout(function () { Actions.welcomepage1(); }, 1000) } render() { const{logo,Container}=Styles; return ( <View style={Container}> <CardSectionNoBorder> <Image source={require('../../Assets/logosymbol.png')} style={logo} /> </CardSectionNoBorder> </View> ) } } const Styles = { Container: { flex: 1, justifyContent: 'center', backgroundColor: "#ffff", }, logo: { width: 120.42, height: 65, alignItems: 'center', justifyContent: 'center', } } export default WelcomePage;
const createError = require('http-errors'); const express = require('express'); const path = require('path'); const cookieParser = require('cookie-parser'); const logger = require('morgan'); const fs = require('fs'); const multer = require('multer') const ejs = require('ejs'); const bodyParser = require('body-parser'); const session = require('express-session'); const app = express(); const upload = multer({dest: 'upload/'}); app.post('/upload-single', upload.single('file'), function (req, res, next) { var file = req.file; var name = file.originalname; var nameArray = name.split(''); var nameMime = []; var l = nameArray.pop(); nameMime.unshift(l); while (nameArray.length != 0 && l != '.') { l = nameArray.pop(); nameMime.unshift(l); } var Mime = nameMime.join(''); console.log(Mime); res.send({ "code": 0 , "msg": "" , "data": { "src": '/download/' + file.filename + Mime } }); fs.renameSync('./upload/' + file.filename, './upload/' + file.filename + Mime); }); app.use('/download', express.static(path.join(__dirname, 'upload'))); app.get('download/:path', function (req, res) { var file = __dirname + '/' + path; res.download(file); }); app.use(bodyParser.json()); app.use(session({secret: 'keyboard cat', resave: false, saveUninitialized: true, cookie: {maxAge: 60 * 60 * 1000}})); app.use(bodyParser.urlencoded({ extended: false })); const rout = require("./server"); rout.forEach(function (item, index) { app.use(item.path, require(item.route)); }); app.engine('html', ejs.__express); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'html'); app.use(logger('dev')); app.use(express.json()); app.use(express.urlencoded({extended: false})); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); // catch 404 and forward to error handler app.use(function (req, res, next) { res.render('404'); }); // error handler app.use(function (err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('500'); }); module.exports = app;
import React from 'react'; import './App.css'; // import {Typography} from '@material-ui/core'; import {Container} from '@material-ui/core'; import Comments from "./components/Comments" // import { Divider, Avatar, Grid, Paper } from "@material-ui/core"; function App() { return ( <div className="App"> <Container maxWidth="sm"> <Comments></Comments> </Container> </div> ); } export default App;
'use strict'; var app = angular.module('ecobitApp', ['ecobitApp.auth', 'ecobitApp.admin', 'ecobitApp.constants', 'ngCookies', 'ngResource', 'ngSanitize', 'btford.socket-io', 'ui.router', 'ui.bootstrap', 'validation.match', 'xeditable', 'ui-notification', 'angularMoment', 'ui.calendar', 'ui.select' ]) .config(function ($urlRouterProvider, $locationProvider) { $urlRouterProvider.otherwise('/'); $locationProvider.html5Mode(true); }).config(function (NotificationProvider) { NotificationProvider.setOptions({ delay: 10000, startTop: 20, startRight: 10, verticalSpacing: 20, horizontalSpacing: 20, positionX: 'right', positionY: 'top' }); }); app.run(function (editableOptions) { editableOptions.theme = 'bs3'; });
import React from "react"; import PropTypes from "prop-types"; import styles from "./channelHeader.css"; function ChannelHeader({ title, children }) { return ( <header className={styles.header}> <h1 className={styles.title}>{title}</h1> {children} </header> ); } ChannelHeader.defaultProps = { children: null }; ChannelHeader.propTypes = { title: PropTypes.string.isRequired }; export default ChannelHeader;
// editted dialog system by nathan //var currentSpeaker; //don't actually need because the parser will decide for u, just need a decider for which JSON to play and which DBOX to use dialogSystem = function(game){ // dialog constants this.DBOX_X = 0+140; // dialog box x-position this.DBOX_Y = 350+50; // dialog box y-position this.DBOX_FONT = 'font'; // dialog box font key this.TEXT_X = 50+140; // text w/in dialog box x-position this.TEXT_Y = 420+50; // text w/in dialog box y-position this.TEXT_SIZE = 32; // text font size (in pixels) this.TEXT_MAX_WIDTH = 715; // max width of text within box this.NEXT_TEXT = '[CLICK]'; // text to display for next prompt this.NEXT_X = 750+140; // next text prompt x-position this.NEXT_Y = 550+50; // next text prompt y-position this.LETTER_TIMER = 10; // # ms each letter takes to "type" onscreen // dialog variables this.dialogConvo = 0; // current "conversation" this.dialogLine = 0; // current line of conversation this.dialogSpeaker = null; // current speaker this.dialogLastSpeaker = null; // last speaker this.dialogTyping = false; // flag to lock player input while text is "typing" this.dialogText = null; // the actual dialog text this.nextText = null; // player prompt text to continue typing // character variables this.cactusboi = null; this.portraitlady = null; this.dog = null; this.dialog = null; this.OFFSCREEN_X = -500; // x,y values to place characters offscreen this.OFFSCREEN_Y = 1000; // }; dialogSystem.prototype = { create: function() { this.dialogConvo = 0; //background intialization this.physics.startSystem(Phaser.Physics.ARCADE); this.bgroundtiles = this.add.group(); this.bground(); // parse dialog from JSON file this.dialog = JSON.parse(this.game.cache.getText(currentJSON)); // add dialog box sprite this.dialogbox = this.add.button(this.DBOX_X, this.DBOX_Y, currentDBOX,function (){ if(!this.dialogTyping) this.TypeText(); },this); this.dialogbox.animations.add('wiggly', [0, 1], 10, true); //puts the wiggle in the dbox this.dialogbox.animations.play('wiggly'); //this.dialogbox.visible = false; // init dialog text this.dialogText = this.add.bitmapText(this.TEXT_X, this.TEXT_Y, this.DBOX_FONT, '', this.TEXT_SIZE); this.nextText = this.add.bitmapText(this.NEXT_X, this.NEXT_Y, this.DBOX_FONT, '', this.TEXT_SIZE); // add character dialog images this.cactusboi = this.add.sprite(this.OFFSCREEN_X, this.DBOX_Y+8, 'cactusboi'); this.cactusboi.anchor.setTo(0, 0.8); this.portraitlady = this.add.sprite(this.OFFSCREEN_X, this.DBOX_Y+8, 'portraitlady'); this.portraitlady.anchor.setTo(0, 1); this.dog = this.add.sprite(this.OFFSCREEN_X, this.DBOX_Y+8, 'dog'); this.dog.anchor.setTo(0, 1); //group for layer control this.layers = this.add.group(); this.layers.add(this.cactusboi); this.layers.add(this.portraitlady); this.layers.add(this.dog); this.layers.add(this.dialogbox); this.layers.add(this.dialogText); // start dialog this.TypeText(); }, update: function() { //background img this.bgroundtiles.forEach(this.wrapSprite, this, true); /******** CHANGE THIS TO A MOUSE CLICK ********/ // check for spacebar press // if(this.input.keyboard.justPressed(Phaser.Keyboard.SPACEBAR) && !this.dialogTyping) { // // trigger dialog // this.TypeText(); // } /**********************************************/ }, TypeText: function() { // lock input while typing this.dialogTyping = true; // clear text this.dialogText.text = ''; this.nextText.text = ''; // make sure there are lines left to read in this convo, otherwise jump to next convo if(this.dialogLine > this.dialog[this.dialogConvo].length-1) { this.dialogLine = 0; this.dialogConvo++; } // make sure we're not out of conversations if(this.dialogConvo >= this.dialog.length) { numDay++; game.state.start('day'); } else { // set current speaker this.dialogSpeaker = this.dialog[this.dialogConvo][this.dialogLine]['speaker']; if(this.dialog[this.dialogConvo][this.dialogLine]['newSpeaker']) { if(this.dialogLastSpeaker) { this.add.tween(this[this.dialogLastSpeaker]).to({x: this.OFFSCREEN_X}, 500, Phaser.Easing.Linear.None, true); } this.add.tween(this[this.dialogSpeaker]).to({x: this.DBOX_X+250, y: this.DBOX_Y+180}, 500, Phaser.Easing.Linear.None, true); } // build dialog (concatenate speaker + line of text) this.dialogLines = this.dialog[this.dialogConvo][this.dialogLine]['speaker'].toUpperCase() + ': ' + this.dialog[this.dialogConvo][this.dialogLine]['dialog']; // setup timer to iterate through each letter in dialog let currentChar = 0; this.textTimer = this.time.events.repeat(this.LETTER_TIMER, this.dialogLines.length, function(){ this.dialogText.text += this.dialogLines[currentChar]; currentChar++; }, this); // callback function fires once timer is finished this.textTimer.timer.onComplete.addOnce(function(){ // show prompt for more text this.nextText = this.add.bitmapText(this.NEXT_X, this.NEXT_Y, this.DBOX_FONT, this.NEXT_TEXT, this.TEXT_SIZE); this.nextText.anchor.setTo(1, 1); // un-lock input this.dialogTyping = false; }, this); // set bounds on dialog this.dialogText.maxWidth = this.TEXT_MAX_WIDTH; // increment dialog line this.dialogLine++; // set past speaker this.dialogLastSpeaker = this.dialogSpeaker; } }, //BACKGROUND STUFF bground: function(){ for(let j = 0; j < 3; j++){ for(let i = 0; i < 4; i++){ this.tile = this.add.sprite(0 + 511*i*.708,0 + 511*j*.708, 'bground'); this.physics.enable(this.tile,Phaser.Physics.ARCADE); this.tile.anchor.set(0.5,0.5); this.tile.scale.set(.708); this.tile.body.velocity.x = -50; this.tile.body.velocity.y = -50; this.bgroundtiles.add(this.tile); } } }, wrapSprite: function(sprite) { // if sprite passes screen edge, wrap to opposite side if(sprite.x + sprite.width/2 < 0) { sprite.x = 1080 + sprite.width/2; } else if(sprite.x - sprite.width/2 > 1080) { sprite.x = 0 - sprite.width/2; } if(sprite.y + sprite.height/2 < 0) { sprite.y = 720 + sprite.height/2; } else if(sprite.y - sprite.height/2 > 720) { sprite.y = 0 - sprite.height/2; } },//END BACKGROUND STUFF };
const DOMNodeCollection = require('./dom_node_collection.js'); window.$l = function(arg) { if (arg instanceof HTMLElement) { const elArr = [arg]; return new DOMNodeCollection(elArr); } else { const nodeList = Array.from(document.querySelectorAll(arg)); return new DOMNodeCollection(nodeList); } };
(function () { 'use strict'; angular .module('app.auth') .controller('LoginController', LoginController); LoginController.$inject = ['$location', '$stateParams', '$scope', 'AuthService', 'BraveAuthConfig']; /** * * @param {object} $location location * @param {object} $stateParams location * @param {object} $scope scope * @param {object} authService AuthService object * @param {object} braveAuthConfig BraveAuthConfigProvider object * @constructor */ function LoginController($location, $stateParams, $scope, authService, braveAuthConfig) { var vm = this; vm.login = login; vm.message = $stateParams.message; // TODO nkler: check if it works with $state.go($state.current ...) vm.usernameFieldTemplate = braveAuthConfig.getUsernameFieldTemplate(); vm.logo = braveAuthConfig.getLogo(); activate(); /** * @name activate * @desc Actions to be performed when this controller is instantiated * @memberOf app.auth.LoginController */ function activate() { } /** * @name login * @desc Log the user in * @memberOf app.auth.LoginController */ function login() { authService.login(vm.username, vm.password); } } })();
import React from 'react'; import { BrowserRouter as Router, Route, Link} from 'react-router-dom'; import Arrow from "./Arrow"; import FormContainer from "./FormContainer"; import LearnForms from "./LearnForms"; import MainContent from "./MainContent"; import ChildState from "./ChildState"; import FormsPractice from "./FormsPractice"; import LearnLifecicle from "./LearnLifecicle"; import Conditional from "./Conditional"; import LearnProps from "./LearnProps"; import LearnEvents from "./LearnEvents"; import FormComponent from "./FormComponent"; import LearnFetch from "./LearnFetch"; import LearnState from "./LearnState"; import TodosContainer from "./TodosContainer"; function Index(){ return <h2>Index</h2> } class LearnRouter extends React.Component{ constructor(){ super(); } render(){ return( <Router> <div> <nav> <ul> <li><Link to="/">Home</Link></li> <li><Link to="/Arrow/">Arrow</Link> </li> <li><Link to="/FormContainer/">FormContainer</Link> </li> <li><Link to="/LearnForms/">LearnForms</Link> </li> <li><Link to="/MainContent/">MainContent</Link> </li> <li><Link to="/ChildState/">ChildState</Link> </li> <li><Link to="/FormsPractice/">FormsPractice</Link> </li> <li><Link to="/LearnLifecicle/">LearnLifecicle</Link> </li> <li><Link to="/Conditional/">Conditional</Link> </li> <li><Link to="/LearnProps/">LearnProps</Link> </li> <li><Link to="/LearnEvents/">LearnEvents</Link> </li> <li><Link to="/FormComponent/">FormComponent</Link> </li> <li><Link to="/LearnFetch/">LearnFetch</Link> </li> <li><Link to="/LearnState/">LearnState</Link> </li> <li><Link to="/TodosContainer/">TodosContainer</Link> </li> </ul> </nav> <Route path="/" exact component={Index} /> <Route path="/Arrow/" component={Arrow} /> <Route path="/FormContainer/" component={FormContainer} /> <Route path="/LearnForms/" component={LearnForms} /> <Route path="/MainContent/" component={MainContent} /> <Route path="/ChildState/" component={ChildState} /> <Route path="/FormsPractice/" component={FormsPractice} /> <Route path="/LearnLifecicle/" component={LearnLifecicle} /> <Route path="/Conditional/" component={Conditional} /> <Route path="/LearnProps/" component={LearnProps} /> <Route path="/LearnEvents/" component={LearnEvents} /> <Route path="/FormComponent/" component={FormComponent} /> <Route path="/LearnFetch/" component={LearnFetch} /> <Route path="/LearnState/" component={LearnState} /> <Route path="/TodosContainer/" component={TodosContainer} /> </div> </Router> ) } } export default LearnRouter;
// learn 23 Утган хандалт болон заагч хандалтын тухай - value VS reference // Утга олголт: 1. энгийн утга олголт буюу value ===> утгын өөрчилөхөд хуулбар нь дамждаг байгаа. // 2. заалтаар утга олголт буюу reference ===> утгын өөрчилөхөд өөрөө дамждаг байгаа. //////////////////////////////// 1. энгийн утга олголт буюу value //////////////////////////////////////////////// // primivite өгөгдлийн төрлүүд дандаа ийм байдлаар утгууд нь copy байдлаар утгууд нь дамжигддаг. var a = 12; //а-гын утгыг b өгөхөд санах ойд байгаа хаягнаас а-гын хуулбар буюу copy дамжигддаг var b = a; // а-гын утганы хуулбар ирэээд санах ойд а-гын хаягнаас өөр хаяг дээр b болон хадгалагддаг. a = 13; // ийм учираас а-гын утгыг 13 болоход b-гын утга өөрчлөхдөхгүй. Ягаад гэвэл санах ойд 2 өөр хаяган дээр байгаа болохоор console.log(a); console.log(b); /////////////////////////////// 2. заалтаар утга олголт буюу reference ///////////////////////////////////////////// //----------- 2а. Объектод заагч утга ашиглах: Object Reference------------------------------------------------------------- var p1 = { name: "notebook", price: "300$" }; //p1 утгыг p2 өгөхөд p1 өөрөө дамжигдаж байна. var p2 = p1; p2.price = 120000; // утгууд өөрөө дамждаг p1 p2 -ын алингийн ч name, price утгыг солиход 2ууллаа өөрчилөгдөж байна. p1.name = "shoes"; console.log("p1 = " + p1.name + " " + p1.price); console.log("p2 = " + p2.name + " " + p2.price); //-------2b. Массивд заагч утга ашиглах: Array Reference-------------------------------------------------------------------- var x = [2, 6, 10]; // Объектодтой ижил нэг хаягыг зөөж байна. var y = x; y[0] = 50; x[3] = 7; console.log(x); console.log(y); //----- 2c. Функцад заагч утга ашиглах: Function Reference------------------------------------------------------------------ var name = "notebook"; var price = 300000; info(name, price); console.log(name + "ны үнэ : " + price); function info(name, price) { console.log(name + " нэртэй бүтээгдэхүүн " + price + " үнэтэй байснаа "); price = price - 5000; //буцаагаад өөррүү хадгалаад хэвлэхэд 5000 хасагдсан утга хэвлэж байна. console.log(price + " болж хямдарлаа "); } //-----2d. Функцруу объект байдлаар хйиж утгыг өөрчилж үзэцгээе. Function+Object+Reference------------------------------------ // функц дотор объектоор утга дамжуулж байгаа тохиолдолд маш болгоомжтой дамжуулахгүй бол функц дотор утгыг өөрчилөхөд дамжуулсан объек дотор утга өөрчилөгдсөн байдаг. Маш олон мөр кодонд энэ 2 өөр өөр газар байж болно. объекын утгыг өөрчлөхөд функцын утга өөрчилөгдөөд байна. мөн функцын утгыг өөрчлөхөд объекын утга өөрчилөгдөөд байна. var product = { name: "shoe", price: "15000" }; infoNew(product); console.log(product.name + " бүтээгдэхүүний үнэ : " + product.price); function infoNew(p) { console.log(p.name + " нэртэй бүтээгдэхүүн " + p.price + " үнэтэй байснаа "); p.price = p.price - 2000; console.log(p.price + " болж хямдарлаа "); }
module.exports = { "extends": "fbjs" };
console.log(null || 2 || undefined); console.log(1 && null && 2); console.log(null || 2 && 3 || 4);
function areaOfCountry(name, area) { const prozent = ((1 / 1489400) * area).toFixed(2); return `${name} is ${prozent}% of the total world's landmass`; } const result = areaOfCountry('Russia', 17098242); console.log(result);
/* * Toady * Copyright 2015 Tom Shawver */ // Dependencies var _ = require('lodash'); var ribbit = require('../app/ribbit/Ribbit'); var util = require('util'); // Parse command and arguments var cmd = process.argv[2] ? process.argv[2].toLowerCase() : ''; var args = process.argv.slice(3).join(' '); // Route command switch (cmd) { case 'start': startToady(args); break; case 'search': search(args); break; case 'install': install(args); break; case 'uninstall': uninstall(args); break; default: printUsage(); process.exit(1); } /** * Outputs a fatal error message and exits. * @param {Error} err An error object to display * @param {number} [code=1] The exit code with which to exit the process. */ function exitFatal(err, code) { if (code === undefined || code === null) { code = 1; } console.log(err.stack); process.exit(code); } /** * Installs a given Toady mod. * @param {string} modName The name of the mod to be installed, without the * prefix */ function install(modName) { var modPkg = ribbit.MOD_PREFIX + modName; console.log('Installing ' + modPkg + '...'); ribbit.install(modName, function(err) { if (err) { exitFatal(err); } else { console.log('Installed!'); } }); } /** * Outputs usage instructions to stdout. */ function printUsage() { var usage = [ 'USAGE: ./ribbit <command> [options]\n', 'COMMANDS:', ' start [config] Starts Toady. Loads the \'default\' config, unless', ' you specify a different one.', ' search [term] Searches for Toady mods that can be installed. If', ' the search term is omitted, we\'ll list everything!', ' install <mod> Installs a Toady mod. If Toady is currently running,', ' use /msg Toady loadmod <mod> in IRC to load it up.', ' uninstall <mod> Uninstalls an installed mod. If Toady is currently', ' running, consider /msg Toady unloadmod <mod> first.' ]; usage.forEach(console.log); } /** * Lists any Toady mods matching the search query, or all mods if no query * is provided. * @param {string} query A search query to limit the results */ function search(query) { ribbit.search(query).then(function(resObj) { if (!resObj.modIds || !resObj.modIds.length) { throw new Error('No results for "' + query + '.'); } var maxId = resObj.modIds.reduce(function(a, b) { return Math.max(a.length || 0, b.length || 0); }, 0); var maxDesc = process.stdout.columns - maxId - 4; console.log(''); resObj.modIds.forEach(function(modId) { console.log(util.format('%s %s', _.padRight(modId, maxId), resObj.res[ribbit.MOD_PREFIX + modId].description.substr(0, maxDesc) )); }); }).catch(exitFatal); } /** * Starts an instance of Toady. If called with no arguments, Toady will * be started using config/default.yaml as the config file. Otherwise, * Toady will attempt to load config/{ARGS}.yaml. * @param {string} [configName] The name of the config to load */ function startToady(configName) { if (configName === 'default') { configName = null; } if (configName) { process.env.NODE_ENV = args; } require('../app/Toady'); } /** * Uninstalls a Toady mod. * @param {string} modId An installed mod ID to be deleted */ function uninstall(modId) { var modPkg = ribbit.MOD_PREFIX + modId; console.log('Uninstalling ' + modPkg + '...'); ribbit.uninstall(modId).then(function() { console.log('Uninstalled.'); }).catch(exitFatal); }
import { Game } from './game.js'; import { MEDIUM } from './gameSpeed.js' import { Speed } from './gameSpeed.js' var game = new Game(); game.runAtSpeed(MEDIUM); //game.runAtSpeed(Speed.MEDIUM);
(function() { 'use strict'; angular .module('Directives') .directive('contentTitle', contentTitle); contentTitle.$inject = []; function contentTitle() { var directive = { templateUrl: 'core-modules/directives/content-title/content-title.directive.html', link: link, restrict: 'EA', }; return directive; function link($scope, element, attrs) { // console.log('elm', element) // console.log('attrsB', attrs) // console.log('scope', $scope) $scope.title = attrs.title // console.log($scope.boom.url) } } })();
var RunView = Backbone.View.extend({ model: null, tagName: 'li', template(model) { // Wire up model events return ` <a href="#${model.id}"> <span class="list-items date">${model.get('date')}</span> <span class="list-items time">${model.get('time')}</span> </a>`; }, render() { // Sets up the DOM this.$el.html(this.template(this.model)); return this.$el; }, }); export default Backbone.View.extend({ collection: null, tagName: 'ul', attributes: { class: 'run-list', }, initialize() { // Setup events this.listenTo(this.collection, 'change reset add remove', this.render); // Make sure that if no new items are fetched we still see something on screen this.render(); }, render() { this.$el.empty(); // For each item in collection make a new 'li' this.collection.forEach((run) => { var listItem = new RunView({model: run}); this.$el.append(listItem.render()); }); this.$el.append(`<li class="new-btn"> <a href="#new" class="plus button"><i class="fa fa-plus"></i></a> </li>`); }, });
import React, { Component } from 'react' import { connect } from 'react-redux'; import TextAreaFieldGroup from '../common/TextAreaFieldGroup' import { sendApplication } from '../../actions/career'; import TextFieldGroup from '../common/TextFieldGroup'; class OfferForm extends Component { constructor(props) { super(props) this.state = { message: '', subject: '', email: '', attachment: null, errors: {} }; } static getDerivedStateFromProps = (nextProps) => { if(nextProps.errors) { return { errors: nextProps.errors }; } }; onSubmit = (e) => { e.preventDefault(); const { message, subject, email, attachment } = this.state; const { sendApplication, id, history } = this.props; sendApplication({ message, subject, email, attachment, offerId: id }, history); } handleUploadFile = event => { const selectedFile = event.target.files; if (selectedFile.length > 0) { if(selectedFile[0].size > 1536) { this.setState({ errors: { ...this.state.errors, file: 'File is too big' } }) } const fileToLoad = selectedFile[0]; const { type, name: fileName } = fileToLoad; const fileReader = new FileReader(); fileReader.onload = fileLoadedEvent => { const file = fileLoadedEvent.target.result; const base64File = new Buffer(file).toString('base64'); this.setState({ attachment: { base64File, fileName, type }, }) }; fileReader.readAsArrayBuffer(fileToLoad); } } handleChange = e => { const { name, value } = e.target; this.setState({ [name]: value, }); }; render() { const { errors, message, subject, email } = this.state; const { isVerified } = this.props; return ( <form className='mt-3' noValidate onSubmit={this.onSubmit}> <h3 className='text-center'>Apply for a job</h3> {!isVerified && <div className='small text-center text-secondary'>(Only verified users can send job applications)</div>} <div className="form-group mt-3"> <TextFieldGroup placeholder="Your email" name="email" type="email" value={email} onChange={this.handleChange} error={errors.email} disabled={!isVerified} /> <TextFieldGroup placeholder="Subject" name="subject" type="text" value={subject} onChange={this.handleChange} error={errors.subject} disabled={!isVerified} /> <TextAreaFieldGroup placeholder="Some message" name="message" value={message} onChange={this.handleChange} error={errors.message} disabled={!isVerified} /> </div> <input disabled={!isVerified} onChange={this.handleUploadFile} type="file" name="upload" accept="application/pdf" /> <button disabled={!isVerified} type="submit" className="btn btn-dark"> Send application </button> </form> ); } } const mapStateToProps = ({ errors }) => ({ errors }) export default connect(mapStateToProps, { sendApplication })(OfferForm);
describe("FolderModel", function () { var folder; beforeEach(function () { folder = new FolderModel(); }); it("should be initialized with default values", function () { expect(folder.get("id")).toEqual(null); expect(folder.get("title")).toEqual(""); expect(folder.get("expanded")).toEqual(true); }); it("should contain task lists when initialized with task lists", function () { var json = { id: 100, title: "Sample Folder", taskLists: [ { id: 101, title: "Sample List A" }, { id: 102, title: "Sample List B" } ] }; var folder = new FolderModel(json); expect(folder.get("id")).toEqual(100); expect(folder.get("title")).toEqual("Sample Folder"); expect(folder.get("taskLists").length).toEqual(2); expect(folder.get("taskLists").at(0).get("id")).toEqual(101); expect(folder.get("taskLists").at(0).get("title")).toEqual("Sample List A"); expect(folder.get("taskLists").at(1).get("id")).toEqual(102); expect(folder.get("taskLists").at(1).get("title")).toEqual("Sample List B"); }); });
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import { openLinkInNewTab, truncateText } from '../utils.ts'; import NotFound from '../assets/not-found.jpg'; const Article = styled.div` width: 20em; height: 25em; border: solid 1px black; cursor: pointer; &:hover { box-shadow: 0px 0px 10px #060f75; } `; const InnerArticle = styled.div` display: grid; grid-template-columns: 20% 80%; height: 76%; `; const Image = styled.img` width: 100%; `; const NewsSourceContainer = styled.section` display: flex; justify-content: center; align-items: center; background: #060f75; `; const NewsSource = styled.p` writing-mode: vertical-rl; color: #ffffff; `; const Title = styled.h3` grid-column: 1/-1; text-align: center; padding: 0 0.2em 0.2em; background: #5e6bfb; margin: 0; height: 5em; display: flex; align-items: center; text-overflow: ellipsis; `; const ImageContainer = styled.div` height: 10em; overflow: hidden; `; const DescriptionContainer = styled.section` padding: 0.5em; height: 8em; text-overflow: ellipsis; `; const Description = styled.p` max-height: 8em; text-overflow: ellipsis; `; const NewsArticle = ({ article: { description, source: { name }, title, url, urlToImage, }, }) => ( <Article onClick={() => openLinkInNewTab(url)} onKeyPress={() => openLinkInNewTab(url)} role="button" tabIndex="0" > <Title>{title}</Title> <InnerArticle> <NewsSourceContainer> <NewsSource>{name}</NewsSource> </NewsSourceContainer> <div> <ImageContainer> <Image src={!urlToImage ? NotFound : urlToImage} alt={`${title}`} /> </ImageContainer> <DescriptionContainer> <Description>{truncateText(description)}</Description> </DescriptionContainer> </div> </InnerArticle> </Article> ); export default NewsArticle; NewsArticle.propTypes = { article: PropTypes.shape({ description: PropTypes.string.isRequired, source: PropTypes.shape({ name: PropTypes.string.isRequired, }).isRequired, title: PropTypes.string.isRequired, url: PropTypes.string.isRequired, urlToImage: PropTypes.string, }).isRequired, };
import React from "react"; import { ApolloProvider, ApolloClient, InMemoryCache, createHttpLink } from "@apollo/client"; import { setContext } from "@apollo/client/link/context"; import { BrowserRouter as Router, Route, Switch } from "react-router-dom"; import Header from "./components/header/"; import Home from "./pages/Home"; import LoginForm from "./pages/Login"; import SignUpForm from "./pages/Signup"; import Instructions from "./components/Instructions"; import Social from "./pages/Social"; import SingleComment from "./pages/SingleComment" const httpLink = createHttpLink({ uri: "/graphql" }); const authLink = setContext((_, { headers }) => { const token = localStorage.getItem("id_token") return { headers: { ...headers, authorization: token ? `Bearer ${token}` : "" } }; }); const client = new ApolloClient({ link: authLink.concat(httpLink), cache: new InMemoryCache() }); function App() { return ( <ApolloProvider client={client}> <Router> <div className="flex-column justify-flex-start min-100-vh"> <Header /> <div className="container"> <Switch> <Route exact path="/" component={Home} /> <Route exact path="/cups/:number"/> <Route exact path="/instructions/:brewId" component={Instructions}/> <Route exact path="/login"component={LoginForm} /> <Route exact path="/signup"component={SignUpForm}/> <Route exact path="/shop"/> <Route exact path="/social" component={Social}/> <Route exact path="/comments/:postId" component={SingleComment}/> </Switch> </div> </div> </Router> </ApolloProvider> ); } export default App;
var MyMath; (function (MyMath) { var PI = 3.14; function calculate_circumference(diameter) { return PI * diameter; } MyMath.calculate_circumference = calculate_circumference; function calculate_rectangle(length, width) { return length * width; } MyMath.calculate_rectangle = calculate_rectangle; })(MyMath || (MyMath = {}));
import React,{useState,useEffect,useCallback, useLayoutEffect} from 'react'; import creativeLogo from '../assets/images/creative-logo1.png'; import Leftbar from './header/Leftbar' import Rightbar from './header/Rightbar' import { MoreHorizontal } from 'react-feather'; import {SearchBarToggle, MobileRightToggle, SwitchToggle} from '../redux/actions' import { Label, Input } from 'reactstrap'; import { useDispatch, useSelector } from 'react-redux'; import {MENUITEMS} from './sidebar/menu' import {Link} from 'react-router-dom' import logo_light from '../assets/images/creative-logo.png' export const Header = () => { const configDB = useSelector(content => content.Customizer.customizer); const sidebar_background_color = configDB.settings.sidebar_background_setting; // eslint-disable-next-line const [mainmenu, setMainMenu] = useState(MENUITEMS); const [searchValue, setsearchValue] = useState(''); // eslint-disable-next-line const [searchResult, setSearchResult] = useState(false); // eslint-disable-next-line const [searchResultEmpty, setSearchResultEmpty] = useState(false); const dispatch = useDispatch(); const searchTog = useSelector(state => state.Common.searchToggle) const mobileRightTog = useSelector(state => state.Common.mobileRightToggle) const switchToggle= useSelector(state => state.Common.switchToggle) const width = useWindowSize() const escFunction = useCallback((event) => { if(event.keyCode === 27) { setsearchValue('') } }, []); function useWindowSize() { const [size, setSize] = useState([0, 0]); useLayoutEffect(() => { function updateSize() { setSize(window.innerWidth); } window.addEventListener('resize', updateSize); updateSize(); return () => window.removeEventListener('resize', updateSize); }, []); return size; } useEffect(() => { if (width <= 991) { document.querySelector(".page-main-header").className = 'page-main-header open' document.querySelector(".page-sidebar").className = 'page-sidebar open' if (localStorage.getItem("layout_version") === 'dark-only') { document.querySelector(".header-logo").className = 'header-logo light'; } else { document.querySelector(".header-logo").className = 'header-logo normal'; } } else { document.querySelector(".page-main-header").className = 'page-main-header ' document.querySelector(".page-sidebar").className = 'page-sidebar ' + sidebar_background_color } document.addEventListener("keydown", escFunction, false); return () => { document.removeEventListener("keydown", escFunction, false); }; }, [escFunction,width,sidebar_background_color]); const handleSearchKeyword = (keyword) => { keyword ? addFix() : removeFix() const items = []; setsearchValue(keyword) mainmenu.filter(menuItems => { if (menuItems.title.toLowerCase().includes(keyword) && menuItems.type === 'link') { items.push(menuItems); } if (!menuItems.children) return false menuItems.children.filter(subItems => { if (subItems.title.toLowerCase().includes(keyword) && subItems.type === 'link') { subItems.icon = menuItems.icon items.push(subItems); } if (!subItems.children) return false subItems.children.filter(suSubItems => { if (suSubItems.title.toLowerCase().includes(keyword)) { suSubItems.icon = menuItems.icon items.push(suSubItems); } return suSubItems }) return subItems }) checkSearchResultEmpty(items) setsearchValue(items); return menuItems }); } const checkSearchResultEmpty = (items) => { if (!items.length) { setSearchResultEmpty(true); document.querySelector(".empty-menu").classList.add('is-open'); } else { setSearchResultEmpty(false); document.querySelector(".empty-menu").classList.remove('is-open'); } } const addFix = () => { setSearchResult(true); document.querySelector(".Typeahead-menu").classList.add('is-open'); } const removeFix = () => { setSearchResult(false) setsearchValue('') } return( <div className={`page-main-header ${switchToggle? 'open': ''}`}> <div className="main-header-right row"> <div className="main-header-left d-lg-none"> <div className="logo-wrapper header-logo normal"><a href="#javascript"> <img className="normallogo" src={creativeLogo} alt=""/> <img className="lightlogo" src={logo_light} alt="" /> </a></div> </div> <div className="mobile-sidebar d-block"> <div className="media-body text-right switch-sm"> <Label className="switch"> <Input type="checkbox" onChange={() => dispatch(SwitchToggle(switchToggle))} checked={!switchToggle}/> <span className="switch-state"></span> </Label> </div> </div> <Leftbar/> <Rightbar/> <form className={`form-inline search-full ${searchTog? 'open': ''}`}> <div className="form-group form-control-plaintext"> <input type="search" id="search" placeholder="Search.." defaultValue={searchValue} onChange={(e) => handleSearchKeyword(e.target.value)} /> <i onClick={() => dispatch(SearchBarToggle(searchTog))} className="icon-close -search close-search"></i> <div className="Typeahead-menu custom-scrollbar" id="search-outer"> {searchValue ? searchValue.map((data, index) => { return ( <div className="ProfileCard u-cf" key={index}> <div className="ProfileCard-avatar"> <data.icon /> </div> <div className="ProfileCard-details"> <div className="ProfileCard-realName"> <Link to={data.path} className="realname" onClick={removeFix} > {data.title} </Link> </div> </div> </div> ) }) : '' } </div> <div className="Typeahead-menu empty-menu"> <div className="tt-dataset tt-dataset-0"> <div className="EmptyMessage"> Opps!! There are no result found. </div> </div> </div> </div> </form> <div className="d-lg-none mobile-toggle pull-right"><MoreHorizontal onClick={() => dispatch(MobileRightToggle(mobileRightTog))}/></div> </div> </div> ) } export default Header
/** * Created by DELL on 2017/11/16. */ const userManageDao=require("../dao/userManageDao.js") const userManageController={ pageCount:5, getAllmanageUser(request,response){ console.log("in usermanage"); let params=[]; params.push((request.params.page-1)*userManageController.pageCount) params.push(userManageController.pageCount); var url=request._parsedOriginalUrl.pathname; var arr=url.split("/"); var page=parseInt(arr[arr.length-1]); userManageDao.getAllmanageUsers(params).then(data=>{ let userlist=data; userManageDao.gettotalCount().then(data=>{ let totalCount=Math.ceil((data[0].countnum)/userManageController.pageCount); response.render("userManage",{userlist:userlist,totalCount:totalCount,pages:page}); }); }).catch(err=>{ console.log(err.message); }); }, editStatus(request,response){ let status=request.body.statusValue; let id=request.body.userid; let params=[status,id]; console.log("statuscontroller:",status); userManageDao.editStatus(params).then(data=>{ console.log("edit----------:",data); response.send(data); }).catch(err=>{ console.log(err.message); }); } } module.exports=userManageController;
var yarp = require('../../yarp'); var ibm_sound_port_receiver = new yarp.Port('sound'); ibm_sound_port_receiver.open('/ibmjs/sound:i'); var ibm_speech_to_text_sender = new yarp.Port('bottle'); ibm_speech_to_text_sender.open('/ibmjs/speech_to_text:o'); const sample_rate = 16000; const bit_depth = 16; const num_samples=16000; const rec_seconds=5; var buff_count=0; var done = false; var text=''; var uint8 = new Uint8Array(num_samples*2*rec_seconds); var fs = require('fs'); const SpeechToTextV1 = require('watson-developer-cloud/speech-to-text/v1'); const SpeechToText = new SpeechToTextV1({ username: 'cdaee4f4-7d66-48a9-ac15-431c55de2b18', password: 'lDEwbqFTFkDm', version: '2018-02-16' }); // Sound from user ibm_sound_port_receiver.onRead(function(msg){ if(buff_count<rec_seconds) { console.log("I am receiving sound ..."); uint8.set(msg.toSend().content, buff_count*(num_samples*2)); buff_count++; } else if (buff_count==rec_seconds) { buff_count=0; console.log('Wav file creation ...'); const audio_file=fs.createWriteStream('giulia_new.wav'); var buffer = getData(uint8, sample_rate); audio_file.write(buffer); console.log('Wav file created !'); SpeechToTextFile(); } }); //Functions function SpeechToTextFile() { var audio_file = fs.createReadStream('giulia_new.wav'); var recognizeParams = { audio: audio_file, 'content_type': 'audio/wav' }; SpeechToText.recognize(recognizeParams, function(error, speechRecognitionResults) { if (error) { console.log(error); } else { console.log(JSON.stringify(speechRecognitionResults)); console.log(JSON.stringify(speechRecognitionResults.results[0])); //if(typeof Results == "undefined") //{ // console.log('Try repeating again please!'); //} //else //{ //console.log(JSON.stringify(speechRecognitionResults, null, 2)); var transcript_msg=JSON.stringify(speechRecognitionResults.results[0].alternatives[0].transcript); ibm_speech_to_text_sender.write(transcript_msg); console.log('Message from STT: ', transcript_msg); //} } }); } function time() { var d = new Date(); var n = d.getTime(); return n } var u32ToArray = function(i) { return [i&0xFF, (i>>8)&0xFF, (i>>16)&0xFF, (i>>24)&0xFF]; }; var u16ToArray = function(i) { return [i&0xFF, (i>>8)&0xFF]; }; function getData(buffer, sampleRate, bitsPerSample = 16) { var data = buffer; var sampleRate = sampleRate; var header = { // OFFS SIZE NOTES chunkId : [0x52,0x49,0x46,0x46], // 0 4 "RIFF" = 0x52494646 chunkSize : 0, // 4 4 36+SubChunk2Size = 4+(8+SubChunk1Size)+(8+SubChunk2Size) format : [0x57,0x41,0x56,0x45], // 8 4 "WAVE" = 0x57415645 subChunk1Id : [0x66,0x6d,0x74,0x20], // 12 4 "fmt " = 0x666d7420 subChunk1Size: 16, // 16 4 16 for PCM audioFormat : 1, // 20 2 PCM = 1 numChannels : 1, // 22 2 Mono = 1, Stereo = 2... sampleRate : sampleRate, // 24 4 8000, 44100... byteRate : 0, // 28 4 SampleRate*NumChannels*BitsPerSample/8 blockAlign : 0, // 32 2 NumChannels*BitsPerSample/8 bitsPerSample: bitsPerSample, // 34 2 8 bits = 8, 16 bits = 16 subChunk2Id : [0x64,0x61,0x74,0x61], // 36 4 "data" = 0x64617461 subChunk2Size: 0 // 40 4 data size = NumSamples*NumChannels*BitsPerSample/8 }; header.blockAlign = (header.numChannels * header.bitsPerSample)/8; header.byteRate = header.blockAlign * header.sampleRate; header.subChunk2Size = data.byteLength; header.chunkSize = 36 + header.subChunk2Size; var headernew = new Uint8Array(44); headernew.set(header.chunkId, 0); headernew.set(u32ToArray(header.chunkSize), 4); headernew.set(header.format, 8); headernew.set(header.subChunk1Id, 12); headernew.set(u32ToArray(header.subChunk1Size), 16); headernew.set(u16ToArray(header.audioFormat), 20); headernew.set(u16ToArray(header.numChannels), 22); headernew.set(u32ToArray(header.sampleRate), 24); headernew.set(u32ToArray(header.byteRate), 28); headernew.set(u16ToArray(header.blockAlign), 32); headernew.set(u16ToArray(header.bitsPerSample), 34); headernew.set(header.subChunk2Id, 36); headernew.set(u32ToArray(header.subChunk2Size), 40); var buffer_sound = new Uint8Array(headernew.length + data.length); buffer_sound.set(headernew); buffer_sound.set(data, headernew.length); return Buffer.alloc((num_samples*2)*rec_seconds, buffer_sound); } /** * Copyright 2016 IBM Corp. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* const watson = require('watson-developer-cloud'); const authorizationService = new watson.AuthorizationV1({ username: process.env.SPEECH_TO_TEXT_USERNAME || 'e0ea3a19-20a9-4c87-a7e6-34a45ee8447e', password: process.env.SPEECH_TO_TEXT_PASSWORD || 'IQ6y6CU1DNAI', url: watson.SpeechToTextV1.URL }); // Inform user that TTS is not configured properly or at all if (!(process.env.SPEECH_TO_TEXT_USERNAME && process.env.SPEECH_TO_TEXT_PASSWORD)) { // eslint-disable-next-line console.warn('WARNING: The app has not been configured with a SPEECH_TO_TEXT_USERNAME and/or ' + 'a SPEECH_TO_TEXT_PASSWORD environment variable. If you wish to have text to speech ' + 'in your working application, please refer to the https://github.com/watson-developer-cloud/car-dashboard ' + 'README documentation on how to set these variables.'); } module.exports = function initSpeechToText(app) { app.get('/api/speech-to-text/token', (req, res) => authorizationService.getToken(function (err, token) { if (err) { console.log('error:', err); console.log('Please refer to the https://github.com/watson-developer-cloud/car-dashboard\n' + 'README documentation on how to set username and password variables.'); } else { res.send(token); } }) ); }; */
import React from "react"; import { push } from "react-router-redux"; import { bindActionCreators } from "redux"; import { connect } from "react-redux"; import { getIexData } from "../../../modules/PullStocks"; import Company from "../../company"; import { checkSign, setColor } from "../../../helpers/helpers"; const addWatchList = props => { return ( <React.Fragment> <div className="stripe" /> <div class="widget"> <h1>We've added {props.symbol} to your watch list</h1> <a href="/watchlist">View my watchlist</a> </div> </React.Fragment> ); }; const mapStateToProps = state => ({ quote: state.PullStocks.quote, path: state.routing.location.pathname, website: state.PullStocks.website, symbol: state.PullStocks.symbol // description: state.PullStocks.description, // ceo: state.PullStocks.ceo, // sector: state.PullStocks.sector, // industry: state.PullStocks.industry }); const mapDispatchToProps = dispatch => bindActionCreators( { getIexData, changePage: () => push("/about-us") }, dispatch ); export default connect( mapStateToProps, mapDispatchToProps )(addWatchList);
// @flow weak import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { withStyles, createStyleSheet } from 'material-ui/styles'; import List, { ListItem, ListItemIcon, ListItemText } from 'material-ui/List'; import Drawer from 'material-ui/Drawer'; import Divider from 'material-ui/Divider'; import DashboardIcon from 'material-ui-icons/Dashboard'; import ListIcon from 'material-ui-icons/List'; import ReportIcon from 'material-ui-icons/Report'; import IconButton from 'material-ui/IconButton'; import MenuIcon from 'material-ui-icons/Menu'; import Blue from 'material-ui/colors/blue'; const styleSheet = createStyleSheet({ list: { width: 250, flex: 'initial', }, listFull: { width: 'auto', flex: 'initial', }, sideMenu: { background: Blue.A400 } }); class SideMenu extends Component { constructor(props) { super(props); this.state = { open: true, docked:true }; this.handleOpen = this.handleOpen.bind(this); this.handleClose = this.handleClose.bind(this); } handleOpen() { this.setState({ open: true }); } handleClose() { this.setState({ open: false }); } render() { const classes = this.props.classes; const mailFolderListItems = ( <div> <ListItem button> <ListItemIcon> <DashboardIcon /> </ListItemIcon> <ListItemText primary="Dashboard" /> </ListItem> <ListItem button> <ListItemIcon> <ListIcon /> </ListItemIcon> <ListItemText primary="Issue" /> </ListItem> </div> ); const otherMailFolderListItems = ( <div> <ListItem button> <ListItemIcon> <ReportIcon /> </ListItemIcon> <ListItemText primary="Report" /> </ListItem> </div> ); const sideList = ( <div> <List className={classes.list} disablePadding> {mailFolderListItems} </List> <Divider /> <List className={classes.list} disablePadding> {otherMailFolderListItems} </List> </div> ); return ( <Drawer docked open onClick={this.handleClose} style={{ zIndex: 10 }} > {sideList} </Drawer> ); } } SideMenu.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styleSheet)(SideMenu);
(function () { var warped_image = document.getElementById('warped_image'), warp_canvas = document.createElement('canvas'), warp_context = warp_canvas.getContext('2d'); // inputs var warp_percentage_input = document.getElementById('warp_percentage'); // for reference, the full method function getQuadraticBezierXYatT(start_point, control_point, end_point, T) { var pow1minusTsquared = Math.pow(1 - T, 2), powTsquared = Math.pow(T, 2); var x = pow1minusTsquared * start_point.x + 2 * (1 - T) * T * control_point.x + powTsquared * end_point.x, y = pow1minusTsquared * start_point.y + 2 * (1 - T) * T * control_point.y + powTsquared * end_point.y; return { x: x, y: y }; } function warpHorizontally (image_to_warp, invert_curve) { var image_width = image_to_warp.width, image_height = image_to_warp.height, warp_percentage = parseFloat(warp_percentage_input.value, 10), // for fun purposes and nicer controls // I chose to determine the offset by applying a percentage value to the image width warp_x_offset = warp_percentage * image_width; warp_canvas.width = image_width + Math.ceil(warp_x_offset * 2); warp_canvas.height = image_height; // see https://www.rgraph.net/blog/an-example-of-the-html5-canvas-quadraticcurveto-function.html // for more details regarding start_point, control_point si end_point var start_point = { x: 0, y: 0 }; var control_point = { x: invert_curve ? warp_x_offset : -warp_x_offset, y: image_height / 2 }; var end_point = { x: 0, y: image_height }; var offset_x_points = [], t = 0; for ( ; t < image_height; t++ ) { var xyAtT = getQuadraticBezierXYatT(start_point, control_point, end_point, t / image_height), x = parseInt(xyAtT.x); offset_x_points.push(x); } warp_context.clearRect(0, 0, warp_canvas.width, warp_canvas.height); var y = 0; for ( ; y < image_height; y++ ) { warp_context.drawImage(image_to_warp, // clip 1 pixel wide slice from the image //x, 0, 1, image_height + warp_y_offset, 0, y, image_width + warp_x_offset, 1, // draw that slice with a y-offset //x, warp_y_offset + offset_y_points[x], 1, image_height + warp_y_offset warp_x_offset + offset_x_points[y], y, image_width + warp_x_offset, 1 ); } } function warpVertically (image_to_warp, invert_curve) { var image_width = image_to_warp.width, image_height = image_to_warp.height, warp_percentage = parseFloat(warp_percentage_input.value, 10), // for fun purposes and nicer controls // I chose to determine the offset by applying a percentage value to the image height warp_y_offset = warp_percentage * image_height; warp_canvas.width = image_width; warp_canvas.height = image_height + Math.ceil(warp_y_offset * 2); // see https://www.rgraph.net/blog/an-example-of-the-html5-canvas-quadraticcurveto-function.html // for more details regarding start_point, control_point si end_point var start_point = { x: 0, y: 0 }; var control_point = { x: image_width / 2, y: invert_curve ? warp_y_offset : -warp_y_offset }; var end_point = { x: image_width, y: 0 }; var offset_y_points = [], t = 0; for ( ; t < image_width; t++ ) { var xyAtT = getQuadraticBezierXYatT(start_point, control_point, end_point, t / image_width), y = parseInt(xyAtT.y); offset_y_points.push(y); } warp_context.clearRect(0, 0, warp_canvas.width, warp_canvas.height); var x = 0; for ( ; x < image_width; x++ ) { warp_context.drawImage(image_to_warp, // clip 1 pixel wide slice from the image x, 0, 1, image_height + warp_y_offset, // draw that slice with a y-offset x, warp_y_offset + offset_y_points[x], 1, image_height + warp_y_offset ); } } function warpImage () { var image_to_warp = new Image(); image_to_warp.onload = function () { var warp_orientation = document.querySelector('input[name="warp_orientation"]:checked').value, invert_curve = document.getElementById('invert_curve').checked; if (warp_orientation === 'horizontal') { warpHorizontally(image_to_warp, invert_curve); } else { warpVertically(image_to_warp, invert_curve); } warped_image.src = warp_canvas.toDataURL(); } image_to_warp.src = 'test_image.jpg'; } warpImage(); window.warpImage = warpImage; })();
let nome = "Jose"; let sobrenome = "Silva"; let frase = `Bem vindo usuário, ${nome} ${sobrenome}!`; document.querySelector('p').innerHTML = frase; function criarcard(){ let title = document.querySelector(".titulo").value; let url = document.querySelector(".url").value; let card = document.getElementById('card'); card.innerHTML += `<div><h2>${title}</h2><br><img src="${url}"></img></div>`; } document.querySelector('button').addEventListener('click',criarcard);
app.component('main', { binsings: {}, templateUrl: 'App/Components/mainTemplate.html', controller: function () { this.mainTitle = 'Inbox'; } })
export { default } from '@smile-io/ember-smile-polaris/components/polaris-color-picker/hue-picker';
import React, {useContext, useEffect, useState} from 'react'; import {ApiStoreContext} from "../../stores/api_store"; import styles from "./styles/UserWall.module.scss"; import {observer} from "mobx-react"; const UserWall = observer((props) => { const context = useContext(ApiStoreContext); if (context.loggedIn) { return <div>{props.children}</div> } else { return <div className={styles.container}>You need to be logged in to be here!"</div> } }); export default UserWall;
import Link from 'next/link'; import styles from '../styles/Home.module.css'; const Links = () => { return ( <div> <div className={styles.container}> <div className={styles.grid}> <Link href='/africa'> <div className={styles.card}> <h1>Africa</h1> </div> </Link> <Link href='/america'> <div className={styles.card}> <h1>America</h1> </div> </Link> <Link href='/asia'> <div className={styles.card}> <h1>Asia</h1> </div> </Link> <Link href='/atlantic'> <div className={styles.card}> <h1>Atlantic</h1> </div> </Link> <Link href='/australia'> <div className={styles.card}> <h1>Australia</h1> </div> </Link> <Link href='/europe'> <div className={styles.card}> <h1>Europe</h1> </div> </Link> <Link href='/indian'> <div className={styles.card}> <h1>Indian Ocean</h1> </div> </Link> <Link href='/pacific'> <div className={styles.card}> <h1>Pacific Ocean</h1> </div> </Link> </div> </div> </div> ) } export default Links
var searchData= [ ['gradojpeg',['GradoJPEG',['../classpresentacion_1_1form_1_1PopUp__Comp.html#acf726751a39641f547274bfe8176fedd',1,'presentacion::form::PopUp_Comp']]] ];
const request = require('request-promise-native'); const moment = require('moment'); const config = require('../config'); const UnauthorizedError = require('../errors/UnauthorizedError'); class FacebookApi { constructor(accessToken = null) { this.accessToken = accessToken; } async getAccessToken(exchangeToken) { try { const { access_token: accessToken, expires_in: expiresIn, } = await this._apiRequest({ uri: `/oauth/access_token`, qs: { grant_type: 'fb_exchange_token', client_id: config.get('FACEBOOK_CLIENT_ID'), client_secret: config.get('FACEBOOK_CLIENT_SECRET'), fb_exchange_token: exchangeToken, }, }); this.accessToken = accessToken; return { accessToken, expiresIn: moment() .add(expiresIn, seconds) .toDate(), }; } catch (e) { console.error('FB error', e.message); throw new UnauthorizedError('invalid_exchange_token'); } } async getMe(fields = []) { return await this._apiRequest({ uri: `/me?fields=${fields.join(',')}`, }); } async _apiRequest(opts) { const { uri, qs = {} } = opts; if (this.accessToken) { qs.access_token = this.accessToken; } return await request({ baseUrl: 'https://graph.facebook.com/', uri: uri, qs, json: true, }); } } module.exports = FacebookApi;
// 链式调用 import ajax from './05-promise-ajax.js' let url = "api/users.json" ajax(url) .then(function (value) { // 1. then 方法返回一个新的 promise 对象 console.log(111); console.log(value); }).then(function (value) { // 2. 后一个 then 方法 实际上就在为上一个 then 方法返回的 promise 做回调注册 console.log(222); console.log(value); // undefined 上一个回调函数默认返回的是 undefined }).then(function (value) { console.log(333); console.log(value); // undefined return ajax(url) // 返回一个自定义 promise }).then(function (value) { // 4. 上一个 then 方法的回调函数若返回是一个 promise ,而不是一个值,那下一个 then 的回调会等待它的结束 console.log(444); console.log(value); // 上一个 ajax 的结束后,返回成功的结果,如果失败就不进来了 return 'ccc' // 返回一个值 默认是 undefined }).then(function (value) { // 3. 上一个 then 方法回调函数的返回值 就是下一个 then 方法回调函数的参数 value console.log(555); console.log(value); // ccc })
function getString() { let userInput = document.getElementById("userInput").value; if(typeof userInput === "string") { let reversedString = reverseString(userInput); displayString(reversedString); } else { alert("Error: Please enter a string"); } } function reverseString(userString) { let reversedString = []; for(let i = userString.length - 1; i >= 0; i--) { reversedString += userString[i]; } return reversedString; } function displayString(reversedString) { let templateRow = ""; templateRow += `<p>${reversedString}</p>`; document.getElementById("results").innerHTML = templateRow; }
const Store = require('flux/utils').Store; const dispatcher = require('../dispatcher/dispatcher'); const SessionConstants = require('../constants/session_constants'); const hashHistory = require('react-router').hashHistory; let _currentUser = {}; const SessionStore = new Store(dispatcher); SessionStore._login = function(payload){ _currentUser = payload.user; hashHistory.push("index"); this.__emitChange(); }; SessionStore._found = function(payload){ _currentUser = payload.user; this.__emitChange(); }; SessionStore._logout = function(){ _currentUser = {}; hashHistory.push("/"); this.__emitChange(); }; SessionStore.currentUser = function(){ return _currentUser; }; SessionStore.isUserLoggedIn = function(){ return Boolean(Object.keys(_currentUser).length); }; SessionStore.__onDispatch = function(payload){ switch(payload.actionType) { case SessionConstants.LOGIN: this._login(payload); break; case SessionConstants.LOGOUT: this._logout(); break; case SessionConstants.USER_FOUND: this._found(payload); break; } }; module.exports = SessionStore;
import util from 'util'; import { SEVERITY_NAME } from '../constants'; /** * Console adapter * */ export default class Console { /** * * @param {Object} options * @constructor */ constructor(options) { this._options = options || { enabled: true }; if (!this._options.hasOwnProperty('enabled')) { this._options.enabled = true; } } /** * * @param {number} facility * @param {number} severity * @param {string} hostname * @param {string} application * @param {string} date * @param {string} message * * eslint-disable max-params */ write(facility, severity, hostname, application, date, message) { // eslint-disable-line max-params if (this._options.enabled) { const output = this._fmt(facility, severity, hostname, application, date, message); this._write(output); } } /** * * * @param {number} facility * @param {number} severity * @param {string} hostname * @param {string} application * @param {string} date * @param {string} message * @private */ _fmt(facility, severity, hostname, application, date, message) { // eslint-disable-line max-params const severityName = SEVERITY_NAME[severity]; return util.format("[%s] %s: %s", date, severityName, message); } /** * * @param {string} output * @private */ _write(output) { console.log(output); // eslint-disable-line no-console } };
$(document).ready(function() { // Wait for the data to load setTimeout(function() { // If data was loaded if($('.movie').length) { // Initially select the first loaded movie $('.movie:nth-child(1)').addClass('selected'); // Selection of movie with mouse on hover // works only after the elements are loaded $('.movie').on('mouseenter', function() { $('.movie.selected').removeClass('selected'); $(this).addClass('selected'); }) $('.movie').on('mouseleave', function() { $(this).removeClass('selected'); }) } }, 1000); // Selection of movie using navigation keys from keyboard (TV buttons) $(document).keydown(function(e) { switch(e.which) { // Right key case 37: { current_index = $('.movie.selected').index(); if(current_index > 0) { $('.movie.selected').removeClass('selected'); $('.movie').eq(current_index-1).addClass('selected'); } } break; // Up key case 38: { current_index = $('.movie.selected').index(); if(current_index > 3) { $('.movie.selected').removeClass('selected'); $('.movie').eq(current_index-4).addClass('selected'); } } break; // Left key case 39: { current_index = $('.movie.selected').index(); if(current_index < $('.movie').length-1) { $('.movie.selected').removeClass('selected'); $('.movie').eq(current_index+1).addClass('selected'); } } break; // Up key case 40: { current_index = $('.movie.selected').index(); if(current_index < $('.movie').length-4) { $('.movie.selected').removeClass('selected'); $('.movie').eq(current_index+4).addClass('selected'); } } break; // Enter key case 13: { $('.movie.selected a img').trigger('click'); } break; // Back key case 8: { // To be implemented } break; default: return; } e.preventDefault(); }); });
function InitializeGuard(multi){ var canvas = document.getElementById('mainCanvas'); var context = canvas.getContext('2d'); context.scale(1,1); GUARD = { initialized: true, spotAng: 0, x : 10, y : 10, width: 150, height: 200, speed: 5, latest : { x : 0, y : 0 }, src : "pics/guardsolo.png" }; } function HandleGuardCollision(){ if(GUARD.y > 0 && GUARD.x < (GAME.canvas.width-GUARD.width) && GUARD.x > 0 && GUARD.y < (GAME.canvas.height - GUARD.height) ){ return false; } return true; } // Rotate rotates a point around // cx, cy : The central point // x, y : The coordinates of point to be rotatedPoint // angle : Angle in degrees of rotation function RotateGuard(cx, cy, x, y, angle) { var radians = (Math.PI / 180) * angle, cos = Math.cos(radians), sin = Math.sin(radians), nx = (cos * (x - cx)) + (sin * (y - cy)) + cx, ny = (cos * (y - cy)) - (sin * (x - cx)) + cy; return [nx, ny]; } // RotateAroundOrigin // x, y : The coordinates of point to be rotatedPoint // angle : Angle in degrees of rotation function RotateAroundOrigin(x, y, angle) { return Rotate(0, 0, x, y, angle); } function RenderGuard(context) { if (!GUARD.initialized) { return; } var guardimg = new Image(); guardimg.src = GUARD.src; context.drawImage(guardimg, GUARD.x, GUARD.y, GUARD.width, GUARD.height); }
var variables________________________________9________________8js________8js____8js__8js_8js = [ [ "variables________________9________8js____8js__8js_8js", "variables________________________________9________________8js________8js____8js__8js_8js.html#ad9c427e331cc6a0682368a6a3ab1517c", null ] ];
const fs = require('fs'); const schedule = require('node-schedule'); const ConfigBuilder = require('../components/configbuilder'); const GekkoManager = require('./gekkomanager'); const config = require('../config/config'); const {StrategyFinder} = require('../components/strategyfinder'); const InfoMessage = { START: 'Running Reactive Trader', }; const ErrorMessage = { NO_STRATEGIES_FOUND: 'No strategies found', }; class TradingManager { constructor() { this.gekkoManager = GekkoManager.getInstance(); this.configBuilder = new ConfigBuilder(); this.strategyFinder = StrategyFinder.getInstance(); if (this.configBuilder.isValid()) { this.start(); } else { throw new Error(WARNING_CONFIG_ERROR); } } static getInstance() { if (!this.instance_) { this.instance_ = new TradingManager(); } return this.instance_; } async start() { await this.gekkoManager.runServer(); // Make sure we have enough backtest data before starting await this.configBuilder.buildImportConfig(); await this.gekkoManager.importData(); // Now start the strategy loop this.updateStrategy(); } async updateStrategy() { // Set new strategy const strategy = await this.strategyFinder.findNewStrategy(); await this.runStrategy(strategy.entity); // Schedule the update const updateInterval = config.updateSettingsTime; const candleSize = strategy.entity.input.candleSize; const interval = updateInterval * candleSize * 1000 * 60; const fireAt = new Date(Date.now() + interval); this.updateSchedule = schedule.scheduleJob(fireAt, () => this.updateStrategy()); console.log('The next update will happen at ' + fireAt); } async runStrategy(strategy) { if (config.paperTrader || config.liveTrader) { const tradeType = config.paperTrader ? 'paper' : 'live'; console.log(`About to start ${tradeType} trading.`); } else { console.log('You need to enable live or paper trading.'); return; } console.log('Running strategy: ', strategy); await this.configBuilder.buildStrategyConfig(strategy); await this.gekkoManager.runTrader(); } } module.exports = () => TradingManager.getInstance();
define(['jquery', 'echarts'], ($, echarts) => { let module = {}; let chart; module.init = (el) => { var chart = echarts.init(document.getElementById(el)); var options = { tooltip: { formatter: "{a} <br/>{c} {b}" }, toolbox: { show: true, feature: { mark: { show: true }, restore: { show: true }, saveAsImage: { show: true } } }, series: [{ name: '速度', type: 'gauge', min: 0, max: 220, splitNumber: 11, axisLine: { // 坐标轴线 lineStyle: { // 属性lineStyle控制线条样式 width: 10 } }, axisTick: { // 坐标轴小标记 length: 15, // 属性length控制线长 lineStyle: { // 属性lineStyle控制线条样式 color: 'auto' } }, splitLine: { // 分隔线 length: 20, // 属性length控制线长 lineStyle: { // 属性lineStyle(详见lineStyle)控制线条样式 color: 'auto' } }, title: { textStyle: { // 其余属性默认使用全局文本样式,详见TEXTSTYLE fontWeight: 'bolder', fontSize: 20, fontStyle: 'italic' } }, detail: { textStyle: { // 其余属性默认使用全局文本样式,详见TEXTSTYLE fontWeight: 'bolder' } }, data: [{ value: 40, name: 'km/h' }] }, { name: '转速', type: 'gauge', center: ['25%', '55%'], // 默认全局居中 radius: '50%', min: 0, max: 7, endAngle: 45, splitNumber: 7, axisLine: { // 坐标轴线 lineStyle: { // 属性lineStyle控制线条样式 width: 8 } }, axisTick: { // 坐标轴小标记 length: 12, // 属性length控制线长 lineStyle: { // 属性lineStyle控制线条样式 color: 'auto' } }, splitLine: { // 分隔线 length: 20, // 属性length控制线长 lineStyle: { // 属性lineStyle(详见lineStyle)控制线条样式 color: 'auto' } }, pointer: { width: 5 }, title: { offsetCenter: [0, '-30%'], // x, y,单位px }, detail: { textStyle: { // 其余属性默认使用全局文本样式,详见TEXTSTYLE fontWeight: 'bolder' } }, data: [{ value: 1.5, name: 'x1000 r/min' }] }, { name: '油表', type: 'gauge', center: ['75%', '50%'], // 默认全局居中 radius: '50%', min: 0, max: 2, startAngle: 135, endAngle: 45, splitNumber: 2, axisLine: { // 坐标轴线 lineStyle: { // 属性lineStyle控制线条样式 color: [ [0.2, '#ff4500'], [0.8, '#48b'], [1, '#228b22'] ], width: 8 } }, axisTick: { // 坐标轴小标记 splitNumber: 5, length: 10, // 属性length控制线长 lineStyle: { // 属性lineStyle控制线条样式 color: 'auto' } }, axisLabel: { formatter: function (v) { switch (v + '') { case '0': return 'E'; case '1': return 'Gas'; case '2': return 'F'; } } }, splitLine: { // 分隔线 length: 15, // 属性length控制线长 lineStyle: { // 属性lineStyle(详见lineStyle)控制线条样式 color: 'auto' } }, pointer: { width: 2 }, title: { show: false }, detail: { show: false }, data: [{ value: 0.5, name: 'gas' }] }, { name: '水表', type: 'gauge', center: ['75%', '50%'], // 默认全局居中 radius: '50%', min: 0, max: 2, startAngle: 315, endAngle: 225, splitNumber: 2, axisLine: { // 坐标轴线 lineStyle: { // 属性lineStyle控制线条样式 color: [ [0.2, '#ff4500'], [0.8, '#48b'], [1, '#228b22'] ], width: 8 } }, axisTick: { // 坐标轴小标记 show: false }, axisLabel: { formatter: function (v) { switch (v + '') { case '0': return 'H'; case '1': return 'Water'; case '2': return 'C'; } } }, splitLine: { // 分隔线 length: 15, // 属性length控制线长 lineStyle: { // 属性lineStyle(详见lineStyle)控制线条样式 color: 'auto' } }, pointer: { width: 2 }, title: { show: false }, detail: { show: false }, data: [{ value: 0.5, name: 'gas' }] } ] }; chart.setOption(options); $(window).on('resize', chart.resize); }; module.destroy = () => { if (chart) { $(window).off('resize', chart.resize); } }; return module; });
import React from 'react'; class EditingBy extends React.Component { constructor(props) { super(props); this.isModifing = this.isModifing.bind(this); } isModifing(editedBy) { if(editedBy == undefined) { return ''; } if(editedBy.length > 0) { return 'fa fa-lock lockList'; } else{ return ''; } } render() { return( <i id = {this.props.Id + "State"} className={this.isModifing(this.props.EditedBy)} aria-hidden="true"> {this.props.EditedBy}</i> ); } } export default EditingBy;
#!/usr/bin/env node const { extendStack } = require('..') function subsystem (err) { return extendStack(err) } setImmediate(() => { const err = subsystem(new Error('some-error')) console.log(err) })
import React from 'react'; import './index.css'; export class AppContentTripDetailFeature extends React.Component{ render(){ const { tripLine } = this.props.tripDetailData; let tripArrA = [tripLine.facilities, tripLine.amusement, tripLine.diet, tripLine.equipmentLeasing, tripLine.qualification]; let name = ['设施', '娱乐活动', '饮食', '装备租赁', '技术指标']; return ( <div className="app-content-trip-detail-feature"> <div className="app-content-trip-detail-feature-title">设施 &amp; 服务</div> <ul className="app-content-trip-detail-feature-panel"> { tripArrA.map((item, index) => { return ( <li className="app-content-trip-detail-feature-each" key={index}> <div className="app-content-trip-detail-feature-each-name">{name[index]}</div> <ul className="app-content-trip-detail-feature-each-content"> {index < 3 ? item.map((item, index) => { return ( <li key={index} className="app-content-trip-detail-feature-each-content-each">{item}</li> ) }) : item.map((item, index) => { return ( <li key={index} className="app-content-trip-detail-feature-each-content-each"> <span className="app-content-trip-detail-feature-each-content-each-name">{item.name}</span> <span className="app-content-trip-detail-feature-each-content-each-value">{item.value}</span> </li> ) })} </ul> </li> ) }) } </ul> </div> ) } } export default AppContentTripDetailFeature;
function set_form(id) { $('.form').slideUp(); $(id).slideDown(); $('#back').slideDown(); $('.bottom3').slideUp(); } function init_botones(){ $('.instrucciones').slideUp(); $('.bottom3').slideDown(); } function back() { $('.form').slideUp(); $('#results_table').slideUp(); $('.bottom3').slideDown(); $('#back').slideUp('slow'); $('#results_table thead').html(""); $('#results_table tbody').html(""); $('#status_bar').slideUp(); } /* var transpose_table = function() { var $this = $("#results_table"); var newrows = []; $this.find("tr").each(function(){ var i = 0; $this.find("td").each(function(){ i++; if(newrows[i] === undefined) { newrows[i] = $("<tr></tr>"); } newrows[i].append($this); }); }); $this.find("tr").remove(); $.each(newrows, function(){ $this.append(this); }); return false; } */ /* var transpose_table = function() { var rows = $('#results_table tr'); var r = rows.eq(0); var nrows = rows.length; var ncols = rows.eq(0).find('th,td').length; var i = 0; var tb = $('<tbody></tbody>'); while (i < ncols) { cell = 0; tem = $('<tr></tr>'); while (cell < ncols) { next = rows.eq(cell++).find('th,td').eq(0); tem.append(next); } tb.append(tem); ++i; } $('#results_table').append(tb); } */ var make_table = function(rows) { var header = ""; $.each(rows[0], function(key, value) { header += "<th class=\"cell\">" + key + "</th>"; }); header += "<tr>" + header + "</tr>"; var body = ""; $.each(rows, function() { var row = ""; $.each(this, function(key, value) { row += '<td class="cell">' + value + "</td>"; }); var id = this.short_description; body += '<tr class="row" id="' + id + '">' + row + "</tr>"; }); return {header: header, body: body}; } var make_table_transposed = function(rows) { var header = ""; var body = ""; $.each(rows[0], function(key, value) { var row = '<td class="pseudo_header">' + key + '</td>'; $.each(rows, function() { row += '<td class="cell">' + this[key] + '</td>'; }); body += '<tr class="row">' + row + '</tr>'; }); return {header: header, body: body}; } var pretty_table = function(rows, transposed) { if (rows.length == 0) { $('#results_table thead').html(""); $('#results_table tbody').html(""); $('#status_bar').text("There are no results for your query") .slideDown(); return; } var table = (transposed ? make_table_transposed : make_table)(rows); /* $('#results_table').removeClass("table transposed_table") .addClass(transposed ? "transposed_table" : "table"); */ $('#results_table thead').html(table.header); $('#results_table tbody').html(table.body); /* if (transposed) transpose_table(); */ $('#results_table').slideDown(); $('#status_bar').text("Shut up and take your table") .slideDown(); } var make_clickable = function() { $('#results_table tbody tr').on('click', function() { var id = $(this).attr('id'); return do_query('by_short', {short_description: id}, {transposed: true}); }); } var do_query = function(url, data, settings) { $('#status_bar').text("Query sent, waiting server..."); // send ajax $.post(url, data, null, 'json') .done(function(rows) { pretty_table(rows, settings.transposed); // make clickable ?? if (settings.clickable) make_clickable(); }) .fail(function() { $('#status_bar').text("Oops, an error ocurred"); }); return false; } function form_search_by_name(name) { return do_query('api_test', {name: name.toUpperCase()}, {clickable: true}); } function form_single(name) { $('#status_bar').text("Falta cambiar form_single por form_search_by_name"); return false; } function form_versus(name1, name2) { return do_query('versus', {name1: name1, name2: name2}, {transposed: true}); } function form_complex(group, column, min, max) { return do_query('complex', {group: group, column: column, min: min, max: max}, {clickable: true}); }
const { Error: JSONAPIError } = require('jsonapi-serializer'); const { getStatusText, INTERNAL_SERVER_ERROR } = require('http-status-codes'); const errors = require('./dictionaries'); class APIError extends Error { constructor({ status = INTERNAL_SERVER_ERROR, code = false, defaultCode = false, error = '' }) { super(getStatusText(status)); this.status = status; this.code = code; this.defaultCode = defaultCode; this.error = error; } handledError(res) { const errorCode = this.code || this.defaultCode; const [entity, error] = errorCode.split('.'); this.error = { ...errors[entity][error], detail: this.error }; res.status(this.error.status).json({ code: this.error.code }); } unHandledError(res) { const unHandledError = new JSONAPIError({ code: this.code || this.status, detail: this.error.message }); res.status(this.status).json(unHandledError); } sendResponse(res) { if (!this.defaultCode) { this.unHandledError(res); } this.handledError(res); this.logError(this.error); } logError() { app.logger.error({ code: this.error.code, title: this.error.title, detail: this.error.detail, message: this.error.message }); } } module.exports = APIError;
$(document).ready(function() { var randomNumber = ""; var emeraldBlue = ""; var emeraldGreen = ""; var emeraldPurple = ""; var emeraldRed = ""; var userTotal = 0; var wins = 0; var losses = 0; $("#numberWins").text("Wins " + wins); $("#numberLosses").text("Losses " + losses); var newGame = function() { randomNumber = Math.floor(Math.random() * 101) + 19; $('#computerRandom').text(randomNumber); emeraldBlue = Math.floor(Math.random() * 11) + 1; emeraldGreen = Math.floor(Math.random() * 11) + 1; emeraldPurple = Math.floor(Math.random() * 11) + 1; emeraldRed = Math.floor(Math.random() * 11) + 1; userTotal = 0; } newGame(); $(".blue-crystal").on("click", function() { userTotal = userTotal + emeraldBlue; $("#userTotal").text(userTotal); if (userTotal === randomNumber) { wins++; $("#WonLost").text("YOU WIN!!"); newGame(); } else if (userTotal > randomNumber) { losses++; $('#WonLost').text("YOU LOSE!!"); newGame(); } }); $(".green-crystal").on("click", function() { userTotal = userTotal + emeraldGreen; $("#userTotal").text(userTotal); if (userTotal === randomNumber) { wins++; $("#WonLost").text("YOU WIN!!"); newGame(); } else if (userTotal > randomNumber) { losses++; $('#WonLost').text("YOU LOSE!!"); newGame(); } }); $(".purple-crystal").on("click", function() { userTotal = userTotal + emeraldPurple; $("#userTotal").text(userTotal); if (userTotal === randomNumber) { wins++; $("#WonLost").text("YOU WIN!!"); newGame(); } else if (userTotal > randomNumber) { losses++; $('#WonLost').text("YOU LOSE!!"); newGame(); } }); $(".red-crystal").on("click", function() { userTotal = userTotal + emeraldRed; $("#userTotal").text(userTotal); if (userTotal === randomNumber) { wins++; $("#WonLost").text("YOU WIN!!"); newGame(); } else if (userTotal > randomNumber) { losses++; $('#WonLost').text("YOU LOSE!!"); newGame(); } }); });
import './custom.scss' console.log('hello world')
/* 我的实现 首先判断数值的大小 */ function check(num) { if(num < 0 || num === 0) { return false; } if(num === 1) { return true; } while(num = num / 2) { if(num % 2 === 0) { return true; } else { continue; } } return false; } /* 网上的简单的实现的方法 */ function check1(num) { if(num === 0 || num < 0) { return false; } if(num & (num - 1)) { return false; } else { return true; } } console.log(check1(8))
import React from 'react' import { connect } from 'react-redux' import { runAll, runTest } from './actions' import apiMeta from '../apiDetails/./apiManifest' class APIStructureTester extends React.Component { constructor () { super() this.runAll = this.runAll.bind(this) } runAll() { runAll(this.props.dispatch) } render () { var self = this.props const data = apiMeta.map(function(apidata, i) { const response = self.testResponse && self.testResponse[apidata.id] return ( <API apidata={apidata} dispatch={self.dispatch} response={response} key={i}/> ) }) return ( <div className='main-container'> <div className='api-list'> <div className='api-list-content'> <div className='api-list-header'> <div className='column'>API Name</div> <div className='column'>API URL</div> {/*<div className='column'>API Params</div>*/} <div className='column'>API Method</div> <div className='column'> <button className='run-test-btn' onClick={this.runAll}>Run All Tests</button> </div> <div className='column'>API Status Code</div> <div className='column'>API Status</div> </div> {data} </div> </div> </div> ) } } const mapStateToProps = function (state) { return { testResponse: state.testResponse } } export default connect(mapStateToProps)(APIStructureTester) class API extends React.Component { constructor (props) { super(props) this.runTest = this.runTest.bind(this) this.all = this.all.bind(this) this.error = this.error.bind(this) this.state = { tab: 'error' } } runTest () { runTest(this.props.dispatch, { id: this.props.apidata.id }) } all () { this.setState({tab: 'all'}) } error () { this.setState({tab: 'error'}) } render () { return ( <div className='api-row'> <div className='column'>{this.props.apidata.displayName}</div> <div className='column'>{this.props.apidata.url}</div> {/*<div className='column'>{JSON.stringify(this.props.apidata.params)}</div>*/} <div className='column'>{this.props.apidata.method}</div> <div className='column'> <button className='run-test-btn' onClick={this.runTest}>Run Test</button> </div> <div className='column'>{this.props.response && this.props.response.status}</div> {this.props.response && <div className='tabs'> <div className='tab-header-container'> <div className={`tab-header ${this.state.tab === 'error' ? 'active': ''}`} onClick={this.error}>Error</div> <div className={`tab-header ${this.state.tab === 'all' ? 'active': ''}`} onClick={this.all}>All</div> </div> <div className={`result-tab-container ${this.state.tab}`}> { this.props.response && this.props.response.finalResult && <ResultFormatter data={this.props.response.finalResult} /> } { this.props.response && this.props.response.errorResult && <ErrorResult data={this.props.response.errorResult} /> } </div> </div> } </div> ) } } class ResultFormatter extends React.Component { render () { const rows = [] for (let key in this.props.data) { const result = this.props.data[key] rows.push( <div className='result-row'> <div className='result-column fixed'>{key}</div> <div className={`result-column fixed ${result.found ? 'correct':'incorrect'}`}>{result.found ? 'True' : 'False'}</div> <div className='result-column fixed'>{result.typeExpected}</div> <div className={`result-column fixed ${result.typeMatched ? 'correct':'incorrect'}`}>{result.typeMatched ? 'True' : 'False'}</div> { !result.value && typeof(result.data) !== 'object' && <div className='result-column fixed'>{result.data}</div> } { result.value && Array.isArray(result.value) && result.value.map((item, i) => { return ( <div > <div className='childName'> Child {i} </div> <ResultFormatter data={item} /> </div> ) }) } {result.value && !Array.isArray(result.value) && <ResultFormatter data={result.value} /> } </div> ) } return ( <div className='result-table'> <div className='result-row header'> <div className='result-column fixed'>Key Name</div> <div className='result-column fixed'>Found ?</div> <div className='result-column fixed'>Expected Type</div> <div className='result-column fixed'>Type Matched ?</div> <div className='result-column fixed'>Value</div> </div> {rows} </div> ) } } class ErrorResult extends React.Component { render () { const content = this.props.data && this.props.data.map((item)=> { return ( <div className='error'> <span>{item.path.join(" --> ")}</span> &nbsp;->&nbsp; <span>{item.message}</span> </div> ) }) return ( <div className='error-result-container'>{content}</div> ) } }
import * as actionTypes from './ActionTypes'; export const addToCart = item => { return dispatch => { dispatch({ type: actionTypes.ADD_TO_CART, item: item }); dispatch(updateTotalPrice()); dispatch(showCartConfirmation()); setTimeout(function() { dispatch(hideCartConfirmation()); }, 1500); dispatch(addToStorage()); }; }; export const updateTotalPrice = () => { return { type: actionTypes.UPDATE_PRICE }; }; export const showProductInModal = item => { return { type: actionTypes.SHOW_PRODUCT_IN_MODAL, item: item }; }; export const showCartConfirmation = () => { return { type: actionTypes.SHOW_CART_CONFIRMATION }; }; export const hideCartConfirmation = () => { return { type: actionTypes.HIDE_CART_CONFIRMATION }; }; export const addToStorage = () => { return { type: actionTypes.ADD_TO_STORAGE }; }; export const getFromStorage = () => { return { type: actionTypes.GET_FROM_STORAGE }; }; export const removeBasketItem = item => { return dispatch => { dispatch({ type: actionTypes.REMOVE_FROM_BASKET, item: item }); dispatch(addToStorage()); dispatch(updateTotalPrice()); }; }; export const orderDone = () => { return dispatch => { dispatch({ type: actionTypes.ORDER_DONE }); dispatch(updateTotalPrice()); }; }; export const sortByPriceLower = () => { return { type: actionTypes.SORT_BY_PRICE_LOWER }; }; export const sortByPriceHigher = () => { return { type: actionTypes.SORT_BY_PRICE_HIGHER }; }; export const sortByName = () => { return { type: actionTypes.SORT_BY_NAME }; };
import React, { Component } from 'react'; import { connect } from 'react-redux'; import moment from 'moment'; import { getSelected } from '../../ducks/currency'; import { fetchTransactionsRequest, getRecords } from '../../ducks/transactions'; import { getWalletUsd } from '../../ducks/wallet'; import styled from 'styled-components'; class TradeTable extends Component { state = {}; componentDidMount() { this.props.fetchTransactionsRequest(); } componentWillReceiveProps(nextProps) { if (this.props.walletUsd !== nextProps.walletUsd) { nextProps.fetchTransactionsRequest(); } } render() { const { transactions, currencyName } = this.props; const tranactionList = transactions ? transactions.data.result : []; return ( <div> <h4>История операций</h4> <TransactionsTableWrap> <TransactionsTable> <thead> <TransactionsTableHead> <TransactionsTh>Операция</TransactionsTh> <TransactionsTh>Дата</TransactionsTh> <TransactionsTh>{currencyName.toUpperCase()}</TransactionsTh> <TransactionsTh>USD</TransactionsTh> </TransactionsTableHead> </thead> <tbody> {tranactionList.map(transaction => { let key_delta = currencyName + '_delta'; return transaction && transaction.hasOwnProperty(key_delta) ? ( <TransactionsTr key={'transaction_' + transaction.id}> <TransactionsTd> {transaction.usd_delta > 0 ? 'Продажа' : 'Покупка'} </TransactionsTd> <TransactionsTd> {moment(transaction.created_at, 'YYYY-MM-DDTHH:mm:ss.SSSZ').format( 'DD.MM.YY HH:mm', )} </TransactionsTd> <TransactionsTd>{transaction[key_delta]}</TransactionsTd> <TransactionsTd>{transaction['usd_delta']}</TransactionsTd> </TransactionsTr> ) : null; })} </tbody> </TransactionsTable> </TransactionsTableWrap> </div> ); } } const mapStateToProps = state => ({ transactions: getRecords(state), currencyName: getSelected(state), walletUsd: getWalletUsd(state), }); const mapDispatchToProps = { fetchTransactionsRequest }; export default connect( mapStateToProps, mapDispatchToProps, )(TradeTable); //#region styles const TransactionsTableWrap = styled.div` max-height: 160px; overflow: auto; `; const TransactionsTable = styled.table` margin: 0; width: 100%; text-align: right; border: 1px solid #edf0f1; border-collapse: collapse; border-radius: 3px; `; const TransactionsTableHead = styled.tr` background-color: #edf0f1; border: 1px solid #edf0f1; `; const TransactionsTh = styled.th` background-color: #edf0f1; border: 1px solid #edf0f1; `; const TransactionsTr = styled.tr` border: 1px solid #edf0f1; `; const TransactionsTd = styled.td` border: 1px solid #edf0f1; padding: 5px 10px; `; //#endregion
import React, { useState, useEffect } from 'react' import api from '../../api' import Stream from './Stream/Stream' import styles from './Sidebar.module.css' const Sidebar = () => { const [ topStreams, setTopStreams ] = useState([]) useEffect(() => { const fetchData = async () => { const result = await api.get('https://api.twitch.tv/helix/streams') const dataArray = result.data.data const gameIds = dataArray.map(stream => { return stream.game_id }) const userIds = dataArray.map(stream => { return stream.user_id }) const baseUrlGames = 'https://api.twitch.tv/helix/games?' const baseUrlUsers = 'https://api.twitch.tv/helix/users?' let queryParamsGames = '' let queryParamsUsers = '' gameIds.map(id => { return ( queryParamsGames = queryParamsGames + `id=${id}&` ) }) userIds.map(id => { return ( queryParamsUsers = queryParamsUsers + `id=${id}&` ) }) const urlGames = baseUrlGames + queryParamsGames const urlUsers = baseUrlUsers + queryParamsUsers const gamesNames = await api.get(urlGames) const usersNames = await api.get(urlUsers) const gamesNameArray = gamesNames.data.data const usersNameArray = usersNames.data.data const finalArray = dataArray.map(stream => { stream.gameName = '' stream.truePic = '' stream.login = '' gamesNameArray.forEach(game => { usersNameArray.forEach(user => { if (stream.user_id === user.id && stream.game_id === game.id) { stream.gameName = game.name stream.truePic = user.profile_image_url stream.login = user.login } }) }) return stream }) setTopStreams(finalArray.slice(0,6)) } fetchData() }, []) console.log(topStreams) return ( <div className={styles.Sidebar}> <h2 className={styles.TitreSidebar}>Chaînes recommandées</h2> <ul className={styles.ListesStream}> {topStreams.map(stream => ( <Stream key={stream.id} stream={stream} /> ))} </ul> </div> ) } export default Sidebar
import {NavigationContainer} from '@react-navigation/native'; import {createStackNavigator} from '@react-navigation/stack'; import React from 'react'; import SignInScreen from './src/screens/SignInScreen'; import SignUpScreen from './src/screens/SignUpScreen'; import SplashScreen from './src/screens/SpashScreen'; const App = () => { const Stack = createStackNavigator(); return ( <NavigationContainer> <Stack.Navigator initialRouteName="SplashScreen" screenOptions={{headerShown: false}}> <Stack.Screen name="SplashScreen" component={SplashScreen} /> <Stack.Screen name="SignInScreen" component={SignInScreen} /> <Stack.Screen name="SignUpScreen" component={SignUpScreen} /> </Stack.Navigator> </NavigationContainer> ); }; export default App;
import vuescroll from 'vuescroll' export default { props: [], components: { vuescroll }, data() { return { slide_options: { vuescroll: { mode: 'slide', detectResize: true, pullRefresh: { enable: true }, pushLoad: { enable: true, auto: true, autoLoadDistance: 0 }, paging: false, zooming: false, snapping: { enable: false, width: 100, height: 300 }, scroller: { bouncing: { top: 100, bottom: 100 }, locking: true, minZoom: .5, maxZoom: 3, speedMultiplier: .5, penetrationDeceleration: .03, penetrationAcceleration: .08, preventDefault: true, preventDefaultOnMove: true, disable: false } }, bar: { disable: true } } } }, methods: { _scroll_refreshActivate(vm, refreshDom) { }, _scroll_refreshStart(vm, refreshDom, done) { //获取数据之后done() setTimeout(() => { done(); }, 60000) }, _scroll_refreshBeforeDeactivate(vm, refreshDom, done) { //获取数据之后进行提示然后done() done(); }, _scroll_loadActivate(vm, refreshDom) { }, _scroll_loadStart(vm, refreshDom, done) { //获取数据之后done() setTimeout(() => { done(); }, 1000) }, _scroll_loadBeforeDeactivate(vm, refreshDom, done) { //获取数据之后进行提示然后done() done(); } } }
import React from 'react'; import './logoBar.css'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faFacebook, faTwitter, faDiscord, faInstagram } from "@fortawesome/free-brands-svg-icons" export default class LogoBar extends React.Component { render() { return ( <div className="logo-bar-container"> <a href="https://www.facebook.com/utmmcss/"> <FontAwesomeIcon icon={faFacebook} /> </a> <a href="https://discord.com/invite/5K3TuF7DkY"> <FontAwesomeIcon icon={faDiscord} /> </a> <a href="https://www.instagram.com/utmmcss/"> <FontAwesomeIcon icon={faInstagram} /> </a> <a href="https://twitter.com/utmmcss"> <FontAwesomeIcon icon={faTwitter} /> </a> </div> ) } }
import React, { Component } from "react"; import { getDog, deleteDog } from "../../actions/dogActions"; import { connect } from "react-redux"; import PropTypes from "prop-types"; import Moment from "react-moment"; import VaccinTable from "./VaccinTable"; import { Link } from "react-router-dom"; export class DogDetail extends Component { state = { dog: {}, erorrs: {} }; componentWillMount() { this.props.getDog(this.props.match.params.id); } componentWillReceiveProps(nextProps) { if (nextProps.dog) { this.setState({ dog: nextProps.dog }); } } onDeleteVaccin = vaccinId => { this.props.deleteVaccin(this.props.match.params.id, vaccinId); }; onDeleteDog = realName => { const dogName = prompt("โปรดระบุชื่อสุนัขตัวที่ต้องการลบให้ถูกต้อง : "); if (dogName === realName) { this.props.deleteDog(this.props.match.params.id, this.props.history); } else { alert("ชื่อไม่ถูกต้อง"); } }; render() { const { dog } = this.state; return ( <div className="row"> <div className="container"> <div className="row"> <div className="col s12"> <h3>{dog.name}</h3> <hr /> </div> <div className="col s12"> <h6> <span style={{ fontWeight: "bold" }}>เพศ : </span> {dog.sex} </h6> <h6> <span style={{ fontWeight: "bold" }}>วัน/เดือน/ปีเกิด : </span> <Moment format="DD/MM/YYYY">{dog.dateofbirth}</Moment> </h6> <h6> <span style={{ fontWeight: "bold" }}>อายุ : </span> <Moment from={dog.dateofbirth} ago /> </h6> <h6> <span style={{ fontWeight: "bold" }}>สีหลัก : </span> {dog.primarycolor} </h6> <h6> <span style={{ fontWeight: "bold" }}>สีรอง : </span> {dog.secondarycolor} </h6> <h6> <span style={{ fontWeight: "bold" }}>สายพันธุ์ : </span> {dog.breed} </h6> <hr style={{ marginTop: "20px" }} /> </div> <div className="col s12"> <div className="row"> <div className="col s6"> <h6> <span style={{ fontWeight: "bold" }}> วัคซีนที่ได้รับแล้ว : </span> </h6> </div> <div className="col s6"> <Link to={`/dog/${this.props.match.params.id}/addvaccin`} className="waves-effect waves-light btn-small right green white-text" onClick={this.showModal}> <i className="material-icons left">add</i> เพิ่มวัคซีน </Link> </div> <div className="col s12" style={{ marginTop: "20px" }}> <VaccinTable vaccination={dog.vaccination} dogId={this.props.match.params.id} /> </div> </div> <hr /> </div> <div className="col s12 center"> <h6> <span className="red-text" style={{ fontWeight: "bold" }}> คำเตื่อน : </span>{" "} หากลบแล้วจะไม่สามารถกู้คืนข้อมูลของสุนัขตัวที่ถูกลบไปแล้วได้ </h6> <button type="button" className="waves-effect waves-light btn red" style={{ marginTop: "10px" }} onClick={this.onDeleteDog.bind(this, dog.name)}> ลบสุนัขจากรายชื่อ </button> </div> </div> </div> </div> ); } } DogDetail.propTypes = { dog: PropTypes.object.isRequired, getDog: PropTypes.func.isRequired, deleteDog: PropTypes.func.isRequired }; const stateToProps = state => ({ dog: state.dog.dog }); export default connect( stateToProps, { getDog, deleteDog } )(DogDetail);
import React, {Component} from "react"; import {Button, Form, Input} from "antd"; import IntlMessages from "util/IntlMessages"; const FormItem = Form.Item; class ResetPassword extends Component { handleSubmit = (e) => { e.preventDefault(); this.props.form.validateFields((err, values) => { if (!err) { console.log('Received values of form: ', values); } }); }; compareToFirstPassword = (rule, value, callback) => { const form = this.props.form; if (value && value !== form.getFieldValue('password')) { callback('Two passwords that you enter is inconsistent!'); } else { callback(); } }; validateToNextPassword = (rule, value, callback) => { const form = this.props.form; if (value && this.props.confirmDirty) { form.validateFields(['confirm'], {force: true}); } callback(); }; render() { const {getFieldDecorator} = this.props.form; return ( <div className="gx-login-container"> <div className="gx-login-content"> <div className="gx-login-header"> <img src={require("assets/images/logo-white.png")} alt="wieldy" title="wieldy"/> </div> <div className="gx-mb-4"> <h2>Reset Password</h2> <p><IntlMessages id="appModule.enterPasswordReset"/></p> </div> <Form onSubmit={this.handleSubmit} className="gx-login-form gx-form-row0"> <FormItem> {getFieldDecorator('password', { rules: [{ required: true, message: 'Please input your password!', }, { validator: this.validateToNextPassword, }], })( <Input type="password" placeholder="New Password"/> )} </FormItem> <FormItem> {getFieldDecorator('confirm', { rules: [{ required: true, message: 'Please confirm your password!', }, { validator: this.compareToFirstPassword, }], })( <Input placeholder="Retype New Password" type="password" onBlur={this.handleConfirmBlur}/> )} </FormItem> <FormItem> <Button type="primary" htmlType="submit"> <IntlMessages id="app.userAuth.reset"/> </Button> </FormItem> </Form> </div> </div> ); } } const WrappedResetPasswordForm = Form.create()(ResetPassword); export default (WrappedResetPasswordForm);
/** * Created by xuwusheng on 15/12/18. */ define(['../../../app'], function (app) { app.factory('logisticsSettle', ['$http','$q','$filter','HOST',function ($http,$q, $filter,HOST) { return { getThead: function () { return [ {name:'序号',type:'pl4GridCount'}, {field:'carOutTime',name:'回执时间'}, {field:'owerCKName',name:'负责仓储'}, {field:'wlComp',name:'配送中心'}, {field:'wlTaskTypeId',name:'配送方式'}, {field:'opUser',name:'配送员'}, {field:'taskId',name:'业务单号'}, {field:'orderID',name:'客户单号'}, // {field:'payWay',name:'结算分类'}, // {field:'billState',name:'订单状态'}, {field:'orderTypeId',name:'业务类型'}, {field:'orderPrice',name:'订单金额'}, {field:'pay',name:'配送费'}, {field:'clearType',name:'结算方式'}, ] }, getSearch: function() { var deferred = $q.defer(); $http.post(HOST + '/payMent/getWlDicLists',{}) .success(function(data) { deferred.resolve(data); }) .error(function(e) { deferred.reject('error:' + e); }); return deferred.promise; }, getDataTable: function (url,data) { //将parm转换成json字符串 data.param=$filter('json')(data.param); var deferred=$q.defer(); $http.post(url, data) .success(function (data) { deferred.resolve(data); }) .error(function (e) { deferred.reject('error:'+e); }); return deferred.promise; } } }]); });/** * Created by xuwusheng on 15/12/18. */
import ScreenPic from "./screen-pic"; export default ScreenPic;
const passport = require('passport'); const passportGoogle = require('passport-google-oauth'); const config = require('../config'); const User = require('../model/user'); const passportConfig = { clientID: '459875133220-6b57t8jq619cnaab7v99f4ru16308u7m.apps.googleusercontent.com', clientSecret: 'dnTpZD6lCvAQkFms8efrdJbG', callbackURL: 'http://localhost:3000/api/authentication/google/redirect' }; if (passportConfig.clientID) { passport.use(new passportGoogle.OAuth2Strategy(passportConfig, function (request, accessToken, refreshToken, profile, done) { User.findOne({'provider':'google','uid':profile.id}) .then((user)=>{ console.log("\n\n\nuser::"+user) if (!user) { console.log('user does not exists',user) User.create({ name:profile.displayName, provider:'google', uid:profile.id, photoUrl:profile.photos[0] }).then((user )=> { return done(null, user) console.log('eita exec hoy nken!!user') }) } else { console.log('user already exists',user) return done(null, user); } }) })); }
const $ = jQuery = jquery = require ("jquery") const notification = require ("cloudflare/core/notification") const common = require ("cloudflare/common") $(document).on ( "cloudflare.speed.auto_minify.initialize", ( event, data ) => { var jsState = data.response.result.value.js === "on" var cssState = data.response.result.value.css === "on" var htmlState = data.response.result.value.html === "on" $(data.section).find ("input[value='javascript']").prop ( "checked", jsState ) $(data.section).find ("input[value='css']").prop ( "checked", cssState ) $(data.section).find ("input[value='html']").prop ( "checked", htmlState ) }) $(document).on ( "cloudflare.speed.auto_minify.change", ( event, data ) => { var jsVal = $(data.section).find ("input[value='javascript']").prop ("checked") var cssVal = $(data.section).find ("input[value='css']").prop ("checked") var htmlVal = $(data.section).find ("input[value='html']").prop ("checked") $(data.section).addClass ("loading") $.ajax ({ url: data.form.endpoint, type: "POST", data: { "form_key": data.form.key, "js": jsVal, "css": cssVal, "html": htmlVal }, success: ( response ) => { notification.showMessages ( response ) common.loadSections (".auto_minify") } }) })
'use strict'; const yeoman = require('yeoman-generator'); const chalk = require('chalk'); const yosay = require('yosay'); // Key = pretty name // Value = generator name const generators = { 'ES6 Module': 'ES6' }; module.exports = yeoman.Base.extend({ prompting: function () { // Have Yeoman greet the user. this.log(yosay( `Welcome to the amazing ${chalk.red('MarshallOfSound')} generator!` )); const prompts = [ { type: 'list', name: 'generator', choices: Object.keys(generators), message: 'Which generator do you want to run?' } ]; return this.prompt(prompts) .then(props => { this.props = props; }); }, writing: function () { // Do nothing }, install: function () { this.spawnCommand('yo', [`mos:${generators[this.props.generator]}`]); } });
// components/Login.js import React, { Component, PropTypes } from 'react' import Input from './Input'; import { Form } from 'formsy-react'; import Dropzone from "react-dropzone"; import { config } from '../config.js' const API_URL = config.API_URL; export default class EditProfilForm extends Component { constructor(props) { super(props); this.state = { image: "" }; } componentDidMount() { this.props.fetchProfilInfos(); let img = localStorage.getItem('img') || null if (img){ this.setState({ image: API_URL+img, file: null }) } } submit(data) { console.log(data); let form = new FormData(); form.append('username', data.username); form.append('email', data.email); form.append('image', this.state.image); this.props.onEditProfilClick(form); } onDrop(files) { this.setState({ image: files[0].preview, file: files[0] }); } render() { const {errorMessage, fetchProfilInfos, onEditProfilClick, userInfos} = this.props let username = localStorage.getItem('username') || null let img = localStorage.getItem('img') || null return ( <Form onSubmit={this.submit.bind(this)} className="edit-profil-form"> <div className="edit-profil-form-right"> <div className="edit-profil-form-right-block"> <div className="edit-profil-form-right-title">{username}</div> {this.state.image != "" ? <div> <div className="edit-profil-form-img-container"> <img className="edit-profil-form-img" src={this.state.image}/> </div> <div className="edit-profil-form-edit btn2"> <svg className="icon icon-edit"> <use xlinkHref="#icon-edit"></use> </svg> <div className="edit-profil-form-edit-text" onClick={(e)=>this.setState({image:"", file: null})}>Modifier la photo</div> </div> </div> : <Dropzone onDrop={this.onDrop.bind(this)} className="edit-profil-form-upload-dropzone"> <div className="edit-profil-form-upload-dropzone-text"><span className="c-main">Cliquez-glissez</span> une photo ici, ou <span className="c-main">cliquez</span> pour sélectionner une photo à uploader</div> </Dropzone> } </div> </div> <div className="edit-profil-form-left"> <div className="edit-profil-form-block"> <Input className=" edit-profil-form-block-input " placeholder="Username" name="username" validations="minLength:2" value={username} title="Prénom" validationError="Votre username doit contenir plus de 2 caractères" required /> </div> {userInfos && <div className="edit-profil-form-block"> <Input className=" edit-profil-form-block-input " placeholder="Adresse email" name="email" value={userInfos.email} title="Adresse email" validations="isEmail" validationError="Email invalide" required /> </div> } {errorMessage && <p>{errorMessage}</p> } <button className="edit-profil-form-btn btn1" type="submit"> Modifier </button> </div> </Form> ) } }
import JSONCell from "./json.vue"; import TimestampCell from "./timestamp.vue"; import NumberCell from "./number.vue"; import StringCell from "./string.vue"; import BooleanCell from "./boolean.vue"; import DurationCell from "./duration.vue"; export const columnTypes = { timestamp: { component: TimestampCell, width: 180, }, duration: { component: DurationCell, width: 80, }, number: { component: NumberCell, width: 100, }, string: { component: StringCell, width: 150, }, boolean: { component: BooleanCell, width: 8 * 5, }, enum: { component: StringCell, width: 100, }, json: { component: JSONCell, width: 250, }, }; export default function (t) { return columnTypes[t] || columnTypes.json; }
import logo from './logo.svg'; import './App.css'; import Topic from './Topics/Topics' import Chatroom from './Chatroom/ChatRoom' import Join from './Join/JoinRoom' import{ useState, useEffect} from 'react'; import { useHistory, BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom'; import { AnimatedRoute, AnimatedSwitch } from 'react-router-transition'; //import { makeStyles } from '@material-ui/core/styles'; //import BottomNavigation from '@material-ui/core/BottomNavigation'; //import BottomNavigationAction from '@material-ui/core/BottomNavigationAction'; //import RestoreIcon from '@material-ui/icons/Restore'; //import FavoriteIcon from '@material-ui/icons/Favorite'; //import LocationOnIcon from '@material-ui/icons/LocationOn'; /*const useStyles = makeStyles({ root: { height: "10vh", }, });*/ function App() { const [activeNavbar, setActiveNavbar] = useState("home") //const classes = useStyles(); return ( <div className="App"> <meta name="viewport" content="width=device-width, initial-scale=1"></meta> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3pro.css"></link> <p class="app-title">chatable.io </p> <div className="app-body"> <Switch > <Route path='/chat' component={()=><Chatroom/> }></Route> <Route path='/join' component={Join}></Route> <Route path='/home' component={()=><Topic props/> }></Route> </Switch> </div> <div class="bottom-nav"> {/* <BottomNavigation value={activeNavbar} onChange={(event, newValue) => { setActiveNavbar(newValue); }} showLabels > <BottomNavigationAction label="home" icon={<RestoreIcon />} /> <BottomNavigationAction label="Favorites" icon={<FavoriteIcon />} /> <BottomNavigationAction label="Nearby" icon={<LocationOnIcon />} /> </BottomNavigation>*/} </div> </div> ); } export default App;
import React, { Component } from "react"; import axios from 'axios'; import Menu from 'sub-antd/lib/menu'; const SubMenu = Menu.SubMenu; class SysMenu extends Component { constructor(props){ super(props); this.state = { menuTree:[] } } handleClick = (e)=>{ if(typeof (this.props.gotoNewPage) === 'function'){ this.props.gotoNewPage(e) } } componentDidMount(){ axios.get("/sysware/api/menu/queryMenu").then(res => { this.setState({ menuTree: res.data.data }); }) } render() { return ( <Menu onClick={this.handleClick} style={{ width: 200 }} mode="inline" > {this.state.menuTree.map((fmenu,findex)=>{ if(fmenu.leaf){ return <Menu.Item key={fmenu.url?fmenu.url:fmenu.name}>{fmenu.name}</Menu.Item>; }else{ return <SubMenu key={fmenu.url?fmenu.url:fmenu.name} title={fmenu.name}> {fmenu.subMenuList&&fmenu.subMenuList.map((smenu,sindex)=>{ return <Menu.Item key={smenu.url?smenu.url:smenu.name}><a href={smenu.url}>{smenu.name}</a></Menu.Item>; })} </SubMenu> } })} </Menu> ); } } export default SysMenu;
({ qsToEventMap: { 'startURL': 'e.c:setStartUrl' }, qsToEventMap2: { 'expid': 'e.c:setExpId' }, handleSelfRegister: function(component) { var accountId = component.get("v.accountId"); var regConfirmUrl = component.get("v.regConfirmUrl"); var firstname = component.find("firstname").get("v.value"); var lastname = component.find("lastname").get("v.value"); var email = component.find("email").get("v.value"); var includePassword = component.get("v.includePasswordField"); var password = component.find("password").get("v.value"); var confirmPassword = component.find("confirmPassword").get("v.value"); var action = component.get("c.selfRegister"); var extraFields = JSON.stringify(component.get("v.extraFields")); // somehow apex controllers refuse to deal with list of maps var startUrl = component.get("v.startUrl"); startUrl = decodeURIComponent(startUrl); action.setParams({ firstname: firstname, lastname: lastname, email: email, password: password, confirmPassword: confirmPassword, accountId: accountId, regConfirmUrl: regConfirmUrl, extraFields: extraFields, startUrl: startUrl, includePassword: includePassword }); action.setCallback(this, $A.getCallback(function (response) { var state = response.getState(); if (state === "SUCCESS") { var rtnValue = response.getReturnValue(); if (rtnValue !== null) { component.set("v.errorMessage", rtnValue); component.set("v.showError", true); } } else if (state === "INCOMPLETE") { this.showToast('error', $A.get("$Label.c.Status_incomplete"), 'Error'); } else if (state === "ERROR") { var errors = response.getError(); if (errors) { if (errors.length > 0) { for (var i = 0; i < errors.length; i++) { if (errors[0].pageErrors) { if (errors[0].pageErrors.length > 0) { for (var j = 0; j < errors[i].pageErrors.length; j++) { this.showToast('error', 'Internal server error: ' + errors[i].pageErrors[j].message, 'Error'); } } } this.showToast('error', errors[i].message, 'Error'); } } } else { this.showToast('error', $A.get("$Label.c.Internal_server_error"), 'Error'); } } })); //$A.enqueueAction(action); }, getExtraFields: function(component) { var action = component.get("c.getExtraFields"); action.setParam("extraFieldsFieldSet", component.get("v.extraFieldsFieldSet")); action.setCallback(this, $A.getCallback(function (response) { var state = response.getState(); if (state === "SUCCESS") { var rtnValue = response.getReturnValue(); if (rtnValue !== null) { component.set('v.extraFields', rtnValue); } } else if (state === "INCOMPLETE") { this.showToast('error', $A.get("$Label.c.Status_incomplete"), 'Error'); } else if (state === "ERROR") { var errors = response.getError(); if (errors) { if (errors.length > 0) { for (var i = 0; i < errors.length; i++) { if (errors[0].pageErrors) { if (errors[0].pageErrors.length > 0) { for (var j = 0; j < errors[i].pageErrors.length; j++) { this.showToast('error', 'Internal server error: ' + errors[i].pageErrors[j].message, 'Error'); } } } this.showToast('error', errors[i].message, 'Error'); } } } else { this.showToast('error', $A.get("$Label.c.Internal_server_error"), 'Error'); } } })); $A.enqueueAction(action); }, setBrandingCookie: function(component) { var expId = component.get("v.expid"); if (expId) { var action = component.get("c.setExperienceId"); action.setParams({ expId: expId }); action.setCallback(this, function(a) {}); $A.enqueueAction(action); } }, showToast: function (type, message, title) { var showToast = $A.get("e.force:showToast"); //console.log('showToast ', showToast); showToast.setParams({ mode: 'pester', type: type, title: title, message: message, duration: '5000' }); showToast.fire(); } })
this.VelhaMania.module('Utilities', function (Utilities, App, Backbone, Marionette, $, _) { var API = { mixinTemplateHelpers: function (target) { var templateHelpers; if (this.templateHelpers) { templateHelpers = this.templateHelpers.call(this, target); } return _.extend(target, templateHelpers); }, viewBase: function () { _.extend(Marionette.View.prototype, { mixinTemplateHelpers: API.mixinTemplateHelpers }); } }; Utilities.on('start', function () { API.viewBase(); }); });
for(var a=0; a<=10; a++){ console.log(a); if(a%2 ==0){ console.log('even'); } else{ console.log('odd'); } }
// Written by Euno Cho, Fall 2019 $(document).ready(function() { "use strict"; var av_name = "partDeriv2CON"; var av = new JSAV(av_name, {animationMode: "none"}); //building tree var tr = av.ds.tree({nodegap: 15, top: -30, left: 350}); var rootA = tr.root("A"); var firstC = tr.newNode("a"); var secondC = tr.newNode("A"); var thirdC = tr.newNode("a"); rootA.addChild(firstC); rootA.addChild(secondC); rootA.addChild(thirdC); tr.layout(); av.displayInit(); av.recorded(); });
import React, { Component } from 'react'; import Calendar from 'react-calendar-mobile'; import './App.css'; class App extends Component { constructor(props) { super(props); this.state = { date1: '', date2: '', month: '', week: '', } } onSelect1(value) { this.setState({ date1: value }); } onChange1(value) { this.setState({ month: value }) } onSelect2(value) { this.setState({ date2: value }) } onChange2(value) { this.setState({ week: value }) } formatDate(date) { if (typeof date === 'object') { return `${date.getFullYear()}-${`0${(date.getMonth() + 1)}`.slice(-2)}-${`0${(date.getDate())}`.slice(-2)}`; } } setDecorate() { const today = new Date(); const threeDays = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 3); const sixDays = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 6); return { [this.formatDate(today)]: true, [this.formatDate(threeDays)]: true, [this.formatDate(sixDays)]: {}, } } render() { var today = new Date(); var nextMonth = new Date(today.getFullYear(), today.getMonth() + 2, today.getDate()); return ( <div className="row"> <Calendar startDateAt={ nextMonth } decorate={ this.setDecorate() } onSelectDate={ (v) => this.onSelect1(v) } onChange={ (v) => this.onChange1(v) }></Calendar> <div className="calendar__value"> <span className="title">Selected Date: </span> <span className="value">{ this.formatDate(this.state.date1) }</span> </div> <div className="calendar__value"> <span className="title">Current Month Start: </span> <span className="value">{ this.formatDate(this.state.month) }</span> </div> <Calendar i18n="zh-cn" weekFormat="short" decorate={ this.setDecorate() } view='week' onSelectDate={ (v) => this.onSelect2(v) } onChange={ (v) => this.onChange2(v) }></Calendar> <div className="calendar__value"> <span className="title">Selected Date: </span> <span className="value">{ this.formatDate(this.state.date2) }</span> </div> <div className="calendar__value"> <span className="title">Current Month Start: </span> <span className="value">{ this.formatDate(this.state.week) }</span> </div> </div> ); } } export default App;
import React, { Component } from 'react' import './index.css' import TypeSelect from '../TypeSelect' import FastBuild from '../fastModule/FastBuild' import AccurateBuild from '../accurateModule/AccurateBuild' import EditTemplate from '../EditTemplate' import FastEditBuild from '../fastEditModule/FastEditBuild' import AccurateEditBuild from '../accurateEditModule/AccurateEditBuild' /* ******** typeMap: 1 => 手动 2 => 批量 3 => 精准 4 => 快速 ********* */ /* viewType: ADD 新增 EDIT 编辑 */ /** * pageType: ACCURATE_BUILD,ACCURATE_EDIT,FAST_BUILD,FAST_EDIT,SELECT **/ export default class GIbuildMain extends Component { constructor(props){ super(props) this.state = { pageType: 'SELECT', selectTemplateData: null } } componentDidMount(){ } selectType=(pageType)=>{ // 选择建群类型,上一步,下一步操作 this.setState({pageType}) if(pageType==='SELECT'||pageType=='FAST_EDIT'){ this.props.setPromptFlagHandle(false) }else{ this.props.setPromptFlagHandle(true) } } selectEditTemplate=(templateData)=>{ // console.log(templateData) this.setState({ selectTemplateData: templateData }) } cancelBuild = () => { this.selectType('SELECT') } render() { const {selectTemplateData} = this.state const {actions,setPromptFlagHandle} = this.props const {pageType} = this.state return ( <div className="gi-build"> { // 页面选择 pageType==='SELECT'?<TypeSelect selectType={this.selectType} actions={actions} selectEditTemplate={this.selectEditTemplate}/>:"" } { // 精准新建 pageType==='ACCURATE_BUILD'?<AccurateBuild selectType={this.selectType} cancelBuild={this.cancelBuild} actions={actions} setPromptFlagHandle={setPromptFlagHandle}/>:'' } { // 快速新建 pageType==='FAST_BUILD'?<FastBuild selectType={this.selectType} cancelBuild={this.cancelBuild} actions={actions} setPromptFlagHandle={setPromptFlagHandle}/>:'' } { // 编辑页面 pageType==='TEMPLATE_EDIT'?<EditTemplate selectTemplateData={selectTemplateData} selectType={this.selectType}/>:'' } { // 根据已有页面精准入群 pageType==='ACCURATE_EDIT'?<AccurateEditBuild selectTemplateData={selectTemplateData} selectType={this.selectType} cancelBuild={this.cancelBuild} actions={actions} setPromptFlagHandle={setPromptFlagHandle}/>:'' } { // 根据已有页面快速入群 pageType==='FAST_EDIT'?<FastEditBuild selectTemplateData={selectTemplateData} selectType={this.selectType}/>:'' } </div> ) } }